xref: /netbsd-src/lib/libc/net/hesiod.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: hesiod.c,v 1.22 2004/05/23 16:54:13 christos Exp $	*/
2 
3 /* Copyright (c) 1996 by Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
10  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
11  * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
12  * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
13  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
14  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
15  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
16  * SOFTWARE.
17  */
18 
19 /* Copyright 1996 by the Massachusetts Institute of Technology.
20  *
21  * Permission to use, copy, modify, and distribute this
22  * software and its documentation for any purpose and without
23  * fee is hereby granted, provided that the above copyright
24  * notice appear in all copies and that both that copyright
25  * notice and this permission notice appear in supporting
26  * documentation, and that the name of M.I.T. not be used in
27  * advertising or publicity pertaining to distribution of the
28  * software without specific, written prior permission.
29  * M.I.T. makes no representations about the suitability of
30  * this software for any purpose.  It is provided "as is"
31  * without express or implied warranty.
32  */
33 
34 /* This file is part of the hesiod library.  It implements the core
35  * portion of the hesiod resolver.
36  *
37  * This file is loosely based on an interim version of hesiod.c from
38  * the BIND IRS library, which was in turn based on an earlier version
39  * of this file.  Extensive changes have been made on each step of the
40  * path.
41  *
42  * This implementation is thread-safe because it uses res_nsend().
43  */
44 
45 #include <sys/cdefs.h>
46 
47 #if defined(LIBC_SCCS) && !defined(lint)
48 __IDSTRING(rcsid_hesiod_c,
49     "#Id: hesiod.c,v 1.18.2.1 1997/01/03 20:48:20 ghudson Exp #");
50 __IDSTRING(rcsid_hesiod_p_h,
51     "#Id: hesiod_p.h,v 1.1 1996/12/08 21:39:37 ghudson Exp #");
52 __IDSTRING(rcsid_hescompat_c,
53     "#Id: hescompat.c,v 1.1.2.1 1996/12/16 08:37:45 ghudson Exp #");
54 __RCSID("$NetBSD: hesiod.c,v 1.22 2004/05/23 16:54:13 christos Exp $");
55 #endif /* LIBC_SCCS and not lint */
56 
57 #include "namespace.h"
58 
59 #include <sys/types.h>
60 #include <sys/param.h>
61 #include <netinet/in.h>
62 #include <arpa/nameser.h>
63 
64 #include <assert.h>
65 #include <ctype.h>
66 #include <errno.h>
67 #include <hesiod.h>
68 #include <resolv.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <unistd.h>
73 
74 #ifdef __weak_alias
75 __weak_alias(hesiod_init,_hesiod_init)
76 __weak_alias(hesiod_end,_hesiod_end)
77 __weak_alias(hesiod_to_bind,_hesiod_to_bind)
78 __weak_alias(hesiod_resolve,_hesiod_resolve)
79 __weak_alias(hesiod_free_list,_hesiod_free_list)
80 __weak_alias(hes_init,_hes_init)
81 __weak_alias(hes_to_bind,_hes_to_bind)
82 __weak_alias(hes_resolve,_hes_resolve)
83 __weak_alias(hes_error,_hes_error)
84 __weak_alias(hes_free,_hes_free)
85 #endif
86 
87 struct hesiod_p {
88 	char	*lhs;			/* normally ".ns" */
89 	char	*rhs;			/* AKA the default hesiod domain */
90 	int	 classes[2];		/* The class search order. */
91 };
92 
93 #define	MAX_HESRESP	1024
94 
95 static int	  read_config_file __P((struct hesiod_p *, const char *));
96 static char	**get_txt_records __P((int, const char *));
97 static int	  init_context __P((void));
98 static void	  translate_errors __P((void));
99 
100 
101 /*
102  * hesiod_init --
103  *	initialize a hesiod_p.
104  */
105 int
106 hesiod_init(context)
107 	void	**context;
108 {
109 	struct hesiod_p	*ctx;
110 	const char	*p, *configname;
111 	int serrno;
112 
113 	_DIAGASSERT(context != NULL);
114 
115 	ctx = malloc(sizeof(struct hesiod_p));
116 	if (ctx) {
117 		*context = ctx;
118 		/*
119 		 * don't permit overrides from environment
120 		 * for set.id programs
121 		 */
122 		if (issetugid())
123 			configname = NULL;
124 		else
125 			configname = getenv("HESIOD_CONFIG");
126 		if (!configname)
127 			configname = _PATH_HESIOD_CONF;
128 		if (read_config_file(ctx, configname) >= 0) {
129 			/*
130 			 * The default rhs can be overridden by an
131 			 * environment variable, unless set.id.
132 			 */
133 			if (issetugid())
134 				p = NULL;
135 			else
136 				p = getenv("HES_DOMAIN");
137 			if (p) {
138 				if (ctx->rhs)
139 					free(ctx->rhs);
140 				ctx->rhs = malloc(strlen(p) + 2);
141 				if (ctx->rhs) {
142 					*ctx->rhs = '.';
143 					strcpy(ctx->rhs + 1,
144 					    (*p == '.') ? p + 1 : p);
145 					return 0;
146 				} else
147 					errno = ENOMEM;
148 			} else
149 				return 0;
150 		}
151 	} else
152 		errno = ENOMEM;
153 
154 	serrno = errno;
155 	if (ctx->lhs)
156 		free(ctx->lhs);
157 	if (ctx->rhs)
158 		free(ctx->rhs);
159 	if (ctx)
160 		free(ctx);
161 	errno = serrno;
162 	return -1;
163 }
164 
165 /*
166  * hesiod_end --
167  *	Deallocates the hesiod_p.
168  */
169 void
170 hesiod_end(context)
171 	void	*context;
172 {
173 	struct hesiod_p *ctx = (struct hesiod_p *) context;
174 
175 	_DIAGASSERT(context != NULL);
176 
177 	free(ctx->rhs);
178 	if (ctx->lhs)
179 		free(ctx->lhs);
180 	free(ctx);
181 }
182 
183 /*
184  * hesiod_to_bind --
185  * 	takes a hesiod (name, type) and returns a DNS
186  *	name which is to be resolved.
187  */
188 char *
189 hesiod_to_bind(void *context, const char *name, const char *type)
190 {
191 	struct hesiod_p *ctx = (struct hesiod_p *) context;
192 	char		 bindname[MAXDNAME], *p, *ret, **rhs_list = NULL;
193 	const char	*rhs;
194 	size_t		 len;
195 
196 	_DIAGASSERT(context != NULL);
197 	_DIAGASSERT(name != NULL);
198 	_DIAGASSERT(type != NULL);
199 
200         if (strlcpy(bindname, name, sizeof(bindname)) >= sizeof(bindname)) {
201                 errno = EMSGSIZE;
202                 return NULL;
203         }
204 
205 	/*
206 	 * Find the right right hand side to use, possibly
207 	 * truncating bindname.
208 	 */
209 	p = strchr(bindname, '@');
210 	if (p) {
211 		*p++ = 0;
212 		if (strchr(p, '.'))
213 			rhs = name + (p - bindname);
214 		else {
215 			rhs_list = hesiod_resolve(context, p, "rhs-extension");
216 			if (rhs_list)
217 				rhs = *rhs_list;
218 			else {
219 				errno = ENOENT;
220 				return NULL;
221 			}
222 		}
223 	} else
224 		rhs = ctx->rhs;
225 
226 	/* See if we have enough room. */
227 	len = strlen(bindname) + 1 + strlen(type);
228 	if (ctx->lhs)
229 		len += strlen(ctx->lhs) + ((ctx->lhs[0] != '.') ? 1 : 0);
230 	len += strlen(rhs) + ((rhs[0] != '.') ? 1 : 0);
231 	if (len > sizeof(bindname) - 1) {
232 		if (rhs_list)
233 			hesiod_free_list(context, rhs_list);
234 		errno = EMSGSIZE;
235 		return NULL;
236 	}
237 	/* Put together the rest of the domain. */
238 	strlcat(bindname, ".", sizeof(bindname));
239 	strlcat(bindname, type, sizeof(bindname));
240 	/* Only append lhs if it isn't empty. */
241 	if (ctx->lhs && ctx->lhs[0] != '\0' ) {
242 		if (ctx->lhs[0] != '.')
243 			strlcat(bindname, ".", sizeof(bindname));
244 		strlcat(bindname, ctx->lhs, sizeof(bindname));
245 	}
246 	if (rhs[0] != '.')
247 		strlcat(bindname, ".", sizeof(bindname));
248 	strlcat(bindname, rhs, sizeof(bindname));
249 
250 	/* rhs_list is no longer needed, since we're done with rhs. */
251 	if (rhs_list)
252 		hesiod_free_list(context, rhs_list);
253 
254 	/* Make a copy of the result and return it to the caller. */
255 	ret = strdup(bindname);
256 	if (ret == NULL)
257 		errno = ENOMEM;
258 	return ret;
259 }
260 
261 /*
262  * hesiod_resolve --
263  *	Given a hesiod name and type, return an array of strings returned
264  *	by the resolver.
265  */
266 char **
267 hesiod_resolve(context, name, type)
268 	void		*context;
269 	const char	*name;
270 	const char	*type;
271 {
272 	struct hesiod_p	*ctx = (struct hesiod_p *) context;
273 	char		*bindname, **retvec;
274 
275 	_DIAGASSERT(context != NULL);
276 	_DIAGASSERT(name != NULL);
277 	_DIAGASSERT(type != NULL);
278 
279 	bindname = hesiod_to_bind(context, name, type);
280 	if (!bindname)
281 		return NULL;
282 
283 	retvec = get_txt_records(ctx->classes[0], bindname);
284 	if (retvec == NULL && errno == ENOENT && ctx->classes[1])
285 		retvec = get_txt_records(ctx->classes[1], bindname);
286 
287 	free(bindname);
288 	return retvec;
289 }
290 
291 /*ARGSUSED*/
292 void
293 hesiod_free_list(context, list)
294 	void	 *context;
295 	char	**list;
296 {
297 	char  **p;
298 
299 	_DIAGASSERT(context != NULL);
300 
301 	if (list == NULL)
302 		return;
303 	for (p = list; *p; p++)
304 		free(*p);
305 	free(list);
306 }
307 
308 
309 /* read_config_file --
310  *	Parse the /etc/hesiod.conf file.  Returns 0 on success,
311  *	-1 on failure.  On failure, it might leave values in ctx->lhs
312  *	or ctx->rhs which need to be freed by the caller.
313  */
314 static int
315 read_config_file(ctx, filename)
316 	struct hesiod_p	*ctx;
317 	const char	*filename;
318 {
319 	char	*key, *data, *p, **which;
320 	char	 buf[MAXDNAME + 7];
321 	int	 n;
322 	FILE	*fp;
323 
324 	_DIAGASSERT(ctx != NULL);
325 	_DIAGASSERT(filename != NULL);
326 
327 	/* Set default query classes. */
328 	ctx->classes[0] = C_IN;
329 	ctx->classes[1] = C_HS;
330 
331 	/* Try to open the configuration file. */
332 	fp = fopen(filename, "r");
333 	if (!fp) {
334 		/* Use compiled in default domain names. */
335 		ctx->lhs = strdup(DEF_LHS);
336 		ctx->rhs = strdup(DEF_RHS);
337 		if (ctx->lhs && ctx->rhs)
338 			return 0;
339 		else {
340 			errno = ENOMEM;
341 			return -1;
342 		}
343 	}
344 	ctx->lhs = NULL;
345 	ctx->rhs = NULL;
346 	while (fgets(buf, sizeof(buf), fp) != NULL) {
347 		p = buf;
348 		if (*p == '#' || *p == '\n' || *p == '\r')
349 			continue;
350 		while (*p == ' ' || *p == '\t')
351 			p++;
352 		key = p;
353 		while (*p != ' ' && *p != '\t' && *p != '=' && *p)
354 			p++;
355 
356 		if (*p == '\0')
357 			continue;
358 
359 		*p++ = 0;
360 
361 		while (isspace((u_char) *p) || *p == '=')
362 			p++;
363 
364 		if (*p == '\0')
365 			continue;
366 
367 		data = p;
368 		while (!isspace((u_char) *p) && *p)
369 			p++;
370 
371 		*p = 0;
372 
373 		if (strcasecmp(key, "lhs") == 0 ||
374 		    strcasecmp(key, "rhs") == 0) {
375 			which = (strcasecmp(key, "lhs") == 0)
376 			    ? &ctx->lhs : &ctx->rhs;
377 			*which = strdup(data);
378 			if (!*which) {
379 				errno = ENOMEM;
380 				return -1;
381 			}
382 		} else {
383 			if (strcasecmp(key, "classes") == 0) {
384 				n = 0;
385 				while (*data && n < 2) {
386 					p = data;
387 					while (*p && *p != ',')
388 						p++;
389 					if (*p)
390 						*p++ = 0;
391 					if (strcasecmp(data, "IN") == 0)
392 						ctx->classes[n++] = C_IN;
393 					else
394 						if (strcasecmp(data, "HS") == 0)
395 							ctx->classes[n++] =
396 							    C_HS;
397 					data = p;
398 				}
399 				while (n < 2)
400 					ctx->classes[n++] = 0;
401 			}
402 		}
403 	}
404 	fclose(fp);
405 
406 	if (!ctx->rhs || ctx->classes[0] == 0 ||
407 	    ctx->classes[0] == ctx->classes[1]) {
408 		errno = ENOEXEC;
409 		return -1;
410 	}
411 	return 0;
412 }
413 
414 /*
415  * get_txt_records --
416  *	Given a DNS class and a DNS name, do a lookup for TXT records, and
417  *	return a list of them.
418  */
419 static char **
420 get_txt_records(qclass, name)
421 	int		 qclass;
422 	const char	*name;
423 {
424 	HEADER		*hp;
425 	unsigned char	 qbuf[PACKETSZ], abuf[MAX_HESRESP], *p, *eom, *eor;
426 	char		*dst, **list;
427 	int		 ancount, qdcount, i, j, n, skip, type, class, len;
428 	res_state	 res = __res_get_state();
429 
430 	if (res == NULL)
431 		return NULL;
432 
433 	_DIAGASSERT(name != NULL);
434 
435 	/* Construct the query. */
436 	n = res_nmkquery(res, QUERY, name, qclass, T_TXT, NULL, 0,
437 	    NULL, qbuf, PACKETSZ);
438 	if (n < 0) {
439 		errno = EMSGSIZE;
440 		__res_put_state(res);
441 		return NULL;
442 	}
443 
444 	/* Send the query. */
445 	n = res_nsend(res, qbuf, n, abuf, MAX_HESRESP);
446 	__res_put_state(res);
447 	if (n < 0) {
448 		errno = ECONNREFUSED;
449 		return NULL;
450 	}
451 	/* Parse the header of the result. */
452 	hp = (HEADER *) (void *) abuf;
453 	ancount = ntohs(hp->ancount);
454 	qdcount = ntohs(hp->qdcount);
455 	p = abuf + sizeof(HEADER);
456 	eom = abuf + n;
457 
458 	/*
459 	 * Skip questions, trying to get to the answer section
460 	 * which follows.
461 	 */
462 	for (i = 0; i < qdcount; i++) {
463 		skip = dn_skipname(p, eom);
464 		if (skip < 0 || p + skip + QFIXEDSZ > eom) {
465 			errno = EMSGSIZE;
466 			return NULL;
467 		}
468 		p += skip + QFIXEDSZ;
469 	}
470 
471 	/* Allocate space for the text record answers. */
472 	list = malloc((ancount + 1) * sizeof(char *));
473 	if (!list) {
474 		errno = ENOMEM;
475 		return NULL;
476 	}
477 	/* Parse the answers. */
478 	j = 0;
479 	for (i = 0; i < ancount; i++) {
480 		/* Parse the header of this answer. */
481 		skip = dn_skipname(p, eom);
482 		if (skip < 0 || p + skip + 10 > eom)
483 			break;
484 		type = p[skip + 0] << 8 | p[skip + 1];
485 		class = p[skip + 2] << 8 | p[skip + 3];
486 		len = p[skip + 8] << 8 | p[skip + 9];
487 		p += skip + 10;
488 		if (p + len > eom) {
489 			errno = EMSGSIZE;
490 			break;
491 		}
492 		/* Skip entries of the wrong class and type. */
493 		if (class != qclass || type != T_TXT) {
494 			p += len;
495 			continue;
496 		}
497 		/* Allocate space for this answer. */
498 		list[j] = malloc((size_t)len);
499 		if (!list[j]) {
500 			errno = ENOMEM;
501 			break;
502 		}
503 		dst = list[j++];
504 
505 		/* Copy answer data into the allocated area. */
506 		eor = p + len;
507 		while (p < eor) {
508 			n = (unsigned char) *p++;
509 			if (p + n > eor) {
510 				errno = EMSGSIZE;
511 				break;
512 			}
513 			memcpy(dst, p, (size_t)n);
514 			p += n;
515 			dst += n;
516 		}
517 		if (p < eor) {
518 			errno = EMSGSIZE;
519 			break;
520 		}
521 		*dst = 0;
522 	}
523 
524 	/*
525 	 * If we didn't terminate the loop normally, something
526 	 * went wrong.
527 	 */
528 	if (i < ancount) {
529 		for (i = 0; i < j; i++)
530 			free(list[i]);
531 		free(list);
532 		return NULL;
533 	}
534 	if (j == 0) {
535 		errno = ENOENT;
536 		free(list);
537 		return NULL;
538 	}
539 	list[j] = NULL;
540 	return list;
541 }
542 
543 /*
544  * COMPATIBILITY FUNCTIONS
545  */
546 
547 static int	  inited = 0;
548 static void	 *context;
549 static int	  errval = HES_ER_UNINIT;
550 
551 int
552 hes_init()
553 {
554 	init_context();
555 	return errval;
556 }
557 
558 char *
559 hes_to_bind(name, type)
560 	const char	*name;
561 	const char	*type;
562 {
563 	static	char	*bindname;
564 
565 	_DIAGASSERT(name != NULL);
566 	_DIAGASSERT(type != NULL);
567 
568 	if (init_context() < 0)
569 		return NULL;
570 	if (bindname)
571 		free(bindname);
572 	bindname = hesiod_to_bind(context, name, type);
573 	if (!bindname)
574 		translate_errors();
575 	return bindname;
576 }
577 
578 char **
579 hes_resolve(name, type)
580 	const char	*name;
581 	const char	*type;
582 {
583 	static char	**list;
584 
585 	_DIAGASSERT(name != NULL);
586 	_DIAGASSERT(type != NULL);
587 
588 	if (init_context() < 0)
589 		return NULL;
590 
591 	/*
592 	 * In the old Hesiod interface, the caller was responsible for
593 	 * freeing the returned strings but not the vector of strings itself.
594 	 */
595 	if (list)
596 		free(list);
597 
598 	list = hesiod_resolve(context, name, type);
599 	if (!list)
600 		translate_errors();
601 	return list;
602 }
603 
604 int
605 hes_error()
606 {
607 	return errval;
608 }
609 
610 void
611 hes_free(hp)
612 	char **hp;
613 {
614 	hesiod_free_list(context, hp);
615 }
616 
617 static int
618 init_context()
619 {
620 	if (!inited) {
621 		inited = 1;
622 		if (hesiod_init(&context) < 0) {
623 			errval = HES_ER_CONFIG;
624 			return -1;
625 		}
626 		errval = HES_ER_OK;
627 	}
628 	return 0;
629 }
630 
631 static void
632 translate_errors()
633 {
634 	switch (errno) {
635 	case ENOENT:
636 		errval = HES_ER_NOTFOUND;
637 		break;
638 	case ECONNREFUSED:
639 	case EMSGSIZE:
640 		errval = HES_ER_NET;
641 		break;
642 	case EFAULT:
643 	case ENOMEM:
644 	default:
645 		/* Not a good match, but the best we can do. */
646 		errval = HES_ER_CONFIG;
647 		break;
648 	}
649 }
650