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 #include <netinet/in.h>
40 #include <arpa/inet.h>
42 #include <arpa/nameser.h>
43 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
44 #include <arpa/nameser_compat.h>
50 #include <process.h> /* Some have getpid() here */
61 #include "inet_net_pton.h"
62 #include "ares_private.h"
65 #undef WIN32 /* Redefined in MingW/MSVC headers */
68 static int init_by_options(ares_channel channel, const struct ares_options *options,
70 static int init_by_environment(ares_channel channel);
71 static int init_by_resolv_conf(ares_channel channel);
72 static int init_by_defaults(ares_channel channel);
74 static int config_nameserver(struct server_state **servers, int *nservers,
76 static int set_search(ares_channel channel, const char *str);
77 static int set_options(ares_channel channel, const char *str);
78 static const char *try_option(const char *p, const char *q, const char *opt);
79 static int init_id_key(rc4_key* key,int key_data_len);
82 static int sortlist_alloc(struct apattern **sortlist, int *nsort, struct apattern *pat);
83 static int ip_addr(const char *s, int len, struct in_addr *addr);
84 static void natural_mask(struct apattern *pat);
85 static int config_domain(ares_channel channel, char *str);
86 static int config_lookup(ares_channel channel, const char *str,
87 const char *bindch, const char *filech);
88 static int config_sortlist(struct apattern **sortlist, int *nsort,
90 static char *try_config(char *s, const char *opt);
93 #define ARES_CONFIG_CHECK(x) (x->lookups && x->nsort > -1 && \
96 x->ndots > -1 && x->timeout > -1 && \
99 int ares_init(ares_channel *channelptr)
101 return ares_init_options(channelptr, NULL, 0);
104 int ares_init_options(ares_channel *channelptr, struct ares_options *options,
107 ares_channel channel;
109 int status = ARES_SUCCESS;
110 struct server_state *server;
114 const char *env = getenv("CARES_MEMDEBUG");
118 env = getenv("CARES_MEMLIMIT");
120 curl_memlimit(atoi(env));
123 channel = malloc(sizeof(struct ares_channeldata));
131 /* Set everything to distinguished values so we know they haven't
135 channel->timeout = -1;
138 channel->udp_port = -1;
139 channel->tcp_port = -1;
140 channel->socket_send_buffer_size = -1;
141 channel->socket_receive_buffer_size = -1;
142 channel->nservers = -1;
143 channel->ndomains = -1;
145 channel->tcp_connection_generation = 0;
146 channel->lookups = NULL;
147 channel->domains = NULL;
148 channel->sortlist = NULL;
149 channel->servers = NULL;
150 channel->sock_state_cb = NULL;
151 channel->sock_state_cb_data = NULL;
153 channel->last_timeout_processed = (time_t)now.tv_sec;
155 /* Initialize our lists of queries */
156 ares__init_list_head(&(channel->all_queries));
157 for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
159 ares__init_list_head(&(channel->queries_by_qid[i]));
161 for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
163 ares__init_list_head(&(channel->queries_by_timeout[i]));
166 /* Initialize configuration by each of the four sources, from highest
167 * precedence to lowest.
170 if (status == ARES_SUCCESS) {
171 status = init_by_options(channel, options, optmask);
172 if (status != ARES_SUCCESS)
173 DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
174 ares_strerror(status)));
176 if (status == ARES_SUCCESS) {
177 status = init_by_environment(channel);
178 if (status != ARES_SUCCESS)
179 DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
180 ares_strerror(status)));
182 if (status == ARES_SUCCESS) {
183 status = init_by_resolv_conf(channel);
184 if (status != ARES_SUCCESS)
185 DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
186 ares_strerror(status)));
188 if (status == ARES_SUCCESS) {
189 status = init_by_defaults(channel);
190 if (status != ARES_SUCCESS)
191 DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
192 ares_strerror(status)));
195 /* Generate random key */
197 if (status == ARES_SUCCESS) {
198 status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
199 if (status == ARES_SUCCESS)
200 channel->next_id = ares__generate_new_id(&channel->id_key);
202 DEBUGF(fprintf(stderr, "Error: init_id_key failed: %s\n",
203 ares_strerror(status)));
206 if (status != ARES_SUCCESS)
208 /* Something failed; clean up memory we may have allocated. */
209 if (channel->servers)
210 free(channel->servers);
211 if (channel->domains)
213 for (i = 0; i < channel->ndomains; i++)
214 free(channel->domains[i]);
215 free(channel->domains);
217 if (channel->sortlist)
218 free(channel->sortlist);
220 free(channel->lookups);
225 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
226 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
227 channel->nservers = 1;
229 /* Initialize server states. */
230 for (i = 0; i < channel->nservers; i++)
232 server = &channel->servers[i];
233 server->udp_socket = ARES_SOCKET_BAD;
234 server->tcp_socket = ARES_SOCKET_BAD;
235 server->tcp_connection_generation = ++channel->tcp_connection_generation;
236 server->tcp_lenbuf_pos = 0;
237 server->tcp_buffer = NULL;
238 server->qhead = NULL;
239 server->qtail = NULL;
240 ares__init_list_head(&(server->queries_to_server));
241 server->channel = channel;
242 server->is_broken = 0;
245 *channelptr = channel;
249 /* Save options from initialized channel */
250 int ares_save_options(ares_channel channel, struct ares_options *options,
255 /* Zero everything out */
256 memset(options, 0, sizeof(struct ares_options));
258 if (!ARES_CONFIG_CHECK(channel))
261 (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TRIES|ARES_OPT_NDOTS|
262 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
263 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
264 ARES_OPT_SORTLIST|ARES_OPT_TIMEOUTMS);
266 /* Copy easy stuff */
267 options->flags = channel->flags;
269 /* We return full millisecond resolution but that's only because we don't
270 set the ARES_OPT_TIMEOUT anymore, only the new ARES_OPT_TIMEOUTMS */
271 options->timeout = channel->timeout;
272 options->tries = channel->tries;
273 options->ndots = channel->ndots;
274 options->udp_port = (unsigned short)channel->udp_port;
275 options->tcp_port = (unsigned short)channel->tcp_port;
276 options->sock_state_cb = channel->sock_state_cb;
277 options->sock_state_cb_data = channel->sock_state_cb_data;
280 if (channel->nservers) {
282 malloc(channel->nservers * sizeof(struct server_state));
283 if (!options->servers && channel->nservers != 0)
285 for (i = 0; i < channel->nservers; i++)
286 options->servers[i] = channel->servers[i].addr;
288 options->nservers = channel->nservers;
291 if (channel->ndomains) {
292 options->domains = malloc(channel->ndomains * sizeof(char *));
293 if (!options->domains)
296 for (i = 0; i < channel->ndomains; i++)
298 options->ndomains = i;
299 options->domains[i] = strdup(channel->domains[i]);
300 if (!options->domains[i])
304 options->ndomains = channel->ndomains;
307 if (channel->lookups) {
308 options->lookups = strdup(channel->lookups);
309 if (!options->lookups && channel->lookups)
314 if (channel->nsort) {
315 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
316 if (!options->sortlist)
318 for (i = 0; i < channel->nsort; i++)
320 memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
321 sizeof(struct apattern));
324 options->nsort = channel->nsort;
329 static int init_by_options(ares_channel channel,
330 const struct ares_options *options,
336 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
337 channel->flags = options->flags;
338 if ((optmask & ARES_OPT_TIMEOUTMS) && channel->timeout == -1)
339 channel->timeout = options->timeout;
340 else if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
341 channel->timeout = options->timeout * 1000;
342 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
343 channel->tries = options->tries;
344 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
345 channel->ndots = options->ndots;
346 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
347 channel->udp_port = options->udp_port;
348 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
349 channel->tcp_port = options->tcp_port;
350 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
352 channel->sock_state_cb = options->sock_state_cb;
353 channel->sock_state_cb_data = options->sock_state_cb_data;
355 if ((optmask & ARES_OPT_SOCK_SNDBUF)
356 && channel->socket_send_buffer_size == -1)
357 channel->socket_send_buffer_size = options->socket_send_buffer_size;
358 if ((optmask & ARES_OPT_SOCK_RCVBUF)
359 && channel->socket_receive_buffer_size == -1)
360 channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
362 /* Copy the servers, if given. */
363 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
365 /* Avoid zero size allocations at any cost */
366 if (options->nservers > 0)
369 malloc(options->nservers * sizeof(struct server_state));
370 if (!channel->servers)
372 for (i = 0; i < options->nservers; i++)
373 channel->servers[i].addr = options->servers[i];
375 channel->nservers = options->nservers;
378 /* Copy the domains, if given. Keep channel->ndomains consistent so
379 * we can clean up in case of error.
381 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
383 /* Avoid zero size allocations at any cost */
384 if (options->ndomains > 0)
386 channel->domains = malloc(options->ndomains * sizeof(char *));
387 if (!channel->domains)
389 for (i = 0; i < options->ndomains; i++)
391 channel->ndomains = i;
392 channel->domains[i] = strdup(options->domains[i]);
393 if (!channel->domains[i])
397 channel->ndomains = options->ndomains;
400 /* Set lookups, if given. */
401 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
403 channel->lookups = strdup(options->lookups);
404 if (!channel->lookups)
409 if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
411 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
412 if (!channel->sortlist)
414 for (i = 0; i < options->nsort; i++)
416 memcpy(&(channel->sortlist[i]), &(options->sortlist[i]), sizeof(struct apattern));
418 channel->nsort = options->nsort;
424 static int init_by_environment(ares_channel channel)
426 const char *localdomain, *res_options;
429 localdomain = getenv("LOCALDOMAIN");
430 if (localdomain && channel->ndomains == -1)
432 status = set_search(channel, localdomain);
433 if (status != ARES_SUCCESS)
437 res_options = getenv("RES_OPTIONS");
440 status = set_options(channel, res_options);
441 if (status != ARES_SUCCESS)
450 * Warning: returns a dynamically allocated buffer, the user MUST
451 * use free() if the function returns 1
453 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
455 /* Test for the size we need */
459 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
460 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
462 *obuf = malloc(size+1);
466 if (RegQueryValueEx(hKey, subkey, 0, NULL,
467 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
480 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
482 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
483 DWORD enum_size = 39;
487 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
488 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
493 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
496 rc = get_res_nt(hVal, subkey, obuf);
504 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
506 FIXED_INFO *fi = alloca (sizeof(*fi));
507 DWORD size = sizeof (*fi);
508 typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
509 get_net_param_func fpGetNetworkParams; /* available only on Win-98/2000+ */
511 IP_ADDR_STRING *ipAddr;
514 size_t ip_size = sizeof("255.255.255.255,")-1;
515 size_t left = ret_size;
522 handle = LoadLibrary ("iphlpapi.dll");
526 fpGetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
527 if (!fpGetNetworkParams)
530 res = (*fpGetNetworkParams) (fi, &size);
531 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
535 if (!fi || (*fpGetNetworkParams) (fi, &size) != ERROR_SUCCESS)
540 printf ("Host Name: %s\n", fi->HostName);
541 printf ("Domain Name: %s\n", fi->DomainName);
542 printf ("DNS Servers:\n"
543 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
545 if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
546 inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
549 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
550 left -= ret - ret_buf;
554 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
555 ipAddr = ipAddr->Next, i++)
557 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
559 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
560 left -= ret - ret_buf;
564 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
569 FreeLibrary (handle);
571 if (debug && left <= ip_size)
572 printf ("Too many nameservers. Truncating to %d addressess", count);
579 static int init_by_resolv_conf(ares_channel channel)
582 int status = -1, nservers = 0, nsort = 0;
583 struct server_state *servers = NULL;
584 struct apattern *sortlist = NULL;
589 NameServer info via IPHLPAPI (IP helper API):
590 GetNetworkParams() should be the trusted source for this.
591 Available in Win-98/2000 and later. If that fail, fall-back to
592 registry information.
596 On Windows 9X, the DNS server can be found in:
597 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
599 On Windows NT/2000/XP/2003:
600 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
602 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
604 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
607 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
618 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
621 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
623 status = config_nameserver(&servers, &nservers, buf);
624 if (status == ARES_SUCCESS)
631 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
635 RegOpenKeyEx(mykey, "Interfaces", 0,
636 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
637 if (get_res_nt(mykey, NAMESERVER, &line))
639 status = config_nameserver(&servers, &nservers, line);
642 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
644 status = config_nameserver(&servers, &nservers, line);
647 /* Try the interfaces */
648 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
650 status = config_nameserver(&servers, &nservers, line);
653 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
655 status = config_nameserver(&servers, &nservers, line);
665 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
669 if ((result = RegQueryValueEx(
670 mykey, NAMESERVER, NULL, &data_type,
673 ) == ERROR_SUCCESS ||
674 result == ERROR_MORE_DATA)
678 line = malloc(bytes+1);
679 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
680 (unsigned char *)line, &bytes) ==
683 status = config_nameserver(&servers, &nservers, line);
692 if (status == ARES_SUCCESS)
695 /* Catch the case when all the above checks fail (which happens when there
696 is no network card or the cable is unplugged) */
699 #elif defined(__riscos__)
701 /* Under RISC OS, name servers are listed in the
702 system variable Inet$Resolvers, space separated. */
704 line = getenv("Inet$Resolvers");
707 char *resolvers = strdup(line), *pos, *space;
714 space = strchr(pos, ' ');
717 status = config_nameserver(&servers, &nservers, pos);
718 if (status != ARES_SUCCESS)
723 if (status == ARES_SUCCESS)
729 #elif defined(WATT32)
733 for (i = 0; def_nameservers[i]; i++)
736 return ARES_SUCCESS; /* use localhost DNS server */
739 servers = calloc(sizeof(*servers), i);
743 for (i = 0; def_nameservers[i]; i++)
744 servers[i].addr.s_addr = htonl(def_nameservers[i]);
754 /* Don't read resolv.conf and friends if we don't have to */
755 if (ARES_CONFIG_CHECK(channel))
758 fp = fopen(PATH_RESOLV_CONF, "r");
760 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
762 if ((p = try_config(line, "domain")) && channel->ndomains == -1)
763 status = config_domain(channel, p);
764 else if ((p = try_config(line, "lookup")) && !channel->lookups)
765 status = config_lookup(channel, p, "bind", "file");
766 else if ((p = try_config(line, "search")) && channel->ndomains == -1)
767 status = set_search(channel, p);
768 else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
769 status = config_nameserver(&servers, &nservers, p);
770 else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
771 status = config_sortlist(&sortlist, &nsort, p);
772 else if ((p = try_config(line, "options")))
773 status = set_options(channel, p);
775 status = ARES_SUCCESS;
776 if (status != ARES_SUCCESS)
789 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
790 error, strerror(error)));
791 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
796 if ((status == ARES_EOF) && (!channel->lookups)) {
797 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
798 fp = fopen("/etc/nsswitch.conf", "r");
800 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
802 if ((p = try_config(line, "hosts:")) && !channel->lookups)
803 status = config_lookup(channel, p, "dns", "files");
815 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
816 error, strerror(error)));
817 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
823 if ((status == ARES_EOF) && (!channel->lookups)) {
824 /* Linux / GNU libc 2.x and possibly others have host.conf */
825 fp = fopen("/etc/host.conf", "r");
827 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
829 if ((p = try_config(line, "order")) && !channel->lookups)
830 status = config_lookup(channel, p, "bind", "hosts");
842 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
843 error, strerror(error)));
844 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
850 if ((status == ARES_EOF) && (!channel->lookups)) {
851 /* Tru64 uses /etc/svc.conf */
852 fp = fopen("/etc/svc.conf", "r");
854 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
856 if ((p = try_config(line, "hosts=")) && !channel->lookups)
857 status = config_lookup(channel, p, "bind", "local");
869 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
870 error, strerror(error)));
871 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
884 if (status != ARES_EOF)
888 if (sortlist != NULL)
893 /* If we got any name server entries, fill them in. */
899 channel->servers = servers;
900 channel->nservers = nservers;
903 /* If we got any sortlist entries, fill them in. */
906 channel->sortlist = sortlist;
907 channel->nsort = nsort;
913 static int init_by_defaults(ares_channel channel)
915 char *hostname = NULL;
916 int rc = ARES_SUCCESS;
918 if (channel->flags == -1)
920 if (channel->timeout == -1)
921 channel->timeout = DEFAULT_TIMEOUT;
922 if (channel->tries == -1)
923 channel->tries = DEFAULT_TRIES;
924 if (channel->ndots == -1)
926 if (channel->udp_port == -1)
927 channel->udp_port = htons(NAMESERVER_PORT);
928 if (channel->tcp_port == -1)
929 channel->tcp_port = htons(NAMESERVER_PORT);
931 if (channel->nservers == -1) {
932 /* If nobody specified servers, try a local named. */
933 channel->servers = malloc(sizeof(struct server_state));
934 if (!channel->servers) {
938 channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
939 channel->nservers = 1;
943 #define toolong(x) (x == -1) && ((ENAMETOOLONG == errno) || (EINVAL == errno))
945 #define toolong(x) (x == -1) && (EINVAL == errno)
948 if (channel->ndomains == -1) {
949 /* Derive a default domain search list from the kernel hostname,
950 * or set it to empty if the hostname isn't helpful.
955 hostname = malloc(len);
962 res = gethostname(hostname, len);
967 p = realloc(hostname, len);
982 channel->ndomains = 0; /* default to none */
983 if (strchr(hostname, '.')) {
984 /* a dot was found */
986 channel->domains = malloc(sizeof(char *));
987 if (!channel->domains) {
991 channel->domains[0] = strdup(strchr(hostname, '.') + 1);
992 if (!channel->domains[0]) {
996 channel->ndomains = 1;
1000 if (channel->nsort == -1) {
1001 channel->sortlist = NULL;
1005 if (!channel->lookups) {
1006 channel->lookups = strdup("fb");
1007 if (!channel->lookups)
1013 if(channel->servers)
1014 free(channel->servers);
1016 if(channel->domains && channel->domains[0])
1017 free(channel->domains[0]);
1018 if(channel->domains)
1019 free(channel->domains);
1020 if(channel->lookups)
1021 free(channel->lookups);
1031 static int config_domain(ares_channel channel, char *str)
1035 /* Set a single search domain. */
1037 while (*q && !ISSPACE(*q))
1040 return set_search(channel, str);
1043 static int config_lookup(ares_channel channel, const char *str,
1044 const char *bindch, const char *filech)
1046 char lookups[3], *l;
1049 /* Set the lookup order. Only the first letter of each work
1050 * is relevant, and it has to be "b" for DNS or "f" for the
1051 * host file. Ignore everything else.
1057 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
1058 if (*p == *bindch) *l++ = 'b';
1061 while (*p && !ISSPACE(*p) && (*p != ','))
1063 while (*p && (ISSPACE(*p) || (*p == ',')))
1067 channel->lookups = strdup(lookups);
1068 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1073 static int config_nameserver(struct server_state **servers, int *nservers,
1076 struct in_addr addr;
1077 struct server_state *newserv;
1078 /* On Windows, there may be more than one nameserver specified in the same
1079 * registry key, so we parse it as a space or comma seperated list.
1088 while (*p && !ISSPACE(*p) && *p != ',')
1097 /* Skip multiple spaces or trailing spaces */
1104 /* This is the part that actually sets the nameserver */
1105 addr.s_addr = inet_addr(begin);
1106 if (addr.s_addr == INADDR_NONE)
1108 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1111 newserv[*nservers].addr = addr;
1120 /* Add a nameserver entry, if this is a valid address. */
1121 addr.s_addr = inet_addr(str);
1122 if (addr.s_addr == INADDR_NONE)
1123 return ARES_SUCCESS;
1124 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1127 newserv[*nservers].addr = addr;
1131 return ARES_SUCCESS;
1135 static int config_sortlist(struct apattern **sortlist, int *nsort,
1138 struct apattern pat;
1141 /* Add sortlist entries. */
1142 while (*str && *str != ';')
1145 char ipbuf[16], ipbufpfx[32];
1146 /* Find just the IP */
1148 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1150 memcpy(ipbuf, str, (int)(q-str));
1151 ipbuf[(int)(q-str)] = '\0';
1152 /* Find the prefix */
1155 const char *str2 = q+1;
1156 while (*q && *q != ';' && !ISSPACE(*q))
1158 memcpy(ipbufpfx, str, (int)(q-str));
1159 ipbufpfx[(int)(q-str)] = '\0';
1164 /* Lets see if it is CIDR */
1165 /* First we'll try IPv6 */
1166 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1168 sizeof(pat.addr.addr6))) > 0)
1170 pat.type = PATTERN_CIDR;
1171 pat.mask.bits = (unsigned short)bits;
1172 pat.family = AF_INET6;
1173 if (!sortlist_alloc(sortlist, nsort, &pat))
1177 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addr.addr4,
1178 sizeof(pat.addr.addr4))) > 0)
1180 pat.type = PATTERN_CIDR;
1181 pat.mask.bits = (unsigned short)bits;
1182 pat.family = AF_INET;
1183 if (!sortlist_alloc(sortlist, nsort, &pat))
1186 /* See if it is just a regular IP */
1187 else if (ip_addr(ipbuf, (int)(q-str), &pat.addr.addr4) == 0)
1191 memcpy(ipbuf, str, (int)(q-str));
1192 ipbuf[(int)(q-str)] = '\0';
1193 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr.addr4) != 0)
1198 pat.family = AF_INET;
1199 pat.type = PATTERN_MASK;
1200 if (!sortlist_alloc(sortlist, nsort, &pat))
1205 while (*q && *q != ';' && !ISSPACE(*q))
1209 while (ISSPACE(*str))
1213 return ARES_SUCCESS;
1217 static int set_search(ares_channel channel, const char *str)
1222 if(channel->ndomains != -1) {
1223 /* if we already have some domains present, free them first */
1224 for(n=0; n < channel->ndomains; n++)
1225 free(channel->domains[n]);
1226 free(channel->domains);
1227 channel->domains = NULL;
1228 channel->ndomains = -1;
1231 /* Count the domains given. */
1236 while (*p && !ISSPACE(*p))
1245 channel->ndomains = 0;
1246 return ARES_SUCCESS;
1249 channel->domains = malloc(n * sizeof(char *));
1250 if (!channel->domains)
1253 /* Now copy the domains. */
1258 channel->ndomains = n;
1260 while (*q && !ISSPACE(*q))
1262 channel->domains[n] = malloc(q - p + 1);
1263 if (!channel->domains[n])
1265 memcpy(channel->domains[n], p, q - p);
1266 channel->domains[n][q - p] = 0;
1272 channel->ndomains = n;
1274 return ARES_SUCCESS;
1277 static int set_options(ares_channel channel, const char *str)
1279 const char *p, *q, *val;
1285 while (*q && !ISSPACE(*q))
1287 val = try_option(p, q, "ndots:");
1288 if (val && channel->ndots == -1)
1289 channel->ndots = atoi(val);
1290 val = try_option(p, q, "retrans:");
1291 if (val && channel->timeout == -1)
1292 channel->timeout = atoi(val);
1293 val = try_option(p, q, "retry:");
1294 if (val && channel->tries == -1)
1295 channel->tries = atoi(val);
1301 return ARES_SUCCESS;
1305 static char *try_config(char *s, const char *opt)
1313 /* no line or no option */
1316 /* trim line comment */
1317 for (i = 0; s[i] && s[i] != '#'; ++i);
1320 /* trim trailing whitespace */
1321 for (j = i-1; j >= 0 && ISSPACE(s[j]); --j);
1324 /* skip leading whitespace */
1325 for (i = 0; s[i] && ISSPACE(s[i]); ++i);
1332 if ((len = strlen(opt)) == 0)
1336 if (strncmp(p, opt, len) != 0)
1337 /* line and option do not match */
1340 /* skip over given option name */
1344 /* no option value */
1347 if ((opt[len-1] != ':') && (opt[len-1] != '=') && !ISSPACE(*p))
1348 /* whitespace between option name and value is mandatory
1349 for given option names which do not end with ':' or '=' */
1352 /* skip over whitespace */
1353 while (*p && ISSPACE(*p))
1357 /* no option value */
1360 /* return pointer to option value */
1365 static const char *try_option(const char *p, const char *q, const char *opt)
1367 size_t len = strlen(opt);
1368 return ((size_t)(q - p) > len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1372 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1373 struct apattern *pat)
1375 struct apattern *newsort;
1376 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1379 newsort[*nsort] = *pat;
1380 *sortlist = newsort;
1385 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1388 /* Four octets and three periods yields at most 15 characters. */
1392 addr->s_addr = inet_addr(ipbuf);
1393 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1398 static void natural_mask(struct apattern *pat)
1400 struct in_addr addr;
1402 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1405 addr.s_addr = ntohl(pat->addr.addr4.s_addr);
1407 /* This is out of date in the CIDR world, but some people might
1410 if (IN_CLASSA(addr.s_addr))
1411 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSA_NET);
1412 else if (IN_CLASSB(addr.s_addr))
1413 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSB_NET);
1415 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSC_NET);
1418 /* initialize an rc4 key. If possible a cryptographically secure random key
1419 is generated using a suitable function (for example win32's RtlGenRandom as
1421 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1422 otherwise the code defaults to cross-platform albeit less secure mechanism
1425 static void randomize_key(unsigned char* key,int key_data_len)
1430 HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1432 BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1433 (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1434 if (pfn && pfn(key,key_data_len) )
1441 FILE *f = fopen(RANDOM_FILE, "rb");
1443 counter = fread(key, 1, key_data_len, f);
1449 if ( !randomized ) {
1450 for (;counter<key_data_len;counter++)
1451 key[counter]=(unsigned char)(rand() % 256);
1455 static int init_id_key(rc4_key* key,int key_data_len)
1457 unsigned char index1;
1458 unsigned char index2;
1459 unsigned char* state;
1461 unsigned char *key_data_ptr = 0;
1463 key_data_ptr = calloc(1,key_data_len);
1467 state = &key->state[0];
1468 for(counter = 0; counter < 256; counter++)
1469 /* unnecessary AND but it keeps some compilers happier */
1470 state[counter] = (unsigned char)(counter & 0xff);
1471 randomize_key(key->state,key_data_len);
1476 for(counter = 0; counter < 256; counter++)
1478 index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1480 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1482 index1 = (unsigned char)((index1 + 1) % key_data_len);
1485 return ARES_SUCCESS;
1488 short ares__generate_new_id(rc4_key* key)
1491 ares__rc4(key, (unsigned char *)&r, sizeof(r));