Home | History | Annotate | Line # | Download | only in net
hesiod.c revision 1.21
      1 /*	$NetBSD: hesiod.c,v 1.21 2004/05/21 02:30:03 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.21 2004/05/21 02:30:03 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 	_DIAGASSERT(name != NULL);
    431 
    432 	/* Make sure the resolver is initialized. */
    433 	if ((res->options & RES_INIT) == 0 && res_ninit(res) == -1) {
    434 		__res_put_state(res);
    435 		return NULL;
    436 	}
    437 
    438 	/* Construct the query. */
    439 	n = res_nmkquery(res, QUERY, name, qclass, T_TXT, NULL, 0,
    440 	    NULL, qbuf, PACKETSZ);
    441 	if (n < 0) {
    442 		errno = EMSGSIZE;
    443 		__res_put_state(res);
    444 		return NULL;
    445 	}
    446 
    447 	/* Send the query. */
    448 	n = res_nsend(res, qbuf, n, abuf, MAX_HESRESP);
    449 	__res_put_state(res);
    450 	if (n < 0) {
    451 		errno = ECONNREFUSED;
    452 		return NULL;
    453 	}
    454 	/* Parse the header of the result. */
    455 	hp = (HEADER *) (void *) abuf;
    456 	ancount = ntohs(hp->ancount);
    457 	qdcount = ntohs(hp->qdcount);
    458 	p = abuf + sizeof(HEADER);
    459 	eom = abuf + n;
    460 
    461 	/*
    462 	 * Skip questions, trying to get to the answer section
    463 	 * which follows.
    464 	 */
    465 	for (i = 0; i < qdcount; i++) {
    466 		skip = dn_skipname(p, eom);
    467 		if (skip < 0 || p + skip + QFIXEDSZ > eom) {
    468 			errno = EMSGSIZE;
    469 			return NULL;
    470 		}
    471 		p += skip + QFIXEDSZ;
    472 	}
    473 
    474 	/* Allocate space for the text record answers. */
    475 	list = malloc((ancount + 1) * sizeof(char *));
    476 	if (!list) {
    477 		errno = ENOMEM;
    478 		return NULL;
    479 	}
    480 	/* Parse the answers. */
    481 	j = 0;
    482 	for (i = 0; i < ancount; i++) {
    483 		/* Parse the header of this answer. */
    484 		skip = dn_skipname(p, eom);
    485 		if (skip < 0 || p + skip + 10 > eom)
    486 			break;
    487 		type = p[skip + 0] << 8 | p[skip + 1];
    488 		class = p[skip + 2] << 8 | p[skip + 3];
    489 		len = p[skip + 8] << 8 | p[skip + 9];
    490 		p += skip + 10;
    491 		if (p + len > eom) {
    492 			errno = EMSGSIZE;
    493 			break;
    494 		}
    495 		/* Skip entries of the wrong class and type. */
    496 		if (class != qclass || type != T_TXT) {
    497 			p += len;
    498 			continue;
    499 		}
    500 		/* Allocate space for this answer. */
    501 		list[j] = malloc((size_t)len);
    502 		if (!list[j]) {
    503 			errno = ENOMEM;
    504 			break;
    505 		}
    506 		dst = list[j++];
    507 
    508 		/* Copy answer data into the allocated area. */
    509 		eor = p + len;
    510 		while (p < eor) {
    511 			n = (unsigned char) *p++;
    512 			if (p + n > eor) {
    513 				errno = EMSGSIZE;
    514 				break;
    515 			}
    516 			memcpy(dst, p, (size_t)n);
    517 			p += n;
    518 			dst += n;
    519 		}
    520 		if (p < eor) {
    521 			errno = EMSGSIZE;
    522 			break;
    523 		}
    524 		*dst = 0;
    525 	}
    526 
    527 	/*
    528 	 * If we didn't terminate the loop normally, something
    529 	 * went wrong.
    530 	 */
    531 	if (i < ancount) {
    532 		for (i = 0; i < j; i++)
    533 			free(list[i]);
    534 		free(list);
    535 		return NULL;
    536 	}
    537 	if (j == 0) {
    538 		errno = ENOENT;
    539 		free(list);
    540 		return NULL;
    541 	}
    542 	list[j] = NULL;
    543 	return list;
    544 }
    545 
    546 /*
    547  * COMPATIBILITY FUNCTIONS
    548  */
    549 
    550 static int	  inited = 0;
    551 static void	 *context;
    552 static int	  errval = HES_ER_UNINIT;
    553 
    554 int
    555 hes_init()
    556 {
    557 	init_context();
    558 	return errval;
    559 }
    560 
    561 char *
    562 hes_to_bind(name, type)
    563 	const char	*name;
    564 	const char	*type;
    565 {
    566 	static	char	*bindname;
    567 
    568 	_DIAGASSERT(name != NULL);
    569 	_DIAGASSERT(type != NULL);
    570 
    571 	if (init_context() < 0)
    572 		return NULL;
    573 	if (bindname)
    574 		free(bindname);
    575 	bindname = hesiod_to_bind(context, name, type);
    576 	if (!bindname)
    577 		translate_errors();
    578 	return bindname;
    579 }
    580 
    581 char **
    582 hes_resolve(name, type)
    583 	const char	*name;
    584 	const char	*type;
    585 {
    586 	static char	**list;
    587 
    588 	_DIAGASSERT(name != NULL);
    589 	_DIAGASSERT(type != NULL);
    590 
    591 	if (init_context() < 0)
    592 		return NULL;
    593 
    594 	/*
    595 	 * In the old Hesiod interface, the caller was responsible for
    596 	 * freeing the returned strings but not the vector of strings itself.
    597 	 */
    598 	if (list)
    599 		free(list);
    600 
    601 	list = hesiod_resolve(context, name, type);
    602 	if (!list)
    603 		translate_errors();
    604 	return list;
    605 }
    606 
    607 int
    608 hes_error()
    609 {
    610 	return errval;
    611 }
    612 
    613 void
    614 hes_free(hp)
    615 	char **hp;
    616 {
    617 	hesiod_free_list(context, hp);
    618 }
    619 
    620 static int
    621 init_context()
    622 {
    623 	if (!inited) {
    624 		inited = 1;
    625 		if (hesiod_init(&context) < 0) {
    626 			errval = HES_ER_CONFIG;
    627 			return -1;
    628 		}
    629 		errval = HES_ER_OK;
    630 	}
    631 	return 0;
    632 }
    633 
    634 static void
    635 translate_errors()
    636 {
    637 	switch (errno) {
    638 	case ENOENT:
    639 		errval = HES_ER_NOTFOUND;
    640 		break;
    641 	case ECONNREFUSED:
    642 	case EMSGSIZE:
    643 		errval = HES_ER_NET;
    644 		break;
    645 	case EFAULT:
    646 	case ENOMEM:
    647 	default:
    648 		/* Not a good match, but the best we can do. */
    649 		errval = HES_ER_CONFIG;
    650 		break;
    651 	}
    652 }
    653