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;
112 const char *env = getenv("CARES_MEMDEBUG");
116 env = getenv("CARES_MEMLIMIT");
118 curl_memlimit(atoi(env));
121 channel = malloc(sizeof(struct ares_channeldata));
127 /* Set everything to distinguished values so we know they haven't
131 channel->timeout = -1;
134 channel->udp_port = -1;
135 channel->tcp_port = -1;
136 channel->socket_send_buffer_size = -1;
137 channel->socket_receive_buffer_size = -1;
138 channel->nservers = -1;
139 channel->ndomains = -1;
141 channel->tcp_connection_generation = 0;
142 channel->lookups = NULL;
143 channel->domains = NULL;
144 channel->sortlist = NULL;
145 channel->servers = NULL;
146 channel->sock_state_cb = NULL;
147 channel->sock_state_cb_data = NULL;
149 channel->last_timeout_processed = (long)time(NULL);
151 /* Initialize our lists of queries */
152 ares__init_list_head(&(channel->all_queries));
153 for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
155 ares__init_list_head(&(channel->queries_by_qid[i]));
157 for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
159 ares__init_list_head(&(channel->queries_by_timeout[i]));
162 /* Initialize configuration by each of the four sources, from highest
163 * precedence to lowest.
166 if (status == ARES_SUCCESS) {
167 status = init_by_options(channel, options, optmask);
168 if (status != ARES_SUCCESS)
169 DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
170 ares_strerror(status)));
172 if (status == ARES_SUCCESS) {
173 status = init_by_environment(channel);
174 if (status != ARES_SUCCESS)
175 DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
176 ares_strerror(status)));
178 if (status == ARES_SUCCESS) {
179 status = init_by_resolv_conf(channel);
180 if (status != ARES_SUCCESS)
181 DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
182 ares_strerror(status)));
184 if (status == ARES_SUCCESS) {
185 status = init_by_defaults(channel);
186 if (status != ARES_SUCCESS)
187 DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
188 ares_strerror(status)));
191 /* Generate random key */
193 if (status == ARES_SUCCESS) {
194 status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
195 if (status == ARES_SUCCESS)
196 channel->next_id = ares__generate_new_id(&channel->id_key);
198 DEBUGF(fprintf(stderr, "Error: init_id_key failed: %s\n",
199 ares_strerror(status)));
202 if (status != ARES_SUCCESS)
204 /* Something failed; clean up memory we may have allocated. */
205 if (channel->servers)
206 free(channel->servers);
207 if (channel->domains)
209 for (i = 0; i < channel->ndomains; i++)
210 free(channel->domains[i]);
211 free(channel->domains);
213 if (channel->sortlist)
214 free(channel->sortlist);
216 free(channel->lookups);
221 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
222 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
223 channel->nservers = 1;
225 /* Initialize server states. */
226 for (i = 0; i < channel->nservers; i++)
228 server = &channel->servers[i];
229 server->udp_socket = ARES_SOCKET_BAD;
230 server->tcp_socket = ARES_SOCKET_BAD;
231 server->tcp_connection_generation = ++channel->tcp_connection_generation;
232 server->tcp_lenbuf_pos = 0;
233 server->tcp_buffer = NULL;
234 server->qhead = NULL;
235 server->qtail = NULL;
236 ares__init_list_head(&(server->queries_to_server));
237 server->channel = channel;
238 server->is_broken = 0;
241 *channelptr = channel;
245 /* Save options from initialized channel */
246 int ares_save_options(ares_channel channel, struct ares_options *options,
251 /* Zero everything out */
252 memset(options, 0, sizeof(struct ares_options));
254 if (!ARES_CONFIG_CHECK(channel))
257 (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TIMEOUT|ARES_OPT_TRIES|ARES_OPT_NDOTS|
258 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
259 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
262 /* Copy easy stuff */
263 options->flags = channel->flags;
264 options->timeout = channel->timeout;
265 options->tries = channel->tries;
266 options->ndots = channel->ndots;
267 options->udp_port = (unsigned short)channel->udp_port;
268 options->tcp_port = (unsigned short)channel->tcp_port;
269 options->sock_state_cb = channel->sock_state_cb;
270 options->sock_state_cb_data = channel->sock_state_cb_data;
273 if (channel->nservers) {
275 malloc(channel->nservers * sizeof(struct server_state));
276 if (!options->servers && channel->nservers != 0)
278 for (i = 0; i < channel->nservers; i++)
279 options->servers[i] = channel->servers[i].addr;
281 options->nservers = channel->nservers;
284 if (channel->ndomains) {
285 options->domains = malloc(channel->ndomains * sizeof(char *));
286 if (!options->domains)
289 for (i = 0; i < channel->ndomains; i++)
291 options->ndomains = i;
292 options->domains[i] = strdup(channel->domains[i]);
293 if (!options->domains[i])
297 options->ndomains = channel->ndomains;
300 if (channel->lookups) {
301 options->lookups = strdup(channel->lookups);
302 if (!options->lookups && channel->lookups)
307 if (channel->nsort) {
308 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
309 if (!options->sortlist)
311 for (i = 0; i < channel->nsort; i++)
313 memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
314 sizeof(struct apattern));
317 options->nsort = channel->nsort;
322 static int init_by_options(ares_channel channel,
323 const struct ares_options *options,
329 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
330 channel->flags = options->flags;
331 if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
332 channel->timeout = options->timeout;
333 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
334 channel->tries = options->tries;
335 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
336 channel->ndots = options->ndots;
337 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
338 channel->udp_port = options->udp_port;
339 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
340 channel->tcp_port = options->tcp_port;
341 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
343 channel->sock_state_cb = options->sock_state_cb;
344 channel->sock_state_cb_data = options->sock_state_cb_data;
346 if ((optmask & ARES_OPT_SOCK_SNDBUF)
347 && channel->socket_send_buffer_size == -1)
348 channel->socket_send_buffer_size = options->socket_send_buffer_size;
349 if ((optmask & ARES_OPT_SOCK_RCVBUF)
350 && channel->socket_receive_buffer_size == -1)
351 channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
353 /* Copy the servers, if given. */
354 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
356 /* Avoid zero size allocations at any cost */
357 if (options->nservers > 0)
360 malloc(options->nservers * sizeof(struct server_state));
361 if (!channel->servers)
363 for (i = 0; i < options->nservers; i++)
364 channel->servers[i].addr = options->servers[i];
366 channel->nservers = options->nservers;
369 /* Copy the domains, if given. Keep channel->ndomains consistent so
370 * we can clean up in case of error.
372 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
374 /* Avoid zero size allocations at any cost */
375 if (options->ndomains > 0)
377 channel->domains = malloc(options->ndomains * sizeof(char *));
378 if (!channel->domains)
380 for (i = 0; i < options->ndomains; i++)
382 channel->ndomains = i;
383 channel->domains[i] = strdup(options->domains[i]);
384 if (!channel->domains[i])
388 channel->ndomains = options->ndomains;
391 /* Set lookups, if given. */
392 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
394 channel->lookups = strdup(options->lookups);
395 if (!channel->lookups)
400 if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
402 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
403 if (!channel->sortlist)
405 for (i = 0; i < options->nsort; i++)
407 memcpy(&(channel->sortlist[i]), &(options->sortlist[i]), sizeof(struct apattern));
409 channel->nsort = options->nsort;
415 static int init_by_environment(ares_channel channel)
417 const char *localdomain, *res_options;
420 localdomain = getenv("LOCALDOMAIN");
421 if (localdomain && channel->ndomains == -1)
423 status = set_search(channel, localdomain);
424 if (status != ARES_SUCCESS)
428 res_options = getenv("RES_OPTIONS");
431 status = set_options(channel, res_options);
432 if (status != ARES_SUCCESS)
441 * Warning: returns a dynamically allocated buffer, the user MUST
442 * use free() if the function returns 1
444 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
446 /* Test for the size we need */
450 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
451 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
453 *obuf = malloc(size+1);
457 if (RegQueryValueEx(hKey, subkey, 0, NULL,
458 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
471 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
473 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
474 DWORD enum_size = 39;
478 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
479 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
484 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
487 rc = get_res_nt(hVal, subkey, obuf);
495 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
497 FIXED_INFO *fi = alloca (sizeof(*fi));
498 DWORD size = sizeof (*fi);
499 typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
500 get_net_param_func fpGetNetworkParams; /* available only on Win-98/2000+ */
502 IP_ADDR_STRING *ipAddr;
505 size_t ip_size = sizeof("255.255.255.255,")-1;
506 size_t left = ret_size;
513 handle = LoadLibrary ("iphlpapi.dll");
517 fpGetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
518 if (!fpGetNetworkParams)
521 res = (*fpGetNetworkParams) (fi, &size);
522 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
526 if (!fi || (*fpGetNetworkParams) (fi, &size) != ERROR_SUCCESS)
531 printf ("Host Name: %s\n", fi->HostName);
532 printf ("Domain Name: %s\n", fi->DomainName);
533 printf ("DNS Servers:\n"
534 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
536 if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
537 inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
540 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
541 left -= ret - ret_buf;
545 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
546 ipAddr = ipAddr->Next, i++)
548 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
550 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
551 left -= ret - ret_buf;
555 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
560 FreeLibrary (handle);
562 if (debug && left <= ip_size)
563 printf ("Too many nameservers. Truncating to %d addressess", count);
570 static int init_by_resolv_conf(ares_channel channel)
573 int status = -1, nservers = 0, nsort = 0;
574 struct server_state *servers = NULL;
575 struct apattern *sortlist = NULL;
580 NameServer info via IPHLPAPI (IP helper API):
581 GetNetworkParams() should be the trusted source for this.
582 Available in Win-98/2000 and later. If that fail, fall-back to
583 registry information.
587 On Windows 9X, the DNS server can be found in:
588 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
590 On Windows NT/2000/XP/2003:
591 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
593 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
595 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
598 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
609 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
612 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
614 status = config_nameserver(&servers, &nservers, buf);
615 if (status == ARES_SUCCESS)
622 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
626 RegOpenKeyEx(mykey, "Interfaces", 0,
627 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
628 if (get_res_nt(mykey, NAMESERVER, &line))
630 status = config_nameserver(&servers, &nservers, line);
633 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
635 status = config_nameserver(&servers, &nservers, line);
638 /* Try the interfaces */
639 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
641 status = config_nameserver(&servers, &nservers, line);
644 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
646 status = config_nameserver(&servers, &nservers, line);
656 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
660 if ((result = RegQueryValueEx(
661 mykey, NAMESERVER, NULL, &data_type,
664 ) == ERROR_SUCCESS ||
665 result == ERROR_MORE_DATA)
669 line = (char *)malloc(bytes+1);
670 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
671 (unsigned char *)line, &bytes) ==
674 status = config_nameserver(&servers, &nservers, line);
683 if (status == ARES_SUCCESS)
686 /* Catch the case when all the above checks fail (which happens when there
687 is no network card or the cable is unplugged) */
690 #elif defined(__riscos__)
692 /* Under RISC OS, name servers are listed in the
693 system variable Inet$Resolvers, space separated. */
695 line = getenv("Inet$Resolvers");
698 char *resolvers = strdup(line), *pos, *space;
705 space = strchr(pos, ' ');
708 status = config_nameserver(&servers, &nservers, pos);
709 if (status != ARES_SUCCESS)
714 if (status == ARES_SUCCESS)
720 #elif defined(WATT32)
724 for (i = 0; def_nameservers[i]; i++)
727 return ARES_SUCCESS; /* use localhost DNS server */
730 servers = calloc(sizeof(*servers), i);
734 for (i = 0; def_nameservers[i]; i++)
735 servers[i].addr.s_addr = htonl(def_nameservers[i]);
745 /* Don't read resolv.conf and friends if we don't have to */
746 if (ARES_CONFIG_CHECK(channel))
749 fp = fopen(PATH_RESOLV_CONF, "r");
751 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
753 if ((p = try_config(line, "domain")) && channel->ndomains == -1)
754 status = config_domain(channel, p);
755 else if ((p = try_config(line, "lookup")) && !channel->lookups)
756 status = config_lookup(channel, p, "bind", "file");
757 else if ((p = try_config(line, "search")) && channel->ndomains == -1)
758 status = set_search(channel, p);
759 else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
760 status = config_nameserver(&servers, &nservers, p);
761 else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
762 status = config_sortlist(&sortlist, &nsort, p);
763 else if ((p = try_config(line, "options")))
764 status = set_options(channel, p);
766 status = ARES_SUCCESS;
767 if (status != ARES_SUCCESS)
780 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
781 error, strerror(error)));
782 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
787 if ((status == ARES_EOF) && (!channel->lookups)) {
788 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
789 fp = fopen("/etc/nsswitch.conf", "r");
791 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
793 if ((p = try_config(line, "hosts:")) && !channel->lookups)
794 status = config_lookup(channel, p, "dns", "files");
806 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
807 error, strerror(error)));
808 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
814 if ((status == ARES_EOF) && (!channel->lookups)) {
815 /* Linux / GNU libc 2.x and possibly others have host.conf */
816 fp = fopen("/etc/host.conf", "r");
818 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
820 if ((p = try_config(line, "order")) && !channel->lookups)
821 status = config_lookup(channel, p, "bind", "hosts");
833 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
834 error, strerror(error)));
835 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
841 if ((status == ARES_EOF) && (!channel->lookups)) {
842 /* Tru64 uses /etc/svc.conf */
843 fp = fopen("/etc/svc.conf", "r");
845 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
847 if ((p = try_config(line, "hosts=")) && !channel->lookups)
848 status = config_lookup(channel, p, "bind", "local");
860 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
861 error, strerror(error)));
862 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
875 if (status != ARES_EOF)
879 if (sortlist != NULL)
884 /* If we got any name server entries, fill them in. */
890 channel->servers = servers;
891 channel->nservers = nservers;
894 /* If we got any sortlist entries, fill them in. */
897 channel->sortlist = sortlist;
898 channel->nsort = nsort;
904 static int init_by_defaults(ares_channel channel)
906 char hostname[MAXHOSTNAMELEN + 1];
908 if (channel->flags == -1)
910 if (channel->timeout == -1)
911 channel->timeout = DEFAULT_TIMEOUT;
912 if (channel->tries == -1)
913 channel->tries = DEFAULT_TRIES;
914 if (channel->ndots == -1)
916 if (channel->udp_port == -1)
917 channel->udp_port = htons(NAMESERVER_PORT);
918 if (channel->tcp_port == -1)
919 channel->tcp_port = htons(NAMESERVER_PORT);
921 if (channel->nservers == -1)
923 /* If nobody specified servers, try a local named. */
924 channel->servers = malloc(sizeof(struct server_state));
925 if (!channel->servers)
927 channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
928 channel->nservers = 1;
931 if (channel->ndomains == -1)
933 /* Derive a default domain search list from the kernel hostname,
934 * or set it to empty if the hostname isn't helpful.
936 if (gethostname(hostname, sizeof(hostname)) == -1
937 || !strchr(hostname, '.'))
939 channel->ndomains = 0;
943 channel->domains = malloc(sizeof(char *));
944 if (!channel->domains)
946 channel->ndomains = 0;
947 channel->domains[0] = strdup(strchr(hostname, '.') + 1);
948 if (!channel->domains[0])
950 channel->ndomains = 1;
954 if (channel->nsort == -1)
956 channel->sortlist = NULL;
960 if (!channel->lookups)
962 channel->lookups = strdup("fb");
963 if (!channel->lookups)
971 static int config_domain(ares_channel channel, char *str)
975 /* Set a single search domain. */
977 while (*q && !ISSPACE(*q))
980 return set_search(channel, str);
983 static int config_lookup(ares_channel channel, const char *str,
984 const char *bindch, const char *filech)
989 /* Set the lookup order. Only the first letter of each work
990 * is relevant, and it has to be "b" for DNS or "f" for the
991 * host file. Ignore everything else.
997 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
998 if (*p == *bindch) *l++ = 'b';
1001 while (*p && !ISSPACE(*p) && (*p != ','))
1003 while (*p && (ISSPACE(*p) || (*p == ',')))
1007 channel->lookups = strdup(lookups);
1008 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1013 static int config_nameserver(struct server_state **servers, int *nservers,
1016 struct in_addr addr;
1017 struct server_state *newserv;
1018 /* On Windows, there may be more than one nameserver specified in the same
1019 * registry key, so we parse it as a space or comma seperated list.
1028 while (*p && !ISSPACE(*p) && *p != ',')
1037 /* Skip multiple spaces or trailing spaces */
1044 /* This is the part that actually sets the nameserver */
1045 addr.s_addr = inet_addr(begin);
1046 if (addr.s_addr == INADDR_NONE)
1048 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1051 newserv[*nservers].addr = addr;
1060 /* Add a nameserver entry, if this is a valid address. */
1061 addr.s_addr = inet_addr(str);
1062 if (addr.s_addr == INADDR_NONE)
1063 return ARES_SUCCESS;
1064 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1067 newserv[*nservers].addr = addr;
1071 return ARES_SUCCESS;
1075 static int config_sortlist(struct apattern **sortlist, int *nsort,
1078 struct apattern pat;
1081 /* Add sortlist entries. */
1082 while (*str && *str != ';')
1085 char ipbuf[16], ipbufpfx[32];
1086 /* Find just the IP */
1088 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1090 memcpy(ipbuf, str, (int)(q-str));
1091 ipbuf[(int)(q-str)] = '\0';
1092 /* Find the prefix */
1095 const char *str2 = q+1;
1096 while (*q && *q != ';' && !ISSPACE(*q))
1098 memcpy(ipbufpfx, str, (int)(q-str));
1099 ipbufpfx[(int)(q-str)] = '\0';
1104 /* Lets see if it is CIDR */
1105 /* First we'll try IPv6 */
1106 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1108 sizeof(pat.addr.addr6))) > 0)
1110 pat.type = PATTERN_CIDR;
1111 pat.mask.bits = (unsigned short)bits;
1112 pat.family = AF_INET6;
1113 if (!sortlist_alloc(sortlist, nsort, &pat))
1117 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addr.addr4,
1118 sizeof(pat.addr.addr4))) > 0)
1120 pat.type = PATTERN_CIDR;
1121 pat.mask.bits = (unsigned short)bits;
1122 pat.family = AF_INET;
1123 if (!sortlist_alloc(sortlist, nsort, &pat))
1126 /* See if it is just a regular IP */
1127 else if (ip_addr(ipbuf, (int)(q-str), &pat.addr.addr4) == 0)
1131 memcpy(ipbuf, str, (int)(q-str));
1132 ipbuf[(int)(q-str)] = '\0';
1133 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr.addr4) != 0)
1138 pat.family = AF_INET;
1139 pat.type = PATTERN_MASK;
1140 if (!sortlist_alloc(sortlist, nsort, &pat))
1145 while (*q && *q != ';' && !ISSPACE(*q))
1149 while (ISSPACE(*str))
1153 return ARES_SUCCESS;
1157 static int set_search(ares_channel channel, const char *str)
1162 if(channel->ndomains != -1) {
1163 /* if we already have some domains present, free them first */
1164 for(n=0; n < channel->ndomains; n++)
1165 free(channel->domains[n]);
1166 free(channel->domains);
1167 channel->domains = NULL;
1168 channel->ndomains = -1;
1171 /* Count the domains given. */
1176 while (*p && !ISSPACE(*p))
1185 channel->ndomains = 0;
1186 return ARES_SUCCESS;
1189 channel->domains = malloc(n * sizeof(char *));
1190 if (!channel->domains)
1193 /* Now copy the domains. */
1198 channel->ndomains = n;
1200 while (*q && !ISSPACE(*q))
1202 channel->domains[n] = malloc(q - p + 1);
1203 if (!channel->domains[n])
1205 memcpy(channel->domains[n], p, q - p);
1206 channel->domains[n][q - p] = 0;
1212 channel->ndomains = n;
1214 return ARES_SUCCESS;
1217 static int set_options(ares_channel channel, const char *str)
1219 const char *p, *q, *val;
1225 while (*q && !ISSPACE(*q))
1227 val = try_option(p, q, "ndots:");
1228 if (val && channel->ndots == -1)
1229 channel->ndots = atoi(val);
1230 val = try_option(p, q, "retrans:");
1231 if (val && channel->timeout == -1)
1232 channel->timeout = atoi(val);
1233 val = try_option(p, q, "retry:");
1234 if (val && channel->tries == -1)
1235 channel->tries = atoi(val);
1241 return ARES_SUCCESS;
1245 static char *try_config(char *s, const char *opt)
1250 if (strncmp(s, opt, len) != 0 || !ISSPACE(s[len]))
1260 static const char *try_option(const char *p, const char *q, const char *opt)
1262 size_t len = strlen(opt);
1263 return ((size_t)(q - p) > len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1267 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1268 struct apattern *pat)
1270 struct apattern *newsort;
1271 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1274 newsort[*nsort] = *pat;
1275 *sortlist = newsort;
1280 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1283 /* Four octets and three periods yields at most 15 characters. */
1287 addr->s_addr = inet_addr(ipbuf);
1288 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1293 static void natural_mask(struct apattern *pat)
1295 struct in_addr addr;
1297 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1300 addr.s_addr = ntohl(pat->addr.addr4.s_addr);
1302 /* This is out of date in the CIDR world, but some people might
1305 if (IN_CLASSA(addr.s_addr))
1306 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSA_NET);
1307 else if (IN_CLASSB(addr.s_addr))
1308 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSB_NET);
1310 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSC_NET);
1313 /* initialize an rc4 key. If possible a cryptographically secure random key
1314 is generated using a suitable function (for example win32's RtlGenRandom as
1316 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1317 otherwise the code defaults to cross-platform albeit less secure mechanism
1320 static void randomize_key(unsigned char* key,int key_data_len)
1325 HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1327 BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1328 (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1329 if (pfn && pfn(key,key_data_len) )
1336 FILE *f = fopen(RANDOM_FILE, "rb");
1338 counter = fread(key, 1, key_data_len, f);
1344 if ( !randomized ) {
1345 for (;counter<key_data_len;counter++)
1346 key[counter]=(unsigned char)(rand() % 256);
1350 static int init_id_key(rc4_key* key,int key_data_len)
1352 unsigned char index1;
1353 unsigned char index2;
1354 unsigned char* state;
1356 unsigned char *key_data_ptr = 0;
1358 key_data_ptr = calloc(1,key_data_len);
1362 randomize_key(key->state,key_data_len);
1363 state = &key->state[0];
1364 for(counter = 0; counter < 256; counter++)
1365 /* unnecessary AND but it keeps some compilers happier */
1366 state[counter] = (unsigned char)(counter & 0xff);
1371 for(counter = 0; counter < 256; counter++)
1373 index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1375 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1377 index1 = (unsigned char)((index1 + 1) % key_data_len);
1380 return ARES_SUCCESS;
1383 short ares__generate_new_id(rc4_key* key)
1386 ares__rc4(key, (unsigned char *)&r, sizeof(r));