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