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 "ares_private.h"
62 #include "inet_net_pton.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;
113 const char *env = getenv("CARES_MEMDEBUG");
117 env = getenv("CARES_MEMLIMIT");
119 curl_memlimit(atoi(env));
122 channel = malloc(sizeof(struct ares_channeldata));
128 /* Set everything to distinguished values so we know they haven't
132 channel->timeout = -1;
135 channel->udp_port = -1;
136 channel->tcp_port = -1;
137 channel->socket_send_buffer_size = -1;
138 channel->socket_receive_buffer_size = -1;
139 channel->nservers = -1;
140 channel->ndomains = -1;
142 channel->tcp_connection_generation = 0;
143 channel->lookups = NULL;
144 channel->domains = NULL;
145 channel->sortlist = NULL;
146 channel->servers = NULL;
147 channel->sock_state_cb = NULL;
148 channel->sock_state_cb_data = NULL;
150 channel->last_timeout_processed = (long)time(NULL);
152 /* Initialize our lists of queries */
153 ares__init_list_head(&(channel->all_queries));
154 for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
156 ares__init_list_head(&(channel->queries_by_qid[i]));
158 for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
160 ares__init_list_head(&(channel->queries_by_timeout[i]));
163 /* Initialize configuration by each of the four sources, from highest
164 * precedence to lowest.
167 if (status == ARES_SUCCESS) {
168 status = init_by_options(channel, options, optmask);
169 if (status != ARES_SUCCESS)
170 DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
171 ares_strerror(status)));
173 if (status == ARES_SUCCESS) {
174 status = init_by_environment(channel);
175 if (status != ARES_SUCCESS)
176 DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
177 ares_strerror(status)));
179 if (status == ARES_SUCCESS) {
180 status = init_by_resolv_conf(channel);
181 if (status != ARES_SUCCESS)
182 DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
183 ares_strerror(status)));
185 if (status == ARES_SUCCESS) {
186 status = init_by_defaults(channel);
187 if (status != ARES_SUCCESS)
188 DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
189 ares_strerror(status)));
192 /* Generate random key */
194 if (status == ARES_SUCCESS) {
195 status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
196 if (status == ARES_SUCCESS)
197 channel->next_id = ares__generate_new_id(&channel->id_key);
199 DEBUGF(fprintf(stderr, "Error: init_id_key failed: %s\n",
200 ares_strerror(status)));
203 if (status != ARES_SUCCESS)
205 /* Something failed; clean up memory we may have allocated. */
206 if (channel->servers)
207 free(channel->servers);
208 if (channel->domains)
210 for (i = 0; i < channel->ndomains; i++)
211 free(channel->domains[i]);
212 free(channel->domains);
214 if (channel->sortlist)
215 free(channel->sortlist);
217 free(channel->lookups);
222 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
223 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
224 channel->nservers = 1;
226 /* Initialize server states. */
227 for (i = 0; i < channel->nservers; i++)
229 server = &channel->servers[i];
230 server->udp_socket = ARES_SOCKET_BAD;
231 server->tcp_socket = ARES_SOCKET_BAD;
232 server->tcp_connection_generation = ++channel->tcp_connection_generation;
233 server->tcp_lenbuf_pos = 0;
234 server->tcp_buffer = NULL;
235 server->qhead = NULL;
236 server->qtail = NULL;
237 ares__init_list_head(&(server->queries_to_server));
238 server->channel = channel;
239 server->is_broken = 0;
242 *channelptr = channel;
246 /* Save options from initialized channel */
247 int ares_save_options(ares_channel channel, struct ares_options *options,
252 /* Zero everything out */
253 memset(options, 0, sizeof(struct ares_options));
255 if (!ARES_CONFIG_CHECK(channel))
258 (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TRIES|ARES_OPT_NDOTS|
259 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
260 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
261 ARES_OPT_SORTLIST|ARES_OPT_TIMEOUTMS);
263 /* Copy easy stuff */
264 options->flags = channel->flags;
266 /* We return full millisecond resolution but that's only because we don't
267 set the ARES_OPT_TIMEOUT anymore, only the new ARES_OPT_TIMEOUTMS */
268 options->timeout = channel->timeout;
269 options->tries = channel->tries;
270 options->ndots = channel->ndots;
271 options->udp_port = (unsigned short)channel->udp_port;
272 options->tcp_port = (unsigned short)channel->tcp_port;
273 options->sock_state_cb = channel->sock_state_cb;
274 options->sock_state_cb_data = channel->sock_state_cb_data;
277 if (channel->nservers) {
279 malloc(channel->nservers * sizeof(struct server_state));
280 if (!options->servers && channel->nservers != 0)
282 for (i = 0; i < channel->nservers; i++)
283 options->servers[i] = channel->servers[i].addr;
285 options->nservers = channel->nservers;
288 if (channel->ndomains) {
289 options->domains = malloc(channel->ndomains * sizeof(char *));
290 if (!options->domains)
293 for (i = 0; i < channel->ndomains; i++)
295 options->ndomains = i;
296 options->domains[i] = strdup(channel->domains[i]);
297 if (!options->domains[i])
301 options->ndomains = channel->ndomains;
304 if (channel->lookups) {
305 options->lookups = strdup(channel->lookups);
306 if (!options->lookups && channel->lookups)
311 if (channel->nsort) {
312 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
313 if (!options->sortlist)
315 for (i = 0; i < channel->nsort; i++)
317 memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
318 sizeof(struct apattern));
321 options->nsort = channel->nsort;
326 static int init_by_options(ares_channel channel,
327 const struct ares_options *options,
333 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
334 channel->flags = options->flags;
335 if ((optmask & ARES_OPT_TIMEOUTMS) && channel->timeout == -1)
336 channel->timeout = options->timeout;
337 else if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
338 channel->timeout = options->timeout * 1000;
339 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
340 channel->tries = options->tries;
341 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
342 channel->ndots = options->ndots;
343 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
344 channel->udp_port = options->udp_port;
345 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
346 channel->tcp_port = options->tcp_port;
347 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
349 channel->sock_state_cb = options->sock_state_cb;
350 channel->sock_state_cb_data = options->sock_state_cb_data;
352 if ((optmask & ARES_OPT_SOCK_SNDBUF)
353 && channel->socket_send_buffer_size == -1)
354 channel->socket_send_buffer_size = options->socket_send_buffer_size;
355 if ((optmask & ARES_OPT_SOCK_RCVBUF)
356 && channel->socket_receive_buffer_size == -1)
357 channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
359 /* Copy the servers, if given. */
360 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
362 /* Avoid zero size allocations at any cost */
363 if (options->nservers > 0)
366 malloc(options->nservers * sizeof(struct server_state));
367 if (!channel->servers)
369 for (i = 0; i < options->nservers; i++)
370 channel->servers[i].addr = options->servers[i];
372 channel->nservers = options->nservers;
375 /* Copy the domains, if given. Keep channel->ndomains consistent so
376 * we can clean up in case of error.
378 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
380 /* Avoid zero size allocations at any cost */
381 if (options->ndomains > 0)
383 channel->domains = malloc(options->ndomains * sizeof(char *));
384 if (!channel->domains)
386 for (i = 0; i < options->ndomains; i++)
388 channel->ndomains = i;
389 channel->domains[i] = strdup(options->domains[i]);
390 if (!channel->domains[i])
394 channel->ndomains = options->ndomains;
397 /* Set lookups, if given. */
398 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
400 channel->lookups = strdup(options->lookups);
401 if (!channel->lookups)
406 if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
408 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
409 if (!channel->sortlist)
411 for (i = 0; i < options->nsort; i++)
413 memcpy(&(channel->sortlist[i]), &(options->sortlist[i]), sizeof(struct apattern));
415 channel->nsort = options->nsort;
421 static int init_by_environment(ares_channel channel)
423 const char *localdomain, *res_options;
426 localdomain = getenv("LOCALDOMAIN");
427 if (localdomain && channel->ndomains == -1)
429 status = set_search(channel, localdomain);
430 if (status != ARES_SUCCESS)
434 res_options = getenv("RES_OPTIONS");
437 status = set_options(channel, res_options);
438 if (status != ARES_SUCCESS)
447 * Warning: returns a dynamically allocated buffer, the user MUST
448 * use free() if the function returns 1
450 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
452 /* Test for the size we need */
456 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
457 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
459 *obuf = malloc(size+1);
463 if (RegQueryValueEx(hKey, subkey, 0, NULL,
464 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
477 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
479 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
480 DWORD enum_size = 39;
484 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
485 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
490 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
493 rc = get_res_nt(hVal, subkey, obuf);
501 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
503 FIXED_INFO *fi = alloca (sizeof(*fi));
504 DWORD size = sizeof (*fi);
505 typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
506 get_net_param_func fpGetNetworkParams; /* available only on Win-98/2000+ */
508 IP_ADDR_STRING *ipAddr;
511 size_t ip_size = sizeof("255.255.255.255,")-1;
512 size_t left = ret_size;
519 handle = LoadLibrary ("iphlpapi.dll");
523 fpGetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
524 if (!fpGetNetworkParams)
527 res = (*fpGetNetworkParams) (fi, &size);
528 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
532 if (!fi || (*fpGetNetworkParams) (fi, &size) != ERROR_SUCCESS)
537 printf ("Host Name: %s\n", fi->HostName);
538 printf ("Domain Name: %s\n", fi->DomainName);
539 printf ("DNS Servers:\n"
540 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
542 if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
543 inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
546 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
547 left -= ret - ret_buf;
551 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
552 ipAddr = ipAddr->Next, i++)
554 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
556 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
557 left -= ret - ret_buf;
561 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
566 FreeLibrary (handle);
568 if (debug && left <= ip_size)
569 printf ("Too many nameservers. Truncating to %d addressess", count);
576 static int init_by_resolv_conf(ares_channel channel)
579 int status = -1, nservers = 0, nsort = 0;
580 struct server_state *servers = NULL;
581 struct apattern *sortlist = NULL;
586 NameServer info via IPHLPAPI (IP helper API):
587 GetNetworkParams() should be the trusted source for this.
588 Available in Win-98/2000 and later. If that fail, fall-back to
589 registry information.
593 On Windows 9X, the DNS server can be found in:
594 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
596 On Windows NT/2000/XP/2003:
597 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
599 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
601 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
604 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
615 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
618 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
620 status = config_nameserver(&servers, &nservers, buf);
621 if (status == ARES_SUCCESS)
628 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
632 RegOpenKeyEx(mykey, "Interfaces", 0,
633 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
634 if (get_res_nt(mykey, NAMESERVER, &line))
636 status = config_nameserver(&servers, &nservers, line);
639 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
641 status = config_nameserver(&servers, &nservers, line);
644 /* Try the interfaces */
645 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
647 status = config_nameserver(&servers, &nservers, line);
650 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
652 status = config_nameserver(&servers, &nservers, line);
662 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
666 if ((result = RegQueryValueEx(
667 mykey, NAMESERVER, NULL, &data_type,
670 ) == ERROR_SUCCESS ||
671 result == ERROR_MORE_DATA)
675 line = (char *)malloc(bytes+1);
676 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
677 (unsigned char *)line, &bytes) ==
680 status = config_nameserver(&servers, &nservers, line);
689 if (status == ARES_SUCCESS)
692 /* Catch the case when all the above checks fail (which happens when there
693 is no network card or the cable is unplugged) */
696 #elif defined(__riscos__)
698 /* Under RISC OS, name servers are listed in the
699 system variable Inet$Resolvers, space separated. */
701 line = getenv("Inet$Resolvers");
704 char *resolvers = strdup(line), *pos, *space;
711 space = strchr(pos, ' ');
714 status = config_nameserver(&servers, &nservers, pos);
715 if (status != ARES_SUCCESS)
720 if (status == ARES_SUCCESS)
726 #elif defined(WATT32)
730 for (i = 0; def_nameservers[i]; i++)
733 return ARES_SUCCESS; /* use localhost DNS server */
736 servers = calloc(sizeof(*servers), i);
740 for (i = 0; def_nameservers[i]; i++)
741 servers[i].addr.s_addr = htonl(def_nameservers[i]);
751 /* Don't read resolv.conf and friends if we don't have to */
752 if (ARES_CONFIG_CHECK(channel))
755 fp = fopen(PATH_RESOLV_CONF, "r");
757 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
759 if ((p = try_config(line, "domain")) && channel->ndomains == -1)
760 status = config_domain(channel, p);
761 else if ((p = try_config(line, "lookup")) && !channel->lookups)
762 status = config_lookup(channel, p, "bind", "file");
763 else if ((p = try_config(line, "search")) && channel->ndomains == -1)
764 status = set_search(channel, p);
765 else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
766 status = config_nameserver(&servers, &nservers, p);
767 else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
768 status = config_sortlist(&sortlist, &nsort, p);
769 else if ((p = try_config(line, "options")))
770 status = set_options(channel, p);
772 status = ARES_SUCCESS;
773 if (status != ARES_SUCCESS)
786 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
787 error, strerror(error)));
788 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
793 if ((status == ARES_EOF) && (!channel->lookups)) {
794 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
795 fp = fopen("/etc/nsswitch.conf", "r");
797 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
799 if ((p = try_config(line, "hosts:")) && !channel->lookups)
800 status = config_lookup(channel, p, "dns", "files");
812 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
813 error, strerror(error)));
814 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
820 if ((status == ARES_EOF) && (!channel->lookups)) {
821 /* Linux / GNU libc 2.x and possibly others have host.conf */
822 fp = fopen("/etc/host.conf", "r");
824 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
826 if ((p = try_config(line, "order")) && !channel->lookups)
827 status = config_lookup(channel, p, "bind", "hosts");
839 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
840 error, strerror(error)));
841 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
847 if ((status == ARES_EOF) && (!channel->lookups)) {
848 /* Tru64 uses /etc/svc.conf */
849 fp = fopen("/etc/svc.conf", "r");
851 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
853 if ((p = try_config(line, "hosts=")) && !channel->lookups)
854 status = config_lookup(channel, p, "bind", "local");
866 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
867 error, strerror(error)));
868 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
881 if (status != ARES_EOF)
885 if (sortlist != NULL)
890 /* If we got any name server entries, fill them in. */
896 channel->servers = servers;
897 channel->nservers = nservers;
900 /* If we got any sortlist entries, fill them in. */
903 channel->sortlist = sortlist;
904 channel->nsort = nsort;
910 static int init_by_defaults(ares_channel channel)
912 char hostname[MAXHOSTNAMELEN + 1];
914 if (channel->flags == -1)
916 if (channel->timeout == -1)
917 channel->timeout = DEFAULT_TIMEOUT;
918 if (channel->tries == -1)
919 channel->tries = DEFAULT_TRIES;
920 if (channel->ndots == -1)
922 if (channel->udp_port == -1)
923 channel->udp_port = htons(NAMESERVER_PORT);
924 if (channel->tcp_port == -1)
925 channel->tcp_port = htons(NAMESERVER_PORT);
927 if (channel->nservers == -1)
929 /* If nobody specified servers, try a local named. */
930 channel->servers = malloc(sizeof(struct server_state));
931 if (!channel->servers)
933 channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
934 channel->nservers = 1;
937 if (channel->ndomains == -1)
939 /* Derive a default domain search list from the kernel hostname,
940 * or set it to empty if the hostname isn't helpful.
942 if (gethostname(hostname, sizeof(hostname)) == -1
943 || !strchr(hostname, '.'))
945 channel->ndomains = 0;
949 channel->domains = malloc(sizeof(char *));
950 if (!channel->domains)
952 channel->ndomains = 0;
953 channel->domains[0] = strdup(strchr(hostname, '.') + 1);
954 if (!channel->domains[0])
956 channel->ndomains = 1;
960 if (channel->nsort == -1)
962 channel->sortlist = NULL;
966 if (!channel->lookups)
968 channel->lookups = strdup("fb");
969 if (!channel->lookups)
977 static int config_domain(ares_channel channel, char *str)
981 /* Set a single search domain. */
983 while (*q && !ISSPACE(*q))
986 return set_search(channel, str);
989 static int config_lookup(ares_channel channel, const char *str,
990 const char *bindch, const char *filech)
995 /* Set the lookup order. Only the first letter of each work
996 * is relevant, and it has to be "b" for DNS or "f" for the
997 * host file. Ignore everything else.
1003 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
1004 if (*p == *bindch) *l++ = 'b';
1007 while (*p && !ISSPACE(*p) && (*p != ','))
1009 while (*p && (ISSPACE(*p) || (*p == ',')))
1013 channel->lookups = strdup(lookups);
1014 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1019 static int config_nameserver(struct server_state **servers, int *nservers,
1022 struct in_addr addr;
1023 struct server_state *newserv;
1024 /* On Windows, there may be more than one nameserver specified in the same
1025 * registry key, so we parse it as a space or comma seperated list.
1034 while (*p && !ISSPACE(*p) && *p != ',')
1043 /* Skip multiple spaces or trailing spaces */
1050 /* This is the part that actually sets the nameserver */
1051 addr.s_addr = inet_addr(begin);
1052 if (addr.s_addr == INADDR_NONE)
1054 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1057 newserv[*nservers].addr = addr;
1066 /* Add a nameserver entry, if this is a valid address. */
1067 addr.s_addr = inet_addr(str);
1068 if (addr.s_addr == INADDR_NONE)
1069 return ARES_SUCCESS;
1070 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1073 newserv[*nservers].addr = addr;
1077 return ARES_SUCCESS;
1081 static int config_sortlist(struct apattern **sortlist, int *nsort,
1084 struct apattern pat;
1087 /* Add sortlist entries. */
1088 while (*str && *str != ';')
1091 char ipbuf[16], ipbufpfx[32];
1092 /* Find just the IP */
1094 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1096 memcpy(ipbuf, str, (int)(q-str));
1097 ipbuf[(int)(q-str)] = '\0';
1098 /* Find the prefix */
1101 const char *str2 = q+1;
1102 while (*q && *q != ';' && !ISSPACE(*q))
1104 memcpy(ipbufpfx, str, (int)(q-str));
1105 ipbufpfx[(int)(q-str)] = '\0';
1110 /* Lets see if it is CIDR */
1111 /* First we'll try IPv6 */
1112 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1114 sizeof(pat.addr.addr6))) > 0)
1116 pat.type = PATTERN_CIDR;
1117 pat.mask.bits = (unsigned short)bits;
1118 pat.family = AF_INET6;
1119 if (!sortlist_alloc(sortlist, nsort, &pat))
1123 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addr.addr4,
1124 sizeof(pat.addr.addr4))) > 0)
1126 pat.type = PATTERN_CIDR;
1127 pat.mask.bits = (unsigned short)bits;
1128 pat.family = AF_INET;
1129 if (!sortlist_alloc(sortlist, nsort, &pat))
1132 /* See if it is just a regular IP */
1133 else if (ip_addr(ipbuf, (int)(q-str), &pat.addr.addr4) == 0)
1137 memcpy(ipbuf, str, (int)(q-str));
1138 ipbuf[(int)(q-str)] = '\0';
1139 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr.addr4) != 0)
1144 pat.family = AF_INET;
1145 pat.type = PATTERN_MASK;
1146 if (!sortlist_alloc(sortlist, nsort, &pat))
1151 while (*q && *q != ';' && !ISSPACE(*q))
1155 while (ISSPACE(*str))
1159 return ARES_SUCCESS;
1163 static int set_search(ares_channel channel, const char *str)
1168 if(channel->ndomains != -1) {
1169 /* if we already have some domains present, free them first */
1170 for(n=0; n < channel->ndomains; n++)
1171 free(channel->domains[n]);
1172 free(channel->domains);
1173 channel->domains = NULL;
1174 channel->ndomains = -1;
1177 /* Count the domains given. */
1182 while (*p && !ISSPACE(*p))
1191 channel->ndomains = 0;
1192 return ARES_SUCCESS;
1195 channel->domains = malloc(n * sizeof(char *));
1196 if (!channel->domains)
1199 /* Now copy the domains. */
1204 channel->ndomains = n;
1206 while (*q && !ISSPACE(*q))
1208 channel->domains[n] = malloc(q - p + 1);
1209 if (!channel->domains[n])
1211 memcpy(channel->domains[n], p, q - p);
1212 channel->domains[n][q - p] = 0;
1218 channel->ndomains = n;
1220 return ARES_SUCCESS;
1223 static int set_options(ares_channel channel, const char *str)
1225 const char *p, *q, *val;
1231 while (*q && !ISSPACE(*q))
1233 val = try_option(p, q, "ndots:");
1234 if (val && channel->ndots == -1)
1235 channel->ndots = atoi(val);
1236 val = try_option(p, q, "retrans:");
1237 if (val && channel->timeout == -1)
1238 channel->timeout = atoi(val);
1239 val = try_option(p, q, "retry:");
1240 if (val && channel->tries == -1)
1241 channel->tries = atoi(val);
1247 return ARES_SUCCESS;
1251 static char *try_config(char *s, const char *opt)
1259 /* no line or no option */
1262 /* trim line comment */
1263 for (i = 0; s[i] && s[i] != '#'; ++i);
1266 /* trim trailing whitespace */
1267 for (j = i-1; j >= 0 && ISSPACE(s[j]); --j);
1270 /* skip leading whitespace */
1271 for (i = 0; s[i] && ISSPACE(s[i]); ++i);
1278 if ((len = strlen(opt)) == 0)
1282 if (strncmp(p, opt, len) != 0)
1283 /* line and option do not match */
1286 /* skip over given option name */
1290 /* no option value */
1293 if ((opt[len-1] != ':') && (opt[len-1] != '=') && !ISSPACE(*p))
1294 /* whitespace between option name and value is mandatory
1295 for given option names which do not end with ':' or '=' */
1298 /* skip over whitespace */
1299 while (*p && ISSPACE(*p))
1303 /* no option value */
1306 /* return pointer to option value */
1311 static const char *try_option(const char *p, const char *q, const char *opt)
1313 size_t len = strlen(opt);
1314 return ((size_t)(q - p) > len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1318 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1319 struct apattern *pat)
1321 struct apattern *newsort;
1322 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1325 newsort[*nsort] = *pat;
1326 *sortlist = newsort;
1331 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1334 /* Four octets and three periods yields at most 15 characters. */
1338 addr->s_addr = inet_addr(ipbuf);
1339 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1344 static void natural_mask(struct apattern *pat)
1346 struct in_addr addr;
1348 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1351 addr.s_addr = ntohl(pat->addr.addr4.s_addr);
1353 /* This is out of date in the CIDR world, but some people might
1356 if (IN_CLASSA(addr.s_addr))
1357 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSA_NET);
1358 else if (IN_CLASSB(addr.s_addr))
1359 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSB_NET);
1361 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSC_NET);
1364 /* initialize an rc4 key. If possible a cryptographically secure random key
1365 is generated using a suitable function (for example win32's RtlGenRandom as
1367 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1368 otherwise the code defaults to cross-platform albeit less secure mechanism
1371 static void randomize_key(unsigned char* key,int key_data_len)
1376 HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1378 BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1379 (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1380 if (pfn && pfn(key,key_data_len) )
1387 FILE *f = fopen(RANDOM_FILE, "rb");
1389 counter = fread(key, 1, key_data_len, f);
1395 if ( !randomized ) {
1396 for (;counter<key_data_len;counter++)
1397 key[counter]=(unsigned char)(rand() % 256);
1401 static int init_id_key(rc4_key* key,int key_data_len)
1403 unsigned char index1;
1404 unsigned char index2;
1405 unsigned char* state;
1407 unsigned char *key_data_ptr = 0;
1409 key_data_ptr = calloc(1,key_data_len);
1413 randomize_key(key->state,key_data_len);
1414 state = &key->state[0];
1415 for(counter = 0; counter < 256; counter++)
1416 /* unnecessary AND but it keeps some compilers happier */
1417 state[counter] = (unsigned char)(counter & 0xff);
1422 for(counter = 0; counter < 256; counter++)
1424 index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1426 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1428 index1 = (unsigned char)((index1 + 1) % key_data_len);
1431 return ARES_SUCCESS;
1434 short ares__generate_new_id(rc4_key* key)
1437 ares__rc4(key, (unsigned char *)&r, sizeof(r));