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