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