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 #define LOG_TAG "res_query"
74
75 #include <arpa/inet.h>
76 #include <arpa/nameser.h>
77 #include <ctype.h>
78 #include <errno.h>
79 #include <netdb.h>
80 #include <netinet/in.h>
81 #include <sys/param.h>
82 #include <sys/types.h>
83 #include <stdio.h>
84 #include <stdlib.h>
85 #include <string.h>
86 #include <unistd.h>
87
88 #include <android-base/logging.h>
89
90 #include "resolv_cache.h"
91 #include "resolv_private.h"
92
93 #if PACKETSZ > 1024
94 #define MAXPACKET PACKETSZ
95 #else
96 #define MAXPACKET 1024
97 #endif
98
99 /*
100 * Formulate a normal query, send, and await answer.
101 * Returned answer is placed in supplied buffer "answer".
102 * Perform preliminary check of answer, returning success only
103 * if no error is indicated and the answer count is nonzero.
104 * Return the size of the response on success, -1 on error.
105 * Error number is left in *herrno.
106 *
107 * Caller must parse answer and determine whether it answers the question.
108 */
res_nquery(res_state statp,const char * name,int cl,int type,u_char * answer,int anslen,int * herrno)109 int res_nquery(res_state statp, const char* name, // domain name
110 int cl, int type, // class and type of query
111 u_char* answer, // buffer to put answer
112 int anslen, // size of answer buffer
113 int* herrno) // legacy and extended h_errno
114 // NETD_RESOLV_H_ERRNO_EXT_*
115 {
116 u_char buf[MAXPACKET];
117 HEADER* hp = (HEADER*) (void*) answer;
118 int n;
119 int rcode = NOERROR;
120 bool retried = false;
121
122 again:
123 hp->rcode = NOERROR; /* default */
124
125 LOG(DEBUG) << __func__ << ": (" << cl << ", " << type << ")";
126
127 n = res_nmkquery(statp, QUERY, name, cl, type, NULL, 0, NULL, buf, sizeof(buf));
128 if (n > 0 && (statp->options & (RES_USE_EDNS0 | RES_USE_DNSSEC)) != 0U && !retried)
129 n = res_nopt(statp, n, buf, sizeof(buf), anslen);
130 if (n <= 0) {
131 LOG(DEBUG) << __func__ << ": mkquery failed";
132 *herrno = NO_RECOVERY;
133 return n;
134 }
135 n = res_nsend(statp, buf, n, answer, anslen, &rcode, 0);
136 if (n < 0) {
137 /* if the query choked with EDNS0, retry without EDNS0 */
138 if ((statp->options & (RES_USE_EDNS0 | RES_USE_DNSSEC)) != 0U &&
139 (statp->_flags & RES_F_EDNS0ERR) && !retried) {
140 LOG(DEBUG) << __func__ << ": retry without EDNS0";
141 retried = true;
142 goto again;
143 }
144 LOG(DEBUG) << __func__ << ": send error";
145
146 // Note that rcodes SERVFAIL, NOTIMP, REFUSED may cause res_nquery() to return a general
147 // error code EAI_AGAIN, but mapping the error code from rcode as res_queryN() does for
148 // getaddrinfo(). Different rcodes trigger different behaviors:
149 //
150 // - SERVFAIL, NOTIMP, REFUSED
151 // These result in send_dg() returning 0, causing res_nsend() to try the next
152 // nameserver. After all nameservers failed, res_nsend() returns -ETIMEDOUT, causing
153 // res_nquery() to return EAI_AGAIN here regardless of the rcode from the DNS response.
154 //
155 // - NXDOMAIN, FORMERR
156 // These rcodes may cause res_nsend() to return successfully (i.e. the result is a
157 // positive integer). In this case, res_nquery() returns error number by referring
158 // the rcode from the DNS response.
159 switch (rcode) {
160 case RCODE_TIMEOUT: // Not defined in RFC.
161 // DNS metrics monitors DNS query timeout.
162 *herrno = NETD_RESOLV_H_ERRNO_EXT_TIMEOUT; // extended h_errno.
163 break;
164 default:
165 *herrno = TRY_AGAIN;
166 break;
167 }
168 return n;
169 }
170
171 if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
172 LOG(DEBUG) << __func__ << ": rcode = (" << p_rcode(hp->rcode)
173 << "), counts = an:" << ntohs(hp->ancount) << " ns:" << ntohs(hp->nscount)
174 << " ar:" << ntohs(hp->arcount);
175
176 switch (hp->rcode) {
177 case NXDOMAIN:
178 *herrno = HOST_NOT_FOUND;
179 break;
180 case SERVFAIL:
181 *herrno = TRY_AGAIN;
182 break;
183 case NOERROR:
184 *herrno = NO_DATA;
185 break;
186 case FORMERR:
187 case NOTIMP:
188 case REFUSED:
189 default:
190 *herrno = NO_RECOVERY;
191 break;
192 }
193 return -1;
194 }
195 return n;
196 }
197
198 /*
199 * Formulate a normal query, send, and retrieve answer in supplied buffer.
200 * Return the size of the response on success, -1 on error.
201 * If enabled, implement search rules until answer or unrecoverable failure
202 * is detected. Error code, if any, is left in *herrno.
203 */
res_nsearch(res_state statp,const char * name,int cl,int type,u_char * answer,int anslen,int * herrno)204 int res_nsearch(res_state statp, const char* name, /* domain name */
205 int cl, int type, /* class and type of query */
206 u_char* answer, /* buffer to put answer */
207 int anslen, /* size of answer */
208 int* herrno) /* legacy and extended
209 h_errno NETD_RESOLV_H_ERRNO_EXT_* */
210 {
211 const char *cp, *const *domain;
212 HEADER* hp = (HEADER*) (void*) answer;
213 u_int dots;
214 int trailing_dot, ret, saved_herrno;
215 int got_nodata = 0, got_servfail = 0, root_on_list = 0;
216 int tried_as_is = 0;
217 int searched = 0;
218
219 errno = 0;
220 *herrno = HOST_NOT_FOUND; /* True if we never query. */
221
222 dots = 0;
223 for (cp = name; *cp != '\0'; cp++) dots += (*cp == '.');
224 trailing_dot = 0;
225 if (cp > name && *--cp == '.') trailing_dot++;
226
227 /*
228 * If there are enough dots in the name, let's just give it a
229 * try 'as is'. The threshold can be set with the "ndots" option.
230 * Also, query 'as is', if there is a trailing dot in the name.
231 */
232 saved_herrno = -1;
233 if (dots >= statp->ndots || trailing_dot) {
234 ret = res_nquerydomain(statp, name, NULL, cl, type, answer, anslen, herrno);
235 if (ret > 0 || trailing_dot) return ret;
236 saved_herrno = *herrno;
237 tried_as_is++;
238 }
239
240 /*
241 * We do at least one level of search if
242 * - there is no dot and RES_DEFNAME is set, or
243 * - there is at least one dot, there is no trailing dot,
244 * and RES_DNSRCH is set.
245 */
246 if ((!dots && (statp->options & RES_DEFNAMES) != 0U) ||
247 (dots && !trailing_dot && (statp->options & RES_DNSRCH) != 0U)) {
248 int done = 0;
249
250 /* Unfortunately we need to load network-specific info
251 * (dns servers, search domains) before
252 * the domain stuff is tried. Will have a better
253 * fix after thread pools are used as this will
254 * be loaded once for the thread instead of each
255 * time a query is tried.
256 */
257 _resolv_populate_res_for_net(statp);
258
259 for (domain = (const char* const*) statp->dnsrch; *domain && !done; domain++) {
260 searched = 1;
261
262 if (domain[0][0] == '\0' || (domain[0][0] == '.' && domain[0][1] == '\0'))
263 root_on_list++;
264
265 ret = res_nquerydomain(statp, name, *domain, cl, type, answer, anslen, herrno);
266 if (ret > 0) return ret;
267
268 /*
269 * If no server present, give up.
270 * If name isn't found in this domain,
271 * keep trying higher domains in the search list
272 * (if that's enabled).
273 * On a NO_DATA error, keep trying, otherwise
274 * a wildcard entry of another type could keep us
275 * from finding this entry higher in the domain.
276 * If we get some other error (negative answer or
277 * server failure), then stop searching up,
278 * but try the input name below in case it's
279 * fully-qualified.
280 */
281 if (errno == ECONNREFUSED) {
282 *herrno = TRY_AGAIN;
283 return -1;
284 }
285
286 switch (*herrno) {
287 case NO_DATA:
288 got_nodata++;
289 break;
290 case HOST_NOT_FOUND:
291 /* keep trying */
292 break;
293 case TRY_AGAIN:
294 if (hp->rcode == SERVFAIL) {
295 /* try next search element, if any */
296 got_servfail++;
297 break;
298 }
299 [[fallthrough]];
300 default:
301 /* anything else implies that we're done */
302 done++;
303 }
304
305 /* if we got here for some reason other than DNSRCH,
306 * we only wanted one iteration of the loop, so stop.
307 */
308 if ((statp->options & RES_DNSRCH) == 0U) done++;
309 }
310 }
311
312 /*
313 * If the query has not already been tried as is then try it
314 * unless RES_NOTLDQUERY is set and there were no dots.
315 */
316 if ((dots || !searched || (statp->options & RES_NOTLDQUERY) == 0U) &&
317 !(tried_as_is || root_on_list)) {
318 ret = res_nquerydomain(statp, name, NULL, cl, type, answer, anslen, herrno);
319 if (ret > 0) return ret;
320 }
321
322 /* if we got here, we didn't satisfy the search.
323 * if we did an initial full query, return that query's H_ERRNO
324 * (note that we wouldn't be here if that query had succeeded).
325 * else if we ever got a nodata, send that back as the reason.
326 * else send back meaningless H_ERRNO, that being the one from
327 * the last DNSRCH we did.
328 */
329 if (saved_herrno != -1)
330 *herrno = saved_herrno;
331 else if (got_nodata)
332 *herrno = NO_DATA;
333 else if (got_servfail)
334 *herrno = TRY_AGAIN;
335 return -1;
336 }
337
338 /*
339 * Perform a call on res_query on the concatenation of name and domain,
340 * removing a trailing dot from name if domain is NULL.
341 */
res_nquerydomain(res_state statp,const char * name,const char * domain,int cl,int type,u_char * answer,int anslen,int * herrno)342 int res_nquerydomain(res_state statp, const char* name, const char* domain, int cl,
343 int type, /* class and type of query */
344 u_char* answer, /* buffer to put answer */
345 int anslen, /* size of answer */
346 int* herrno) /* legacy and extended h_errno NETD_RESOLV_H_ERRNO_EXT_* */
347 {
348 char nbuf[MAXDNAME];
349 const char* longname = nbuf;
350 int n, d;
351
352 if (domain == NULL) {
353 LOG(DEBUG) << __func__ << ": (null, " << cl << ", " << type << ")";
354 /*
355 * Check for trailing '.';
356 * copy without '.' if present.
357 */
358 n = strlen(name);
359 if (n >= MAXDNAME) {
360 *herrno = NO_RECOVERY;
361 return -1;
362 }
363 n--;
364 if (n >= 0 && name[n] == '.') {
365 strncpy(nbuf, name, (size_t) n);
366 nbuf[n] = '\0';
367 } else
368 longname = name;
369 } else {
370 LOG(DEBUG) << __func__ << ": (" << cl << ", " << type << ")";
371 n = strlen(name);
372 d = strlen(domain);
373 if (n + d + 1 >= MAXDNAME) {
374 *herrno = NO_RECOVERY;
375 return -1;
376 }
377 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
378 }
379 return res_nquery(statp, longname, cl, type, answer, anslen, herrno);
380 }
381