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 void 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->nservers = -1;
137 channel->ndomains = -1;
139 channel->lookups = NULL;
140 channel->queries = NULL;
141 channel->domains = NULL;
142 channel->sortlist = NULL;
143 channel->servers = NULL;
144 channel->sock_state_cb = NULL;
145 channel->sock_state_cb_data = NULL;
147 /* Initialize configuration by each of the four sources, from highest
148 * precedence to lowest.
151 if (status == ARES_SUCCESS) {
152 status = init_by_options(channel, options, optmask);
153 if (status != ARES_SUCCESS)
154 DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
155 ares_strerror(status)));
157 if (status == ARES_SUCCESS) {
158 status = init_by_environment(channel);
159 if (status != ARES_SUCCESS)
160 DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
161 ares_strerror(status)));
163 if (status == ARES_SUCCESS) {
164 status = init_by_resolv_conf(channel);
165 if (status != ARES_SUCCESS)
166 DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
167 ares_strerror(status)));
169 if (status == ARES_SUCCESS) {
170 status = init_by_defaults(channel);
171 if (status != ARES_SUCCESS)
172 DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
173 ares_strerror(status)));
175 if (status != ARES_SUCCESS)
177 /* Something failed; clean up memory we may have allocated. */
178 if (channel->servers)
179 free(channel->servers);
180 if (channel->domains)
182 for (i = 0; i < channel->ndomains; i++)
183 free(channel->domains[i]);
184 free(channel->domains);
186 if (channel->sortlist)
187 free(channel->sortlist);
189 free(channel->lookups);
194 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
195 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
196 channel->nservers = 1;
198 /* Initialize server states. */
199 for (i = 0; i < channel->nservers; i++)
201 server = &channel->servers[i];
202 server->udp_socket = ARES_SOCKET_BAD;
203 server->tcp_socket = ARES_SOCKET_BAD;
204 server->tcp_lenbuf_pos = 0;
205 server->tcp_buffer = NULL;
206 server->qhead = NULL;
207 server->qtail = NULL;
210 init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
212 channel->next_id = ares__generate_new_id(&channel->id_key);
213 channel->queries = NULL;
215 *channelptr = channel;
219 /* Save options from initialized channel */
220 int ares_save_options(ares_channel channel, struct ares_options *options,
225 /* Zero everything out */
226 memset(options, 0, sizeof(struct ares_options));
228 if (!ARES_CONFIG_CHECK(channel))
231 (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TIMEOUT|ARES_OPT_TRIES|ARES_OPT_NDOTS|
232 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
233 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
236 /* Copy easy stuff */
237 options->flags = channel->flags;
238 options->timeout = channel->timeout;
239 options->tries = channel->tries;
240 options->ndots = channel->ndots;
241 options->udp_port = channel->udp_port;
242 options->tcp_port = channel->tcp_port;
243 options->sock_state_cb = channel->sock_state_cb;
244 options->sock_state_cb_data = channel->sock_state_cb_data;
248 malloc(channel->nservers * sizeof(struct server_state));
249 if (!options->servers && channel->nservers != 0)
251 for (i = 0; i < channel->nservers; i++)
252 options->servers[i] = channel->servers[i].addr;
253 options->nservers = channel->nservers;
256 options->domains = malloc(channel->ndomains * sizeof(char *));
257 if (!options->domains)
259 for (i = 0; i < channel->ndomains; i++)
261 options->ndomains = i;
262 options->domains[i] = strdup(channel->domains[i]);
263 if (!options->domains[i])
266 options->ndomains = channel->ndomains;
269 options->lookups = strdup(channel->lookups);
270 if (!options->lookups)
274 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
275 if (!options->sortlist)
277 for (i = 0; i < channel->nsort; i++)
279 memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
280 sizeof(struct apattern));
282 options->nsort = channel->nsort;
287 static int init_by_options(ares_channel channel,
288 const struct ares_options *options,
294 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
295 channel->flags = options->flags;
296 if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
297 channel->timeout = options->timeout;
298 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
299 channel->tries = options->tries;
300 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
301 channel->ndots = options->ndots;
302 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
303 channel->udp_port = options->udp_port;
304 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
305 channel->tcp_port = options->tcp_port;
306 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
308 channel->sock_state_cb = options->sock_state_cb;
309 channel->sock_state_cb_data = options->sock_state_cb_data;
312 /* Copy the servers, if given. */
313 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
315 /* Avoid zero size allocations at any cost */
316 if (options->nservers > 0)
319 malloc(options->nservers * sizeof(struct server_state));
320 if (!channel->servers)
322 for (i = 0; i < options->nservers; i++)
323 channel->servers[i].addr = options->servers[i];
325 channel->nservers = options->nservers;
328 /* Copy the domains, if given. Keep channel->ndomains consistent so
329 * we can clean up in case of error.
331 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
333 /* Avoid zero size allocations at any cost */
334 if (options->ndomains > 0)
336 channel->domains = malloc(options->ndomains * sizeof(char *));
337 if (!channel->domains)
339 for (i = 0; i < options->ndomains; i++)
341 channel->ndomains = i;
342 channel->domains[i] = strdup(options->domains[i]);
343 if (!channel->domains[i])
347 channel->ndomains = options->ndomains;
350 /* Set lookups, if given. */
351 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
353 channel->lookups = strdup(options->lookups);
354 if (!channel->lookups)
359 if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
361 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
362 if (!channel->sortlist)
364 for (i = 0; i < options->nsort; i++)
366 memcpy(&(channel->sortlist[i]), &(options->sortlist[i]), sizeof(struct apattern));
368 channel->nsort = options->nsort;
374 static int init_by_environment(ares_channel channel)
376 const char *localdomain, *res_options;
379 localdomain = getenv("LOCALDOMAIN");
380 if (localdomain && channel->ndomains == -1)
382 status = set_search(channel, localdomain);
383 if (status != ARES_SUCCESS)
387 res_options = getenv("RES_OPTIONS");
390 status = set_options(channel, res_options);
391 if (status != ARES_SUCCESS)
400 * Warning: returns a dynamically allocated buffer, the user MUST
401 * use free() if the function returns 1
403 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
405 /* Test for the size we need */
409 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
410 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
412 *obuf = malloc(size+1);
416 if (RegQueryValueEx(hKey, subkey, 0, NULL,
417 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
430 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
432 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
433 DWORD enum_size = 39;
437 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
438 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
443 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
446 rc = get_res_nt(hVal, subkey, obuf);
454 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
456 FIXED_INFO *fi = alloca (sizeof(*fi));
457 DWORD size = sizeof (*fi);
458 typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
459 get_net_param_func GetNetworkParams; /* available only on Win-98/2000+ */
461 IP_ADDR_STRING *ipAddr;
464 size_t ip_size = sizeof("255.255.255.255,")-1;
465 size_t left = ret_size;
472 handle = LoadLibrary ("iphlpapi.dll");
476 GetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
477 if (!GetNetworkParams)
480 res = (*GetNetworkParams) (fi, &size);
481 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
485 if (!fi || (*GetNetworkParams) (fi, &size) != ERROR_SUCCESS)
490 printf ("Host Name: %s\n", fi->HostName);
491 printf ("Domain Name: %s\n", fi->DomainName);
492 printf ("DNS Servers:\n"
493 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
495 if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
496 inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
499 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
500 left -= ret - ret_buf;
504 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
505 ipAddr = ipAddr->Next, i++)
507 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
509 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
510 left -= ret - ret_buf;
514 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
519 FreeLibrary (handle);
521 if (debug && left <= ip_size)
522 printf ("Too many nameservers. Truncating to %d addressess", count);
529 static int init_by_resolv_conf(ares_channel channel)
532 int status = -1, nservers = 0, nsort = 0;
533 struct server_state *servers = NULL;
534 struct apattern *sortlist = NULL;
539 NameServer info via IPHLPAPI (IP helper API):
540 GetNetworkParams() should be the trusted source for this.
541 Available in Win-98/2000 and later. If that fail, fall-back to
542 registry information.
546 On Windows 9X, the DNS server can be found in:
547 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
549 On Windows NT/2000/XP/2003:
550 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
552 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
554 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
557 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
568 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
571 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
573 status = config_nameserver(&servers, &nservers, buf);
574 if (status == ARES_SUCCESS)
581 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
585 RegOpenKeyEx(mykey, "Interfaces", 0,
586 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
587 if (get_res_nt(mykey, NAMESERVER, &line))
589 status = config_nameserver(&servers, &nservers, line);
592 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
594 status = config_nameserver(&servers, &nservers, line);
597 /* Try the interfaces */
598 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
600 status = config_nameserver(&servers, &nservers, line);
603 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
605 status = config_nameserver(&servers, &nservers, line);
615 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
619 if ((result = RegQueryValueEx(
620 mykey, NAMESERVER, NULL, &data_type,
623 ) == ERROR_SUCCESS ||
624 result == ERROR_MORE_DATA)
628 line = (char *)malloc(bytes+1);
629 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
630 (unsigned char *)line, &bytes) ==
633 status = config_nameserver(&servers, &nservers, line);
642 if (status == ARES_SUCCESS)
645 /* Catch the case when all the above checks fail (which happens when there
646 is no network card or the cable is unplugged) */
649 #elif defined(__riscos__)
651 /* Under RISC OS, name servers are listed in the
652 system variable Inet$Resolvers, space separated. */
654 line = getenv("Inet$Resolvers");
657 char *resolvers = strdup(line), *pos, *space;
664 space = strchr(pos, ' ');
667 status = config_nameserver(&servers, &nservers, pos);
668 if (status != ARES_SUCCESS)
673 if (status == ARES_SUCCESS)
679 #elif defined(WATT32)
683 for (i = 0; def_nameservers[i]; i++)
686 return ARES_SUCCESS; /* use localhost DNS server */
689 servers = calloc(sizeof(*servers), i);
693 for (i = 0; def_nameservers[i]; i++)
694 servers[i].addr.s_addr = htonl(def_nameservers[i]);
704 /* Don't read resolv.conf and friends if we don't have to */
705 if (ARES_CONFIG_CHECK(channel))
708 fp = fopen(PATH_RESOLV_CONF, "r");
710 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
712 if ((p = try_config(line, "domain")) && channel->ndomains == -1)
713 status = config_domain(channel, p);
714 else if ((p = try_config(line, "lookup")) && !channel->lookups)
715 status = config_lookup(channel, p, "bind", "file");
716 else if ((p = try_config(line, "search")) && channel->ndomains == -1)
717 status = set_search(channel, p);
718 else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
719 status = config_nameserver(&servers, &nservers, p);
720 else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
721 status = config_sortlist(&sortlist, &nsort, p);
722 else if ((p = try_config(line, "options")))
723 status = set_options(channel, p);
725 status = ARES_SUCCESS;
726 if (status != ARES_SUCCESS)
739 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
740 error, strerror(error)));
741 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
746 if ((status == ARES_EOF) && (!channel->lookups)) {
747 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
748 fp = fopen("/etc/nsswitch.conf", "r");
750 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
752 if ((p = try_config(line, "hosts:")) && !channel->lookups)
753 status = config_lookup(channel, p, "dns", "files");
765 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
766 error, strerror(error)));
767 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
773 if ((status == ARES_EOF) && (!channel->lookups)) {
774 /* Linux / GNU libc 2.x and possibly others have host.conf */
775 fp = fopen("/etc/host.conf", "r");
777 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
779 if ((p = try_config(line, "order")) && !channel->lookups)
780 status = config_lookup(channel, p, "bind", "hosts");
792 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
793 error, strerror(error)));
794 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
800 if ((status == ARES_EOF) && (!channel->lookups)) {
801 /* Tru64 uses /etc/svc.conf */
802 fp = fopen("/etc/svc.conf", "r");
804 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
806 if ((p = try_config(line, "hosts=")) && !channel->lookups)
807 status = config_lookup(channel, p, "bind", "local");
819 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
820 error, strerror(error)));
821 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
834 if (status != ARES_EOF)
838 if (sortlist != NULL)
843 /* If we got any name server entries, fill them in. */
849 channel->servers = servers;
850 channel->nservers = nservers;
853 /* If we got any sortlist entries, fill them in. */
856 channel->sortlist = sortlist;
857 channel->nsort = nsort;
863 static int init_by_defaults(ares_channel channel)
865 char hostname[MAXHOSTNAMELEN + 1];
867 if (channel->flags == -1)
869 if (channel->timeout == -1)
870 channel->timeout = DEFAULT_TIMEOUT;
871 if (channel->tries == -1)
872 channel->tries = DEFAULT_TRIES;
873 if (channel->ndots == -1)
875 if (channel->udp_port == -1)
876 channel->udp_port = htons(NAMESERVER_PORT);
877 if (channel->tcp_port == -1)
878 channel->tcp_port = htons(NAMESERVER_PORT);
880 if (channel->nservers == -1)
882 /* If nobody specified servers, try a local named. */
883 channel->servers = malloc(sizeof(struct server_state));
884 if (!channel->servers)
886 channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
887 channel->nservers = 1;
890 if (channel->ndomains == -1)
892 /* Derive a default domain search list from the kernel hostname,
893 * or set it to empty if the hostname isn't helpful.
895 if (gethostname(hostname, sizeof(hostname)) == -1
896 || !strchr(hostname, '.'))
898 channel->ndomains = 0;
902 channel->domains = malloc(sizeof(char *));
903 if (!channel->domains)
905 channel->ndomains = 0;
906 channel->domains[0] = strdup(strchr(hostname, '.') + 1);
907 if (!channel->domains[0])
909 channel->ndomains = 1;
913 if (channel->nsort == -1)
915 channel->sortlist = NULL;
919 if (!channel->lookups)
921 channel->lookups = strdup("fb");
922 if (!channel->lookups)
930 static int config_domain(ares_channel channel, char *str)
934 /* Set a single search domain. */
936 while (*q && !ISSPACE(*q))
939 return set_search(channel, str);
942 static int config_lookup(ares_channel channel, const char *str,
943 const char *bindch, const char *filech)
948 /* Set the lookup order. Only the first letter of each work
949 * is relevant, and it has to be "b" for DNS or "f" for the
950 * host file. Ignore everything else.
956 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
957 if (*p == *bindch) *l++ = 'b';
960 while (*p && !ISSPACE(*p) && (*p != ','))
962 while (*p && (ISSPACE(*p) || (*p == ',')))
966 channel->lookups = strdup(lookups);
967 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
972 static int config_nameserver(struct server_state **servers, int *nservers,
976 struct server_state *newserv;
977 /* On Windows, there may be more than one nameserver specified in the same
978 * registry key, so we parse it as a space or comma seperated list.
987 while (*p && !ISSPACE(*p) && *p != ',')
996 /* Skip multiple spaces or trailing spaces */
1003 /* This is the part that actually sets the nameserver */
1004 addr.s_addr = inet_addr(begin);
1005 if (addr.s_addr == INADDR_NONE)
1007 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1010 newserv[*nservers].addr = addr;
1019 /* Add a nameserver entry, if this is a valid address. */
1020 addr.s_addr = inet_addr(str);
1021 if (addr.s_addr == INADDR_NONE)
1022 return ARES_SUCCESS;
1023 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1026 newserv[*nservers].addr = addr;
1030 return ARES_SUCCESS;
1034 static int config_sortlist(struct apattern **sortlist, int *nsort,
1037 struct apattern pat;
1040 /* Add sortlist entries. */
1041 while (*str && *str != ';')
1044 char ipbuf[16], ipbufpfx[32];
1045 /* Find just the IP */
1047 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1049 memcpy(ipbuf, str, (int)(q-str));
1050 ipbuf[(int)(q-str)] = '\0';
1051 /* Find the prefix */
1054 const char *str2 = q+1;
1055 while (*q && *q != ';' && !ISSPACE(*q))
1057 memcpy(ipbufpfx, str, (int)(q-str));
1058 ipbufpfx[(int)(q-str)] = '\0';
1063 /* Lets see if it is CIDR */
1064 /* First we'll try IPv6 */
1065 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1067 sizeof(pat.addr.addr6))) > 0)
1069 pat.type = PATTERN_CIDR;
1070 pat.mask.bits = (unsigned short)bits;
1071 pat.family = AF_INET6;
1072 if (!sortlist_alloc(sortlist, nsort, &pat))
1076 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addr.addr4,
1077 sizeof(pat.addr.addr4))) > 0)
1079 pat.type = PATTERN_CIDR;
1080 pat.mask.bits = (unsigned short)bits;
1081 pat.family = AF_INET;
1082 if (!sortlist_alloc(sortlist, nsort, &pat))
1085 /* See if it is just a regular IP */
1086 else if (ip_addr(ipbuf, (int)(q-str), &pat.addr.addr4) == 0)
1090 memcpy(ipbuf, str, (int)(q-str));
1091 ipbuf[(int)(q-str)] = '\0';
1092 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr.addr4) != 0)
1097 pat.family = AF_INET;
1098 pat.type = PATTERN_MASK;
1099 if (!sortlist_alloc(sortlist, nsort, &pat))
1104 while (*q && *q != ';' && !ISSPACE(*q))
1108 while (ISSPACE(*str))
1112 return ARES_SUCCESS;
1116 static int set_search(ares_channel channel, const char *str)
1121 if(channel->ndomains != -1) {
1122 /* if we already have some domains present, free them first */
1123 for(n=0; n < channel->ndomains; n++)
1124 free(channel->domains[n]);
1125 free(channel->domains);
1126 channel->domains = NULL;
1127 channel->ndomains = -1;
1130 /* Count the domains given. */
1135 while (*p && !ISSPACE(*p))
1144 channel->ndomains = 0;
1145 return ARES_SUCCESS;
1148 channel->domains = malloc(n * sizeof(char *));
1149 if (!channel->domains)
1152 /* Now copy the domains. */
1157 channel->ndomains = n;
1159 while (*q && !ISSPACE(*q))
1161 channel->domains[n] = malloc(q - p + 1);
1162 if (!channel->domains[n])
1164 memcpy(channel->domains[n], p, q - p);
1165 channel->domains[n][q - p] = 0;
1171 channel->ndomains = n;
1173 return ARES_SUCCESS;
1176 static int set_options(ares_channel channel, const char *str)
1178 const char *p, *q, *val;
1184 while (*q && !ISSPACE(*q))
1186 val = try_option(p, q, "ndots:");
1187 if (val && channel->ndots == -1)
1188 channel->ndots = atoi(val);
1189 val = try_option(p, q, "retrans:");
1190 if (val && channel->timeout == -1)
1191 channel->timeout = atoi(val);
1192 val = try_option(p, q, "retry:");
1193 if (val && channel->tries == -1)
1194 channel->tries = atoi(val);
1200 return ARES_SUCCESS;
1204 static char *try_config(char *s, const char *opt)
1209 if (strncmp(s, opt, len) != 0 || !ISSPACE(s[len]))
1219 static const char *try_option(const char *p, const char *q, const char *opt)
1221 size_t len = strlen(opt);
1222 return ((size_t)(q - p) > len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1226 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1227 struct apattern *pat)
1229 struct apattern *newsort;
1230 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1233 newsort[*nsort] = *pat;
1234 *sortlist = newsort;
1239 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1242 /* Four octets and three periods yields at most 15 characters. */
1246 addr->s_addr = inet_addr(ipbuf);
1247 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1252 static void natural_mask(struct apattern *pat)
1254 struct in_addr addr;
1256 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1259 addr.s_addr = ntohl(pat->addr.addr4.s_addr);
1261 /* This is out of date in the CIDR world, but some people might
1264 if (IN_CLASSA(addr.s_addr))
1265 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSA_NET);
1266 else if (IN_CLASSB(addr.s_addr))
1267 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSB_NET);
1269 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSC_NET);
1272 /* initialize an rc4 key. If possible a cryptographically secure random key
1273 is generated using a suitable function (for example win32's RtlGenRandom as
1275 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1276 otherwise the code defaults to cross-platform albeit less secure mechanism
1279 static void randomize_key(unsigned char* key,int key_data_len)
1284 HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1286 BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1287 (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1288 if (pfn && pfn(key,key_data_len) )
1296 FILE *f = fopen(RANDOM_FILE, "rb");
1299 size_t rc = fread(buffer, key_data_len, 1, f);
1300 for(i=0; i<rc && counter < key_data_len; i++)
1301 key[counter++]=buffer[i];
1307 if ( !randomized ) {
1308 for (;counter<key_data_len;counter++)
1309 key[counter]=rand() % 256;
1313 static void init_id_key(rc4_key* key,int key_data_len)
1315 unsigned char index1;
1316 unsigned char index2;
1317 unsigned char* state;
1319 unsigned char *key_data_ptr = 0;
1321 key_data_ptr = calloc(1,key_data_len);
1322 randomize_key(key->state,key_data_len);
1323 state = &key->state[0];
1324 for(counter = 0; counter < 256; counter++)
1325 state[counter] = counter;
1330 for(counter = 0; counter < 256; counter++)
1332 index2 = (key_data_ptr[index1] + state[counter] +
1334 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1336 index1 = (index1 + 1) % key_data_len;
1342 short ares__generate_new_id(rc4_key* key)
1345 ares__rc4(key, (unsigned char *)&r, sizeof(r));