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