Home | History | Annotate | Line # | Download | only in net
hesiod.c revision 1.12
      1 /*	$NetBSD: hesiod.c,v 1.12 2000/01/22 22:19:15 mycroft 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 not truly thread-safe at the moment because
     43  * it uses res_send() and accesses _res.
     44  */
     45 
     46 #include <sys/cdefs.h>
     47 
     48 #if defined(LIBC_SCCS) && !defined(lint)
     49 __IDSTRING(rcsid_hesiod_c,
     50     "#Id: hesiod.c,v 1.18.2.1 1997/01/03 20:48:20 ghudson Exp #");
     51 __IDSTRING(rcsid_hesiod_p_h,
     52     "#Id: hesiod_p.h,v 1.1 1996/12/08 21:39:37 ghudson Exp #");
     53 __IDSTRING(rcsid_hescompat_c,
     54     "#Id: hescompat.c,v 1.1.2.1 1996/12/16 08:37:45 ghudson Exp #");
     55 __RCSID("$NetBSD: hesiod.c,v 1.12 2000/01/22 22:19:15 mycroft Exp $");
     56 #endif /* LIBC_SCCS and not lint */
     57 
     58 #include "namespace.h"
     59 
     60 #include <sys/types.h>
     61 #include <sys/param.h>
     62 #include <netinet/in.h>
     63 #include <arpa/nameser.h>
     64 
     65 #include <assert.h>
     66 #include <ctype.h>
     67 #include <errno.h>
     68 #include <hesiod.h>
     69 #include <resolv.h>
     70 #include <stdio.h>
     71 #include <stdlib.h>
     72 #include <string.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 		configname = getenv("HESIOD_CONFIG");
    119 		if (!configname)
    120 			configname = _PATH_HESIOD_CONF;
    121 		if (read_config_file(ctx, configname) >= 0) {
    122 			/*
    123 			 * The default rhs can be overridden by an
    124 			 * environment variable.
    125 			 */
    126 			p = getenv("HES_DOMAIN");
    127 			if (p) {
    128 				if (ctx->rhs)
    129 					free(ctx->rhs);
    130 				ctx->rhs = malloc(strlen(p) + 2);
    131 				if (ctx->rhs) {
    132 					*ctx->rhs = '.';
    133 					strcpy(ctx->rhs + 1,
    134 					    (*p == '.') ? p + 1 : p);
    135 					return 0;
    136 				} else
    137 					errno = ENOMEM;
    138 			} else
    139 				return 0;
    140 		}
    141 	} else
    142 		errno = ENOMEM;
    143 
    144 	serrno = errno;
    145 	if (ctx->lhs)
    146 		free(ctx->lhs);
    147 	if (ctx->rhs)
    148 		free(ctx->rhs);
    149 	if (ctx)
    150 		free(ctx);
    151 	errno = serrno;
    152 	return -1;
    153 }
    154 
    155 /*
    156  * hesiod_end --
    157  *	Deallocates the hesiod_p.
    158  */
    159 void
    160 hesiod_end(context)
    161 	void	*context;
    162 {
    163 	struct hesiod_p *ctx = (struct hesiod_p *) context;
    164 
    165 	_DIAGASSERT(context != NULL);
    166 
    167 	free(ctx->rhs);
    168 	if (ctx->lhs)
    169 		free(ctx->lhs);
    170 	free(ctx);
    171 }
    172 
    173 /*
    174  * hesiod_to_bind --
    175  * 	takes a hesiod (name, type) and returns a DNS
    176  *	name which is to be resolved.
    177  */
    178 char *
    179 hesiod_to_bind(void *context, const char *name, const char *type)
    180 {
    181 	struct hesiod_p *ctx = (struct hesiod_p *) context;
    182 	char		 bindname[MAXDNAME], *p, *ret, **rhs_list = NULL;
    183 	const char	*rhs;
    184 	int		 len;
    185 
    186 	_DIAGASSERT(context != NULL);
    187 	_DIAGASSERT(name != NULL);
    188 	_DIAGASSERT(type != NULL);
    189 
    190 	strcpy(bindname, name);
    191 
    192 		/*
    193 		 * Find the right right hand side to use, possibly
    194 		 * truncating bindname.
    195 		 */
    196 	p = strchr(bindname, '@');
    197 	if (p) {
    198 		*p++ = 0;
    199 		if (strchr(p, '.'))
    200 			rhs = name + (p - bindname);
    201 		else {
    202 			rhs_list = hesiod_resolve(context, p, "rhs-extension");
    203 			if (rhs_list)
    204 				rhs = *rhs_list;
    205 			else {
    206 				errno = ENOENT;
    207 				return NULL;
    208 			}
    209 		}
    210 	} else
    211 		rhs = ctx->rhs;
    212 
    213 		/* See if we have enough room. */
    214 	len = strlen(bindname) + 1 + strlen(type);
    215 	if (ctx->lhs)
    216 		len += strlen(ctx->lhs) + ((ctx->lhs[0] != '.') ? 1 : 0);
    217 	len += strlen(rhs) + ((rhs[0] != '.') ? 1 : 0);
    218 	if (len > sizeof(bindname) - 1) {
    219 		if (rhs_list)
    220 			hesiod_free_list(context, rhs_list);
    221 		errno = EMSGSIZE;
    222 		return NULL;
    223 	}
    224 		/* Put together the rest of the domain. */
    225 	strcat(bindname, ".");
    226 	strcat(bindname, type);
    227 		/* Only append lhs if it isn't empty. */
    228 	if (ctx->lhs && ctx->lhs[0] != '\0' ) {
    229 		if (ctx->lhs[0] != '.')
    230 			strcat(bindname, ".");
    231 		strcat(bindname, ctx->lhs);
    232 	}
    233 	if (rhs[0] != '.')
    234 		strcat(bindname, ".");
    235 	strcat(bindname, rhs);
    236 
    237 		/* rhs_list is no longer needed, since we're done with rhs. */
    238 	if (rhs_list)
    239 		hesiod_free_list(context, rhs_list);
    240 
    241 		/* Make a copy of the result and return it to the caller. */
    242 	ret = strdup(bindname);
    243 	if (!ret)
    244 		errno = ENOMEM;
    245 	return ret;
    246 }
    247 
    248 /*
    249  * hesiod_resolve --
    250  *	Given a hesiod name and type, return an array of strings returned
    251  *	by the resolver.
    252  */
    253 char **
    254 hesiod_resolve(context, name, type)
    255 	void		*context;
    256 	const char	*name;
    257 	const char	*type;
    258 {
    259 	struct hesiod_p	*ctx = (struct hesiod_p *) context;
    260 	char		*bindname, **retvec;
    261 
    262 	_DIAGASSERT(context != NULL);
    263 	_DIAGASSERT(name != NULL);
    264 	_DIAGASSERT(type != NULL);
    265 
    266 	bindname = hesiod_to_bind(context, name, type);
    267 	if (!bindname)
    268 		return NULL;
    269 
    270 	retvec = get_txt_records(ctx->classes[0], bindname);
    271 	if (retvec == NULL && errno == ENOENT && ctx->classes[1])
    272 		retvec = get_txt_records(ctx->classes[1], bindname);
    273 
    274 	free(bindname);
    275 	return retvec;
    276 }
    277 
    278 /*ARGSUSED*/
    279 void
    280 hesiod_free_list(context, list)
    281 	void	 *context;
    282 	char	**list;
    283 {
    284 	char  **p;
    285 
    286 	_DIAGASSERT(context != NULL);
    287 
    288 	if (list == NULL)
    289 		return;
    290 	for (p = list; *p; p++)
    291 		free(*p);
    292 	free(list);
    293 }
    294 
    295 
    296 /* read_config_file --
    297  *	Parse the /etc/hesiod.conf file.  Returns 0 on success,
    298  *	-1 on failure.  On failure, it might leave values in ctx->lhs
    299  *	or ctx->rhs which need to be freed by the caller.
    300  */
    301 static int
    302 read_config_file(ctx, filename)
    303 	struct hesiod_p	*ctx;
    304 	const char	*filename;
    305 {
    306 	char	*key, *data, *p, **which;
    307 	char	 buf[MAXDNAME + 7];
    308 	int	 n;
    309 	FILE	*fp;
    310 
    311 	_DIAGASSERT(ctx != NULL);
    312 	_DIAGASSERT(filename != NULL);
    313 
    314 		/* Set default query classes. */
    315 	ctx->classes[0] = C_IN;
    316 	ctx->classes[1] = C_HS;
    317 
    318 		/* Try to open the configuration file. */
    319 	fp = fopen(filename, "r");
    320 	if (!fp) {
    321 		/* Use compiled in default domain names. */
    322 		ctx->lhs = strdup(DEF_LHS);
    323 		ctx->rhs = strdup(DEF_RHS);
    324 		if (ctx->lhs && ctx->rhs)
    325 			return 0;
    326 		else {
    327 			errno = ENOMEM;
    328 			return -1;
    329 		}
    330 	}
    331 	ctx->lhs = NULL;
    332 	ctx->rhs = NULL;
    333 	while (fgets(buf, sizeof(buf), fp) != NULL) {
    334 		p = buf;
    335 		if (*p == '#' || *p == '\n' || *p == '\r')
    336 			continue;
    337 		while (*p == ' ' || *p == '\t')
    338 			p++;
    339 		key = p;
    340 		while (*p != ' ' && *p != '\t' && *p != '=')
    341 			p++;
    342 		*p++ = 0;
    343 
    344 		while (isspace(*p) || *p == '=')
    345 			p++;
    346 		data = p;
    347 		while (!isspace(*p))
    348 			p++;
    349 		*p = 0;
    350 
    351 		if (strcasecmp(key, "lhs") == 0 ||
    352 		    strcasecmp(key, "rhs") == 0) {
    353 			which = (strcasecmp(key, "lhs") == 0)
    354 			    ? &ctx->lhs : &ctx->rhs;
    355 			*which = strdup(data);
    356 			if (!*which) {
    357 				errno = ENOMEM;
    358 				return -1;
    359 			}
    360 		} else {
    361 			if (strcasecmp(key, "classes") == 0) {
    362 				n = 0;
    363 				while (*data && n < 2) {
    364 					p = data;
    365 					while (*p && *p != ',')
    366 						p++;
    367 					if (*p)
    368 						*p++ = 0;
    369 					if (strcasecmp(data, "IN") == 0)
    370 						ctx->classes[n++] = C_IN;
    371 					else
    372 						if (strcasecmp(data, "HS") == 0)
    373 							ctx->classes[n++] =
    374 							    C_HS;
    375 					data = p;
    376 				}
    377 				while (n < 2)
    378 					ctx->classes[n++] = 0;
    379 			}
    380 		}
    381 	}
    382 	fclose(fp);
    383 
    384 	if (!ctx->rhs || ctx->classes[0] == 0 ||
    385 	    ctx->classes[0] == ctx->classes[1]) {
    386 		errno = ENOEXEC;
    387 		return -1;
    388 	}
    389 	return 0;
    390 }
    391 
    392 /*
    393  * get_txt_records --
    394  *	Given a DNS class and a DNS name, do a lookup for TXT records, and
    395  *	return a list of them.
    396  */
    397 static char **
    398 get_txt_records(qclass, name)
    399 	int		 qclass;
    400 	const char	*name;
    401 {
    402 	HEADER		*hp;
    403 	unsigned char	 qbuf[PACKETSZ], abuf[MAX_HESRESP], *p, *eom, *eor;
    404 	char		*dst, **list;
    405 	int		 ancount, qdcount, i, j, n, skip, type, class, len;
    406 
    407 	_DIAGASSERT(name != NULL);
    408 
    409 		/* Make sure the resolver is initialized. */
    410 	if ((_res.options & RES_INIT) == 0 && res_init() == -1)
    411 		return NULL;
    412 
    413 		/* Construct the query. */
    414 	n = res_mkquery(QUERY, name, qclass, T_TXT, NULL, 0,
    415 	    NULL, qbuf, PACKETSZ);
    416 	if (n < 0)
    417 		return NULL;
    418 
    419 		/* Send the query. */
    420 	n = res_send(qbuf, n, abuf, MAX_HESRESP);
    421 	if (n < 0) {
    422 		errno = ECONNREFUSED;
    423 		return NULL;
    424 	}
    425 		/* Parse the header of the result. */
    426 	hp = (HEADER *) (void *) abuf;
    427 	ancount = ntohs(hp->ancount);
    428 	qdcount = ntohs(hp->qdcount);
    429 	p = abuf + sizeof(HEADER);
    430 	eom = abuf + n;
    431 
    432 		/*
    433 		 * Skip questions, trying to get to the answer section
    434 		 * which follows.
    435 		 */
    436 	for (i = 0; i < qdcount; i++) {
    437 		skip = dn_skipname(p, eom);
    438 		if (skip < 0 || p + skip + QFIXEDSZ > eom) {
    439 			errno = EMSGSIZE;
    440 			return NULL;
    441 		}
    442 		p += skip + QFIXEDSZ;
    443 	}
    444 
    445 		/* Allocate space for the text record answers. */
    446 	list = malloc((ancount + 1) * sizeof(char *));
    447 	if (!list) {
    448 		errno = ENOMEM;
    449 		return NULL;
    450 	}
    451 		/* Parse the answers. */
    452 	j = 0;
    453 	for (i = 0; i < ancount; i++) {
    454 		/* Parse the header of this answer. */
    455 		skip = dn_skipname(p, eom);
    456 		if (skip < 0 || p + skip + 10 > eom)
    457 			break;
    458 		type = p[skip + 0] << 8 | p[skip + 1];
    459 		class = p[skip + 2] << 8 | p[skip + 3];
    460 		len = p[skip + 8] << 8 | p[skip + 9];
    461 		p += skip + 10;
    462 		if (p + len > eom) {
    463 			errno = EMSGSIZE;
    464 			break;
    465 		}
    466 		/* Skip entries of the wrong class and type. */
    467 		if (class != qclass || type != T_TXT) {
    468 			p += len;
    469 			continue;
    470 		}
    471 		/* Allocate space for this answer. */
    472 		list[j] = malloc((size_t)len);
    473 		if (!list[j]) {
    474 			errno = ENOMEM;
    475 			break;
    476 		}
    477 		dst = list[j++];
    478 
    479 		/* Copy answer data into the allocated area. */
    480 		eor = p + len;
    481 		while (p < eor) {
    482 			n = (unsigned char) *p++;
    483 			if (p + n > eor) {
    484 				errno = EMSGSIZE;
    485 				break;
    486 			}
    487 			memcpy(dst, p, (size_t)n);
    488 			p += n;
    489 			dst += n;
    490 		}
    491 		if (p < eor) {
    492 			errno = EMSGSIZE;
    493 			break;
    494 		}
    495 		*dst = 0;
    496 	}
    497 
    498 		/*
    499 		 * If we didn't terminate the loop normally, something
    500 		 * went wrong.
    501 		 */
    502 	if (i < ancount) {
    503 		for (i = 0; i < j; i++)
    504 			free(list[i]);
    505 		free(list);
    506 		return NULL;
    507 	}
    508 	if (j == 0) {
    509 		errno = ENOENT;
    510 		free(list);
    511 		return NULL;
    512 	}
    513 	list[j] = NULL;
    514 	return list;
    515 }
    516 
    517 		/*
    518 		 *	COMPATIBILITY FUNCTIONS
    519 		 */
    520 
    521 static int	  inited = 0;
    522 static void	 *context;
    523 static int	  errval = HES_ER_UNINIT;
    524 
    525 int
    526 hes_init()
    527 {
    528 	init_context();
    529 	return errval;
    530 }
    531 
    532 char *
    533 hes_to_bind(name, type)
    534 	const char	*name;
    535 	const char	*type;
    536 {
    537 	static	char	*bindname;
    538 
    539 	_DIAGASSERT(name != NULL);
    540 	_DIAGASSERT(type != NULL);
    541 
    542 	if (init_context() < 0)
    543 		return NULL;
    544 	if (bindname)
    545 		free(bindname);
    546 	bindname = hesiod_to_bind(context, name, type);
    547 	if (!bindname)
    548 		translate_errors();
    549 	return bindname;
    550 }
    551 
    552 char **
    553 hes_resolve(name, type)
    554 	const char	*name;
    555 	const char	*type;
    556 {
    557 	static char	**list;
    558 
    559 	_DIAGASSERT(name != NULL);
    560 	_DIAGASSERT(type != NULL);
    561 
    562 	if (init_context() < 0)
    563 		return NULL;
    564 
    565 	/*
    566 	 * In the old Hesiod interface, the caller was responsible for
    567 	 * freeing the returned strings but not the vector of strings itself.
    568 	 */
    569 	if (list)
    570 		free(list);
    571 
    572 	list = hesiod_resolve(context, name, type);
    573 	if (!list)
    574 		translate_errors();
    575 	return list;
    576 }
    577 
    578 int
    579 hes_error()
    580 {
    581 	return errval;
    582 }
    583 
    584 void
    585 hes_free(hp)
    586 	char **hp;
    587 {
    588 	hesiod_free_list(context, hp);
    589 }
    590 
    591 static int
    592 init_context()
    593 {
    594 	if (!inited) {
    595 		inited = 1;
    596 		if (hesiod_init(&context) < 0) {
    597 			errval = HES_ER_CONFIG;
    598 			return -1;
    599 		}
    600 		errval = HES_ER_OK;
    601 	}
    602 	return 0;
    603 }
    604 
    605 static void
    606 translate_errors()
    607 {
    608 	switch (errno) {
    609 	case ENOENT:
    610 		errval = HES_ER_NOTFOUND;
    611 		break;
    612 	case ECONNREFUSED:
    613 	case EMSGSIZE:
    614 		errval = HES_ER_NET;
    615 		break;
    616 	case EFAULT:
    617 	case ENOMEM:
    618 	default:
    619 		/* Not a good match, but the best we can do. */
    620 		errval = HES_ER_CONFIG;
    621 		break;
    622 	}
    623 }
    624