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