1 /* Copyright 1998 by the Massachusetts Institute of Technology.
3 * Permission to use, copy, modify, and distribute this
4 * software and its documentation for any purpose and without
5 * fee is hereby granted, provided that the above copyright
6 * notice appear in all copies and that both that copyright
7 * notice and this permission notice appear in supporting
8 * documentation, and that the name of M.I.T. not be used in
9 * advertising or publicity pertaining to distribution of the
10 * software without specific, written prior permission.
11 * M.I.T. makes no representations about the suitability of
12 * this software for any purpose. It is provided "as is"
13 * without express or implied warranty.
17 #include <sys/types.h>
19 #if defined(WIN32) && !defined(WATT32)
25 #include <sys/param.h>
26 #ifdef HAVE_SYS_TIME_H
30 #ifdef HAVE_SYS_SOCKET_H
31 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
37 #include <arpa/nameser.h>
38 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
39 #include <arpa/nameser_compat.h>
53 #include "ares_private.h"
54 #include "inet_net_pton.h"
57 #undef WIN32 /* Redefined in MingW/MSVC headers */
60 static int init_by_options(ares_channel channel, struct ares_options *options,
62 static int init_by_environment(ares_channel channel);
63 static int init_by_resolv_conf(ares_channel channel);
64 static int init_by_defaults(ares_channel channel);
66 static int config_nameserver(struct server_state **servers, int *nservers,
68 static int set_search(ares_channel channel, const char *str);
69 static int set_options(ares_channel channel, const char *str);
70 static const char *try_option(const char *p, const char *q, const char *opt);
72 static int sortlist_alloc(struct apattern **sortlist, int *nsort, struct apattern *pat);
73 static int ip_addr(const char *s, int len, struct in_addr *addr);
74 static void natural_mask(struct apattern *pat);
75 static int config_domain(ares_channel channel, char *str);
76 static int config_lookup(ares_channel channel, const char *str,
77 const char *bindch, const char *filech);
78 static int config_sortlist(struct apattern **sortlist, int *nsort,
80 static char *try_config(char *s, const char *opt);
83 int ares_init(ares_channel *channelptr)
85 return ares_init_options(channelptr, NULL, 0);
88 int ares_init_options(ares_channel *channelptr, struct ares_options *options,
93 struct server_state *server;
96 channel = malloc(sizeof(struct ares_channeldata));
100 /* Set everything to distinguished values so we know they haven't
104 channel->timeout = -1;
107 channel->udp_port = -1;
108 channel->tcp_port = -1;
109 channel->nservers = -1;
110 channel->ndomains = -1;
112 channel->lookups = NULL;
113 channel->queries = NULL;
114 channel->domains = NULL;
115 channel->sortlist = NULL;
117 /* Initialize configuration by each of the four sources, from highest
118 * precedence to lowest.
120 status = init_by_options(channel, options, optmask);
121 if (status == ARES_SUCCESS)
122 status = init_by_environment(channel);
123 if (status == ARES_SUCCESS)
124 status = init_by_resolv_conf(channel);
125 if (status == ARES_SUCCESS)
126 status = init_by_defaults(channel);
127 if (status != ARES_SUCCESS)
129 /* Something failed; clean up memory we may have allocated. */
130 if (channel->nservers != -1)
131 free(channel->servers);
132 if (channel->domains)
134 for (i = 0; i < channel->ndomains; i++)
135 free(channel->domains[i]);
136 free(channel->domains);
138 if (channel->sortlist)
139 free(channel->sortlist);
141 free(channel->lookups);
146 /* Trim to one server if ARES_FLAG_PRIMARY is set. */
147 if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
148 channel->nservers = 1;
150 /* Initialize server states. */
151 for (i = 0; i < channel->nservers; i++)
153 server = &channel->servers[i];
154 server->udp_socket = ARES_SOCKET_BAD;
155 server->tcp_socket = ARES_SOCKET_BAD;
156 server->tcp_lenbuf_pos = 0;
157 server->tcp_buffer = NULL;
158 server->qhead = NULL;
159 server->qtail = NULL;
162 /* Choose a somewhat random query ID. The main point is to avoid
163 * collisions with stale queries. An attacker trying to spoof a DNS
164 * answer also has to guess the query ID, but it's only a 16-bit
165 * field, so there's not much to be done about that.
167 gettimeofday(&tv, NULL);
168 channel->next_id = (unsigned short)
169 (tv.tv_sec ^ tv.tv_usec ^ getpid()) & 0xffff;
171 channel->queries = NULL;
173 *channelptr = channel;
177 static int init_by_options(ares_channel channel, struct ares_options *options,
183 if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
184 channel->flags = options->flags;
185 if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
186 channel->timeout = options->timeout;
187 if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
188 channel->tries = options->tries;
189 if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
190 channel->ndots = options->ndots;
191 if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
192 channel->udp_port = options->udp_port;
193 if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
194 channel->tcp_port = options->tcp_port;
196 /* Copy the servers, if given. */
197 if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
200 malloc(options->nservers * sizeof(struct server_state));
201 if (!channel->servers && options->nservers != 0)
203 for (i = 0; i < options->nservers; i++)
204 channel->servers[i].addr = options->servers[i];
205 channel->nservers = options->nservers;
208 /* Copy the domains, if given. Keep channel->ndomains consistent so
209 * we can clean up in case of error.
211 if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
213 channel->domains = malloc(options->ndomains * sizeof(char *));
214 if (!channel->domains && options->ndomains != 0)
216 for (i = 0; i < options->ndomains; i++)
218 channel->ndomains = i;
219 channel->domains[i] = strdup(options->domains[i]);
220 if (!channel->domains[i])
223 channel->ndomains = options->ndomains;
226 /* Set lookups, if given. */
227 if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
229 channel->lookups = strdup(options->lookups);
230 if (!channel->lookups)
237 static int init_by_environment(ares_channel channel)
239 const char *localdomain, *res_options;
242 localdomain = getenv("LOCALDOMAIN");
243 if (localdomain && channel->ndomains == -1)
245 status = set_search(channel, localdomain);
246 if (status != ARES_SUCCESS)
250 res_options = getenv("RES_OPTIONS");
253 status = set_options(channel, res_options);
254 if (status != ARES_SUCCESS)
263 * Warning: returns a dynamically allocated buffer, the user MUST
264 * use free() if the function returns 1
266 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
268 /* Test for the size we need */
272 result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
273 if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
275 *obuf = malloc(size+1);
279 if (RegQueryValueEx(hKey, subkey, 0, NULL,
280 (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
293 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
295 char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
296 DWORD enum_size = 39;
300 while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
301 NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
306 if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
309 rc = get_res_nt(hVal, subkey, obuf);
317 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
319 FIXED_INFO *fi = alloca (sizeof(*fi));
320 DWORD size = sizeof (*fi);
321 typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
322 get_net_param_func GetNetworkParams; /* available only on Win-98/2000+ */
324 IP_ADDR_STRING *ipAddr;
327 size_t ip_size = sizeof("255.255.255.255,")-1;
328 size_t left = ret_size;
335 handle = LoadLibrary ("iphlpapi.dll");
339 GetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
340 if (!GetNetworkParams)
343 res = (*GetNetworkParams) (fi, &size);
344 if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
348 if (!fi || (*GetNetworkParams) (fi, &size) != ERROR_SUCCESS)
353 printf ("Host Name: %s\n", fi->HostName);
354 printf ("Domain Name: %s\n", fi->DomainName);
355 printf ("DNS Servers:\n"
356 " %s (primary)\n", fi->DnsServerList.IpAddress.String);
358 if (inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
361 ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
362 left -= ret - ret_buf;
366 for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
367 ipAddr = ipAddr->Next, i++)
369 if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
371 ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
372 left -= ret - ret_buf;
376 printf (" %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
381 FreeLibrary (handle);
383 if (debug && left <= ip_size)
384 printf ("Too many nameservers. Truncating to %d addressess", count);
391 static int init_by_resolv_conf(ares_channel channel)
394 int status = -1, nservers = 0, nsort = 0;
395 struct server_state *servers = NULL;
396 struct apattern *sortlist = NULL;
401 NameServer info via IPHLPAPI (IP helper API):
402 GetNetworkParams() should be the trusted source for this.
403 Available in Win-98/2000 and later. If that fail, fall-back to
404 registry information.
408 On Windows 9X, the DNS server can be found in:
409 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
411 On Windows NT/2000/XP/2003:
412 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
414 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
416 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
419 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
430 if (channel->nservers > -1) /* don't override ARES_OPT_SERVER */
433 if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
435 status = config_nameserver(&servers, &nservers, buf);
436 if (status == ARES_SUCCESS)
443 HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
447 RegOpenKeyEx(mykey, "Interfaces", 0,
448 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
449 if (get_res_nt(mykey, NAMESERVER, &line))
451 status = config_nameserver(&servers, &nservers, line);
454 else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
456 status = config_nameserver(&servers, &nservers, line);
459 /* Try the interfaces */
460 else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
462 status = config_nameserver(&servers, &nservers, line);
465 else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
467 status = config_nameserver(&servers, &nservers, line);
477 HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
481 if ((result = RegQueryValueEx(
482 mykey, NAMESERVER, NULL, &data_type,
485 ) == ERROR_SUCCESS ||
486 result == ERROR_MORE_DATA)
490 line = (char *)malloc(bytes+1);
491 if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
492 (unsigned char *)line, &bytes) ==
495 status = config_nameserver(&servers, &nservers, line);
504 if (status == ARES_SUCCESS)
507 #elif defined(riscos)
509 /* Under RISC OS, name servers are listed in the
510 system variable Inet$Resolvers, space separated. */
512 line = getenv("Inet$Resolvers");
515 char *resolvers = strdup(line), *pos, *space;
522 space = strchr(pos, ' ');
525 status = config_nameserver(&servers, &nservers, pos);
526 if (status != ARES_SUCCESS)
531 if (status == ARES_SUCCESS)
537 #elif defined(WATT32)
541 for (i = 0; def_nameservers[i]; i++)
544 return ARES_SUCCESS; /* use localhost DNS server */
547 servers = calloc(sizeof(*servers), i);
551 for (i = 0; def_nameservers[i]; i++)
552 servers[i].addr.s_addr = htonl(def_nameservers[i]);
561 fp = fopen(PATH_RESOLV_CONF, "r");
563 return (errno == ENOENT) ? ARES_SUCCESS : ARES_EFILE;
564 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
566 if ((p = try_config(line, "domain")))
567 status = config_domain(channel, p);
568 else if ((p = try_config(line, "lookup")) && !channel->lookups)
569 status = config_lookup(channel, p, "bind", "file");
570 else if ((p = try_config(line, "search")))
571 status = set_search(channel, p);
572 else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
573 status = config_nameserver(&servers, &nservers, p);
574 else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
575 status = config_sortlist(&sortlist, &nsort, p);
576 else if ((p = try_config(line, "options")))
577 status = set_options(channel, p);
579 status = ARES_SUCCESS;
580 if (status != ARES_SUCCESS)
585 if (!channel->lookups) {
586 /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
587 fp = fopen("/etc/nsswitch.conf", "r");
589 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
591 if ((p = try_config(line, "hosts:")) && !channel->lookups)
592 status = config_lookup(channel, p, "dns", "files");
598 if (!channel->lookups) {
599 /* Linux / GNU libc 2.x and possibly others have host.conf */
600 fp = fopen("/etc/host.conf", "r");
602 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
604 if ((p = try_config(line, "order")) && !channel->lookups)
605 status = config_lookup(channel, p, "bind", "hosts");
611 if (!channel->lookups) {
612 /* Tru64 uses /etc/svc.conf */
613 fp = fopen("/etc/svc.conf", "r");
615 while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
617 if ((p = try_config(line, "hosts=")) && !channel->lookups)
618 status = config_lookup(channel, p, "bind", "local");
631 if (status != ARES_EOF)
635 if (sortlist != NULL)
640 /* If we got any name server entries, fill them in. */
646 channel->servers = servers;
647 channel->nservers = nservers;
650 /* If we got any sortlist entries, fill them in. */
653 channel->sortlist = sortlist;
654 channel->nsort = nsort;
660 static int init_by_defaults(ares_channel channel)
662 char hostname[MAXHOSTNAMELEN + 1];
664 if (channel->flags == -1)
666 if (channel->timeout == -1)
667 channel->timeout = DEFAULT_TIMEOUT;
668 if (channel->tries == -1)
669 channel->tries = DEFAULT_TRIES;
670 if (channel->ndots == -1)
672 if (channel->udp_port == -1)
673 channel->udp_port = htons(NAMESERVER_PORT);
674 if (channel->tcp_port == -1)
675 channel->tcp_port = htons(NAMESERVER_PORT);
677 if (channel->nservers == -1)
679 /* If nobody specified servers, try a local named. */
680 channel->servers = malloc(sizeof(struct server_state));
681 if (!channel->servers)
683 channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
684 channel->nservers = 1;
687 if (channel->ndomains == -1)
689 /* Derive a default domain search list from the kernel hostname,
690 * or set it to empty if the hostname isn't helpful.
692 if (gethostname(hostname, sizeof(hostname)) == -1
693 || !strchr(hostname, '.'))
695 channel->domains = malloc(0);
696 channel->ndomains = 0;
700 channel->domains = malloc(sizeof(char *));
701 if (!channel->domains)
703 channel->ndomains = 0;
704 channel->domains[0] = strdup(strchr(hostname, '.') + 1);
705 if (!channel->domains[0])
707 channel->ndomains = 1;
711 if (channel->nsort == -1)
713 channel->sortlist = NULL;
717 if (!channel->lookups)
719 channel->lookups = strdup("fb");
720 if (!channel->lookups)
728 static int config_domain(ares_channel channel, char *str)
732 /* Set a single search domain. */
734 while (*q && !isspace((unsigned char)*q))
737 return set_search(channel, str);
740 static int config_lookup(ares_channel channel, const char *str,
741 const char *bindch, const char *filech)
746 /* Set the lookup order. Only the first letter of each work
747 * is relevant, and it has to be "b" for DNS or "f" for the
748 * host file. Ignore everything else.
754 if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
755 if (*p == *bindch) *l++ = 'b';
758 while (*p && !isspace((unsigned char)*p) && (*p != ','))
760 while (*p && (isspace((unsigned char)*p) || (*p == ',')))
764 channel->lookups = strdup(lookups);
765 return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
770 static int config_nameserver(struct server_state **servers, int *nservers,
774 struct server_state *newserv;
775 /* On Windows, there may be more than one nameserver specified in the same
776 * registry key, so we parse it as a space or comma seperated list.
785 while (*p && !isspace(*p) && *p != ',')
794 /* Skip multiple spaces or trailing spaces */
801 /* This is the part that actually sets the nameserver */
802 addr.s_addr = inet_addr(begin);
803 if (addr.s_addr == INADDR_NONE)
805 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
808 newserv[*nservers].addr = addr;
817 /* Add a nameserver entry, if this is a valid address. */
818 addr.s_addr = inet_addr(str);
819 if (addr.s_addr == INADDR_NONE)
821 newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
824 newserv[*nservers].addr = addr;
832 static int config_sortlist(struct apattern **sortlist, int *nsort,
838 /* Add sortlist entries. */
839 while (*str && *str != ';')
842 char ipbuf[16], ipbufpfx[32];
843 /* Find just the IP */
845 while (*q && *q != '/' && *q != ';' && !isspace((unsigned char)*q))
847 memcpy(ipbuf, str, (int)(q-str));
848 ipbuf[(int)(q-str)] = 0;
849 /* Find the prefix */
852 const char *str2 = q+1;
853 while (*q && *q != ';' && !isspace((unsigned char)*q))
855 memcpy(ipbufpfx, str, (int)(q-str));
856 ipbufpfx[(int)(q-str)] = 0;
861 /* Lets see if it is CIDR */
862 /* First we'll try IPv6 */
863 if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx ? ipbufpfx : ipbuf,
865 sizeof(pat.addr.addr6))) > 0)
867 pat.type = PATTERN_CIDR;
868 pat.mask.bits = bits;
869 pat.family = AF_INET6;
870 if (!sortlist_alloc(sortlist, nsort, &pat))
874 (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addr.addr4,
875 sizeof(pat.addr.addr4))) > 0)
877 pat.type = PATTERN_CIDR;
878 pat.mask.bits = bits;
879 pat.family = AF_INET;
880 if (!sortlist_alloc(sortlist, nsort, &pat))
883 /* See if it is just a regular IP */
884 else if (ip_addr(ipbuf, (int)(q-str), &pat.addr.addr4) == 0)
888 memcpy(ipbuf, str, (int)(q-str));
889 ipbuf[(int)(q-str)] = 0;
890 if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr.addr4) != 0)
895 pat.family = AF_INET;
896 pat.type = PATTERN_MASK;
897 if (!sortlist_alloc(sortlist, nsort, &pat))
902 while (*q && *q != ';' && !isspace((unsigned char)*q))
906 while (isspace((unsigned char)*str))
914 static int set_search(ares_channel channel, const char *str)
919 if(channel->ndomains != -1) {
920 /* if we already have some domains present, free them first */
921 for(n=0; n < channel->ndomains; n++)
922 free(channel->domains[n]);
923 free(channel->domains);
924 channel->ndomains = -1;
927 /* Count the domains given. */
932 while (*p && !isspace((unsigned char)*p))
934 while (isspace((unsigned char)*p))
939 channel->domains = malloc(n * sizeof(char *));
940 if (!channel->domains && n)
943 /* Now copy the domains. */
948 channel->ndomains = n;
950 while (*q && !isspace((unsigned char)*q))
952 channel->domains[n] = malloc(q - p + 1);
953 if (!channel->domains[n])
955 memcpy(channel->domains[n], p, q - p);
956 channel->domains[n][q - p] = 0;
958 while (isspace((unsigned char)*p))
962 channel->ndomains = n;
967 static int set_options(ares_channel channel, const char *str)
969 const char *p, *q, *val;
975 while (*q && !isspace((unsigned char)*q))
977 val = try_option(p, q, "ndots:");
978 if (val && channel->ndots == -1)
979 channel->ndots = atoi(val);
980 val = try_option(p, q, "retrans:");
981 if (val && channel->timeout == -1)
982 channel->timeout = atoi(val);
983 val = try_option(p, q, "retry:");
984 if (val && channel->tries == -1)
985 channel->tries = atoi(val);
987 while (isspace((unsigned char)*p))
995 static char *try_config(char *s, const char *opt)
1000 if (strncmp(s, opt, len) != 0 || !isspace((unsigned char)s[len]))
1003 while (isspace((unsigned char)*s))
1010 static const char *try_option(const char *p, const char *q, const char *opt)
1012 size_t len = strlen(opt);
1013 return ((size_t)(q - p) > len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1017 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1018 struct apattern *pat)
1020 struct apattern *newsort;
1021 newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1024 newsort[*nsort] = *pat;
1025 *sortlist = newsort;
1030 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1033 /* Four octets and three periods yields at most 15 characters. */
1037 addr->s_addr = inet_addr(ipbuf);
1038 if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1043 static void natural_mask(struct apattern *pat)
1045 struct in_addr addr;
1047 /* Store a host-byte-order copy of pat in a struct in_addr. Icky,
1050 addr.s_addr = ntohl(pat->addr.addr4.s_addr);
1052 /* This is out of date in the CIDR world, but some people might
1055 if (IN_CLASSA(addr.s_addr))
1056 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSA_NET);
1057 else if (IN_CLASSB(addr.s_addr))
1058 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSB_NET);
1060 pat->mask.addr.addr4.s_addr = htonl(IN_CLASSC_NET);