1/*	$NetBSD: res_query.c,v 1.16 2015/02/24 17:56:20 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#if defined(LIBC_SCCS) && !defined(lint)
70static const char sccsid[] = "@(#)res_query.c	8.1 (Berkeley) 6/4/93";
71static const char rcsid[] = "$Id: res_query.c,v 1.11 2008/11/14 02:36:51 marka Exp $";
72#endif /* LIBC_SCCS and not lint */
73
74#include "port_before.h"
75#include <sys/types.h>
76#include <sys/param.h>
77#include <netinet/in.h>
78#include <arpa/inet.h>
79#include <arpa/nameser.h>
80#include <ctype.h>
81#include <errno.h>
82#include <netdb.h>
83#include <resolv.h>
84#include <stdio.h>
85#include <stdlib.h>
86#include <string.h>
87#include "port_after.h"
88
89/* Options.  Leave them on. */
90//#define DEBUG
91
92#if PACKETSZ > 1024
93#define MAXPACKET	PACKETSZ
94#else
95#define MAXPACKET	1024
96#endif
97
98/*%
99 * Formulate a normal query, send, and await answer.
100 * Returned answer is placed in supplied buffer "answer".
101 * Perform preliminary check of answer, returning success only
102 * if no error is indicated and the answer count is nonzero.
103 * Return the size of the response on success, -1 on error.
104 * Error number is left in H_ERRNO.
105 *
106 * Caller must parse answer and determine whether it answers the question.
107 */
108int
109res_nquery(res_state statp,
110	   const char *name,	/*%< domain name */
111	   int class, int type,	/*%< class and type of query */
112	   u_char *answer,	/*%< buffer to put answer */
113	   int anslen)		/*%< size of answer buffer */
114{
115	u_char buf[MAXPACKET];
116	HEADER *hp = (HEADER *)(void *)answer;
117	u_int oflags;
118	u_char *rdata;
119	int n;
120
121	oflags = statp->_flags;
122
123again:
124	hp->rcode = NOERROR;	/*%< default */
125#ifdef DEBUG
126	if (statp->options & RES_DEBUG)
127		printf(";; res_query(%s, %d, %d)\n", name, class, type);
128#endif
129
130	n = res_nmkquery(statp, QUERY, name, class, type, NULL, 0, NULL,
131			 buf, (int)sizeof(buf));
132#ifdef RES_USE_EDNS0
133	if (n > 0 && (statp->_flags & RES_F_EDNS0ERR) == 0 &&
134	    (statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC|RES_NSID)) != 0U) {
135		n = res_nopt(statp, n, buf, (int)sizeof(buf), anslen);
136		rdata = &buf[n];
137		if (n > 0 && (statp->options & RES_NSID) != 0U) {
138			n = res_nopt_rdata(statp, n, buf, (int)sizeof(buf),
139			    rdata, NS_OPT_NSID, 0, NULL);
140		}
141	}
142#endif
143	if (n <= 0) {
144#ifdef DEBUG
145		if (statp->options & RES_DEBUG)
146			printf(";; res_query: mkquery failed\n");
147#endif
148		RES_SET_H_ERRNO(statp, NO_RECOVERY);
149		return (n);
150	}
151
152	n = res_nsend(statp, buf, n, answer, anslen);
153	if (n < 0) {
154#ifdef RES_USE_EDNS0
155		/* if the query choked with EDNS0, retry without EDNS0 */
156		if ((statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U &&
157		    ((oflags ^ statp->_flags) & RES_F_EDNS0ERR) != 0) {
158			statp->_flags |= RES_F_EDNS0ERR;
159			if (statp->options & RES_DEBUG)
160				printf(";; res_nquery: retry without EDNS0\n");
161			goto again;
162		}
163#endif
164#ifdef DEBUG
165		if (statp->options & RES_DEBUG)
166			printf(";; res_query: send error\n");
167#endif
168		RES_SET_H_ERRNO(statp, TRY_AGAIN);
169		return (n);
170	}
171
172	if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
173#ifdef DEBUG
174		if (statp->options & RES_DEBUG)
175			printf(";; rcode = (%s), counts = an:%d ns:%d ar:%d\n",
176			       p_rcode(hp->rcode),
177			       ntohs(hp->ancount),
178			       ntohs(hp->nscount),
179			       ntohs(hp->arcount));
180#endif
181		switch (hp->rcode) {
182		case NXDOMAIN:
183			RES_SET_H_ERRNO(statp, HOST_NOT_FOUND);
184			break;
185		case SERVFAIL:
186			RES_SET_H_ERRNO(statp, TRY_AGAIN);
187			break;
188		case NOERROR:
189			RES_SET_H_ERRNO(statp, NO_DATA);
190			break;
191		case FORMERR:
192		case NOTIMP:
193		case REFUSED:
194		default:
195			RES_SET_H_ERRNO(statp, NO_RECOVERY);
196			break;
197		}
198		return (-1);
199	}
200	return (n);
201}
202
203/*%
204 * Formulate a normal query, send, and retrieve answer in supplied buffer.
205 * Return the size of the response on success, -1 on error.
206 * If enabled, implement search rules until answer or unrecoverable failure
207 * is detected.  Error code, if any, is left in H_ERRNO.
208 */
209int
210res_nsearch(res_state statp,
211	    const char *name,	/*%< domain name */
212	    int class, int type,	/*%< class and type of query */
213	    u_char *answer,	/*%< buffer to put answer */
214	    int anslen)		/*%< size of answer */
215{
216	const char *cp, * const *domain;
217	HEADER *hp = (HEADER *)(void *)answer;
218	char tmp[NS_MAXDNAME];
219	u_int dots;
220	int trailing_dot, ret, saved_herrno;
221	int got_nodata = 0, got_servfail = 0, root_on_list = 0;
222	int tried_as_is = 0;
223	int searched = 0;
224
225	errno = 0;
226	RES_SET_H_ERRNO(statp, HOST_NOT_FOUND);  /*%< True if we never query. */
227	dots = 0;
228	for (cp = name; *cp != '\0'; cp++)
229		dots += (*cp == '.');
230	trailing_dot = 0;
231	if (cp > name && *--cp == '.')
232		trailing_dot++;
233
234	/* If there aren't any dots, it could be a user-level alias. */
235	if (!dots && (cp = res_hostalias(statp, name, tmp, sizeof tmp))!= NULL)
236		return (res_nquery(statp, cp, class, type, answer, anslen));
237
238	/*
239	 * If there are enough dots in the name, let's just give it a
240	 * try 'as is'. The threshold can be set with the "ndots" option.
241	 * Also, query 'as is', if there is a trailing dot in the name.
242	 */
243	saved_herrno = -1;
244	if (dots >= statp->ndots || trailing_dot) {
245		ret = res_nquerydomain(statp, name, NULL, class, type,
246					 answer, anslen);
247		if (ret > 0 || trailing_dot)
248			return (ret);
249		saved_herrno = statp->res_h_errno;
250		tried_as_is++;
251	}
252
253	/*
254	 * We do at least one level of search if
255	 *	- there is no dot and RES_DEFNAME is set, or
256	 *	- there is at least one dot, there is no trailing dot,
257	 *	  and RES_DNSRCH is set.
258	 */
259	if ((!dots && (statp->options & RES_DEFNAMES) != 0U) ||
260	    (dots && !trailing_dot && (statp->options & RES_DNSRCH) != 0U)) {
261		int done = 0;
262
263		for (domain = (const char * const *)statp->dnsrch;
264		     *domain && !done;
265		     domain++) {
266			searched = 1;
267
268			if (domain[0][0] == '\0' ||
269			    (domain[0][0] == '.' && domain[0][1] == '\0'))
270				root_on_list++;
271
272			ret = res_nquerydomain(statp, name, *domain,
273					       class, type,
274					       answer, anslen);
275			if (ret > 0)
276				return (ret);
277
278			/*
279			 * If no server present, give up.
280			 * If name isn't found in this domain,
281			 * keep trying higher domains in the search list
282			 * (if that's enabled).
283			 * On a NO_DATA error, keep trying, otherwise
284			 * a wildcard entry of another type could keep us
285			 * from finding this entry higher in the domain.
286			 * If we get some other error (negative answer or
287			 * server failure), then stop searching up,
288			 * but try the input name below in case it's
289			 * fully-qualified.
290			 */
291			if (errno == ECONNREFUSED) {
292				RES_SET_H_ERRNO(statp, TRY_AGAIN);
293				return (-1);
294			}
295
296			switch (statp->res_h_errno) {
297			case NO_DATA:
298				got_nodata++;
299				/* FALLTHROUGH */
300			case HOST_NOT_FOUND:
301				/* keep trying */
302				break;
303			case TRY_AGAIN:
304				if (hp->rcode == SERVFAIL) {
305					/* try next search element, if any */
306					got_servfail++;
307					break;
308				}
309				/* FALLTHROUGH */
310			default:
311				/* anything else implies that we're done */
312				done++;
313			}
314
315			/* if we got here for some reason other than DNSRCH,
316			 * we only wanted one iteration of the loop, so stop.
317			 */
318			if ((statp->options & RES_DNSRCH) == 0U)
319				done++;
320		}
321	}
322
323	/*
324	 * If the query has not already been tried as is then try it
325	 * unless RES_NOTLDQUERY is set and there were no dots.
326	 */
327	if ((dots || !searched || (statp->options & RES_NOTLDQUERY) == 0U) &&
328	    !(tried_as_is || root_on_list)) {
329		ret = res_nquerydomain(statp, name, NULL, class, type,
330				       answer, anslen);
331		if (ret > 0)
332			return (ret);
333	}
334
335	/* if we got here, we didn't satisfy the search.
336	 * if we did an initial full query, return that query's H_ERRNO
337	 * (note that we wouldn't be here if that query had succeeded).
338	 * else if we ever got a nodata, send that back as the reason.
339	 * else send back meaningless H_ERRNO, that being the one from
340	 * the last DNSRCH we did.
341	 */
342	if (saved_herrno != -1)
343		RES_SET_H_ERRNO(statp, saved_herrno);
344	else if (got_nodata)
345		RES_SET_H_ERRNO(statp, NO_DATA);
346	else if (got_servfail)
347		RES_SET_H_ERRNO(statp, TRY_AGAIN);
348	return (-1);
349}
350
351/*%
352 * Perform a call on res_query on the concatenation of name and domain,
353 * removing a trailing dot from name if domain is NULL.
354 */
355int
356res_nquerydomain(res_state statp,
357	    const char *name,
358	    const char *domain,
359	    int class, int type,	/*%< class and type of query */
360	    u_char *answer,		/*%< buffer to put answer */
361	    int anslen)		/*%< size of answer */
362{
363	char nbuf[MAXDNAME];
364	const char *longname = nbuf;
365	size_t n, d;
366
367#ifdef DEBUG
368	if (statp->options & RES_DEBUG)
369		printf(";; res_nquerydomain(%s, %s, %d, %d)\n",
370		       name, domain?domain:"<Nil>", class, type);
371#endif
372	if (domain == NULL) {
373		/*
374		 * Check for trailing '.';
375		 * copy without '.' if present.
376		 */
377		n = strlen(name);
378		if (n >= MAXDNAME) {
379			RES_SET_H_ERRNO(statp, NO_RECOVERY);
380			return (-1);
381		}
382		if (n && name[--n] == '.') {
383			strncpy(nbuf, name, n);
384			nbuf[n] = '\0';
385		} else
386			longname = name;
387	} else {
388		n = strlen(name);
389		d = strlen(domain);
390		if (n + d + 1 >= MAXDNAME) {
391			RES_SET_H_ERRNO(statp, NO_RECOVERY);
392			return (-1);
393		}
394		sprintf(nbuf, "%s.%s", name, domain);
395	}
396	return (res_nquery(statp, longname, class, type, answer, anslen));
397}
398
399const char *
400res_hostalias(const res_state statp, const char *name, char *dst, size_t siz) {
401	char *file, *cp1, *cp2;
402	char buf[BUFSIZ];
403	FILE *fp;
404
405	if (statp->options & RES_NOALIASES)
406		return (NULL);
407
408	file = getenv("HOSTALIASES");
409	if (file == NULL || (fp = fopen(file, "re")) == NULL)
410		return (NULL);
411	buf[sizeof(buf) - 1] = '\0';
412	while (fgets(buf, (int)sizeof(buf), fp)) {
413		for (cp1 = buf; *cp1 && !isspace((unsigned char)*cp1); ++cp1)
414			;
415		if (!*cp1)
416			break;
417		*cp1 = '\0';
418		if (ns_samename(buf, name) == 1) {
419			while (isspace((unsigned char)*++cp1))
420				;
421			if (!*cp1)
422				break;
423			for (cp2 = cp1 + 1; *cp2 &&
424			     !isspace((unsigned char)*cp2); ++cp2)
425				;
426			*cp2 = '\0';
427			strncpy(dst, cp1, siz - 1);
428			dst[siz - 1] = '\0';
429			fclose(fp);
430			return (dst);
431		}
432	}
433	fclose(fp);
434	return (NULL);
435}
436
437/*! \file */
438