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