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;
247 if (channel->nservers) {
249 malloc(channel->nservers * sizeof(struct server_state));
250 if (!options->servers && channel->nservers != 0)
252 for (i = 0; i < channel->nservers; i++)
253 options->servers[i] = channel->servers[i].addr;
255 options->nservers = channel->nservers;
258 if (channel->ndomains) {
259 options->domains = malloc(channel->ndomains * sizeof(char *));
260 if (!options->domains)
263 for (i = 0; i < channel->ndomains; i++)
265 options->ndomains = i;
266 options->domains[i] = strdup(channel->domains[i]);
267 if (!options->domains[i])
271 options->ndomains = channel->ndomains;
274 if (channel->lookups) {
275 options->lookups = strdup(channel->lookups);
276 if (!options->lookups && channel->lookups)
281 if (channel->nsort) {
282 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
283 if (!options->sortlist)
285 for (i = 0; i < channel->nsort; i++)
287 memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
288 sizeof(struct apattern));
291 options->nsort = channel->nsort;
296 static int init_by_options(ares_channel channel,
297 const struct ares_options *options,
303 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
304 channel->flags = options->flags;
305 if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
306 channel->timeout = options->timeout;
307 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
308 channel->tries = options->tries;
309 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
310 channel->ndots = options->ndots;
311 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
312 channel->udp_port = options->udp_port;
313 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
314 channel->tcp_port = options->tcp_port;
315 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
317 channel->sock_state_cb = options->sock_state_cb;
318 channel->sock_state_cb_data = options->sock_state_cb_data;
321 /* Copy the servers, if given. */
322 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
324 /* Avoid zero size allocations at any cost */
325 if (options->nservers > 0)
328 malloc(options->nservers * sizeof(struct server_state));
329 if (!channel->servers)
331 for (i = 0; i < options->nservers; i++)
332 channel->servers[i].addr = options->servers[i];
334 channel->nservers = options->nservers;
337 /* Copy the domains, if given. Keep channel->ndomains consistent so
338 * we can clean up in case of error.
340 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
342 /* Avoid zero size allocations at any cost */
343 if (options->ndomains > 0)
345 channel->domains = malloc(options->ndomains * sizeof(char *));
346 if (!channel->domains)
348 for (i = 0; i < options->ndomains; i++)
350 channel->ndomains = i;
351 channel->domains[i] = strdup(options->domains[i]);
352 if (!channel->domains[i])
356 channel->ndomains = options->ndomains;
359 /* Set lookups, if given. */
360 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
362 channel->lookups = strdup(options->lookups);
363 if (!channel->lookups)
368 if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
370 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
371 if (!channel->sortlist)
373 for (i = 0; i < options->nsort; i++)
375 memcpy(&(channel->sortlist[i]), &(options->sortlist[i]), sizeof(struct apattern));
377 channel->nsort = options->nsort;
383 static int init_by_environment(ares_channel channel)
385 const char *localdomain, *res_options;
388 localdomain = getenv("LOCALDOMAIN");
389 if (localdomain && channel->ndomains == -1)
391 status = set_search(channel, localdomain);
392 if (status != ARES_SUCCESS)
396 res_options = getenv("RES_OPTIONS");
399 status = set_options(channel, res_options);
400 if (status != ARES_SUCCESS)
409 * Warning: returns a dynamically allocated buffer, the user MUST
410 * use free() if the function returns 1
412 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
414 /* Test for the size we need */
418 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
419 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
421 *obuf = malloc(size+1);
425 if (RegQueryValueEx(hKey, subkey, 0, NULL,
426 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
439 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
441 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
442 DWORD enum_size = 39;
446 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
447 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
452 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
455 rc = get_res_nt(hVal, subkey, obuf);
463 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
465 FIXED_INFO *fi = alloca (sizeof(*fi));
466 DWORD size = sizeof (*fi);
467 typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
468 get_net_param_func GetNetworkParams; /* available only on Win-98/2000+ */
470 IP_ADDR_STRING *ipAddr;
473 size_t ip_size = sizeof("255.255.255.255,")-1;
474 size_t left = ret_size;
481 handle = LoadLibrary ("iphlpapi.dll");
485 GetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
486 if (!GetNetworkParams)
489 res = (*GetNetworkParams) (fi, &size);
490 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
494 if (!fi || (*GetNetworkParams) (fi, &size) != ERROR_SUCCESS)
499 printf ("Host Name: %s\n", fi->HostName);
500 printf ("Domain Name: %s\n", fi->DomainName);
501 printf ("DNS Servers:\n"
502 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
504 if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
505 inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
508 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
509 left -= ret - ret_buf;
513 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
514 ipAddr = ipAddr->Next, i++)
516 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
518 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
519 left -= ret - ret_buf;
523 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
528 FreeLibrary (handle);
530 if (debug && left <= ip_size)
531 printf ("Too many nameservers. Truncating to %d addressess", count);
538 static int init_by_resolv_conf(ares_channel channel)
541 int status = -1, nservers = 0, nsort = 0;
542 struct server_state *servers = NULL;
543 struct apattern *sortlist = NULL;
548 NameServer info via IPHLPAPI (IP helper API):
549 GetNetworkParams() should be the trusted source for this.
550 Available in Win-98/2000 and later. If that fail, fall-back to
551 registry information.
555 On Windows 9X, the DNS server can be found in:
556 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
558 On Windows NT/2000/XP/2003:
559 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
561 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
563 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
566 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
577 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
580 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
582 status = config_nameserver(&servers, &nservers, buf);
583 if (status == ARES_SUCCESS)
590 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
594 RegOpenKeyEx(mykey, "Interfaces", 0,
595 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
596 if (get_res_nt(mykey, NAMESERVER, &line))
598 status = config_nameserver(&servers, &nservers, line);
601 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
603 status = config_nameserver(&servers, &nservers, line);
606 /* Try the interfaces */
607 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
609 status = config_nameserver(&servers, &nservers, line);
612 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
614 status = config_nameserver(&servers, &nservers, line);
624 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
628 if ((result = RegQueryValueEx(
629 mykey, NAMESERVER, NULL, &data_type,
632 ) == ERROR_SUCCESS ||
633 result == ERROR_MORE_DATA)
637 line = (char *)malloc(bytes+1);
638 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
639 (unsigned char *)line, &bytes) ==
642 status = config_nameserver(&servers, &nservers, line);
651 if (status == ARES_SUCCESS)
654 /* Catch the case when all the above checks fail (which happens when there
655 is no network card or the cable is unplugged) */
658 #elif defined(__riscos__)
660 /* Under RISC OS, name servers are listed in the
661 system variable Inet$Resolvers, space separated. */
663 line = getenv("Inet$Resolvers");
666 char *resolvers = strdup(line), *pos, *space;
673 space = strchr(pos, ' ');
676 status = config_nameserver(&servers, &nservers, pos);
677 if (status != ARES_SUCCESS)
682 if (status == ARES_SUCCESS)
688 #elif defined(WATT32)
692 for (i = 0; def_nameservers[i]; i++)
695 return ARES_SUCCESS; /* use localhost DNS server */
698 servers = calloc(sizeof(*servers), i);
702 for (i = 0; def_nameservers[i]; i++)
703 servers[i].addr.s_addr = htonl(def_nameservers[i]);
713 /* Don't read resolv.conf and friends if we don't have to */
714 if (ARES_CONFIG_CHECK(channel))
717 fp = fopen(PATH_RESOLV_CONF, "r");
719 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
721 if ((p = try_config(line, "domain")) && channel->ndomains == -1)
722 status = config_domain(channel, p);
723 else if ((p = try_config(line, "lookup")) && !channel->lookups)
724 status = config_lookup(channel, p, "bind", "file");
725 else if ((p = try_config(line, "search")) && channel->ndomains == -1)
726 status = set_search(channel, p);
727 else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
728 status = config_nameserver(&servers, &nservers, p);
729 else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
730 status = config_sortlist(&sortlist, &nsort, p);
731 else if ((p = try_config(line, "options")))
732 status = set_options(channel, p);
734 status = ARES_SUCCESS;
735 if (status != ARES_SUCCESS)
748 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
749 error, strerror(error)));
750 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
755 if ((status == ARES_EOF) && (!channel->lookups)) {
756 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
757 fp = fopen("/etc/nsswitch.conf", "r");
759 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
761 if ((p = try_config(line, "hosts:")) && !channel->lookups)
762 status = config_lookup(channel, p, "dns", "files");
774 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
775 error, strerror(error)));
776 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
782 if ((status == ARES_EOF) && (!channel->lookups)) {
783 /* Linux / GNU libc 2.x and possibly others have host.conf */
784 fp = fopen("/etc/host.conf", "r");
786 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
788 if ((p = try_config(line, "order")) && !channel->lookups)
789 status = config_lookup(channel, p, "bind", "hosts");
801 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
802 error, strerror(error)));
803 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
809 if ((status == ARES_EOF) && (!channel->lookups)) {
810 /* Tru64 uses /etc/svc.conf */
811 fp = fopen("/etc/svc.conf", "r");
813 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
815 if ((p = try_config(line, "hosts=")) && !channel->lookups)
816 status = config_lookup(channel, p, "bind", "local");
828 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
829 error, strerror(error)));
830 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
843 if (status != ARES_EOF)
847 if (sortlist != NULL)
852 /* If we got any name server entries, fill them in. */
858 channel->servers = servers;
859 channel->nservers = nservers;
862 /* If we got any sortlist entries, fill them in. */
865 channel->sortlist = sortlist;
866 channel->nsort = nsort;
872 static int init_by_defaults(ares_channel channel)
874 char hostname[MAXHOSTNAMELEN + 1];
876 if (channel->flags == -1)
878 if (channel->timeout == -1)
879 channel->timeout = DEFAULT_TIMEOUT;
880 if (channel->tries == -1)
881 channel->tries = DEFAULT_TRIES;
882 if (channel->ndots == -1)
884 if (channel->udp_port == -1)
885 channel->udp_port = htons(NAMESERVER_PORT);
886 if (channel->tcp_port == -1)
887 channel->tcp_port = htons(NAMESERVER_PORT);
889 if (channel->nservers == -1)
891 /* If nobody specified servers, try a local named. */
892 channel->servers = malloc(sizeof(struct server_state));
893 if (!channel->servers)
895 channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
896 channel->nservers = 1;
899 if (channel->ndomains == -1)
901 /* Derive a default domain search list from the kernel hostname,
902 * or set it to empty if the hostname isn't helpful.
904 if (gethostname(hostname, sizeof(hostname)) == -1
905 || !strchr(hostname, '.'))
907 channel->ndomains = 0;
911 channel->domains = malloc(sizeof(char *));
912 if (!channel->domains)
914 channel->ndomains = 0;
915 channel->domains[0] = strdup(strchr(hostname, '.') + 1);
916 if (!channel->domains[0])
918 channel->ndomains = 1;
922 if (channel->nsort == -1)
924 channel->sortlist = NULL;
928 if (!channel->lookups)
930 channel->lookups = strdup("fb");
931 if (!channel->lookups)
939 static int config_domain(ares_channel channel, char *str)
943 /* Set a single search domain. */
945 while (*q && !ISSPACE(*q))
948 return set_search(channel, str);
951 static int config_lookup(ares_channel channel, const char *str,
952 const char *bindch, const char *filech)
957 /* Set the lookup order. Only the first letter of each work
958 * is relevant, and it has to be "b" for DNS or "f" for the
959 * host file. Ignore everything else.
965 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
966 if (*p == *bindch) *l++ = 'b';
969 while (*p && !ISSPACE(*p) && (*p != ','))
971 while (*p && (ISSPACE(*p) || (*p == ',')))
975 channel->lookups = strdup(lookups);
976 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
981 static int config_nameserver(struct server_state **servers, int *nservers,
985 struct server_state *newserv;
986 /* On Windows, there may be more than one nameserver specified in the same
987 * registry key, so we parse it as a space or comma seperated list.
996 while (*p && !ISSPACE(*p) && *p != ',')
1005 /* Skip multiple spaces or trailing spaces */
1012 /* This is the part that actually sets the nameserver */
1013 addr.s_addr = inet_addr(begin);
1014 if (addr.s_addr == INADDR_NONE)
1016 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1019 newserv[*nservers].addr = addr;
1028 /* Add a nameserver entry, if this is a valid address. */
1029 addr.s_addr = inet_addr(str);
1030 if (addr.s_addr == INADDR_NONE)
1031 return ARES_SUCCESS;
1032 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1035 newserv[*nservers].addr = addr;
1039 return ARES_SUCCESS;
1043 static int config_sortlist(struct apattern **sortlist, int *nsort,
1046 struct apattern pat;
1049 /* Add sortlist entries. */
1050 while (*str && *str != ';')
1053 char ipbuf[16], ipbufpfx[32];
1054 /* Find just the IP */
1056 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1058 memcpy(ipbuf, str, (int)(q-str));
1059 ipbuf[(int)(q-str)] = '\0';
1060 /* Find the prefix */
1063 const char *str2 = q+1;
1064 while (*q && *q != ';' && !ISSPACE(*q))
1066 memcpy(ipbufpfx, str, (int)(q-str));
1067 ipbufpfx[(int)(q-str)] = '\0';
1072 /* Lets see if it is CIDR */
1073 /* First we'll try IPv6 */
1074 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1076 sizeof(pat.addr.addr6))) > 0)
1078 pat.type = PATTERN_CIDR;
1079 pat.mask.bits = (unsigned short)bits;
1080 pat.family = AF_INET6;
1081 if (!sortlist_alloc(sortlist, nsort, &pat))
1085 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addr.addr4,
1086 sizeof(pat.addr.addr4))) > 0)
1088 pat.type = PATTERN_CIDR;
1089 pat.mask.bits = (unsigned short)bits;
1090 pat.family = AF_INET;
1091 if (!sortlist_alloc(sortlist, nsort, &pat))
1094 /* See if it is just a regular IP */
1095 else if (ip_addr(ipbuf, (int)(q-str), &pat.addr.addr4) == 0)
1099 memcpy(ipbuf, str, (int)(q-str));
1100 ipbuf[(int)(q-str)] = '\0';
1101 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr.addr4) != 0)
1106 pat.family = AF_INET;
1107 pat.type = PATTERN_MASK;
1108 if (!sortlist_alloc(sortlist, nsort, &pat))
1113 while (*q && *q != ';' && !ISSPACE(*q))
1117 while (ISSPACE(*str))
1121 return ARES_SUCCESS;
1125 static int set_search(ares_channel channel, const char *str)
1130 if(channel->ndomains != -1) {
1131 /* if we already have some domains present, free them first */
1132 for(n=0; n < channel->ndomains; n++)
1133 free(channel->domains[n]);
1134 free(channel->domains);
1135 channel->domains = NULL;
1136 channel->ndomains = -1;
1139 /* Count the domains given. */
1144 while (*p && !ISSPACE(*p))
1153 channel->ndomains = 0;
1154 return ARES_SUCCESS;
1157 channel->domains = malloc(n * sizeof(char *));
1158 if (!channel->domains)
1161 /* Now copy the domains. */
1166 channel->ndomains = n;
1168 while (*q && !ISSPACE(*q))
1170 channel->domains[n] = malloc(q - p + 1);
1171 if (!channel->domains[n])
1173 memcpy(channel->domains[n], p, q - p);
1174 channel->domains[n][q - p] = 0;
1180 channel->ndomains = n;
1182 return ARES_SUCCESS;
1185 static int set_options(ares_channel channel, const char *str)
1187 const char *p, *q, *val;
1193 while (*q && !ISSPACE(*q))
1195 val = try_option(p, q, "ndots:");
1196 if (val && channel->ndots == -1)
1197 channel->ndots = atoi(val);
1198 val = try_option(p, q, "retrans:");
1199 if (val && channel->timeout == -1)
1200 channel->timeout = atoi(val);
1201 val = try_option(p, q, "retry:");
1202 if (val && channel->tries == -1)
1203 channel->tries = atoi(val);
1209 return ARES_SUCCESS;
1213 static char *try_config(char *s, const char *opt)
1218 if (strncmp(s, opt, len) != 0 || !ISSPACE(s[len]))
1228 static const char *try_option(const char *p, const char *q, const char *opt)
1230 size_t len = strlen(opt);
1231 return ((size_t)(q - p) > len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1235 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1236 struct apattern *pat)
1238 struct apattern *newsort;
1239 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1242 newsort[*nsort] = *pat;
1243 *sortlist = newsort;
1248 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1251 /* Four octets and three periods yields at most 15 characters. */
1255 addr->s_addr = inet_addr(ipbuf);
1256 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1261 static void natural_mask(struct apattern *pat)
1263 struct in_addr addr;
1265 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1268 addr.s_addr = ntohl(pat->addr.addr4.s_addr);
1270 /* This is out of date in the CIDR world, but some people might
1273 if (IN_CLASSA(addr.s_addr))
1274 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSA_NET);
1275 else if (IN_CLASSB(addr.s_addr))
1276 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSB_NET);
1278 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSC_NET);
1281 /* initialize an rc4 key. If possible a cryptographically secure random key
1282 is generated using a suitable function (for example win32's RtlGenRandom as
1284 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1285 otherwise the code defaults to cross-platform albeit less secure mechanism
1288 static void randomize_key(unsigned char* key,int key_data_len)
1293 HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1295 BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1296 (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1297 if (pfn && pfn(key,key_data_len) )
1305 FILE *f = fopen(RANDOM_FILE, "rb");
1308 size_t rc = fread(buffer, key_data_len, 1, f);
1309 for(i=0; i<rc && counter < key_data_len; i++)
1310 key[counter++]=buffer[i];
1316 if ( !randomized ) {
1317 for (;counter<key_data_len;counter++)
1318 key[counter]=rand() % 256;
1322 static void init_id_key(rc4_key* key,int key_data_len)
1324 unsigned char index1;
1325 unsigned char index2;
1326 unsigned char* state;
1328 unsigned char *key_data_ptr = 0;
1330 key_data_ptr = calloc(1,key_data_len);
1331 randomize_key(key->state,key_data_len);
1332 state = &key->state[0];
1333 for(counter = 0; counter < 256; counter++)
1334 /* unnecessary AND but it keeps some compilers happier */
1335 state[counter] = counter & 0xff;
1340 for(counter = 0; counter < 256; counter++)
1342 index2 = (key_data_ptr[index1] + state[counter] +
1344 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1346 index1 = (index1 + 1) % key_data_len;
1352 short ares__generate_new_id(rc4_key* key)
1355 ares__rc4(key, (unsigned char *)&r, sizeof(r));