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