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)
26 #ifdef HAVE_SYS_PARAM_H
27 #include <sys/param.h>
30 #ifdef HAVE_SYS_TIME_H
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
38 #ifdef HAVE_NETINET_IN_H
39 #include <netinet/in.h>
46 #ifdef HAVE_ARPA_INET_H
47 #include <arpa/inet.h>
50 #ifdef HAVE_ARPA_NAMESER_H
51 # include <arpa/nameser.h>
55 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
56 # include <arpa/nameser_compat.h>
70 #include "inet_net_pton.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 channel = malloc(sizeof(struct ares_channeldata));
140 /* Set everything to distinguished values so we know they haven't
144 channel->timeout = -1;
147 channel->rotate = -1;
148 channel->udp_port = -1;
149 channel->tcp_port = -1;
150 channel->socket_send_buffer_size = -1;
151 channel->socket_receive_buffer_size = -1;
152 channel->nservers = -1;
153 channel->ndomains = -1;
155 channel->tcp_connection_generation = 0;
156 channel->lookups = NULL;
157 channel->domains = NULL;
158 channel->sortlist = NULL;
159 channel->servers = NULL;
160 channel->sock_state_cb = NULL;
161 channel->sock_state_cb_data = NULL;
163 channel->last_server = 0;
164 channel->last_timeout_processed = (time_t)now.tv_sec;
166 /* Initialize our lists of queries */
167 ares__init_list_head(&(channel->all_queries));
168 for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
170 ares__init_list_head(&(channel->queries_by_qid[i]));
172 for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
174 ares__init_list_head(&(channel->queries_by_timeout[i]));
177 /* Initialize configuration by each of the four sources, from highest
178 * precedence to lowest.
181 if (status == ARES_SUCCESS) {
182 status = init_by_options(channel, options, optmask);
183 if (status != ARES_SUCCESS)
184 DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
185 ares_strerror(status)));
187 if (status == ARES_SUCCESS) {
188 status = init_by_environment(channel);
189 if (status != ARES_SUCCESS)
190 DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
191 ares_strerror(status)));
193 if (status == ARES_SUCCESS) {
194 status = init_by_resolv_conf(channel);
195 if (status != ARES_SUCCESS)
196 DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
197 ares_strerror(status)));
199 if (status == ARES_SUCCESS) {
200 status = init_by_defaults(channel);
201 if (status != ARES_SUCCESS)
202 DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
203 ares_strerror(status)));
206 /* Generate random key */
208 if (status == ARES_SUCCESS) {
209 status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
210 if (status == ARES_SUCCESS)
211 channel->next_id = ares__generate_new_id(&channel->id_key);
213 DEBUGF(fprintf(stderr, "Error: init_id_key failed: %s\n",
214 ares_strerror(status)));
217 if (status != ARES_SUCCESS)
219 /* Something failed; clean up memory we may have allocated. */
220 if (channel->servers)
221 free(channel->servers);
222 if (channel->domains)
224 for (i = 0; i < channel->ndomains; i++)
225 free(channel->domains[i]);
226 free(channel->domains);
228 if (channel->sortlist)
229 free(channel->sortlist);
231 free(channel->lookups);
236 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
237 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
238 channel->nservers = 1;
240 /* Initialize server states. */
241 for (i = 0; i < channel->nservers; i++)
243 server = &channel->servers[i];
244 server->udp_socket = ARES_SOCKET_BAD;
245 server->tcp_socket = ARES_SOCKET_BAD;
246 server->tcp_connection_generation = ++channel->tcp_connection_generation;
247 server->tcp_lenbuf_pos = 0;
248 server->tcp_buffer = NULL;
249 server->qhead = NULL;
250 server->qtail = NULL;
251 ares__init_list_head(&(server->queries_to_server));
252 server->channel = channel;
253 server->is_broken = 0;
256 *channelptr = channel;
260 /* Save options from initialized channel */
261 int ares_save_options(ares_channel channel, struct ares_options *options,
266 /* Zero everything out */
267 memset(options, 0, sizeof(struct ares_options));
269 if (!ARES_CONFIG_CHECK(channel))
272 (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TRIES|ARES_OPT_NDOTS|
273 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
274 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
275 ARES_OPT_SORTLIST|ARES_OPT_TIMEOUTMS);
277 /* Copy easy stuff */
278 options->flags = channel->flags;
280 /* We return full millisecond resolution but that's only because we don't
281 set the ARES_OPT_TIMEOUT anymore, only the new ARES_OPT_TIMEOUTMS */
282 options->timeout = channel->timeout;
283 options->tries = channel->tries;
284 options->ndots = channel->ndots;
285 options->udp_port = (unsigned short)channel->udp_port;
286 options->tcp_port = (unsigned short)channel->tcp_port;
287 options->sock_state_cb = channel->sock_state_cb;
288 options->sock_state_cb_data = channel->sock_state_cb_data;
291 if (channel->nservers) {
293 malloc(channel->nservers * sizeof(struct server_state));
294 if (!options->servers && channel->nservers != 0)
296 for (i = 0; i < channel->nservers; i++)
297 options->servers[i] = channel->servers[i].addr;
299 options->nservers = channel->nservers;
302 if (channel->ndomains) {
303 options->domains = malloc(channel->ndomains * sizeof(char *));
304 if (!options->domains)
307 for (i = 0; i < channel->ndomains; i++)
309 options->ndomains = i;
310 options->domains[i] = strdup(channel->domains[i]);
311 if (!options->domains[i])
315 options->ndomains = channel->ndomains;
318 if (channel->lookups) {
319 options->lookups = strdup(channel->lookups);
320 if (!options->lookups && channel->lookups)
325 if (channel->nsort) {
326 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
327 if (!options->sortlist)
329 for (i = 0; i < channel->nsort; i++)
331 memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
332 sizeof(struct apattern));
335 options->nsort = channel->nsort;
340 static int init_by_options(ares_channel channel,
341 const struct ares_options *options,
347 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
348 channel->flags = options->flags;
349 if ((optmask & ARES_OPT_TIMEOUTMS) && channel->timeout == -1)
350 channel->timeout = options->timeout;
351 else if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
352 channel->timeout = options->timeout * 1000;
353 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
354 channel->tries = options->tries;
355 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
356 channel->ndots = options->ndots;
357 if ((optmask & ARES_OPT_ROTATE) && channel->rotate == -1)
358 channel->rotate = options->rotate;
359 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
360 channel->udp_port = options->udp_port;
361 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
362 channel->tcp_port = options->tcp_port;
363 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
365 channel->sock_state_cb = options->sock_state_cb;
366 channel->sock_state_cb_data = options->sock_state_cb_data;
368 if ((optmask & ARES_OPT_SOCK_SNDBUF)
369 && channel->socket_send_buffer_size == -1)
370 channel->socket_send_buffer_size = options->socket_send_buffer_size;
371 if ((optmask & ARES_OPT_SOCK_RCVBUF)
372 && channel->socket_receive_buffer_size == -1)
373 channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
375 /* Copy the servers, if given. */
376 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
378 /* Avoid zero size allocations at any cost */
379 if (options->nservers > 0)
382 malloc(options->nservers * sizeof(struct server_state));
383 if (!channel->servers)
385 for (i = 0; i < options->nservers; i++)
386 channel->servers[i].addr = options->servers[i];
388 channel->nservers = options->nservers;
391 /* Copy the domains, if given. Keep channel->ndomains consistent so
392 * we can clean up in case of error.
394 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
396 /* Avoid zero size allocations at any cost */
397 if (options->ndomains > 0)
399 channel->domains = malloc(options->ndomains * sizeof(char *));
400 if (!channel->domains)
402 for (i = 0; i < options->ndomains; i++)
404 channel->ndomains = i;
405 channel->domains[i] = strdup(options->domains[i]);
406 if (!channel->domains[i])
410 channel->ndomains = options->ndomains;
413 /* Set lookups, if given. */
414 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
416 channel->lookups = strdup(options->lookups);
417 if (!channel->lookups)
422 if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
424 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
425 if (!channel->sortlist)
427 for (i = 0; i < options->nsort; i++)
429 memcpy(&(channel->sortlist[i]), &(options->sortlist[i]), sizeof(struct apattern));
431 channel->nsort = options->nsort;
437 static int init_by_environment(ares_channel channel)
439 const char *localdomain, *res_options;
442 localdomain = getenv("LOCALDOMAIN");
443 if (localdomain && channel->ndomains == -1)
445 status = set_search(channel, localdomain);
446 if (status != ARES_SUCCESS)
450 res_options = getenv("RES_OPTIONS");
453 status = set_options(channel, res_options);
454 if (status != ARES_SUCCESS)
463 * Warning: returns a dynamically allocated buffer, the user MUST
464 * use free() if the function returns 1
466 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
468 /* Test for the size we need */
472 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
473 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
475 *obuf = malloc(size+1);
479 if (RegQueryValueEx(hKey, subkey, 0, NULL,
480 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
493 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
495 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
496 DWORD enum_size = 39;
500 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
501 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
506 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
509 rc = get_res_nt(hVal, subkey, obuf);
517 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
519 FIXED_INFO *fi = alloca (sizeof(*fi));
520 DWORD size = sizeof (*fi);
521 typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
522 get_net_param_func fpGetNetworkParams; /* available only on Win-98/2000+ */
524 IP_ADDR_STRING *ipAddr;
527 size_t ip_size = sizeof("255.255.255.255,")-1;
528 size_t left = ret_size;
535 handle = LoadLibrary ("iphlpapi.dll");
539 fpGetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
540 if (!fpGetNetworkParams)
543 res = (*fpGetNetworkParams) (fi, &size);
544 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
548 if (!fi || (*fpGetNetworkParams) (fi, &size) != ERROR_SUCCESS)
553 printf ("Host Name: %s\n", fi->HostName);
554 printf ("Domain Name: %s\n", fi->DomainName);
555 printf ("DNS Servers:\n"
556 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
558 if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
559 inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
562 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
563 left -= ret - ret_buf;
567 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
568 ipAddr = ipAddr->Next, i++)
570 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
572 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
573 left -= ret - ret_buf;
577 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
582 FreeLibrary (handle);
584 if (debug && left <= ip_size)
585 printf ("Too many nameservers. Truncating to %d addressess", count);
592 static int init_by_resolv_conf(ares_channel channel)
595 int status = -1, nservers = 0, nsort = 0;
596 struct server_state *servers = NULL;
597 struct apattern *sortlist = NULL;
602 NameServer info via IPHLPAPI (IP helper API):
603 GetNetworkParams() should be the trusted source for this.
604 Available in Win-98/2000 and later. If that fail, fall-back to
605 registry information.
609 On Windows 9X, the DNS server can be found in:
610 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
612 On Windows NT/2000/XP/2003:
613 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
615 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
617 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
620 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
631 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
634 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
636 status = config_nameserver(&servers, &nservers, buf);
637 if (status == ARES_SUCCESS)
644 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
648 RegOpenKeyEx(mykey, "Interfaces", 0,
649 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
650 if (get_res_nt(mykey, NAMESERVER, &line))
652 status = config_nameserver(&servers, &nservers, line);
655 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
657 status = config_nameserver(&servers, &nservers, line);
660 /* Try the interfaces */
661 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
663 status = config_nameserver(&servers, &nservers, line);
666 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
668 status = config_nameserver(&servers, &nservers, line);
678 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
682 if ((result = RegQueryValueEx(
683 mykey, NAMESERVER, NULL, &data_type,
686 ) == ERROR_SUCCESS ||
687 result == ERROR_MORE_DATA)
691 line = malloc(bytes+1);
692 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
693 (unsigned char *)line, &bytes) ==
696 status = config_nameserver(&servers, &nservers, line);
705 if (status == ARES_SUCCESS)
708 /* Catch the case when all the above checks fail (which happens when there
709 is no network card or the cable is unplugged) */
712 #elif defined(__riscos__)
714 /* Under RISC OS, name servers are listed in the
715 system variable Inet$Resolvers, space separated. */
717 line = getenv("Inet$Resolvers");
720 char *resolvers = strdup(line), *pos, *space;
727 space = strchr(pos, ' ');
730 status = config_nameserver(&servers, &nservers, pos);
731 if (status != ARES_SUCCESS)
736 if (status == ARES_SUCCESS)
742 #elif defined(WATT32)
746 for (i = 0; def_nameservers[i]; i++)
749 return ARES_SUCCESS; /* use localhost DNS server */
752 servers = calloc(sizeof(*servers), i);
756 for (i = 0; def_nameservers[i]; i++)
757 servers[i].addr.s_addr = htonl(def_nameservers[i]);
767 /* Don't read resolv.conf and friends if we don't have to */
768 if (ARES_CONFIG_CHECK(channel))
771 fp = fopen(PATH_RESOLV_CONF, "r");
773 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
775 if ((p = try_config(line, "domain")) && channel->ndomains == -1)
776 status = config_domain(channel, p);
777 else if ((p = try_config(line, "lookup")) && !channel->lookups)
778 status = config_lookup(channel, p, "bind", "file");
779 else if ((p = try_config(line, "search")) && channel->ndomains == -1)
780 status = set_search(channel, p);
781 else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
782 status = config_nameserver(&servers, &nservers, p);
783 else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
784 status = config_sortlist(&sortlist, &nsort, p);
785 else if ((p = try_config(line, "options")))
786 status = set_options(channel, p);
788 status = ARES_SUCCESS;
789 if (status != ARES_SUCCESS)
802 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
803 error, strerror(error)));
804 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
809 if ((status == ARES_EOF) && (!channel->lookups)) {
810 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
811 fp = fopen("/etc/nsswitch.conf", "r");
813 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
815 if ((p = try_config(line, "hosts:")) && !channel->lookups)
816 status = config_lookup(channel, p, "dns", "files");
828 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
829 error, strerror(error)));
830 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
836 if ((status == ARES_EOF) && (!channel->lookups)) {
837 /* Linux / GNU libc 2.x and possibly others have host.conf */
838 fp = fopen("/etc/host.conf", "r");
840 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
842 if ((p = try_config(line, "order")) && !channel->lookups)
843 status = config_lookup(channel, p, "bind", "hosts");
855 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
856 error, strerror(error)));
857 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
863 if ((status == ARES_EOF) && (!channel->lookups)) {
864 /* Tru64 uses /etc/svc.conf */
865 fp = fopen("/etc/svc.conf", "r");
867 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
869 if ((p = try_config(line, "hosts=")) && !channel->lookups)
870 status = config_lookup(channel, p, "bind", "local");
882 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
883 error, strerror(error)));
884 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
897 if (status != ARES_EOF)
901 if (sortlist != NULL)
906 /* If we got any name server entries, fill them in. */
912 channel->servers = servers;
913 channel->nservers = nservers;
916 /* If we got any sortlist entries, fill them in. */
919 channel->sortlist = sortlist;
920 channel->nsort = nsort;
926 static int init_by_defaults(ares_channel channel)
928 char *hostname = NULL;
929 int rc = ARES_SUCCESS;
931 if (channel->flags == -1)
933 if (channel->timeout == -1)
934 channel->timeout = DEFAULT_TIMEOUT;
935 if (channel->tries == -1)
936 channel->tries = DEFAULT_TRIES;
937 if (channel->ndots == -1)
939 if (channel->rotate == -1)
941 if (channel->udp_port == -1)
942 channel->udp_port = htons(NAMESERVER_PORT);
943 if (channel->tcp_port == -1)
944 channel->tcp_port = htons(NAMESERVER_PORT);
946 if (channel->nservers == -1) {
947 /* If nobody specified servers, try a local named. */
948 channel->servers = malloc(sizeof(struct server_state));
949 if (!channel->servers) {
953 channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
954 channel->nservers = 1;
958 #define toolong(x) (x == -1) && ((ENAMETOOLONG == errno) || (EINVAL == errno))
960 #define toolong(x) (x == -1) && (EINVAL == errno)
963 if (channel->ndomains == -1) {
964 /* Derive a default domain search list from the kernel hostname,
965 * or set it to empty if the hostname isn't helpful.
970 hostname = malloc(len);
977 res = gethostname(hostname, len);
982 p = realloc(hostname, len);
997 channel->ndomains = 0; /* default to none */
998 if (strchr(hostname, '.')) {
999 /* a dot was found */
1001 channel->domains = malloc(sizeof(char *));
1002 if (!channel->domains) {
1006 channel->domains[0] = strdup(strchr(hostname, '.') + 1);
1007 if (!channel->domains[0]) {
1011 channel->ndomains = 1;
1015 if (channel->nsort == -1) {
1016 channel->sortlist = NULL;
1020 if (!channel->lookups) {
1021 channel->lookups = strdup("fb");
1022 if (!channel->lookups)
1028 if(channel->servers)
1029 free(channel->servers);
1031 if(channel->domains && channel->domains[0])
1032 free(channel->domains[0]);
1033 if(channel->domains)
1034 free(channel->domains);
1035 if(channel->lookups)
1036 free(channel->lookups);
1046 static int config_domain(ares_channel channel, char *str)
1050 /* Set a single search domain. */
1052 while (*q && !ISSPACE(*q))
1055 return set_search(channel, str);
1058 static int config_lookup(ares_channel channel, const char *str,
1059 const char *bindch, const char *filech)
1061 char lookups[3], *l;
1064 /* Set the lookup order. Only the first letter of each work
1065 * is relevant, and it has to be "b" for DNS or "f" for the
1066 * host file. Ignore everything else.
1072 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
1073 if (*p == *bindch) *l++ = 'b';
1076 while (*p && !ISSPACE(*p) && (*p != ','))
1078 while (*p && (ISSPACE(*p) || (*p == ',')))
1082 channel->lookups = strdup(lookups);
1083 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1088 static int config_nameserver(struct server_state **servers, int *nservers,
1091 struct in_addr addr;
1092 struct server_state *newserv;
1093 /* On Windows, there may be more than one nameserver specified in the same
1094 * registry key, so we parse it as a space or comma seperated list.
1103 while (*p && !ISSPACE(*p) && *p != ',')
1112 /* Skip multiple spaces or trailing spaces */
1119 /* This is the part that actually sets the nameserver */
1120 addr.s_addr = inet_addr(begin);
1121 if (addr.s_addr == INADDR_NONE)
1123 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1126 newserv[*nservers].addr = addr;
1135 /* Add a nameserver entry, if this is a valid address. */
1136 addr.s_addr = inet_addr(str);
1137 if (addr.s_addr == INADDR_NONE)
1138 return ARES_SUCCESS;
1139 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1142 newserv[*nservers].addr = addr;
1146 return ARES_SUCCESS;
1150 static int config_sortlist(struct apattern **sortlist, int *nsort,
1153 struct apattern pat;
1156 /* Add sortlist entries. */
1157 while (*str && *str != ';')
1160 char ipbuf[16], ipbufpfx[32];
1161 /* Find just the IP */
1163 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1165 memcpy(ipbuf, str, (int)(q-str));
1166 ipbuf[(int)(q-str)] = '\0';
1167 /* Find the prefix */
1170 const char *str2 = q+1;
1171 while (*q && *q != ';' && !ISSPACE(*q))
1173 memcpy(ipbufpfx, str, (int)(q-str));
1174 ipbufpfx[(int)(q-str)] = '\0';
1179 /* Lets see if it is CIDR */
1180 /* First we'll try IPv6 */
1181 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1183 sizeof(pat.addr.addr6))) > 0)
1185 pat.type = PATTERN_CIDR;
1186 pat.mask.bits = (unsigned short)bits;
1187 pat.family = AF_INET6;
1188 if (!sortlist_alloc(sortlist, nsort, &pat))
1192 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addr.addr4,
1193 sizeof(pat.addr.addr4))) > 0)
1195 pat.type = PATTERN_CIDR;
1196 pat.mask.bits = (unsigned short)bits;
1197 pat.family = AF_INET;
1198 if (!sortlist_alloc(sortlist, nsort, &pat))
1201 /* See if it is just a regular IP */
1202 else if (ip_addr(ipbuf, (int)(q-str), &pat.addr.addr4) == 0)
1206 memcpy(ipbuf, str, (int)(q-str));
1207 ipbuf[(int)(q-str)] = '\0';
1208 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr.addr4) != 0)
1213 pat.family = AF_INET;
1214 pat.type = PATTERN_MASK;
1215 if (!sortlist_alloc(sortlist, nsort, &pat))
1220 while (*q && *q != ';' && !ISSPACE(*q))
1224 while (ISSPACE(*str))
1228 return ARES_SUCCESS;
1232 static int set_search(ares_channel channel, const char *str)
1237 if(channel->ndomains != -1) {
1238 /* if we already have some domains present, free them first */
1239 for(n=0; n < channel->ndomains; n++)
1240 free(channel->domains[n]);
1241 free(channel->domains);
1242 channel->domains = NULL;
1243 channel->ndomains = -1;
1246 /* Count the domains given. */
1251 while (*p && !ISSPACE(*p))
1260 channel->ndomains = 0;
1261 return ARES_SUCCESS;
1264 channel->domains = malloc(n * sizeof(char *));
1265 if (!channel->domains)
1268 /* Now copy the domains. */
1273 channel->ndomains = n;
1275 while (*q && !ISSPACE(*q))
1277 channel->domains[n] = malloc(q - p + 1);
1278 if (!channel->domains[n])
1280 memcpy(channel->domains[n], p, q - p);
1281 channel->domains[n][q - p] = 0;
1287 channel->ndomains = n;
1289 return ARES_SUCCESS;
1292 static int set_options(ares_channel channel, const char *str)
1294 const char *p, *q, *val;
1300 while (*q && !ISSPACE(*q))
1302 val = try_option(p, q, "ndots:");
1303 if (val && channel->ndots == -1)
1304 channel->ndots = atoi(val);
1305 val = try_option(p, q, "retrans:");
1306 if (val && channel->timeout == -1)
1307 channel->timeout = atoi(val);
1308 val = try_option(p, q, "retry:");
1309 if (val && channel->tries == -1)
1310 channel->tries = atoi(val);
1311 val = try_option(p, q, "rotate");
1312 if (val && channel->rotate == -1)
1313 channel->rotate = 1;
1319 return ARES_SUCCESS;
1323 static char *try_config(char *s, const char *opt)
1331 /* no line or no option */
1334 /* trim line comment */
1335 for (i = 0; s[i] && s[i] != '#'; ++i);
1338 /* trim trailing whitespace */
1339 for (j = i-1; j >= 0 && ISSPACE(s[j]); --j);
1342 /* skip leading whitespace */
1343 for (i = 0; s[i] && ISSPACE(s[i]); ++i);
1350 if ((len = strlen(opt)) == 0)
1354 if (strncmp(p, opt, len) != 0)
1355 /* line and option do not match */
1358 /* skip over given option name */
1362 /* no option value */
1365 if ((opt[len-1] != ':') && (opt[len-1] != '=') && !ISSPACE(*p))
1366 /* whitespace between option name and value is mandatory
1367 for given option names which do not end with ':' or '=' */
1370 /* skip over whitespace */
1371 while (*p && ISSPACE(*p))
1375 /* no option value */
1378 /* return pointer to option value */
1383 static const char *try_option(const char *p, const char *q, const char *opt)
1385 size_t len = strlen(opt);
1386 return ((size_t)(q - p) >= len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1390 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1391 struct apattern *pat)
1393 struct apattern *newsort;
1394 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1397 newsort[*nsort] = *pat;
1398 *sortlist = newsort;
1403 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1406 /* Four octets and three periods yields at most 15 characters. */
1410 addr->s_addr = inet_addr(ipbuf);
1411 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1416 static void natural_mask(struct apattern *pat)
1418 struct in_addr addr;
1420 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1423 addr.s_addr = ntohl(pat->addr.addr4.s_addr);
1425 /* This is out of date in the CIDR world, but some people might
1428 if (IN_CLASSA(addr.s_addr))
1429 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSA_NET);
1430 else if (IN_CLASSB(addr.s_addr))
1431 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSB_NET);
1433 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSC_NET);
1436 /* initialize an rc4 key. If possible a cryptographically secure random key
1437 is generated using a suitable function (for example win32's RtlGenRandom as
1439 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1440 otherwise the code defaults to cross-platform albeit less secure mechanism
1443 static void randomize_key(unsigned char* key,int key_data_len)
1448 HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1450 BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1451 (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1452 if (pfn && pfn(key,key_data_len) )
1459 FILE *f = fopen(RANDOM_FILE, "rb");
1461 counter = fread(key, 1, key_data_len, f);
1467 if ( !randomized ) {
1468 for (;counter<key_data_len;counter++)
1469 key[counter]=(unsigned char)(rand() % 256);
1473 static int init_id_key(rc4_key* key,int key_data_len)
1475 unsigned char index1;
1476 unsigned char index2;
1477 unsigned char* state;
1479 unsigned char *key_data_ptr = 0;
1481 key_data_ptr = calloc(1,key_data_len);
1485 state = &key->state[0];
1486 for(counter = 0; counter < 256; counter++)
1487 /* unnecessary AND but it keeps some compilers happier */
1488 state[counter] = (unsigned char)(counter & 0xff);
1489 randomize_key(key->state,key_data_len);
1494 for(counter = 0; counter < 256; counter++)
1496 index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1498 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1500 index1 = (unsigned char)((index1 + 1) % key_data_len);
1503 return ARES_SUCCESS;
1506 short ares__generate_new_id(rc4_key* key)
1509 ares__rc4(key, (unsigned char *)&r, sizeof(r));