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 #include <sys/param.h>
27 #ifdef HAVE_SYS_TIME_H
31 #ifdef HAVE_SYS_SOCKET_H
32 #include <sys/socket.h>
35 #include <netinet/in.h>
36 #include <arpa/inet.h>
38 #include <arpa/nameser.h>
39 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
40 #include <arpa/nameser_compat.h>
46 #include <process.h> /* Some have getpid() here */
57 #include "ares_private.h"
58 #include "inet_net_pton.h"
61 #undef WIN32 /* Redefined in MingW/MSVC headers */
64 static int init_by_options(ares_channel channel, const struct ares_options *options,
66 static int init_by_environment(ares_channel channel);
67 static int init_by_resolv_conf(ares_channel channel);
68 static int init_by_defaults(ares_channel channel);
70 static int config_nameserver(struct server_state **servers, int *nservers,
72 static int set_search(ares_channel channel, const char *str);
73 static int set_options(ares_channel channel, const char *str);
74 static const char *try_option(const char *p, const char *q, const char *opt);
75 static void init_id_key(rc4_key* key,int key_data_len);
78 static int sortlist_alloc(struct apattern **sortlist, int *nsort, struct apattern *pat);
79 static int ip_addr(const char *s, int len, struct in_addr *addr);
80 static void natural_mask(struct apattern *pat);
81 static int config_domain(ares_channel channel, char *str);
82 static int config_lookup(ares_channel channel, const char *str,
83 const char *bindch, const char *filech);
84 static int config_sortlist(struct apattern **sortlist, int *nsort,
86 static char *try_config(char *s, const char *opt);
89 #define ARES_CONFIG_CHECK(x) (x->lookups && x->nsort > -1 && \
92 x->ndots > -1 && x->timeout > -1 && \
95 int ares_init(ares_channel *channelptr)
97 return ares_init_options(channelptr, NULL, 0);
100 int ares_init_options(ares_channel *channelptr, struct ares_options *options,
103 ares_channel channel;
105 int status = ARES_SUCCESS;
106 struct server_state *server;
109 const char *env = getenv("CARES_MEMDEBUG");
113 env = getenv("CARES_MEMLIMIT");
115 curl_memlimit(atoi(env));
118 channel = malloc(sizeof(struct ares_channeldata));
124 /* Set everything to distinguished values so we know they haven't
128 channel->timeout = -1;
131 channel->udp_port = -1;
132 channel->tcp_port = -1;
133 channel->nservers = -1;
134 channel->ndomains = -1;
136 channel->lookups = NULL;
137 channel->queries = NULL;
138 channel->domains = NULL;
139 channel->sortlist = NULL;
140 channel->servers = NULL;
141 channel->sock_state_cb = NULL;
142 channel->sock_state_cb_data = NULL;
144 /* Initialize configuration by each of the four sources, from highest
145 * precedence to lowest.
148 if (status == ARES_SUCCESS) {
149 status = init_by_options(channel, options, optmask);
150 if (status != ARES_SUCCESS)
151 DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
152 ares_strerror(status)));
154 if (status == ARES_SUCCESS) {
155 status = init_by_environment(channel);
156 if (status != ARES_SUCCESS)
157 DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
158 ares_strerror(status)));
160 if (status == ARES_SUCCESS) {
161 status = init_by_resolv_conf(channel);
162 if (status != ARES_SUCCESS)
163 DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
164 ares_strerror(status)));
166 if (status == ARES_SUCCESS) {
167 status = init_by_defaults(channel);
168 if (status != ARES_SUCCESS)
169 DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
170 ares_strerror(status)));
172 if (status != ARES_SUCCESS)
174 /* Something failed; clean up memory we may have allocated. */
175 if (channel->servers)
176 free(channel->servers);
177 if (channel->domains)
179 for (i = 0; i < channel->ndomains; i++)
180 free(channel->domains[i]);
181 free(channel->domains);
183 if (channel->sortlist)
184 free(channel->sortlist);
186 free(channel->lookups);
191 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
192 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
193 channel->nservers = 1;
195 /* Initialize server states. */
196 for (i = 0; i < channel->nservers; i++)
198 server = &channel->servers[i];
199 server->udp_socket = ARES_SOCKET_BAD;
200 server->tcp_socket = ARES_SOCKET_BAD;
201 server->tcp_lenbuf_pos = 0;
202 server->tcp_buffer = NULL;
203 server->qhead = NULL;
204 server->qtail = NULL;
207 init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
209 channel->next_id = ares__generate_new_id(&channel->id_key);
210 channel->queries = NULL;
212 *channelptr = channel;
216 /* Save options from initialized channel */
217 int ares_save_options(ares_channel channel, struct ares_options *options,
222 /* Zero everything out */
223 memset(options, 0, sizeof(struct ares_options));
225 if (!ARES_CONFIG_CHECK(channel))
228 (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TIMEOUT|ARES_OPT_TRIES|ARES_OPT_NDOTS|
229 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
230 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
233 /* Copy easy stuff */
234 options->flags = channel->flags;
235 options->timeout = channel->timeout;
236 options->tries = channel->tries;
237 options->ndots = channel->ndots;
238 options->udp_port = channel->udp_port;
239 options->tcp_port = channel->tcp_port;
240 options->sock_state_cb = channel->sock_state_cb;
241 options->sock_state_cb_data = channel->sock_state_cb_data;
245 malloc(channel->nservers * sizeof(struct server_state));
246 if (!options->servers && channel->nservers != 0)
248 for (i = 0; i < channel->nservers; i++)
249 options->servers[i] = channel->servers[i].addr;
250 options->nservers = channel->nservers;
253 options->domains = malloc(channel->ndomains * sizeof(char *));
254 if (!options->domains)
256 for (i = 0; i < channel->ndomains; i++)
258 options->ndomains = i;
259 options->domains[i] = strdup(channel->domains[i]);
260 if (!options->domains[i])
263 options->ndomains = channel->ndomains;
266 options->lookups = strdup(channel->lookups);
267 if (!options->lookups)
271 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
272 if (!options->sortlist)
274 for (i = 0; i < channel->nsort; i++)
276 memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
277 sizeof(struct apattern));
279 options->nsort = channel->nsort;
284 static int init_by_options(ares_channel channel,
285 const struct ares_options *options,
291 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
292 channel->flags = options->flags;
293 if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
294 channel->timeout = options->timeout;
295 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
296 channel->tries = options->tries;
297 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
298 channel->ndots = options->ndots;
299 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
300 channel->udp_port = options->udp_port;
301 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
302 channel->tcp_port = options->tcp_port;
303 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
305 channel->sock_state_cb = options->sock_state_cb;
306 channel->sock_state_cb_data = options->sock_state_cb_data;
309 /* Copy the servers, if given. */
310 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
312 /* Avoid zero size allocations at any cost */
313 if (options->nservers > 0)
316 malloc(options->nservers * sizeof(struct server_state));
317 if (!channel->servers)
319 for (i = 0; i < options->nservers; i++)
320 channel->servers[i].addr = options->servers[i];
322 channel->nservers = options->nservers;
325 /* Copy the domains, if given. Keep channel->ndomains consistent so
326 * we can clean up in case of error.
328 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
330 /* Avoid zero size allocations at any cost */
331 if (options->ndomains > 0)
333 channel->domains = malloc(options->ndomains * sizeof(char *));
334 if (!channel->domains)
336 for (i = 0; i < options->ndomains; i++)
338 channel->ndomains = i;
339 channel->domains[i] = strdup(options->domains[i]);
340 if (!channel->domains[i])
344 channel->ndomains = options->ndomains;
347 /* Set lookups, if given. */
348 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
350 channel->lookups = strdup(options->lookups);
351 if (!channel->lookups)
356 if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
358 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
359 if (!channel->sortlist)
361 for (i = 0; i < options->nsort; i++)
363 memcpy(&(channel->sortlist[i]), &(options->sortlist[i]), sizeof(struct apattern));
365 channel->nsort = options->nsort;
371 static int init_by_environment(ares_channel channel)
373 const char *localdomain, *res_options;
376 localdomain = getenv("LOCALDOMAIN");
377 if (localdomain && channel->ndomains == -1)
379 status = set_search(channel, localdomain);
380 if (status != ARES_SUCCESS)
384 res_options = getenv("RES_OPTIONS");
387 status = set_options(channel, res_options);
388 if (status != ARES_SUCCESS)
397 * Warning: returns a dynamically allocated buffer, the user MUST
398 * use free() if the function returns 1
400 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
402 /* Test for the size we need */
406 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
407 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
409 *obuf = malloc(size+1);
413 if (RegQueryValueEx(hKey, subkey, 0, NULL,
414 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
427 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
429 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
430 DWORD enum_size = 39;
434 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
435 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
440 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
443 rc = get_res_nt(hVal, subkey, obuf);
451 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
453 FIXED_INFO *fi = alloca (sizeof(*fi));
454 DWORD size = sizeof (*fi);
455 typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
456 get_net_param_func GetNetworkParams; /* available only on Win-98/2000+ */
458 IP_ADDR_STRING *ipAddr;
461 size_t ip_size = sizeof("255.255.255.255,")-1;
462 size_t left = ret_size;
469 handle = LoadLibrary ("iphlpapi.dll");
473 GetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
474 if (!GetNetworkParams)
477 res = (*GetNetworkParams) (fi, &size);
478 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
482 if (!fi || (*GetNetworkParams) (fi, &size) != ERROR_SUCCESS)
487 printf ("Host Name: %s\n", fi->HostName);
488 printf ("Domain Name: %s\n", fi->DomainName);
489 printf ("DNS Servers:\n"
490 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
492 if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
493 inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
496 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
497 left -= ret - ret_buf;
501 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
502 ipAddr = ipAddr->Next, i++)
504 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
506 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
507 left -= ret - ret_buf;
511 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
516 FreeLibrary (handle);
518 if (debug && left <= ip_size)
519 printf ("Too many nameservers. Truncating to %d addressess", count);
526 static int init_by_resolv_conf(ares_channel channel)
529 int status = -1, nservers = 0, nsort = 0;
530 struct server_state *servers = NULL;
531 struct apattern *sortlist = NULL;
536 NameServer info via IPHLPAPI (IP helper API):
537 GetNetworkParams() should be the trusted source for this.
538 Available in Win-98/2000 and later. If that fail, fall-back to
539 registry information.
543 On Windows 9X, the DNS server can be found in:
544 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
546 On Windows NT/2000/XP/2003:
547 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
549 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
551 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
554 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
565 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
568 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
570 status = config_nameserver(&servers, &nservers, buf);
571 if (status == ARES_SUCCESS)
578 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
582 RegOpenKeyEx(mykey, "Interfaces", 0,
583 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
584 if (get_res_nt(mykey, NAMESERVER, &line))
586 status = config_nameserver(&servers, &nservers, line);
589 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
591 status = config_nameserver(&servers, &nservers, line);
594 /* Try the interfaces */
595 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
597 status = config_nameserver(&servers, &nservers, line);
600 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
602 status = config_nameserver(&servers, &nservers, line);
612 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
616 if ((result = RegQueryValueEx(
617 mykey, NAMESERVER, NULL, &data_type,
620 ) == ERROR_SUCCESS ||
621 result == ERROR_MORE_DATA)
625 line = (char *)malloc(bytes+1);
626 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
627 (unsigned char *)line, &bytes) ==
630 status = config_nameserver(&servers, &nservers, line);
639 if (status == ARES_SUCCESS)
642 /* Catch the case when all the above checks fail (which happens when there
643 is no network card or the cable is unplugged) */
646 #elif defined(__riscos__)
648 /* Under RISC OS, name servers are listed in the
649 system variable Inet$Resolvers, space separated. */
651 line = getenv("Inet$Resolvers");
654 char *resolvers = strdup(line), *pos, *space;
661 space = strchr(pos, ' ');
664 status = config_nameserver(&servers, &nservers, pos);
665 if (status != ARES_SUCCESS)
670 if (status == ARES_SUCCESS)
676 #elif defined(WATT32)
680 for (i = 0; def_nameservers[i]; i++)
683 return ARES_SUCCESS; /* use localhost DNS server */
686 servers = calloc(sizeof(*servers), i);
690 for (i = 0; def_nameservers[i]; i++)
691 servers[i].addr.s_addr = htonl(def_nameservers[i]);
701 /* Don't read resolv.conf and friends if we don't have to */
702 if (ARES_CONFIG_CHECK(channel))
705 fp = fopen(PATH_RESOLV_CONF, "r");
707 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
709 if ((p = try_config(line, "domain")) && channel->ndomains == -1)
710 status = config_domain(channel, p);
711 else if ((p = try_config(line, "lookup")) && !channel->lookups)
712 status = config_lookup(channel, p, "bind", "file");
713 else if ((p = try_config(line, "search")) && channel->ndomains == -1)
714 status = set_search(channel, p);
715 else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
716 status = config_nameserver(&servers, &nservers, p);
717 else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
718 status = config_sortlist(&sortlist, &nsort, p);
719 else if ((p = try_config(line, "options")))
720 status = set_options(channel, p);
722 status = ARES_SUCCESS;
723 if (status != ARES_SUCCESS)
736 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
737 error, strerror(error)));
738 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
743 if ((status == ARES_EOF) && (!channel->lookups)) {
744 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
745 fp = fopen("/etc/nsswitch.conf", "r");
747 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
749 if ((p = try_config(line, "hosts:")) && !channel->lookups)
750 status = config_lookup(channel, p, "dns", "files");
762 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
763 error, strerror(error)));
764 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
770 if ((status == ARES_EOF) && (!channel->lookups)) {
771 /* Linux / GNU libc 2.x and possibly others have host.conf */
772 fp = fopen("/etc/host.conf", "r");
774 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
776 if ((p = try_config(line, "order")) && !channel->lookups)
777 status = config_lookup(channel, p, "bind", "hosts");
789 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
790 error, strerror(error)));
791 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
797 if ((status == ARES_EOF) && (!channel->lookups)) {
798 /* Tru64 uses /etc/svc.conf */
799 fp = fopen("/etc/svc.conf", "r");
801 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
803 if ((p = try_config(line, "hosts=")) && !channel->lookups)
804 status = config_lookup(channel, p, "bind", "local");
816 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
817 error, strerror(error)));
818 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
831 if (status != ARES_EOF)
835 if (sortlist != NULL)
840 /* If we got any name server entries, fill them in. */
846 channel->servers = servers;
847 channel->nservers = nservers;
850 /* If we got any sortlist entries, fill them in. */
853 channel->sortlist = sortlist;
854 channel->nsort = nsort;
860 static int init_by_defaults(ares_channel channel)
862 char hostname[MAXHOSTNAMELEN + 1];
864 if (channel->flags == -1)
866 if (channel->timeout == -1)
867 channel->timeout = DEFAULT_TIMEOUT;
868 if (channel->tries == -1)
869 channel->tries = DEFAULT_TRIES;
870 if (channel->ndots == -1)
872 if (channel->udp_port == -1)
873 channel->udp_port = htons(NAMESERVER_PORT);
874 if (channel->tcp_port == -1)
875 channel->tcp_port = htons(NAMESERVER_PORT);
877 if (channel->nservers == -1)
879 /* If nobody specified servers, try a local named. */
880 channel->servers = malloc(sizeof(struct server_state));
881 if (!channel->servers)
883 channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
884 channel->nservers = 1;
887 if (channel->ndomains == -1)
889 /* Derive a default domain search list from the kernel hostname,
890 * or set it to empty if the hostname isn't helpful.
892 if (gethostname(hostname, sizeof(hostname)) == -1
893 || !strchr(hostname, '.'))
895 channel->ndomains = 0;
899 channel->domains = malloc(sizeof(char *));
900 if (!channel->domains)
902 channel->ndomains = 0;
903 channel->domains[0] = strdup(strchr(hostname, '.') + 1);
904 if (!channel->domains[0])
906 channel->ndomains = 1;
910 if (channel->nsort == -1)
912 channel->sortlist = NULL;
916 if (!channel->lookups)
918 channel->lookups = strdup("fb");
919 if (!channel->lookups)
927 static int config_domain(ares_channel channel, char *str)
931 /* Set a single search domain. */
933 while (*q && !ISSPACE(*q))
936 return set_search(channel, str);
939 static int config_lookup(ares_channel channel, const char *str,
940 const char *bindch, const char *filech)
945 /* Set the lookup order. Only the first letter of each work
946 * is relevant, and it has to be "b" for DNS or "f" for the
947 * host file. Ignore everything else.
953 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
954 if (*p == *bindch) *l++ = 'b';
957 while (*p && !ISSPACE(*p) && (*p != ','))
959 while (*p && (ISSPACE(*p) || (*p == ',')))
963 channel->lookups = strdup(lookups);
964 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
969 static int config_nameserver(struct server_state **servers, int *nservers,
973 struct server_state *newserv;
974 /* On Windows, there may be more than one nameserver specified in the same
975 * registry key, so we parse it as a space or comma seperated list.
984 while (*p && !ISSPACE(*p) && *p != ',')
993 /* Skip multiple spaces or trailing spaces */
1000 /* This is the part that actually sets the nameserver */
1001 addr.s_addr = inet_addr(begin);
1002 if (addr.s_addr == INADDR_NONE)
1004 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1007 newserv[*nservers].addr = addr;
1016 /* Add a nameserver entry, if this is a valid address. */
1017 addr.s_addr = inet_addr(str);
1018 if (addr.s_addr == INADDR_NONE)
1019 return ARES_SUCCESS;
1020 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1023 newserv[*nservers].addr = addr;
1027 return ARES_SUCCESS;
1031 static int config_sortlist(struct apattern **sortlist, int *nsort,
1034 struct apattern pat;
1037 /* Add sortlist entries. */
1038 while (*str && *str != ';')
1041 char ipbuf[16], ipbufpfx[32];
1042 /* Find just the IP */
1044 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1046 memcpy(ipbuf, str, (int)(q-str));
1047 ipbuf[(int)(q-str)] = '\0';
1048 /* Find the prefix */
1051 const char *str2 = q+1;
1052 while (*q && *q != ';' && !ISSPACE(*q))
1054 memcpy(ipbufpfx, str, (int)(q-str));
1055 ipbufpfx[(int)(q-str)] = '\0';
1060 /* Lets see if it is CIDR */
1061 /* First we'll try IPv6 */
1062 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx ? ipbufpfx : ipbuf,
1064 sizeof(pat.addr.addr6))) > 0)
1066 pat.type = PATTERN_CIDR;
1067 pat.mask.bits = (unsigned short)bits;
1068 pat.family = AF_INET6;
1069 if (!sortlist_alloc(sortlist, nsort, &pat))
1073 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addr.addr4,
1074 sizeof(pat.addr.addr4))) > 0)
1076 pat.type = PATTERN_CIDR;
1077 pat.mask.bits = (unsigned short)bits;
1078 pat.family = AF_INET;
1079 if (!sortlist_alloc(sortlist, nsort, &pat))
1082 /* See if it is just a regular IP */
1083 else if (ip_addr(ipbuf, (int)(q-str), &pat.addr.addr4) == 0)
1087 memcpy(ipbuf, str, (int)(q-str));
1088 ipbuf[(int)(q-str)] = '\0';
1089 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr.addr4) != 0)
1094 pat.family = AF_INET;
1095 pat.type = PATTERN_MASK;
1096 if (!sortlist_alloc(sortlist, nsort, &pat))
1101 while (*q && *q != ';' && !ISSPACE(*q))
1105 while (ISSPACE(*str))
1109 return ARES_SUCCESS;
1113 static int set_search(ares_channel channel, const char *str)
1118 if(channel->ndomains != -1) {
1119 /* if we already have some domains present, free them first */
1120 for(n=0; n < channel->ndomains; n++)
1121 free(channel->domains[n]);
1122 free(channel->domains);
1123 channel->domains = NULL;
1124 channel->ndomains = -1;
1127 /* Count the domains given. */
1132 while (*p && !ISSPACE(*p))
1141 channel->ndomains = 0;
1142 return ARES_SUCCESS;
1145 channel->domains = malloc(n * sizeof(char *));
1146 if (!channel->domains)
1149 /* Now copy the domains. */
1154 channel->ndomains = n;
1156 while (*q && !ISSPACE(*q))
1158 channel->domains[n] = malloc(q - p + 1);
1159 if (!channel->domains[n])
1161 memcpy(channel->domains[n], p, q - p);
1162 channel->domains[n][q - p] = 0;
1168 channel->ndomains = n;
1170 return ARES_SUCCESS;
1173 static int set_options(ares_channel channel, const char *str)
1175 const char *p, *q, *val;
1181 while (*q && !ISSPACE(*q))
1183 val = try_option(p, q, "ndots:");
1184 if (val && channel->ndots == -1)
1185 channel->ndots = atoi(val);
1186 val = try_option(p, q, "retrans:");
1187 if (val && channel->timeout == -1)
1188 channel->timeout = atoi(val);
1189 val = try_option(p, q, "retry:");
1190 if (val && channel->tries == -1)
1191 channel->tries = atoi(val);
1197 return ARES_SUCCESS;
1201 static char *try_config(char *s, const char *opt)
1206 if (strncmp(s, opt, len) != 0 || !ISSPACE(s[len]))
1216 static const char *try_option(const char *p, const char *q, const char *opt)
1218 size_t len = strlen(opt);
1219 return ((size_t)(q - p) > len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1223 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1224 struct apattern *pat)
1226 struct apattern *newsort;
1227 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1230 newsort[*nsort] = *pat;
1231 *sortlist = newsort;
1236 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1239 /* Four octets and three periods yields at most 15 characters. */
1243 addr->s_addr = inet_addr(ipbuf);
1244 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1249 static void natural_mask(struct apattern *pat)
1251 struct in_addr addr;
1253 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1256 addr.s_addr = ntohl(pat->addr.addr4.s_addr);
1258 /* This is out of date in the CIDR world, but some people might
1261 if (IN_CLASSA(addr.s_addr))
1262 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSA_NET);
1263 else if (IN_CLASSB(addr.s_addr))
1264 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSB_NET);
1266 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSC_NET);
1269 /* initialize an rc4 key. If possible a cryptographically secure random key
1270 is generated using a suitable function (for example win32's RtlGenRandom as
1272 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1273 otherwise the code defaults to cross-platform albeit less secure mechanism
1276 static void randomize_key(unsigned char* key,int key_data_len)
1280 HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1282 BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1283 (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1284 if (pfn && pfn(key,key_data_len) )
1291 if ( !randomized ) {
1293 for (counter=0;counter<key_data_len;counter++)
1294 key[counter]=rand() % 256;
1298 static void init_id_key(rc4_key* key,int key_data_len)
1300 unsigned char index1;
1301 unsigned char index2;
1302 unsigned char* state;
1304 unsigned char *key_data_ptr = 0;
1306 key_data_ptr = calloc(1,key_data_len);
1307 randomize_key(key->state,key_data_len);
1308 state = &key->state[0];
1309 for(counter = 0; counter < 256; counter++)
1310 state[counter] = counter;
1315 for(counter = 0; counter < 256; counter++)
1317 index2 = (key_data_ptr[index1] + state[counter] +
1319 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1321 index1 = (index1 + 1) % key_data_len;
1327 short ares__generate_new_id(rc4_key* key)
1330 ares__rc4(key, (unsigned char *)&r, sizeof(r));