Modified license using SPDX license identifier
[platform/upstream/c-ares.git] / ares_getsock.c
1
2 /* Copyright (C) 2005 - 2010, Daniel Stenberg
3  *
4  * Permission to use, copy, modify, and distribute this software and its
5  * documentation for any purpose and without fee is hereby granted, provided
6  * that the above copyright notice appear in all copies and that both that
7  * copyright notice and this permission notice appear in supporting
8  * documentation, and that the name of M.I.T. not be used in advertising or
9  * publicity pertaining to distribution of the software without specific,
10  * written prior permission.  M.I.T. makes no representations about the
11  * suitability of this software for any purpose.  It is provided "as is"
12  * without express or implied warranty.
13  */
14
15 #include "ares_setup.h"
16
17 #include "ares.h"
18 #include "ares_private.h"
19
20 int ares_getsock(ares_channel channel,
21                  ares_socket_t *socks,
22                  int numsocks) /* size of the 'socks' array */
23 {
24   struct server_state *server;
25   int i;
26   int sockindex=0;
27   int bitmap = 0;
28   unsigned int setbits = 0xffffffff;
29
30   /* Are there any active queries? */
31   int active_queries = !ares__is_list_empty(&(channel->all_queries));
32
33   for (i = 0;
34        (i < channel->nservers) && (sockindex < ARES_GETSOCK_MAXNUM);
35        i++)
36     {
37       server = &channel->servers[i];
38       /* We only need to register interest in UDP sockets if we have
39        * outstanding queries.
40        */
41       if (active_queries && server->udp_socket != ARES_SOCKET_BAD)
42         {
43           if(sockindex >= numsocks)
44             break;
45           socks[sockindex] = server->udp_socket;
46           bitmap |= ARES_GETSOCK_READABLE(setbits, sockindex);
47           sockindex++;
48         }
49       /* We always register for TCP events, because we want to know
50        * when the other side closes the connection, so we don't waste
51        * time trying to use a broken connection.
52        */
53       if (server->tcp_socket != ARES_SOCKET_BAD)
54        {
55          if(sockindex >= numsocks)
56            break;
57          socks[sockindex] = server->tcp_socket;
58          bitmap |= ARES_GETSOCK_READABLE(setbits, sockindex);
59
60          if (server->qhead && active_queries)
61            /* then the tcp socket is also writable! */
62            bitmap |= ARES_GETSOCK_WRITABLE(setbits, sockindex);
63
64          sockindex++;
65        }
66     }
67   return bitmap;
68 }