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