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