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.
969 channel->ndomains = 0; /* default to none */
971 #ifdef HAVE_GETHOSTNAME
972 hostname = malloc(len);
979 res = gethostname(hostname, len);
984 p = realloc(hostname, len);
999 if (strchr(hostname, '.')) {
1000 /* a dot was found */
1002 channel->domains = malloc(sizeof(char *));
1003 if (!channel->domains) {
1007 channel->domains[0] = strdup(strchr(hostname, '.') + 1);
1008 if (!channel->domains[0]) {
1012 channel->ndomains = 1;
1017 if (channel->nsort == -1) {
1018 channel->sortlist = NULL;
1022 if (!channel->lookups) {
1023 channel->lookups = strdup("fb");
1024 if (!channel->lookups)
1030 if(channel->servers)
1031 free(channel->servers);
1033 if(channel->domains && channel->domains[0])
1034 free(channel->domains[0]);
1035 if(channel->domains)
1036 free(channel->domains);
1037 if(channel->lookups)
1038 free(channel->lookups);
1048 static int config_domain(ares_channel channel, char *str)
1052 /* Set a single search domain. */
1054 while (*q && !ISSPACE(*q))
1057 return set_search(channel, str);
1060 static int config_lookup(ares_channel channel, const char *str,
1061 const char *bindch, const char *filech)
1063 char lookups[3], *l;
1066 /* Set the lookup order. Only the first letter of each work
1067 * is relevant, and it has to be "b" for DNS or "f" for the
1068 * host file. Ignore everything else.
1074 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
1075 if (*p == *bindch) *l++ = 'b';
1078 while (*p && !ISSPACE(*p) && (*p != ','))
1080 while (*p && (ISSPACE(*p) || (*p == ',')))
1084 channel->lookups = strdup(lookups);
1085 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1090 static int config_nameserver(struct server_state **servers, int *nservers,
1093 struct in_addr addr;
1094 struct server_state *newserv;
1095 /* On Windows, there may be more than one nameserver specified in the same
1096 * registry key, so we parse it as a space or comma seperated list.
1105 while (*p && !ISSPACE(*p) && *p != ',')
1114 /* Skip multiple spaces or trailing spaces */
1121 /* This is the part that actually sets the nameserver */
1122 addr.s_addr = inet_addr(begin);
1123 if (addr.s_addr == INADDR_NONE)
1125 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1128 newserv[*nservers].addr = addr;
1137 /* Add a nameserver entry, if this is a valid address. */
1138 addr.s_addr = inet_addr(str);
1139 if (addr.s_addr == INADDR_NONE)
1140 return ARES_SUCCESS;
1141 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1144 newserv[*nservers].addr = addr;
1148 return ARES_SUCCESS;
1152 static int config_sortlist(struct apattern **sortlist, int *nsort,
1155 struct apattern pat;
1158 /* Add sortlist entries. */
1159 while (*str && *str != ';')
1162 char ipbuf[16], ipbufpfx[32];
1163 /* Find just the IP */
1165 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1167 memcpy(ipbuf, str, (int)(q-str));
1168 ipbuf[(int)(q-str)] = '\0';
1169 /* Find the prefix */
1172 const char *str2 = q+1;
1173 while (*q && *q != ';' && !ISSPACE(*q))
1175 memcpy(ipbufpfx, str, (int)(q-str));
1176 ipbufpfx[(int)(q-str)] = '\0';
1181 /* Lets see if it is CIDR */
1182 /* First we'll try IPv6 */
1183 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1185 sizeof(pat.addrV6))) > 0)
1187 pat.type = PATTERN_CIDR;
1188 pat.mask.bits = (unsigned short)bits;
1189 pat.family = AF_INET6;
1190 if (!sortlist_alloc(sortlist, nsort, &pat))
1194 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addrV4,
1195 sizeof(pat.addrV4))) > 0)
1197 pat.type = PATTERN_CIDR;
1198 pat.mask.bits = (unsigned short)bits;
1199 pat.family = AF_INET;
1200 if (!sortlist_alloc(sortlist, nsort, &pat))
1203 /* See if it is just a regular IP */
1204 else if (ip_addr(ipbuf, (int)(q-str), &pat.addrV4) == 0)
1208 memcpy(ipbuf, str, (int)(q-str));
1209 ipbuf[(int)(q-str)] = '\0';
1210 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr4) != 0)
1215 pat.family = AF_INET;
1216 pat.type = PATTERN_MASK;
1217 if (!sortlist_alloc(sortlist, nsort, &pat))
1222 while (*q && *q != ';' && !ISSPACE(*q))
1226 while (ISSPACE(*str))
1230 return ARES_SUCCESS;
1234 static int set_search(ares_channel channel, const char *str)
1239 if(channel->ndomains != -1) {
1240 /* if we already have some domains present, free them first */
1241 for(n=0; n < channel->ndomains; n++)
1242 free(channel->domains[n]);
1243 free(channel->domains);
1244 channel->domains = NULL;
1245 channel->ndomains = -1;
1248 /* Count the domains given. */
1253 while (*p && !ISSPACE(*p))
1262 channel->ndomains = 0;
1263 return ARES_SUCCESS;
1266 channel->domains = malloc(n * sizeof(char *));
1267 if (!channel->domains)
1270 /* Now copy the domains. */
1275 channel->ndomains = n;
1277 while (*q && !ISSPACE(*q))
1279 channel->domains[n] = malloc(q - p + 1);
1280 if (!channel->domains[n])
1282 memcpy(channel->domains[n], p, q - p);
1283 channel->domains[n][q - p] = 0;
1289 channel->ndomains = n;
1291 return ARES_SUCCESS;
1294 static int set_options(ares_channel channel, const char *str)
1296 const char *p, *q, *val;
1302 while (*q && !ISSPACE(*q))
1304 val = try_option(p, q, "ndots:");
1305 if (val && channel->ndots == -1)
1306 channel->ndots = atoi(val);
1307 val = try_option(p, q, "retrans:");
1308 if (val && channel->timeout == -1)
1309 channel->timeout = atoi(val);
1310 val = try_option(p, q, "retry:");
1311 if (val && channel->tries == -1)
1312 channel->tries = atoi(val);
1313 val = try_option(p, q, "rotate");
1314 if (val && channel->rotate == -1)
1315 channel->rotate = 1;
1321 return ARES_SUCCESS;
1325 static char *try_config(char *s, const char *opt)
1333 /* no line or no option */
1336 /* trim line comment */
1337 for (i = 0; s[i] && s[i] != '#'; ++i);
1340 /* trim trailing whitespace */
1341 for (j = i-1; j >= 0 && ISSPACE(s[j]); --j);
1344 /* skip leading whitespace */
1345 for (i = 0; s[i] && ISSPACE(s[i]); ++i);
1352 if ((len = strlen(opt)) == 0)
1356 if (strncmp(p, opt, len) != 0)
1357 /* line and option do not match */
1360 /* skip over given option name */
1364 /* no option value */
1367 if ((opt[len-1] != ':') && (opt[len-1] != '=') && !ISSPACE(*p))
1368 /* whitespace between option name and value is mandatory
1369 for given option names which do not end with ':' or '=' */
1372 /* skip over whitespace */
1373 while (*p && ISSPACE(*p))
1377 /* no option value */
1380 /* return pointer to option value */
1385 static const char *try_option(const char *p, const char *q, const char *opt)
1387 size_t len = strlen(opt);
1388 return ((size_t)(q - p) >= len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1392 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1393 struct apattern *pat)
1395 struct apattern *newsort;
1396 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1399 newsort[*nsort] = *pat;
1400 *sortlist = newsort;
1405 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1408 /* Four octets and three periods yields at most 15 characters. */
1412 addr->s_addr = inet_addr(ipbuf);
1413 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1418 static void natural_mask(struct apattern *pat)
1420 struct in_addr addr;
1422 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1425 addr.s_addr = ntohl(pat->addrV4.s_addr);
1427 /* This is out of date in the CIDR world, but some people might
1430 if (IN_CLASSA(addr.s_addr))
1431 pat->mask.addr4.s_addr = htonl(IN_CLASSA_NET);
1432 else if (IN_CLASSB(addr.s_addr))
1433 pat->mask.addr4.s_addr = htonl(IN_CLASSB_NET);
1435 pat->mask.addr4.s_addr = htonl(IN_CLASSC_NET);
1438 /* initialize an rc4 key. If possible a cryptographically secure random key
1439 is generated using a suitable function (for example win32's RtlGenRandom as
1441 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1442 otherwise the code defaults to cross-platform albeit less secure mechanism
1445 static void randomize_key(unsigned char* key,int key_data_len)
1450 HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1452 BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1453 (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1454 if (pfn && pfn(key,key_data_len) )
1461 FILE *f = fopen(RANDOM_FILE, "rb");
1463 counter = fread(key, 1, key_data_len, f);
1469 if ( !randomized ) {
1470 for (;counter<key_data_len;counter++)
1471 key[counter]=(unsigned char)(rand() % 256);
1475 static int init_id_key(rc4_key* key,int key_data_len)
1477 unsigned char index1;
1478 unsigned char index2;
1479 unsigned char* state;
1481 unsigned char *key_data_ptr = 0;
1483 key_data_ptr = calloc(1,key_data_len);
1487 state = &key->state[0];
1488 for(counter = 0; counter < 256; counter++)
1489 /* unnecessary AND but it keeps some compilers happier */
1490 state[counter] = (unsigned char)(counter & 0xff);
1491 randomize_key(key->state,key_data_len);
1496 for(counter = 0; counter < 256; counter++)
1498 index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1500 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1502 index1 = (unsigned char)((index1 + 1) % key_data_len);
1505 return ARES_SUCCESS;
1508 unsigned short ares__generate_new_id(rc4_key* key)
1511 ares__rc4(key, (unsigned char *)&r, sizeof(r));