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