2 /* Copyright 1998 by the Massachusetts Institute of Technology.
3 * Copyright (C) 2007-2010 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_private.h"
73 #include <sys/system_properties.h>
77 #undef WIN32 /* Redefined in MingW/MSVC headers */
80 static int init_by_options(ares_channel channel, const struct ares_options *options,
82 static int init_by_environment(ares_channel channel);
83 static int init_by_resolv_conf(ares_channel channel);
84 static int init_by_defaults(ares_channel channel);
87 static int config_nameserver(struct server_state **servers, int *nservers,
90 static int set_search(ares_channel channel, const char *str);
91 static int set_options(ares_channel channel, const char *str);
92 static const char *try_option(const char *p, const char *q, const char *opt);
93 static int init_id_key(rc4_key* key,int key_data_len);
95 #if !defined(WIN32) && !defined(WATT32)
96 static int sortlist_alloc(struct apattern **sortlist, int *nsort, struct apattern *pat);
97 static int ip_addr(const char *s, int len, struct in_addr *addr);
98 static void natural_mask(struct apattern *pat);
99 static int config_domain(ares_channel channel, char *str);
100 static int config_lookup(ares_channel channel, const char *str,
101 const char *bindch, const char *filech);
102 static int config_sortlist(struct apattern **sortlist, int *nsort,
104 static char *try_config(char *s, const char *opt);
107 #define ARES_CONFIG_CHECK(x) (x->lookups && x->nsort > -1 && \
108 x->nservers > -1 && \
109 x->ndomains > -1 && \
110 x->ndots > -1 && x->timeout > -1 && \
113 int ares_init(ares_channel *channelptr)
115 return ares_init_options(channelptr, NULL, 0);
118 int ares_init_options(ares_channel *channelptr, struct ares_options *options,
121 ares_channel channel;
123 int status = ARES_SUCCESS;
127 const char *env = getenv("CARES_MEMDEBUG");
131 env = getenv("CARES_MEMLIMIT");
133 curl_memlimit(atoi(env));
136 if (ares_library_initialized() != ARES_SUCCESS)
137 return ARES_ENOTINITIALIZED;
139 channel = malloc(sizeof(struct ares_channeldata));
147 /* Set everything to distinguished values so we know they haven't
151 channel->timeout = -1;
154 channel->rotate = -1;
155 channel->udp_port = -1;
156 channel->tcp_port = -1;
157 channel->socket_send_buffer_size = -1;
158 channel->socket_receive_buffer_size = -1;
159 channel->nservers = -1;
160 channel->ndomains = -1;
162 channel->tcp_connection_generation = 0;
163 channel->lookups = NULL;
164 channel->domains = NULL;
165 channel->sortlist = NULL;
166 channel->servers = NULL;
167 channel->sock_state_cb = NULL;
168 channel->sock_state_cb_data = NULL;
169 channel->sock_create_cb = NULL;
170 channel->sock_create_cb_data = NULL;
172 channel->last_server = 0;
173 channel->last_timeout_processed = (time_t)now.tv_sec;
175 memset(&channel->local_dev_name, 0, sizeof(channel->local_dev_name));
176 channel->local_ip4 = 0;
177 memset(&channel->local_ip6, 0, sizeof(channel->local_ip6));
179 /* Initialize our lists of queries */
180 ares__init_list_head(&(channel->all_queries));
181 for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
183 ares__init_list_head(&(channel->queries_by_qid[i]));
185 for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
187 ares__init_list_head(&(channel->queries_by_timeout[i]));
190 /* Initialize configuration by each of the four sources, from highest
191 * precedence to lowest.
194 if (status == ARES_SUCCESS) {
195 status = init_by_options(channel, options, optmask);
196 if (status != ARES_SUCCESS)
197 DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
198 ares_strerror(status)));
200 if (status == ARES_SUCCESS) {
201 status = init_by_environment(channel);
202 if (status != ARES_SUCCESS)
203 DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
204 ares_strerror(status)));
206 if (status == ARES_SUCCESS) {
207 status = init_by_resolv_conf(channel);
208 if (status != ARES_SUCCESS)
209 DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
210 ares_strerror(status)));
214 * No matter what failed or succeeded, seed defaults to provide
215 * useful behavior for things that we missed.
217 status = init_by_defaults(channel);
218 if (status != ARES_SUCCESS)
219 DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
220 ares_strerror(status)));
222 /* Generate random key */
224 if (status == ARES_SUCCESS) {
225 status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
226 if (status == ARES_SUCCESS)
227 channel->next_id = ares__generate_new_id(&channel->id_key);
229 DEBUGF(fprintf(stderr, "Error: init_id_key failed: %s\n",
230 ares_strerror(status)));
233 if (status != ARES_SUCCESS)
235 /* Something failed; clean up memory we may have allocated. */
236 if (channel->servers)
237 free(channel->servers);
238 if (channel->domains)
240 for (i = 0; i < channel->ndomains; i++)
241 free(channel->domains[i]);
242 free(channel->domains);
244 if (channel->sortlist)
245 free(channel->sortlist);
247 free(channel->lookups);
252 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
253 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
254 channel->nservers = 1;
256 ares__init_servers_state(channel);
258 *channelptr = channel;
262 /* ares_dup() duplicates a channel handle with all its options and returns a
263 new channel handle */
264 int ares_dup(ares_channel *dest, ares_channel src)
266 struct ares_options opts;
267 struct ares_addr_node *servers;
268 int ipv6_nservers = 0;
272 *dest = NULL; /* in case of failure return NULL explicitly */
274 /* First get the options supported by the old ares_save_options() function,
275 which is most of them */
276 rc = ares_save_options(src, &opts, &optmask);
280 /* Then create the new channel with those options */
281 rc = ares_init_options(dest, &opts, optmask);
283 /* destroy the options copy to not leak any memory */
284 ares_destroy_options(&opts);
289 /* Now clone the options that ares_save_options() doesn't support. */
290 (*dest)->sock_create_cb = src->sock_create_cb;
291 (*dest)->sock_create_cb_data = src->sock_create_cb_data;
293 strncpy((*dest)->local_dev_name, src->local_dev_name, sizeof(src->local_dev_name));
294 (*dest)->local_ip4 = src->local_ip4;
295 memcpy((*dest)->local_ip6, src->local_ip6, sizeof(src->local_ip6));
297 /* Full name server cloning required when not all are IPv4 */
298 for (i = 0; i < src->nservers; i++)
300 if (src->servers[i].addr.family != AF_INET) {
306 rc = ares_get_servers(src, &servers);
307 if (rc != ARES_SUCCESS)
309 rc = ares_set_servers(*dest, servers);
310 ares_free_data(servers);
311 if (rc != ARES_SUCCESS)
315 return ARES_SUCCESS; /* everything went fine */
318 /* Save options from initialized channel */
319 int ares_save_options(ares_channel channel, struct ares_options *options,
323 int ipv4_nservers = 0;
325 /* Zero everything out */
326 memset(options, 0, sizeof(struct ares_options));
328 if (!ARES_CONFIG_CHECK(channel))
331 /* Traditionally the optmask wasn't saved in the channel struct so it was
332 recreated here. ROTATE is the first option that has no struct field of
333 its own in the public config struct */
334 (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TRIES|ARES_OPT_NDOTS|
335 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
336 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
337 ARES_OPT_SORTLIST|ARES_OPT_TIMEOUTMS) |
338 (channel->optmask & ARES_OPT_ROTATE);
340 /* Copy easy stuff */
341 options->flags = channel->flags;
343 /* We return full millisecond resolution but that's only because we don't
344 set the ARES_OPT_TIMEOUT anymore, only the new ARES_OPT_TIMEOUTMS */
345 options->timeout = channel->timeout;
346 options->tries = channel->tries;
347 options->ndots = channel->ndots;
348 options->udp_port = (unsigned short)channel->udp_port;
349 options->tcp_port = (unsigned short)channel->tcp_port;
350 options->sock_state_cb = channel->sock_state_cb;
351 options->sock_state_cb_data = channel->sock_state_cb_data;
353 /* Copy IPv4 servers */
354 if (channel->nservers) {
355 for (i = 0; i < channel->nservers; i++)
357 if (channel->servers[i].addr.family == AF_INET)
361 options->servers = malloc(ipv4_nservers * sizeof(struct server_state));
362 if (!options->servers)
364 for (i = j = 0; i < channel->nservers; i++)
366 if (channel->servers[i].addr.family == AF_INET)
367 memcpy(&options->servers[j++],
368 &channel->servers[i].addr.addrV4,
369 sizeof(channel->servers[i].addr.addrV4));
373 options->nservers = ipv4_nservers;
376 if (channel->ndomains) {
377 options->domains = malloc(channel->ndomains * sizeof(char *));
378 if (!options->domains)
381 for (i = 0; i < channel->ndomains; i++)
383 options->ndomains = i;
384 options->domains[i] = strdup(channel->domains[i]);
385 if (!options->domains[i])
389 options->ndomains = channel->ndomains;
392 if (channel->lookups) {
393 options->lookups = strdup(channel->lookups);
394 if (!options->lookups && channel->lookups)
399 if (channel->nsort) {
400 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
401 if (!options->sortlist)
403 for (i = 0; i < channel->nsort; i++)
405 memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
406 sizeof(struct apattern));
409 options->nsort = channel->nsort;
414 static int init_by_options(ares_channel channel,
415 const struct ares_options *options,
421 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
422 channel->flags = options->flags;
423 if ((optmask & ARES_OPT_TIMEOUTMS) && channel->timeout == -1)
424 channel->timeout = options->timeout;
425 else if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
426 channel->timeout = options->timeout * 1000;
427 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
428 channel->tries = options->tries;
429 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
430 channel->ndots = options->ndots;
431 if ((optmask & ARES_OPT_ROTATE) && channel->rotate == -1)
433 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
434 channel->udp_port = options->udp_port;
435 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
436 channel->tcp_port = options->tcp_port;
437 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
439 channel->sock_state_cb = options->sock_state_cb;
440 channel->sock_state_cb_data = options->sock_state_cb_data;
442 if ((optmask & ARES_OPT_SOCK_SNDBUF)
443 && channel->socket_send_buffer_size == -1)
444 channel->socket_send_buffer_size = options->socket_send_buffer_size;
445 if ((optmask & ARES_OPT_SOCK_RCVBUF)
446 && channel->socket_receive_buffer_size == -1)
447 channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
449 /* Copy the IPv4 servers, if given. */
450 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
452 /* Avoid zero size allocations at any cost */
453 if (options->nservers > 0)
456 malloc(options->nservers * sizeof(struct server_state));
457 if (!channel->servers)
459 for (i = 0; i < options->nservers; i++)
461 channel->servers[i].addr.family = AF_INET;
462 memcpy(&channel->servers[i].addr.addrV4,
463 &options->servers[i],
464 sizeof(channel->servers[i].addr.addrV4));
467 channel->nservers = options->nservers;
470 /* Copy the domains, if given. Keep channel->ndomains consistent so
471 * we can clean up in case of error.
473 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
475 /* Avoid zero size allocations at any cost */
476 if (options->ndomains > 0)
478 channel->domains = malloc(options->ndomains * sizeof(char *));
479 if (!channel->domains)
481 for (i = 0; i < options->ndomains; i++)
483 channel->ndomains = i;
484 channel->domains[i] = strdup(options->domains[i]);
485 if (!channel->domains[i])
489 channel->ndomains = options->ndomains;
492 /* Set lookups, if given. */
493 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
495 channel->lookups = strdup(options->lookups);
496 if (!channel->lookups)
501 if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
503 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
504 if (!channel->sortlist)
506 for (i = 0; i < options->nsort; i++)
508 memcpy(&(channel->sortlist[i]), &(options->sortlist[i]),
509 sizeof(struct apattern));
511 channel->nsort = options->nsort;
514 channel->optmask = optmask;
519 static int init_by_environment(ares_channel channel)
521 const char *localdomain, *res_options;
524 localdomain = getenv("LOCALDOMAIN");
525 if (localdomain && channel->ndomains == -1)
527 status = set_search(channel, localdomain);
528 if (status != ARES_SUCCESS)
532 res_options = getenv("RES_OPTIONS");
535 status = set_options(channel, res_options);
536 if (status != ARES_SUCCESS)
545 * Warning: returns a dynamically allocated buffer, the user MUST
546 * use free() if the function returns 1
548 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
550 /* Test for the size we need */
554 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
555 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
557 *obuf = malloc(size+1);
561 if (RegQueryValueEx(hKey, subkey, 0, NULL,
562 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
575 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
577 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
578 DWORD enum_size = 39;
582 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
583 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
588 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
591 rc = get_res_nt(hVal, subkey, obuf);
599 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
601 FIXED_INFO *fi, *newfi;
602 DWORD size = sizeof (*fi);
603 IP_ADDR_STRING *ipAddr;
606 size_t ip_size = sizeof("255.255.255.255,")-1;
607 size_t left = ret_size;
615 res = (*ares_fpGetNetworkParams) (fi, &size);
616 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
619 newfi = realloc(fi, size);
624 res = (*ares_fpGetNetworkParams) (fi, &size);
625 if (res != ERROR_SUCCESS)
630 printf ("Host Name: %s\n", fi->HostName);
631 printf ("Domain Name: %s\n", fi->DomainName);
632 printf ("DNS Servers:\n"
633 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
635 if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
636 inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
639 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
640 left -= ret - ret_buf;
644 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
645 ipAddr = ipAddr->Next, i++)
647 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
649 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
650 left -= ret - ret_buf;
654 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
661 if (debug && left <= ip_size)
662 printf ("Too many nameservers. Truncating to %d addressess", count);
669 static int init_by_resolv_conf(ares_channel channel)
674 int status = -1, nservers = 0, nsort = 0;
675 struct server_state *servers = NULL;
676 struct apattern *sortlist = NULL;
681 NameServer info via IPHLPAPI (IP helper API):
682 GetNetworkParams() should be the trusted source for this.
683 Available in Win-98/2000 and later. If that fail, fall-back to
684 registry information.
688 On Windows 9X, the DNS server can be found in:
689 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
691 On Windows NT/2000/XP/2003:
692 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
694 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
696 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
699 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
710 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
713 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
715 status = config_nameserver(&servers, &nservers, buf);
716 if (status == ARES_SUCCESS)
723 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
727 RegOpenKeyEx(mykey, "Interfaces", 0,
728 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
729 if (get_res_nt(mykey, NAMESERVER, &line))
731 status = config_nameserver(&servers, &nservers, line);
734 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
736 status = config_nameserver(&servers, &nservers, line);
739 /* Try the interfaces */
740 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
742 status = config_nameserver(&servers, &nservers, line);
745 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
747 status = config_nameserver(&servers, &nservers, line);
757 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
761 if ((result = RegQueryValueEx(
762 mykey, NAMESERVER, NULL, &data_type,
765 ) == ERROR_SUCCESS ||
766 result == ERROR_MORE_DATA)
770 line = malloc(bytes+1);
771 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
772 (unsigned char *)line, &bytes) ==
775 status = config_nameserver(&servers, &nservers, line);
784 if (status == ARES_SUCCESS)
787 /* Catch the case when all the above checks fail (which happens when there
788 is no network card or the cable is unplugged) */
791 #elif defined(__riscos__)
793 /* Under RISC OS, name servers are listed in the
794 system variable Inet$Resolvers, space separated. */
796 line = getenv("Inet$Resolvers");
799 char *resolvers = strdup(line), *pos, *space;
806 space = strchr(pos, ' ');
809 status = config_nameserver(&servers, &nservers, pos);
810 if (status != ARES_SUCCESS)
815 if (status == ARES_SUCCESS)
821 #elif defined(WATT32)
825 for (i = 0; def_nameservers[i]; i++)
828 return ARES_SUCCESS; /* use localhost DNS server */
831 servers = calloc(i, sizeof(struct server_state));
835 for (i = 0; def_nameservers[i]; i++)
836 servers[i].addr.addrV4.s_addr = htonl(def_nameservers[i]);
839 #elif defined(ANDROID)
840 char value[PROP_VALUE_MAX]="";
841 __system_property_get("net.dns1", value);
842 status = config_nameserver(&servers, &nservers, value);
843 if (status == ARES_SUCCESS)
852 /* Don't read resolv.conf and friends if we don't have to */
853 if (ARES_CONFIG_CHECK(channel))
856 fp = fopen(PATH_RESOLV_CONF, "r");
858 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
860 if ((p = try_config(line, "domain")))
861 status = config_domain(channel, p);
862 else if ((p = try_config(line, "lookup")) && !channel->lookups)
863 status = config_lookup(channel, p, "bind", "file");
864 else if ((p = try_config(line, "search")))
865 status = set_search(channel, p);
866 else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
867 status = config_nameserver(&servers, &nservers, p);
868 else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
869 status = config_sortlist(&sortlist, &nsort, p);
870 else if ((p = try_config(line, "options")))
871 status = set_options(channel, p);
873 status = ARES_SUCCESS;
874 if (status != ARES_SUCCESS)
887 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
888 error, strerror(error)));
889 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
894 if ((status == ARES_EOF) && (!channel->lookups)) {
895 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
896 fp = fopen("/etc/nsswitch.conf", "r");
898 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
900 if ((p = try_config(line, "hosts:")) && !channel->lookups)
901 status = config_lookup(channel, p, "dns", "files");
913 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
914 error, strerror(error)));
915 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
921 if ((status == ARES_EOF) && (!channel->lookups)) {
922 /* Linux / GNU libc 2.x and possibly others have host.conf */
923 fp = fopen("/etc/host.conf", "r");
925 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
927 if ((p = try_config(line, "order")) && !channel->lookups)
928 status = config_lookup(channel, p, "bind", "hosts");
940 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
941 error, strerror(error)));
942 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
948 if ((status == ARES_EOF) && (!channel->lookups)) {
949 /* Tru64 uses /etc/svc.conf */
950 fp = fopen("/etc/svc.conf", "r");
952 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
954 if ((p = try_config(line, "hosts=")) && !channel->lookups)
955 status = config_lookup(channel, p, "bind", "local");
967 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
968 error, strerror(error)));
969 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
982 if (status != ARES_EOF)
986 if (sortlist != NULL)
991 /* If we got any name server entries, fill them in. */
997 channel->servers = servers;
998 channel->nservers = nservers;
1001 /* If we got any sortlist entries, fill them in. */
1004 channel->sortlist = sortlist;
1005 channel->nsort = nsort;
1008 return ARES_SUCCESS;
1011 static int init_by_defaults(ares_channel channel)
1013 char *hostname = NULL;
1014 int rc = ARES_SUCCESS;
1015 #ifdef HAVE_GETHOSTNAME
1019 if (channel->flags == -1)
1021 if (channel->timeout == -1)
1022 channel->timeout = DEFAULT_TIMEOUT;
1023 if (channel->tries == -1)
1024 channel->tries = DEFAULT_TRIES;
1025 if (channel->ndots == -1)
1027 if (channel->rotate == -1)
1028 channel->rotate = 0;
1029 if (channel->udp_port == -1)
1030 channel->udp_port = htons(NAMESERVER_PORT);
1031 if (channel->tcp_port == -1)
1032 channel->tcp_port = htons(NAMESERVER_PORT);
1034 if (channel->nservers == -1) {
1035 /* If nobody specified servers, try a local named. */
1036 channel->servers = malloc(sizeof(struct server_state));
1037 if (!channel->servers) {
1041 channel->servers[0].addr.family = AF_INET;
1042 channel->servers[0].addr.addrV4.s_addr = htonl(INADDR_LOOPBACK);
1043 channel->nservers = 1;
1047 #define toolong(x) (x == -1) && ((ENAMETOOLONG == errno) || (EINVAL == errno))
1049 #define toolong(x) (x == -1) && (EINVAL == errno)
1052 if (channel->ndomains == -1) {
1053 /* Derive a default domain search list from the kernel hostname,
1054 * or set it to empty if the hostname isn't helpful.
1058 channel->ndomains = 0; /* default to none */
1060 #ifdef HAVE_GETHOSTNAME
1061 hostname = malloc(len);
1068 res = gethostname(hostname, len);
1073 p = realloc(hostname, len);
1088 dot = strchr(hostname, '.');
1090 /* a dot was found */
1091 channel->domains = malloc(sizeof(char *));
1092 if (!channel->domains) {
1096 channel->domains[0] = strdup(dot + 1);
1097 if (!channel->domains[0]) {
1101 channel->ndomains = 1;
1106 if (channel->nsort == -1) {
1107 channel->sortlist = NULL;
1111 if (!channel->lookups) {
1112 channel->lookups = strdup("fb");
1113 if (!channel->lookups)
1119 if(channel->servers)
1120 free(channel->servers);
1122 if(channel->domains && channel->domains[0])
1123 free(channel->domains[0]);
1124 if(channel->domains)
1125 free(channel->domains);
1126 if(channel->lookups)
1127 free(channel->lookups);
1136 #if !defined(WIN32) && !defined(WATT32)
1137 static int config_domain(ares_channel channel, char *str)
1141 /* Set a single search domain. */
1143 while (*q && !ISSPACE(*q))
1146 return set_search(channel, str);
1149 #if defined(__INTEL_COMPILER) && (__INTEL_COMPILER == 910) && \
1150 defined(__OPTIMIZE__) && defined(__unix__) && defined(__i386__)
1151 /* workaround icc 9.1 optimizer issue */
1152 # define vqualifier volatile
1157 static int config_lookup(ares_channel channel, const char *str,
1158 const char *bindch, const char *filech)
1160 char lookups[3], *l;
1161 const char *vqualifier p;
1163 /* Set the lookup order. Only the first letter of each work
1164 * is relevant, and it has to be "b" for DNS or "f" for the
1165 * host file. Ignore everything else.
1171 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
1172 if (*p == *bindch) *l++ = 'b';
1175 while (*p && !ISSPACE(*p) && (*p != ','))
1177 while (*p && (ISSPACE(*p) || (*p == ',')))
1181 channel->lookups = strdup(lookups);
1182 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1184 #endif /* !WIN32 & !WATT32 */
1187 static int config_nameserver(struct server_state **servers, int *nservers,
1190 struct ares_addr host;
1191 struct server_state *newserv;
1193 /* On Windows, there may be more than one nameserver specified in the same
1194 * registry key, so we parse input as a space or comma seperated list.
1198 /* Skip whitespace and commas. */
1199 while (*p && (ISSPACE(*p) || (*p == ',')))
1202 /* No more input, done. */
1205 /* Pointer to start of IPv4 or IPv6 address part. */
1208 /* Advance past this address. */
1209 while (*p && !ISSPACE(*p) && (*p != ','))
1212 /* Null terminate this address. */
1215 /* Reached end of input, done when this address is processed. */
1218 /* Convert textual address to binary format. */
1219 if (ares_inet_pton(AF_INET, txtaddr, &host.addrV4) == 1)
1220 host.family = AF_INET;
1221 else if (ares_inet_pton(AF_INET6, txtaddr, &host.addrV6) == 1)
1222 host.family = AF_INET6;
1226 /* Resize servers state array. */
1227 newserv = realloc(*servers, (*nservers + 1) *
1228 sizeof(struct server_state));
1232 /* Store address data. */
1233 newserv[*nservers].addr.family = host.family;
1234 if (host.family == AF_INET)
1235 memcpy(&newserv[*nservers].addr.addrV4, &host.addrV4,
1236 sizeof(host.addrV4));
1238 memcpy(&newserv[*nservers].addr.addrV6, &host.addrV6,
1239 sizeof(host.addrV6));
1241 /* Update arguments. */
1246 return ARES_SUCCESS;
1250 static int config_sortlist(struct apattern **sortlist, int *nsort,
1253 struct apattern pat;
1256 /* Add sortlist entries. */
1257 while (*str && *str != ';')
1260 char ipbuf[16], ipbufpfx[32];
1261 /* Find just the IP */
1263 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1265 memcpy(ipbuf, str, (int)(q-str));
1266 ipbuf[(int)(q-str)] = '\0';
1267 /* Find the prefix */
1270 const char *str2 = q+1;
1271 while (*q && *q != ';' && !ISSPACE(*q))
1273 memcpy(ipbufpfx, str, (int)(q-str));
1274 ipbufpfx[(int)(q-str)] = '\0';
1279 /* Lets see if it is CIDR */
1280 /* First we'll try IPv6 */
1281 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1283 sizeof(pat.addrV6))) > 0)
1285 pat.type = PATTERN_CIDR;
1286 pat.mask.bits = (unsigned short)bits;
1287 pat.family = AF_INET6;
1288 if (!sortlist_alloc(sortlist, nsort, &pat))
1292 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addrV4,
1293 sizeof(pat.addrV4))) > 0)
1295 pat.type = PATTERN_CIDR;
1296 pat.mask.bits = (unsigned short)bits;
1297 pat.family = AF_INET;
1298 if (!sortlist_alloc(sortlist, nsort, &pat))
1301 /* See if it is just a regular IP */
1302 else if (ip_addr(ipbuf, (int)(q-str), &pat.addrV4) == 0)
1306 memcpy(ipbuf, str, (int)(q-str));
1307 ipbuf[(int)(q-str)] = '\0';
1308 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr4) != 0)
1313 pat.family = AF_INET;
1314 pat.type = PATTERN_MASK;
1315 if (!sortlist_alloc(sortlist, nsort, &pat))
1320 while (*q && *q != ';' && !ISSPACE(*q))
1324 while (ISSPACE(*str))
1328 return ARES_SUCCESS;
1331 #endif /* !WATT32 */
1333 static int set_search(ares_channel channel, const char *str)
1338 if(channel->ndomains != -1) {
1339 /* if we already have some domains present, free them first */
1340 for(n=0; n < channel->ndomains; n++)
1341 free(channel->domains[n]);
1342 free(channel->domains);
1343 channel->domains = NULL;
1344 channel->ndomains = -1;
1347 /* Count the domains given. */
1352 while (*p && !ISSPACE(*p))
1361 channel->ndomains = 0;
1362 return ARES_SUCCESS;
1365 channel->domains = malloc(n * sizeof(char *));
1366 if (!channel->domains)
1369 /* Now copy the domains. */
1374 channel->ndomains = n;
1376 while (*q && !ISSPACE(*q))
1378 channel->domains[n] = malloc(q - p + 1);
1379 if (!channel->domains[n])
1381 memcpy(channel->domains[n], p, q - p);
1382 channel->domains[n][q - p] = 0;
1388 channel->ndomains = n;
1390 return ARES_SUCCESS;
1393 static int set_options(ares_channel channel, const char *str)
1395 const char *p, *q, *val;
1401 while (*q && !ISSPACE(*q))
1403 val = try_option(p, q, "ndots:");
1404 if (val && channel->ndots == -1)
1405 channel->ndots = atoi(val);
1406 val = try_option(p, q, "retrans:");
1407 if (val && channel->timeout == -1)
1408 channel->timeout = atoi(val);
1409 val = try_option(p, q, "retry:");
1410 if (val && channel->tries == -1)
1411 channel->tries = atoi(val);
1412 val = try_option(p, q, "rotate");
1413 if (val && channel->rotate == -1)
1414 channel->rotate = 1;
1420 return ARES_SUCCESS;
1423 static const char *try_option(const char *p, const char *q, const char *opt)
1425 size_t len = strlen(opt);
1426 return ((size_t)(q - p) >= len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1429 #if !defined(WIN32) && !defined(WATT32)
1430 static char *try_config(char *s, const char *opt)
1437 /* no line or no option */
1440 /* trim line comment */
1442 while (*p && (*p != '#'))
1446 /* trim trailing whitespace */
1448 while ((q >= s) && ISSPACE(*q))
1452 /* skip leading whitespace */
1454 while (*p && ISSPACE(*p))
1461 if ((len = strlen(opt)) == 0)
1465 if (strncmp(p, opt, len) != 0)
1466 /* line and option do not match */
1469 /* skip over given option name */
1473 /* no option value */
1476 if ((opt[len-1] != ':') && (opt[len-1] != '=') && !ISSPACE(*p))
1477 /* whitespace between option name and value is mandatory
1478 for given option names which do not end with ':' or '=' */
1481 /* skip over whitespace */
1482 while (*p && ISSPACE(*p))
1486 /* no option value */
1489 /* return pointer to option value */
1493 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1494 struct apattern *pat)
1496 struct apattern *newsort;
1497 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1500 newsort[*nsort] = *pat;
1501 *sortlist = newsort;
1506 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1509 /* Four octets and three periods yields at most 15 characters. */
1513 addr->s_addr = inet_addr(ipbuf);
1514 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1519 static void natural_mask(struct apattern *pat)
1521 struct in_addr addr;
1523 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1526 addr.s_addr = ntohl(pat->addrV4.s_addr);
1528 /* This is out of date in the CIDR world, but some people might
1531 if (IN_CLASSA(addr.s_addr))
1532 pat->mask.addr4.s_addr = htonl(IN_CLASSA_NET);
1533 else if (IN_CLASSB(addr.s_addr))
1534 pat->mask.addr4.s_addr = htonl(IN_CLASSB_NET);
1536 pat->mask.addr4.s_addr = htonl(IN_CLASSC_NET);
1538 #endif /* !WIN32 && !WATT32 */
1540 /* initialize an rc4 key. If possible a cryptographically secure random key
1541 is generated using a suitable function (for example win32's RtlGenRandom as
1543 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1544 otherwise the code defaults to cross-platform albeit less secure mechanism
1547 static void randomize_key(unsigned char* key,int key_data_len)
1553 if (ares_fpSystemFunction036)
1555 res = (*ares_fpSystemFunction036) (key, key_data_len);
1561 FILE *f = fopen(RANDOM_FILE, "rb");
1563 counter = fread(key, 1, key_data_len, f);
1569 if ( !randomized ) {
1570 for (;counter<key_data_len;counter++)
1571 key[counter]=(unsigned char)(rand() % 256);
1575 static int init_id_key(rc4_key* key,int key_data_len)
1577 unsigned char index1;
1578 unsigned char index2;
1579 unsigned char* state;
1581 unsigned char *key_data_ptr = 0;
1583 key_data_ptr = calloc(1,key_data_len);
1587 state = &key->state[0];
1588 for(counter = 0; counter < 256; counter++)
1589 /* unnecessary AND but it keeps some compilers happier */
1590 state[counter] = (unsigned char)(counter & 0xff);
1591 randomize_key(key->state,key_data_len);
1596 for(counter = 0; counter < 256; counter++)
1598 index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1600 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1602 index1 = (unsigned char)((index1 + 1) % key_data_len);
1605 return ARES_SUCCESS;
1608 unsigned short ares__generate_new_id(rc4_key* key)
1611 ares__rc4(key, (unsigned char *)&r, sizeof(r));
1615 void ares_set_local_ip4(ares_channel channel, uint32_t local_ip)
1617 channel->local_ip4 = local_ip;
1620 /* local_ip6 should be 16 bytes in length */
1621 void ares_set_local_ip6(ares_channel channel,
1622 const unsigned char* local_ip6)
1624 memcpy(&channel->local_ip6, local_ip6, sizeof(channel->local_ip6));
1627 /* local_dev_name should be null terminated. */
1628 void ares_set_local_dev(ares_channel channel,
1629 const char* local_dev_name)
1631 strncpy(channel->local_dev_name, local_dev_name,
1632 sizeof(channel->local_dev_name));
1633 channel->local_dev_name[sizeof(channel->local_dev_name) - 1] = 0;
1637 void ares_set_socket_callback(ares_channel channel,
1638 ares_sock_create_callback cb,
1641 channel->sock_create_cb = cb;
1642 channel->sock_create_cb_data = data;
1645 void ares__init_servers_state(ares_channel channel)
1647 struct server_state *server;
1650 for (i = 0; i < channel->nservers; i++)
1652 server = &channel->servers[i];
1653 server->udp_socket = ARES_SOCKET_BAD;
1654 server->tcp_socket = ARES_SOCKET_BAD;
1655 server->tcp_connection_generation = ++channel->tcp_connection_generation;
1656 server->tcp_lenbuf_pos = 0;
1657 server->tcp_buffer_pos = 0;
1658 server->tcp_buffer = NULL;
1659 server->tcp_length = 0;
1660 server->qhead = NULL;
1661 server->qtail = NULL;
1662 ares__init_list_head(&server->queries_to_server);
1663 server->channel = channel;
1664 server->is_broken = 0;