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->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->queries = NULL;
144 channel->domains = NULL;
145 channel->sortlist = NULL;
146 channel->servers = NULL;
147 channel->sock_state_cb = NULL;
148 channel->sock_state_cb_data = NULL;
150 /* Initialize configuration by each of the four sources, from highest
151 * precedence to lowest.
154 if (status == ARES_SUCCESS) {
155 status = init_by_options(channel, options, optmask);
156 if (status != ARES_SUCCESS)
157 DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
158 ares_strerror(status)));
160 if (status == ARES_SUCCESS) {
161 status = init_by_environment(channel);
162 if (status != ARES_SUCCESS)
163 DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
164 ares_strerror(status)));
166 if (status == ARES_SUCCESS) {
167 status = init_by_resolv_conf(channel);
168 if (status != ARES_SUCCESS)
169 DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
170 ares_strerror(status)));
172 if (status == ARES_SUCCESS) {
173 status = init_by_defaults(channel);
174 if (status != ARES_SUCCESS)
175 DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
176 ares_strerror(status)));
178 if (status != ARES_SUCCESS)
180 /* Something failed; clean up memory we may have allocated. */
181 if (channel->servers)
182 free(channel->servers);
183 if (channel->domains)
185 for (i = 0; i < channel->ndomains; i++)
186 free(channel->domains[i]);
187 free(channel->domains);
189 if (channel->sortlist)
190 free(channel->sortlist);
192 free(channel->lookups);
197 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
198 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
199 channel->nservers = 1;
201 /* Initialize server states. */
202 for (i = 0; i < channel->nservers; i++)
204 server = &channel->servers[i];
205 server->udp_socket = ARES_SOCKET_BAD;
206 server->tcp_socket = ARES_SOCKET_BAD;
207 server->tcp_connection_generation = ++channel->tcp_connection_generation;
208 server->tcp_lenbuf_pos = 0;
209 server->tcp_buffer = NULL;
210 server->qhead = NULL;
211 server->qtail = NULL;
212 server->is_broken = 0;
215 init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
217 channel->next_id = ares__generate_new_id(&channel->id_key);
218 channel->queries = NULL;
220 *channelptr = channel;
224 /* Save options from initialized channel */
225 int ares_save_options(ares_channel channel, struct ares_options *options,
230 /* Zero everything out */
231 memset(options, 0, sizeof(struct ares_options));
233 if (!ARES_CONFIG_CHECK(channel))
236 (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TIMEOUT|ARES_OPT_TRIES|ARES_OPT_NDOTS|
237 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
238 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
241 /* Copy easy stuff */
242 options->flags = channel->flags;
243 options->timeout = channel->timeout;
244 options->tries = channel->tries;
245 options->ndots = channel->ndots;
246 options->udp_port = channel->udp_port;
247 options->tcp_port = channel->tcp_port;
248 options->sock_state_cb = channel->sock_state_cb;
249 options->sock_state_cb_data = channel->sock_state_cb_data;
252 if (channel->nservers) {
254 malloc(channel->nservers * sizeof(struct server_state));
255 if (!options->servers && channel->nservers != 0)
257 for (i = 0; i < channel->nservers; i++)
258 options->servers[i] = channel->servers[i].addr;
260 options->nservers = channel->nservers;
263 if (channel->ndomains) {
264 options->domains = malloc(channel->ndomains * sizeof(char *));
265 if (!options->domains)
268 for (i = 0; i < channel->ndomains; i++)
270 options->ndomains = i;
271 options->domains[i] = strdup(channel->domains[i]);
272 if (!options->domains[i])
276 options->ndomains = channel->ndomains;
279 if (channel->lookups) {
280 options->lookups = strdup(channel->lookups);
281 if (!options->lookups && channel->lookups)
286 if (channel->nsort) {
287 options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
288 if (!options->sortlist)
290 for (i = 0; i < channel->nsort; i++)
292 memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
293 sizeof(struct apattern));
296 options->nsort = channel->nsort;
301 static int init_by_options(ares_channel channel,
302 const struct ares_options *options,
308 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
309 channel->flags = options->flags;
310 if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
311 channel->timeout = options->timeout;
312 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
313 channel->tries = options->tries;
314 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
315 channel->ndots = options->ndots;
316 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
317 channel->udp_port = options->udp_port;
318 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
319 channel->tcp_port = options->tcp_port;
320 if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
322 channel->sock_state_cb = options->sock_state_cb;
323 channel->sock_state_cb_data = options->sock_state_cb_data;
325 if ((optmask & ARES_OPT_SOCK_SNDBUF)
326 && channel->socket_send_buffer_size == -1)
327 channel->socket_send_buffer_size = options->socket_send_buffer_size;
328 if ((optmask & ARES_OPT_SOCK_RCVBUF)
329 && channel->socket_receive_buffer_size == -1)
330 channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
332 /* Copy the servers, if given. */
333 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
335 /* Avoid zero size allocations at any cost */
336 if (options->nservers > 0)
339 malloc(options->nservers * sizeof(struct server_state));
340 if (!channel->servers)
342 for (i = 0; i < options->nservers; i++)
343 channel->servers[i].addr = options->servers[i];
345 channel->nservers = options->nservers;
348 /* Copy the domains, if given. Keep channel->ndomains consistent so
349 * we can clean up in case of error.
351 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
353 /* Avoid zero size allocations at any cost */
354 if (options->ndomains > 0)
356 channel->domains = malloc(options->ndomains * sizeof(char *));
357 if (!channel->domains)
359 for (i = 0; i < options->ndomains; i++)
361 channel->ndomains = i;
362 channel->domains[i] = strdup(options->domains[i]);
363 if (!channel->domains[i])
367 channel->ndomains = options->ndomains;
370 /* Set lookups, if given. */
371 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
373 channel->lookups = strdup(options->lookups);
374 if (!channel->lookups)
379 if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
381 channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
382 if (!channel->sortlist)
384 for (i = 0; i < options->nsort; i++)
386 memcpy(&(channel->sortlist[i]), &(options->sortlist[i]), sizeof(struct apattern));
388 channel->nsort = options->nsort;
394 static int init_by_environment(ares_channel channel)
396 const char *localdomain, *res_options;
399 localdomain = getenv("LOCALDOMAIN");
400 if (localdomain && channel->ndomains == -1)
402 status = set_search(channel, localdomain);
403 if (status != ARES_SUCCESS)
407 res_options = getenv("RES_OPTIONS");
410 status = set_options(channel, res_options);
411 if (status != ARES_SUCCESS)
420 * Warning: returns a dynamically allocated buffer, the user MUST
421 * use free() if the function returns 1
423 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
425 /* Test for the size we need */
429 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
430 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
432 *obuf = malloc(size+1);
436 if (RegQueryValueEx(hKey, subkey, 0, NULL,
437 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
450 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
452 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
453 DWORD enum_size = 39;
457 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
458 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
463 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
466 rc = get_res_nt(hVal, subkey, obuf);
474 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
476 FIXED_INFO *fi = alloca (sizeof(*fi));
477 DWORD size = sizeof (*fi);
478 typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
479 get_net_param_func GetNetworkParams; /* available only on Win-98/2000+ */
481 IP_ADDR_STRING *ipAddr;
484 size_t ip_size = sizeof("255.255.255.255,")-1;
485 size_t left = ret_size;
492 handle = LoadLibrary ("iphlpapi.dll");
496 GetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
497 if (!GetNetworkParams)
500 res = (*GetNetworkParams) (fi, &size);
501 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
505 if (!fi || (*GetNetworkParams) (fi, &size) != ERROR_SUCCESS)
510 printf ("Host Name: %s\n", fi->HostName);
511 printf ("Domain Name: %s\n", fi->DomainName);
512 printf ("DNS Servers:\n"
513 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
515 if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
516 inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
519 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
520 left -= ret - ret_buf;
524 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
525 ipAddr = ipAddr->Next, i++)
527 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
529 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
530 left -= ret - ret_buf;
534 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
539 FreeLibrary (handle);
541 if (debug && left <= ip_size)
542 printf ("Too many nameservers. Truncating to %d addressess", count);
549 static int init_by_resolv_conf(ares_channel channel)
552 int status = -1, nservers = 0, nsort = 0;
553 struct server_state *servers = NULL;
554 struct apattern *sortlist = NULL;
559 NameServer info via IPHLPAPI (IP helper API):
560 GetNetworkParams() should be the trusted source for this.
561 Available in Win-98/2000 and later. If that fail, fall-back to
562 registry information.
566 On Windows 9X, the DNS server can be found in:
567 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
569 On Windows NT/2000/XP/2003:
570 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
572 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
574 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
577 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
588 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
591 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
593 status = config_nameserver(&servers, &nservers, buf);
594 if (status == ARES_SUCCESS)
601 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
605 RegOpenKeyEx(mykey, "Interfaces", 0,
606 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
607 if (get_res_nt(mykey, NAMESERVER, &line))
609 status = config_nameserver(&servers, &nservers, line);
612 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
614 status = config_nameserver(&servers, &nservers, line);
617 /* Try the interfaces */
618 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
620 status = config_nameserver(&servers, &nservers, line);
623 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
625 status = config_nameserver(&servers, &nservers, line);
635 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
639 if ((result = RegQueryValueEx(
640 mykey, NAMESERVER, NULL, &data_type,
643 ) == ERROR_SUCCESS ||
644 result == ERROR_MORE_DATA)
648 line = (char *)malloc(bytes+1);
649 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
650 (unsigned char *)line, &bytes) ==
653 status = config_nameserver(&servers, &nservers, line);
662 if (status == ARES_SUCCESS)
665 /* Catch the case when all the above checks fail (which happens when there
666 is no network card or the cable is unplugged) */
669 #elif defined(__riscos__)
671 /* Under RISC OS, name servers are listed in the
672 system variable Inet$Resolvers, space separated. */
674 line = getenv("Inet$Resolvers");
677 char *resolvers = strdup(line), *pos, *space;
684 space = strchr(pos, ' ');
687 status = config_nameserver(&servers, &nservers, pos);
688 if (status != ARES_SUCCESS)
693 if (status == ARES_SUCCESS)
699 #elif defined(WATT32)
703 for (i = 0; def_nameservers[i]; i++)
706 return ARES_SUCCESS; /* use localhost DNS server */
709 servers = calloc(sizeof(*servers), i);
713 for (i = 0; def_nameservers[i]; i++)
714 servers[i].addr.s_addr = htonl(def_nameservers[i]);
724 /* Don't read resolv.conf and friends if we don't have to */
725 if (ARES_CONFIG_CHECK(channel))
728 fp = fopen(PATH_RESOLV_CONF, "r");
730 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
732 if ((p = try_config(line, "domain")) && channel->ndomains == -1)
733 status = config_domain(channel, p);
734 else if ((p = try_config(line, "lookup")) && !channel->lookups)
735 status = config_lookup(channel, p, "bind", "file");
736 else if ((p = try_config(line, "search")) && channel->ndomains == -1)
737 status = set_search(channel, p);
738 else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
739 status = config_nameserver(&servers, &nservers, p);
740 else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
741 status = config_sortlist(&sortlist, &nsort, p);
742 else if ((p = try_config(line, "options")))
743 status = set_options(channel, p);
745 status = ARES_SUCCESS;
746 if (status != ARES_SUCCESS)
759 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
760 error, strerror(error)));
761 DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
766 if ((status == ARES_EOF) && (!channel->lookups)) {
767 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
768 fp = fopen("/etc/nsswitch.conf", "r");
770 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
772 if ((p = try_config(line, "hosts:")) && !channel->lookups)
773 status = config_lookup(channel, p, "dns", "files");
785 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
786 error, strerror(error)));
787 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
793 if ((status == ARES_EOF) && (!channel->lookups)) {
794 /* Linux / GNU libc 2.x and possibly others have host.conf */
795 fp = fopen("/etc/host.conf", "r");
797 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
799 if ((p = try_config(line, "order")) && !channel->lookups)
800 status = config_lookup(channel, p, "bind", "hosts");
812 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
813 error, strerror(error)));
814 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
820 if ((status == ARES_EOF) && (!channel->lookups)) {
821 /* Tru64 uses /etc/svc.conf */
822 fp = fopen("/etc/svc.conf", "r");
824 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
826 if ((p = try_config(line, "hosts=")) && !channel->lookups)
827 status = config_lookup(channel, p, "bind", "local");
839 DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
840 error, strerror(error)));
841 DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
854 if (status != ARES_EOF)
858 if (sortlist != NULL)
863 /* If we got any name server entries, fill them in. */
869 channel->servers = servers;
870 channel->nservers = nservers;
873 /* If we got any sortlist entries, fill them in. */
876 channel->sortlist = sortlist;
877 channel->nsort = nsort;
883 static int init_by_defaults(ares_channel channel)
885 char hostname[MAXHOSTNAMELEN + 1];
887 if (channel->flags == -1)
889 if (channel->timeout == -1)
890 channel->timeout = DEFAULT_TIMEOUT;
891 if (channel->tries == -1)
892 channel->tries = DEFAULT_TRIES;
893 if (channel->ndots == -1)
895 if (channel->udp_port == -1)
896 channel->udp_port = htons(NAMESERVER_PORT);
897 if (channel->tcp_port == -1)
898 channel->tcp_port = htons(NAMESERVER_PORT);
900 if (channel->nservers == -1)
902 /* If nobody specified servers, try a local named. */
903 channel->servers = malloc(sizeof(struct server_state));
904 if (!channel->servers)
906 channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
907 channel->nservers = 1;
910 if (channel->ndomains == -1)
912 /* Derive a default domain search list from the kernel hostname,
913 * or set it to empty if the hostname isn't helpful.
915 if (gethostname(hostname, sizeof(hostname)) == -1
916 || !strchr(hostname, '.'))
918 channel->ndomains = 0;
922 channel->domains = malloc(sizeof(char *));
923 if (!channel->domains)
925 channel->ndomains = 0;
926 channel->domains[0] = strdup(strchr(hostname, '.') + 1);
927 if (!channel->domains[0])
929 channel->ndomains = 1;
933 if (channel->nsort == -1)
935 channel->sortlist = NULL;
939 if (!channel->lookups)
941 channel->lookups = strdup("fb");
942 if (!channel->lookups)
950 static int config_domain(ares_channel channel, char *str)
954 /* Set a single search domain. */
956 while (*q && !ISSPACE(*q))
959 return set_search(channel, str);
962 static int config_lookup(ares_channel channel, const char *str,
963 const char *bindch, const char *filech)
968 /* Set the lookup order. Only the first letter of each work
969 * is relevant, and it has to be "b" for DNS or "f" for the
970 * host file. Ignore everything else.
976 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
977 if (*p == *bindch) *l++ = 'b';
980 while (*p && !ISSPACE(*p) && (*p != ','))
982 while (*p && (ISSPACE(*p) || (*p == ',')))
986 channel->lookups = strdup(lookups);
987 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
992 static int config_nameserver(struct server_state **servers, int *nservers,
996 struct server_state *newserv;
997 /* On Windows, there may be more than one nameserver specified in the same
998 * registry key, so we parse it as a space or comma seperated list.
1007 while (*p && !ISSPACE(*p) && *p != ',')
1016 /* Skip multiple spaces or trailing spaces */
1023 /* This is the part that actually sets the nameserver */
1024 addr.s_addr = inet_addr(begin);
1025 if (addr.s_addr == INADDR_NONE)
1027 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1030 newserv[*nservers].addr = addr;
1039 /* Add a nameserver entry, if this is a valid address. */
1040 addr.s_addr = inet_addr(str);
1041 if (addr.s_addr == INADDR_NONE)
1042 return ARES_SUCCESS;
1043 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1046 newserv[*nservers].addr = addr;
1050 return ARES_SUCCESS;
1054 static int config_sortlist(struct apattern **sortlist, int *nsort,
1057 struct apattern pat;
1060 /* Add sortlist entries. */
1061 while (*str && *str != ';')
1064 char ipbuf[16], ipbufpfx[32];
1065 /* Find just the IP */
1067 while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1069 memcpy(ipbuf, str, (int)(q-str));
1070 ipbuf[(int)(q-str)] = '\0';
1071 /* Find the prefix */
1074 const char *str2 = q+1;
1075 while (*q && *q != ';' && !ISSPACE(*q))
1077 memcpy(ipbufpfx, str, (int)(q-str));
1078 ipbufpfx[(int)(q-str)] = '\0';
1083 /* Lets see if it is CIDR */
1084 /* First we'll try IPv6 */
1085 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1087 sizeof(pat.addr.addr6))) > 0)
1089 pat.type = PATTERN_CIDR;
1090 pat.mask.bits = (unsigned short)bits;
1091 pat.family = AF_INET6;
1092 if (!sortlist_alloc(sortlist, nsort, &pat))
1096 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addr.addr4,
1097 sizeof(pat.addr.addr4))) > 0)
1099 pat.type = PATTERN_CIDR;
1100 pat.mask.bits = (unsigned short)bits;
1101 pat.family = AF_INET;
1102 if (!sortlist_alloc(sortlist, nsort, &pat))
1105 /* See if it is just a regular IP */
1106 else if (ip_addr(ipbuf, (int)(q-str), &pat.addr.addr4) == 0)
1110 memcpy(ipbuf, str, (int)(q-str));
1111 ipbuf[(int)(q-str)] = '\0';
1112 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr.addr4) != 0)
1117 pat.family = AF_INET;
1118 pat.type = PATTERN_MASK;
1119 if (!sortlist_alloc(sortlist, nsort, &pat))
1124 while (*q && *q != ';' && !ISSPACE(*q))
1128 while (ISSPACE(*str))
1132 return ARES_SUCCESS;
1136 static int set_search(ares_channel channel, const char *str)
1141 if(channel->ndomains != -1) {
1142 /* if we already have some domains present, free them first */
1143 for(n=0; n < channel->ndomains; n++)
1144 free(channel->domains[n]);
1145 free(channel->domains);
1146 channel->domains = NULL;
1147 channel->ndomains = -1;
1150 /* Count the domains given. */
1155 while (*p && !ISSPACE(*p))
1164 channel->ndomains = 0;
1165 return ARES_SUCCESS;
1168 channel->domains = malloc(n * sizeof(char *));
1169 if (!channel->domains)
1172 /* Now copy the domains. */
1177 channel->ndomains = n;
1179 while (*q && !ISSPACE(*q))
1181 channel->domains[n] = malloc(q - p + 1);
1182 if (!channel->domains[n])
1184 memcpy(channel->domains[n], p, q - p);
1185 channel->domains[n][q - p] = 0;
1191 channel->ndomains = n;
1193 return ARES_SUCCESS;
1196 static int set_options(ares_channel channel, const char *str)
1198 const char *p, *q, *val;
1204 while (*q && !ISSPACE(*q))
1206 val = try_option(p, q, "ndots:");
1207 if (val && channel->ndots == -1)
1208 channel->ndots = atoi(val);
1209 val = try_option(p, q, "retrans:");
1210 if (val && channel->timeout == -1)
1211 channel->timeout = atoi(val);
1212 val = try_option(p, q, "retry:");
1213 if (val && channel->tries == -1)
1214 channel->tries = atoi(val);
1220 return ARES_SUCCESS;
1224 static char *try_config(char *s, const char *opt)
1229 if (strncmp(s, opt, len) != 0 || !ISSPACE(s[len]))
1239 static const char *try_option(const char *p, const char *q, const char *opt)
1241 size_t len = strlen(opt);
1242 return ((size_t)(q - p) > len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1246 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1247 struct apattern *pat)
1249 struct apattern *newsort;
1250 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1253 newsort[*nsort] = *pat;
1254 *sortlist = newsort;
1259 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1262 /* Four octets and three periods yields at most 15 characters. */
1266 addr->s_addr = inet_addr(ipbuf);
1267 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1272 static void natural_mask(struct apattern *pat)
1274 struct in_addr addr;
1276 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1279 addr.s_addr = ntohl(pat->addr.addr4.s_addr);
1281 /* This is out of date in the CIDR world, but some people might
1284 if (IN_CLASSA(addr.s_addr))
1285 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSA_NET);
1286 else if (IN_CLASSB(addr.s_addr))
1287 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSB_NET);
1289 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSC_NET);
1292 /* initialize an rc4 key. If possible a cryptographically secure random key
1293 is generated using a suitable function (for example win32's RtlGenRandom as
1295 http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1296 otherwise the code defaults to cross-platform albeit less secure mechanism
1299 static void randomize_key(unsigned char* key,int key_data_len)
1304 HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1306 BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1307 (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1308 if (pfn && pfn(key,key_data_len) )
1316 FILE *f = fopen(RANDOM_FILE, "rb");
1319 size_t rc = fread(buffer, key_data_len, 1, f);
1320 for(i=0; i<rc && counter < key_data_len; i++)
1321 key[counter++]=buffer[i];
1327 if ( !randomized ) {
1328 for (;counter<key_data_len;counter++)
1329 key[counter]=rand() % 256;
1333 static void init_id_key(rc4_key* key,int key_data_len)
1335 unsigned char index1;
1336 unsigned char index2;
1337 unsigned char* state;
1339 unsigned char *key_data_ptr = 0;
1341 key_data_ptr = calloc(1,key_data_len);
1342 randomize_key(key->state,key_data_len);
1343 state = &key->state[0];
1344 for(counter = 0; counter < 256; counter++)
1345 /* unnecessary AND but it keeps some compilers happier */
1346 state[counter] = counter & 0xff;
1351 for(counter = 0; counter < 256; counter++)
1353 index2 = (key_data_ptr[index1] + state[counter] +
1355 ARES_SWAP_BYTE(&state[counter], &state[index2]);
1357 index1 = (index1 + 1) % key_data_len;
1363 short ares__generate_new_id(rc4_key* key)
1366 ares__rc4(key, (unsigned char *)&r, sizeof(r));