• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /* Copyright 1998, 2011, 2013 by the Massachusetts Institute of Technology.
3  *
4  * Permission to use, copy, modify, and distribute this
5  * software and its documentation for any purpose and without
6  * fee is hereby granted, provided that the above copyright
7  * notice appear in all copies and that both that copyright
8  * notice and this permission notice appear in supporting
9  * documentation, and that the name of M.I.T. not be used in
10  * advertising or publicity pertaining to distribution of the
11  * software without specific, written prior permission.
12  * M.I.T. makes no representations about the suitability of
13  * this software for any purpose.  It is provided "as is"
14  * without express or implied warranty.
15  */
16 
17 #include "ares_setup.h"
18 
19 #ifdef HAVE_NETINET_IN_H
20 #  include <netinet/in.h>
21 #endif
22 #ifdef HAVE_NETDB_H
23 #  include <netdb.h>
24 #endif
25 #ifdef HAVE_ARPA_INET_H
26 #  include <arpa/inet.h>
27 #endif
28 #ifdef HAVE_ARPA_NAMESER_H
29 #  include <arpa/nameser.h>
30 #else
31 #  include "nameser.h"
32 #endif
33 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
34 #  include <arpa/nameser_compat.h>
35 #endif
36 
37 #ifdef HAVE_STRINGS_H
38 #include <strings.h>
39 #endif
40 
41 #include "ares.h"
42 #include "ares_inet_net_pton.h"
43 #include "bitncmp.h"
44 #include "ares_platform.h"
45 #include "ares_nowarn.h"
46 #include "ares_private.h"
47 
48 #ifdef WATT32
49 #undef WIN32
50 #endif
51 
52 struct host_query {
53   /* Arguments passed to ares_gethostbyname() */
54   ares_channel channel;
55   char *name;
56   ares_host_callback callback;
57   void *arg;
58   int sent_family; /* this family is what was is being used */
59   int want_family; /* this family is what is asked for in the API */
60   const char *remaining_lookups;
61   int timeouts;
62 };
63 
64 static void next_lookup(struct host_query *hquery, int status_code);
65 static void host_callback(void *arg, int status, int timeouts,
66                           unsigned char *abuf, int alen);
67 static void end_hquery(struct host_query *hquery, int status,
68                        struct hostent *host);
69 static int fake_hostent(const char *name, int family,
70                         ares_host_callback callback, void *arg);
71 static int file_lookup(const char *name, int family, struct hostent **host);
72 static void sort_addresses(struct hostent *host,
73                            const struct apattern *sortlist, int nsort);
74 static void sort6_addresses(struct hostent *host,
75                             const struct apattern *sortlist, int nsort);
76 static int get_address_index(const struct in_addr *addr,
77                              const struct apattern *sortlist, int nsort);
78 static int get6_address_index(const struct ares_in6_addr *addr,
79                               const struct apattern *sortlist, int nsort);
80 
ares_gethostbyname(ares_channel channel,const char * name,int family,ares_host_callback callback,void * arg)81 void ares_gethostbyname(ares_channel channel, const char *name, int family,
82                         ares_host_callback callback, void *arg)
83 {
84   struct host_query *hquery;
85 
86   /* Right now we only know how to look up Internet addresses - and unspec
87      means try both basically. */
88   switch (family) {
89   case AF_INET:
90   case AF_INET6:
91   case AF_UNSPEC:
92     break;
93   default:
94     callback(arg, ARES_ENOTIMP, 0, NULL);
95     return;
96   }
97 
98   /* Per RFC 7686, reject queries for ".onion" domain names with NXDOMAIN. */
99   if (ares__is_onion_domain(name))
100     {
101       callback(arg, ARES_ENOTFOUND, 0, NULL);
102       return;
103     }
104 
105   if (fake_hostent(name, family, callback, arg))
106     return;
107 
108   /* Allocate and fill in the host query structure. */
109   hquery = ares_malloc(sizeof(struct host_query));
110   if (!hquery)
111     {
112       callback(arg, ARES_ENOMEM, 0, NULL);
113       return;
114     }
115   hquery->channel = channel;
116   hquery->name = ares_strdup(name);
117   hquery->want_family = family;
118   hquery->sent_family = -1; /* nothing is sent yet */
119   if (!hquery->name) {
120     ares_free(hquery);
121     callback(arg, ARES_ENOMEM, 0, NULL);
122     return;
123   }
124   hquery->callback = callback;
125   hquery->arg = arg;
126   hquery->remaining_lookups = channel->lookups;
127   hquery->timeouts = 0;
128 
129   /* Start performing lookups according to channel->lookups. */
130   next_lookup(hquery, ARES_ECONNREFUSED /* initial error code */);
131 }
132 
next_lookup(struct host_query * hquery,int status_code)133 static void next_lookup(struct host_query *hquery, int status_code)
134 {
135   const char *p;
136   struct hostent *host;
137   int status = status_code;
138 
139   for (p = hquery->remaining_lookups; *p; p++)
140     {
141       switch (*p)
142         {
143         case 'b':
144           /* DNS lookup */
145           hquery->remaining_lookups = p + 1;
146           if ((hquery->want_family == AF_INET6) ||
147               (hquery->want_family == AF_UNSPEC)) {
148             /* if inet6 or unspec, start out with AAAA */
149             hquery->sent_family = AF_INET6;
150             ares_search(hquery->channel, hquery->name, C_IN, T_AAAA,
151                         host_callback, hquery);
152           }
153           else {
154             hquery->sent_family = AF_INET;
155             ares_search(hquery->channel, hquery->name, C_IN, T_A,
156                         host_callback, hquery);
157           }
158           return;
159 
160         case 'f':
161           /* Host file lookup */
162           status = file_lookup(hquery->name, hquery->want_family, &host);
163 
164           /* this status check below previously checked for !ARES_ENOTFOUND,
165              but we should not assume that this single error code is the one
166              that can occur, as that is in fact no longer the case */
167           if (status == ARES_SUCCESS)
168             {
169               end_hquery(hquery, status, host);
170               return;
171             }
172           status = status_code;   /* Use original status code */
173           break;
174         }
175     }
176   end_hquery(hquery, status, NULL);
177 }
178 
host_callback(void * arg,int status,int timeouts,unsigned char * abuf,int alen)179 static void host_callback(void *arg, int status, int timeouts,
180                           unsigned char *abuf, int alen)
181 {
182   struct host_query *hquery = (struct host_query *) arg;
183   ares_channel channel = hquery->channel;
184   struct hostent *host = NULL;
185 
186   hquery->timeouts += timeouts;
187   if (status == ARES_SUCCESS)
188     {
189       if (hquery->sent_family == AF_INET)
190         {
191           status = ares_parse_a_reply(abuf, alen, &host, NULL, NULL);
192           if (host && channel->nsort)
193             sort_addresses(host, channel->sortlist, channel->nsort);
194         }
195       else if (hquery->sent_family == AF_INET6)
196         {
197           status = ares_parse_aaaa_reply(abuf, alen, &host, NULL, NULL);
198           if ((status == ARES_ENODATA || status == ARES_EBADRESP ||
199                (status == ARES_SUCCESS && host && host->h_addr_list[0] == NULL)) &&
200                 hquery->want_family == AF_UNSPEC) {
201             /* The query returned something but either there were no AAAA
202                records (e.g. just CNAME) or the response was malformed.  Try
203                looking up A instead. */
204             if (host)
205               ares_free_hostent(host);
206             hquery->sent_family = AF_INET;
207             ares_search(hquery->channel, hquery->name, C_IN, T_A,
208                         host_callback, hquery);
209             return;
210           }
211           if (host && channel->nsort)
212             sort6_addresses(host, channel->sortlist, channel->nsort);
213         }
214       if (status == ARES_SUCCESS && host && host->h_addr_list[0] == NULL)
215       {
216         /* The query returned something but had no A/AAAA record
217            (even after potentially retrying AAAA with A)
218            so we should treat this as an error */
219         status = ARES_ENODATA;
220       }
221       end_hquery(hquery, status, host);
222     }
223   else if ((status == ARES_ENODATA || status == ARES_EBADRESP ||
224             status == ARES_ETIMEOUT) && (hquery->sent_family == AF_INET6 &&
225             hquery->want_family == AF_UNSPEC))
226     {
227       /* The AAAA query yielded no useful result.  Now look up an A instead. */
228       hquery->sent_family = AF_INET;
229       ares_search(hquery->channel, hquery->name, C_IN, T_A, host_callback,
230                   hquery);
231     }
232   else if (status == ARES_EDESTRUCTION)
233     end_hquery(hquery, status, NULL);
234   else
235     next_lookup(hquery, status);
236 }
237 
end_hquery(struct host_query * hquery,int status,struct hostent * host)238 static void end_hquery(struct host_query *hquery, int status,
239                        struct hostent *host)
240 {
241   hquery->callback(hquery->arg, status, hquery->timeouts, host);
242   if (host)
243     ares_free_hostent(host);
244   ares_free(hquery->name);
245   ares_free(hquery);
246 }
247 
248 /* If the name looks like an IP address, fake up a host entry, end the
249  * query immediately, and return true.  Otherwise return false.
250  */
fake_hostent(const char * name,int family,ares_host_callback callback,void * arg)251 static int fake_hostent(const char *name, int family,
252                         ares_host_callback callback, void *arg)
253 {
254   struct hostent hostent;
255   char *aliases[1] = { NULL };
256   char *addrs[2];
257   int result = 0;
258   struct in_addr in;
259   struct ares_in6_addr in6;
260 
261   if (family == AF_INET || family == AF_INET6)
262     {
263       /* It only looks like an IP address if it's all numbers and dots. */
264       int numdots = 0, valid = 1;
265       const char *p;
266       for (p = name; *p; p++)
267         {
268           if (!ISDIGIT(*p) && *p != '.') {
269             valid = 0;
270             break;
271           } else if (*p == '.') {
272             numdots++;
273           }
274         }
275 
276       /* if we don't have 3 dots, it is illegal
277        * (although inet_pton doesn't think so).
278        */
279       if (numdots != 3 || !valid)
280         result = 0;
281       else
282         result = (ares_inet_pton(AF_INET, name, &in) < 1 ? 0 : 1);
283 
284       if (result)
285         family = AF_INET;
286     }
287   if (family == AF_INET6)
288     result = (ares_inet_pton(AF_INET6, name, &in6) < 1 ? 0 : 1);
289 
290   if (!result)
291     return 0;
292 
293   if (family == AF_INET)
294     {
295       hostent.h_length = (int)sizeof(struct in_addr);
296       addrs[0] = (char *)&in;
297     }
298   else if (family == AF_INET6)
299     {
300       hostent.h_length = (int)sizeof(struct ares_in6_addr);
301       addrs[0] = (char *)&in6;
302     }
303   /* Duplicate the name, to avoid a constness violation. */
304   hostent.h_name = ares_strdup(name);
305   if (!hostent.h_name)
306     {
307       callback(arg, ARES_ENOMEM, 0, NULL);
308       return 1;
309     }
310 
311   /* Fill in the rest of the host structure and terminate the query. */
312   addrs[1] = NULL;
313   hostent.h_aliases = aliases;
314   hostent.h_addrtype = aresx_sitoss(family);
315   hostent.h_addr_list = addrs;
316   callback(arg, ARES_SUCCESS, 0, &hostent);
317 
318   ares_free((char *)(hostent.h_name));
319   return 1;
320 }
321 
322 /* This is an API method */
ares_gethostbyname_file(ares_channel channel,const char * name,int family,struct hostent ** host)323 int ares_gethostbyname_file(ares_channel channel, const char *name,
324                             int family, struct hostent **host)
325 {
326   int result;
327 
328   /* We only take the channel to ensure that ares_init() been called. */
329   if(channel == NULL)
330     {
331       /* Anything will do, really.  This seems fine, and is consistent with
332          other error cases. */
333       *host = NULL;
334       return ARES_ENOTFOUND;
335     }
336 
337   /* Just chain to the internal implementation we use here; it's exactly
338    * what we want.
339    */
340   result = file_lookup(name, family, host);
341   if(result != ARES_SUCCESS)
342     {
343       /* We guarantee a NULL hostent on failure. */
344       *host = NULL;
345     }
346   return result;
347 }
348 
file_lookup(const char * name,int family,struct hostent ** host)349 static int file_lookup(const char *name, int family, struct hostent **host)
350 {
351   FILE *fp;
352   char **alias;
353   int status;
354   int error;
355 
356 #ifdef WIN32
357   char PATH_HOSTS[MAX_PATH];
358   win_platform platform;
359 
360   PATH_HOSTS[0] = '\0';
361 
362   platform = ares__getplatform();
363 
364   if (platform == WIN_NT) {
365     char tmp[MAX_PATH];
366     HKEY hkeyHosts;
367 
368     if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0, KEY_READ,
369                      &hkeyHosts) == ERROR_SUCCESS)
370     {
371       DWORD dwLength = MAX_PATH;
372       RegQueryValueExA(hkeyHosts, DATABASEPATH, NULL, NULL, (LPBYTE)tmp,
373                       &dwLength);
374       ExpandEnvironmentStringsA(tmp, PATH_HOSTS, MAX_PATH);
375       RegCloseKey(hkeyHosts);
376     }
377   }
378   else if (platform == WIN_9X)
379     GetWindowsDirectoryA(PATH_HOSTS, MAX_PATH);
380   else
381     return ARES_ENOTFOUND;
382 
383   strcat(PATH_HOSTS, WIN_PATH_HOSTS);
384 
385 #elif defined(WATT32)
386   extern const char *_w32_GetHostsFile (void);
387   const char *PATH_HOSTS = _w32_GetHostsFile();
388 
389   if (!PATH_HOSTS)
390     return ARES_ENOTFOUND;
391 #endif
392 
393   /* Per RFC 7686, reject queries for ".onion" domain names with NXDOMAIN. */
394   if (ares__is_onion_domain(name))
395     return ARES_ENOTFOUND;
396 
397 
398   fp = fopen(PATH_HOSTS, "r");
399   if (!fp)
400     {
401       error = ERRNO;
402       switch(error)
403         {
404         case ENOENT:
405         case ESRCH:
406           return ARES_ENOTFOUND;
407         default:
408           DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
409                          error, strerror(error)));
410           DEBUGF(fprintf(stderr, "Error opening file: %s\n",
411                          PATH_HOSTS));
412           *host = NULL;
413           return ARES_EFILE;
414         }
415     }
416   while ((status = ares__get_hostent(fp, family, host)) == ARES_SUCCESS)
417     {
418       if (strcasecmp((*host)->h_name, name) == 0)
419         break;
420       for (alias = (*host)->h_aliases; *alias; alias++)
421         {
422           if (strcasecmp(*alias, name) == 0)
423             break;
424         }
425       if (*alias)
426         break;
427       ares_free_hostent(*host);
428     }
429   fclose(fp);
430   if (status == ARES_EOF)
431     status = ARES_ENOTFOUND;
432   if (status != ARES_SUCCESS)
433     *host = NULL;
434   return status;
435 }
436 
sort_addresses(struct hostent * host,const struct apattern * sortlist,int nsort)437 static void sort_addresses(struct hostent *host,
438                            const struct apattern *sortlist, int nsort)
439 {
440   struct in_addr a1, a2;
441   int i1, i2, ind1, ind2;
442 
443   /* This is a simple insertion sort, not optimized at all.  i1 walks
444    * through the address list, with the loop invariant that everything
445    * to the left of i1 is sorted.  In the loop body, the value at i1 is moved
446    * back through the list (via i2) until it is in sorted order.
447    */
448   for (i1 = 0; host->h_addr_list[i1]; i1++)
449     {
450       memcpy(&a1, host->h_addr_list[i1], sizeof(struct in_addr));
451       ind1 = get_address_index(&a1, sortlist, nsort);
452       for (i2 = i1 - 1; i2 >= 0; i2--)
453         {
454           memcpy(&a2, host->h_addr_list[i2], sizeof(struct in_addr));
455           ind2 = get_address_index(&a2, sortlist, nsort);
456           if (ind2 <= ind1)
457             break;
458           memcpy(host->h_addr_list[i2 + 1], &a2, sizeof(struct in_addr));
459         }
460       memcpy(host->h_addr_list[i2 + 1], &a1, sizeof(struct in_addr));
461     }
462 }
463 
464 /* Find the first entry in sortlist which matches addr.  Return nsort
465  * if none of them match.
466  */
get_address_index(const struct in_addr * addr,const struct apattern * sortlist,int nsort)467 static int get_address_index(const struct in_addr *addr,
468                              const struct apattern *sortlist,
469                              int nsort)
470 {
471   int i;
472 
473   for (i = 0; i < nsort; i++)
474     {
475       if (sortlist[i].family != AF_INET)
476         continue;
477       if (sortlist[i].type == PATTERN_MASK)
478         {
479           if ((addr->s_addr & sortlist[i].mask.addr4.s_addr)
480               == sortlist[i].addrV4.s_addr)
481             break;
482         }
483       else
484         {
485           if (!ares__bitncmp(&addr->s_addr, &sortlist[i].addrV4.s_addr,
486                              sortlist[i].mask.bits))
487             break;
488         }
489     }
490   return i;
491 }
492 
sort6_addresses(struct hostent * host,const struct apattern * sortlist,int nsort)493 static void sort6_addresses(struct hostent *host,
494                             const struct apattern *sortlist, int nsort)
495 {
496   struct ares_in6_addr a1, a2;
497   int i1, i2, ind1, ind2;
498 
499   /* This is a simple insertion sort, not optimized at all.  i1 walks
500    * through the address list, with the loop invariant that everything
501    * to the left of i1 is sorted.  In the loop body, the value at i1 is moved
502    * back through the list (via i2) until it is in sorted order.
503    */
504   for (i1 = 0; host->h_addr_list[i1]; i1++)
505     {
506       memcpy(&a1, host->h_addr_list[i1], sizeof(struct ares_in6_addr));
507       ind1 = get6_address_index(&a1, sortlist, nsort);
508       for (i2 = i1 - 1; i2 >= 0; i2--)
509         {
510           memcpy(&a2, host->h_addr_list[i2], sizeof(struct ares_in6_addr));
511           ind2 = get6_address_index(&a2, sortlist, nsort);
512           if (ind2 <= ind1)
513             break;
514           memcpy(host->h_addr_list[i2 + 1], &a2, sizeof(struct ares_in6_addr));
515         }
516       memcpy(host->h_addr_list[i2 + 1], &a1, sizeof(struct ares_in6_addr));
517     }
518 }
519 
520 /* Find the first entry in sortlist which matches addr.  Return nsort
521  * if none of them match.
522  */
get6_address_index(const struct ares_in6_addr * addr,const struct apattern * sortlist,int nsort)523 static int get6_address_index(const struct ares_in6_addr *addr,
524                               const struct apattern *sortlist,
525                               int nsort)
526 {
527   int i;
528 
529   for (i = 0; i < nsort; i++)
530     {
531       if (sortlist[i].family != AF_INET6)
532         continue;
533       if (!ares__bitncmp(addr, &sortlist[i].addrV6, sortlist[i].mask.bits))
534         break;
535     }
536   return i;
537 }
538