Update.
[jlayton/glibc.git] / hesiod / hesiod.c
1 /* Copyright (c) 1996 by Internet Software Consortium.
2  *
3  * Permission to use, copy, modify, and distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
8  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
9  * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
10  * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
11  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
12  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
13  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
14  * SOFTWARE.
15  */
16
17 /* Copyright 1996 by the Massachusetts Institute of Technology.
18  *
19  * Permission to use, copy, modify, and distribute this
20  * software and its documentation for any purpose and without
21  * fee is hereby granted, provided that the above copyright
22  * notice appear in all copies and that both that copyright
23  * notice and this permission notice appear in supporting
24  * documentation, and that the name of M.I.T. not be used in
25  * advertising or publicity pertaining to distribution of the
26  * software without specific, written prior permission.
27  * M.I.T. makes no representations about the suitability of
28  * this software for any purpose.  It is provided "as is"
29  * without express or implied warranty.
30  */
31
32 /* This file is part of the hesiod library.  It implements the core
33  * portion of the hesiod resolver.
34  *
35  * This file is loosely based on an interim version of hesiod.c from
36  * the BIND IRS library, which was in turn based on an earlier version
37  * of this file.  Extensive changes have been made on each step of the
38  * path.
39  *
40  * This implementation is not truly thread-safe at the moment because
41  * it uses res_send() and accesses _res.
42  */
43
44 static const char rcsid[] = "$Id$";
45
46 #include <sys/types.h>
47 #include <netinet/in.h>
48 #include <arpa/nameser.h>
49 #include <errno.h>
50 #include <netdb.h>
51 #include <resolv.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <ctype.h>
56 #include "hesiod.h"
57 #include "hesiod_p.h"
58
59 /* A few operating systems don't define these. */
60 #ifndef C_HS
61 #define C_HS    4
62 #endif
63 #ifndef T_TXT
64 #define T_TXT   16
65 #endif
66
67 static int read_config_file(struct hesiod_p *ctx, const char *filename);
68 static char **get_txt_records(struct hesiod_p *ctx, int class,
69                               const char *name);
70 #ifdef _LIBC
71 # define cistrcmp(s1, s2) strcasecmp (s1, s2)
72 #else
73 static int cistrcmp(const char *s1, const char *s2);
74 #endif
75
76 /* This function is called to initialize a hesiod_p. */
77 int hesiod_init(void **context)
78 {
79   struct hesiod_p *ctx;
80   const char *p, *configname;
81
82   ctx = malloc(sizeof(struct hesiod_p));
83   if (ctx)
84     {
85       *context = ctx;
86       configname = __secure_getenv("HESIOD_CONFIG");
87       if (!configname)
88         configname = SYSCONFDIR "/hesiod.conf";
89       if (read_config_file(ctx, configname) >= 0)
90         {
91           /* The default rhs can be overridden by an environment variable. */
92           p = __secure_getenv("HES_DOMAIN");
93           if (p)
94             {
95               if (ctx->rhs)
96                 free(ctx->rhs);
97               ctx->rhs = malloc(strlen(p) + 2);
98               if (ctx->rhs)
99                 {
100                   *ctx->rhs = '.';
101                   strcpy(ctx->rhs + 1, (*p == '.') ? p + 1 : p);
102                   return 0;
103                 }
104               else
105                 __set_errno (ENOMEM);
106             }
107           else
108             return 0;
109         }
110     }
111   else
112     __set_errno (ENOMEM);
113
114   if (ctx->lhs)
115     free(ctx->lhs);
116   if (ctx->rhs)
117     free(ctx->rhs);
118   if (ctx)
119     free(ctx);
120   return -1;
121 }
122
123 /* This function deallocates the hesiod_p. */
124 void hesiod_end(void *context)
125 {
126   struct hesiod_p *ctx = (struct hesiod_p *) context;
127
128   free(ctx->rhs);
129   if (ctx->lhs)
130     free(ctx->lhs);
131   free(ctx);
132 }
133
134 /* This function takes a hesiod (name, type) and returns a DNS
135  * name which is to be resolved.
136  */
137 char *hesiod_to_bind(void *context, const char *name, const char *type)
138 {
139   struct hesiod_p *ctx = (struct hesiod_p *) context;
140   char bindname[MAXDNAME], *p, *endp, *ret, **rhs_list = NULL;
141   const char *rhs;
142   size_t len;
143
144   endp = stpcpy(bindname, name);
145
146   /* Find the right right hand side to use, possibly truncating bindname. */
147   p = strchr(bindname, '@');
148   if (p)
149     {
150       *p++ = 0;
151       if (strchr(p, '.'))
152         rhs = name + (p - bindname);
153       else
154         {
155           rhs_list = hesiod_resolve(context, p, "rhs-extension");
156           if (rhs_list)
157             rhs = *rhs_list;
158           else
159             {
160               __set_errno (ENOENT);
161               return NULL;
162             }
163         }
164     } else
165       rhs = ctx->rhs;
166
167   /* See if we have enough room. */
168   len = (endp - bindname) + 1 + strlen(type);
169   if (ctx->lhs)
170     len += strlen(ctx->lhs) + ((ctx->lhs[0] != '.') ? 1 : 0);
171   len += strlen(rhs) + ((rhs[0] != '.') ? 1 : 0);
172   if (len > sizeof(bindname) - 1)
173     {
174       if (rhs_list)
175         hesiod_free_list(context, rhs_list);
176       __set_errno (EMSGSIZE);
177       return NULL;
178     }
179
180   /* Put together the rest of the domain. */
181   endp = __stpcpy (__stpcpy (endp, "."), type);
182   if (ctx->lhs)
183     {
184       if (ctx->lhs[0] != '.')
185         endp = __stpcpy (endp, ".");
186       endp = __stpcpy (endp, ctx->lhs);
187     }
188   if (rhs[0] != '.')
189     endp = __stpcpy (endp, ".");
190   endp = __stpcpy (endp, rhs);
191
192   /* rhs_list is no longer needed, since we're done with rhs. */
193   if (rhs_list)
194     hesiod_free_list(context, rhs_list);
195
196   /* Make a copy of the result and return it to the caller. */
197   ret = malloc((endp - bindname) + 1);
198   if (!ret)
199     {
200       __set_errno (ENOMEM);
201       return NULL;
202     }
203   strcpy(ret, bindname);
204   return ret;
205 }
206
207 /* This is the core function.  Given a hesiod name and type, it
208  * returns an array of strings returned by the resolver.
209  */
210 char **hesiod_resolve(void *context, const char *name, const char *type)
211 {
212   struct hesiod_p *ctx = (struct hesiod_p *) context;
213   char *bindname, **retvec;
214
215   bindname = hesiod_to_bind(context, name, type);
216   if (!bindname)
217     return NULL;
218
219   retvec = get_txt_records(ctx, ctx->classes[0], bindname);
220   if (retvec == NULL && errno == ENOENT && ctx->classes[1])
221     retvec = get_txt_records(ctx, ctx->classes[1], bindname);
222
223   free(bindname);
224   return retvec;
225 }
226
227 void hesiod_free_list(void *context, char **list)
228 {
229   char **p;
230
231   for (p = list; *p; p++)
232     free(*p);
233   free(list);
234 }
235
236 /* This function parses the /etc/hesiod.conf file.  Returns 0 on success,
237  * -1 on failure.  On failure, it might leave values in ctx->lhs or
238  * ctx->rhs which need to be freed by the caller. */
239 static int read_config_file(struct hesiod_p *ctx, const char *filename)
240 {
241   char *key, *data, *p, **which;
242   char buf[MAXDNAME + 7];
243   int n;
244   FILE *fp;
245
246   /* Set default query classes. */
247   ctx->classes[0] = C_IN;
248   ctx->classes[1] = C_HS;
249
250   /* Try to open the configuration file. */
251   fp = fopen(filename, "r");
252   if (!fp)
253     {
254       /* Use compiled in default domain names. */
255       ctx->lhs = malloc(strlen(DEF_LHS) + 1);
256       ctx->rhs = malloc(strlen(DEF_RHS) + 1);
257       if (ctx->lhs && ctx->rhs)
258         {
259           strcpy(ctx->lhs, DEF_LHS);
260           strcpy(ctx->rhs, DEF_RHS);
261           return 0;
262         }
263       else
264         {
265           __set_errno (ENOMEM);
266           return -1;
267         }
268     }
269
270   ctx->lhs = NULL;
271   ctx->rhs = NULL;
272   while (fgets(buf, sizeof(buf), fp) != NULL)
273     {
274       p = buf;
275       if (*p == '#' || *p == '\n' || *p == '\r')
276         continue;
277       while(*p == ' ' || *p == '\t')
278         p++;
279       key = p;
280       while(*p != ' ' && *p != '\t' && *p != '=')
281         p++;
282       *p++ = 0;
283
284       while(isspace(*p) || *p == '=')
285         p++;
286       data = p;
287       while(!isspace(*p))
288         p++;
289       *p = 0;
290
291       if (cistrcmp(key, "lhs") == 0 || cistrcmp(key, "rhs") == 0)
292         {
293           which = (strcmp(key, "lhs") == 0) ? &ctx->lhs : &ctx->rhs;
294           *which = malloc(strlen(data) + 1);
295           if (!*which)
296             {
297               __set_errno (ENOMEM);
298               return -1;
299             }
300           strcpy(*which, data);
301         }
302       else if (cistrcmp(key, "classes") == 0)
303         {
304           n = 0;
305           while (*data && n < 2)
306             {
307               p = data;
308               while (*p && *p != ',')
309                 p++;
310               if (*p)
311                 *p++ = 0;
312               if (cistrcmp(data, "IN") == 0)
313                 ctx->classes[n++] = C_IN;
314               else if (cistrcmp(data, "HS") == 0)
315                 ctx->classes[n++] = C_HS;
316               data = p;
317             }
318           while (n < 2)
319             ctx->classes[n++] = 0;
320         }
321     }
322   fclose(fp);
323
324   if (!ctx->rhs || ctx->classes[0] == 0 || ctx->classes[0] == ctx->classes[1])
325     {
326       __set_errno (ENOEXEC);
327       return -1;
328     }
329
330   return 0;
331 }
332
333 /* Given a DNS class and a DNS name, do a lookup for TXT records, and
334  * return a list of them.
335  */
336 static char **get_txt_records(struct hesiod_p *ctx, int qclass,
337                               const char *name)
338 {
339   HEADER *hp;
340   unsigned char qbuf[PACKETSZ], abuf[MAX_HESRESP], *p, *eom, *eor;
341   char *dst, **list;
342   int ancount, qdcount, i, j, n, skip, type, class, len;
343
344   /* Make sure the resolver is initialized. */
345   if ((_res.options & RES_INIT) == 0 && res_init() == -1)
346     return NULL;
347
348   /* Construct the query. */
349   n = res_mkquery(QUERY, name, qclass, T_TXT, NULL, 0,
350                   NULL, qbuf, PACKETSZ);
351   if (n < 0)
352       return NULL;
353
354   /* Send the query. */
355   n = res_send(qbuf, n, abuf, MAX_HESRESP);
356   if (n < 0)
357     {
358       __set_errno (ECONNREFUSED);
359       return NULL;
360     }
361
362   /* Parse the header of the result. */
363   hp = (HEADER *) abuf;
364   ancount = ntohs(hp->ancount);
365   qdcount = ntohs(hp->qdcount);
366   p = abuf + sizeof(HEADER);
367   eom = abuf + n;
368
369   /* Skip questions, trying to get to the answer section which follows. */
370   for (i = 0; i < qdcount; i++)
371     {
372       skip = dn_skipname(p, eom);
373       if (skip < 0 || p + skip + QFIXEDSZ > eom)
374         {
375           __set_errno (EMSGSIZE);
376           return NULL;
377         }
378       p += skip + QFIXEDSZ;
379     }
380
381   /* Allocate space for the text record answers. */
382   list = malloc((ancount + 1) * sizeof(char *));
383   if (!list)
384     {
385       __set_errno (ENOMEM);
386       return NULL;
387     }
388
389   /* Parse the answers. */
390   j = 0;
391   for (i = 0; i < ancount; i++)
392     {
393       /* Parse the header of this answer. */
394       skip = dn_skipname(p, eom);
395       if (skip < 0 || p + skip + 10 > eom)
396         break;
397       type = p[skip + 0] << 8 | p[skip + 1];
398       class = p[skip + 2] << 8 | p[skip + 3];
399       len = p[skip + 8] << 8 | p[skip + 9];
400       p += skip + 10;
401       if (p + len > eom)
402         {
403           __set_errno (EMSGSIZE);
404           break;
405         }
406
407       /* Skip entries of the wrong class and type. */
408       if (class != qclass || type != T_TXT)
409         {
410           p += len;
411           continue;
412         }
413
414       /* Allocate space for this answer. */
415       list[j] = malloc(len);
416       if (!list[j])
417         {
418           __set_errno (ENOMEM);
419           break;
420         }
421       dst = list[j++];
422
423       /* Copy answer data into the allocated area. */
424       eor = p + len;
425       while (p < eor)
426         {
427           n = (unsigned char) *p++;
428           if (p + n > eor)
429             {
430               __set_errno (EMSGSIZE);
431               break;
432             }
433           memcpy(dst, p, n);
434           p += n;
435           dst += n;
436         }
437       if (p < eor)
438         {
439           __set_errno (EMSGSIZE);
440           break;
441         }
442       *dst = 0;
443     }
444
445   /* If we didn't terminate the loop normally, something went wrong. */
446   if (i < ancount)
447     {
448       for (i = 0; i < j; i++)
449         free(list[i]);
450       free(list);
451       return NULL;
452     }
453
454   if (j == 0)
455     {
456       __set_errno (ENOENT);
457       free(list);
458       return NULL;
459     }
460
461   list[j] = NULL;
462   return list;
463 }
464
465 #ifndef _LIBC
466 static int cistrcmp(const char *s1, const char *s2)
467 {
468   while (*s1 && tolower(*s1) == tolower(*s2))
469     {
470       s1++;
471       s2++;
472     }
473   return tolower(*s1) - tolower(*s2);
474 }
475 #endif