ares_private.h: use curl_memdebug.h instead of memdebug.h
[platform/upstream/c-ares.git] / ares_timeout.c
1
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
17 #include "ares_setup.h"
18
19 #ifdef HAVE_LIMITS_H
20 #include <limits.h>
21 #endif
22
23 #include "ares.h"
24 #include "ares_private.h"
25
26 /* WARNING: Beware that this is linear in the number of outstanding
27  * requests! You are probably far better off just calling ares_process()
28  * once per second, rather than calling ares_timeout() to figure out
29  * when to next call ares_process().
30  */
31 struct timeval *ares_timeout(ares_channel channel, struct timeval *maxtv,
32                              struct timeval *tvbuf)
33 {
34   struct query *query;
35   struct list_node* list_head;
36   struct list_node* list_node;
37   struct timeval now;
38   struct timeval nextstop;
39   long offset, min_offset;
40
41   /* No queries, no timeout (and no fetch of the current time). */
42   if (ares__is_list_empty(&(channel->all_queries)))
43     return maxtv;
44
45   /* Find the minimum timeout for the current set of queries. */
46   now = ares__tvnow();
47   min_offset = -1;
48
49   list_head = &(channel->all_queries);
50   for (list_node = list_head->next; list_node != list_head;
51        list_node = list_node->next)
52     {
53       query = list_node->data;
54       if (query->timeout.tv_sec == 0)
55         continue;
56       offset = ares__timeoffset(&now, &query->timeout);
57       if (offset < 0)
58         offset = 0;
59       if (min_offset == -1 || offset < min_offset)
60         min_offset = offset;
61     }
62
63   /* If we found a minimum timeout and it's sooner than the one specified in
64    * maxtv (if any), return it.  Otherwise go with maxtv.
65    */
66   if (min_offset != -1)
67     {
68       int ioffset = (min_offset > (long)INT_MAX) ? INT_MAX : (int)min_offset;
69
70       nextstop.tv_sec = ioffset/1000;
71       nextstop.tv_usec = (ioffset%1000)*1000;
72
73       if (!maxtv || ares__timedout(maxtv, &nextstop))
74         {
75           *tvbuf = nextstop;
76           return tvbuf;
77         }
78     }
79
80   return maxtv;
81 }