be1f92b216cd5fa35986091faa24d4c2db0b2870
[platform/upstream/c-ares.git] / ares_gethostbyname.c
1 /* $Id$ */
2
3 /* Copyright 1998 by the Massachusetts Institute of Technology.
4  *
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.
16  */
17
18 #include "setup.h"
19
20 #if defined(WIN32) && !defined(WATT32)
21 #include "nameser.h"
22 #else
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <netdb.h>
27 #ifdef HAVE_ARPA_NAMESER_H
28 #include <arpa/nameser.h>
29 #endif
30 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
31 #include <arpa/nameser_compat.h>
32 #endif
33 #endif
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <ctype.h>
39 #ifdef HAVE_STRINGS_H
40 #include <strings.h>
41 #endif
42
43 #include "ares.h"
44 #include "inet_net_pton.h"
45 #include "bitncmp.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 family;
59   const char *remaining_lookups;
60   int timeouts;
61 };
62
63 static void next_lookup(struct host_query *hquery, int status_code);
64 static void host_callback(void *arg, int status, int timeouts,
65                           unsigned char *abuf, int alen);
66 static void end_hquery(struct host_query *hquery, int status,
67                        struct hostent *host);
68 static int fake_hostent(const char *name, int family, ares_host_callback callback,
69                         void *arg);
70 static int file_lookup(const char *name, int family, struct hostent **host);
71 static void sort_addresses(struct hostent *host, struct apattern *sortlist,
72                            int nsort);
73 static void sort6_addresses(struct hostent *host, struct apattern *sortlist,
74                            int nsort);
75 static int get_address_index(struct in_addr *addr, struct apattern *sortlist,
76                              int nsort);
77 static int get6_address_index(struct in6_addr *addr, struct apattern *sortlist,
78                              int nsort);
79
80 void ares_gethostbyname(ares_channel channel, const char *name, int family,
81                         ares_host_callback callback, void *arg)
82 {
83   struct host_query *hquery;
84
85   /* Right now we only know how to look up Internet addresses. */
86   if (family != AF_INET && family != AF_INET6)
87     {
88       callback(arg, ARES_ENOTIMP, 0, NULL);
89       return;
90     }
91
92   if (fake_hostent(name, family, callback, arg))
93     return;
94
95   /* Allocate and fill in the host query structure. */
96   hquery = malloc(sizeof(struct host_query));
97   if (!hquery)
98     {
99       callback(arg, ARES_ENOMEM, 0, NULL);
100       return;
101     }
102   hquery->channel = channel;
103   hquery->name = strdup(name);
104   hquery->family = family;
105   if (!hquery->name)
106     {
107       free(hquery);
108       callback(arg, ARES_ENOMEM, 0, NULL);
109       return;
110     }
111   hquery->callback = callback;
112   hquery->arg = arg;
113   hquery->remaining_lookups = channel->lookups;
114   hquery->timeouts = 0;
115
116   /* Start performing lookups according to channel->lookups. */
117   next_lookup(hquery, ARES_ECONNREFUSED /* initial error code */);
118 }
119
120 static void next_lookup(struct host_query *hquery, int status_code)
121 {
122   const char *p;
123   struct hostent *host;
124   int status = status_code;
125
126   for (p = hquery->remaining_lookups; *p; p++)
127     {
128       switch (*p)
129         {
130         case 'b':
131           /* DNS lookup */
132           hquery->remaining_lookups = p + 1;
133           if (hquery->family == AF_INET6)
134             ares_search(hquery->channel, hquery->name, C_IN, T_AAAA,
135                         host_callback, hquery);
136           else
137             ares_search(hquery->channel, hquery->name, C_IN, T_A, host_callback,
138                         hquery);
139           return;
140
141         case 'f':
142           /* Host file lookup */
143           status = file_lookup(hquery->name, hquery->family, &host);
144
145           /* this status check below previously checked for !ARES_ENOTFOUND,
146              but we should not assume that this single error code is the one
147              that can occur, as that is in fact no longer the case */
148           if (status == ARES_SUCCESS)
149             {
150               end_hquery(hquery, status, host);
151               return;
152             }
153           status = status_code;   /* Use original status code */
154           break;
155         }
156     }
157   end_hquery(hquery, status, NULL);
158 }
159
160 static void host_callback(void *arg, int status, int timeouts,
161                           unsigned char *abuf, int alen)
162 {
163   struct host_query *hquery = (struct host_query *) arg;
164   ares_channel channel = hquery->channel;
165   struct hostent *host = NULL;
166
167   hquery->timeouts += timeouts;
168   if (status == ARES_SUCCESS)
169     {
170       if (hquery->family == AF_INET)
171         {
172           status = ares_parse_a_reply(abuf, alen, &host, NULL, NULL);
173           if (host && channel->nsort)
174             sort_addresses(host, channel->sortlist, channel->nsort);
175         }
176       else if (hquery->family == AF_INET6)
177         {
178           status = ares_parse_aaaa_reply(abuf, alen, &host, NULL, NULL);
179           if (status == ARES_ENODATA)
180             {
181               /* The query returned something (e.g. CNAME) but there were no
182                  AAAA records.  Try looking up A instead.  */
183               hquery->family = AF_INET;
184               ares_search(hquery->channel, hquery->name, C_IN, T_A, host_callback,
185                           hquery);
186               return;
187             }
188           if (host && channel->nsort)
189             sort6_addresses(host, channel->sortlist, channel->nsort);
190         }
191       end_hquery(hquery, status, host);
192     }
193   else if (status == ARES_ENODATA && hquery->family == AF_INET6)
194     {
195       /* There was no AAAA. Now lookup an A */
196       hquery->family = AF_INET;
197       ares_search(hquery->channel, hquery->name, C_IN, T_A, host_callback,
198                   hquery);
199     }
200   else if (status == ARES_EDESTRUCTION)
201     end_hquery(hquery, status, NULL);
202   else
203     next_lookup(hquery, status);
204 }
205
206 static void end_hquery(struct host_query *hquery, int status,
207                        struct hostent *host)
208 {
209   hquery->callback(hquery->arg, status, hquery->timeouts, host);
210   if (host)
211     ares_free_hostent(host);
212   free(hquery->name);
213   free(hquery);
214 }
215
216 /* If the name looks like an IP address, fake up a host entry, end the
217  * query immediately, and return true.  Otherwise return false.
218  */
219 static int fake_hostent(const char *name, int family, ares_host_callback callback,
220                         void *arg)
221 {
222   struct hostent hostent;
223   char *aliases[1] = { NULL };
224   char *addrs[2];
225   int result = 0;
226   struct in_addr in;
227   struct in6_addr in6;
228
229   if (family == AF_INET)
230     {
231       /* It only looks like an IP address if it's all numbers and dots. */
232       int numdots = 0;
233       const char *p;
234       for (p = name; *p; p++)
235         {
236           if (!ISDIGIT(*p) && *p != '.') {
237             return 0;
238           } else if (*p == '.') {
239             numdots++;
240           }
241         }
242     
243       /* if we don't have 3 dots, it is illegal 
244        * (although inet_addr doesn't think so).
245        */
246       if (numdots != 3)
247         result = 0;
248       else
249         result = ((in.s_addr = inet_addr(name)) == INADDR_NONE ? 0 : 1);
250     }
251   else if (family == AF_INET6)
252     result = (ares_inet_pton(AF_INET6, name, &in6) < 1 ? 0 : 1);
253
254   if (!result)
255     return 0;
256
257   if (family == AF_INET)
258     {
259       hostent.h_length = sizeof(struct in_addr);
260       addrs[0] = (char *)&in;
261     }
262   else if (family == AF_INET6)
263     {
264       hostent.h_length = sizeof(struct in6_addr);
265       addrs[0] = (char *)&in6;
266     }
267   /* Duplicate the name, to avoid a constness violation. */
268   hostent.h_name = strdup(name);
269   if (!hostent.h_name)
270     {
271       callback(arg, ARES_ENOMEM, 0, NULL);
272       return 1;
273     }
274
275   /* Fill in the rest of the host structure and terminate the query. */
276   addrs[1] = NULL;
277   hostent.h_aliases = aliases;
278   hostent.h_addrtype = family;
279   hostent.h_addr_list = addrs;
280   callback(arg, ARES_SUCCESS, 0, &hostent);
281
282   free((char *)(hostent.h_name));
283   return 1;
284 }
285
286 static int file_lookup(const char *name, int family, struct hostent **host)
287 {
288   FILE *fp;
289   char **alias;
290   int status;
291   int error;
292
293 #ifdef WIN32
294   char PATH_HOSTS[MAX_PATH];
295   if (IS_NT()) {
296     char tmp[MAX_PATH];
297     HKEY hkeyHosts;
298
299     if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0, KEY_READ, &hkeyHosts)
300         == ERROR_SUCCESS)
301     {
302       DWORD dwLength = MAX_PATH;
303       RegQueryValueEx(hkeyHosts, DATABASEPATH, NULL, NULL, (LPBYTE)tmp,
304                       &dwLength);
305       ExpandEnvironmentStrings(tmp, PATH_HOSTS, MAX_PATH);
306       RegCloseKey(hkeyHosts);
307     }
308   }
309   else
310     GetWindowsDirectory(PATH_HOSTS, MAX_PATH);
311
312   strcat(PATH_HOSTS, WIN_PATH_HOSTS);
313
314 #elif defined(WATT32)
315   extern const char *_w32_GetHostsFile (void);
316   const char *PATH_HOSTS = _w32_GetHostsFile();
317
318   if (!PATH_HOSTS)
319     return ARES_ENOTFOUND;
320 #endif
321
322   fp = fopen(PATH_HOSTS, "r");
323   if (!fp)
324     {
325       error = ERRNO;
326       switch(error)
327         {
328         case ENOENT:
329         case ESRCH:
330           return ARES_ENOTFOUND;
331         default:
332           DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
333                          error, strerror(error)));
334           DEBUGF(fprintf(stderr, "Error opening file: %s\n",
335                          PATH_HOSTS));
336           *host = NULL;
337           return ARES_EFILE;
338         }
339     }
340   while ((status = ares__get_hostent(fp, family, host)) == ARES_SUCCESS)
341     {
342       if (strcasecmp((*host)->h_name, name) == 0)
343         break;
344       for (alias = (*host)->h_aliases; *alias; alias++)
345         {
346           if (strcasecmp(*alias, name) == 0)
347             break;
348         }
349       if (*alias)
350         break;
351       ares_free_hostent(*host);
352     }
353   fclose(fp);
354   if (status == ARES_EOF)
355     status = ARES_ENOTFOUND;
356   if (status != ARES_SUCCESS)
357     *host = NULL;
358   return status;
359 }
360
361 static void sort_addresses(struct hostent *host, struct apattern *sortlist,
362                            int nsort)
363 {
364   struct in_addr a1, a2;
365   int i1, i2, ind1, ind2;
366
367   /* This is a simple insertion sort, not optimized at all.  i1 walks
368    * through the address list, with the loop invariant that everything
369    * to the left of i1 is sorted.  In the loop body, the value at i1 is moved
370    * back through the list (via i2) until it is in sorted order.
371    */
372   for (i1 = 0; host->h_addr_list[i1]; i1++)
373     {
374       memcpy(&a1, host->h_addr_list[i1], sizeof(struct in_addr));
375       ind1 = get_address_index(&a1, sortlist, nsort);
376       for (i2 = i1 - 1; i2 >= 0; i2--)
377         {
378           memcpy(&a2, host->h_addr_list[i2], sizeof(struct in_addr));
379           ind2 = get_address_index(&a2, sortlist, nsort);
380           if (ind2 <= ind1)
381             break;
382           memcpy(host->h_addr_list[i2 + 1], &a2, sizeof(struct in_addr));
383         }
384       memcpy(host->h_addr_list[i2 + 1], &a1, sizeof(struct in_addr));
385     }
386 }
387
388 /* Find the first entry in sortlist which matches addr.  Return nsort
389  * if none of them match.
390  */
391 static int get_address_index(struct in_addr *addr, struct apattern *sortlist,
392                              int nsort)
393 {
394   int i;
395
396   for (i = 0; i < nsort; i++)
397     {
398       if (sortlist[i].family != AF_INET)
399         continue;
400       if (sortlist[i].type == PATTERN_MASK)
401         {
402           if ((addr->s_addr & sortlist[i].mask.addr.addr4.s_addr)
403               == sortlist[i].addr.addr4.s_addr)
404             break;
405         }
406       else
407         {
408           if (!ares_bitncmp(&addr->s_addr, &sortlist[i].addr.addr4.s_addr,
409                             sortlist[i].mask.bits))
410             break;
411         }
412     }
413   return i;
414 }
415
416 static void sort6_addresses(struct hostent *host, struct apattern *sortlist,
417                            int nsort)
418 {
419   struct in6_addr a1, a2;
420   int i1, i2, ind1, ind2;
421
422   /* This is a simple insertion sort, not optimized at all.  i1 walks
423    * through the address list, with the loop invariant that everything
424    * to the left of i1 is sorted.  In the loop body, the value at i1 is moved
425    * back through the list (via i2) until it is in sorted order.
426    */
427   for (i1 = 0; host->h_addr_list[i1]; i1++)
428     {
429       memcpy(&a1, host->h_addr_list[i1], sizeof(struct in6_addr));
430       ind1 = get6_address_index(&a1, sortlist, nsort);
431       for (i2 = i1 - 1; i2 >= 0; i2--)
432         {
433           memcpy(&a2, host->h_addr_list[i2], sizeof(struct in6_addr));
434           ind2 = get6_address_index(&a2, sortlist, nsort);
435           if (ind2 <= ind1)
436             break;
437           memcpy(host->h_addr_list[i2 + 1], &a2, sizeof(struct in6_addr));
438         }
439       memcpy(host->h_addr_list[i2 + 1], &a1, sizeof(struct in6_addr));
440     }
441 }
442
443 /* Find the first entry in sortlist which matches addr.  Return nsort
444  * if none of them match.
445  */
446 static int get6_address_index(struct in6_addr *addr, struct apattern *sortlist,
447                              int nsort)
448 {
449   int i;
450
451   for (i = 0; i < nsort; i++)
452     {
453       if (sortlist[i].family != AF_INET6)
454         continue;
455         if (!ares_bitncmp(&addr->s6_addr, &sortlist[i].addr.addr6.s6_addr, sortlist[i].mask.bits))
456           break;
457     }
458   return i;
459 }