Home | History | Annotate | Line # | Download | only in resolv
res_query.c revision 1.18
      1 /*	$NetBSD: res_query.c,v 1.18 2024/08/24 22:37:41 christos 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
     89 static const char sccsid[] = "@(#)res_query.c	8.1 (Berkeley) 6/4/93";
     90 static 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.18 2024/08/24 22:37:41 christos 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  */
    144 int
    145 res_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 	int n;
    155 
    156 	oflags = statp->_flags;
    157 
    158 again:
    159 	hp->rcode = NOERROR;	/*%< default */
    160 #ifdef DEBUG
    161 	if (statp->options & RES_DEBUG)
    162 		printf(";; res_query(%s, %d, %d)\n", name, class, type);
    163 #endif
    164 
    165 	n = res_nmkquery(statp, QUERY, name, class, type, NULL, 0, NULL,
    166 			 buf, (int)sizeof(buf));
    167 #ifdef RES_USE_EDNS0
    168 	if (n > 0 && (statp->_flags & RES_F_EDNS0ERR) == 0 &&
    169 	    (statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC|RES_NSID)) != 0U) {
    170 		n = res_nopt(statp, n, buf, (int)sizeof(buf), anslen);
    171 		if (n > 0 && (statp->options & RES_NSID) != 0U) {
    172 			n = res_nopt_rdata(statp, n, buf, (int)sizeof(buf),
    173 			    buf + n, NS_OPT_NSID, 0, NULL);
    174 		}
    175 	}
    176 #endif
    177 	if (n <= 0) {
    178 #ifdef DEBUG
    179 		if (statp->options & RES_DEBUG)
    180 			printf(";; res_query: mkquery failed\n");
    181 #endif
    182 		RES_SET_H_ERRNO(statp, NO_RECOVERY);
    183 		return (n);
    184 	}
    185 
    186 	n = res_nsend(statp, buf, n, answer, anslen);
    187 	if (n < 0) {
    188 #ifdef RES_USE_EDNS0
    189 		/* if the query choked with EDNS0, retry without EDNS0 */
    190 		if ((statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U &&
    191 		    ((oflags ^ statp->_flags) & RES_F_EDNS0ERR) != 0) {
    192 			statp->_flags |= RES_F_EDNS0ERR;
    193 			if (statp->options & RES_DEBUG)
    194 				printf(";; res_nquery: retry without EDNS0\n");
    195 			goto again;
    196 		}
    197 #endif
    198 #ifdef DEBUG
    199 		if (statp->options & RES_DEBUG)
    200 			printf(";; res_query: send error\n");
    201 #endif
    202 		RES_SET_H_ERRNO(statp, TRY_AGAIN);
    203 		return (n);
    204 	}
    205 
    206 	if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
    207 #ifdef DEBUG
    208 		if (statp->options & RES_DEBUG)
    209 			printf(";; rcode = (%s), counts = an:%d ns:%d ar:%d\n",
    210 			       p_rcode(hp->rcode),
    211 			       ntohs(hp->ancount),
    212 			       ntohs(hp->nscount),
    213 			       ntohs(hp->arcount));
    214 #endif
    215 		switch (hp->rcode) {
    216 		case NXDOMAIN:
    217 			RES_SET_H_ERRNO(statp, HOST_NOT_FOUND);
    218 			break;
    219 		case SERVFAIL:
    220 			RES_SET_H_ERRNO(statp, TRY_AGAIN);
    221 			break;
    222 		case NOERROR:
    223 			RES_SET_H_ERRNO(statp, NO_DATA);
    224 			break;
    225 		case FORMERR:
    226 		case NOTIMP:
    227 		case REFUSED:
    228 		default:
    229 			RES_SET_H_ERRNO(statp, NO_RECOVERY);
    230 			break;
    231 		}
    232 		return (-1);
    233 	}
    234 	return (n);
    235 }
    236 
    237 /*%
    238  * Formulate a normal query, send, and retrieve answer in supplied buffer.
    239  * Return the size of the response on success, -1 on error.
    240  * If enabled, implement search rules until answer or unrecoverable failure
    241  * is detected.  Error code, if any, is left in H_ERRNO.
    242  */
    243 int
    244 res_nsearch(res_state statp,
    245 	    const char *name,	/*%< domain name */
    246 	    int class, int type,	/*%< class and type of query */
    247 	    u_char *answer,	/*%< buffer to put answer */
    248 	    int anslen)		/*%< size of answer */
    249 {
    250 	const char *cp, * const *domain;
    251 	HEADER *hp = (HEADER *)(void *)answer;
    252 	char tmp[NS_MAXDNAME];
    253 	u_int dots;
    254 	int trailing_dot, ret, saved_herrno;
    255 	int got_nodata = 0, got_servfail = 0, root_on_list = 0;
    256 	int tried_as_is = 0;
    257 	int searched = 0;
    258 
    259 	errno = 0;
    260 	RES_SET_H_ERRNO(statp, HOST_NOT_FOUND);  /*%< True if we never query. */
    261 	dots = 0;
    262 	for (cp = name; *cp != '\0'; cp++)
    263 		dots += (*cp == '.');
    264 	trailing_dot = 0;
    265 	if (cp > name && *--cp == '.')
    266 		trailing_dot++;
    267 
    268 	/* If there aren't any dots, it could be a user-level alias. */
    269 	if (!dots && (cp = res_hostalias(statp, name, tmp, sizeof tmp))!= NULL)
    270 		return (res_nquery(statp, cp, class, type, answer, anslen));
    271 
    272 	/*
    273 	 * If there are enough dots in the name, let's just give it a
    274 	 * try 'as is'. The threshold can be set with the "ndots" option.
    275 	 * Also, query 'as is', if there is a trailing dot in the name.
    276 	 */
    277 	saved_herrno = -1;
    278 	if (dots >= statp->ndots || trailing_dot) {
    279 		ret = res_nquerydomain(statp, name, NULL, class, type,
    280 					 answer, anslen);
    281 		if (ret > 0 || trailing_dot)
    282 			return (ret);
    283 		saved_herrno = statp->res_h_errno;
    284 		tried_as_is++;
    285 	}
    286 
    287 	/*
    288 	 * We do at least one level of search if
    289 	 *	- there is no dot and RES_DEFNAME is set, or
    290 	 *	- there is at least one dot, there is no trailing dot,
    291 	 *	  and RES_DNSRCH is set.
    292 	 */
    293 	if ((!dots && (statp->options & RES_DEFNAMES) != 0U) ||
    294 	    (dots && !trailing_dot && (statp->options & RES_DNSRCH) != 0U)) {
    295 		int done = 0;
    296 
    297 		for (domain = (const char * const *)statp->dnsrch;
    298 		     *domain && !done;
    299 		     domain++) {
    300 			searched = 1;
    301 
    302 			if (domain[0][0] == '\0' ||
    303 			    (domain[0][0] == '.' && domain[0][1] == '\0'))
    304 				root_on_list++;
    305 
    306 			ret = res_nquerydomain(statp, name, *domain,
    307 					       class, type,
    308 					       answer, anslen);
    309 			if (ret > 0)
    310 				return (ret);
    311 
    312 			/*
    313 			 * If no server present, give up.
    314 			 * If name isn't found in this domain,
    315 			 * keep trying higher domains in the search list
    316 			 * (if that's enabled).
    317 			 * On a NO_DATA error, keep trying, otherwise
    318 			 * a wildcard entry of another type could keep us
    319 			 * from finding this entry higher in the domain.
    320 			 * If we get some other error (negative answer or
    321 			 * server failure), then stop searching up,
    322 			 * but try the input name below in case it's
    323 			 * fully-qualified.
    324 			 */
    325 			if (errno == ECONNREFUSED) {
    326 				RES_SET_H_ERRNO(statp, TRY_AGAIN);
    327 				return (-1);
    328 			}
    329 
    330 			switch (statp->res_h_errno) {
    331 			case NO_DATA:
    332 				got_nodata++;
    333 				/* FALLTHROUGH */
    334 			case HOST_NOT_FOUND:
    335 				/* keep trying */
    336 				break;
    337 			case TRY_AGAIN:
    338 				if (hp->rcode == SERVFAIL) {
    339 					/* try next search element, if any */
    340 					got_servfail++;
    341 					break;
    342 				}
    343 				/* FALLTHROUGH */
    344 			default:
    345 				/* anything else implies that we're done */
    346 				done++;
    347 			}
    348 
    349 			/* if we got here for some reason other than DNSRCH,
    350 			 * we only wanted one iteration of the loop, so stop.
    351 			 */
    352 			if ((statp->options & RES_DNSRCH) == 0U)
    353 				done++;
    354 		}
    355 	}
    356 
    357 	/*
    358 	 * If the query has not already been tried as is then try it
    359 	 * unless RES_NOTLDQUERY is set and there were no dots.
    360 	 */
    361 	if ((dots || !searched || (statp->options & RES_NOTLDQUERY) == 0U) &&
    362 	    !(tried_as_is || root_on_list)) {
    363 		ret = res_nquerydomain(statp, name, NULL, class, type,
    364 				       answer, anslen);
    365 		if (ret > 0)
    366 			return (ret);
    367 	}
    368 
    369 	/* if we got here, we didn't satisfy the search.
    370 	 * if we did an initial full query, return that query's H_ERRNO
    371 	 * (note that we wouldn't be here if that query had succeeded).
    372 	 * else if we ever got a nodata, send that back as the reason.
    373 	 * else send back meaningless H_ERRNO, that being the one from
    374 	 * the last DNSRCH we did.
    375 	 */
    376 	if (saved_herrno != -1)
    377 		RES_SET_H_ERRNO(statp, saved_herrno);
    378 	else if (got_nodata)
    379 		RES_SET_H_ERRNO(statp, NO_DATA);
    380 	else if (got_servfail)
    381 		RES_SET_H_ERRNO(statp, TRY_AGAIN);
    382 	return (-1);
    383 }
    384 
    385 /*%
    386  * Perform a call on res_query on the concatenation of name and domain,
    387  * removing a trailing dot from name if domain is NULL.
    388  */
    389 int
    390 res_nquerydomain(res_state statp,
    391 	    const char *name,
    392 	    const char *domain,
    393 	    int class, int type,	/*%< class and type of query */
    394 	    u_char *answer,		/*%< buffer to put answer */
    395 	    int anslen)		/*%< size of answer */
    396 {
    397 	char nbuf[MAXDNAME];
    398 	const char *longname = nbuf;
    399 	size_t n;
    400 
    401 #ifdef DEBUG
    402 	if (statp->options & RES_DEBUG)
    403 		printf(";; res_nquerydomain(%s, %s, %d, %d)\n",
    404 		       name, domain?domain:"<Nil>", class, type);
    405 #endif
    406 	if (domain == NULL) {
    407 		/*
    408 		 * Check for trailing '.';
    409 		 * copy without '.' if present.
    410 		 */
    411 		n = strlen(name);
    412 		if (n >= MAXDNAME) {
    413 			RES_SET_H_ERRNO(statp, NO_RECOVERY);
    414 			return (-1);
    415 		}
    416 		if (n && name[--n] == '.') {
    417 			snprintf(nbuf, sizeof(nbuf), "%*s", (int)n, name);
    418 		} else
    419 			longname = name;
    420 	} else {
    421 		if ((size_t)snprintf(nbuf, sizeof(nbuf), "%s.%s",
    422 				name, domain) >= sizeof(nbuf)) {
    423 			RES_SET_H_ERRNO(statp, NO_RECOVERY);
    424 			return (-1);
    425 		}
    426 	}
    427 	return (res_nquery(statp, longname, class, type, answer, anslen));
    428 }
    429 
    430 const char *
    431 res_hostalias(const res_state statp, const char *name, char *dst, size_t siz) {
    432 	char *file, *cp1, *cp2;
    433 	char buf[BUFSIZ];
    434 	FILE *fp;
    435 
    436 	if (statp->options & RES_NOALIASES)
    437 		return (NULL);
    438 	/*
    439 	 * forbid hostaliases for setuid binary, due to possible security
    440 	 * breach.
    441 	 */
    442 	if (issetugid())
    443 		return (NULL);
    444 	file = getenv("HOSTALIASES");
    445 	if (file == NULL || (fp = fopen(file, "re")) == NULL)
    446 		return (NULL);
    447 	buf[sizeof(buf) - 1] = '\0';
    448 	while (fgets(buf, (int)sizeof(buf), fp)) {
    449 		for (cp1 = buf; *cp1 && !isspace((unsigned char)*cp1); ++cp1)
    450 			;
    451 		if (!*cp1)
    452 			break;
    453 		*cp1 = '\0';
    454 		if (ns_samename(buf, name) == 1) {
    455 			while (isspace((unsigned char)*++cp1))
    456 				;
    457 			if (!*cp1)
    458 				break;
    459 			for (cp2 = cp1 + 1; *cp2 &&
    460 			     !isspace((unsigned char)*cp2); ++cp2)
    461 				;
    462 			*cp2 = '\0';
    463 			strncpy(dst, cp1, siz - 1);
    464 			dst[siz - 1] = '\0';
    465 			fclose(fp);
    466 			return (dst);
    467 		}
    468 	}
    469 	fclose(fp);
    470 	return (NULL);
    471 }
    472 
    473 /*! \file */
    474