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