xref: /minix3/lib/libc/net/hesiod.c (revision ef01931f760fe8114e6dd99a6864c92b3a85ae12)
1 /*	$NetBSD: hesiod.c,v 1.25 2011/01/05 00:09:43 wiz 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.25 2011/01/05 00:09:43 wiz 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 = calloc(1, 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) {
156 		if (ctx->lhs)
157 			free(ctx->lhs);
158 		if (ctx->rhs)
159 			free(ctx->rhs);
160 		free(ctx);
161 	}
162 	errno = serrno;
163 	return -1;
164 }
165 
166 /*
167  * hesiod_end --
168  *	Deallocates the hesiod_p.
169  */
170 void
171 hesiod_end(context)
172 	void	*context;
173 {
174 	struct hesiod_p *ctx = (struct hesiod_p *) context;
175 
176 	_DIAGASSERT(context != NULL);
177 
178 	free(ctx->rhs);
179 	if (ctx->lhs)
180 		free(ctx->lhs);
181 	free(ctx);
182 }
183 
184 /*
185  * hesiod_to_bind --
186  * 	takes a hesiod (name, type) and returns a DNS
187  *	name which is to be resolved.
188  */
189 char *
190 hesiod_to_bind(void *context, const char *name, const char *type)
191 {
192 	struct hesiod_p *ctx = (struct hesiod_p *) context;
193 	char		 bindname[MAXDNAME], *p, *ret, **rhs_list = NULL;
194 	const char	*rhs;
195 	size_t		 len;
196 
197 	_DIAGASSERT(context != NULL);
198 	_DIAGASSERT(name != NULL);
199 	_DIAGASSERT(type != NULL);
200 
201         if (strlcpy(bindname, name, sizeof(bindname)) >= sizeof(bindname)) {
202                 errno = EMSGSIZE;
203                 return NULL;
204         }
205 
206 	/*
207 	 * Find the right right hand side to use, possibly
208 	 * truncating bindname.
209 	 */
210 	p = strchr(bindname, '@');
211 	if (p) {
212 		*p++ = 0;
213 		if (strchr(p, '.'))
214 			rhs = name + (p - bindname);
215 		else {
216 			rhs_list = hesiod_resolve(context, p, "rhs-extension");
217 			if (rhs_list)
218 				rhs = *rhs_list;
219 			else {
220 				errno = ENOENT;
221 				return NULL;
222 			}
223 		}
224 	} else
225 		rhs = ctx->rhs;
226 
227 	/* See if we have enough room. */
228 	len = strlen(bindname) + 1 + strlen(type);
229 	if (ctx->lhs)
230 		len += strlen(ctx->lhs) + ((ctx->lhs[0] != '.') ? 1 : 0);
231 	len += strlen(rhs) + ((rhs[0] != '.') ? 1 : 0);
232 	if (len > sizeof(bindname) - 1) {
233 		if (rhs_list)
234 			hesiod_free_list(context, rhs_list);
235 		errno = EMSGSIZE;
236 		return NULL;
237 	}
238 	/* Put together the rest of the domain. */
239 	strlcat(bindname, ".", sizeof(bindname));
240 	strlcat(bindname, type, sizeof(bindname));
241 	/* Only append lhs if it isn't empty. */
242 	if (ctx->lhs && ctx->lhs[0] != '\0' ) {
243 		if (ctx->lhs[0] != '.')
244 			strlcat(bindname, ".", sizeof(bindname));
245 		strlcat(bindname, ctx->lhs, sizeof(bindname));
246 	}
247 	if (rhs[0] != '.')
248 		strlcat(bindname, ".", sizeof(bindname));
249 	strlcat(bindname, rhs, sizeof(bindname));
250 
251 	/* rhs_list is no longer needed, since we're done with rhs. */
252 	if (rhs_list)
253 		hesiod_free_list(context, rhs_list);
254 
255 	/* Make a copy of the result and return it to the caller. */
256 	ret = strdup(bindname);
257 	if (ret == NULL)
258 		errno = ENOMEM;
259 	return ret;
260 }
261 
262 /*
263  * hesiod_resolve --
264  *	Given a hesiod name and type, return an array of strings returned
265  *	by the resolver.
266  */
267 char **
268 hesiod_resolve(context, name, type)
269 	void		*context;
270 	const char	*name;
271 	const char	*type;
272 {
273 	struct hesiod_p	*ctx = (struct hesiod_p *) context;
274 	char		*bindname, **retvec;
275 
276 	_DIAGASSERT(context != NULL);
277 	_DIAGASSERT(name != NULL);
278 	_DIAGASSERT(type != NULL);
279 
280 	bindname = hesiod_to_bind(context, name, type);
281 	if (!bindname)
282 		return NULL;
283 
284 	retvec = get_txt_records(ctx->classes[0], bindname);
285 	if (retvec == NULL && errno == ENOENT && ctx->classes[1])
286 		retvec = get_txt_records(ctx->classes[1], bindname);
287 
288 	free(bindname);
289 	return retvec;
290 }
291 
292 /*ARGSUSED*/
293 void
294 hesiod_free_list(context, list)
295 	void	 *context;
296 	char	**list;
297 {
298 	char  **p;
299 
300 	_DIAGASSERT(context != NULL);
301 
302 	if (list == NULL)
303 		return;
304 	for (p = list; *p; p++)
305 		free(*p);
306 	free(list);
307 }
308 
309 
310 /* read_config_file --
311  *	Parse the /etc/hesiod.conf file.  Returns 0 on success,
312  *	-1 on failure.  On failure, it might leave values in ctx->lhs
313  *	or ctx->rhs which need to be freed by the caller.
314  */
315 static int
316 read_config_file(ctx, filename)
317 	struct hesiod_p	*ctx;
318 	const char	*filename;
319 {
320 	char	*key, *data, *p, **which;
321 	char	 buf[MAXDNAME + 7];
322 	int	 n;
323 	FILE	*fp;
324 
325 	_DIAGASSERT(ctx != NULL);
326 	_DIAGASSERT(filename != NULL);
327 
328 	/* Set default query classes. */
329 	ctx->classes[0] = C_IN;
330 	ctx->classes[1] = C_HS;
331 
332 	/* Try to open the configuration file. */
333 	fp = fopen(filename, "r");
334 	if (!fp) {
335 		/* Use compiled in default domain names. */
336 		ctx->lhs = strdup(DEF_LHS);
337 		ctx->rhs = strdup(DEF_RHS);
338 		if (ctx->lhs && ctx->rhs)
339 			return 0;
340 		else {
341 			errno = ENOMEM;
342 			return -1;
343 		}
344 	}
345 	ctx->lhs = NULL;
346 	ctx->rhs = NULL;
347 	while (fgets(buf, sizeof(buf), fp) != NULL) {
348 		p = buf;
349 		if (*p == '#' || *p == '\n' || *p == '\r')
350 			continue;
351 		while (*p == ' ' || *p == '\t')
352 			p++;
353 		key = p;
354 		while (*p != ' ' && *p != '\t' && *p != '=' && *p)
355 			p++;
356 
357 		if (*p == '\0')
358 			continue;
359 
360 		*p++ = 0;
361 
362 		while (isspace((u_char) *p) || *p == '=')
363 			p++;
364 
365 		if (*p == '\0')
366 			continue;
367 
368 		data = p;
369 		while (!isspace((u_char) *p) && *p)
370 			p++;
371 
372 		*p = 0;
373 
374 		if (strcasecmp(key, "lhs") == 0 ||
375 		    strcasecmp(key, "rhs") == 0) {
376 			which = (strcasecmp(key, "lhs") == 0)
377 			    ? &ctx->lhs : &ctx->rhs;
378 			*which = strdup(data);
379 			if (!*which) {
380 				errno = ENOMEM;
381 				(void)fclose(fp);
382 				return -1;
383 			}
384 		} else {
385 			if (strcasecmp(key, "classes") == 0) {
386 				n = 0;
387 				while (*data && n < 2) {
388 					p = data;
389 					while (*p && *p != ',')
390 						p++;
391 					if (*p)
392 						*p++ = 0;
393 					if (strcasecmp(data, "IN") == 0)
394 						ctx->classes[n++] = C_IN;
395 					else
396 						if (strcasecmp(data, "HS") == 0)
397 							ctx->classes[n++] =
398 							    C_HS;
399 					data = p;
400 				}
401 				while (n < 2)
402 					ctx->classes[n++] = 0;
403 			}
404 		}
405 	}
406 	fclose(fp);
407 
408 	if (!ctx->rhs || ctx->classes[0] == 0 ||
409 	    ctx->classes[0] == ctx->classes[1]) {
410 		errno = ENOEXEC;
411 		return -1;
412 	}
413 	return 0;
414 }
415 
416 /*
417  * get_txt_records --
418  *	Given a DNS class and a DNS name, do a lookup for TXT records, and
419  *	return a list of them.
420  */
421 static char **
422 get_txt_records(qclass, name)
423 	int		 qclass;
424 	const char	*name;
425 {
426 	HEADER		*hp;
427 	unsigned char	 qbuf[PACKETSZ], abuf[MAX_HESRESP], *p, *eom, *eor;
428 	char		*dst, **list;
429 	int		 ancount, qdcount, i, j, n, skip, type, class, len;
430 	res_state	 res = __res_get_state();
431 
432 	if (res == NULL)
433 		return NULL;
434 
435 	_DIAGASSERT(name != NULL);
436 
437 	/* Construct the query. */
438 	n = res_nmkquery(res, QUERY, name, qclass, T_TXT, NULL, 0,
439 	    NULL, qbuf, PACKETSZ);
440 	if (n < 0) {
441 		errno = EMSGSIZE;
442 		__res_put_state(res);
443 		return NULL;
444 	}
445 
446 	/* Send the query. */
447 	n = res_nsend(res, qbuf, n, abuf, MAX_HESRESP);
448 	__res_put_state(res);
449 	if (n < 0) {
450 		errno = ECONNREFUSED;
451 		return NULL;
452 	}
453 	/* Parse the header of the result. */
454 	hp = (HEADER *) (void *) abuf;
455 	ancount = ntohs(hp->ancount);
456 	qdcount = ntohs(hp->qdcount);
457 	p = abuf + sizeof(HEADER);
458 	eom = abuf + n;
459 
460 	/*
461 	 * Skip questions, trying to get to the answer section
462 	 * which follows.
463 	 */
464 	for (i = 0; i < qdcount; i++) {
465 		skip = dn_skipname(p, eom);
466 		if (skip < 0 || p + skip + QFIXEDSZ > eom) {
467 			errno = EMSGSIZE;
468 			return NULL;
469 		}
470 		p += skip + QFIXEDSZ;
471 	}
472 
473 	/* Allocate space for the text record answers. */
474 	list = malloc((ancount + 1) * sizeof(char *));
475 	if (!list) {
476 		errno = ENOMEM;
477 		return NULL;
478 	}
479 	/* Parse the answers. */
480 	j = 0;
481 	for (i = 0; i < ancount; i++) {
482 		/* Parse the header of this answer. */
483 		skip = dn_skipname(p, eom);
484 		if (skip < 0 || p + skip + 10 > eom)
485 			break;
486 		type = p[skip + 0] << 8 | p[skip + 1];
487 		class = p[skip + 2] << 8 | p[skip + 3];
488 		len = p[skip + 8] << 8 | p[skip + 9];
489 		p += skip + 10;
490 		if (p + len > eom) {
491 			errno = EMSGSIZE;
492 			break;
493 		}
494 		/* Skip entries of the wrong class and type. */
495 		if (class != qclass || type != T_TXT) {
496 			p += len;
497 			continue;
498 		}
499 		/* Allocate space for this answer. */
500 		list[j] = malloc((size_t)len);
501 		if (!list[j]) {
502 			errno = ENOMEM;
503 			break;
504 		}
505 		dst = list[j++];
506 
507 		/* Copy answer data into the allocated area. */
508 		eor = p + len;
509 		while (p < eor) {
510 			n = (unsigned char) *p++;
511 			if (p + n > eor) {
512 				errno = EMSGSIZE;
513 				break;
514 			}
515 			memcpy(dst, p, (size_t)n);
516 			p += n;
517 			dst += n;
518 		}
519 		if (p < eor) {
520 			errno = EMSGSIZE;
521 			break;
522 		}
523 		*dst = 0;
524 	}
525 
526 	/*
527 	 * If we didn't terminate the loop normally, something
528 	 * went wrong.
529 	 */
530 	if (i < ancount) {
531 		for (i = 0; i < j; i++)
532 			free(list[i]);
533 		free(list);
534 		return NULL;
535 	}
536 	if (j == 0) {
537 		errno = ENOENT;
538 		free(list);
539 		return NULL;
540 	}
541 	list[j] = NULL;
542 	return list;
543 }
544 
545 /*
546  * COMPATIBILITY FUNCTIONS
547  */
548 
549 static int	  inited = 0;
550 static void	 *context;
551 static int	  errval = HES_ER_UNINIT;
552 
553 int
554 hes_init()
555 {
556 	init_context();
557 	return errval;
558 }
559 
560 char *
561 hes_to_bind(name, type)
562 	const char	*name;
563 	const char	*type;
564 {
565 	static	char	*bindname;
566 
567 	_DIAGASSERT(name != NULL);
568 	_DIAGASSERT(type != NULL);
569 
570 	if (init_context() < 0)
571 		return NULL;
572 	if (bindname)
573 		free(bindname);
574 	bindname = hesiod_to_bind(context, name, type);
575 	if (!bindname)
576 		translate_errors();
577 	return bindname;
578 }
579 
580 char **
581 hes_resolve(name, type)
582 	const char	*name;
583 	const char	*type;
584 {
585 	static char	**list;
586 
587 	_DIAGASSERT(name != NULL);
588 	_DIAGASSERT(type != NULL);
589 
590 	if (init_context() < 0)
591 		return NULL;
592 
593 	/*
594 	 * In the old Hesiod interface, the caller was responsible for
595 	 * freeing the returned strings but not the vector of strings itself.
596 	 */
597 	if (list)
598 		free(list);
599 
600 	list = hesiod_resolve(context, name, type);
601 	if (!list)
602 		translate_errors();
603 	return list;
604 }
605 
606 int
607 hes_error()
608 {
609 	return errval;
610 }
611 
612 void
613 hes_free(hp)
614 	char **hp;
615 {
616 	hesiod_free_list(context, hp);
617 }
618 
619 static int
620 init_context()
621 {
622 	if (!inited) {
623 		inited = 1;
624 		if (hesiod_init(&context) < 0) {
625 			errval = HES_ER_CONFIG;
626 			return -1;
627 		}
628 		errval = HES_ER_OK;
629 	}
630 	return 0;
631 }
632 
633 static void
634 translate_errors()
635 {
636 	switch (errno) {
637 	case ENOENT:
638 		errval = HES_ER_NOTFOUND;
639 		break;
640 	case ECONNREFUSED:
641 	case EMSGSIZE:
642 		errval = HES_ER_NET;
643 		break;
644 	default:
645 		/* Not a good match, but the best we can do. */
646 		errval = HES_ER_CONFIG;
647 		break;
648 	}
649 }
650