3 /* Copyright 1998 by the Massachusetts Institute of Technology.
4 * Copyright (C) 2007-2009 by Daniel Stenberg
6 * Permission to use, copy, modify, and distribute this
7 * software and its documentation for any purpose and without
8 * fee is hereby granted, provided that the above copyright
9 * notice appear in all copies and that both that copyright
10 * notice and this permission notice appear in supporting
11 * documentation, and that the name of M.I.T. not be used in
12 * advertising or publicity pertaining to distribution of the
13 * software without specific, written prior permission.
14 * M.I.T. makes no representations about the suitability of
15 * this software for any purpose. It is provided "as is"
16 * without express or implied warranty.
21 #if defined(WIN32) && !defined(WATT32)
25 #ifdef HAVE_SYS_PARAM_H
26 #include <sys/param.h>
29 #ifdef HAVE_SYS_TIME_H
33 #ifdef HAVE_SYS_SOCKET_H
34 #include <sys/socket.h>
37 #ifdef HAVE_NETINET_IN_H
38 #include <netinet/in.h>
45 #ifdef HAVE_ARPA_INET_H
46 #include <arpa/inet.h>
49 #ifdef HAVE_ARPA_NAMESER_H
50 # include <arpa/nameser.h>
54 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
55 # include <arpa/nameser_compat.h>
69 #include "inet_net_pton.h"
70 #include "ares_library_init.h"
71 #include "ares_private.h"
74 #undef WIN32 /* Redefined in MingW/MSVC headers */
77 static int init_by_options(ares_channel channel, const struct ares_options *options,
79 static int init_by_environment(ares_channel channel);
80 static int init_by_resolv_conf(ares_channel channel);
81 static int init_by_defaults(ares_channel channel);
83 static int config_nameserver(struct server_state **servers, int *nservers,
85 static int set_search(ares_channel channel, const char *str);
86 static int set_options(ares_channel channel, const char *str);
87 static const char *try_option(const char *p, const char *q, const char *opt);
88 static int init_id_key(rc4_key* key,int key_data_len);
91 static int sortlist_alloc(struct apattern **sortlist, int *nsort, struct apattern *pat);
92 static int ip_addr(const char *s, int len, struct in_addr *addr);
93 static void natural_mask(struct apattern *pat);
94 static int config_domain(ares_channel channel, char *str);
95 static int config_lookup(ares_channel channel, const char *str,
96 const char *bindch, const char *filech);
97 static int config_sortlist(struct apattern **sortlist, int *nsort,
99 static char *try_config(char *s, const char *opt);
102 #define ARES_CONFIG_CHECK(x) (x->lookups && x->nsort > -1 && \
103 x->nservers > -1 && \
104 x->ndomains > -1 && \
105 x->ndots > -1 && x->timeout > -1 && \
108 int ares_init(ares_channel *channelptr)
110 return ares_init_options(channelptr, NULL, 0);
113 int ares_init_options(ares_channel *channelptr, struct ares_options *options,
116 ares_channel channel;
118 int status = ARES_SUCCESS;
119 struct server_state *server;
123 const char *env = getenv("CARES_MEMDEBUG");
127 env = getenv("CARES_MEMLIMIT");
129 curl_memlimit(atoi(env));
132 if (ares_library_initialized() != ARES_SUCCESS)
133 return ARES_ENOTINITIALIZED;
135 channel = malloc(sizeof(struct ares_channeldata));
143 /* Set everything to distinguished values so we know they haven't
147 channel->timeout = -1;
150 channel->rotate = -1;
151 channel->udp_port = -1;
152 channel->tcp_port = -1;
153 channel->socket_send_buffer_size = -1;
154 channel->socket_receive_buffer_size = -1;
155 channel->nservers = -1;
156 channel->ndomains = -1;
158 channel->tcp_connection_generation = 0;
159 channel->lookups = NULL;
160 channel->domains = NULL;
161 channel->sortlist = NULL;
162 channel->servers = NULL;
163 channel->sock_state_cb = NULL;
164 channel->sock_state_cb_data = NULL;
165 channel->sock_create_cb = NULL;
166 channel->sock_create_cb_data = NULL;
168 channel->last_server = 0;
169 channel->last_timeout_processed = (time_t)now.tv_sec;
171 /* Initialize our lists of queries */
172 ares__init_list_head(&(channel->all_queries));
173 for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
175 ares__init_list_head(&(channel->queries_by_qid[i]));
177 for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
179 ares__init_list_head(&(channel->queries_by_timeout[i]));
182 /* Initialize configuration by each of the four sources, from highest
183 * precedence to lowest.
186 if (status == ARES_SUCCESS) {
187 status = init_by_options(channel, options, optmask);
188 if (status != ARES_SUCCESS)
189 DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
190 ares_strerror(status)));
192 if (status == ARES_SUCCESS) {
193 status = init_by_environment(channel);
194 if (status != ARES_SUCCESS)
195 DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
196 ares_strerror(status)));
198 if (status == ARES_SUCCESS) {
199 status = init_by_resolv_conf(channel);
200 if (status != ARES_SUCCESS)
201 DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
202 ares_strerror(status)));
206 * No matter what failed or succeeded, seed defaults to provide
207 * useful behavior for things that we missed.
209 status = init_by_defaults(channel);
210 if (status != ARES_SUCCESS)
211 DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
212 ares_strerror(status)));
214 /* Generate random key */
216 if (status == ARES_SUCCESS) {
217 status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
218 if (status == ARES_SUCCESS)
219 channel->next_id = ares__generate_new_id(&channel->id_key);
221 DEBUGF(fprintf(stderr, "Error: init_id_key failed: %s\n",
222 ares_strerror(status)));
225 if (status != ARES_SUCCESS)
227 /* Something failed; clean up memory we may have allocated. */
228 if (channel->servers)
229 free(channel->servers);
230 if (channel->domains)
232 for (i = 0; i < channel->ndomains; i++)
233 free(channel->domains[i]);
234 free(channel->domains);
236 if (channel->sortlist)
237 free(channel->sortlist);
239 free(channel->lookups);
244 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
245 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
246 channel->nservers = 1;
248 /* Initialize server states. */
249 for (i = 0; i < channel->nservers; i++)
251 server = &channel->servers[i];
252 server->udp_socket = ARES_SOCKET_BAD;
253 server->tcp_socket = ARES_SOCKET_BAD;
254 server->tcp_connection_generation = ++channel->tcp_connection_generation;
255 server->tcp_lenbuf_pos = 0;
256 server->tcp_buffer = NULL;
257 server->qhead = NULL;
258 server->qtail = NULL;
259 ares__init_list_head(&(server->queries_to_server));
260 server->channel = channel;
261 server->is_broken = 0;
264 *channelptr = channel;
268 /* ares_dup() duplicates a channel handle with all its options and returns a
269 new channel handle */
270 int ares_dup(ares_channel *dest, ares_channel src)
272 struct ares_options opts;
276 *dest = NULL; /* in case of failure return NULL explicitly */
278 /* First get the options supported by the old ares_save_options() function,
279 which is most of them */
280 rc = ares_save_options(src, &opts, &optmask);
284 /* Then create the new channel with those options */
285 rc = ares_init_options(dest, &opts, optmask);
287 /* destroy the options copy to not leak any memory */
288 ares_destroy_options(&opts);
293 /* Now clone the options that ares_save_options() doesn't support. */
294 (*dest)->sock_create_cb = src->sock_create_cb;
295 (*dest)->sock_create_cb_data = src->sock_create_cb_data;
298 return ARES_SUCCESS; /* everything went fine */
302 /* Save options from initialized channel */
303 int ares_save_options(ares_channel channel, struct ares_options *options,
308 /* Zero everything out */
309 memset(options, 0, sizeof(struct ares_options));
311 if (!ARES_CONFIG_CHECK(channel))
314 /* Traditionally the optmask wasn't saved in the channel struct so it was
315 recreated here. ROTATE is the first option that has no struct field of
316 its own in the public config struct */
317 (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TRIES|ARES_OPT_NDOTS|
318 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
319 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
320 ARES_OPT_SORTLIST|ARES_OPT_TIMEOUTMS) |
321 (channel->optmask & ARES_OPT_ROTATE);
323 /* Copy easy stuff */
324 options->flags = channel->flags;
326 /* We return full millisecond resolution but that's only because we don't
327 set the ARES_OPT_TIMEOUT anymore, only the new ARES_OPT_TIMEOUTMS */
328 options->timeout = channel->timeout;
329 options->tries = channel->tries;
330 options->ndots = channel->ndots;
331 options->udp_port = (unsigned short)channel->udp_port;
332 options->tcp_port = (unsigned short)channel->tcp_port;
333 options->sock_state_cb = channel->sock_state_cb;
334 options->sock_state_cb_data = channel->sock_state_cb_data;
337 if (channel->nservers) {
339 malloc(channel->nservers * sizeof(struct server_state));
340 if (!options->servers && channel->nservers != 0)
342 for (i = 0; i < channel->nservers; i++)
343 options->servers[i] = channel->servers[i].addr;
345 options->nservers = channel->nservers;
348 if (channel->ndomains) {
349 options->domains = malloc(channel->ndomains * sizeof(char *));
350 if (!options->domains)
353 for (i = 0; i < channel->ndomains; i++)
355 options->ndomains = i;
356 options->domains[i] = strdup(channel->domains[i]);
357 if (!options->domains[i])
361 options->ndomains = channel->ndomains;
364 if (channel->lookups) {
365 options->lookups = strdup(channel->lookups);
366 if (!options->lookups && channel->lookups)
371 if (channel->nsort) {
372 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
373 if (!options->sortlist)
375 for (i = 0; i < channel->nsort; i++)
377 memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
378 sizeof(struct apattern));
381 options->nsort = channel->nsort;
386 static int init_by_options(ares_channel channel,
387 const struct ares_options *options,
393 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
394 channel->flags = options->flags;
395 if ((optmask & ARES_OPT_TIMEOUTMS) && channel->timeout == -1)
396 channel->timeout = options->timeout;
397 else if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
398 channel->timeout = options->timeout * 1000;
399 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
400 channel->tries = options->tries;
401 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
402 channel->ndots = options->ndots;
403 if ((optmask & ARES_OPT_ROTATE) && channel->rotate == -1)
405 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
406 channel->udp_port = options->udp_port;
407 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
408 channel->tcp_port = options->tcp_port;
409 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
411 channel->sock_state_cb = options->sock_state_cb;
412 channel->sock_state_cb_data = options->sock_state_cb_data;
414 if ((optmask & ARES_OPT_SOCK_SNDBUF)
415 && channel->socket_send_buffer_size == -1)
416 channel->socket_send_buffer_size = options->socket_send_buffer_size;
417 if ((optmask & ARES_OPT_SOCK_RCVBUF)
418 && channel->socket_receive_buffer_size == -1)
419 channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
421 /* Copy the servers, if given. */
422 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
424 /* Avoid zero size allocations at any cost */
425 if (options->nservers > 0)
428 malloc(options->nservers * sizeof(struct server_state));
429 if (!channel->servers)
431 for (i = 0; i < options->nservers; i++)
432 channel->servers[i].addr = options->servers[i];
434 channel->nservers = options->nservers;
437 /* Copy the domains, if given. Keep channel->ndomains consistent so
438 * we can clean up in case of error.
440 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
442 /* Avoid zero size allocations at any cost */
443 if (options->ndomains > 0)
445 channel->domains = malloc(options->ndomains * sizeof(char *));
446 if (!channel->domains)
448 for (i = 0; i < options->ndomains; i++)
450 channel->ndomains = i;
451 channel->domains[i] = strdup(options->domains[i]);
452 if (!channel->domains[i])
456 channel->ndomains = options->ndomains;
459 /* Set lookups, if given. */
460 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
462 channel->lookups = strdup(options->lookups);
463 if (!channel->lookups)
468 if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
470 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
471 if (!channel->sortlist)
473 for (i = 0; i < options->nsort; i++)
475 memcpy(&(channel->sortlist[i]), &(options->sortlist[i]),
476 sizeof(struct apattern));
478 channel->nsort = options->nsort;
481 channel->optmask = optmask;
486 static int init_by_environment(ares_channel channel)
488 const char *localdomain, *res_options;
491 localdomain = getenv("LOCALDOMAIN");
492 if (localdomain && channel->ndomains == -1)
494 status = set_search(channel, localdomain);
495 if (status != ARES_SUCCESS)
499 res_options = getenv("RES_OPTIONS");
502 status = set_options(channel, res_options);
503 if (status != ARES_SUCCESS)
512 * Warning: returns a dynamically allocated buffer, the user MUST
513 * use free() if the function returns 1
515 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
517 /* Test for the size we need */
521 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
522 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
524 *obuf = malloc(size+1);
528 if (RegQueryValueEx(hKey, subkey, 0, NULL,
529 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
542 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
544 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
545 DWORD enum_size = 39;
549 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
550 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
555 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
558 rc = get_res_nt(hVal, subkey, obuf);
566 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
568 FIXED_INFO *fi, *newfi;
569 DWORD size = sizeof (*fi);
570 IP_ADDR_STRING *ipAddr;
573 size_t ip_size = sizeof("255.255.255.255,")-1;
574 size_t left = ret_size;
582 res = (*fpGetNetworkParams) (fi, &size);
583 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
586 newfi = realloc(fi, size);
591 res = (*fpGetNetworkParams) (fi, &size);
592 if (res != ERROR_SUCCESS)
597 printf ("Host Name: %s\n", fi->HostName);
598 printf ("Domain Name: %s\n", fi->DomainName);
599 printf ("DNS Servers:\n"
600 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
602 if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
603 inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
606 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
607 left -= ret - ret_buf;
611 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
612 ipAddr = ipAddr->Next, i++)
614 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
616 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
617 left -= ret - ret_buf;
621 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
628 if (debug && left <= ip_size)
629 printf ("Too many nameservers. Truncating to %d addressess", count);
636 static int init_by_resolv_conf(ares_channel channel)
639 int status = -1, nservers = 0, nsort = 0;
640 struct server_state *servers = NULL;
641 struct apattern *sortlist = NULL;
646 NameServer info via IPHLPAPI (IP helper API):
647 GetNetworkParams() should be the trusted source for this.
648 Available in Win-98/2000 and later. If that fail, fall-back to
649 registry information.
653 On Windows 9X, the DNS server can be found in:
654 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
656 On Windows NT/2000/XP/2003:
657 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
659 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
661 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
664 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
675 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
678 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
680 status = config_nameserver(&servers, &nservers, buf);
681 if (status == ARES_SUCCESS)
688 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
692 RegOpenKeyEx(mykey, "Interfaces", 0,
693 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
694 if (get_res_nt(mykey, NAMESERVER, &line))
696 status = config_nameserver(&servers, &nservers, line);
699 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
701 status = config_nameserver(&servers, &nservers, line);
704 /* Try the interfaces */
705 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
707 status = config_nameserver(&servers, &nservers, line);
710 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
712 status = config_nameserver(&servers, &nservers, line);
722 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
726 if ((result = RegQueryValueEx(
727 mykey, NAMESERVER, NULL, &data_type,
730 ) == ERROR_SUCCESS ||
731 result == ERROR_MORE_DATA)
735 line = malloc(bytes+1);
736 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
737 (unsigned char *)line, &bytes) ==
740 status = config_nameserver(&servers, &nservers, line);
749 if (status == ARES_SUCCESS)
752 /* Catch the case when all the above checks fail (which happens when there
753 is no network card or the cable is unplugged) */
756 #elif defined(__riscos__)
758 /* Under RISC OS, name servers are listed in the
759 system variable Inet$Resolvers, space separated. */
761 line = getenv("Inet$Resolvers");
764 char *resolvers = strdup(line), *pos, *space;
771 space = strchr(pos, ' ');
774 status = config_nameserver(&servers, &nservers, pos);
775 if (status != ARES_SUCCESS)
780 if (status == ARES_SUCCESS)
786 #elif defined(WATT32)
790 for (i = 0; def_nameservers[i]; i++)
793 return ARES_SUCCESS; /* use localhost DNS server */
796 servers = calloc(sizeof(*servers), i);
800 for (i = 0; def_nameservers[i]; i++)
801 servers[i].addr.s_addr = htonl(def_nameservers[i]);
811 /* Don't read resolv.conf and friends if we don't have to */
812 if (ARES_CONFIG_CHECK(channel))
815 fp = fopen(PATH_RESOLV_CONF, "r");
817 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
819 if ((p = try_config(line, "domain")) && channel->ndomains == -1)
820 status = config_domain(channel, p);
821 else if ((p = try_config(line, "lookup")) && !channel->lookups)
822 status = config_lookup(channel, p, "bind", "file");
823 else if ((p = try_config(line, "search")) && channel->ndomains == -1)
824 status = set_search(channel, p);
825 else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
826 status = config_nameserver(&servers, &nservers, p);
827 else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
828 status = config_sortlist(&sortlist, &nsort, p);
829 else if ((p = try_config(line, "options")))
830 status = set_options(channel, p);
832 status = ARES_SUCCESS;
833 if (status != ARES_SUCCESS)
846 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
847 error, strerror(error)));
848 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
853 if ((status == ARES_EOF) && (!channel->lookups)) {
854 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
855 fp = fopen("/etc/nsswitch.conf", "r");
857 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
859 if ((p = try_config(line, "hosts:")) && !channel->lookups)
860 status = config_lookup(channel, p, "dns", "files");
872 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
873 error, strerror(error)));
874 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
880 if ((status == ARES_EOF) && (!channel->lookups)) {
881 /* Linux / GNU libc 2.x and possibly others have host.conf */
882 fp = fopen("/etc/host.conf", "r");
884 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
886 if ((p = try_config(line, "order")) && !channel->lookups)
887 status = config_lookup(channel, p, "bind", "hosts");
899 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
900 error, strerror(error)));
901 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
907 if ((status == ARES_EOF) && (!channel->lookups)) {
908 /* Tru64 uses /etc/svc.conf */
909 fp = fopen("/etc/svc.conf", "r");
911 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
913 if ((p = try_config(line, "hosts=")) && !channel->lookups)
914 status = config_lookup(channel, p, "bind", "local");
926 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
927 error, strerror(error)));
928 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
941 if (status != ARES_EOF)
945 if (sortlist != NULL)
950 /* If we got any name server entries, fill them in. */
956 channel->servers = servers;
957 channel->nservers = nservers;
960 /* If we got any sortlist entries, fill them in. */
963 channel->sortlist = sortlist;
964 channel->nsort = nsort;
970 static int init_by_defaults(ares_channel channel)
972 char *hostname = NULL;
973 int rc = ARES_SUCCESS;
975 if (channel->flags == -1)
977 if (channel->timeout == -1)
978 channel->timeout = DEFAULT_TIMEOUT;
979 if (channel->tries == -1)
980 channel->tries = DEFAULT_TRIES;
981 if (channel->ndots == -1)
983 if (channel->rotate == -1)
985 if (channel->udp_port == -1)
986 channel->udp_port = htons(NAMESERVER_PORT);
987 if (channel->tcp_port == -1)
988 channel->tcp_port = htons(NAMESERVER_PORT);
990 if (channel->nservers == -1) {
991 /* If nobody specified servers, try a local named. */
992 channel->servers = malloc(sizeof(struct server_state));
993 if (!channel->servers) {
997 channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
998 channel->nservers = 1;
1002 #define toolong(x) (x == -1) && ((ENAMETOOLONG == errno) || (EINVAL == errno))
1004 #define toolong(x) (x == -1) && (EINVAL == errno)
1007 if (channel->ndomains == -1) {
1008 /* Derive a default domain search list from the kernel hostname,
1009 * or set it to empty if the hostname isn't helpful.
1013 channel->ndomains = 0; /* default to none */
1015 #ifdef HAVE_GETHOSTNAME
1016 hostname = malloc(len);
1023 res = gethostname(hostname, len);
1028 p = realloc(hostname, len);
1043 if (strchr(hostname, '.')) {
1044 /* a dot was found */
1046 channel->domains = malloc(sizeof(char *));
1047 if (!channel->domains) {
1051 channel->domains[0] = strdup(strchr(hostname, '.') + 1);
1052 if (!channel->domains[0]) {
1056 channel->ndomains = 1;
1061 if (channel->nsort == -1) {
1062 channel->sortlist = NULL;
1066 if (!channel->lookups) {
1067 channel->lookups = strdup("fb");
1068 if (!channel->lookups)
1074 if(channel->servers)
1075 free(channel->servers);
1077 if(channel->domains && channel->domains[0])
1078 free(channel->domains[0]);
1079 if(channel->domains)
1080 free(channel->domains);
1081 if(channel->lookups)
1082 free(channel->lookups);
1092 static int config_domain(ares_channel channel, char *str)
1096 /* Set a single search domain. */
1098 while (*q && !ISSPACE(*q))
1101 return set_search(channel, str);
1104 static int config_lookup(ares_channel channel, const char *str,
1105 const char *bindch, const char *filech)
1107 char lookups[3], *l;
1110 /* Set the lookup order. Only the first letter of each work
1111 * is relevant, and it has to be "b" for DNS or "f" for the
1112 * host file. Ignore everything else.
1118 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
1119 if (*p == *bindch) *l++ = 'b';
1122 while (*p && !ISSPACE(*p) && (*p != ','))
1124 while (*p && (ISSPACE(*p) || (*p == ',')))
1128 channel->lookups = strdup(lookups);
1129 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1134 static int config_nameserver(struct server_state **servers, int *nservers,
1137 struct in_addr addr;
1138 struct server_state *newserv;
1139 /* On Windows, there may be more than one nameserver specified in the same
1140 * registry key, so we parse it as a space or comma seperated list.
1149 while (*p && !ISSPACE(*p) && *p != ',')
1158 /* Skip multiple spaces or trailing spaces */
1165 /* This is the part that actually sets the nameserver */
1166 addr.s_addr = inet_addr(begin);
1167 if (addr.s_addr == INADDR_NONE)
1169 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1172 newserv[*nservers].addr = addr;
1181 /* Add a nameserver entry, if this is a valid address. */
1182 addr.s_addr = inet_addr(str);
1183 if (addr.s_addr == INADDR_NONE)
1184 return ARES_SUCCESS;
1185 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1188 newserv[*nservers].addr = addr;
1192 return ARES_SUCCESS;
1196 static int config_sortlist(struct apattern **sortlist, int *nsort,
1199 struct apattern pat;
1202 /* Add sortlist entries. */
1203 while (*str && *str != ';')
1206 char ipbuf[16], ipbufpfx[32];
1207 /* Find just the IP */
1209 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1211 memcpy(ipbuf, str, (int)(q-str));
1212 ipbuf[(int)(q-str)] = '\0';
1213 /* Find the prefix */
1216 const char *str2 = q+1;
1217 while (*q && *q != ';' && !ISSPACE(*q))
1219 memcpy(ipbufpfx, str, (int)(q-str));
1220 ipbufpfx[(int)(q-str)] = '\0';
1225 /* Lets see if it is CIDR */
1226 /* First we'll try IPv6 */
1227 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1229 sizeof(pat.addrV6))) > 0)
1231 pat.type = PATTERN_CIDR;
1232 pat.mask.bits = (unsigned short)bits;
1233 pat.family = AF_INET6;
1234 if (!sortlist_alloc(sortlist, nsort, &pat))
1238 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addrV4,
1239 sizeof(pat.addrV4))) > 0)
1241 pat.type = PATTERN_CIDR;
1242 pat.mask.bits = (unsigned short)bits;
1243 pat.family = AF_INET;
1244 if (!sortlist_alloc(sortlist, nsort, &pat))
1247 /* See if it is just a regular IP */
1248 else if (ip_addr(ipbuf, (int)(q-str), &pat.addrV4) == 0)
1252 memcpy(ipbuf, str, (int)(q-str));
1253 ipbuf[(int)(q-str)] = '\0';
1254 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr4) != 0)
1259 pat.family = AF_INET;
1260 pat.type = PATTERN_MASK;
1261 if (!sortlist_alloc(sortlist, nsort, &pat))
1266 while (*q && *q != ';' && !ISSPACE(*q))
1270 while (ISSPACE(*str))
1274 return ARES_SUCCESS;
1278 static int set_search(ares_channel channel, const char *str)
1283 if(channel->ndomains != -1) {
1284 /* if we already have some domains present, free them first */
1285 for(n=0; n < channel->ndomains; n++)
1286 free(channel->domains[n]);
1287 free(channel->domains);
1288 channel->domains = NULL;
1289 channel->ndomains = -1;
1292 /* Count the domains given. */
1297 while (*p && !ISSPACE(*p))
1306 channel->ndomains = 0;
1307 return ARES_SUCCESS;
1310 channel->domains = malloc(n * sizeof(char *));
1311 if (!channel->domains)
1314 /* Now copy the domains. */
1319 channel->ndomains = n;
1321 while (*q && !ISSPACE(*q))
1323 channel->domains[n] = malloc(q - p + 1);
1324 if (!channel->domains[n])
1326 memcpy(channel->domains[n], p, q - p);
1327 channel->domains[n][q - p] = 0;
1333 channel->ndomains = n;
1335 return ARES_SUCCESS;
1338 static int set_options(ares_channel channel, const char *str)
1340 const char *p, *q, *val;
1346 while (*q && !ISSPACE(*q))
1348 val = try_option(p, q, "ndots:");
1349 if (val && channel->ndots == -1)
1350 channel->ndots = atoi(val);
1351 val = try_option(p, q, "retrans:");
1352 if (val && channel->timeout == -1)
1353 channel->timeout = atoi(val);
1354 val = try_option(p, q, "retry:");
1355 if (val && channel->tries == -1)
1356 channel->tries = atoi(val);
1357 val = try_option(p, q, "rotate");
1358 if (val && channel->rotate == -1)
1359 channel->rotate = 1;
1365 return ARES_SUCCESS;
1369 static char *try_config(char *s, const char *opt)
1377 /* no line or no option */
1380 /* trim line comment */
1381 for (i = 0; s[i] && s[i] != '#'; ++i);
1384 /* trim trailing whitespace */
1385 for (j = i-1; j >= 0 && ISSPACE(s[j]); --j);
1388 /* skip leading whitespace */
1389 for (i = 0; s[i] && ISSPACE(s[i]); ++i);
1396 if ((len = strlen(opt)) == 0)
1400 if (strncmp(p, opt, len) != 0)
1401 /* line and option do not match */
1404 /* skip over given option name */
1408 /* no option value */
1411 if ((opt[len-1] != ':') && (opt[len-1] != '=') && !ISSPACE(*p))
1412 /* whitespace between option name and value is mandatory
1413 for given option names which do not end with ':' or '=' */
1416 /* skip over whitespace */
1417 while (*p && ISSPACE(*p))
1421 /* no option value */
1424 /* return pointer to option value */
1429 static const char *try_option(const char *p, const char *q, const char *opt)
1431 size_t len = strlen(opt);
1432 return ((size_t)(q - p) >= len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1436 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1437 struct apattern *pat)
1439 struct apattern *newsort;
1440 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1443 newsort[*nsort] = *pat;
1444 *sortlist = newsort;
1449 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1452 /* Four octets and three periods yields at most 15 characters. */
1456 addr->s_addr = inet_addr(ipbuf);
1457 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1462 static void natural_mask(struct apattern *pat)
1464 struct in_addr addr;
1466 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1469 addr.s_addr = ntohl(pat->addrV4.s_addr);
1471 /* This is out of date in the CIDR world, but some people might
1474 if (IN_CLASSA(addr.s_addr))
1475 pat->mask.addr4.s_addr = htonl(IN_CLASSA_NET);
1476 else if (IN_CLASSB(addr.s_addr))
1477 pat->mask.addr4.s_addr = htonl(IN_CLASSB_NET);
1479 pat->mask.addr4.s_addr = htonl(IN_CLASSC_NET);
1482 /* initialize an rc4 key. If possible a cryptographically secure random key
1483 is generated using a suitable function (for example win32's RtlGenRandom as
1485 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1486 otherwise the code defaults to cross-platform albeit less secure mechanism
1489 static void randomize_key(unsigned char* key,int key_data_len)
1495 if (fpSystemFunction036)
1497 res = (*fpSystemFunction036) (key, key_data_len);
1503 FILE *f = fopen(RANDOM_FILE, "rb");
1505 counter = fread(key, 1, key_data_len, f);
1511 if ( !randomized ) {
1512 for (;counter<key_data_len;counter++)
1513 key[counter]=(unsigned char)(rand() % 256);
1517 static int init_id_key(rc4_key* key,int key_data_len)
1519 unsigned char index1;
1520 unsigned char index2;
1521 unsigned char* state;
1523 unsigned char *key_data_ptr = 0;
1525 key_data_ptr = calloc(1,key_data_len);
1529 state = &key->state[0];
1530 for(counter = 0; counter < 256; counter++)
1531 /* unnecessary AND but it keeps some compilers happier */
1532 state[counter] = (unsigned char)(counter & 0xff);
1533 randomize_key(key->state,key_data_len);
1538 for(counter = 0; counter < 256; counter++)
1540 index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1542 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1544 index1 = (unsigned char)((index1 + 1) % key_data_len);
1547 return ARES_SUCCESS;
1550 unsigned short ares__generate_new_id(rc4_key* key)
1553 ares__rc4(key, (unsigned char *)&r, sizeof(r));
1557 void ares_set_socket_callback(ares_channel channel,
1558 ares_sock_create_callback cb,
1561 channel->sock_create_cb = cb;
1562 channel->sock_create_cb_data = data;