2 /* Copyright 1998 by the Massachusetts Institute of Technology.
3 * Copyright (C) 2007-2011 by Daniel Stenberg
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.
18 #include "ares_setup.h"
24 #ifdef HAVE_SYS_PARAM_H
25 #include <sys/param.h>
28 #ifdef HAVE_SYS_TIME_H
32 #ifdef HAVE_SYS_SOCKET_H
33 #include <sys/socket.h>
36 #ifdef HAVE_NETINET_IN_H
37 #include <netinet/in.h>
44 #ifdef HAVE_ARPA_INET_H
45 #include <arpa/inet.h>
48 #ifdef HAVE_ARPA_NAMESER_H
49 # include <arpa/nameser.h>
53 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
54 # include <arpa/nameser_compat.h>
68 #include "inet_net_pton.h"
69 #include "ares_library_init.h"
70 #include "ares_nowarn.h"
71 #include "ares_private.h"
74 #include <sys/system_properties.h>
78 #undef WIN32 /* Redefined in MingW/MSVC headers */
81 static int init_by_options(ares_channel channel, const struct ares_options *options,
83 static int init_by_environment(ares_channel channel);
84 static int init_by_resolv_conf(ares_channel channel);
85 static int init_by_defaults(ares_channel channel);
88 static int config_nameserver(struct server_state **servers, int *nservers,
91 static int set_search(ares_channel channel, const char *str);
92 static int set_options(ares_channel channel, const char *str);
93 static const char *try_option(const char *p, const char *q, const char *opt);
94 static int init_id_key(rc4_key* key,int key_data_len);
96 #if !defined(WIN32) && !defined(WATT32)
97 static int sortlist_alloc(struct apattern **sortlist, int *nsort, struct apattern *pat);
98 static int ip_addr(const char *s, ssize_t len, struct in_addr *addr);
99 static void natural_mask(struct apattern *pat);
100 static int config_domain(ares_channel channel, char *str);
101 static int config_lookup(ares_channel channel, const char *str,
102 const char *bindch, const char *filech);
103 static int config_sortlist(struct apattern **sortlist, int *nsort,
105 static char *try_config(char *s, const char *opt, char scc);
108 #define ARES_CONFIG_CHECK(x) (x->lookups && x->nsort > -1 && \
109 x->nservers > -1 && \
110 x->ndomains > -1 && \
111 x->ndots > -1 && x->timeout > -1 && \
114 int ares_init(ares_channel *channelptr)
116 return ares_init_options(channelptr, NULL, 0);
119 int ares_init_options(ares_channel *channelptr, struct ares_options *options,
122 ares_channel channel;
124 int status = ARES_SUCCESS;
128 const char *env = getenv("CARES_MEMDEBUG");
132 env = getenv("CARES_MEMLIMIT");
135 long num = strtol(env, &endptr, 10);
136 if((endptr != env) && (endptr == env + strlen(env)) && (num > 0))
141 if (ares_library_initialized() != ARES_SUCCESS)
142 return ARES_ENOTINITIALIZED;
144 channel = malloc(sizeof(struct ares_channeldata));
152 /* Set everything to distinguished values so we know they haven't
156 channel->timeout = -1;
159 channel->rotate = -1;
160 channel->udp_port = -1;
161 channel->tcp_port = -1;
162 channel->socket_send_buffer_size = -1;
163 channel->socket_receive_buffer_size = -1;
164 channel->nservers = -1;
165 channel->ndomains = -1;
167 channel->tcp_connection_generation = 0;
168 channel->lookups = NULL;
169 channel->domains = NULL;
170 channel->sortlist = NULL;
171 channel->servers = NULL;
172 channel->sock_state_cb = NULL;
173 channel->sock_state_cb_data = NULL;
174 channel->sock_create_cb = NULL;
175 channel->sock_create_cb_data = NULL;
177 channel->last_server = 0;
178 channel->last_timeout_processed = (time_t)now.tv_sec;
180 memset(&channel->local_dev_name, 0, sizeof(channel->local_dev_name));
181 channel->local_ip4 = 0;
182 memset(&channel->local_ip6, 0, sizeof(channel->local_ip6));
184 /* Initialize our lists of queries */
185 ares__init_list_head(&(channel->all_queries));
186 for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
188 ares__init_list_head(&(channel->queries_by_qid[i]));
190 for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
192 ares__init_list_head(&(channel->queries_by_timeout[i]));
195 /* Initialize configuration by each of the four sources, from highest
196 * precedence to lowest.
199 if (status == ARES_SUCCESS) {
200 status = init_by_options(channel, options, optmask);
201 if (status != ARES_SUCCESS)
202 DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
203 ares_strerror(status)));
205 if (status == ARES_SUCCESS) {
206 status = init_by_environment(channel);
207 if (status != ARES_SUCCESS)
208 DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
209 ares_strerror(status)));
211 if (status == ARES_SUCCESS) {
212 status = init_by_resolv_conf(channel);
213 if (status != ARES_SUCCESS)
214 DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
215 ares_strerror(status)));
219 * No matter what failed or succeeded, seed defaults to provide
220 * useful behavior for things that we missed.
222 status = init_by_defaults(channel);
223 if (status != ARES_SUCCESS)
224 DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
225 ares_strerror(status)));
227 /* Generate random key */
229 if (status == ARES_SUCCESS) {
230 status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
231 if (status == ARES_SUCCESS)
232 channel->next_id = ares__generate_new_id(&channel->id_key);
234 DEBUGF(fprintf(stderr, "Error: init_id_key failed: %s\n",
235 ares_strerror(status)));
238 if (status != ARES_SUCCESS)
240 /* Something failed; clean up memory we may have allocated. */
241 if (channel->servers)
242 free(channel->servers);
243 if (channel->domains)
245 for (i = 0; i < channel->ndomains; i++)
246 free(channel->domains[i]);
247 free(channel->domains);
249 if (channel->sortlist)
250 free(channel->sortlist);
252 free(channel->lookups);
257 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
258 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
259 channel->nservers = 1;
261 ares__init_servers_state(channel);
263 *channelptr = channel;
267 /* ares_dup() duplicates a channel handle with all its options and returns a
268 new channel handle */
269 int ares_dup(ares_channel *dest, ares_channel src)
271 struct ares_options opts;
272 struct ares_addr_node *servers;
273 int ipv6_nservers = 0;
277 *dest = NULL; /* in case of failure return NULL explicitly */
279 /* First get the options supported by the old ares_save_options() function,
280 which is most of them */
281 rc = ares_save_options(src, &opts, &optmask);
285 /* Then create the new channel with those options */
286 rc = ares_init_options(dest, &opts, optmask);
288 /* destroy the options copy to not leak any memory */
289 ares_destroy_options(&opts);
294 /* Now clone the options that ares_save_options() doesn't support. */
295 (*dest)->sock_create_cb = src->sock_create_cb;
296 (*dest)->sock_create_cb_data = src->sock_create_cb_data;
298 strncpy((*dest)->local_dev_name, src->local_dev_name, sizeof(src->local_dev_name));
299 (*dest)->local_ip4 = src->local_ip4;
300 memcpy((*dest)->local_ip6, src->local_ip6, sizeof(src->local_ip6));
302 /* Full name server cloning required when not all are IPv4 */
303 for (i = 0; i < src->nservers; i++)
305 if (src->servers[i].addr.family != AF_INET) {
311 rc = ares_get_servers(src, &servers);
312 if (rc != ARES_SUCCESS)
314 rc = ares_set_servers(*dest, servers);
315 ares_free_data(servers);
316 if (rc != ARES_SUCCESS)
320 return ARES_SUCCESS; /* everything went fine */
323 /* Save options from initialized channel */
324 int ares_save_options(ares_channel channel, struct ares_options *options,
328 int ipv4_nservers = 0;
330 /* Zero everything out */
331 memset(options, 0, sizeof(struct ares_options));
333 if (!ARES_CONFIG_CHECK(channel))
336 /* Traditionally the optmask wasn't saved in the channel struct so it was
337 recreated here. ROTATE is the first option that has no struct field of
338 its own in the public config struct */
339 (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TRIES|ARES_OPT_NDOTS|
340 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
341 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
342 ARES_OPT_SORTLIST|ARES_OPT_TIMEOUTMS) |
343 (channel->optmask & ARES_OPT_ROTATE);
345 /* Copy easy stuff */
346 options->flags = channel->flags;
348 /* We return full millisecond resolution but that's only because we don't
349 set the ARES_OPT_TIMEOUT anymore, only the new ARES_OPT_TIMEOUTMS */
350 options->timeout = channel->timeout;
351 options->tries = channel->tries;
352 options->ndots = channel->ndots;
353 options->udp_port = (unsigned short)channel->udp_port;
354 options->tcp_port = (unsigned short)channel->tcp_port;
355 options->sock_state_cb = channel->sock_state_cb;
356 options->sock_state_cb_data = channel->sock_state_cb_data;
358 /* Copy IPv4 servers */
359 if (channel->nservers) {
360 for (i = 0; i < channel->nservers; i++)
362 if (channel->servers[i].addr.family == AF_INET)
366 options->servers = malloc(ipv4_nservers * sizeof(struct server_state));
367 if (!options->servers)
369 for (i = j = 0; i < channel->nservers; i++)
371 if (channel->servers[i].addr.family == AF_INET)
372 memcpy(&options->servers[j++],
373 &channel->servers[i].addr.addrV4,
374 sizeof(channel->servers[i].addr.addrV4));
378 options->nservers = ipv4_nservers;
381 if (channel->ndomains) {
382 options->domains = malloc(channel->ndomains * sizeof(char *));
383 if (!options->domains)
386 for (i = 0; i < channel->ndomains; i++)
388 options->ndomains = i;
389 options->domains[i] = strdup(channel->domains[i]);
390 if (!options->domains[i])
394 options->ndomains = channel->ndomains;
397 if (channel->lookups) {
398 options->lookups = strdup(channel->lookups);
399 if (!options->lookups && channel->lookups)
404 if (channel->nsort) {
405 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
406 if (!options->sortlist)
408 for (i = 0; i < channel->nsort; i++)
409 options->sortlist[i] = channel->sortlist[i];
411 options->nsort = channel->nsort;
416 static int init_by_options(ares_channel channel,
417 const struct ares_options *options,
423 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
424 channel->flags = options->flags;
425 if ((optmask & ARES_OPT_TIMEOUTMS) && channel->timeout == -1)
426 channel->timeout = options->timeout;
427 else if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
428 channel->timeout = options->timeout * 1000;
429 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
430 channel->tries = options->tries;
431 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
432 channel->ndots = options->ndots;
433 if ((optmask & ARES_OPT_ROTATE) && channel->rotate == -1)
435 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
436 channel->udp_port = options->udp_port;
437 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
438 channel->tcp_port = options->tcp_port;
439 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
441 channel->sock_state_cb = options->sock_state_cb;
442 channel->sock_state_cb_data = options->sock_state_cb_data;
444 if ((optmask & ARES_OPT_SOCK_SNDBUF)
445 && channel->socket_send_buffer_size == -1)
446 channel->socket_send_buffer_size = options->socket_send_buffer_size;
447 if ((optmask & ARES_OPT_SOCK_RCVBUF)
448 && channel->socket_receive_buffer_size == -1)
449 channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
451 /* Copy the IPv4 servers, if given. */
452 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
454 /* Avoid zero size allocations at any cost */
455 if (options->nservers > 0)
458 malloc(options->nservers * sizeof(struct server_state));
459 if (!channel->servers)
461 for (i = 0; i < options->nservers; i++)
463 channel->servers[i].addr.family = AF_INET;
464 memcpy(&channel->servers[i].addr.addrV4,
465 &options->servers[i],
466 sizeof(channel->servers[i].addr.addrV4));
469 channel->nservers = options->nservers;
472 /* Copy the domains, if given. Keep channel->ndomains consistent so
473 * we can clean up in case of error.
475 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
477 /* Avoid zero size allocations at any cost */
478 if (options->ndomains > 0)
480 channel->domains = malloc(options->ndomains * sizeof(char *));
481 if (!channel->domains)
483 for (i = 0; i < options->ndomains; i++)
485 channel->ndomains = i;
486 channel->domains[i] = strdup(options->domains[i]);
487 if (!channel->domains[i])
491 channel->ndomains = options->ndomains;
494 /* Set lookups, if given. */
495 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
497 channel->lookups = strdup(options->lookups);
498 if (!channel->lookups)
503 if ((optmask & ARES_OPT_SORTLIST) && (channel->nsort == -1) &&
504 (options->nsort>0)) {
505 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
506 if (!channel->sortlist)
508 for (i = 0; i < options->nsort; i++)
509 channel->sortlist[i] = options->sortlist[i];
510 channel->nsort = options->nsort;
513 channel->optmask = optmask;
518 static int init_by_environment(ares_channel channel)
520 const char *localdomain, *res_options;
523 localdomain = getenv("LOCALDOMAIN");
524 if (localdomain && channel->ndomains == -1)
526 status = set_search(channel, localdomain);
527 if (status != ARES_SUCCESS)
531 res_options = getenv("RES_OPTIONS");
534 status = set_options(channel, res_options);
535 if (status != ARES_SUCCESS)
544 * Warning: returns a dynamically allocated buffer, the user MUST
545 * use free() if the function returns 1
547 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
549 /* Test for the size we need */
553 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
554 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
556 *obuf = malloc(size+1);
560 if (RegQueryValueEx(hKey, subkey, 0, NULL,
561 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
574 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
576 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
577 DWORD enum_size = 39;
581 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
582 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
587 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
590 rc = get_res_nt(hVal, subkey, obuf);
598 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
600 FIXED_INFO *fi, *newfi;
601 DWORD size = sizeof (*fi);
602 IP_ADDR_STRING *ipAddr;
605 size_t ip_size = sizeof("255.255.255.255,")-1;
606 size_t left = ret_size;
614 res = (*ares_fpGetNetworkParams) (fi, &size);
615 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
618 newfi = realloc(fi, size);
623 res = (*ares_fpGetNetworkParams) (fi, &size);
624 if (res != ERROR_SUCCESS)
629 printf ("Host Name: %s\n", fi->HostName);
630 printf ("Domain Name: %s\n", fi->DomainName);
631 printf ("DNS Servers:\n"
632 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
634 if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
635 inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
638 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
639 left -= ret - ret_buf;
643 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
644 ipAddr = ipAddr->Next, i++)
646 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
648 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
649 left -= ret - ret_buf;
653 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
660 if (debug && left <= ip_size)
661 printf ("Too many nameservers. Truncating to %d addressess", count);
668 static int init_by_resolv_conf(ares_channel channel)
673 int status = -1, nservers = 0, nsort = 0;
674 struct server_state *servers = NULL;
675 struct apattern *sortlist = NULL;
680 NameServer info via IPHLPAPI (IP helper API):
681 GetNetworkParams() should be the trusted source for this.
682 Available in Win-98/2000 and later. If that fail, fall-back to
683 registry information.
687 On Windows 9X, the DNS server can be found in:
688 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
690 On Windows NT/2000/XP/2003:
691 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
693 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
695 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
698 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
709 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
712 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
714 status = config_nameserver(&servers, &nservers, buf);
715 if (status == ARES_SUCCESS)
722 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
726 RegOpenKeyEx(mykey, "Interfaces", 0,
727 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
728 if (get_res_nt(mykey, NAMESERVER, &line))
730 status = config_nameserver(&servers, &nservers, line);
733 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
735 status = config_nameserver(&servers, &nservers, line);
738 /* Try the interfaces */
739 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
741 status = config_nameserver(&servers, &nservers, line);
744 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
746 status = config_nameserver(&servers, &nservers, line);
756 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
760 if ((result = RegQueryValueEx(
761 mykey, NAMESERVER, NULL, &data_type,
764 ) == ERROR_SUCCESS ||
765 result == ERROR_MORE_DATA)
769 line = malloc(bytes+1);
770 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
771 (unsigned char *)line, &bytes) ==
774 status = config_nameserver(&servers, &nservers, line);
783 if (status == ARES_SUCCESS)
786 /* Catch the case when all the above checks fail (which happens when there
787 is no network card or the cable is unplugged) */
790 #elif defined(__riscos__)
792 /* Under RISC OS, name servers are listed in the
793 system variable Inet$Resolvers, space separated. */
795 line = getenv("Inet$Resolvers");
798 char *resolvers = strdup(line), *pos, *space;
805 space = strchr(pos, ' ');
808 status = config_nameserver(&servers, &nservers, pos);
809 if (status != ARES_SUCCESS)
814 if (status == ARES_SUCCESS)
820 #elif defined(WATT32)
824 for (i = 0; def_nameservers[i]; i++)
827 return ARES_SUCCESS; /* use localhost DNS server */
830 servers = calloc(i, sizeof(struct server_state));
834 for (i = 0; def_nameservers[i]; i++)
836 servers[i].addr.addrV4.s_addr = htonl(def_nameservers[i]);
837 servers[i].addr.family = AF_INET;
841 #elif defined(ANDROID)
842 char value[PROP_VALUE_MAX]="";
843 __system_property_get("net.dns1", value);
844 status = config_nameserver(&servers, &nservers, value);
845 if (status == ARES_SUCCESS)
854 /* Don't read resolv.conf and friends if we don't have to */
855 if (ARES_CONFIG_CHECK(channel))
858 fp = fopen(PATH_RESOLV_CONF, "r");
860 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
862 if ((p = try_config(line, "domain", ';')))
863 status = config_domain(channel, p);
864 else if ((p = try_config(line, "lookup", ';')) && !channel->lookups)
865 status = config_lookup(channel, p, "bind", "file");
866 else if ((p = try_config(line, "search", ';')))
867 status = set_search(channel, p);
868 else if ((p = try_config(line, "nameserver", ';')) &&
869 channel->nservers == -1)
870 status = config_nameserver(&servers, &nservers, p);
871 else if ((p = try_config(line, "sortlist", ';')) &&
872 channel->nsort == -1)
873 status = config_sortlist(&sortlist, &nsort, p);
874 else if ((p = try_config(line, "options", ';')))
875 status = set_options(channel, p);
877 status = ARES_SUCCESS;
878 if (status != ARES_SUCCESS)
891 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
892 error, strerror(error)));
893 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
898 if ((status == ARES_EOF) && (!channel->lookups)) {
899 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
900 fp = fopen("/etc/nsswitch.conf", "r");
902 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
904 if ((p = try_config(line, "hosts:", '\0')) && !channel->lookups)
906 (void)config_lookup(channel, p, "dns", "files");
918 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
919 error, strerror(error)));
920 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
926 if ((status == ARES_EOF) && (!channel->lookups)) {
927 /* Linux / GNU libc 2.x and possibly others have host.conf */
928 fp = fopen("/etc/host.conf", "r");
930 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
932 if ((p = try_config(line, "order", '\0')) && !channel->lookups)
934 (void)config_lookup(channel, p, "bind", "hosts");
946 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
947 error, strerror(error)));
948 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
954 if ((status == ARES_EOF) && (!channel->lookups)) {
955 /* Tru64 uses /etc/svc.conf */
956 fp = fopen("/etc/svc.conf", "r");
958 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
960 if ((p = try_config(line, "hosts=", '\0')) && !channel->lookups)
962 (void)config_lookup(channel, p, "bind", "local");
974 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
975 error, strerror(error)));
976 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
989 if (status != ARES_EOF)
993 if (sortlist != NULL)
998 /* If we got any name server entries, fill them in. */
1004 channel->servers = servers;
1005 channel->nservers = nservers;
1008 /* If we got any sortlist entries, fill them in. */
1011 channel->sortlist = sortlist;
1012 channel->nsort = nsort;
1015 return ARES_SUCCESS;
1018 static int init_by_defaults(ares_channel channel)
1020 char *hostname = NULL;
1021 int rc = ARES_SUCCESS;
1022 #ifdef HAVE_GETHOSTNAME
1026 if (channel->flags == -1)
1028 if (channel->timeout == -1)
1029 channel->timeout = DEFAULT_TIMEOUT;
1030 if (channel->tries == -1)
1031 channel->tries = DEFAULT_TRIES;
1032 if (channel->ndots == -1)
1034 if (channel->rotate == -1)
1035 channel->rotate = 0;
1036 if (channel->udp_port == -1)
1037 channel->udp_port = htons(NAMESERVER_PORT);
1038 if (channel->tcp_port == -1)
1039 channel->tcp_port = htons(NAMESERVER_PORT);
1041 if (channel->nservers == -1) {
1042 /* If nobody specified servers, try a local named. */
1043 channel->servers = malloc(sizeof(struct server_state));
1044 if (!channel->servers) {
1048 channel->servers[0].addr.family = AF_INET;
1049 channel->servers[0].addr.addrV4.s_addr = htonl(INADDR_LOOPBACK);
1050 channel->nservers = 1;
1053 #if defined(USE_WINSOCK)
1054 #define toolong(x) (x == -1) && (SOCKERRNO == WSAEFAULT)
1055 #elif defined(ENAMETOOLONG)
1056 #define toolong(x) (x == -1) && ((SOCKERRNO == ENAMETOOLONG) || \
1057 (SOCKERRNO == EINVAL))
1059 #define toolong(x) (x == -1) && (SOCKERRNO == EINVAL)
1062 if (channel->ndomains == -1) {
1063 /* Derive a default domain search list from the kernel hostname,
1064 * or set it to empty if the hostname isn't helpful.
1068 channel->ndomains = 0; /* default to none */
1070 #ifdef HAVE_GETHOSTNAME
1071 hostname = malloc(len);
1078 res = gethostname(hostname, len);
1083 p = realloc(hostname, len);
1098 dot = strchr(hostname, '.');
1100 /* a dot was found */
1101 channel->domains = malloc(sizeof(char *));
1102 if (!channel->domains) {
1106 channel->domains[0] = strdup(dot + 1);
1107 if (!channel->domains[0]) {
1111 channel->ndomains = 1;
1116 if (channel->nsort == -1) {
1117 channel->sortlist = NULL;
1121 if (!channel->lookups) {
1122 channel->lookups = strdup("fb");
1123 if (!channel->lookups)
1129 if(channel->servers)
1130 free(channel->servers);
1132 if(channel->domains && channel->domains[0])
1133 free(channel->domains[0]);
1134 if(channel->domains)
1135 free(channel->domains);
1136 if(channel->lookups)
1137 free(channel->lookups);
1146 #if !defined(WIN32) && !defined(WATT32)
1147 static int config_domain(ares_channel channel, char *str)
1151 /* Set a single search domain. */
1153 while (*q && !ISSPACE(*q))
1156 return set_search(channel, str);
1159 #if defined(__INTEL_COMPILER) && (__INTEL_COMPILER == 910) && \
1160 defined(__OPTIMIZE__) && defined(__unix__) && defined(__i386__)
1161 /* workaround icc 9.1 optimizer issue */
1162 # define vqualifier volatile
1167 static int config_lookup(ares_channel channel, const char *str,
1168 const char *bindch, const char *filech)
1170 char lookups[3], *l;
1171 const char *vqualifier p;
1173 /* Set the lookup order. Only the first letter of each work
1174 * is relevant, and it has to be "b" for DNS or "f" for the
1175 * host file. Ignore everything else.
1181 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
1182 if (*p == *bindch) *l++ = 'b';
1185 while (*p && !ISSPACE(*p) && (*p != ','))
1187 while (*p && (ISSPACE(*p) || (*p == ',')))
1191 channel->lookups = strdup(lookups);
1192 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1194 #endif /* !WIN32 & !WATT32 */
1197 static int config_nameserver(struct server_state **servers, int *nservers,
1200 struct ares_addr host;
1201 struct server_state *newserv;
1203 /* On Windows, there may be more than one nameserver specified in the same
1204 * registry key, so we parse input as a space or comma seperated list.
1208 /* Skip whitespace and commas. */
1209 while (*p && (ISSPACE(*p) || (*p == ',')))
1212 /* No more input, done. */
1215 /* Pointer to start of IPv4 or IPv6 address part. */
1218 /* Advance past this address. */
1219 while (*p && !ISSPACE(*p) && (*p != ','))
1222 /* Null terminate this address. */
1225 /* Reached end of input, done when this address is processed. */
1228 /* Convert textual address to binary format. */
1229 if (ares_inet_pton(AF_INET, txtaddr, &host.addrV4) == 1)
1230 host.family = AF_INET;
1231 else if (ares_inet_pton(AF_INET6, txtaddr, &host.addrV6) == 1)
1232 host.family = AF_INET6;
1236 /* Resize servers state array. */
1237 newserv = realloc(*servers, (*nservers + 1) *
1238 sizeof(struct server_state));
1242 /* Store address data. */
1243 newserv[*nservers].addr.family = host.family;
1244 if (host.family == AF_INET)
1245 memcpy(&newserv[*nservers].addr.addrV4, &host.addrV4,
1246 sizeof(host.addrV4));
1248 memcpy(&newserv[*nservers].addr.addrV6, &host.addrV6,
1249 sizeof(host.addrV6));
1251 /* Update arguments. */
1256 return ARES_SUCCESS;
1260 static int config_sortlist(struct apattern **sortlist, int *nsort,
1263 struct apattern pat;
1266 /* Add sortlist entries. */
1267 while (*str && *str != ';')
1270 char ipbuf[16], ipbufpfx[32];
1271 /* Find just the IP */
1273 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1275 memcpy(ipbuf, str, q-str);
1276 ipbuf[q-str] = '\0';
1277 /* Find the prefix */
1280 const char *str2 = q+1;
1281 while (*q && *q != ';' && !ISSPACE(*q))
1283 memcpy(ipbufpfx, str, q-str);
1284 ipbufpfx[q-str] = '\0';
1289 /* Lets see if it is CIDR */
1290 /* First we'll try IPv6 */
1291 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1293 sizeof(pat.addrV6))) > 0)
1295 pat.type = PATTERN_CIDR;
1296 pat.mask.bits = (unsigned short)bits;
1297 pat.family = AF_INET6;
1298 if (!sortlist_alloc(sortlist, nsort, &pat))
1301 else if (ipbufpfx[0] &&
1302 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addrV4,
1303 sizeof(pat.addrV4))) > 0)
1305 pat.type = PATTERN_CIDR;
1306 pat.mask.bits = (unsigned short)bits;
1307 pat.family = AF_INET;
1308 if (!sortlist_alloc(sortlist, nsort, &pat))
1311 /* See if it is just a regular IP */
1312 else if (ip_addr(ipbuf, q-str, &pat.addrV4) == 0)
1316 memcpy(ipbuf, str, q-str);
1317 ipbuf[q-str] = '\0';
1318 if (ip_addr(ipbuf, q-str, &pat.mask.addr4) != 0)
1323 pat.family = AF_INET;
1324 pat.type = PATTERN_MASK;
1325 if (!sortlist_alloc(sortlist, nsort, &pat))
1330 while (*q && *q != ';' && !ISSPACE(*q))
1334 while (ISSPACE(*str))
1338 return ARES_SUCCESS;
1341 #endif /* !WATT32 */
1343 static int set_search(ares_channel channel, const char *str)
1348 if(channel->ndomains != -1) {
1349 /* if we already have some domains present, free them first */
1350 for(n=0; n < channel->ndomains; n++)
1351 free(channel->domains[n]);
1352 free(channel->domains);
1353 channel->domains = NULL;
1354 channel->ndomains = -1;
1357 /* Count the domains given. */
1362 while (*p && !ISSPACE(*p))
1371 channel->ndomains = 0;
1372 return ARES_SUCCESS;
1375 channel->domains = malloc(n * sizeof(char *));
1376 if (!channel->domains)
1379 /* Now copy the domains. */
1384 channel->ndomains = n;
1386 while (*q && !ISSPACE(*q))
1388 channel->domains[n] = malloc(q - p + 1);
1389 if (!channel->domains[n])
1391 memcpy(channel->domains[n], p, q - p);
1392 channel->domains[n][q - p] = 0;
1398 channel->ndomains = n;
1400 return ARES_SUCCESS;
1403 static int set_options(ares_channel channel, const char *str)
1405 const char *p, *q, *val;
1411 while (*q && !ISSPACE(*q))
1413 val = try_option(p, q, "ndots:");
1414 if (val && channel->ndots == -1)
1415 channel->ndots = aresx_sltosi(strtol(val, NULL, 10));
1416 val = try_option(p, q, "retrans:");
1417 if (val && channel->timeout == -1)
1418 channel->timeout = aresx_sltosi(strtol(val, NULL, 10));
1419 val = try_option(p, q, "retry:");
1420 if (val && channel->tries == -1)
1421 channel->tries = aresx_sltosi(strtol(val, NULL, 10));
1422 val = try_option(p, q, "rotate");
1423 if (val && channel->rotate == -1)
1424 channel->rotate = 1;
1430 return ARES_SUCCESS;
1433 static const char *try_option(const char *p, const char *q, const char *opt)
1435 size_t len = strlen(opt);
1436 return ((size_t)(q - p) >= len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1439 #if !defined(WIN32) && !defined(WATT32)
1440 static char *try_config(char *s, const char *opt, char scc)
1447 /* no line or no option */
1450 /* Hash '#' character is always used as primary comment char, additionally
1451 a not-NUL secondary comment char will be considered when specified. */
1453 /* trim line comment */
1456 while (*p && (*p != '#') && (*p != scc))
1459 while (*p && (*p != '#'))
1463 /* trim trailing whitespace */
1465 while ((q >= s) && ISSPACE(*q))
1469 /* skip leading whitespace */
1471 while (*p && ISSPACE(*p))
1478 if ((len = strlen(opt)) == 0)
1482 if (strncmp(p, opt, len) != 0)
1483 /* line and option do not match */
1486 /* skip over given option name */
1490 /* no option value */
1493 if ((opt[len-1] != ':') && (opt[len-1] != '=') && !ISSPACE(*p))
1494 /* whitespace between option name and value is mandatory
1495 for given option names which do not end with ':' or '=' */
1498 /* skip over whitespace */
1499 while (*p && ISSPACE(*p))
1503 /* no option value */
1506 /* return pointer to option value */
1510 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1511 struct apattern *pat)
1513 struct apattern *newsort;
1514 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1517 newsort[*nsort] = *pat;
1518 *sortlist = newsort;
1523 static int ip_addr(const char *ipbuf, ssize_t len, struct in_addr *addr)
1526 /* Four octets and three periods yields at most 15 characters. */
1530 addr->s_addr = inet_addr(ipbuf);
1531 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1536 static void natural_mask(struct apattern *pat)
1538 struct in_addr addr;
1540 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1543 addr.s_addr = ntohl(pat->addrV4.s_addr);
1545 /* This is out of date in the CIDR world, but some people might
1548 if (IN_CLASSA(addr.s_addr))
1549 pat->mask.addr4.s_addr = htonl(IN_CLASSA_NET);
1550 else if (IN_CLASSB(addr.s_addr))
1551 pat->mask.addr4.s_addr = htonl(IN_CLASSB_NET);
1553 pat->mask.addr4.s_addr = htonl(IN_CLASSC_NET);
1555 #endif /* !WIN32 && !WATT32 */
1557 /* initialize an rc4 key. If possible a cryptographically secure random key
1558 is generated using a suitable function (for example win32's RtlGenRandom as
1560 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1561 otherwise the code defaults to cross-platform albeit less secure mechanism
1564 static void randomize_key(unsigned char* key,int key_data_len)
1570 if (ares_fpSystemFunction036)
1572 res = (*ares_fpSystemFunction036) (key, key_data_len);
1578 FILE *f = fopen(RANDOM_FILE, "rb");
1580 counter = aresx_uztosi(fread(key, 1, key_data_len, f));
1586 if ( !randomized ) {
1587 for (;counter<key_data_len;counter++)
1588 key[counter]=(unsigned char)(rand() % 256);
1592 static int init_id_key(rc4_key* key,int key_data_len)
1594 unsigned char index1;
1595 unsigned char index2;
1596 unsigned char* state;
1598 unsigned char *key_data_ptr = 0;
1600 key_data_ptr = calloc(1,key_data_len);
1604 state = &key->state[0];
1605 for(counter = 0; counter < 256; counter++)
1606 /* unnecessary AND but it keeps some compilers happier */
1607 state[counter] = (unsigned char)(counter & 0xff);
1608 randomize_key(key->state,key_data_len);
1613 for(counter = 0; counter < 256; counter++)
1615 index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1617 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1619 index1 = (unsigned char)((index1 + 1) % key_data_len);
1622 return ARES_SUCCESS;
1625 unsigned short ares__generate_new_id(rc4_key* key)
1628 ares__rc4(key, (unsigned char *)&r, sizeof(r));
1632 void ares_set_local_ip4(ares_channel channel, unsigned int local_ip)
1634 channel->local_ip4 = local_ip;
1637 /* local_ip6 should be 16 bytes in length */
1638 void ares_set_local_ip6(ares_channel channel,
1639 const unsigned char* local_ip6)
1641 memcpy(&channel->local_ip6, local_ip6, sizeof(channel->local_ip6));
1644 /* local_dev_name should be null terminated. */
1645 void ares_set_local_dev(ares_channel channel,
1646 const char* local_dev_name)
1648 strncpy(channel->local_dev_name, local_dev_name,
1649 sizeof(channel->local_dev_name));
1650 channel->local_dev_name[sizeof(channel->local_dev_name) - 1] = 0;
1654 void ares_set_socket_callback(ares_channel channel,
1655 ares_sock_create_callback cb,
1658 channel->sock_create_cb = cb;
1659 channel->sock_create_cb_data = data;
1662 void ares__init_servers_state(ares_channel channel)
1664 struct server_state *server;
1667 for (i = 0; i < channel->nservers; i++)
1669 server = &channel->servers[i];
1670 server->udp_socket = ARES_SOCKET_BAD;
1671 server->tcp_socket = ARES_SOCKET_BAD;
1672 server->tcp_connection_generation = ++channel->tcp_connection_generation;
1673 server->tcp_lenbuf_pos = 0;
1674 server->tcp_buffer_pos = 0;
1675 server->tcp_buffer = NULL;
1676 server->tcp_length = 0;
1677 server->qhead = NULL;
1678 server->qtail = NULL;
1679 ares__init_list_head(&server->queries_to_server);
1680 server->channel = channel;
1681 server->is_broken = 0;