1/*	$NetBSD: res_query.c,v 1.17 2023/08/01 08:47:25 mrg Exp $	*/
2
3/*
4 * Portions Copyright (C) 2004, 2005, 2008  Internet Systems Consortium, Inc. ("ISC")
5 * Portions Copyright (C) 1996-2001, 2003  Internet Software Consortium.
6 *
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
12 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
14 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
16 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17 * PERFORMANCE OF THIS SOFTWARE.
18 */
19
20/*
21 * Copyright (c) 1988, 1993
22 *    The Regents of the University of California.  All rights reserved.
23 *
24 * Redistribution and use in source and binary forms, with or without
25 * modification, are permitted provided that the following conditions
26 * are met:
27 * 1. Redistributions of source code must retain the above copyright
28 *    notice, this list of conditions and the following disclaimer.
29 * 2. Redistributions in binary form must reproduce the above copyright
30 *    notice, this list of conditions and the following disclaimer in the
31 *    documentation and/or other materials provided with the distribution.
32 * 3. Neither the name of the University nor the names of its contributors
33 *    may be used to endorse or promote products derived from this software
34 *    without specific prior written permission.
35 *
36 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
37 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
39 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
40 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
41 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
42 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
44 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
45 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46 * SUCH DAMAGE.
47 */
48
49/*
50 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
51 *
52 * Permission to use, copy, modify, and distribute this software for any
53 * purpose with or without fee is hereby granted, provided that the above
54 * copyright notice and this permission notice appear in all copies, and that
55 * the name of Digital Equipment Corporation not be used in advertising or
56 * publicity pertaining to distribution of the document or software without
57 * specific, written prior permission.
58 *
59 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
60 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
61 * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
62 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
63 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
64 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
65 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
66 * SOFTWARE.
67 */
68
69/*
70 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
71 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
72 *
73 * Permission to use, copy, modify, and distribute this software for any
74 * purpose with or without fee is hereby granted, provided that the above
75 * copyright notice and this permission notice appear in all copies.
76 *
77 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
78 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
79 * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
80 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
81 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
82 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
83 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
84 */
85
86#include <sys/cdefs.h>
87#if defined(LIBC_SCCS) && !defined(lint)
88#ifdef notdef
89static const char sccsid[] = "@(#)res_query.c	8.1 (Berkeley) 6/4/93";
90static const char rcsid[] = "Id: res_query.c,v 1.11 2008/11/14 02:36:51 marka Exp";
91#else
92__RCSID("$NetBSD: res_query.c,v 1.17 2023/08/01 08:47:25 mrg Exp $");
93#endif
94#endif /* LIBC_SCCS and not lint */
95
96#include "port_before.h"
97
98#include "namespace.h"
99#include <sys/types.h>
100#include <sys/param.h>
101#include <netinet/in.h>
102#include <arpa/inet.h>
103#include <arpa/nameser.h>
104#include <ctype.h>
105#include <errno.h>
106#include <netdb.h>
107#include <resolv.h>
108#include <stdio.h>
109#include <stdlib.h>
110#include <unistd.h>
111#include <string.h>
112#include "port_after.h"
113
114#if 0
115#ifdef __weak_alias
116__weak_alias(res_nquery,_res_nquery)
117__weak_alias(res_nsearch,_res_nsearch)
118__weak_alias(res_nquerydomain,__res_nquerydomain)
119__weak_alias(res_hostalias,__res_hostalias)
120#endif
121#endif
122
123/* Options.  Leave them on. */
124#ifndef DEBUG
125#define DEBUG
126#endif
127
128#if PACKETSZ > 1024
129#define MAXPACKET	PACKETSZ
130#else
131#define MAXPACKET	1024
132#endif
133
134/*%
135 * Formulate a normal query, send, and await answer.
136 * Returned answer is placed in supplied buffer "answer".
137 * Perform preliminary check of answer, returning success only
138 * if no error is indicated and the answer count is nonzero.
139 * Return the size of the response on success, -1 on error.
140 * Error number is left in H_ERRNO.
141 *
142 * Caller must parse answer and determine whether it answers the question.
143 */
144int
145res_nquery(res_state statp,
146	   const char *name,	/*%< domain name */
147	   int class, int type,	/*%< class and type of query */
148	   u_char *answer,	/*%< buffer to put answer */
149	   int anslen)		/*%< size of answer buffer */
150{
151	u_char buf[MAXPACKET];
152	HEADER *hp = (HEADER *)(void *)answer;
153	u_int oflags;
154	u_char *rdata;
155	int n;
156
157	oflags = statp->_flags;
158
159again:
160	hp->rcode = NOERROR;	/*%< default */
161#ifdef DEBUG
162	if (statp->options & RES_DEBUG)
163		printf(";; res_query(%s, %d, %d)\n", name, class, type);
164#endif
165
166	n = res_nmkquery(statp, QUERY, name, class, type, NULL, 0, NULL,
167			 buf, (int)sizeof(buf));
168#ifdef RES_USE_EDNS0
169	if (n > 0 && (statp->_flags & RES_F_EDNS0ERR) == 0 &&
170	    (statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC|RES_NSID)) != 0U) {
171		n = res_nopt(statp, n, buf, (int)sizeof(buf), anslen);
172		rdata = &buf[n];
173		if (n > 0 && (statp->options & RES_NSID) != 0U) {
174			n = res_nopt_rdata(statp, n, buf, (int)sizeof(buf),
175			    rdata, NS_OPT_NSID, 0, NULL);
176		}
177	}
178#endif
179	if (n <= 0) {
180#ifdef DEBUG
181		if (statp->options & RES_DEBUG)
182			printf(";; res_query: mkquery failed\n");
183#endif
184		RES_SET_H_ERRNO(statp, NO_RECOVERY);
185		return (n);
186	}
187
188	n = res_nsend(statp, buf, n, answer, anslen);
189	if (n < 0) {
190#ifdef RES_USE_EDNS0
191		/* if the query choked with EDNS0, retry without EDNS0 */
192		if ((statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U &&
193		    ((oflags ^ statp->_flags) & RES_F_EDNS0ERR) != 0) {
194			statp->_flags |= RES_F_EDNS0ERR;
195			if (statp->options & RES_DEBUG)
196				printf(";; res_nquery: retry without EDNS0\n");
197			goto again;
198		}
199#endif
200#ifdef DEBUG
201		if (statp->options & RES_DEBUG)
202			printf(";; res_query: send error\n");
203#endif
204		RES_SET_H_ERRNO(statp, TRY_AGAIN);
205		return (n);
206	}
207
208	if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
209#ifdef DEBUG
210		if (statp->options & RES_DEBUG)
211			printf(";; rcode = (%s), counts = an:%d ns:%d ar:%d\n",
212			       p_rcode(hp->rcode),
213			       ntohs(hp->ancount),
214			       ntohs(hp->nscount),
215			       ntohs(hp->arcount));
216#endif
217		switch (hp->rcode) {
218		case NXDOMAIN:
219			RES_SET_H_ERRNO(statp, HOST_NOT_FOUND);
220			break;
221		case SERVFAIL:
222			RES_SET_H_ERRNO(statp, TRY_AGAIN);
223			break;
224		case NOERROR:
225			RES_SET_H_ERRNO(statp, NO_DATA);
226			break;
227		case FORMERR:
228		case NOTIMP:
229		case REFUSED:
230		default:
231			RES_SET_H_ERRNO(statp, NO_RECOVERY);
232			break;
233		}
234		return (-1);
235	}
236	return (n);
237}
238
239/*%
240 * Formulate a normal query, send, and retrieve answer in supplied buffer.
241 * Return the size of the response on success, -1 on error.
242 * If enabled, implement search rules until answer or unrecoverable failure
243 * is detected.  Error code, if any, is left in H_ERRNO.
244 */
245int
246res_nsearch(res_state statp,
247	    const char *name,	/*%< domain name */
248	    int class, int type,	/*%< class and type of query */
249	    u_char *answer,	/*%< buffer to put answer */
250	    int anslen)		/*%< size of answer */
251{
252	const char *cp, * const *domain;
253	HEADER *hp = (HEADER *)(void *)answer;
254	char tmp[NS_MAXDNAME];
255	u_int dots;
256	int trailing_dot, ret, saved_herrno;
257	int got_nodata = 0, got_servfail = 0, root_on_list = 0;
258	int tried_as_is = 0;
259	int searched = 0;
260
261	errno = 0;
262	RES_SET_H_ERRNO(statp, HOST_NOT_FOUND);  /*%< True if we never query. */
263	dots = 0;
264	for (cp = name; *cp != '\0'; cp++)
265		dots += (*cp == '.');
266	trailing_dot = 0;
267	if (cp > name && *--cp == '.')
268		trailing_dot++;
269
270	/* If there aren't any dots, it could be a user-level alias. */
271	if (!dots && (cp = res_hostalias(statp, name, tmp, sizeof tmp))!= NULL)
272		return (res_nquery(statp, cp, class, type, answer, anslen));
273
274	/*
275	 * If there are enough dots in the name, let's just give it a
276	 * try 'as is'. The threshold can be set with the "ndots" option.
277	 * Also, query 'as is', if there is a trailing dot in the name.
278	 */
279	saved_herrno = -1;
280	if (dots >= statp->ndots || trailing_dot) {
281		ret = res_nquerydomain(statp, name, NULL, class, type,
282					 answer, anslen);
283		if (ret > 0 || trailing_dot)
284			return (ret);
285		saved_herrno = statp->res_h_errno;
286		tried_as_is++;
287	}
288
289	/*
290	 * We do at least one level of search if
291	 *	- there is no dot and RES_DEFNAME is set, or
292	 *	- there is at least one dot, there is no trailing dot,
293	 *	  and RES_DNSRCH is set.
294	 */
295	if ((!dots && (statp->options & RES_DEFNAMES) != 0U) ||
296	    (dots && !trailing_dot && (statp->options & RES_DNSRCH) != 0U)) {
297		int done = 0;
298
299		for (domain = (const char * const *)statp->dnsrch;
300		     *domain && !done;
301		     domain++) {
302			searched = 1;
303
304			if (domain[0][0] == '\0' ||
305			    (domain[0][0] == '.' && domain[0][1] == '\0'))
306				root_on_list++;
307
308			ret = res_nquerydomain(statp, name, *domain,
309					       class, type,
310					       answer, anslen);
311			if (ret > 0)
312				return (ret);
313
314			/*
315			 * If no server present, give up.
316			 * If name isn't found in this domain,
317			 * keep trying higher domains in the search list
318			 * (if that's enabled).
319			 * On a NO_DATA error, keep trying, otherwise
320			 * a wildcard entry of another type could keep us
321			 * from finding this entry higher in the domain.
322			 * If we get some other error (negative answer or
323			 * server failure), then stop searching up,
324			 * but try the input name below in case it's
325			 * fully-qualified.
326			 */
327			if (errno == ECONNREFUSED) {
328				RES_SET_H_ERRNO(statp, TRY_AGAIN);
329				return (-1);
330			}
331
332			switch (statp->res_h_errno) {
333			case NO_DATA:
334				got_nodata++;
335				/* FALLTHROUGH */
336			case HOST_NOT_FOUND:
337				/* keep trying */
338				break;
339			case TRY_AGAIN:
340				if (hp->rcode == SERVFAIL) {
341					/* try next search element, if any */
342					got_servfail++;
343					break;
344				}
345				/* FALLTHROUGH */
346			default:
347				/* anything else implies that we're done */
348				done++;
349			}
350
351			/* if we got here for some reason other than DNSRCH,
352			 * we only wanted one iteration of the loop, so stop.
353			 */
354			if ((statp->options & RES_DNSRCH) == 0U)
355				done++;
356		}
357	}
358
359	/*
360	 * If the query has not already been tried as is then try it
361	 * unless RES_NOTLDQUERY is set and there were no dots.
362	 */
363	if ((dots || !searched || (statp->options & RES_NOTLDQUERY) == 0U) &&
364	    !(tried_as_is || root_on_list)) {
365		ret = res_nquerydomain(statp, name, NULL, class, type,
366				       answer, anslen);
367		if (ret > 0)
368			return (ret);
369	}
370
371	/* if we got here, we didn't satisfy the search.
372	 * if we did an initial full query, return that query's H_ERRNO
373	 * (note that we wouldn't be here if that query had succeeded).
374	 * else if we ever got a nodata, send that back as the reason.
375	 * else send back meaningless H_ERRNO, that being the one from
376	 * the last DNSRCH we did.
377	 */
378	if (saved_herrno != -1)
379		RES_SET_H_ERRNO(statp, saved_herrno);
380	else if (got_nodata)
381		RES_SET_H_ERRNO(statp, NO_DATA);
382	else if (got_servfail)
383		RES_SET_H_ERRNO(statp, TRY_AGAIN);
384	return (-1);
385}
386
387/*%
388 * Perform a call on res_query on the concatenation of name and domain,
389 * removing a trailing dot from name if domain is NULL.
390 */
391int
392res_nquerydomain(res_state statp,
393	    const char *name,
394	    const char *domain,
395	    int class, int type,	/*%< class and type of query */
396	    u_char *answer,		/*%< buffer to put answer */
397	    int anslen)		/*%< size of answer */
398{
399	char nbuf[MAXDNAME];
400	const char *longname = nbuf;
401	size_t n;
402
403#ifdef DEBUG
404	if (statp->options & RES_DEBUG)
405		printf(";; res_nquerydomain(%s, %s, %d, %d)\n",
406		       name, domain?domain:"<Nil>", class, type);
407#endif
408	if (domain == NULL) {
409		/*
410		 * Check for trailing '.';
411		 * copy without '.' if present.
412		 */
413		n = strlen(name);
414		if (n >= MAXDNAME) {
415			RES_SET_H_ERRNO(statp, NO_RECOVERY);
416			return (-1);
417		}
418		if (n && name[--n] == '.') {
419			snprintf(nbuf, sizeof(nbuf), "%*s", (int)n, name);
420		} else
421			longname = name;
422	} else {
423		if ((size_t)snprintf(nbuf, sizeof(nbuf), "%s.%s",
424				name, domain) >= sizeof(nbuf)) {
425			RES_SET_H_ERRNO(statp, NO_RECOVERY);
426			return (-1);
427		}
428	}
429	return (res_nquery(statp, longname, class, type, answer, anslen));
430}
431
432const char *
433res_hostalias(const res_state statp, const char *name, char *dst, size_t siz) {
434	char *file, *cp1, *cp2;
435	char buf[BUFSIZ];
436	FILE *fp;
437
438	if (statp->options & RES_NOALIASES)
439		return (NULL);
440	/*
441	 * forbid hostaliases for setuid binary, due to possible security
442	 * breach.
443	 */
444	if (issetugid())
445		return (NULL);
446	file = getenv("HOSTALIASES");
447	if (file == NULL || (fp = fopen(file, "re")) == NULL)
448		return (NULL);
449	buf[sizeof(buf) - 1] = '\0';
450	while (fgets(buf, (int)sizeof(buf), fp)) {
451		for (cp1 = buf; *cp1 && !isspace((unsigned char)*cp1); ++cp1)
452			;
453		if (!*cp1)
454			break;
455		*cp1 = '\0';
456		if (ns_samename(buf, name) == 1) {
457			while (isspace((unsigned char)*++cp1))
458				;
459			if (!*cp1)
460				break;
461			for (cp2 = cp1 + 1; *cp2 &&
462			     !isspace((unsigned char)*cp2); ++cp2)
463				;
464			*cp2 = '\0';
465			strncpy(dst, cp1, siz - 1);
466			dst[siz - 1] = '\0';
467			fclose(fp);
468			return (dst);
469		}
470	}
471	fclose(fp);
472	return (NULL);
473}
474
475/*! \file */
476