2 /* Copyright 1998 by the Massachusetts Institute of Technology.
3 * Copyright (C) 2007-2012 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"
20 #ifdef HAVE_SYS_PARAM_H
21 #include <sys/param.h>
24 #ifdef HAVE_SYS_TIME_H
28 #ifdef HAVE_SYS_SOCKET_H
29 #include <sys/socket.h>
32 #ifdef HAVE_NETINET_IN_H
33 #include <netinet/in.h>
40 #ifdef HAVE_ARPA_INET_H
41 #include <arpa/inet.h>
44 #ifdef HAVE_ARPA_NAMESER_H
45 # include <arpa/nameser.h>
49 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
50 # include <arpa/nameser_compat.h>
63 #if defined(ANDROID) || defined(__ANDROID__)
64 #include <sys/system_properties.h>
65 /* From the Bionic sources */
66 #define DNS_PROP_NAME_PREFIX "net.dns"
67 #define MAX_DNS_PROPERTIES 8
71 #include "inet_ntop.h"
72 #include "inet_net_pton.h"
73 #include "ares_library_init.h"
74 #include "ares_nowarn.h"
75 #include "ares_platform.h"
76 #include "ares_private.h"
79 #undef WIN32 /* Redefined in MingW/MSVC headers */
82 static int init_by_options(ares_channel channel,
83 const struct ares_options *options,
85 static int init_by_environment(ares_channel channel);
86 static int init_by_resolv_conf(ares_channel channel);
87 static int init_by_defaults(ares_channel channel);
90 static int config_nameserver(struct server_state **servers, int *nservers,
93 static int set_search(ares_channel channel, const char *str);
94 static int set_options(ares_channel channel, const char *str);
95 static const char *try_option(const char *p, const char *q, const char *opt);
96 static int init_id_key(rc4_key* key,int key_data_len);
98 #if !defined(WIN32) && !defined(WATT32) && \
99 !defined(ANDROID) && !defined(__ANDROID__)
100 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
101 struct apattern *pat);
102 static int ip_addr(const char *s, ssize_t len, struct in_addr *addr);
103 static void natural_mask(struct apattern *pat);
104 static int config_domain(ares_channel channel, char *str);
105 static int config_lookup(ares_channel channel, const char *str,
106 const char *bindch, const char *filech);
107 static int config_sortlist(struct apattern **sortlist, int *nsort,
109 static char *try_config(char *s, const char *opt, char scc);
112 #define ARES_CONFIG_CHECK(x) (x->lookups && x->nsort > -1 && \
113 x->nservers > -1 && \
114 x->ndomains > -1 && \
115 x->ndots > -1 && x->timeout > -1 && \
118 int ares_init(ares_channel *channelptr)
120 return ares_init_options(channelptr, NULL, 0);
123 int ares_init_options(ares_channel *channelptr, struct ares_options *options,
126 ares_channel channel;
128 int status = ARES_SUCCESS;
132 const char *env = getenv("CARES_MEMDEBUG");
136 env = getenv("CARES_MEMLIMIT");
139 long num = strtol(env, &endptr, 10);
140 if((endptr != env) && (endptr == env + strlen(env)) && (num > 0))
145 if (ares_library_initialized() != ARES_SUCCESS)
146 return ARES_ENOTINITIALIZED;
148 channel = malloc(sizeof(struct ares_channeldata));
156 /* Set everything to distinguished values so we know they haven't
160 channel->timeout = -1;
163 channel->rotate = -1;
164 channel->udp_port = -1;
165 channel->tcp_port = -1;
166 channel->socket_send_buffer_size = -1;
167 channel->socket_receive_buffer_size = -1;
168 channel->nservers = -1;
169 channel->ndomains = -1;
171 channel->tcp_connection_generation = 0;
172 channel->lookups = NULL;
173 channel->domains = NULL;
174 channel->sortlist = NULL;
175 channel->servers = NULL;
176 channel->sock_state_cb = NULL;
177 channel->sock_state_cb_data = NULL;
178 channel->sock_create_cb = NULL;
179 channel->sock_create_cb_data = NULL;
181 channel->last_server = 0;
182 channel->last_timeout_processed = (time_t)now.tv_sec;
184 memset(&channel->local_dev_name, 0, sizeof(channel->local_dev_name));
185 channel->local_ip4 = 0;
186 memset(&channel->local_ip6, 0, sizeof(channel->local_ip6));
188 /* Initialize our lists of queries */
189 ares__init_list_head(&(channel->all_queries));
190 for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
192 ares__init_list_head(&(channel->queries_by_qid[i]));
194 for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
196 ares__init_list_head(&(channel->queries_by_timeout[i]));
199 /* Initialize configuration by each of the four sources, from highest
200 * precedence to lowest.
203 if (status == ARES_SUCCESS) {
204 status = init_by_options(channel, options, optmask);
205 if (status != ARES_SUCCESS)
206 DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
207 ares_strerror(status)));
209 if (status == ARES_SUCCESS) {
210 status = init_by_environment(channel);
211 if (status != ARES_SUCCESS)
212 DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
213 ares_strerror(status)));
215 if (status == ARES_SUCCESS) {
216 status = init_by_resolv_conf(channel);
217 if (status != ARES_SUCCESS)
218 DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
219 ares_strerror(status)));
223 * No matter what failed or succeeded, seed defaults to provide
224 * useful behavior for things that we missed.
226 status = init_by_defaults(channel);
227 if (status != ARES_SUCCESS)
228 DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
229 ares_strerror(status)));
231 /* Generate random key */
233 if (status == ARES_SUCCESS) {
234 status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
235 if (status == ARES_SUCCESS)
236 channel->next_id = ares__generate_new_id(&channel->id_key);
238 DEBUGF(fprintf(stderr, "Error: init_id_key failed: %s\n",
239 ares_strerror(status)));
242 if (status != ARES_SUCCESS)
244 /* Something failed; clean up memory we may have allocated. */
245 if (channel->servers)
246 free(channel->servers);
247 if (channel->domains)
249 for (i = 0; i < channel->ndomains; i++)
250 free(channel->domains[i]);
251 free(channel->domains);
253 if (channel->sortlist)
254 free(channel->sortlist);
256 free(channel->lookups);
261 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
262 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
263 channel->nservers = 1;
265 ares__init_servers_state(channel);
267 *channelptr = channel;
271 /* ares_dup() duplicates a channel handle with all its options and returns a
272 new channel handle */
273 int ares_dup(ares_channel *dest, ares_channel src)
275 struct ares_options opts;
276 struct ares_addr_node *servers;
277 int ipv6_nservers = 0;
281 *dest = NULL; /* in case of failure return NULL explicitly */
283 /* First get the options supported by the old ares_save_options() function,
284 which is most of them */
285 rc = ares_save_options(src, &opts, &optmask);
289 /* Then create the new channel with those options */
290 rc = ares_init_options(dest, &opts, optmask);
292 /* destroy the options copy to not leak any memory */
293 ares_destroy_options(&opts);
298 /* Now clone the options that ares_save_options() doesn't support. */
299 (*dest)->sock_create_cb = src->sock_create_cb;
300 (*dest)->sock_create_cb_data = src->sock_create_cb_data;
302 strncpy((*dest)->local_dev_name, src->local_dev_name,
303 sizeof(src->local_dev_name));
304 (*dest)->local_ip4 = src->local_ip4;
305 memcpy((*dest)->local_ip6, src->local_ip6, sizeof(src->local_ip6));
307 /* Full name server cloning required when not all are IPv4 */
308 for (i = 0; i < src->nservers; i++)
310 if (src->servers[i].addr.family != AF_INET) {
316 rc = ares_get_servers(src, &servers);
317 if (rc != ARES_SUCCESS)
319 rc = ares_set_servers(*dest, servers);
320 ares_free_data(servers);
321 if (rc != ARES_SUCCESS)
325 return ARES_SUCCESS; /* everything went fine */
328 /* Save options from initialized channel */
329 int ares_save_options(ares_channel channel, struct ares_options *options,
333 int ipv4_nservers = 0;
335 /* Zero everything out */
336 memset(options, 0, sizeof(struct ares_options));
338 if (!ARES_CONFIG_CHECK(channel))
341 /* Traditionally the optmask wasn't saved in the channel struct so it was
342 recreated here. ROTATE is the first option that has no struct field of
343 its own in the public config struct */
344 (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TRIES|ARES_OPT_NDOTS|
345 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
346 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
347 ARES_OPT_SORTLIST|ARES_OPT_TIMEOUTMS) |
348 (channel->optmask & ARES_OPT_ROTATE);
350 /* Copy easy stuff */
351 options->flags = channel->flags;
353 /* We return full millisecond resolution but that's only because we don't
354 set the ARES_OPT_TIMEOUT anymore, only the new ARES_OPT_TIMEOUTMS */
355 options->timeout = channel->timeout;
356 options->tries = channel->tries;
357 options->ndots = channel->ndots;
358 options->udp_port = (unsigned short)channel->udp_port;
359 options->tcp_port = (unsigned short)channel->tcp_port;
360 options->sock_state_cb = channel->sock_state_cb;
361 options->sock_state_cb_data = channel->sock_state_cb_data;
363 /* Copy IPv4 servers */
364 if (channel->nservers) {
365 for (i = 0; i < channel->nservers; i++)
367 if (channel->servers[i].addr.family == AF_INET)
371 options->servers = malloc(ipv4_nservers * sizeof(struct in_addr));
372 if (!options->servers)
374 for (i = j = 0; i < channel->nservers; i++)
376 if (channel->servers[i].addr.family == AF_INET)
377 memcpy(&options->servers[j++],
378 &channel->servers[i].addr.addrV4,
379 sizeof(channel->servers[i].addr.addrV4));
383 options->nservers = ipv4_nservers;
386 if (channel->ndomains) {
387 options->domains = malloc(channel->ndomains * sizeof(char *));
388 if (!options->domains)
391 for (i = 0; i < channel->ndomains; i++)
393 options->ndomains = i;
394 options->domains[i] = strdup(channel->domains[i]);
395 if (!options->domains[i])
399 options->ndomains = channel->ndomains;
402 if (channel->lookups) {
403 options->lookups = strdup(channel->lookups);
404 if (!options->lookups && channel->lookups)
409 if (channel->nsort) {
410 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
411 if (!options->sortlist)
413 for (i = 0; i < channel->nsort; i++)
414 options->sortlist[i] = channel->sortlist[i];
416 options->nsort = channel->nsort;
421 static int init_by_options(ares_channel channel,
422 const struct ares_options *options,
428 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
429 channel->flags = options->flags;
430 if ((optmask & ARES_OPT_TIMEOUTMS) && channel->timeout == -1)
431 channel->timeout = options->timeout;
432 else if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
433 channel->timeout = options->timeout * 1000;
434 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
435 channel->tries = options->tries;
436 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
437 channel->ndots = options->ndots;
438 if ((optmask & ARES_OPT_ROTATE) && channel->rotate == -1)
440 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
441 channel->udp_port = htons(options->udp_port);
442 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
443 channel->tcp_port = htons(options->tcp_port);
444 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
446 channel->sock_state_cb = options->sock_state_cb;
447 channel->sock_state_cb_data = options->sock_state_cb_data;
449 if ((optmask & ARES_OPT_SOCK_SNDBUF)
450 && channel->socket_send_buffer_size == -1)
451 channel->socket_send_buffer_size = options->socket_send_buffer_size;
452 if ((optmask & ARES_OPT_SOCK_RCVBUF)
453 && channel->socket_receive_buffer_size == -1)
454 channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
456 /* Copy the IPv4 servers, if given. */
457 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
459 /* Avoid zero size allocations at any cost */
460 if (options->nservers > 0)
463 malloc(options->nservers * sizeof(struct server_state));
464 if (!channel->servers)
466 for (i = 0; i < options->nservers; i++)
468 channel->servers[i].addr.family = AF_INET;
469 memcpy(&channel->servers[i].addr.addrV4,
470 &options->servers[i],
471 sizeof(channel->servers[i].addr.addrV4));
474 channel->nservers = options->nservers;
477 /* Copy the domains, if given. Keep channel->ndomains consistent so
478 * we can clean up in case of error.
480 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
482 /* Avoid zero size allocations at any cost */
483 if (options->ndomains > 0)
485 channel->domains = malloc(options->ndomains * sizeof(char *));
486 if (!channel->domains)
488 for (i = 0; i < options->ndomains; i++)
490 channel->ndomains = i;
491 channel->domains[i] = strdup(options->domains[i]);
492 if (!channel->domains[i])
496 channel->ndomains = options->ndomains;
499 /* Set lookups, if given. */
500 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
502 channel->lookups = strdup(options->lookups);
503 if (!channel->lookups)
508 if ((optmask & ARES_OPT_SORTLIST) && (channel->nsort == -1) &&
509 (options->nsort>0)) {
510 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
511 if (!channel->sortlist)
513 for (i = 0; i < options->nsort; i++)
514 channel->sortlist[i] = options->sortlist[i];
515 channel->nsort = options->nsort;
518 channel->optmask = optmask;
523 static int init_by_environment(ares_channel channel)
525 const char *localdomain, *res_options;
528 localdomain = getenv("LOCALDOMAIN");
529 if (localdomain && channel->ndomains == -1)
531 status = set_search(channel, localdomain);
532 if (status != ARES_SUCCESS)
536 res_options = getenv("RES_OPTIONS");
539 status = set_options(channel, res_options);
540 if (status != ARES_SUCCESS)
549 * Warning: returns a dynamically allocated buffer, the user MUST
550 * use free() if the function returns 1
552 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
554 /* Test for the size we need */
558 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
559 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
561 *obuf = malloc(size+1);
565 if (RegQueryValueEx(hKey, subkey, 0, NULL,
566 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
579 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
581 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
582 DWORD enum_size = 39;
586 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
587 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
592 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
595 rc = get_res_nt(hVal, subkey, obuf);
603 /* get_iphlpapi_dns_classic() is supported on W98 and newer */
604 static int get_iphlpapi_dns_classic(char *ret_buf, size_t ret_size)
606 FIXED_INFO *fi, *newfi;
607 struct ares_addr namesrvr;
609 IP_ADDR_STRING *ipAddr;
612 DWORD size = sizeof (*fi);
613 char *endptr = ret_buf;
622 res = (*ares_fpGetNetworkParams) (fi, &size);
623 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
626 newfi = realloc(fi, size);
631 res = (*ares_fpGetNetworkParams) (fi, &size);
632 if (res != ERROR_SUCCESS)
635 for (ipAddr = &fi->DnsServerList; ipAddr; ipAddr = ipAddr->Next)
637 txtaddr = &ipAddr->IpAddress.String[0];
639 /* Validate converting textual address to binary format. */
640 if (ares_inet_pton(AF_INET, txtaddr, &namesrvr.addrV4) == 1)
642 if ((namesrvr.addrV4.S_un.S_addr == INADDR_ANY) ||
643 (namesrvr.addrV4.S_un.S_addr == INADDR_NONE))
646 else if (ares_inet_pton(AF_INET6, txtaddr, &namesrvr.addrV6) == 1)
648 if (memcmp(&namesrvr.addrV6, &ares_in6addr_any,
649 sizeof(namesrvr.addrV6)) == 0)
655 txtlen = strlen(txtaddr);
656 if (ret_size >= strlen(ret_buf) + txtlen + 2)
658 sprintf(endptr, "%s,", txtaddr);
659 endptr += txtlen + 1;
668 if (endptr != ret_buf)
669 *(endptr - 1) = '\0';
674 #define IPAA_INITIAL_BUF_SZ 15 * 1024
675 #define IPAA_MAX_TRIES 3
677 static int get_iphlpapi_dns_info(char *ret_buf, size_t ret_size)
679 IP_ADAPTER_DNS_SERVER_ADDRESS *ipaDNSAddr;
680 IP_ADAPTER_ADDRESSES *ipaa, *newipaa, *ipaaEntry;
682 ULONG ReqBufsz = IPAA_INITIAL_BUF_SZ;
683 ULONG Bufsz = IPAA_INITIAL_BUF_SZ;
685 char *endptr = ret_buf;
686 int trying = IPAA_MAX_TRIES;
691 struct sockaddr_in *sa4;
692 struct sockaddr_in6 *sa6;
695 char txtaddr[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")];
698 /* Unless GetAdaptersAddresses is available, use GetNetworkParams */
699 if (ares_fpGetAdaptersAddresses == ZERO_NULL)
700 return get_iphlpapi_dns_classic(ret_buf, ret_size);
704 ipaa = malloc(Bufsz);
708 /* Usually this call suceeds with initial buffer size */
709 res = (*ares_fpGetAdaptersAddresses) (AF_UNSPEC, AddrFlags, NULL,
711 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
714 while ((res == ERROR_BUFFER_OVERFLOW) && (--trying))
716 if (Bufsz < ReqBufsz)
718 newipaa = realloc(ipaa, ReqBufsz);
724 res = (*ares_fpGetAdaptersAddresses) (AF_UNSPEC, AddrFlags, NULL,
726 if (res == ERROR_SUCCESS)
729 if (res != ERROR_SUCCESS)
732 for (ipaaEntry = ipaa; ipaaEntry; ipaaEntry = ipaaEntry->Next)
734 for (ipaDNSAddr = ipaaEntry->FirstDnsServerAddress;
736 ipaDNSAddr = ipaDNSAddr->Next)
738 namesrvr.sa = ipaDNSAddr->Address.lpSockaddr;
740 if (namesrvr.sa->sa_family == AF_INET)
742 if ((namesrvr.sa4->sin_addr.S_un.S_addr == INADDR_ANY) ||
743 (namesrvr.sa4->sin_addr.S_un.S_addr == INADDR_NONE))
745 if (! ares_inet_ntop(AF_INET, &namesrvr.sa4->sin_addr,
746 txtaddr, sizeof(txtaddr)))
749 else if (namesrvr.sa->sa_family == AF_INET6)
751 if (memcmp(&namesrvr.sa6->sin6_addr, &ares_in6addr_any,
752 sizeof(namesrvr.sa6->sin6_addr)) == 0)
754 if (! ares_inet_ntop(AF_INET, &namesrvr.sa6->sin6_addr,
755 txtaddr, sizeof(txtaddr)))
761 txtlen = strlen(txtaddr);
762 if (ret_size >= strlen(ret_buf) + txtlen + 2)
764 sprintf(endptr, "%s,", txtaddr);
765 endptr += txtlen + 1;
775 if (endptr != ret_buf)
776 *(endptr - 1) = '\0';
782 static int init_by_resolv_conf(ares_channel channel)
784 #if !defined(ANDROID) && !defined(__ANDROID__) && !defined(WATT32)
787 int status = -1, nservers = 0, nsort = 0;
788 struct server_state *servers = NULL;
789 struct apattern *sortlist = NULL;
794 NameServer info via IPHLPAPI (IP helper API):
795 GetNetworkParams() should be the trusted source for this.
796 Available in Win-98/2000 and later. If that fail, fall-back to
797 registry information.
801 On Windows 9X, the DNS server can be found in:
802 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
804 On Windows NT/2000/XP/2003:
805 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
807 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
809 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
812 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
822 win_platform platform;
824 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
827 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
829 status = config_nameserver(&servers, &nservers, buf);
830 if (status == ARES_SUCCESS)
834 platform = ares__getplatform();
836 if (platform == WIN_NT)
839 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
843 RegOpenKeyEx(mykey, "Interfaces", 0,
844 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
845 if (get_res_nt(mykey, NAMESERVER, &line))
847 status = config_nameserver(&servers, &nservers, line);
850 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
852 status = config_nameserver(&servers, &nservers, line);
855 /* Try the interfaces */
856 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
858 status = config_nameserver(&servers, &nservers, line);
861 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
863 status = config_nameserver(&servers, &nservers, line);
870 else if (platform == WIN_9X)
873 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
877 if ((result = RegQueryValueEx(
878 mykey, NAMESERVER, NULL, &data_type,
881 ) == ERROR_SUCCESS ||
882 result == ERROR_MORE_DATA)
886 line = malloc(bytes+1);
887 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
888 (unsigned char *)line, &bytes) ==
891 status = config_nameserver(&servers, &nservers, line);
900 if (status == ARES_SUCCESS)
903 /* Catch the case when all the above checks fail (which happens when there
904 is no network card or the cable is unplugged) */
907 #elif defined(__riscos__)
909 /* Under RISC OS, name servers are listed in the
910 system variable Inet$Resolvers, space separated. */
912 line = getenv("Inet$Resolvers");
915 char *resolvers = strdup(line), *pos, *space;
922 space = strchr(pos, ' ');
925 status = config_nameserver(&servers, &nservers, pos);
926 if (status != ARES_SUCCESS)
931 if (status == ARES_SUCCESS)
937 #elif defined(WATT32)
941 for (i = 0; def_nameservers[i]; i++)
944 return ARES_SUCCESS; /* use localhost DNS server */
947 servers = calloc(i, sizeof(struct server_state));
951 for (i = 0; def_nameservers[i]; i++)
953 servers[i].addr.addrV4.s_addr = htonl(def_nameservers[i]);
954 servers[i].addr.family = AF_INET;
958 #elif defined(ANDROID) || defined(__ANDROID__)
960 char propname[PROP_NAME_MAX];
961 char propvalue[PROP_VALUE_MAX]="";
963 for (i = 1; i <= MAX_DNS_PROPERTIES; i++) {
964 snprintf(propname, sizeof(propname), "%s%u", DNS_PROP_NAME_PREFIX, i);
965 if (__system_property_get(propname, propvalue) < 1) {
969 status = config_nameserver(&servers, &nservers, propvalue);
970 if (status != ARES_SUCCESS)
981 /* Don't read resolv.conf and friends if we don't have to */
982 if (ARES_CONFIG_CHECK(channel))
985 fp = fopen(PATH_RESOLV_CONF, "r");
987 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
989 if ((p = try_config(line, "domain", ';')))
990 status = config_domain(channel, p);
991 else if ((p = try_config(line, "lookup", ';')) && !channel->lookups)
992 status = config_lookup(channel, p, "bind", "file");
993 else if ((p = try_config(line, "search", ';')))
994 status = set_search(channel, p);
995 else if ((p = try_config(line, "nameserver", ';')) &&
996 channel->nservers == -1)
997 status = config_nameserver(&servers, &nservers, p);
998 else if ((p = try_config(line, "sortlist", ';')) &&
999 channel->nsort == -1)
1000 status = config_sortlist(&sortlist, &nsort, p);
1001 else if ((p = try_config(line, "options", ';')))
1002 status = set_options(channel, p);
1004 status = ARES_SUCCESS;
1005 if (status != ARES_SUCCESS)
1018 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
1019 error, strerror(error)));
1020 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
1021 status = ARES_EFILE;
1025 if ((status == ARES_EOF) && (!channel->lookups)) {
1026 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
1027 fp = fopen("/etc/nsswitch.conf", "r");
1029 while ((status = ares__read_line(fp, &line, &linesize)) ==
1032 if ((p = try_config(line, "hosts:", '\0')) && !channel->lookups)
1034 (void)config_lookup(channel, p, "dns", "files");
1046 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
1047 error, strerror(error)));
1048 DEBUGF(fprintf(stderr, "Error opening file: %s\n",
1049 "/etc/nsswitch.conf"));
1050 status = ARES_EFILE;
1055 if ((status == ARES_EOF) && (!channel->lookups)) {
1056 /* Linux / GNU libc 2.x and possibly others have host.conf */
1057 fp = fopen("/etc/host.conf", "r");
1059 while ((status = ares__read_line(fp, &line, &linesize)) ==
1062 if ((p = try_config(line, "order", '\0')) && !channel->lookups)
1064 (void)config_lookup(channel, p, "bind", "hosts");
1076 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
1077 error, strerror(error)));
1078 DEBUGF(fprintf(stderr, "Error opening file: %s\n",
1080 status = ARES_EFILE;
1085 if ((status == ARES_EOF) && (!channel->lookups)) {
1086 /* Tru64 uses /etc/svc.conf */
1087 fp = fopen("/etc/svc.conf", "r");
1089 while ((status = ares__read_line(fp, &line, &linesize)) ==
1092 if ((p = try_config(line, "hosts=", '\0')) && !channel->lookups)
1094 (void)config_lookup(channel, p, "bind", "local");
1106 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
1107 error, strerror(error)));
1108 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
1109 status = ARES_EFILE;
1120 /* Handle errors. */
1121 if (status != ARES_EOF)
1123 if (servers != NULL)
1125 if (sortlist != NULL)
1130 /* If we got any name server entries, fill them in. */
1136 channel->servers = servers;
1137 channel->nservers = nservers;
1140 /* If we got any sortlist entries, fill them in. */
1143 channel->sortlist = sortlist;
1144 channel->nsort = nsort;
1147 return ARES_SUCCESS;
1150 static int init_by_defaults(ares_channel channel)
1152 char *hostname = NULL;
1153 int rc = ARES_SUCCESS;
1154 #ifdef HAVE_GETHOSTNAME
1158 if (channel->flags == -1)
1160 if (channel->timeout == -1)
1161 channel->timeout = DEFAULT_TIMEOUT;
1162 if (channel->tries == -1)
1163 channel->tries = DEFAULT_TRIES;
1164 if (channel->ndots == -1)
1166 if (channel->rotate == -1)
1167 channel->rotate = 0;
1168 if (channel->udp_port == -1)
1169 channel->udp_port = htons(NAMESERVER_PORT);
1170 if (channel->tcp_port == -1)
1171 channel->tcp_port = htons(NAMESERVER_PORT);
1173 if (channel->nservers == -1) {
1174 /* If nobody specified servers, try a local named. */
1175 channel->servers = malloc(sizeof(struct server_state));
1176 if (!channel->servers) {
1180 channel->servers[0].addr.family = AF_INET;
1181 channel->servers[0].addr.addrV4.s_addr = htonl(INADDR_LOOPBACK);
1182 channel->nservers = 1;
1185 #if defined(USE_WINSOCK)
1186 #define toolong(x) (x == -1) && (SOCKERRNO == WSAEFAULT)
1187 #elif defined(ENAMETOOLONG)
1188 #define toolong(x) (x == -1) && ((SOCKERRNO == ENAMETOOLONG) || \
1189 (SOCKERRNO == EINVAL))
1191 #define toolong(x) (x == -1) && (SOCKERRNO == EINVAL)
1194 if (channel->ndomains == -1) {
1195 /* Derive a default domain search list from the kernel hostname,
1196 * or set it to empty if the hostname isn't helpful.
1198 #ifndef HAVE_GETHOSTNAME
1199 channel->ndomains = 0; /* default to none */
1201 GETHOSTNAME_TYPE_ARG2 lenv = 64;
1204 channel->ndomains = 0; /* default to none */
1206 hostname = malloc(len);
1213 res = gethostname(hostname, lenv);
1219 p = realloc(hostname, len);
1234 dot = strchr(hostname, '.');
1236 /* a dot was found */
1237 channel->domains = malloc(sizeof(char *));
1238 if (!channel->domains) {
1242 channel->domains[0] = strdup(dot + 1);
1243 if (!channel->domains[0]) {
1247 channel->ndomains = 1;
1252 if (channel->nsort == -1) {
1253 channel->sortlist = NULL;
1257 if (!channel->lookups) {
1258 channel->lookups = strdup("fb");
1259 if (!channel->lookups)
1265 if(channel->servers) {
1266 free(channel->servers);
1267 channel->servers = NULL;
1270 if(channel->domains && channel->domains[0])
1271 free(channel->domains[0]);
1272 if(channel->domains) {
1273 free(channel->domains);
1274 channel->domains = NULL;
1277 if(channel->lookups) {
1278 free(channel->lookups);
1279 channel->lookups = NULL;
1289 #if !defined(WIN32) && !defined(WATT32) && \
1290 !defined(ANDROID) && !defined(__ANDROID__)
1291 static int config_domain(ares_channel channel, char *str)
1295 /* Set a single search domain. */
1297 while (*q && !ISSPACE(*q))
1300 return set_search(channel, str);
1303 #if defined(__INTEL_COMPILER) && (__INTEL_COMPILER == 910) && \
1304 defined(__OPTIMIZE__) && defined(__unix__) && defined(__i386__)
1305 /* workaround icc 9.1 optimizer issue */
1306 # define vqualifier volatile
1311 static int config_lookup(ares_channel channel, const char *str,
1312 const char *bindch, const char *filech)
1314 char lookups[3], *l;
1315 const char *vqualifier p;
1317 /* Set the lookup order. Only the first letter of each work
1318 * is relevant, and it has to be "b" for DNS or "f" for the
1319 * host file. Ignore everything else.
1325 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
1326 if (*p == *bindch) *l++ = 'b';
1329 while (*p && !ISSPACE(*p) && (*p != ','))
1331 while (*p && (ISSPACE(*p) || (*p == ',')))
1335 channel->lookups = strdup(lookups);
1336 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1338 #endif /* !WIN32 & !WATT32 & !ANDROID & !__ANDROID__ */
1341 static int config_nameserver(struct server_state **servers, int *nservers,
1344 struct ares_addr host;
1345 struct server_state *newserv;
1347 /* On Windows, there may be more than one nameserver specified in the same
1348 * registry key, so we parse input as a space or comma seperated list.
1352 /* Skip whitespace and commas. */
1353 while (*p && (ISSPACE(*p) || (*p == ',')))
1356 /* No more input, done. */
1359 /* Pointer to start of IPv4 or IPv6 address part. */
1362 /* Advance past this address. */
1363 while (*p && !ISSPACE(*p) && (*p != ','))
1366 /* Null terminate this address. */
1369 /* Reached end of input, done when this address is processed. */
1372 /* Convert textual address to binary format. */
1373 if (ares_inet_pton(AF_INET, txtaddr, &host.addrV4) == 1)
1374 host.family = AF_INET;
1375 else if (ares_inet_pton(AF_INET6, txtaddr, &host.addrV6) == 1)
1376 host.family = AF_INET6;
1380 /* Resize servers state array. */
1381 newserv = realloc(*servers, (*nservers + 1) *
1382 sizeof(struct server_state));
1386 /* Store address data. */
1387 newserv[*nservers].addr.family = host.family;
1388 if (host.family == AF_INET)
1389 memcpy(&newserv[*nservers].addr.addrV4, &host.addrV4,
1390 sizeof(host.addrV4));
1392 memcpy(&newserv[*nservers].addr.addrV6, &host.addrV6,
1393 sizeof(host.addrV6));
1395 /* Update arguments. */
1400 return ARES_SUCCESS;
1403 #if !defined(WIN32) && !defined(ANDROID) && !defined(__ANDROID__)
1404 static int config_sortlist(struct apattern **sortlist, int *nsort,
1407 struct apattern pat;
1410 /* Add sortlist entries. */
1411 while (*str && *str != ';')
1414 char ipbuf[16], ipbufpfx[32];
1415 /* Find just the IP */
1417 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1419 memcpy(ipbuf, str, q-str);
1420 ipbuf[q-str] = '\0';
1421 /* Find the prefix */
1424 const char *str2 = q+1;
1425 while (*q && *q != ';' && !ISSPACE(*q))
1427 memcpy(ipbufpfx, str, q-str);
1428 ipbufpfx[q-str] = '\0';
1433 /* Lets see if it is CIDR */
1434 /* First we'll try IPv6 */
1435 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1437 sizeof(pat.addrV6))) > 0)
1439 pat.type = PATTERN_CIDR;
1440 pat.mask.bits = (unsigned short)bits;
1441 pat.family = AF_INET6;
1442 if (!sortlist_alloc(sortlist, nsort, &pat))
1445 else if (ipbufpfx[0] &&
1446 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addrV4,
1447 sizeof(pat.addrV4))) > 0)
1449 pat.type = PATTERN_CIDR;
1450 pat.mask.bits = (unsigned short)bits;
1451 pat.family = AF_INET;
1452 if (!sortlist_alloc(sortlist, nsort, &pat))
1455 /* See if it is just a regular IP */
1456 else if (ip_addr(ipbuf, q-str, &pat.addrV4) == 0)
1460 memcpy(ipbuf, str, q-str);
1461 ipbuf[q-str] = '\0';
1462 if (ip_addr(ipbuf, q-str, &pat.mask.addr4) != 0)
1467 pat.family = AF_INET;
1468 pat.type = PATTERN_MASK;
1469 if (!sortlist_alloc(sortlist, nsort, &pat))
1474 while (*q && *q != ';' && !ISSPACE(*q))
1478 while (ISSPACE(*str))
1482 return ARES_SUCCESS;
1484 #endif /* !WIN32 & !ANDROID & !__ANDROID__ */
1485 #endif /* !WATT32 */
1487 static int set_search(ares_channel channel, const char *str)
1492 if(channel->ndomains != -1) {
1493 /* if we already have some domains present, free them first */
1494 for(n=0; n < channel->ndomains; n++)
1495 free(channel->domains[n]);
1496 free(channel->domains);
1497 channel->domains = NULL;
1498 channel->ndomains = -1;
1501 /* Count the domains given. */
1506 while (*p && !ISSPACE(*p))
1515 channel->ndomains = 0;
1516 return ARES_SUCCESS;
1519 channel->domains = malloc(n * sizeof(char *));
1520 if (!channel->domains)
1523 /* Now copy the domains. */
1528 channel->ndomains = n;
1530 while (*q && !ISSPACE(*q))
1532 channel->domains[n] = malloc(q - p + 1);
1533 if (!channel->domains[n])
1535 memcpy(channel->domains[n], p, q - p);
1536 channel->domains[n][q - p] = 0;
1542 channel->ndomains = n;
1544 return ARES_SUCCESS;
1547 static int set_options(ares_channel channel, const char *str)
1549 const char *p, *q, *val;
1555 while (*q && !ISSPACE(*q))
1557 val = try_option(p, q, "ndots:");
1558 if (val && channel->ndots == -1)
1559 channel->ndots = aresx_sltosi(strtol(val, NULL, 10));
1560 val = try_option(p, q, "retrans:");
1561 if (val && channel->timeout == -1)
1562 channel->timeout = aresx_sltosi(strtol(val, NULL, 10));
1563 val = try_option(p, q, "retry:");
1564 if (val && channel->tries == -1)
1565 channel->tries = aresx_sltosi(strtol(val, NULL, 10));
1566 val = try_option(p, q, "rotate");
1567 if (val && channel->rotate == -1)
1568 channel->rotate = 1;
1574 return ARES_SUCCESS;
1577 static const char *try_option(const char *p, const char *q, const char *opt)
1579 size_t len = strlen(opt);
1580 return ((size_t)(q - p) >= len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1583 #if !defined(WIN32) && !defined(WATT32) && \
1584 !defined(ANDROID) && !defined(__ANDROID__)
1585 static char *try_config(char *s, const char *opt, char scc)
1592 /* no line or no option */
1595 /* Hash '#' character is always used as primary comment char, additionally
1596 a not-NUL secondary comment char will be considered when specified. */
1598 /* trim line comment */
1601 while (*p && (*p != '#') && (*p != scc))
1604 while (*p && (*p != '#'))
1608 /* trim trailing whitespace */
1610 while ((q >= s) && ISSPACE(*q))
1614 /* skip leading whitespace */
1616 while (*p && ISSPACE(*p))
1623 if ((len = strlen(opt)) == 0)
1627 if (strncmp(p, opt, len) != 0)
1628 /* line and option do not match */
1631 /* skip over given option name */
1635 /* no option value */
1638 if ((opt[len-1] != ':') && (opt[len-1] != '=') && !ISSPACE(*p))
1639 /* whitespace between option name and value is mandatory
1640 for given option names which do not end with ':' or '=' */
1643 /* skip over whitespace */
1644 while (*p && ISSPACE(*p))
1648 /* no option value */
1651 /* return pointer to option value */
1655 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1656 struct apattern *pat)
1658 struct apattern *newsort;
1659 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1662 newsort[*nsort] = *pat;
1663 *sortlist = newsort;
1668 static int ip_addr(const char *ipbuf, ssize_t len, struct in_addr *addr)
1671 /* Four octets and three periods yields at most 15 characters. */
1675 addr->s_addr = inet_addr(ipbuf);
1676 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1681 static void natural_mask(struct apattern *pat)
1683 struct in_addr addr;
1685 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1688 addr.s_addr = ntohl(pat->addrV4.s_addr);
1690 /* This is out of date in the CIDR world, but some people might
1693 if (IN_CLASSA(addr.s_addr))
1694 pat->mask.addr4.s_addr = htonl(IN_CLASSA_NET);
1695 else if (IN_CLASSB(addr.s_addr))
1696 pat->mask.addr4.s_addr = htonl(IN_CLASSB_NET);
1698 pat->mask.addr4.s_addr = htonl(IN_CLASSC_NET);
1700 #endif /* !WIN32 & !WATT32 & !ANDROID & !__ANDROID__ */
1702 /* initialize an rc4 key. If possible a cryptographically secure random key
1703 is generated using a suitable function (for example win32's RtlGenRandom as
1705 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1706 otherwise the code defaults to cross-platform albeit less secure mechanism
1709 static void randomize_key(unsigned char* key,int key_data_len)
1715 if (ares_fpSystemFunction036)
1717 res = (*ares_fpSystemFunction036) (key, key_data_len);
1723 FILE *f = fopen(RANDOM_FILE, "rb");
1725 counter = aresx_uztosi(fread(key, 1, key_data_len, f));
1732 for (;counter<key_data_len;counter++)
1733 key[counter]=(unsigned char)(rand() % 256);
1737 static int init_id_key(rc4_key* key,int key_data_len)
1739 unsigned char index1;
1740 unsigned char index2;
1741 unsigned char* state;
1743 unsigned char *key_data_ptr = 0;
1745 key_data_ptr = calloc(1,key_data_len);
1749 state = &key->state[0];
1750 for(counter = 0; counter < 256; counter++)
1751 /* unnecessary AND but it keeps some compilers happier */
1752 state[counter] = (unsigned char)(counter & 0xff);
1753 randomize_key(key->state,key_data_len);
1758 for(counter = 0; counter < 256; counter++)
1760 index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1762 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1764 index1 = (unsigned char)((index1 + 1) % key_data_len);
1767 return ARES_SUCCESS;
1770 unsigned short ares__generate_new_id(rc4_key* key)
1773 ares__rc4(key, (unsigned char *)&r, sizeof(r));
1777 void ares_set_local_ip4(ares_channel channel, unsigned int local_ip)
1779 channel->local_ip4 = local_ip;
1782 /* local_ip6 should be 16 bytes in length */
1783 void ares_set_local_ip6(ares_channel channel,
1784 const unsigned char* local_ip6)
1786 memcpy(&channel->local_ip6, local_ip6, sizeof(channel->local_ip6));
1789 /* local_dev_name should be null terminated. */
1790 void ares_set_local_dev(ares_channel channel,
1791 const char* local_dev_name)
1793 strncpy(channel->local_dev_name, local_dev_name,
1794 sizeof(channel->local_dev_name));
1795 channel->local_dev_name[sizeof(channel->local_dev_name) - 1] = 0;
1799 void ares_set_socket_callback(ares_channel channel,
1800 ares_sock_create_callback cb,
1803 channel->sock_create_cb = cb;
1804 channel->sock_create_cb_data = data;
1807 void ares__init_servers_state(ares_channel channel)
1809 struct server_state *server;
1812 for (i = 0; i < channel->nservers; i++)
1814 server = &channel->servers[i];
1815 server->udp_socket = ARES_SOCKET_BAD;
1816 server->tcp_socket = ARES_SOCKET_BAD;
1817 server->tcp_connection_generation = ++channel->tcp_connection_generation;
1818 server->tcp_lenbuf_pos = 0;
1819 server->tcp_buffer_pos = 0;
1820 server->tcp_buffer = NULL;
1821 server->tcp_length = 0;
1822 server->qhead = NULL;
1823 server->qtail = NULL;
1824 ares__init_list_head(&server->queries_to_server);
1825 server->channel = channel;
1826 server->is_broken = 0;