3 /* Copyright 1998 by the Massachusetts Institute of Technology.
5 * Permission to use, copy, modify, and distribute this
6 * software and its documentation for any purpose and without
7 * fee is hereby granted, provided that the above copyright
8 * notice appear in all copies and that both that copyright
9 * notice and this permission notice appear in supporting
10 * documentation, and that the name of M.I.T. not be used in
11 * advertising or publicity pertaining to distribution of the
12 * software without specific, written prior permission.
13 * M.I.T. makes no representations about the suitability of
14 * this software for any purpose. It is provided "as is"
15 * without express or implied warranty.
20 #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 #include <netinet/in.h>
39 #include <arpa/inet.h>
41 #include <arpa/nameser.h>
42 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
43 #include <arpa/nameser_compat.h>
49 #include <process.h> /* Some have getpid() here */
60 #include "ares_private.h"
61 #include "inet_net_pton.h"
64 #undef WIN32 /* Redefined in MingW/MSVC headers */
67 static int init_by_options(ares_channel channel, const struct ares_options *options,
69 static int init_by_environment(ares_channel channel);
70 static int init_by_resolv_conf(ares_channel channel);
71 static int init_by_defaults(ares_channel channel);
73 static int config_nameserver(struct server_state **servers, int *nservers,
75 static int set_search(ares_channel channel, const char *str);
76 static int set_options(ares_channel channel, const char *str);
77 static const char *try_option(const char *p, const char *q, const char *opt);
78 static int init_id_key(rc4_key* key,int key_data_len);
81 static int sortlist_alloc(struct apattern **sortlist, int *nsort, struct apattern *pat);
82 static int ip_addr(const char *s, int len, struct in_addr *addr);
83 static void natural_mask(struct apattern *pat);
84 static int config_domain(ares_channel channel, char *str);
85 static int config_lookup(ares_channel channel, const char *str,
86 const char *bindch, const char *filech);
87 static int config_sortlist(struct apattern **sortlist, int *nsort,
89 static char *try_config(char *s, const char *opt);
92 #define ARES_CONFIG_CHECK(x) (x->lookups && x->nsort > -1 && \
95 x->ndots > -1 && x->timeout > -1 && \
98 int ares_init(ares_channel *channelptr)
100 return ares_init_options(channelptr, NULL, 0);
103 int ares_init_options(ares_channel *channelptr, struct ares_options *options,
106 ares_channel channel;
108 int status = ARES_SUCCESS;
109 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 gettimeofday(&tv, NULL);
151 channel->last_timeout_processed = tv.tv_sec;
153 /* Initialize our lists of queries */
154 ares__init_list_head(&(channel->all_queries));
155 for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
157 ares__init_list_head(&(channel->queries_by_qid[i]));
159 for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
161 ares__init_list_head(&(channel->queries_by_timeout[i]));
164 /* Initialize configuration by each of the four sources, from highest
165 * precedence to lowest.
168 if (status == ARES_SUCCESS) {
169 status = init_by_options(channel, options, optmask);
170 if (status != ARES_SUCCESS)
171 DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
172 ares_strerror(status)));
174 if (status == ARES_SUCCESS) {
175 status = init_by_environment(channel);
176 if (status != ARES_SUCCESS)
177 DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
178 ares_strerror(status)));
180 if (status == ARES_SUCCESS) {
181 status = init_by_resolv_conf(channel);
182 if (status != ARES_SUCCESS)
183 DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
184 ares_strerror(status)));
186 if (status == ARES_SUCCESS) {
187 status = init_by_defaults(channel);
188 if (status != ARES_SUCCESS)
189 DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
190 ares_strerror(status)));
193 /* Generate random key */
195 if (status == ARES_SUCCESS) {
196 status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
197 if (status == ARES_SUCCESS)
198 channel->next_id = ares__generate_new_id(&channel->id_key);
200 DEBUGF(fprintf(stderr, "Error: init_id_key failed: %s\n",
201 ares_strerror(status)));
204 if (status != ARES_SUCCESS)
206 /* Something failed; clean up memory we may have allocated. */
207 if (channel->servers)
208 free(channel->servers);
209 if (channel->domains)
211 for (i = 0; i < channel->ndomains; i++)
212 free(channel->domains[i]);
213 free(channel->domains);
215 if (channel->sortlist)
216 free(channel->sortlist);
218 free(channel->lookups);
223 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
224 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
225 channel->nservers = 1;
227 /* Initialize server states. */
228 for (i = 0; i < channel->nservers; i++)
230 server = &channel->servers[i];
231 server->udp_socket = ARES_SOCKET_BAD;
232 server->tcp_socket = ARES_SOCKET_BAD;
233 server->tcp_connection_generation = ++channel->tcp_connection_generation;
234 server->tcp_lenbuf_pos = 0;
235 server->tcp_buffer = NULL;
236 server->qhead = NULL;
237 server->qtail = NULL;
238 ares__init_list_head(&(server->queries_to_server));
239 server->channel = channel;
240 server->is_broken = 0;
243 *channelptr = channel;
247 /* Save options from initialized channel */
248 int ares_save_options(ares_channel channel, struct ares_options *options,
253 /* Zero everything out */
254 memset(options, 0, sizeof(struct ares_options));
256 if (!ARES_CONFIG_CHECK(channel))
259 (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TIMEOUT|ARES_OPT_TRIES|ARES_OPT_NDOTS|
260 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
261 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
264 /* Copy easy stuff */
265 options->flags = channel->flags;
266 options->timeout = channel->timeout;
267 options->tries = channel->tries;
268 options->ndots = channel->ndots;
269 options->udp_port = (unsigned short)channel->udp_port;
270 options->tcp_port = (unsigned short)channel->tcp_port;
271 options->sock_state_cb = channel->sock_state_cb;
272 options->sock_state_cb_data = channel->sock_state_cb_data;
275 if (channel->nservers) {
277 malloc(channel->nservers * sizeof(struct server_state));
278 if (!options->servers && channel->nservers != 0)
280 for (i = 0; i < channel->nservers; i++)
281 options->servers[i] = channel->servers[i].addr;
283 options->nservers = channel->nservers;
286 if (channel->ndomains) {
287 options->domains = malloc(channel->ndomains * sizeof(char *));
288 if (!options->domains)
291 for (i = 0; i < channel->ndomains; i++)
293 options->ndomains = i;
294 options->domains[i] = strdup(channel->domains[i]);
295 if (!options->domains[i])
299 options->ndomains = channel->ndomains;
302 if (channel->lookups) {
303 options->lookups = strdup(channel->lookups);
304 if (!options->lookups && channel->lookups)
309 if (channel->nsort) {
310 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
311 if (!options->sortlist)
313 for (i = 0; i < channel->nsort; i++)
315 memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
316 sizeof(struct apattern));
319 options->nsort = channel->nsort;
324 static int init_by_options(ares_channel channel,
325 const struct ares_options *options,
331 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
332 channel->flags = options->flags;
333 if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
334 channel->timeout = options->timeout;
335 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
336 channel->tries = options->tries;
337 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
338 channel->ndots = options->ndots;
339 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
340 channel->udp_port = options->udp_port;
341 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
342 channel->tcp_port = options->tcp_port;
343 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
345 channel->sock_state_cb = options->sock_state_cb;
346 channel->sock_state_cb_data = options->sock_state_cb_data;
348 if ((optmask & ARES_OPT_SOCK_SNDBUF)
349 && channel->socket_send_buffer_size == -1)
350 channel->socket_send_buffer_size = options->socket_send_buffer_size;
351 if ((optmask & ARES_OPT_SOCK_RCVBUF)
352 && channel->socket_receive_buffer_size == -1)
353 channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
355 /* Copy the servers, if given. */
356 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
358 /* Avoid zero size allocations at any cost */
359 if (options->nservers > 0)
362 malloc(options->nservers * sizeof(struct server_state));
363 if (!channel->servers)
365 for (i = 0; i < options->nservers; i++)
366 channel->servers[i].addr = options->servers[i];
368 channel->nservers = options->nservers;
371 /* Copy the domains, if given. Keep channel->ndomains consistent so
372 * we can clean up in case of error.
374 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
376 /* Avoid zero size allocations at any cost */
377 if (options->ndomains > 0)
379 channel->domains = malloc(options->ndomains * sizeof(char *));
380 if (!channel->domains)
382 for (i = 0; i < options->ndomains; i++)
384 channel->ndomains = i;
385 channel->domains[i] = strdup(options->domains[i]);
386 if (!channel->domains[i])
390 channel->ndomains = options->ndomains;
393 /* Set lookups, if given. */
394 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
396 channel->lookups = strdup(options->lookups);
397 if (!channel->lookups)
402 if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
404 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
405 if (!channel->sortlist)
407 for (i = 0; i < options->nsort; i++)
409 memcpy(&(channel->sortlist[i]), &(options->sortlist[i]), sizeof(struct apattern));
411 channel->nsort = options->nsort;
417 static int init_by_environment(ares_channel channel)
419 const char *localdomain, *res_options;
422 localdomain = getenv("LOCALDOMAIN");
423 if (localdomain && channel->ndomains == -1)
425 status = set_search(channel, localdomain);
426 if (status != ARES_SUCCESS)
430 res_options = getenv("RES_OPTIONS");
433 status = set_options(channel, res_options);
434 if (status != ARES_SUCCESS)
443 * Warning: returns a dynamically allocated buffer, the user MUST
444 * use free() if the function returns 1
446 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
448 /* Test for the size we need */
452 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
453 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
455 *obuf = malloc(size+1);
459 if (RegQueryValueEx(hKey, subkey, 0, NULL,
460 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
473 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
475 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
476 DWORD enum_size = 39;
480 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
481 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
486 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
489 rc = get_res_nt(hVal, subkey, obuf);
497 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
499 FIXED_INFO *fi = alloca (sizeof(*fi));
500 DWORD size = sizeof (*fi);
501 typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
502 get_net_param_func fpGetNetworkParams; /* available only on Win-98/2000+ */
504 IP_ADDR_STRING *ipAddr;
507 size_t ip_size = sizeof("255.255.255.255,")-1;
508 size_t left = ret_size;
515 handle = LoadLibrary ("iphlpapi.dll");
519 fpGetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
520 if (!fpGetNetworkParams)
523 res = (*fpGetNetworkParams) (fi, &size);
524 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
528 if (!fi || (*fpGetNetworkParams) (fi, &size) != ERROR_SUCCESS)
533 printf ("Host Name: %s\n", fi->HostName);
534 printf ("Domain Name: %s\n", fi->DomainName);
535 printf ("DNS Servers:\n"
536 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
538 if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
539 inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
542 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
543 left -= ret - ret_buf;
547 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
548 ipAddr = ipAddr->Next, i++)
550 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
552 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
553 left -= ret - ret_buf;
557 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
562 FreeLibrary (handle);
564 if (debug && left <= ip_size)
565 printf ("Too many nameservers. Truncating to %d addressess", count);
572 static int init_by_resolv_conf(ares_channel channel)
575 int status = -1, nservers = 0, nsort = 0;
576 struct server_state *servers = NULL;
577 struct apattern *sortlist = NULL;
582 NameServer info via IPHLPAPI (IP helper API):
583 GetNetworkParams() should be the trusted source for this.
584 Available in Win-98/2000 and later. If that fail, fall-back to
585 registry information.
589 On Windows 9X, the DNS server can be found in:
590 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
592 On Windows NT/2000/XP/2003:
593 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
595 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
597 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
600 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
611 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
614 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
616 status = config_nameserver(&servers, &nservers, buf);
617 if (status == ARES_SUCCESS)
624 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
628 RegOpenKeyEx(mykey, "Interfaces", 0,
629 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
630 if (get_res_nt(mykey, NAMESERVER, &line))
632 status = config_nameserver(&servers, &nservers, line);
635 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
637 status = config_nameserver(&servers, &nservers, line);
640 /* Try the interfaces */
641 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
643 status = config_nameserver(&servers, &nservers, line);
646 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
648 status = config_nameserver(&servers, &nservers, line);
658 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
662 if ((result = RegQueryValueEx(
663 mykey, NAMESERVER, NULL, &data_type,
666 ) == ERROR_SUCCESS ||
667 result == ERROR_MORE_DATA)
671 line = (char *)malloc(bytes+1);
672 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
673 (unsigned char *)line, &bytes) ==
676 status = config_nameserver(&servers, &nservers, line);
685 if (status == ARES_SUCCESS)
688 /* Catch the case when all the above checks fail (which happens when there
689 is no network card or the cable is unplugged) */
692 #elif defined(__riscos__)
694 /* Under RISC OS, name servers are listed in the
695 system variable Inet$Resolvers, space separated. */
697 line = getenv("Inet$Resolvers");
700 char *resolvers = strdup(line), *pos, *space;
707 space = strchr(pos, ' ');
710 status = config_nameserver(&servers, &nservers, pos);
711 if (status != ARES_SUCCESS)
716 if (status == ARES_SUCCESS)
722 #elif defined(WATT32)
726 for (i = 0; def_nameservers[i]; i++)
729 return ARES_SUCCESS; /* use localhost DNS server */
732 servers = calloc(sizeof(*servers), i);
736 for (i = 0; def_nameservers[i]; i++)
737 servers[i].addr.s_addr = htonl(def_nameservers[i]);
747 /* Don't read resolv.conf and friends if we don't have to */
748 if (ARES_CONFIG_CHECK(channel))
751 fp = fopen(PATH_RESOLV_CONF, "r");
753 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
755 if ((p = try_config(line, "domain")) && channel->ndomains == -1)
756 status = config_domain(channel, p);
757 else if ((p = try_config(line, "lookup")) && !channel->lookups)
758 status = config_lookup(channel, p, "bind", "file");
759 else if ((p = try_config(line, "search")) && channel->ndomains == -1)
760 status = set_search(channel, p);
761 else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
762 status = config_nameserver(&servers, &nservers, p);
763 else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
764 status = config_sortlist(&sortlist, &nsort, p);
765 else if ((p = try_config(line, "options")))
766 status = set_options(channel, p);
768 status = ARES_SUCCESS;
769 if (status != ARES_SUCCESS)
782 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
783 error, strerror(error)));
784 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
789 if ((status == ARES_EOF) && (!channel->lookups)) {
790 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
791 fp = fopen("/etc/nsswitch.conf", "r");
793 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
795 if ((p = try_config(line, "hosts:")) && !channel->lookups)
796 status = config_lookup(channel, p, "dns", "files");
808 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
809 error, strerror(error)));
810 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
816 if ((status == ARES_EOF) && (!channel->lookups)) {
817 /* Linux / GNU libc 2.x and possibly others have host.conf */
818 fp = fopen("/etc/host.conf", "r");
820 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
822 if ((p = try_config(line, "order")) && !channel->lookups)
823 status = config_lookup(channel, p, "bind", "hosts");
835 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
836 error, strerror(error)));
837 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
843 if ((status == ARES_EOF) && (!channel->lookups)) {
844 /* Tru64 uses /etc/svc.conf */
845 fp = fopen("/etc/svc.conf", "r");
847 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
849 if ((p = try_config(line, "hosts=")) && !channel->lookups)
850 status = config_lookup(channel, p, "bind", "local");
862 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
863 error, strerror(error)));
864 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
877 if (status != ARES_EOF)
881 if (sortlist != NULL)
886 /* If we got any name server entries, fill them in. */
892 channel->servers = servers;
893 channel->nservers = nservers;
896 /* If we got any sortlist entries, fill them in. */
899 channel->sortlist = sortlist;
900 channel->nsort = nsort;
906 static int init_by_defaults(ares_channel channel)
908 char hostname[MAXHOSTNAMELEN + 1];
910 if (channel->flags == -1)
912 if (channel->timeout == -1)
913 channel->timeout = DEFAULT_TIMEOUT;
914 if (channel->tries == -1)
915 channel->tries = DEFAULT_TRIES;
916 if (channel->ndots == -1)
918 if (channel->udp_port == -1)
919 channel->udp_port = htons(NAMESERVER_PORT);
920 if (channel->tcp_port == -1)
921 channel->tcp_port = htons(NAMESERVER_PORT);
923 if (channel->nservers == -1)
925 /* If nobody specified servers, try a local named. */
926 channel->servers = malloc(sizeof(struct server_state));
927 if (!channel->servers)
929 channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
930 channel->nservers = 1;
933 if (channel->ndomains == -1)
935 /* Derive a default domain search list from the kernel hostname,
936 * or set it to empty if the hostname isn't helpful.
938 if (gethostname(hostname, sizeof(hostname)) == -1
939 || !strchr(hostname, '.'))
941 channel->ndomains = 0;
945 channel->domains = malloc(sizeof(char *));
946 if (!channel->domains)
948 channel->ndomains = 0;
949 channel->domains[0] = strdup(strchr(hostname, '.') + 1);
950 if (!channel->domains[0])
952 channel->ndomains = 1;
956 if (channel->nsort == -1)
958 channel->sortlist = NULL;
962 if (!channel->lookups)
964 channel->lookups = strdup("fb");
965 if (!channel->lookups)
973 static int config_domain(ares_channel channel, char *str)
977 /* Set a single search domain. */
979 while (*q && !ISSPACE(*q))
982 return set_search(channel, str);
985 static int config_lookup(ares_channel channel, const char *str,
986 const char *bindch, const char *filech)
991 /* Set the lookup order. Only the first letter of each work
992 * is relevant, and it has to be "b" for DNS or "f" for the
993 * host file. Ignore everything else.
999 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
1000 if (*p == *bindch) *l++ = 'b';
1003 while (*p && !ISSPACE(*p) && (*p != ','))
1005 while (*p && (ISSPACE(*p) || (*p == ',')))
1009 channel->lookups = strdup(lookups);
1010 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1015 static int config_nameserver(struct server_state **servers, int *nservers,
1018 struct in_addr addr;
1019 struct server_state *newserv;
1020 /* On Windows, there may be more than one nameserver specified in the same
1021 * registry key, so we parse it as a space or comma seperated list.
1030 while (*p && !ISSPACE(*p) && *p != ',')
1039 /* Skip multiple spaces or trailing spaces */
1046 /* This is the part that actually sets the nameserver */
1047 addr.s_addr = inet_addr(begin);
1048 if (addr.s_addr == INADDR_NONE)
1050 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1053 newserv[*nservers].addr = addr;
1062 /* Add a nameserver entry, if this is a valid address. */
1063 addr.s_addr = inet_addr(str);
1064 if (addr.s_addr == INADDR_NONE)
1065 return ARES_SUCCESS;
1066 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1069 newserv[*nservers].addr = addr;
1073 return ARES_SUCCESS;
1077 static int config_sortlist(struct apattern **sortlist, int *nsort,
1080 struct apattern pat;
1083 /* Add sortlist entries. */
1084 while (*str && *str != ';')
1087 char ipbuf[16], ipbufpfx[32];
1088 /* Find just the IP */
1090 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1092 memcpy(ipbuf, str, (int)(q-str));
1093 ipbuf[(int)(q-str)] = '\0';
1094 /* Find the prefix */
1097 const char *str2 = q+1;
1098 while (*q && *q != ';' && !ISSPACE(*q))
1100 memcpy(ipbufpfx, str, (int)(q-str));
1101 ipbufpfx[(int)(q-str)] = '\0';
1106 /* Lets see if it is CIDR */
1107 /* First we'll try IPv6 */
1108 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1110 sizeof(pat.addr.addr6))) > 0)
1112 pat.type = PATTERN_CIDR;
1113 pat.mask.bits = (unsigned short)bits;
1114 pat.family = AF_INET6;
1115 if (!sortlist_alloc(sortlist, nsort, &pat))
1119 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addr.addr4,
1120 sizeof(pat.addr.addr4))) > 0)
1122 pat.type = PATTERN_CIDR;
1123 pat.mask.bits = (unsigned short)bits;
1124 pat.family = AF_INET;
1125 if (!sortlist_alloc(sortlist, nsort, &pat))
1128 /* See if it is just a regular IP */
1129 else if (ip_addr(ipbuf, (int)(q-str), &pat.addr.addr4) == 0)
1133 memcpy(ipbuf, str, (int)(q-str));
1134 ipbuf[(int)(q-str)] = '\0';
1135 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr.addr4) != 0)
1140 pat.family = AF_INET;
1141 pat.type = PATTERN_MASK;
1142 if (!sortlist_alloc(sortlist, nsort, &pat))
1147 while (*q && *q != ';' && !ISSPACE(*q))
1151 while (ISSPACE(*str))
1155 return ARES_SUCCESS;
1159 static int set_search(ares_channel channel, const char *str)
1164 if(channel->ndomains != -1) {
1165 /* if we already have some domains present, free them first */
1166 for(n=0; n < channel->ndomains; n++)
1167 free(channel->domains[n]);
1168 free(channel->domains);
1169 channel->domains = NULL;
1170 channel->ndomains = -1;
1173 /* Count the domains given. */
1178 while (*p && !ISSPACE(*p))
1187 channel->ndomains = 0;
1188 return ARES_SUCCESS;
1191 channel->domains = malloc(n * sizeof(char *));
1192 if (!channel->domains)
1195 /* Now copy the domains. */
1200 channel->ndomains = n;
1202 while (*q && !ISSPACE(*q))
1204 channel->domains[n] = malloc(q - p + 1);
1205 if (!channel->domains[n])
1207 memcpy(channel->domains[n], p, q - p);
1208 channel->domains[n][q - p] = 0;
1214 channel->ndomains = n;
1216 return ARES_SUCCESS;
1219 static int set_options(ares_channel channel, const char *str)
1221 const char *p, *q, *val;
1227 while (*q && !ISSPACE(*q))
1229 val = try_option(p, q, "ndots:");
1230 if (val && channel->ndots == -1)
1231 channel->ndots = atoi(val);
1232 val = try_option(p, q, "retrans:");
1233 if (val && channel->timeout == -1)
1234 channel->timeout = atoi(val);
1235 val = try_option(p, q, "retry:");
1236 if (val && channel->tries == -1)
1237 channel->tries = atoi(val);
1243 return ARES_SUCCESS;
1247 static char *try_config(char *s, const char *opt)
1252 if (strncmp(s, opt, len) != 0 || !ISSPACE(s[len]))
1262 static const char *try_option(const char *p, const char *q, const char *opt)
1264 size_t len = strlen(opt);
1265 return ((size_t)(q - p) > len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1269 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1270 struct apattern *pat)
1272 struct apattern *newsort;
1273 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1276 newsort[*nsort] = *pat;
1277 *sortlist = newsort;
1282 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1285 /* Four octets and three periods yields at most 15 characters. */
1289 addr->s_addr = inet_addr(ipbuf);
1290 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1295 static void natural_mask(struct apattern *pat)
1297 struct in_addr addr;
1299 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1302 addr.s_addr = ntohl(pat->addr.addr4.s_addr);
1304 /* This is out of date in the CIDR world, but some people might
1307 if (IN_CLASSA(addr.s_addr))
1308 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSA_NET);
1309 else if (IN_CLASSB(addr.s_addr))
1310 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSB_NET);
1312 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSC_NET);
1315 /* initialize an rc4 key. If possible a cryptographically secure random key
1316 is generated using a suitable function (for example win32's RtlGenRandom as
1318 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1319 otherwise the code defaults to cross-platform albeit less secure mechanism
1322 static void randomize_key(unsigned char* key,int key_data_len)
1327 HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1329 BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1330 (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1331 if (pfn && pfn(key,key_data_len) )
1339 FILE *f = fopen(RANDOM_FILE, "rb");
1342 size_t rc = fread(buffer, key_data_len, 1, f);
1343 for(i=0; i<rc && counter < key_data_len; i++)
1344 key[counter++]=buffer[i];
1350 if ( !randomized ) {
1351 for (;counter<key_data_len;counter++)
1352 key[counter]=(unsigned char)(rand() % 256);
1356 static int init_id_key(rc4_key* key,int key_data_len)
1358 unsigned char index1;
1359 unsigned char index2;
1360 unsigned char* state;
1362 unsigned char *key_data_ptr = 0;
1364 key_data_ptr = calloc(1,key_data_len);
1368 randomize_key(key->state,key_data_len);
1369 state = &key->state[0];
1370 for(counter = 0; counter < 256; counter++)
1371 /* unnecessary AND but it keeps some compilers happier */
1372 state[counter] = (unsigned char)(counter & 0xff);
1377 for(counter = 0; counter < 256; counter++)
1379 index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1381 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1383 index1 = (unsigned char)((index1 + 1) % key_data_len);
1386 return ARES_SUCCESS;
1389 short ares__generate_new_id(rc4_key* key)
1392 ares__rc4(key, (unsigned char *)&r, sizeof(r));