- Introducing millisecond resolution support for the timeout option. See
[platform/upstream/c-ares.git] / ares_init.c
1 /* $Id$ */
2
3 /* Copyright 1998 by the Massachusetts Institute of Technology.
4  * Copyright (C) 2007-2008 by Daniel Stenberg
5  *
6  * Permission to use, copy, modify, and distribute this
7  * software and its documentation for any purpose and without
8  * fee is hereby granted, provided that the above copyright
9  * notice appear in all copies and that both that copyright
10  * notice and this permission notice appear in supporting
11  * documentation, and that the name of M.I.T. not be used in
12  * advertising or publicity pertaining to distribution of the
13  * software without specific, written prior permission.
14  * M.I.T. makes no representations about the suitability of
15  * this software for any purpose.  It is provided "as is"
16  * without express or implied warranty.
17  */
18
19 #include "setup.h"
20
21 #if defined(WIN32) && !defined(WATT32)
22 #include "nameser.h"
23 #include <iphlpapi.h>
24 #include <malloc.h>
25
26 #else
27 #ifdef HAVE_SYS_PARAM_H
28 #include <sys/param.h>
29 #endif
30
31 #ifdef HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34
35 #ifdef HAVE_SYS_SOCKET_H
36 #include <sys/socket.h>
37 #endif
38
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
41 #include <netdb.h>
42 #include <arpa/nameser.h>
43 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
44 #include <arpa/nameser_compat.h>
45 #endif
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
49 #ifdef HAVE_PROCESS_H
50 #include <process.h>  /* Some have getpid() here */
51 #endif
52 #endif
53
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <ctype.h>
58 #include <time.h>
59 #include <errno.h>
60 #include "ares.h"
61 #include "ares_private.h"
62 #include "inet_net_pton.h"
63
64 #ifdef WATT32
65 #undef WIN32  /* Redefined in MingW/MSVC headers */
66 #endif
67
68 static int init_by_options(ares_channel channel, const struct ares_options *options,
69                            int optmask);
70 static int init_by_environment(ares_channel channel);
71 static int init_by_resolv_conf(ares_channel channel);
72 static int init_by_defaults(ares_channel channel);
73
74 static int config_nameserver(struct server_state **servers, int *nservers,
75                              char *str);
76 static int set_search(ares_channel channel, const char *str);
77 static int set_options(ares_channel channel, const char *str);
78 static const char *try_option(const char *p, const char *q, const char *opt);
79 static int init_id_key(rc4_key* key,int key_data_len);
80
81 #ifndef WIN32
82 static int sortlist_alloc(struct apattern **sortlist, int *nsort, struct apattern *pat);
83 static int ip_addr(const char *s, int len, struct in_addr *addr);
84 static void natural_mask(struct apattern *pat);
85 static int config_domain(ares_channel channel, char *str);
86 static int config_lookup(ares_channel channel, const char *str,
87                          const char *bindch, const char *filech);
88 static int config_sortlist(struct apattern **sortlist, int *nsort,
89                            const char *str);
90 static char *try_config(char *s, const char *opt);
91 #endif
92
93 #define ARES_CONFIG_CHECK(x) (x->lookups && x->nsort > -1 && \
94                              x->nservers > -1 && \
95                              x->ndomains > -1 && \
96                              x->ndots > -1 && x->timeout > -1 && \
97                              x->tries > -1)
98
99 int ares_init(ares_channel *channelptr)
100 {
101   return ares_init_options(channelptr, NULL, 0);
102 }
103
104 int ares_init_options(ares_channel *channelptr, struct ares_options *options,
105                       int optmask)
106 {
107   ares_channel channel;
108   int i;
109   int status = ARES_SUCCESS;
110   struct server_state *server;
111
112 #ifdef CURLDEBUG
113   const char *env = getenv("CARES_MEMDEBUG");
114
115   if (env)
116     curl_memdebug(env);
117   env = getenv("CARES_MEMLIMIT");
118   if (env)
119     curl_memlimit(atoi(env));
120 #endif
121
122   channel = malloc(sizeof(struct ares_channeldata));
123   if (!channel) {
124     *channelptr = NULL;
125     return ARES_ENOMEM;
126   }
127
128   /* Set everything to distinguished values so we know they haven't
129    * been set yet.
130    */
131   channel->flags = -1;
132   channel->timeout = -1;
133   channel->tries = -1;
134   channel->ndots = -1;
135   channel->udp_port = -1;
136   channel->tcp_port = -1;
137   channel->socket_send_buffer_size = -1;
138   channel->socket_receive_buffer_size = -1;
139   channel->nservers = -1;
140   channel->ndomains = -1;
141   channel->nsort = -1;
142   channel->tcp_connection_generation = 0;
143   channel->lookups = NULL;
144   channel->domains = NULL;
145   channel->sortlist = NULL;
146   channel->servers = NULL;
147   channel->sock_state_cb = NULL;
148   channel->sock_state_cb_data = NULL;
149
150   channel->last_timeout_processed = (long)time(NULL);
151
152   /* Initialize our lists of queries */
153   ares__init_list_head(&(channel->all_queries));
154   for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
155     {
156       ares__init_list_head(&(channel->queries_by_qid[i]));
157     }
158   for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
159     {
160       ares__init_list_head(&(channel->queries_by_timeout[i]));
161     }
162
163   /* Initialize configuration by each of the four sources, from highest
164    * precedence to lowest.
165    */
166
167   if (status == ARES_SUCCESS) {
168   status = init_by_options(channel, options, optmask);
169     if (status != ARES_SUCCESS)
170       DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
171                      ares_strerror(status)));
172   }
173   if (status == ARES_SUCCESS) {
174     status = init_by_environment(channel);
175     if (status != ARES_SUCCESS)
176       DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
177                      ares_strerror(status)));
178   }
179   if (status == ARES_SUCCESS) {
180     status = init_by_resolv_conf(channel);
181     if (status != ARES_SUCCESS)
182       DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
183                      ares_strerror(status)));
184   }
185   if (status == ARES_SUCCESS) {
186     status = init_by_defaults(channel);
187     if (status != ARES_SUCCESS)
188       DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
189                      ares_strerror(status)));
190   }
191
192   /* Generate random key */
193
194   if (status == ARES_SUCCESS) {
195     status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
196     if (status == ARES_SUCCESS)
197       channel->next_id = ares__generate_new_id(&channel->id_key);
198     else
199       DEBUGF(fprintf(stderr, "Error: init_id_key failed: %s\n",
200                      ares_strerror(status)));
201   }
202
203   if (status != ARES_SUCCESS)
204     {
205       /* Something failed; clean up memory we may have allocated. */
206       if (channel->servers)
207         free(channel->servers);
208       if (channel->domains)
209         {
210           for (i = 0; i < channel->ndomains; i++)
211             free(channel->domains[i]);
212           free(channel->domains);
213         }
214       if (channel->sortlist)
215         free(channel->sortlist);
216       if(channel->lookups)
217         free(channel->lookups);
218       free(channel);
219       return status;
220     }
221
222   /* Trim to one server if ARES_FLAG_PRIMARY is set. */
223   if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
224     channel->nservers = 1;
225
226   /* Initialize server states. */
227   for (i = 0; i < channel->nservers; i++)
228     {
229       server = &channel->servers[i];
230       server->udp_socket = ARES_SOCKET_BAD;
231       server->tcp_socket = ARES_SOCKET_BAD;
232       server->tcp_connection_generation = ++channel->tcp_connection_generation;
233       server->tcp_lenbuf_pos = 0;
234       server->tcp_buffer = NULL;
235       server->qhead = NULL;
236       server->qtail = NULL;
237       ares__init_list_head(&(server->queries_to_server));
238       server->channel = channel;
239       server->is_broken = 0;
240     }
241
242   *channelptr = channel;
243   return ARES_SUCCESS;
244 }
245
246 /* Save options from initialized channel */
247 int ares_save_options(ares_channel channel, struct ares_options *options,
248                       int *optmask)
249 {
250   int i;
251
252   /* Zero everything out */
253   memset(options, 0, sizeof(struct ares_options));
254
255   if (!ARES_CONFIG_CHECK(channel))
256     return ARES_ENODATA;
257
258   (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TRIES|ARES_OPT_NDOTS|
259                 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
260                 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
261                 ARES_OPT_SORTLIST|ARES_OPT_TIMEOUTMS);
262
263   /* Copy easy stuff */
264   options->flags   = channel->flags;
265
266   /* We return full millisecond resolution but that's only because we don't
267      set the ARES_OPT_TIMEOUT anymore, only the new ARES_OPT_TIMEOUTMS */
268   options->timeout = channel->timeout;
269   options->tries   = channel->tries;
270   options->ndots   = channel->ndots;
271   options->udp_port = (unsigned short)channel->udp_port;
272   options->tcp_port = (unsigned short)channel->tcp_port;
273   options->sock_state_cb     = channel->sock_state_cb;
274   options->sock_state_cb_data = channel->sock_state_cb_data;
275
276   /* Copy servers */
277   if (channel->nservers) {
278     options->servers =
279       malloc(channel->nservers * sizeof(struct server_state));
280     if (!options->servers && channel->nservers != 0)
281       return ARES_ENOMEM;
282     for (i = 0; i < channel->nservers; i++)
283       options->servers[i] = channel->servers[i].addr;
284   }
285   options->nservers = channel->nservers;
286
287   /* copy domains */
288   if (channel->ndomains) {
289     options->domains = malloc(channel->ndomains * sizeof(char *));
290     if (!options->domains)
291       return ARES_ENOMEM;
292
293     for (i = 0; i < channel->ndomains; i++)
294     {
295       options->ndomains = i;
296       options->domains[i] = strdup(channel->domains[i]);
297       if (!options->domains[i])
298         return ARES_ENOMEM;
299     }
300   }
301   options->ndomains = channel->ndomains;
302
303   /* copy lookups */
304   if (channel->lookups) {
305     options->lookups = strdup(channel->lookups);
306     if (!options->lookups && channel->lookups)
307       return ARES_ENOMEM;
308   }
309
310   /* copy sortlist */
311   if (channel->nsort) {
312     options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
313     if (!options->sortlist)
314       return ARES_ENOMEM;
315     for (i = 0; i < channel->nsort; i++)
316     {
317       memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
318              sizeof(struct apattern));
319     }
320   }
321   options->nsort = channel->nsort;
322
323   return ARES_SUCCESS;
324 }
325
326 static int init_by_options(ares_channel channel,
327                            const struct ares_options *options,
328                            int optmask)
329 {
330   int i;
331
332   /* Easy stuff. */
333   if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
334     channel->flags = options->flags;
335   if ((optmask & ARES_OPT_TIMEOUTMS) && channel->timeout == -1)
336     channel->timeout = options->timeout;
337   else if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
338     channel->timeout = options->timeout * 1000;
339   if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
340     channel->tries = options->tries;
341   if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
342     channel->ndots = options->ndots;
343   if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
344     channel->udp_port = options->udp_port;
345   if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
346     channel->tcp_port = options->tcp_port;
347   if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
348     {
349       channel->sock_state_cb = options->sock_state_cb;
350       channel->sock_state_cb_data = options->sock_state_cb_data;
351     }
352   if ((optmask & ARES_OPT_SOCK_SNDBUF)
353       && channel->socket_send_buffer_size == -1)
354     channel->socket_send_buffer_size = options->socket_send_buffer_size;
355   if ((optmask & ARES_OPT_SOCK_RCVBUF)
356       && channel->socket_receive_buffer_size == -1)
357     channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
358
359   /* Copy the servers, if given. */
360   if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
361     {
362       /* Avoid zero size allocations at any cost */
363       if (options->nservers > 0)
364         {
365           channel->servers =
366             malloc(options->nservers * sizeof(struct server_state));
367           if (!channel->servers)
368             return ARES_ENOMEM;
369           for (i = 0; i < options->nservers; i++)
370             channel->servers[i].addr = options->servers[i];
371         }
372       channel->nservers = options->nservers;
373     }
374
375   /* Copy the domains, if given.  Keep channel->ndomains consistent so
376    * we can clean up in case of error.
377    */
378   if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
379     {
380       /* Avoid zero size allocations at any cost */
381       if (options->ndomains > 0)
382       {
383         channel->domains = malloc(options->ndomains * sizeof(char *));
384         if (!channel->domains)
385           return ARES_ENOMEM;
386         for (i = 0; i < options->ndomains; i++)
387           {
388             channel->ndomains = i;
389             channel->domains[i] = strdup(options->domains[i]);
390             if (!channel->domains[i])
391               return ARES_ENOMEM;
392           }
393       }
394       channel->ndomains = options->ndomains;
395     }
396
397   /* Set lookups, if given. */
398   if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
399     {
400       channel->lookups = strdup(options->lookups);
401       if (!channel->lookups)
402         return ARES_ENOMEM;
403     }
404
405   /* copy sortlist */
406   if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
407     {
408       channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
409       if (!channel->sortlist)
410         return ARES_ENOMEM;
411       for (i = 0; i < options->nsort; i++)
412         {
413           memcpy(&(channel->sortlist[i]), &(options->sortlist[i]), sizeof(struct apattern));
414         }
415       channel->nsort = options->nsort;
416     }
417
418   return ARES_SUCCESS;
419 }
420
421 static int init_by_environment(ares_channel channel)
422 {
423   const char *localdomain, *res_options;
424   int status;
425
426   localdomain = getenv("LOCALDOMAIN");
427   if (localdomain && channel->ndomains == -1)
428     {
429       status = set_search(channel, localdomain);
430       if (status != ARES_SUCCESS)
431         return status;
432     }
433
434   res_options = getenv("RES_OPTIONS");
435   if (res_options)
436     {
437       status = set_options(channel, res_options);
438       if (status != ARES_SUCCESS)
439         return status;
440     }
441
442   return ARES_SUCCESS;
443 }
444
445 #ifdef WIN32
446 /*
447  * Warning: returns a dynamically allocated buffer, the user MUST
448  * use free() if the function returns 1
449  */
450 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
451 {
452   /* Test for the size we need */
453   DWORD size = 0;
454   int result;
455
456   result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
457   if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
458     return 0;
459   *obuf = malloc(size+1);
460   if (!*obuf)
461     return 0;
462
463   if (RegQueryValueEx(hKey, subkey, 0, NULL,
464                       (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
465   {
466     free(*obuf);
467     return 0;
468   }
469   if (size == 1)
470   {
471     free(*obuf);
472     return 0;
473   }
474   return 1;
475 }
476
477 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
478 {
479   char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
480   DWORD enum_size = 39;
481   int idx = 0;
482   HKEY hVal;
483
484   while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
485                       NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
486   {
487     int rc;
488
489     enum_size = 39;
490     if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
491         ERROR_SUCCESS)
492       continue;
493     rc = get_res_nt(hVal, subkey, obuf);
494       RegCloseKey(hVal);
495     if (rc)
496       return 1;
497     }
498   return 0;
499 }
500
501 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
502 {
503   FIXED_INFO    *fi   = alloca (sizeof(*fi));
504   DWORD          size = sizeof (*fi);
505   typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
506   get_net_param_func fpGetNetworkParams;  /* available only on Win-98/2000+ */
507   HMODULE        handle;
508   IP_ADDR_STRING *ipAddr;
509   int            i, count = 0;
510   int            debug  = 0;
511   size_t         ip_size = sizeof("255.255.255.255,")-1;
512   size_t         left = ret_size;
513   char          *ret = ret_buf;
514   HRESULT        res;
515
516   if (!fi)
517      return (0);
518
519   handle = LoadLibrary ("iphlpapi.dll");
520   if (!handle)
521      return (0);
522
523   fpGetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
524   if (!fpGetNetworkParams)
525      goto quit;
526
527   res = (*fpGetNetworkParams) (fi, &size);
528   if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
529      goto quit;
530
531   fi = alloca (size);
532   if (!fi || (*fpGetNetworkParams) (fi, &size) != ERROR_SUCCESS)
533      goto quit;
534
535   if (debug)
536   {
537     printf ("Host Name: %s\n", fi->HostName);
538     printf ("Domain Name: %s\n", fi->DomainName);
539     printf ("DNS Servers:\n"
540             "    %s (primary)\n", fi->DnsServerList.IpAddress.String);
541   }
542   if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
543       inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
544       left > ip_size)
545   {
546     ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
547     left -= ret - ret_buf;
548     count++;
549   }
550
551   for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
552        ipAddr = ipAddr->Next, i++)
553   {
554     if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
555     {
556        ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
557        left -= ret - ret_buf;
558        count++;
559     }
560     if (debug)
561        printf ("    %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
562   }
563
564 quit:
565   if (handle)
566      FreeLibrary (handle);
567
568   if (debug && left <= ip_size)
569      printf ("Too many nameservers. Truncating to %d addressess", count);
570   if (ret > ret_buf)
571      ret[-1] = '\0';
572   return (count);
573 }
574 #endif
575
576 static int init_by_resolv_conf(ares_channel channel)
577 {
578   char *line = NULL;
579   int status = -1, nservers = 0, nsort = 0;
580   struct server_state *servers = NULL;
581   struct apattern *sortlist = NULL;
582
583 #ifdef WIN32
584
585     /*
586   NameServer info via IPHLPAPI (IP helper API):
587     GetNetworkParams() should be the trusted source for this.
588     Available in Win-98/2000 and later. If that fail, fall-back to
589     registry information.
590
591   NameServer Registry:
592
593    On Windows 9X, the DNS server can be found in:
594 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
595
596         On Windows NT/2000/XP/2003:
597 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
598         or
599 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
600         or
601 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
602 NameServer
603         or
604 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
605 DhcpNameServer
606    */
607
608   HKEY mykey;
609   HKEY subkey;
610   DWORD data_type;
611   DWORD bytes;
612   DWORD result;
613   char  buf[256];
614
615   if (channel->nservers > -1)  /* don't override ARES_OPT_SERVER */
616      return ARES_SUCCESS;
617
618   if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
619   {
620     status = config_nameserver(&servers, &nservers, buf);
621     if (status == ARES_SUCCESS)
622       goto okay;
623   }
624
625   if (IS_NT())
626   {
627     if (RegOpenKeyEx(
628           HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
629           KEY_READ, &mykey
630           ) == ERROR_SUCCESS)
631     {
632       RegOpenKeyEx(mykey, "Interfaces", 0,
633                    KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
634       if (get_res_nt(mykey, NAMESERVER, &line))
635       {
636         status = config_nameserver(&servers, &nservers, line);
637         free(line);
638       }
639       else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
640       {
641         status = config_nameserver(&servers, &nservers, line);
642         free(line);
643       }
644       /* Try the interfaces */
645       else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
646       {
647         status = config_nameserver(&servers, &nservers, line);
648         free(line);
649       }
650       else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
651       {
652         status = config_nameserver(&servers, &nservers, line);
653         free(line);
654       }
655       RegCloseKey(subkey);
656       RegCloseKey(mykey);
657     }
658   }
659   else
660   {
661     if (RegOpenKeyEx(
662           HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
663           KEY_READ, &mykey
664           ) == ERROR_SUCCESS)
665     {
666       if ((result = RegQueryValueEx(
667              mykey, NAMESERVER, NULL, &data_type,
668              NULL, &bytes
669              )
670             ) == ERROR_SUCCESS ||
671           result == ERROR_MORE_DATA)
672       {
673         if (bytes)
674         {
675           line = (char *)malloc(bytes+1);
676           if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
677                               (unsigned char *)line, &bytes) ==
678               ERROR_SUCCESS)
679           {
680             status = config_nameserver(&servers, &nservers, line);
681           }
682           free(line);
683         }
684       }
685     }
686     RegCloseKey(mykey);
687   }
688
689   if (status == ARES_SUCCESS)
690     status = ARES_EOF;
691   else
692     /* Catch the case when all the above checks fail (which happens when there
693        is no network card or the cable is unplugged) */
694     status = ARES_EFILE;
695
696 #elif defined(__riscos__)
697
698   /* Under RISC OS, name servers are listed in the
699      system variable Inet$Resolvers, space separated. */
700
701   line = getenv("Inet$Resolvers");
702   status = ARES_EOF;
703   if (line) {
704     char *resolvers = strdup(line), *pos, *space;
705
706     if (!resolvers)
707       return ARES_ENOMEM;
708
709     pos = resolvers;
710     do {
711       space = strchr(pos, ' ');
712       if (space)
713         *space = '\0';
714       status = config_nameserver(&servers, &nservers, pos);
715       if (status != ARES_SUCCESS)
716         break;
717       pos = space + 1;
718     } while (space);
719
720     if (status == ARES_SUCCESS)
721       status = ARES_EOF;
722
723     free(resolvers);
724   }
725
726 #elif defined(WATT32)
727   int i;
728
729   sock_init();
730   for (i = 0; def_nameservers[i]; i++)
731       ;
732   if (i == 0)
733     return ARES_SUCCESS; /* use localhost DNS server */
734
735   nservers = i;
736   servers = calloc(sizeof(*servers), i);
737   if (!servers)
738      return ARES_ENOMEM;
739
740   for (i = 0; def_nameservers[i]; i++)
741       servers[i].addr.s_addr = htonl(def_nameservers[i]);
742   status = ARES_EOF;
743
744 #else
745   {
746     char *p;
747     FILE *fp;
748     int linesize;
749     int error;
750
751     /* Don't read resolv.conf and friends if we don't have to */
752     if (ARES_CONFIG_CHECK(channel))
753         return ARES_SUCCESS;
754
755     fp = fopen(PATH_RESOLV_CONF, "r");
756     if (fp) {
757       while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
758       {
759         if ((p = try_config(line, "domain")) && channel->ndomains == -1)
760           status = config_domain(channel, p);
761         else if ((p = try_config(line, "lookup")) && !channel->lookups)
762           status = config_lookup(channel, p, "bind", "file");
763         else if ((p = try_config(line, "search")) && channel->ndomains == -1)
764           status = set_search(channel, p);
765         else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
766           status = config_nameserver(&servers, &nservers, p);
767         else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
768           status = config_sortlist(&sortlist, &nsort, p);
769         else if ((p = try_config(line, "options")))
770           status = set_options(channel, p);
771         else
772           status = ARES_SUCCESS;
773         if (status != ARES_SUCCESS)
774           break;
775       }
776       fclose(fp);
777     }
778     else {
779       error = ERRNO;
780       switch(error) {
781       case ENOENT:
782       case ESRCH:
783         status = ARES_EOF;
784         break;
785       default:
786         DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
787                        error, strerror(error)));
788         DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
789         status = ARES_EFILE;
790       }
791     }
792
793     if ((status == ARES_EOF) && (!channel->lookups)) {
794       /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
795       fp = fopen("/etc/nsswitch.conf", "r");
796       if (fp) {
797         while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
798         {
799           if ((p = try_config(line, "hosts:")) && !channel->lookups)
800             status = config_lookup(channel, p, "dns", "files");
801         }
802         fclose(fp);
803       }
804       else {
805         error = ERRNO;
806         switch(error) {
807         case ENOENT:
808         case ESRCH:
809           status = ARES_EOF;
810           break;
811         default:
812           DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
813                          error, strerror(error)));
814           DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
815           status = ARES_EFILE;
816         }
817       }
818     }
819
820     if ((status == ARES_EOF) && (!channel->lookups)) {
821       /* Linux / GNU libc 2.x and possibly others have host.conf */
822       fp = fopen("/etc/host.conf", "r");
823       if (fp) {
824         while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
825         {
826           if ((p = try_config(line, "order")) && !channel->lookups)
827             status = config_lookup(channel, p, "bind", "hosts");
828         }
829         fclose(fp);
830       }
831       else {
832         error = ERRNO;
833         switch(error) {
834         case ENOENT:
835         case ESRCH:
836           status = ARES_EOF;
837           break;
838         default:
839           DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
840                          error, strerror(error)));
841           DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
842           status = ARES_EFILE;
843         }
844       }
845     }
846
847     if ((status == ARES_EOF) && (!channel->lookups)) {
848       /* Tru64 uses /etc/svc.conf */
849       fp = fopen("/etc/svc.conf", "r");
850       if (fp) {
851         while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
852         {
853           if ((p = try_config(line, "hosts=")) && !channel->lookups)
854             status = config_lookup(channel, p, "bind", "local");
855         }
856         fclose(fp);
857       }
858       else {
859         error = ERRNO;
860         switch(error) {
861         case ENOENT:
862         case ESRCH:
863           status = ARES_EOF;
864           break;
865         default:
866           DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
867                          error, strerror(error)));
868           DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
869           status = ARES_EFILE;
870         }
871       }
872     }
873
874     if(line)
875       free(line);
876   }
877
878 #endif
879
880   /* Handle errors. */
881   if (status != ARES_EOF)
882     {
883       if (servers != NULL)
884         free(servers);
885       if (sortlist != NULL)
886         free(sortlist);
887       return status;
888     }
889
890   /* If we got any name server entries, fill them in. */
891 #ifdef WIN32
892 okay:
893 #endif
894   if (servers)
895     {
896       channel->servers = servers;
897       channel->nservers = nservers;
898     }
899
900   /* If we got any sortlist entries, fill them in. */
901   if (sortlist)
902     {
903       channel->sortlist = sortlist;
904       channel->nsort = nsort;
905     }
906
907   return ARES_SUCCESS;
908 }
909
910 static int init_by_defaults(ares_channel channel)
911 {
912   char hostname[MAXHOSTNAMELEN + 1];
913
914   if (channel->flags == -1)
915     channel->flags = 0;
916   if (channel->timeout == -1)
917     channel->timeout = DEFAULT_TIMEOUT;
918   if (channel->tries == -1)
919     channel->tries = DEFAULT_TRIES;
920   if (channel->ndots == -1)
921     channel->ndots = 1;
922   if (channel->udp_port == -1)
923     channel->udp_port = htons(NAMESERVER_PORT);
924   if (channel->tcp_port == -1)
925     channel->tcp_port = htons(NAMESERVER_PORT);
926
927   if (channel->nservers == -1)
928     {
929       /* If nobody specified servers, try a local named. */
930       channel->servers = malloc(sizeof(struct server_state));
931       if (!channel->servers)
932         return ARES_ENOMEM;
933       channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
934       channel->nservers = 1;
935     }
936
937   if (channel->ndomains == -1)
938     {
939       /* Derive a default domain search list from the kernel hostname,
940        * or set it to empty if the hostname isn't helpful.
941        */
942       if (gethostname(hostname, sizeof(hostname)) == -1
943           || !strchr(hostname, '.'))
944         {
945           channel->ndomains = 0;
946         }
947       else
948         {
949           channel->domains = malloc(sizeof(char *));
950           if (!channel->domains)
951             return ARES_ENOMEM;
952           channel->ndomains = 0;
953           channel->domains[0] = strdup(strchr(hostname, '.') + 1);
954           if (!channel->domains[0])
955             return ARES_ENOMEM;
956           channel->ndomains = 1;
957         }
958     }
959
960   if (channel->nsort == -1)
961     {
962       channel->sortlist = NULL;
963       channel->nsort = 0;
964     }
965
966   if (!channel->lookups)
967     {
968       channel->lookups = strdup("fb");
969       if (!channel->lookups)
970         return ARES_ENOMEM;
971     }
972
973   return ARES_SUCCESS;
974 }
975
976 #ifndef WIN32
977 static int config_domain(ares_channel channel, char *str)
978 {
979   char *q;
980
981   /* Set a single search domain. */
982   q = str;
983   while (*q && !ISSPACE(*q))
984     q++;
985   *q = '\0';
986   return set_search(channel, str);
987 }
988
989 static int config_lookup(ares_channel channel, const char *str,
990                          const char *bindch, const char *filech)
991 {
992   char lookups[3], *l;
993   const char *p;
994
995   /* Set the lookup order.  Only the first letter of each work
996    * is relevant, and it has to be "b" for DNS or "f" for the
997    * host file.  Ignore everything else.
998    */
999   l = lookups;
1000   p = str;
1001   while (*p)
1002     {
1003       if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
1004         if (*p == *bindch) *l++ = 'b';
1005         else *l++ = 'f';
1006       }
1007       while (*p && !ISSPACE(*p) && (*p != ','))
1008         p++;
1009       while (*p && (ISSPACE(*p) || (*p == ',')))
1010         p++;
1011     }
1012   *l = '\0';
1013   channel->lookups = strdup(lookups);
1014   return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1015 }
1016
1017 #endif
1018
1019 static int config_nameserver(struct server_state **servers, int *nservers,
1020                              char *str)
1021 {
1022   struct in_addr addr;
1023   struct server_state *newserv;
1024   /* On Windows, there may be more than one nameserver specified in the same
1025    * registry key, so we parse it as a space or comma seperated list.
1026    */
1027 #ifdef WIN32
1028   char *p = str;
1029   char *begin = str;
1030   int more = 1;
1031   while (more)
1032   {
1033     more = 0;
1034     while (*p && !ISSPACE(*p) && *p != ',')
1035       p++;
1036
1037     if (*p)
1038     {
1039       *p = '\0';
1040       more = 1;
1041     }
1042
1043     /* Skip multiple spaces or trailing spaces */
1044     if (!*begin)
1045     {
1046       begin = ++p;
1047       continue;
1048     }
1049
1050     /* This is the part that actually sets the nameserver */
1051     addr.s_addr = inet_addr(begin);
1052     if (addr.s_addr == INADDR_NONE)
1053       continue;
1054     newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1055     if (!newserv)
1056       return ARES_ENOMEM;
1057     newserv[*nservers].addr = addr;
1058     *servers = newserv;
1059     (*nservers)++;
1060
1061     if (!more)
1062       break;
1063     begin = ++p;
1064   }
1065 #else
1066   /* Add a nameserver entry, if this is a valid address. */
1067   addr.s_addr = inet_addr(str);
1068   if (addr.s_addr == INADDR_NONE)
1069     return ARES_SUCCESS;
1070   newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1071   if (!newserv)
1072     return ARES_ENOMEM;
1073   newserv[*nservers].addr = addr;
1074   *servers = newserv;
1075   (*nservers)++;
1076 #endif
1077   return ARES_SUCCESS;
1078 }
1079
1080 #ifndef WIN32
1081 static int config_sortlist(struct apattern **sortlist, int *nsort,
1082                            const char *str)
1083 {
1084   struct apattern pat;
1085   const char *q;
1086
1087   /* Add sortlist entries. */
1088   while (*str && *str != ';')
1089     {
1090       int bits;
1091       char ipbuf[16], ipbufpfx[32];
1092       /* Find just the IP */
1093       q = str;
1094       while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1095         q++;
1096       memcpy(ipbuf, str, (int)(q-str));
1097       ipbuf[(int)(q-str)] = '\0';
1098       /* Find the prefix */
1099       if (*q == '/')
1100         {
1101           const char *str2 = q+1;
1102           while (*q && *q != ';' && !ISSPACE(*q))
1103             q++;
1104           memcpy(ipbufpfx, str, (int)(q-str));
1105           ipbufpfx[(int)(q-str)] = '\0';
1106           str = str2;
1107         }
1108       else
1109         ipbufpfx[0] = '\0';
1110       /* Lets see if it is CIDR */
1111       /* First we'll try IPv6 */
1112       if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1113                                      &pat.addr.addr6,
1114                                      sizeof(pat.addr.addr6))) > 0)
1115         {
1116           pat.type = PATTERN_CIDR;
1117           pat.mask.bits = (unsigned short)bits;
1118           pat.family = AF_INET6;
1119           if (!sortlist_alloc(sortlist, nsort, &pat))
1120             return ARES_ENOMEM;
1121         }
1122       if (ipbufpfx[0] &&
1123           (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addr.addr4,
1124                                      sizeof(pat.addr.addr4))) > 0)
1125         {
1126           pat.type = PATTERN_CIDR;
1127           pat.mask.bits = (unsigned short)bits;
1128           pat.family = AF_INET;
1129           if (!sortlist_alloc(sortlist, nsort, &pat))
1130             return ARES_ENOMEM;
1131         }
1132       /* See if it is just a regular IP */
1133       else if (ip_addr(ipbuf, (int)(q-str), &pat.addr.addr4) == 0)
1134         {
1135           if (ipbufpfx[0])
1136             {
1137               memcpy(ipbuf, str, (int)(q-str));
1138               ipbuf[(int)(q-str)] = '\0';
1139               if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr.addr4) != 0)
1140                 natural_mask(&pat);
1141             }
1142           else
1143             natural_mask(&pat);
1144           pat.family = AF_INET;
1145           pat.type = PATTERN_MASK;
1146           if (!sortlist_alloc(sortlist, nsort, &pat))
1147             return ARES_ENOMEM;
1148         }
1149       else
1150         {
1151           while (*q && *q != ';' && !ISSPACE(*q))
1152             q++;
1153         }
1154       str = q;
1155       while (ISSPACE(*str))
1156         str++;
1157     }
1158
1159   return ARES_SUCCESS;
1160 }
1161 #endif
1162
1163 static int set_search(ares_channel channel, const char *str)
1164 {
1165   int n;
1166   const char *p, *q;
1167
1168   if(channel->ndomains != -1) {
1169     /* if we already have some domains present, free them first */
1170     for(n=0; n < channel->ndomains; n++)
1171       free(channel->domains[n]);
1172     free(channel->domains);
1173     channel->domains = NULL;
1174     channel->ndomains = -1;
1175   }
1176
1177   /* Count the domains given. */
1178   n = 0;
1179   p = str;
1180   while (*p)
1181     {
1182       while (*p && !ISSPACE(*p))
1183         p++;
1184       while (ISSPACE(*p))
1185         p++;
1186       n++;
1187     }
1188
1189   if (!n)
1190     {
1191       channel->ndomains = 0;
1192       return ARES_SUCCESS;
1193     }
1194
1195   channel->domains = malloc(n * sizeof(char *));
1196   if (!channel->domains)
1197     return ARES_ENOMEM;
1198
1199   /* Now copy the domains. */
1200   n = 0;
1201   p = str;
1202   while (*p)
1203     {
1204       channel->ndomains = n;
1205       q = p;
1206       while (*q && !ISSPACE(*q))
1207         q++;
1208       channel->domains[n] = malloc(q - p + 1);
1209       if (!channel->domains[n])
1210         return ARES_ENOMEM;
1211       memcpy(channel->domains[n], p, q - p);
1212       channel->domains[n][q - p] = 0;
1213       p = q;
1214       while (ISSPACE(*p))
1215         p++;
1216       n++;
1217     }
1218   channel->ndomains = n;
1219
1220   return ARES_SUCCESS;
1221 }
1222
1223 static int set_options(ares_channel channel, const char *str)
1224 {
1225   const char *p, *q, *val;
1226
1227   p = str;
1228   while (*p)
1229     {
1230       q = p;
1231       while (*q && !ISSPACE(*q))
1232         q++;
1233       val = try_option(p, q, "ndots:");
1234       if (val && channel->ndots == -1)
1235         channel->ndots = atoi(val);
1236       val = try_option(p, q, "retrans:");
1237       if (val && channel->timeout == -1)
1238         channel->timeout = atoi(val);
1239       val = try_option(p, q, "retry:");
1240       if (val && channel->tries == -1)
1241         channel->tries = atoi(val);
1242       p = q;
1243       while (ISSPACE(*p))
1244         p++;
1245     }
1246
1247   return ARES_SUCCESS;
1248 }
1249
1250 #ifndef WIN32
1251 static char *try_config(char *s, const char *opt)
1252 {
1253   size_t len;
1254   ssize_t i;
1255   ssize_t j;
1256   char *p;
1257
1258   if (!s || !opt)
1259     /* no line or no option */
1260     return NULL;
1261
1262   /* trim line comment */
1263   for (i = 0; s[i] && s[i] != '#'; ++i);
1264   s[i] = '\0';
1265
1266   /* trim trailing whitespace */
1267   for (j = i-1; j >= 0 && ISSPACE(s[j]); --j);
1268   s[++j] = '\0';
1269
1270   /* skip leading whitespace */
1271   for (i = 0; s[i] && ISSPACE(s[i]); ++i);
1272   p = &s[i];
1273
1274   if (!*p)
1275     /* empty line */
1276     return NULL;
1277
1278   if ((len = strlen(opt)) == 0)
1279     /* empty option */
1280     return NULL;
1281
1282   if (strncmp(p, opt, len) != 0)
1283     /* line and option do not match */
1284     return NULL;
1285
1286   /* skip over given option name */
1287   p += len;
1288
1289   if (!*p)
1290     /* no option value */
1291     return NULL;
1292
1293   if ((opt[len-1] != ':') && (opt[len-1] != '=') && !ISSPACE(*p))
1294     /* whitespace between option name and value is mandatory
1295        for given option names which do not end with ':' or '=' */
1296     return NULL;
1297
1298   /* skip over whitespace */
1299   while (*p && ISSPACE(*p))
1300     p++;
1301
1302   if (!*p)
1303     /* no option value */
1304     return NULL;
1305
1306   /* return pointer to option value */
1307   return p;
1308 }
1309 #endif
1310
1311 static const char *try_option(const char *p, const char *q, const char *opt)
1312 {
1313   size_t len = strlen(opt);
1314   return ((size_t)(q - p) > len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1315 }
1316
1317 #ifndef WIN32
1318 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1319                           struct apattern *pat)
1320 {
1321   struct apattern *newsort;
1322   newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1323   if (!newsort)
1324     return 0;
1325   newsort[*nsort] = *pat;
1326   *sortlist = newsort;
1327   (*nsort)++;
1328   return 1;
1329 }
1330
1331 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1332 {
1333
1334   /* Four octets and three periods yields at most 15 characters. */
1335   if (len > 15)
1336     return -1;
1337
1338   addr->s_addr = inet_addr(ipbuf);
1339   if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1340     return -1;
1341   return 0;
1342 }
1343
1344 static void natural_mask(struct apattern *pat)
1345 {
1346   struct in_addr addr;
1347
1348   /* Store a host-byte-order copy of pat in a struct in_addr.  Icky,
1349    * but portable.
1350    */
1351   addr.s_addr = ntohl(pat->addr.addr4.s_addr);
1352
1353   /* This is out of date in the CIDR world, but some people might
1354    * still rely on it.
1355    */
1356   if (IN_CLASSA(addr.s_addr))
1357     pat->mask.addr.addr4.s_addr = htonl(IN_CLASSA_NET);
1358   else if (IN_CLASSB(addr.s_addr))
1359     pat->mask.addr.addr4.s_addr = htonl(IN_CLASSB_NET);
1360   else
1361     pat->mask.addr.addr4.s_addr = htonl(IN_CLASSC_NET);
1362 }
1363 #endif
1364 /* initialize an rc4 key. If possible a cryptographically secure random key
1365    is generated using a suitable function (for example win32's RtlGenRandom as
1366    described in
1367    http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1368    otherwise the code defaults to cross-platform albeit less secure mechanism
1369    using rand
1370 */
1371 static void randomize_key(unsigned char* key,int key_data_len)
1372 {
1373   int randomized = 0;
1374   int counter=0;
1375 #ifdef WIN32
1376   HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1377   if (lib) {
1378     BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1379       (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1380     if (pfn && pfn(key,key_data_len) )
1381       randomized = 1;
1382
1383     FreeLibrary(lib);
1384   }
1385 #else /* !WIN32 */
1386 #ifdef RANDOM_FILE
1387   FILE *f = fopen(RANDOM_FILE, "rb");
1388   if(f) {
1389     counter = fread(key, 1, key_data_len, f);
1390     fclose(f);
1391   }
1392 #endif
1393 #endif /* WIN32 */
1394
1395   if ( !randomized ) {
1396     for (;counter<key_data_len;counter++)
1397       key[counter]=(unsigned char)(rand() % 256);
1398   }
1399 }
1400
1401 static int init_id_key(rc4_key* key,int key_data_len)
1402 {
1403   unsigned char index1;
1404   unsigned char index2;
1405   unsigned char* state;
1406   short counter;
1407   unsigned char *key_data_ptr = 0;
1408
1409   key_data_ptr = calloc(1,key_data_len);
1410   if (!key_data_ptr)
1411     return ARES_ENOMEM;
1412
1413   randomize_key(key->state,key_data_len);
1414   state = &key->state[0];
1415   for(counter = 0; counter < 256; counter++)
1416     /* unnecessary AND but it keeps some compilers happier */
1417     state[counter] = (unsigned char)(counter & 0xff);
1418   key->x = 0;
1419   key->y = 0;
1420   index1 = 0;
1421   index2 = 0;
1422   for(counter = 0; counter < 256; counter++)
1423   {
1424     index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1425                               index2) % 256);
1426     ARES_SWAP_BYTE(&state[counter], &state[index2]);
1427
1428     index1 = (unsigned char)((index1 + 1) % key_data_len);
1429   }
1430   free(key_data_ptr);
1431   return ARES_SUCCESS;
1432 }
1433
1434 short ares__generate_new_id(rc4_key* key)
1435 {
1436   short r=0;
1437   ares__rc4(key, (unsigned char *)&r, sizeof(r));
1438   return r;
1439 }