3 /* Copyright 1998 by the Massachusetts Institute of Technology.
4 * Copyright (C) 2007-2008 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)
27 #ifdef HAVE_SYS_PARAM_H
28 #include <sys/param.h>
31 #ifdef HAVE_SYS_TIME_H
35 #ifdef HAVE_SYS_SOCKET_H
36 #include <sys/socket.h>
39 #ifdef HAVE_NETINET_IN_H
40 #include <netinet/in.h>
47 #ifdef HAVE_ARPA_INET_H
48 #include <arpa/inet.h>
51 #ifdef HAVE_ARPA_NAMESER_H
52 #include <arpa/nameser.h>
55 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
56 #include <arpa/nameser_compat.h>
62 #include <process.h> /* Some have getpid() here */
73 #include "inet_net_pton.h"
74 #include "ares_private.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);
86 static int config_nameserver(struct server_state **servers, int *nservers,
88 static int set_search(ares_channel channel, const char *str);
89 static int set_options(ares_channel channel, const char *str);
90 static const char *try_option(const char *p, const char *q, const char *opt);
91 static int init_id_key(rc4_key* key,int key_data_len);
94 static int sortlist_alloc(struct apattern **sortlist, int *nsort, struct apattern *pat);
95 static int ip_addr(const char *s, int len, struct in_addr *addr);
96 static void natural_mask(struct apattern *pat);
97 static int config_domain(ares_channel channel, char *str);
98 static int config_lookup(ares_channel channel, const char *str,
99 const char *bindch, const char *filech);
100 static int config_sortlist(struct apattern **sortlist, int *nsort,
102 static char *try_config(char *s, const char *opt);
105 #define ARES_CONFIG_CHECK(x) (x->lookups && x->nsort > -1 && \
106 x->nservers > -1 && \
107 x->ndomains > -1 && \
108 x->ndots > -1 && x->timeout > -1 && \
111 int ares_init(ares_channel *channelptr)
113 return ares_init_options(channelptr, NULL, 0);
116 int ares_init_options(ares_channel *channelptr, struct ares_options *options,
119 ares_channel channel;
121 int status = ARES_SUCCESS;
122 struct server_state *server;
126 const char *env = getenv("CARES_MEMDEBUG");
130 env = getenv("CARES_MEMLIMIT");
132 curl_memlimit(atoi(env));
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->udp_port = -1;
151 channel->tcp_port = -1;
152 channel->socket_send_buffer_size = -1;
153 channel->socket_receive_buffer_size = -1;
154 channel->nservers = -1;
155 channel->ndomains = -1;
157 channel->tcp_connection_generation = 0;
158 channel->lookups = NULL;
159 channel->domains = NULL;
160 channel->sortlist = NULL;
161 channel->servers = NULL;
162 channel->sock_state_cb = NULL;
163 channel->sock_state_cb_data = NULL;
165 channel->last_timeout_processed = (time_t)now.tv_sec;
167 /* Initialize our lists of queries */
168 ares__init_list_head(&(channel->all_queries));
169 for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
171 ares__init_list_head(&(channel->queries_by_qid[i]));
173 for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
175 ares__init_list_head(&(channel->queries_by_timeout[i]));
178 /* Initialize configuration by each of the four sources, from highest
179 * precedence to lowest.
182 if (status == ARES_SUCCESS) {
183 status = init_by_options(channel, options, optmask);
184 if (status != ARES_SUCCESS)
185 DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
186 ares_strerror(status)));
188 if (status == ARES_SUCCESS) {
189 status = init_by_environment(channel);
190 if (status != ARES_SUCCESS)
191 DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
192 ares_strerror(status)));
194 if (status == ARES_SUCCESS) {
195 status = init_by_resolv_conf(channel);
196 if (status != ARES_SUCCESS)
197 DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
198 ares_strerror(status)));
200 if (status == ARES_SUCCESS) {
201 status = init_by_defaults(channel);
202 if (status != ARES_SUCCESS)
203 DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
204 ares_strerror(status)));
207 /* Generate random key */
209 if (status == ARES_SUCCESS) {
210 status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
211 if (status == ARES_SUCCESS)
212 channel->next_id = ares__generate_new_id(&channel->id_key);
214 DEBUGF(fprintf(stderr, "Error: init_id_key failed: %s\n",
215 ares_strerror(status)));
218 if (status != ARES_SUCCESS)
220 /* Something failed; clean up memory we may have allocated. */
221 if (channel->servers)
222 free(channel->servers);
223 if (channel->domains)
225 for (i = 0; i < channel->ndomains; i++)
226 free(channel->domains[i]);
227 free(channel->domains);
229 if (channel->sortlist)
230 free(channel->sortlist);
232 free(channel->lookups);
237 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
238 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
239 channel->nservers = 1;
241 /* Initialize server states. */
242 for (i = 0; i < channel->nservers; i++)
244 server = &channel->servers[i];
245 server->udp_socket = ARES_SOCKET_BAD;
246 server->tcp_socket = ARES_SOCKET_BAD;
247 server->tcp_connection_generation = ++channel->tcp_connection_generation;
248 server->tcp_lenbuf_pos = 0;
249 server->tcp_buffer = NULL;
250 server->qhead = NULL;
251 server->qtail = NULL;
252 ares__init_list_head(&(server->queries_to_server));
253 server->channel = channel;
254 server->is_broken = 0;
257 *channelptr = channel;
261 /* Save options from initialized channel */
262 int ares_save_options(ares_channel channel, struct ares_options *options,
267 /* Zero everything out */
268 memset(options, 0, sizeof(struct ares_options));
270 if (!ARES_CONFIG_CHECK(channel))
273 (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TRIES|ARES_OPT_NDOTS|
274 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
275 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
276 ARES_OPT_SORTLIST|ARES_OPT_TIMEOUTMS);
278 /* Copy easy stuff */
279 options->flags = channel->flags;
281 /* We return full millisecond resolution but that's only because we don't
282 set the ARES_OPT_TIMEOUT anymore, only the new ARES_OPT_TIMEOUTMS */
283 options->timeout = channel->timeout;
284 options->tries = channel->tries;
285 options->ndots = channel->ndots;
286 options->udp_port = (unsigned short)channel->udp_port;
287 options->tcp_port = (unsigned short)channel->tcp_port;
288 options->sock_state_cb = channel->sock_state_cb;
289 options->sock_state_cb_data = channel->sock_state_cb_data;
292 if (channel->nservers) {
294 malloc(channel->nservers * sizeof(struct server_state));
295 if (!options->servers && channel->nservers != 0)
297 for (i = 0; i < channel->nservers; i++)
298 options->servers[i] = channel->servers[i].addr;
300 options->nservers = channel->nservers;
303 if (channel->ndomains) {
304 options->domains = malloc(channel->ndomains * sizeof(char *));
305 if (!options->domains)
308 for (i = 0; i < channel->ndomains; i++)
310 options->ndomains = i;
311 options->domains[i] = strdup(channel->domains[i]);
312 if (!options->domains[i])
316 options->ndomains = channel->ndomains;
319 if (channel->lookups) {
320 options->lookups = strdup(channel->lookups);
321 if (!options->lookups && channel->lookups)
326 if (channel->nsort) {
327 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
328 if (!options->sortlist)
330 for (i = 0; i < channel->nsort; i++)
332 memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
333 sizeof(struct apattern));
336 options->nsort = channel->nsort;
341 static int init_by_options(ares_channel channel,
342 const struct ares_options *options,
348 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
349 channel->flags = options->flags;
350 if ((optmask & ARES_OPT_TIMEOUTMS) && channel->timeout == -1)
351 channel->timeout = options->timeout;
352 else if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
353 channel->timeout = options->timeout * 1000;
354 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
355 channel->tries = options->tries;
356 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
357 channel->ndots = options->ndots;
358 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
359 channel->udp_port = options->udp_port;
360 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
361 channel->tcp_port = options->tcp_port;
362 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
364 channel->sock_state_cb = options->sock_state_cb;
365 channel->sock_state_cb_data = options->sock_state_cb_data;
367 if ((optmask & ARES_OPT_SOCK_SNDBUF)
368 && channel->socket_send_buffer_size == -1)
369 channel->socket_send_buffer_size = options->socket_send_buffer_size;
370 if ((optmask & ARES_OPT_SOCK_RCVBUF)
371 && channel->socket_receive_buffer_size == -1)
372 channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
374 /* Copy the servers, if given. */
375 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
377 /* Avoid zero size allocations at any cost */
378 if (options->nservers > 0)
381 malloc(options->nservers * sizeof(struct server_state));
382 if (!channel->servers)
384 for (i = 0; i < options->nservers; i++)
385 channel->servers[i].addr = options->servers[i];
387 channel->nservers = options->nservers;
390 /* Copy the domains, if given. Keep channel->ndomains consistent so
391 * we can clean up in case of error.
393 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
395 /* Avoid zero size allocations at any cost */
396 if (options->ndomains > 0)
398 channel->domains = malloc(options->ndomains * sizeof(char *));
399 if (!channel->domains)
401 for (i = 0; i < options->ndomains; i++)
403 channel->ndomains = i;
404 channel->domains[i] = strdup(options->domains[i]);
405 if (!channel->domains[i])
409 channel->ndomains = options->ndomains;
412 /* Set lookups, if given. */
413 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
415 channel->lookups = strdup(options->lookups);
416 if (!channel->lookups)
421 if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
423 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
424 if (!channel->sortlist)
426 for (i = 0; i < options->nsort; i++)
428 memcpy(&(channel->sortlist[i]), &(options->sortlist[i]), sizeof(struct apattern));
430 channel->nsort = options->nsort;
436 static int init_by_environment(ares_channel channel)
438 const char *localdomain, *res_options;
441 localdomain = getenv("LOCALDOMAIN");
442 if (localdomain && channel->ndomains == -1)
444 status = set_search(channel, localdomain);
445 if (status != ARES_SUCCESS)
449 res_options = getenv("RES_OPTIONS");
452 status = set_options(channel, res_options);
453 if (status != ARES_SUCCESS)
462 * Warning: returns a dynamically allocated buffer, the user MUST
463 * use free() if the function returns 1
465 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
467 /* Test for the size we need */
471 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
472 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
474 *obuf = malloc(size+1);
478 if (RegQueryValueEx(hKey, subkey, 0, NULL,
479 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
492 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
494 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
495 DWORD enum_size = 39;
499 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
500 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
505 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
508 rc = get_res_nt(hVal, subkey, obuf);
516 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
518 FIXED_INFO *fi = alloca (sizeof(*fi));
519 DWORD size = sizeof (*fi);
520 typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
521 get_net_param_func fpGetNetworkParams; /* available only on Win-98/2000+ */
523 IP_ADDR_STRING *ipAddr;
526 size_t ip_size = sizeof("255.255.255.255,")-1;
527 size_t left = ret_size;
534 handle = LoadLibrary ("iphlpapi.dll");
538 fpGetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
539 if (!fpGetNetworkParams)
542 res = (*fpGetNetworkParams) (fi, &size);
543 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
547 if (!fi || (*fpGetNetworkParams) (fi, &size) != ERROR_SUCCESS)
552 printf ("Host Name: %s\n", fi->HostName);
553 printf ("Domain Name: %s\n", fi->DomainName);
554 printf ("DNS Servers:\n"
555 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
557 if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
558 inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
561 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
562 left -= ret - ret_buf;
566 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
567 ipAddr = ipAddr->Next, i++)
569 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
571 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
572 left -= ret - ret_buf;
576 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
581 FreeLibrary (handle);
583 if (debug && left <= ip_size)
584 printf ("Too many nameservers. Truncating to %d addressess", count);
591 static int init_by_resolv_conf(ares_channel channel)
594 int status = -1, nservers = 0, nsort = 0;
595 struct server_state *servers = NULL;
596 struct apattern *sortlist = NULL;
601 NameServer info via IPHLPAPI (IP helper API):
602 GetNetworkParams() should be the trusted source for this.
603 Available in Win-98/2000 and later. If that fail, fall-back to
604 registry information.
608 On Windows 9X, the DNS server can be found in:
609 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
611 On Windows NT/2000/XP/2003:
612 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
614 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
616 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
619 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
630 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
633 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
635 status = config_nameserver(&servers, &nservers, buf);
636 if (status == ARES_SUCCESS)
643 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
647 RegOpenKeyEx(mykey, "Interfaces", 0,
648 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
649 if (get_res_nt(mykey, NAMESERVER, &line))
651 status = config_nameserver(&servers, &nservers, line);
654 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
656 status = config_nameserver(&servers, &nservers, line);
659 /* Try the interfaces */
660 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
662 status = config_nameserver(&servers, &nservers, line);
665 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
667 status = config_nameserver(&servers, &nservers, line);
677 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
681 if ((result = RegQueryValueEx(
682 mykey, NAMESERVER, NULL, &data_type,
685 ) == ERROR_SUCCESS ||
686 result == ERROR_MORE_DATA)
690 line = malloc(bytes+1);
691 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
692 (unsigned char *)line, &bytes) ==
695 status = config_nameserver(&servers, &nservers, line);
704 if (status == ARES_SUCCESS)
707 /* Catch the case when all the above checks fail (which happens when there
708 is no network card or the cable is unplugged) */
711 #elif defined(__riscos__)
713 /* Under RISC OS, name servers are listed in the
714 system variable Inet$Resolvers, space separated. */
716 line = getenv("Inet$Resolvers");
719 char *resolvers = strdup(line), *pos, *space;
726 space = strchr(pos, ' ');
729 status = config_nameserver(&servers, &nservers, pos);
730 if (status != ARES_SUCCESS)
735 if (status == ARES_SUCCESS)
741 #elif defined(WATT32)
745 for (i = 0; def_nameservers[i]; i++)
748 return ARES_SUCCESS; /* use localhost DNS server */
751 servers = calloc(sizeof(*servers), i);
755 for (i = 0; def_nameservers[i]; i++)
756 servers[i].addr.s_addr = htonl(def_nameservers[i]);
766 /* Don't read resolv.conf and friends if we don't have to */
767 if (ARES_CONFIG_CHECK(channel))
770 fp = fopen(PATH_RESOLV_CONF, "r");
772 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
774 if ((p = try_config(line, "domain")) && channel->ndomains == -1)
775 status = config_domain(channel, p);
776 else if ((p = try_config(line, "lookup")) && !channel->lookups)
777 status = config_lookup(channel, p, "bind", "file");
778 else if ((p = try_config(line, "search")) && channel->ndomains == -1)
779 status = set_search(channel, p);
780 else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
781 status = config_nameserver(&servers, &nservers, p);
782 else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
783 status = config_sortlist(&sortlist, &nsort, p);
784 else if ((p = try_config(line, "options")))
785 status = set_options(channel, p);
787 status = ARES_SUCCESS;
788 if (status != ARES_SUCCESS)
801 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
802 error, strerror(error)));
803 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
808 if ((status == ARES_EOF) && (!channel->lookups)) {
809 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
810 fp = fopen("/etc/nsswitch.conf", "r");
812 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
814 if ((p = try_config(line, "hosts:")) && !channel->lookups)
815 status = config_lookup(channel, p, "dns", "files");
827 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
828 error, strerror(error)));
829 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
835 if ((status == ARES_EOF) && (!channel->lookups)) {
836 /* Linux / GNU libc 2.x and possibly others have host.conf */
837 fp = fopen("/etc/host.conf", "r");
839 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
841 if ((p = try_config(line, "order")) && !channel->lookups)
842 status = config_lookup(channel, p, "bind", "hosts");
854 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
855 error, strerror(error)));
856 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
862 if ((status == ARES_EOF) && (!channel->lookups)) {
863 /* Tru64 uses /etc/svc.conf */
864 fp = fopen("/etc/svc.conf", "r");
866 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
868 if ((p = try_config(line, "hosts=")) && !channel->lookups)
869 status = config_lookup(channel, p, "bind", "local");
881 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
882 error, strerror(error)));
883 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
896 if (status != ARES_EOF)
900 if (sortlist != NULL)
905 /* If we got any name server entries, fill them in. */
911 channel->servers = servers;
912 channel->nservers = nservers;
915 /* If we got any sortlist entries, fill them in. */
918 channel->sortlist = sortlist;
919 channel->nsort = nsort;
925 static int init_by_defaults(ares_channel channel)
927 char *hostname = NULL;
928 int rc = ARES_SUCCESS;
930 if (channel->flags == -1)
932 if (channel->timeout == -1)
933 channel->timeout = DEFAULT_TIMEOUT;
934 if (channel->tries == -1)
935 channel->tries = DEFAULT_TRIES;
936 if (channel->ndots == -1)
938 if (channel->udp_port == -1)
939 channel->udp_port = htons(NAMESERVER_PORT);
940 if (channel->tcp_port == -1)
941 channel->tcp_port = htons(NAMESERVER_PORT);
943 if (channel->nservers == -1) {
944 /* If nobody specified servers, try a local named. */
945 channel->servers = malloc(sizeof(struct server_state));
946 if (!channel->servers) {
950 channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
951 channel->nservers = 1;
955 #define toolong(x) (x == -1) && ((ENAMETOOLONG == errno) || (EINVAL == errno))
957 #define toolong(x) (x == -1) && (EINVAL == errno)
960 if (channel->ndomains == -1) {
961 /* Derive a default domain search list from the kernel hostname,
962 * or set it to empty if the hostname isn't helpful.
967 hostname = malloc(len);
974 res = gethostname(hostname, len);
979 p = realloc(hostname, len);
994 channel->ndomains = 0; /* default to none */
995 if (strchr(hostname, '.')) {
996 /* a dot was found */
998 channel->domains = malloc(sizeof(char *));
999 if (!channel->domains) {
1003 channel->domains[0] = strdup(strchr(hostname, '.') + 1);
1004 if (!channel->domains[0]) {
1008 channel->ndomains = 1;
1012 if (channel->nsort == -1) {
1013 channel->sortlist = NULL;
1017 if (!channel->lookups) {
1018 channel->lookups = strdup("fb");
1019 if (!channel->lookups)
1025 if(channel->servers)
1026 free(channel->servers);
1028 if(channel->domains && channel->domains[0])
1029 free(channel->domains[0]);
1030 if(channel->domains)
1031 free(channel->domains);
1032 if(channel->lookups)
1033 free(channel->lookups);
1043 static int config_domain(ares_channel channel, char *str)
1047 /* Set a single search domain. */
1049 while (*q && !ISSPACE(*q))
1052 return set_search(channel, str);
1055 static int config_lookup(ares_channel channel, const char *str,
1056 const char *bindch, const char *filech)
1058 char lookups[3], *l;
1061 /* Set the lookup order. Only the first letter of each work
1062 * is relevant, and it has to be "b" for DNS or "f" for the
1063 * host file. Ignore everything else.
1069 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
1070 if (*p == *bindch) *l++ = 'b';
1073 while (*p && !ISSPACE(*p) && (*p != ','))
1075 while (*p && (ISSPACE(*p) || (*p == ',')))
1079 channel->lookups = strdup(lookups);
1080 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1085 static int config_nameserver(struct server_state **servers, int *nservers,
1088 struct in_addr addr;
1089 struct server_state *newserv;
1090 /* On Windows, there may be more than one nameserver specified in the same
1091 * registry key, so we parse it as a space or comma seperated list.
1100 while (*p && !ISSPACE(*p) && *p != ',')
1109 /* Skip multiple spaces or trailing spaces */
1116 /* This is the part that actually sets the nameserver */
1117 addr.s_addr = inet_addr(begin);
1118 if (addr.s_addr == INADDR_NONE)
1120 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1123 newserv[*nservers].addr = addr;
1132 /* Add a nameserver entry, if this is a valid address. */
1133 addr.s_addr = inet_addr(str);
1134 if (addr.s_addr == INADDR_NONE)
1135 return ARES_SUCCESS;
1136 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1139 newserv[*nservers].addr = addr;
1143 return ARES_SUCCESS;
1147 static int config_sortlist(struct apattern **sortlist, int *nsort,
1150 struct apattern pat;
1153 /* Add sortlist entries. */
1154 while (*str && *str != ';')
1157 char ipbuf[16], ipbufpfx[32];
1158 /* Find just the IP */
1160 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1162 memcpy(ipbuf, str, (int)(q-str));
1163 ipbuf[(int)(q-str)] = '\0';
1164 /* Find the prefix */
1167 const char *str2 = q+1;
1168 while (*q && *q != ';' && !ISSPACE(*q))
1170 memcpy(ipbufpfx, str, (int)(q-str));
1171 ipbufpfx[(int)(q-str)] = '\0';
1176 /* Lets see if it is CIDR */
1177 /* First we'll try IPv6 */
1178 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1180 sizeof(pat.addr.addr6))) > 0)
1182 pat.type = PATTERN_CIDR;
1183 pat.mask.bits = (unsigned short)bits;
1184 pat.family = AF_INET6;
1185 if (!sortlist_alloc(sortlist, nsort, &pat))
1189 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addr.addr4,
1190 sizeof(pat.addr.addr4))) > 0)
1192 pat.type = PATTERN_CIDR;
1193 pat.mask.bits = (unsigned short)bits;
1194 pat.family = AF_INET;
1195 if (!sortlist_alloc(sortlist, nsort, &pat))
1198 /* See if it is just a regular IP */
1199 else if (ip_addr(ipbuf, (int)(q-str), &pat.addr.addr4) == 0)
1203 memcpy(ipbuf, str, (int)(q-str));
1204 ipbuf[(int)(q-str)] = '\0';
1205 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr.addr4) != 0)
1210 pat.family = AF_INET;
1211 pat.type = PATTERN_MASK;
1212 if (!sortlist_alloc(sortlist, nsort, &pat))
1217 while (*q && *q != ';' && !ISSPACE(*q))
1221 while (ISSPACE(*str))
1225 return ARES_SUCCESS;
1229 static int set_search(ares_channel channel, const char *str)
1234 if(channel->ndomains != -1) {
1235 /* if we already have some domains present, free them first */
1236 for(n=0; n < channel->ndomains; n++)
1237 free(channel->domains[n]);
1238 free(channel->domains);
1239 channel->domains = NULL;
1240 channel->ndomains = -1;
1243 /* Count the domains given. */
1248 while (*p && !ISSPACE(*p))
1257 channel->ndomains = 0;
1258 return ARES_SUCCESS;
1261 channel->domains = malloc(n * sizeof(char *));
1262 if (!channel->domains)
1265 /* Now copy the domains. */
1270 channel->ndomains = n;
1272 while (*q && !ISSPACE(*q))
1274 channel->domains[n] = malloc(q - p + 1);
1275 if (!channel->domains[n])
1277 memcpy(channel->domains[n], p, q - p);
1278 channel->domains[n][q - p] = 0;
1284 channel->ndomains = n;
1286 return ARES_SUCCESS;
1289 static int set_options(ares_channel channel, const char *str)
1291 const char *p, *q, *val;
1297 while (*q && !ISSPACE(*q))
1299 val = try_option(p, q, "ndots:");
1300 if (val && channel->ndots == -1)
1301 channel->ndots = atoi(val);
1302 val = try_option(p, q, "retrans:");
1303 if (val && channel->timeout == -1)
1304 channel->timeout = atoi(val);
1305 val = try_option(p, q, "retry:");
1306 if (val && channel->tries == -1)
1307 channel->tries = atoi(val);
1313 return ARES_SUCCESS;
1317 static char *try_config(char *s, const char *opt)
1325 /* no line or no option */
1328 /* trim line comment */
1329 for (i = 0; s[i] && s[i] != '#'; ++i);
1332 /* trim trailing whitespace */
1333 for (j = i-1; j >= 0 && ISSPACE(s[j]); --j);
1336 /* skip leading whitespace */
1337 for (i = 0; s[i] && ISSPACE(s[i]); ++i);
1344 if ((len = strlen(opt)) == 0)
1348 if (strncmp(p, opt, len) != 0)
1349 /* line and option do not match */
1352 /* skip over given option name */
1356 /* no option value */
1359 if ((opt[len-1] != ':') && (opt[len-1] != '=') && !ISSPACE(*p))
1360 /* whitespace between option name and value is mandatory
1361 for given option names which do not end with ':' or '=' */
1364 /* skip over whitespace */
1365 while (*p && ISSPACE(*p))
1369 /* no option value */
1372 /* return pointer to option value */
1377 static const char *try_option(const char *p, const char *q, const char *opt)
1379 size_t len = strlen(opt);
1380 return ((size_t)(q - p) > len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1384 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1385 struct apattern *pat)
1387 struct apattern *newsort;
1388 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1391 newsort[*nsort] = *pat;
1392 *sortlist = newsort;
1397 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1400 /* Four octets and three periods yields at most 15 characters. */
1404 addr->s_addr = inet_addr(ipbuf);
1405 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1410 static void natural_mask(struct apattern *pat)
1412 struct in_addr addr;
1414 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1417 addr.s_addr = ntohl(pat->addr.addr4.s_addr);
1419 /* This is out of date in the CIDR world, but some people might
1422 if (IN_CLASSA(addr.s_addr))
1423 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSA_NET);
1424 else if (IN_CLASSB(addr.s_addr))
1425 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSB_NET);
1427 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSC_NET);
1430 /* initialize an rc4 key. If possible a cryptographically secure random key
1431 is generated using a suitable function (for example win32's RtlGenRandom as
1433 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1434 otherwise the code defaults to cross-platform albeit less secure mechanism
1437 static void randomize_key(unsigned char* key,int key_data_len)
1442 HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1444 BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1445 (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1446 if (pfn && pfn(key,key_data_len) )
1453 FILE *f = fopen(RANDOM_FILE, "rb");
1455 counter = fread(key, 1, key_data_len, f);
1461 if ( !randomized ) {
1462 for (;counter<key_data_len;counter++)
1463 key[counter]=(unsigned char)(rand() % 256);
1467 static int init_id_key(rc4_key* key,int key_data_len)
1469 unsigned char index1;
1470 unsigned char index2;
1471 unsigned char* state;
1473 unsigned char *key_data_ptr = 0;
1475 key_data_ptr = calloc(1,key_data_len);
1479 state = &key->state[0];
1480 for(counter = 0; counter < 256; counter++)
1481 /* unnecessary AND but it keeps some compilers happier */
1482 state[counter] = (unsigned char)(counter & 0xff);
1483 randomize_key(key->state,key_data_len);
1488 for(counter = 0; counter < 256; counter++)
1490 index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1492 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1494 index1 = (unsigned char)((index1 + 1) % key_data_len);
1497 return ARES_SUCCESS;
1500 short ares__generate_new_id(rc4_key* key)
1503 ares__rc4(key, (unsigned char *)&r, sizeof(r));