ares_timeout.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* $Id$ */
  2. /* Copyright 1998 by the Massachusetts Institute of Technology.
  3. *
  4. * Permission to use, copy, modify, and distribute this
  5. * software and its documentation for any purpose and without
  6. * fee is hereby granted, provided that the above copyright
  7. * notice appear in all copies and that both that copyright
  8. * notice and this permission notice appear in supporting
  9. * documentation, and that the name of M.I.T. not be used in
  10. * advertising or publicity pertaining to distribution of the
  11. * software without specific, written prior permission.
  12. * M.I.T. makes no representations about the suitability of
  13. * this software for any purpose. It is provided "as is"
  14. * without express or implied warranty.
  15. */
  16. #include "setup.h"
  17. #ifdef HAVE_SYS_TIME_H
  18. #include <sys/time.h>
  19. #endif
  20. #include <time.h>
  21. #include "ares.h"
  22. #include "ares_private.h"
  23. /* WARNING: Beware that this is linear in the number of outstanding
  24. * requests! You are probably far better off just calling ares_process()
  25. * once per second, rather than calling ares_timeout() to figure out
  26. * when to next call ares_process().
  27. */
  28. struct timeval *ares_timeout(ares_channel channel, struct timeval *maxtv,
  29. struct timeval *tvbuf)
  30. {
  31. struct query *query;
  32. struct list_node* list_head;
  33. struct list_node* list_node;
  34. struct timeval now;
  35. struct timeval nextstop;
  36. long offset, min_offset;
  37. /* No queries, no timeout (and no fetch of the current time). */
  38. if (ares__is_list_empty(&(channel->all_queries)))
  39. return maxtv;
  40. /* Find the minimum timeout for the current set of queries. */
  41. now = ares__tvnow();
  42. min_offset = -1;
  43. list_head = &(channel->all_queries);
  44. for (list_node = list_head->next; list_node != list_head;
  45. list_node = list_node->next)
  46. {
  47. query = list_node->data;
  48. if (query->timeout.tv_sec == 0)
  49. continue;
  50. offset = ares__timeoffset(&now, &query->timeout);
  51. if (offset < 0)
  52. offset = 0;
  53. if (min_offset == -1 || offset < min_offset)
  54. min_offset = offset;
  55. }
  56. if(min_offset != -1) {
  57. nextstop.tv_sec = min_offset/1000;
  58. nextstop.tv_usec = (min_offset%1000)*1000;
  59. }
  60. /* If we found a minimum timeout and it's sooner than the one specified in
  61. * maxtv (if any), return it. Otherwise go with maxtv.
  62. */
  63. if (min_offset != -1 && (!maxtv || ares__timedout(maxtv, &nextstop)))
  64. {
  65. *tvbuf = nextstop;
  66. return tvbuf;
  67. }
  68. else
  69. return maxtv;
  70. }