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