Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / grpc-cloned / deps / grpc / third_party / cares / cares / ares_gethostbyname.c
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
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
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
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       end_hquery(hquery, status, host);
215     }
216   else if ((status == ARES_ENODATA || status == ARES_EBADRESP ||
217             status == ARES_ETIMEOUT) && (hquery->sent_family == AF_INET6 &&
218             hquery->want_family == AF_UNSPEC))
219     {
220       /* The AAAA query yielded no useful result.  Now look up an A instead. */
221       hquery->sent_family = AF_INET;
222       ares_search(hquery->channel, hquery->name, C_IN, T_A, host_callback,
223                   hquery);
224     }
225   else if (status == ARES_EDESTRUCTION)
226     end_hquery(hquery, status, NULL);
227   else
228     next_lookup(hquery, status);
229 }
230
231 static void end_hquery(struct host_query *hquery, int status,
232                        struct hostent *host)
233 {
234   hquery->callback(hquery->arg, status, hquery->timeouts, host);
235   if (host)
236     ares_free_hostent(host);
237   ares_free(hquery->name);
238   ares_free(hquery);
239 }
240
241 /* If the name looks like an IP address, fake up a host entry, end the
242  * query immediately, and return true.  Otherwise return false.
243  */
244 static int fake_hostent(const char *name, int family,
245                         ares_host_callback callback, void *arg)
246 {
247   struct hostent hostent;
248   char *aliases[1] = { NULL };
249   char *addrs[2];
250   int result = 0;
251   struct in_addr in;
252   struct ares_in6_addr in6;
253
254   if (family == AF_INET || family == AF_INET6)
255     {
256       /* It only looks like an IP address if it's all numbers and dots. */
257       int numdots = 0, valid = 1;
258       const char *p;
259       for (p = name; *p; p++)
260         {
261           if (!ISDIGIT(*p) && *p != '.') {
262             valid = 0;
263             break;
264           } else if (*p == '.') {
265             numdots++;
266           }
267         }
268
269       /* if we don't have 3 dots, it is illegal
270        * (although inet_addr doesn't think so).
271        */
272       if (numdots != 3 || !valid)
273         result = 0;
274       else
275         result = ((in.s_addr = inet_addr(name)) == INADDR_NONE ? 0 : 1);
276
277       if (result)
278         family = AF_INET;
279     }
280   if (family == AF_INET6)
281     result = (ares_inet_pton(AF_INET6, name, &in6) < 1 ? 0 : 1);
282
283   if (!result)
284     return 0;
285
286   if (family == AF_INET)
287     {
288       hostent.h_length = (int)sizeof(struct in_addr);
289       addrs[0] = (char *)&in;
290     }
291   else if (family == AF_INET6)
292     {
293       hostent.h_length = (int)sizeof(struct ares_in6_addr);
294       addrs[0] = (char *)&in6;
295     }
296   /* Duplicate the name, to avoid a constness violation. */
297   hostent.h_name = ares_strdup(name);
298   if (!hostent.h_name)
299     {
300       callback(arg, ARES_ENOMEM, 0, NULL);
301       return 1;
302     }
303
304   /* Fill in the rest of the host structure and terminate the query. */
305   addrs[1] = NULL;
306   hostent.h_aliases = aliases;
307   hostent.h_addrtype = aresx_sitoss(family);
308   hostent.h_addr_list = addrs;
309   callback(arg, ARES_SUCCESS, 0, &hostent);
310
311   ares_free((char *)(hostent.h_name));
312   return 1;
313 }
314
315 /* This is an API method */
316 int ares_gethostbyname_file(ares_channel channel, const char *name,
317                             int family, struct hostent **host)
318 {
319   int result;
320
321   /* We only take the channel to ensure that ares_init() been called. */
322   if(channel == NULL)
323     {
324       /* Anything will do, really.  This seems fine, and is consistent with
325          other error cases. */
326       *host = NULL;
327       return ARES_ENOTFOUND;
328     }
329
330   /* Just chain to the internal implementation we use here; it's exactly
331    * what we want.
332    */
333   result = file_lookup(name, family, host);
334   if(result != ARES_SUCCESS)
335     {
336       /* We guarantee a NULL hostent on failure. */
337       *host = NULL;
338     }
339   return result;
340 }
341
342 static int file_lookup(const char *name, int family, struct hostent **host)
343 {
344   FILE *fp;
345   char **alias;
346   int status;
347   int error;
348
349   /* Per RFC 7686, reject queries for ".onion" domain names with NXDOMAIN. */
350   if (ares__is_onion_domain(name))
351     return ARES_ENOTFOUND;
352
353 #ifdef WIN32
354   char PATH_HOSTS[MAX_PATH];
355   win_platform platform;
356
357   PATH_HOSTS[0] = '\0';
358
359   platform = ares__getplatform();
360
361   if (platform == WIN_NT) {
362     char tmp[MAX_PATH];
363     HKEY hkeyHosts;
364
365     if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0, KEY_READ,
366                      &hkeyHosts) == ERROR_SUCCESS)
367     {
368       DWORD dwLength = MAX_PATH;
369       RegQueryValueExA(hkeyHosts, DATABASEPATH, NULL, NULL, (LPBYTE)tmp,
370                       &dwLength);
371       ExpandEnvironmentStringsA(tmp, PATH_HOSTS, MAX_PATH);
372       RegCloseKey(hkeyHosts);
373     }
374   }
375   else if (platform == WIN_9X)
376     GetWindowsDirectoryA(PATH_HOSTS, MAX_PATH);
377   else
378     return ARES_ENOTFOUND;
379
380   strcat(PATH_HOSTS, WIN_PATH_HOSTS);
381
382 #elif defined(WATT32)
383   extern const char *_w32_GetHostsFile (void);
384   const char *PATH_HOSTS = _w32_GetHostsFile();
385
386   if (!PATH_HOSTS)
387     return ARES_ENOTFOUND;
388 #endif
389
390   fp = fopen(PATH_HOSTS, "r");
391   if (!fp)
392     {
393       error = ERRNO;
394       switch(error)
395         {
396         case ENOENT:
397         case ESRCH:
398           return ARES_ENOTFOUND;
399         default:
400           DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
401                          error, strerror(error)));
402           DEBUGF(fprintf(stderr, "Error opening file: %s\n",
403                          PATH_HOSTS));
404           *host = NULL;
405           return ARES_EFILE;
406         }
407     }
408   while ((status = ares__get_hostent(fp, family, host)) == ARES_SUCCESS)
409     {
410       if (strcasecmp((*host)->h_name, name) == 0)
411         break;
412       for (alias = (*host)->h_aliases; *alias; alias++)
413         {
414           if (strcasecmp(*alias, name) == 0)
415             break;
416         }
417       if (*alias)
418         break;
419       ares_free_hostent(*host);
420     }
421   fclose(fp);
422   if (status == ARES_EOF)
423     status = ARES_ENOTFOUND;
424   if (status != ARES_SUCCESS)
425     *host = NULL;
426   return status;
427 }
428
429 static void sort_addresses(struct hostent *host,
430                            const struct apattern *sortlist, int nsort)
431 {
432   struct in_addr a1, a2;
433   int i1, i2, ind1, ind2;
434
435   /* This is a simple insertion sort, not optimized at all.  i1 walks
436    * through the address list, with the loop invariant that everything
437    * to the left of i1 is sorted.  In the loop body, the value at i1 is moved
438    * back through the list (via i2) until it is in sorted order.
439    */
440   for (i1 = 0; host->h_addr_list[i1]; i1++)
441     {
442       memcpy(&a1, host->h_addr_list[i1], sizeof(struct in_addr));
443       ind1 = get_address_index(&a1, sortlist, nsort);
444       for (i2 = i1 - 1; i2 >= 0; i2--)
445         {
446           memcpy(&a2, host->h_addr_list[i2], sizeof(struct in_addr));
447           ind2 = get_address_index(&a2, sortlist, nsort);
448           if (ind2 <= ind1)
449             break;
450           memcpy(host->h_addr_list[i2 + 1], &a2, sizeof(struct in_addr));
451         }
452       memcpy(host->h_addr_list[i2 + 1], &a1, sizeof(struct in_addr));
453     }
454 }
455
456 /* Find the first entry in sortlist which matches addr.  Return nsort
457  * if none of them match.
458  */
459 static int get_address_index(const struct in_addr *addr,
460                              const struct apattern *sortlist,
461                              int nsort)
462 {
463   int i;
464
465   for (i = 0; i < nsort; i++)
466     {
467       if (sortlist[i].family != AF_INET)
468         continue;
469       if (sortlist[i].type == PATTERN_MASK)
470         {
471           if ((addr->s_addr & sortlist[i].mask.addr4.s_addr)
472               == sortlist[i].addrV4.s_addr)
473             break;
474         }
475       else
476         {
477           if (!ares__bitncmp(&addr->s_addr, &sortlist[i].addrV4.s_addr,
478                              sortlist[i].mask.bits))
479             break;
480         }
481     }
482   return i;
483 }
484
485 static void sort6_addresses(struct hostent *host,
486                             const struct apattern *sortlist, int nsort)
487 {
488   struct ares_in6_addr a1, a2;
489   int i1, i2, ind1, ind2;
490
491   /* This is a simple insertion sort, not optimized at all.  i1 walks
492    * through the address list, with the loop invariant that everything
493    * to the left of i1 is sorted.  In the loop body, the value at i1 is moved
494    * back through the list (via i2) until it is in sorted order.
495    */
496   for (i1 = 0; host->h_addr_list[i1]; i1++)
497     {
498       memcpy(&a1, host->h_addr_list[i1], sizeof(struct ares_in6_addr));
499       ind1 = get6_address_index(&a1, sortlist, nsort);
500       for (i2 = i1 - 1; i2 >= 0; i2--)
501         {
502           memcpy(&a2, host->h_addr_list[i2], sizeof(struct ares_in6_addr));
503           ind2 = get6_address_index(&a2, sortlist, nsort);
504           if (ind2 <= ind1)
505             break;
506           memcpy(host->h_addr_list[i2 + 1], &a2, sizeof(struct ares_in6_addr));
507         }
508       memcpy(host->h_addr_list[i2 + 1], &a1, sizeof(struct ares_in6_addr));
509     }
510 }
511
512 /* Find the first entry in sortlist which matches addr.  Return nsort
513  * if none of them match.
514  */
515 static int get6_address_index(const struct ares_in6_addr *addr,
516                               const struct apattern *sortlist,
517                               int nsort)
518 {
519   int i;
520
521   for (i = 0; i < nsort; i++)
522     {
523       if (sortlist[i].family != AF_INET6)
524         continue;
525       if (!ares__bitncmp(addr, &sortlist[i].addrV6, sortlist[i].mask.bits))
526         break;
527     }
528   return i;
529 }