1 /*	$NetBSD: res_send.c,v 1.9 2006/01/24 17:41:25 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 1985, 1989, 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 /*
74  * Send query to name server and wait for reply.
75  */
76 
77 #define LOG_TAG "resolv"
78 
79 #include <chrono>
80 
81 #include <sys/param.h>
82 #include <sys/socket.h>
83 #include <sys/time.h>
84 #include <sys/uio.h>
85 
86 #include <arpa/inet.h>
87 #include <arpa/nameser.h>
88 
89 #include <errno.h>
90 #include <fcntl.h>
91 #include <netdb.h>
92 #include <poll.h>
93 #include <signal.h>
94 #include <stdlib.h>
95 #include <string.h>
96 #include <time.h>
97 #include <unistd.h>
98 #include <span>
99 
100 #include <android-base/logging.h>
101 #include <android-base/result.h>
102 #include <android/multinetwork.h>  // ResNsendFlags
103 
104 #include <netdutils/Slice.h>
105 #include <netdutils/Stopwatch.h>
106 #include "DnsTlsDispatcher.h"
107 #include "DnsTlsTransport.h"
108 #include "Experiments.h"
109 #include "PrivateDnsConfiguration.h"
110 #include "netd_resolv/resolv.h"
111 #include "private/android_filesystem_config.h"
112 
113 #include "doh.h"
114 #include "res_comp.h"
115 #include "res_debug.h"
116 #include "resolv_cache.h"
117 #include "stats.h"
118 #include "stats.pb.h"
119 #include "util.h"
120 
121 using namespace std::chrono_literals;
122 // TODO: use the namespace something like android::netd_resolv for libnetd_resolv
123 using android::base::ErrnoError;
124 using android::base::Result;
125 using android::base::unique_fd;
126 using android::net::CacheStatus;
127 using android::net::DnsQueryEvent;
128 using android::net::DnsTlsDispatcher;
129 using android::net::DnsTlsServer;
130 using android::net::DnsTlsTransport;
131 using android::net::Experiments;
132 using android::net::IpVersion;
133 using android::net::IV_IPV4;
134 using android::net::IV_IPV6;
135 using android::net::IV_UNKNOWN;
136 using android::net::LinuxErrno;
137 using android::net::NetworkDnsEventReported;
138 using android::net::NS_T_AAAA;
139 using android::net::NS_T_INVALID;
140 using android::net::NsRcode;
141 using android::net::NsType;
142 using android::net::PrivateDnsConfiguration;
143 using android::net::PrivateDnsMode;
144 using android::net::PrivateDnsStatus;
145 using android::net::PROTO_DOH;
146 using android::net::PROTO_MDNS;
147 using android::net::PROTO_TCP;
148 using android::net::PROTO_UDP;
149 using android::netdutils::IPSockAddr;
150 using android::netdutils::Slice;
151 using android::netdutils::Stopwatch;
152 using std::span;
153 
154 const std::vector<IPSockAddr> mdns_addrs = {IPSockAddr::toIPSockAddr("ff02::fb", 5353),
155                                             IPSockAddr::toIPSockAddr("224.0.0.251", 5353)};
156 
157 static int setupUdpSocket(ResState* statp, const sockaddr* sockap, unique_fd* fd_out, int* terrno);
158 static int send_dg(ResState* statp, res_params* params, span<const uint8_t> msg, span<uint8_t> ans,
159                    int* terrno, size_t* ns, int* v_circuit, int* gotsomewhere, int* rcode);
160 static int send_vc(ResState* statp, res_params* params, span<const uint8_t> msg, span<uint8_t> ans,
161                    int* terrno, size_t ns, int* rcode);
162 static int send_mdns(ResState* statp, span<const uint8_t> msg, span<uint8_t> ans, int* terrno,
163                      int* rcode);
164 static void dump_error(const char*, const struct sockaddr*);
165 
166 static int sock_eq(struct sockaddr*, struct sockaddr*);
167 static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
168                                 const struct timespec timeout);
169 static int retrying_poll(const int sock, short events, const struct timespec* finish);
170 static int res_private_dns_send(ResState*, const Slice query, const Slice answer, int* rcode,
171                                 bool* fallback);
172 static int res_tls_send(const std::list<DnsTlsServer>& tlsServers, ResState*, const Slice query,
173                         const Slice answer, int* rcode, PrivateDnsMode mode);
174 static ssize_t res_doh_send(ResState*, const Slice query, const Slice answer, int* rcode);
175 static int elapsedTimeInMs(const timespec& from);
176 
getQueryType(span<const uint8_t> msg)177 NsType getQueryType(span<const uint8_t> msg) {
178     ns_msg handle;
179     ns_rr rr;
180     if (ns_initparse(msg.data(), msg.size(), &handle) < 0 ||
181         ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
182         return NS_T_INVALID;
183     }
184     return static_cast<NsType>(ns_rr_type(rr));
185 }
186 
ipFamilyToIPVersion(const int ipFamily)187 IpVersion ipFamilyToIPVersion(const int ipFamily) {
188     switch (ipFamily) {
189         case AF_INET:
190             return IV_IPV4;
191         case AF_INET6:
192             return IV_IPV6;
193         default:
194             return IV_UNKNOWN;
195     }
196 }
197 
198 // BEGIN: Code copied from ISC eventlib
199 // TODO: move away from this code
200 #define BILLION 1000000000
201 
evConsTime(time_t sec,long nsec)202 static struct timespec evConsTime(time_t sec, long nsec) {
203     struct timespec x;
204 
205     x.tv_sec = sec;
206     x.tv_nsec = nsec;
207     return (x);
208 }
209 
evAddTime(struct timespec addend1,struct timespec addend2)210 static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
211     struct timespec x;
212 
213     x.tv_sec = addend1.tv_sec + addend2.tv_sec;
214     x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
215     if (x.tv_nsec >= BILLION) {
216         x.tv_sec++;
217         x.tv_nsec -= BILLION;
218     }
219     return (x);
220 }
221 
evSubTime(struct timespec minuend,struct timespec subtrahend)222 static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
223     struct timespec x;
224 
225     x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
226     if (minuend.tv_nsec >= subtrahend.tv_nsec)
227         x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
228     else {
229         x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
230         x.tv_sec--;
231     }
232     return (x);
233 }
234 
evCmpTime(struct timespec a,struct timespec b)235 static int evCmpTime(struct timespec a, struct timespec b) {
236 #define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
237     time_t s = a.tv_sec - b.tv_sec;
238     long n;
239 
240     if (s != 0) return SGN(s);
241 
242     n = a.tv_nsec - b.tv_nsec;
243     return SGN(n);
244 }
245 
evNowTime(void)246 static struct timespec evNowTime(void) {
247     struct timespec tsnow;
248     clock_gettime(CLOCK_REALTIME, &tsnow);
249     return tsnow;
250 }
251 
252 // END: Code copied from ISC eventlib
253 
254 /* BIONIC-BEGIN: implement source port randomization */
random_bind(int s,int family)255 static int random_bind(int s, int family) {
256     sockaddr_union u;
257     int j;
258     socklen_t slen;
259 
260     /* clear all, this also sets the IP4/6 address to 'any' */
261     memset(&u, 0, sizeof u);
262 
263     switch (family) {
264         case AF_INET:
265             u.sin.sin_family = family;
266             slen = sizeof u.sin;
267             break;
268         case AF_INET6:
269             u.sin6.sin6_family = family;
270             slen = sizeof u.sin6;
271             break;
272         default:
273             errno = EPROTO;
274             return -1;
275     }
276 
277     /* first try to bind to a random source port a few times */
278     for (j = 0; j < 10; j++) {
279         /* find a random port between 1025 .. 65534 */
280         int port = 1025 + (arc4random_uniform(65535 - 1025));
281         // RFC 6762 section 5.1: Don't use 5353 source port on one-shot Multicast DNS queries. DNS
282         // resolver does not fully compliant mDNS.
283         if (port == 5353) continue;
284 
285         if (family == AF_INET)
286             u.sin.sin_port = htons(port);
287         else
288             u.sin6.sin6_port = htons(port);
289 
290         if (!bind(s, &u.sa, slen)) return 0;
291     }
292 
293     // nothing after 10 attempts, our network table is probably busy
294     // let the system decide which port is best
295     if (family == AF_INET)
296         u.sin.sin_port = 0;
297     else
298         u.sin6.sin6_port = 0;
299 
300     return bind(s, &u.sa, slen);
301 }
302 /* BIONIC-END */
303 
304 // Disables all nameservers other than selectedServer
res_set_usable_server(int selectedServer,int nscount,bool usable_servers[])305 static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
306     int usableIndex = 0;
307     for (int ns = 0; ns < nscount; ns++) {
308         if (usable_servers[ns]) ++usableIndex;
309         if (usableIndex != selectedServer) usable_servers[ns] = false;
310     }
311 }
312 
313 // Looks up the nameserver address in res.nsaddrs[], returns the ns number if found, otherwise -1.
res_ourserver_p(ResState * statp,const sockaddr * sa)314 static int res_ourserver_p(ResState* statp, const sockaddr* sa) {
315     const sockaddr_in *inp, *srv;
316     const sockaddr_in6 *in6p, *srv6;
317     int ns = 0;
318     switch (sa->sa_family) {
319         case AF_INET:
320             inp = (const struct sockaddr_in*) (const void*) sa;
321 
322             for (const IPSockAddr& ipsa : statp->nsaddrs) {
323                 sockaddr_storage ss = ipsa;
324                 srv = reinterpret_cast<sockaddr_in*>(&ss);
325                 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
326                     (srv->sin_addr.s_addr == INADDR_ANY ||
327                      srv->sin_addr.s_addr == inp->sin_addr.s_addr))
328                     return ns;
329                 ++ns;
330             }
331             break;
332         case AF_INET6:
333             in6p = (const struct sockaddr_in6*) (const void*) sa;
334             for (const IPSockAddr& ipsa : statp->nsaddrs) {
335                 sockaddr_storage ss = ipsa;
336                 srv6 = reinterpret_cast<sockaddr_in6*>(&ss);
337                 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
338 #ifdef HAVE_SIN6_SCOPE_ID
339                     (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
340 #endif
341                     (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
342                      IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
343                     return ns;
344                 ++ns;
345             }
346             break;
347         default:
348             break;
349     }
350     return -1;
351 }
352 
353 /* int
354  * res_nameinquery(name, type, cl, msg, eom)
355  *	look for (name, type, cl) in the query section of packet (msg, eom)
356  * requires:
357  *	msg + HFIXEDSZ <= eom
358  * returns:
359  *	-1 : format error
360  *	0  : not found
361  *	>0 : found
362  * author:
363  *	paul vixie, 29may94
364  */
res_nameinquery(const char * name,int type,int cl,const uint8_t * msg,const uint8_t * eom)365 int res_nameinquery(const char* name, int type, int cl, const uint8_t* msg, const uint8_t* eom) {
366     const uint8_t* cp = msg + HFIXEDSZ;
367     int qdcount = ntohs(((const HEADER*)(const void*)msg)->qdcount);
368 
369     while (qdcount-- > 0) {
370         char tname[MAXDNAME + 1];
371         int n = dn_expand(msg, eom, cp, tname, sizeof tname);
372         if (n < 0) return (-1);
373         cp += n;
374         if (cp + 2 * INT16SZ > eom) return (-1);
375         int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
376         cp += INT16SZ;
377         int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
378         cp += INT16SZ;
379         if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
380     }
381     return (0);
382 }
383 
384 /* int
385  * res_queriesmatch(buf1, eom1, buf2, eom2)
386  *	is there a 1:1 mapping of (name,type,class)
387  *	in (buf1,eom1) and (buf2,eom2)?
388  * returns:
389  *	-1 : format error
390  *	0  : not a 1:1 mapping
391  *	>0 : is a 1:1 mapping
392  * author:
393  *	paul vixie, 29may94
394  */
res_queriesmatch(const uint8_t * buf1,const uint8_t * eom1,const uint8_t * buf2,const uint8_t * eom2)395 int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
396                      const uint8_t* eom2) {
397     const uint8_t* cp = buf1 + HFIXEDSZ;
398     int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
399 
400     if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
401 
402     /*
403      * Only header section present in replies to
404      * dynamic update packets.
405      */
406     if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
407         (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
408         return (1);
409 
410     if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
411     while (qdcount-- > 0) {
412         char tname[MAXDNAME + 1];
413         int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
414         if (n < 0) return (-1);
415         cp += n;
416         if (cp + 2 * INT16SZ > eom1) return (-1);
417         int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
418         cp += INT16SZ;
419         int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
420         cp += INT16SZ;
421         if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
422     }
423     return (1);
424 }
425 
addDnsQueryEvent(NetworkDnsEventReported * event)426 static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
427     return event->mutable_dns_query_events()->add_dns_query_event();
428 }
429 
isNetworkRestricted(int terrno)430 static bool isNetworkRestricted(int terrno) {
431     // It's possible that system was in some network restricted mode, which blocked
432     // the operation of sending packet and resulted in EPERM errno.
433     // It would be no reason to keep retrying on that case.
434     // TODO: Check the system status to know if network restricted mode is
435     // enabled.
436     return (terrno == EPERM);
437 }
438 
res_nsend(ResState * statp,span<const uint8_t> msg,span<uint8_t> ans,int * rcode,uint32_t flags,std::chrono::milliseconds sleepTimeMs)439 int res_nsend(ResState* statp, span<const uint8_t> msg, span<uint8_t> ans, int* rcode,
440               uint32_t flags, std::chrono::milliseconds sleepTimeMs) {
441     LOG(DEBUG) << __func__;
442 
443     // Should not happen
444     if (ans.size() < HFIXEDSZ) {
445         // TODO: Remove errno once callers stop using it
446         errno = EINVAL;
447         return -EINVAL;
448     }
449     res_pquery(msg);
450 
451     int anslen = 0;
452     Stopwatch cacheStopwatch;
453     ResolvCacheStatus cache_status = resolv_cache_lookup(statp->netid, msg, ans, &anslen, flags);
454     const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
455     if (cache_status == RESOLV_CACHE_FOUND) {
456         HEADER* hp = (HEADER*)(void*)ans.data();
457         *rcode = hp->rcode;
458         DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
459         dnsQueryEvent->set_latency_micros(cacheLatencyUs);
460         dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
461         dnsQueryEvent->set_type(getQueryType(msg));
462         return anslen;
463     } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
464         // had a cache miss for a known network, so populate the thread private
465         // data so the normal resolve path can do its thing
466         resolv_populate_res_for_net(statp);
467     }
468 
469     // MDNS
470     if (isMdnsResolution(statp->flags)) {
471         // Use an impossible error code as default value.
472         int terrno = ETIME;
473         int resplen = 0;
474         *rcode = RCODE_INTERNAL_ERROR;
475         Stopwatch queryStopwatch;
476         resplen = send_mdns(statp, msg, ans, &terrno, rcode);
477         const IPSockAddr& receivedMdnsAddr =
478                 (getQueryType(msg) == NS_T_AAAA) ? mdns_addrs[0] : mdns_addrs[1];
479         DnsQueryEvent* mDnsQueryEvent = addDnsQueryEvent(statp->event);
480         mDnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
481         mDnsQueryEvent->set_latency_micros(saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
482         mDnsQueryEvent->set_ip_version(ipFamilyToIPVersion(receivedMdnsAddr.family()));
483         mDnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
484         mDnsQueryEvent->set_protocol(PROTO_MDNS);
485         mDnsQueryEvent->set_type(getQueryType(msg));
486         mDnsQueryEvent->set_linux_errno(static_cast<LinuxErrno>(terrno));
487         resolv_stats_add(statp->netid, receivedMdnsAddr, mDnsQueryEvent);
488 
489         if (resplen > 0) {
490             LOG(DEBUG) << __func__ << ": got answer from mDNS:";
491             res_pquery(ans.first(resplen));
492 
493             if (cache_status == RESOLV_CACHE_NOTFOUND) {
494                 resolv_cache_add(statp->netid, msg, std::span(ans.data(), resplen));
495             }
496             return resplen;
497         }
498     }
499 
500     if (statp->nameserverCount() == 0) {
501         // We have no nameservers configured and it's not a MDNS resolution, so there's no
502         // point trying. Tell the cache the query failed, or any retries and anyone else
503         // asking the same question will block for PENDING_REQUEST_TIMEOUT seconds instead
504         // of failing fast.
505         _resolv_cache_query_failed(statp->netid, msg, flags);
506         LOG(DEBUG) << __func__ << ": no nameserver";
507         // TODO: Remove errno once callers stop using it
508         errno = ESRCH;
509         return -ESRCH;
510     }
511 
512     // Private DNS
513     if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
514         bool fallback = false;
515         int resplen =
516                 res_private_dns_send(statp, Slice(const_cast<uint8_t*>(msg.data()), msg.size()),
517                                      Slice(ans.data(), ans.size()), rcode, &fallback);
518         if (resplen > 0) {
519             LOG(DEBUG) << __func__ << ": got answer from Private DNS";
520             res_pquery(ans.first(resplen));
521             if (cache_status == RESOLV_CACHE_NOTFOUND) {
522                 resolv_cache_add(statp->netid, msg, ans.first(resplen));
523             }
524             return resplen;
525         }
526         if (!fallback) {
527             _resolv_cache_query_failed(statp->netid, msg, flags);
528             LOG(DEBUG) << __func__ << ": private DNS failed";
529             return -ETIMEDOUT;
530         }
531     }
532 
533     // If parallel_lookup is enabled, it might be required to wait some time to avoid
534     // gateways from dropping packets if queries are sent too close together.
535     if (sleepTimeMs != 0ms) {
536         std::this_thread::sleep_for(sleepTimeMs);
537     }
538 
539     res_stats stats[MAXNS]{};
540     res_params params;
541     int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats, statp->nsaddrs);
542     if (revision_id < 0) {
543         LOG(ERROR) << __func__ << ": revision_id < 0";
544         // TODO: Remove errno once callers stop using it
545         errno = ESRCH;
546         return -ESRCH;
547     }
548 
549     bool usable_servers[MAXNS];
550     int usableServersCount = android_net_res_stats_get_usable_servers(
551             &params, stats, statp->nameserverCount(), usable_servers);
552 
553     if (statp->sort_nameservers) {
554         // It's unnecessary to mark a DNS server as unusable since broken servers will be less
555         // likely to be chosen.
556         for (int i = 0; i < statp->nameserverCount(); i++) {
557             usable_servers[i] = true;
558         }
559     }
560 
561     // TODO: Let it always choose the first nameserver when sort_nameservers is enabled.
562     if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
563         auto hp = reinterpret_cast<const HEADER*>(msg.data());
564 
565         // Select a random server based on the query id
566         int selectedServer = (hp->id % usableServersCount) + 1;
567         res_set_usable_server(selectedServer, statp->nameserverCount(), usable_servers);
568     }
569 
570     // Send request, RETRY times, or until successful.
571     int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
572     int useTcp = msg.size() > PACKETSZ;
573     int gotsomewhere = 0;
574 
575     // Use an impossible error code as default value
576     int terrno = ETIME;
577     // plaintext DNS
578     for (int attempt = 0; attempt < retryTimes; ++attempt) {
579         for (size_t ns = 0; ns < statp->nsaddrs.size(); ++ns) {
580             if (!usable_servers[ns]) continue;
581 
582             *rcode = RCODE_INTERNAL_ERROR;
583             LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
584                        << ") address = " << statp->nsaddrs[ns].toString();
585 
586             ::android::net::Protocol query_proto = useTcp ? PROTO_TCP : PROTO_UDP;
587             const time_t query_time = time(nullptr);
588             int delay = 0;
589             bool fallbackTCP = false;
590             const bool shouldRecordStats = (attempt == 0);
591             int resplen;
592             Stopwatch queryStopwatch;
593             int retry_count_for_event = 0;
594             size_t actualNs = ns;
595             // Use an impossible error code as default value
596             terrno = ETIME;
597             if (useTcp) {
598                 // TCP; at most one attempt per server.
599                 attempt = retryTimes;
600                 resplen = send_vc(statp, &params, msg, ans, &terrno, ns, rcode);
601                 delay = elapsedTimeInMs(statp->tcp_nssock_ts);
602 
603                 if (msg.size() <= PACKETSZ && resplen <= 0 &&
604                     statp->tc_mode == aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP) {
605                     // reset to UDP for next query on next DNS server if resolver is currently doing
606                     // TCP fallback retry and current server does not support TCP connectin
607                     useTcp = false;
608                 }
609                 LOG(INFO) << __func__ << ": used send_vc " << resplen << " terrno: " << terrno;
610             } else {
611                 // UDP
612                 resplen = send_dg(statp, &params, msg, ans, &terrno, &actualNs, &useTcp,
613                                   &gotsomewhere, rcode);
614                 delay = elapsedTimeInMs(statp->udpsocks_ts[actualNs]);
615                 fallbackTCP = useTcp ? true : false;
616                 retry_count_for_event = attempt;
617                 LOG(INFO) << __func__ << ": used send_dg " << resplen << " terrno: " << terrno;
618             }
619 
620             const IPSockAddr& receivedServerAddr = statp->nsaddrs[actualNs];
621             DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
622             dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
623             // When |retryTimes| > 1, we cannot actually know the correct latency value if we
624             // received the answer from the previous server. So temporarily set the latency as -1 if
625             // that condition happened.
626             // TODO: make the latency value accurate.
627             dnsQueryEvent->set_latency_micros(
628                     (actualNs == ns) ? saturate_cast<int32_t>(queryStopwatch.timeTakenUs()) : -1);
629             dnsQueryEvent->set_dns_server_index(actualNs);
630             dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(receivedServerAddr.family()));
631             dnsQueryEvent->set_retry_times(retry_count_for_event);
632             dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
633             dnsQueryEvent->set_protocol(query_proto);
634             dnsQueryEvent->set_type(getQueryType(msg));
635             dnsQueryEvent->set_linux_errno(static_cast<LinuxErrno>(terrno));
636 
637             // Only record stats the first time we try a query. This ensures that
638             // queries that deterministically fail (e.g., a name that always returns
639             // SERVFAIL or times out) do not unduly affect the stats.
640             if (shouldRecordStats) {
641                 // (b/151166599): This is a workaround to prevent that DnsResolver calculates the
642                 // reliability of DNS servers from being broken when network restricted mode is
643                 // enabled.
644                 // TODO: Introduce the new server selection instead of skipping stats recording.
645                 if (!isNetworkRestricted(terrno)) {
646                     res_sample sample;
647                     res_stats_set_sample(&sample, query_time, *rcode, delay);
648                     resolv_cache_add_resolver_stats_sample(statp->netid, revision_id,
649                                                            receivedServerAddr, sample,
650                                                            params.max_samples);
651                     resolv_stats_add(statp->netid, receivedServerAddr, dnsQueryEvent);
652                 }
653             }
654 
655             if (resplen == 0) continue;
656             if (fallbackTCP) {
657                 ns--;
658                 continue;
659             }
660             if (resplen < 0) {
661                 _resolv_cache_query_failed(statp->netid, msg, flags);
662                 statp->closeSockets();
663                 return -terrno;
664             }
665 
666             LOG(DEBUG) << __func__ << ": got answer:";
667             res_pquery(ans.first(resplen));
668 
669             if (cache_status == RESOLV_CACHE_NOTFOUND) {
670                 resolv_cache_add(statp->netid, msg, std::span(ans.data(), resplen));
671             }
672             statp->closeSockets();
673             return (resplen);
674         }  // for each ns
675     }  // for each retry
676     statp->closeSockets();
677     terrno = useTcp ? terrno : gotsomewhere ? ETIMEDOUT : ECONNREFUSED;
678     // TODO: Remove errno once callers stop using it
679     errno = useTcp ? terrno
680                    : gotsomewhere ? ETIMEDOUT /* no answer obtained */
681                                   : ECONNREFUSED /* no nameservers found */;
682 
683     _resolv_cache_query_failed(statp->netid, msg, flags);
684     return -terrno;
685 }
686 
get_timeout(ResState * statp,const res_params * params,const int addrIndex)687 static struct timespec get_timeout(ResState* statp, const res_params* params, const int addrIndex) {
688     int msec;
689     msec = params->base_timeout_msec << addrIndex;
690     // Legacy algorithm which scales the timeout by nameserver number.
691     // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
692     // This has no effect with 1 or 2 nameservers
693     if (addrIndex > 0) {
694         msec /= statp->nameserverCount();
695     }
696     // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
697     if (msec < 1000) {
698         msec = 1000;  // Use at least 1000ms
699     }
700     LOG(DEBUG) << __func__ << ": using timeout of " << msec << " msec";
701 
702     struct timespec result;
703     result.tv_sec = msec / 1000;
704     result.tv_nsec = (msec % 1000) * 1000000;
705     return result;
706 }
707 
send_vc(ResState * statp,res_params * params,span<const uint8_t> msg,span<uint8_t> ans,int * terrno,size_t ns,int * rcode)708 static int send_vc(ResState* statp, res_params* params, span<const uint8_t> msg, span<uint8_t> ans,
709                    int* terrno, size_t ns, int* rcode) {
710     const HEADER* hp = (const HEADER*)(const void*)msg.data();
711     HEADER* anhp = (HEADER*)(void*)ans.data();
712     struct sockaddr* nsap;
713     int nsaplen;
714     int truncating, connreset, n;
715     uint8_t* cp;
716 
717     LOG(DEBUG) << __func__ << ": using send_vc";
718 
719     // It should never happen, but just in case.
720     if (ns >= statp->nsaddrs.size()) {
721         LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
722         *terrno = EINVAL;
723         return -1;
724     }
725 
726     sockaddr_storage ss = statp->nsaddrs[ns];
727     nsap = reinterpret_cast<sockaddr*>(&ss);
728     nsaplen = sockaddrSize(nsap);
729 
730     connreset = 0;
731 same_ns:
732     truncating = 0;
733 
734     /* Are we still talking to whom we want to talk to? */
735     if (statp->tcp_nssock >= 0 && (statp->flags & RES_F_VC) != 0) {
736         struct sockaddr_storage peer;
737         socklen_t size = sizeof peer;
738         unsigned old_mark;
739         socklen_t mark_size = sizeof(old_mark);
740         if (getpeername(statp->tcp_nssock, (struct sockaddr*)(void*)&peer, &size) < 0 ||
741             !sock_eq((struct sockaddr*)(void*)&peer, nsap) ||
742             getsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
743             old_mark != statp->mark) {
744             statp->closeSockets();
745         }
746     }
747 
748     if (statp->tcp_nssock < 0 || (statp->flags & RES_F_VC) == 0) {
749         if (statp->tcp_nssock >= 0) statp->closeSockets();
750 
751         statp->tcp_nssock.reset(socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0));
752         if (statp->tcp_nssock < 0) {
753             *terrno = errno;
754             PLOG(DEBUG) << __func__ << ": socket(vc): ";
755             switch (errno) {
756                 case EPROTONOSUPPORT:
757                 case EPFNOSUPPORT:
758                 case EAFNOSUPPORT:
759                     return 0;
760                 default:
761                     return -1;
762             }
763         }
764         statp->tcp_nssock_ts = evNowTime();
765         const uid_t uid = statp->enforce_dns_uid ? AID_DNS : statp->uid;
766         resolv_tag_socket(statp->tcp_nssock, uid, statp->pid);
767         if (statp->mark != MARK_UNSET) {
768             if (setsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &statp->mark,
769                            sizeof(statp->mark)) < 0) {
770                 *terrno = errno;
771                 PLOG(DEBUG) << __func__ << ": setsockopt: ";
772                 return -1;
773             }
774         }
775         errno = 0;
776         if (random_bind(statp->tcp_nssock, nsap->sa_family) < 0) {
777             *terrno = errno;
778             dump_error("bind/vc", nsap);
779             statp->closeSockets();
780             return (0);
781         }
782         if (connect_with_timeout(statp->tcp_nssock, nsap, (socklen_t)nsaplen,
783                                  get_timeout(statp, params, ns)) < 0) {
784             *terrno = errno;
785             dump_error("connect/vc", nsap);
786             statp->closeSockets();
787             /*
788              * The way connect_with_timeout() is implemented prevents us from reliably
789              * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
790              * currently both cases are handled in the same way, there is no need to
791              * change this (yet). If we ever need to reliably distinguish between these
792              * cases, both connect_with_timeout() and retrying_poll() need to be
793              * modified, though.
794              */
795             *rcode = RCODE_TIMEOUT;
796             return (0);
797         }
798         statp->flags |= RES_F_VC;
799     }
800 
801     /*
802      * Send length & message
803      */
804     uint16_t len = htons(static_cast<uint16_t>(msg.size()));
805     const iovec iov[] = {
806             {.iov_base = &len, .iov_len = INT16SZ},
807             {.iov_base = const_cast<uint8_t*>(msg.data()),
808              .iov_len = static_cast<size_t>(msg.size())},
809     };
810     if (writev(statp->tcp_nssock, iov, 2) != static_cast<ptrdiff_t>(INT16SZ + msg.size())) {
811         *terrno = errno;
812         PLOG(DEBUG) << __func__ << ": write failed: ";
813         statp->closeSockets();
814         return (0);
815     }
816     /*
817      * Receive length & response
818      */
819 read_len:
820     cp = ans.data();
821     len = INT16SZ;
822     while ((n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
823         cp += n;
824         if ((len -= n) == 0) break;
825     }
826     if (n <= 0) {
827         *terrno = errno;
828         PLOG(DEBUG) << __func__ << ": read failed: ";
829         statp->closeSockets();
830         /*
831          * A long running process might get its TCP
832          * connection reset if the remote server was
833          * restarted.  Requery the server instead of
834          * trying a new one.  When there is only one
835          * server, this means that a query might work
836          * instead of failing.  We only allow one reset
837          * per query to prevent looping.
838          */
839         if (*terrno == ECONNRESET && !connreset) {
840             connreset = 1;
841             goto same_ns;
842         }
843         return (0);
844     }
845     uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans.data()));
846     if (resplen > ans.size()) {
847         LOG(DEBUG) << __func__ << ": response truncated";
848         truncating = 1;
849         len = ans.size();
850     } else
851         len = resplen;
852     if (len < HFIXEDSZ) {
853         /*
854          * Undersized message.
855          */
856         LOG(DEBUG) << __func__ << ": undersized: " << len;
857         *terrno = EMSGSIZE;
858         statp->closeSockets();
859         return (0);
860     }
861     cp = ans.data();
862     while (len != 0 && (n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
863         cp += n;
864         len -= n;
865     }
866     if (n <= 0) {
867         *terrno = errno;
868         PLOG(DEBUG) << __func__ << ": read(vc): ";
869         statp->closeSockets();
870         return (0);
871     }
872 
873     if (truncating) {
874         /*
875          * Flush rest of answer so connection stays in synch.
876          */
877         anhp->tc = 1;
878         len = resplen - ans.size();
879         while (len != 0) {
880             char junk[PACKETSZ];
881 
882             n = read(statp->tcp_nssock, junk, (len > sizeof junk) ? sizeof junk : len);
883             if (n > 0)
884                 len -= n;
885             else
886                 break;
887         }
888         LOG(WARNING) << __func__ << ": resplen " << resplen << " exceeds buf size " << ans.size();
889         // return size should never exceed container size
890         resplen = ans.size();
891     }
892     /*
893      * If the calling application has bailed out of
894      * a previous call and failed to arrange to have
895      * the circuit closed or the server has got
896      * itself confused, then drop the packet and
897      * wait for the correct one.
898      */
899     if (hp->id != anhp->id) {
900         LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
901         res_pquery({ans.data(), resplen});
902         goto read_len;
903     }
904 
905     /*
906      * All is well, or the error is fatal.  Signal that the
907      * next nameserver ought not be tried.
908      */
909     if (resplen > 0) {
910         *rcode = anhp->rcode;
911     }
912     *terrno = 0;
913     return (resplen);
914 }
915 
916 /* return -1 on error (errno set), 0 on success */
connect_with_timeout(int sock,const sockaddr * nsap,socklen_t salen,const timespec timeout)917 static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
918                                 const timespec timeout) {
919     int res, origflags;
920 
921     origflags = fcntl(sock, F_GETFL, 0);
922     fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
923 
924     res = connect(sock, nsap, salen);
925     if (res < 0 && errno != EINPROGRESS) {
926         res = -1;
927         goto done;
928     }
929     if (res != 0) {
930         timespec now = evNowTime();
931         timespec finish = evAddTime(now, timeout);
932         LOG(DEBUG) << __func__ << ": " << sock << " send_vc";
933         res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
934         if (res <= 0) {
935             res = -1;
936         }
937     }
938 done:
939     fcntl(sock, F_SETFL, origflags);
940     LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
941     return res;
942 }
943 
retrying_poll(const int sock,const short events,const struct timespec * finish)944 static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
945     struct timespec now, timeout;
946 
947 retry:
948     LOG(DEBUG) << __func__ << ": " << sock << " retrying_poll";
949 
950     now = evNowTime();
951     if (evCmpTime(*finish, now) > 0)
952         timeout = evSubTime(*finish, now);
953     else
954         timeout = evConsTime(0L, 0L);
955     struct pollfd fds = {.fd = sock, .events = events};
956     int n = ppoll(&fds, 1, &timeout, /*__mask=*/NULL);
957     if (n == 0) {
958         LOG(DEBUG) << __func__ << ": " << sock << " retrying_poll timeout";
959         errno = ETIMEDOUT;
960         return 0;
961     }
962     if (n < 0) {
963         if (errno == EINTR) goto retry;
964         PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
965         return n;
966     }
967     if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
968         int error;
969         socklen_t len = sizeof(error);
970         if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
971             errno = error;
972             PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
973             return -1;
974         }
975     }
976     LOG(DEBUG) << __func__ << ": " << sock << " retrying_poll returning " << n;
977     return n;
978 }
979 
extractUdpFdset(ResState * statp,const short events=POLLIN)980 static std::vector<pollfd> extractUdpFdset(ResState* statp, const short events = POLLIN) {
981     std::vector<pollfd> fdset(statp->nsaddrs.size());
982     for (size_t i = 0; i < statp->nsaddrs.size(); ++i) {
983         fdset[i] = {.fd = statp->udpsocks[i], .events = events};
984     }
985     return fdset;
986 }
987 
udpRetryingPoll(ResState * statp,const timespec * finish)988 static Result<std::vector<int>> udpRetryingPoll(ResState* statp, const timespec* finish) {
989     for (;;) {
990         LOG(DEBUG) << __func__ << ": poll";
991         timespec start_time = evNowTime();
992         timespec timeout = (evCmpTime(*finish, start_time) > 0) ? evSubTime(*finish, start_time)
993                                                                 : evConsTime(0L, 0L);
994         std::vector<pollfd> fdset = extractUdpFdset(statp);
995         const int n = ppoll(fdset.data(), fdset.size(), &timeout, /*__mask=*/nullptr);
996         if (n <= 0) {
997             if (errno == EINTR && n < 0) continue;
998             if (n == 0) errno = ETIMEDOUT;
999             PLOG(INFO) << __func__ << ": failed";
1000             return ErrnoError();
1001         }
1002         std::vector<int> fdsToRead;
1003         for (const auto& pollfd : fdset) {
1004             if (pollfd.revents & (POLLIN | POLLERR)) {
1005                 fdsToRead.push_back(pollfd.fd);
1006             }
1007         }
1008         LOG(DEBUG) << __func__ << ": "
1009                    << " returning fd size: " << fdsToRead.size();
1010         return fdsToRead;
1011     }
1012 }
1013 
udpRetryingPollWrapper(ResState * statp,int addrInfo,const timespec * finish)1014 static Result<std::vector<int>> udpRetryingPollWrapper(ResState* statp, int addrInfo,
1015                                                        const timespec* finish) {
1016     const bool keepListeningUdp =
1017             android::net::Experiments::getInstance()->getFlag("keep_listening_udp", 0);
1018     if (keepListeningUdp) return udpRetryingPoll(statp, finish);
1019 
1020     if (int n = retrying_poll(statp->udpsocks[addrInfo], POLLIN, finish); n <= 0) {
1021         return ErrnoError();
1022     }
1023     return std::vector<int>{statp->udpsocks[addrInfo]};
1024 }
1025 
ignoreInvalidAnswer(ResState * statp,const sockaddr_storage & from,span<const uint8_t> msg,span<uint8_t> ans,int * receivedFromNs)1026 bool ignoreInvalidAnswer(ResState* statp, const sockaddr_storage& from, span<const uint8_t> msg,
1027                          span<uint8_t> ans, int* receivedFromNs) {
1028     const HEADER* hp = (const HEADER*)(const void*)msg.data();
1029     HEADER* anhp = (HEADER*)(void*)ans.data();
1030     if (hp->id != anhp->id) {
1031         // response from old query, ignore it.
1032         LOG(DEBUG) << __func__ << ": old answer:";
1033         return true;
1034     }
1035     if (*receivedFromNs = res_ourserver_p(statp, (sockaddr*)(void*)&from); *receivedFromNs < 0) {
1036         // response from wrong server? ignore it.
1037         LOG(DEBUG) << __func__ << ": not our server:";
1038         return true;
1039     }
1040     if (!res_queriesmatch(msg.data(), msg.data() + msg.size(), ans.data(),
1041                           ans.data() + ans.size())) {
1042         // response contains wrong query? ignore it.
1043         LOG(DEBUG) << __func__ << ": wrong query name:";
1044         return true;
1045     }
1046     return false;
1047 }
1048 
1049 // return  1 - setup udp socket success.
1050 // return  0 - bind error, protocol error.
1051 // return -1 - create socket fail, except |EPROTONOSUPPORT| EPFNOSUPPORT |EAFNOSUPPORT|.
1052 //             set socket option fail.
setupUdpSocket(ResState * statp,const sockaddr * sockap,unique_fd * fd_out,int * terrno)1053 static int setupUdpSocket(ResState* statp, const sockaddr* sockap, unique_fd* fd_out, int* terrno) {
1054     fd_out->reset(socket(sockap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1055 
1056     if (*fd_out < 0) {
1057         *terrno = errno;
1058         PLOG(ERROR) << __func__ << ": socket: ";
1059         switch (errno) {
1060             case EPROTONOSUPPORT:
1061             case EPFNOSUPPORT:
1062             case EAFNOSUPPORT:
1063                 return 0;
1064             default:
1065                 return -1;
1066         }
1067     }
1068     const uid_t uid = statp->enforce_dns_uid ? AID_DNS : statp->uid;
1069     resolv_tag_socket(*fd_out, uid, statp->pid);
1070     if (statp->mark != MARK_UNSET) {
1071         if (setsockopt(*fd_out, SOL_SOCKET, SO_MARK, &(statp->mark), sizeof(statp->mark)) < 0) {
1072             *terrno = errno;
1073             return -1;
1074         }
1075     }
1076 
1077     if (random_bind(*fd_out, sockap->sa_family) < 0) {
1078         *terrno = errno;
1079         dump_error("bind", sockap);
1080         return 0;
1081     }
1082     return 1;
1083 }
1084 
send_dg(ResState * statp,res_params * params,span<const uint8_t> msg,span<uint8_t> ans,int * terrno,size_t * ns,int * v_circuit,int * gotsomewhere,int * rcode)1085 static int send_dg(ResState* statp, res_params* params, span<const uint8_t> msg, span<uint8_t> ans,
1086                    int* terrno, size_t* ns, int* v_circuit, int* gotsomewhere, int* rcode) {
1087     // It should never happen, but just in case.
1088     if (*ns >= statp->nsaddrs.size()) {
1089         LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
1090         *terrno = EINVAL;
1091         return -1;
1092     }
1093 
1094     const sockaddr_storage ss = statp->nsaddrs[*ns];
1095     const sockaddr* nsap = reinterpret_cast<const sockaddr*>(&ss);
1096 
1097     if (statp->udpsocks[*ns] == -1) {
1098         int result = setupUdpSocket(statp, nsap, &statp->udpsocks[*ns], terrno);
1099         if (result <= 0) return result;
1100         statp->udpsocks_ts[*ns] = evNowTime();
1101 
1102         // Use a "connected" datagram socket to receive an ECONNREFUSED error
1103         // on the next socket operation when the server responds with an
1104         // ICMP port-unreachable error. This way we can detect the absence of
1105         // a nameserver without timing out.
1106         if (connect(statp->udpsocks[*ns], nsap, sockaddrSize(nsap)) < 0) {
1107             *terrno = errno;
1108             dump_error("connect(dg)", nsap);
1109             statp->closeSockets();
1110             return 0;
1111         }
1112         LOG(DEBUG) << __func__ << ": new DG socket";
1113     }
1114     if (send(statp->udpsocks[*ns], msg.data(), msg.size(), 0) !=
1115         static_cast<ptrdiff_t>(msg.size())) {
1116         *terrno = errno;
1117         PLOG(DEBUG) << __func__ << ": send: ";
1118         statp->closeSockets();
1119         return 0;
1120     }
1121 
1122     timespec timeout = get_timeout(statp, params, *ns);
1123     timespec start_time = evNowTime();
1124     timespec finish = evAddTime(start_time, timeout);
1125     for (;;) {
1126         // Wait for reply.
1127         auto result = udpRetryingPollWrapper(statp, *ns, &finish);
1128 
1129         if (!result.has_value()) {
1130             const bool isTimeout = (result.error().code() == ETIMEDOUT);
1131             *rcode = (isTimeout) ? RCODE_TIMEOUT : *rcode;
1132             *terrno = (isTimeout) ? ETIMEDOUT : errno;
1133             *gotsomewhere = (isTimeout) ? 1 : *gotsomewhere;
1134             // Leave the UDP sockets open on timeout so we can keep listening for
1135             // a late response from this server while retrying on the next server.
1136             if (!isTimeout) statp->closeSockets();
1137             LOG(DEBUG) << __func__ << ": " << (isTimeout ? "timeout" : "poll");
1138             return 0;
1139         }
1140         bool needRetry = false;
1141         for (int fd : result.value()) {
1142             needRetry = false;
1143             sockaddr_storage from;
1144             socklen_t fromlen = sizeof(from);
1145             int resplen =
1146                     recvfrom(fd, ans.data(), ans.size(), 0, (sockaddr*)(void*)&from, &fromlen);
1147             if (resplen <= 0) {
1148                 *terrno = errno;
1149                 PLOG(DEBUG) << __func__ << ": recvfrom: ";
1150                 continue;
1151             }
1152             *gotsomewhere = 1;
1153             if (resplen < HFIXEDSZ) {
1154                 // Undersized message.
1155                 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
1156                 *terrno = EMSGSIZE;
1157                 continue;
1158             }
1159             if (resplen > static_cast<ptrdiff_t>(ans.size())) {
1160                 LOG(FATAL) << __func__ << ": invalid resplen (too large): " << resplen;
1161             }
1162 
1163             int receivedFromNs = *ns;
1164             if (needRetry = ignoreInvalidAnswer(statp, from, msg, ans, &receivedFromNs);
1165                 needRetry) {
1166                 res_pquery(ans.first(resplen));
1167                 continue;
1168             }
1169 
1170             HEADER* anhp = (HEADER*)(void*)ans.data();
1171             if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
1172                 //  Do not retry if the server do not understand EDNS0.
1173                 //  The case has to be captured here, as FORMERR packet do not
1174                 //  carry query section, hence res_queriesmatch() returns 0.
1175                 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
1176                 res_pquery(ans.first(resplen));
1177                 // record the error
1178                 statp->flags |= RES_F_EDNS0ERR;
1179                 *terrno = EREMOTEIO;
1180                 continue;
1181             }
1182 
1183             if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1184                 LOG(DEBUG) << __func__ << ": server rejected query:";
1185                 res_pquery(ans.first(resplen));
1186                 *rcode = anhp->rcode;
1187                 continue;
1188             }
1189             if (anhp->tc) {
1190                 // To get the rest of answer,
1191                 // use TCP with same server.
1192                 LOG(DEBUG) << __func__ << ": truncated answer";
1193                 *terrno = E2BIG;
1194                 *v_circuit = 1;
1195                 return 1;
1196             }
1197             // All is well, or the error is fatal. Signal that the
1198             // next nameserver ought not be tried.
1199 
1200             *rcode = anhp->rcode;
1201             *ns = receivedFromNs;
1202             *terrno = 0;
1203             return resplen;
1204         }
1205         if (!needRetry) return 0;
1206     }
1207 }
1208 
1209 // return length - when receiving valid packets.
1210 // return 0      - when mdns packets transfer error.
send_mdns(ResState * statp,span<const uint8_t> msg,span<uint8_t> ans,int * terrno,int * rcode)1211 static int send_mdns(ResState* statp, span<const uint8_t> msg, span<uint8_t> ans, int* terrno,
1212                      int* rcode) {
1213     const sockaddr_storage ss = (getQueryType(msg) == NS_T_AAAA) ? mdns_addrs[0] : mdns_addrs[1];
1214     const sockaddr* mdnsap = reinterpret_cast<const sockaddr*>(&ss);
1215     unique_fd fd;
1216 
1217     if (setupUdpSocket(statp, mdnsap, &fd, terrno) <= 0) return 0;
1218 
1219     if (sendto(fd, msg.data(), msg.size(), 0, mdnsap, sockaddrSize(mdnsap)) !=
1220         static_cast<ptrdiff_t>(msg.size())) {
1221         *terrno = errno;
1222         return 0;
1223     }
1224     // RFC 6762: Typically, the timeout would also be shortened to two or three seconds.
1225     const struct timespec finish = evAddTime(evNowTime(), {2, 2000000});
1226 
1227     // Wait for reply.
1228     if (retrying_poll(fd, POLLIN, &finish) <= 0) {
1229         *terrno = errno;
1230         if (*terrno == ETIMEDOUT) *rcode = RCODE_TIMEOUT;
1231         LOG(ERROR) << __func__ << ": " << ((*terrno == ETIMEDOUT) ? "timeout" : "poll failed");
1232         return 0;
1233     }
1234 
1235     sockaddr_storage from;
1236     socklen_t fromlen = sizeof(from);
1237     int resplen = recvfrom(fd, ans.data(), ans.size(), 0, (sockaddr*)(void*)&from, &fromlen);
1238 
1239     if (resplen <= 0) {
1240         *terrno = errno;
1241         return 0;
1242     }
1243 
1244     if (resplen < HFIXEDSZ) {
1245         // Undersized message.
1246         LOG(ERROR) << __func__ << ": undersized: " << resplen;
1247         *terrno = EMSGSIZE;
1248         return 0;
1249     }
1250 
1251     HEADER* anhp = (HEADER*)(void*)ans.data();
1252     if (anhp->tc) {
1253         LOG(DEBUG) << __func__ << ": truncated answer";
1254         *terrno = E2BIG;
1255         return 0;
1256     }
1257 
1258     *rcode = anhp->rcode;
1259     *terrno = 0;
1260     return resplen;
1261 }
1262 
dump_error(const char * str,const struct sockaddr * address)1263 static void dump_error(const char* str, const struct sockaddr* address) {
1264     char hbuf[NI_MAXHOST];
1265     char sbuf[NI_MAXSERV];
1266     constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
1267     const int err = errno;
1268 
1269     if (!WOULD_LOG(DEBUG)) return;
1270 
1271     if (getnameinfo(address, sockaddrSize(address), hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
1272                     niflags)) {
1273         strncpy(hbuf, "?", sizeof(hbuf) - 1);
1274         hbuf[sizeof(hbuf) - 1] = '\0';
1275         strncpy(sbuf, "?", sizeof(sbuf) - 1);
1276         sbuf[sizeof(sbuf) - 1] = '\0';
1277     }
1278     errno = err;
1279     PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
1280 }
1281 
sock_eq(struct sockaddr * a,struct sockaddr * b)1282 static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1283     struct sockaddr_in *a4, *b4;
1284     struct sockaddr_in6 *a6, *b6;
1285 
1286     if (a->sa_family != b->sa_family) return 0;
1287     switch (a->sa_family) {
1288         case AF_INET:
1289             a4 = (struct sockaddr_in*) (void*) a;
1290             b4 = (struct sockaddr_in*) (void*) b;
1291             return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1292         case AF_INET6:
1293             a6 = (struct sockaddr_in6*) (void*) a;
1294             b6 = (struct sockaddr_in6*) (void*) b;
1295             return a6->sin6_port == b6->sin6_port &&
1296 #ifdef HAVE_SIN6_SCOPE_ID
1297                    a6->sin6_scope_id == b6->sin6_scope_id &&
1298 #endif
1299                    IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1300         default:
1301             return 0;
1302     }
1303 }
1304 
res_private_dns_send(ResState * statp,const Slice query,const Slice answer,int * rcode,bool * fallback)1305 static int res_private_dns_send(ResState* statp, const Slice query, const Slice answer, int* rcode,
1306                                 bool* fallback) {
1307     const unsigned netId = statp->netid;
1308 
1309     auto& privateDnsConfiguration = PrivateDnsConfiguration::getInstance();
1310     PrivateDnsStatus privateDnsStatus = privateDnsConfiguration.getStatus(netId);
1311     statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
1312 
1313     ssize_t result = -1;
1314     switch (privateDnsStatus.mode) {
1315         case PrivateDnsMode::OFF: {
1316             *fallback = true;
1317             return -1;
1318         }
1319         case PrivateDnsMode::OPPORTUNISTIC: {
1320             *fallback = true;
1321             if (privateDnsStatus.hasValidatedDohServers()) {
1322                 result = res_doh_send(statp, query, answer, rcode);
1323                 if (result != DOH_RESULT_CAN_NOT_SEND) return result;
1324             }
1325             return res_tls_send(privateDnsStatus.validatedServers(), statp, query, answer, rcode,
1326                                 privateDnsStatus.mode);
1327         }
1328         case PrivateDnsMode::STRICT: {
1329             *fallback = false;
1330             if (privateDnsStatus.hasValidatedDohServers()) {
1331                 result = res_doh_send(statp, query, answer, rcode);
1332                 if (result != DOH_RESULT_CAN_NOT_SEND) return result;
1333             }
1334             if (privateDnsStatus.validatedServers().empty()) {
1335                 // Sleep and iterate some small number of times checking for the
1336                 // arrival of resolved and validated server IP addresses, instead
1337                 // of returning an immediate error.
1338                 // This is needed because as soon as a network becomes the default network, apps
1339                 // will send DNS queries on that network. If no servers have yet validated, and we
1340                 // do not block those queries, they would immediately fail, causing
1341                 // application-visible errors. Note that this can happen even before the network
1342                 // validates, since an unvalidated network can become the default network if no
1343                 // validated networks are available.
1344                 //
1345                 // TODO: see if there is a better way to address this problem, such as buffering the
1346                 // queries in a queue or only blocking queries for the first few seconds after a
1347                 // default network change.
1348                 for (int i = 0; i < 42; i++) {
1349                     std::this_thread::sleep_for(std::chrono::milliseconds(100));
1350 
1351                     // Calling getStatus() to merely check if there's any validated server seems
1352                     // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed
1353                     // ups.
1354                     privateDnsStatus = privateDnsConfiguration.getStatus(netId);
1355 
1356                     if (privateDnsStatus.hasValidatedDohServers()) {
1357                         result = res_doh_send(statp, query, answer, rcode);
1358                         if (result != DOH_RESULT_CAN_NOT_SEND) return result;
1359                     }
1360 
1361                     // Switch to use the DoT servers if they are validated.
1362                     if (!privateDnsStatus.validatedServers().empty()) {
1363                         break;
1364                     }
1365                 }
1366             }
1367             return res_tls_send(privateDnsStatus.validatedServers(), statp, query, answer, rcode,
1368                                 privateDnsStatus.mode);
1369         }
1370     }
1371     LOG(ERROR) << __func__ << ": unknown private DNS mode";
1372     return -1;
1373 }
1374 
res_doh_send(ResState * statp,const Slice query,const Slice answer,int * rcode)1375 ssize_t res_doh_send(ResState* statp, const Slice query, const Slice answer, int* rcode) {
1376     auto& privateDnsConfiguration = PrivateDnsConfiguration::getInstance();
1377     const unsigned netId = statp->netid;
1378     LOG(DEBUG) << __func__ << ": performing query over Https";
1379     Stopwatch queryStopwatch;
1380     int queryTimeout = Experiments::getInstance()->getFlag(
1381             "doh_query_timeout_ms", PrivateDnsConfiguration::kDohQueryDefaultTimeoutMs);
1382     if (queryTimeout < 1000) {
1383         queryTimeout = 1000;
1384     }
1385     ssize_t result = privateDnsConfiguration.dohQuery(netId, query, answer, queryTimeout);
1386     LOG(INFO) << __func__ << ": Https query result: " << result << ", netid=" << netId;
1387 
1388     if (result == DOH_RESULT_CAN_NOT_SEND) return DOH_RESULT_CAN_NOT_SEND;
1389 
1390     DnsQueryEvent* dnsQueryEvent = statp->event->mutable_dns_query_events()->add_dns_query_event();
1391     dnsQueryEvent->set_latency_micros(saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
1392     // TODO: Make this information available.
1393     // dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(?));
1394     if (result > 0) {
1395         *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
1396     } else {
1397         *rcode = -result;
1398     }
1399     dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
1400     dnsQueryEvent->set_protocol(PROTO_DOH);
1401     span<const uint8_t> msg(query.base(), query.size());
1402     dnsQueryEvent->set_type(getQueryType(msg));
1403 
1404     auto dohServerAddr = privateDnsConfiguration.getDohServer(netId);
1405     if (dohServerAddr.ok()) {
1406         resolv_stats_add(netId, dohServerAddr.value(), dnsQueryEvent);
1407     }
1408 
1409     return result;
1410 }
1411 
res_tls_send(const std::list<DnsTlsServer> & tlsServers,ResState * statp,const Slice query,const Slice answer,int * rcode,PrivateDnsMode mode)1412 int res_tls_send(const std::list<DnsTlsServer>& tlsServers, ResState* statp, const Slice query,
1413                  const Slice answer, int* rcode, PrivateDnsMode mode) {
1414     if (tlsServers.empty()) return -1;
1415     LOG(DEBUG) << __func__ << ": performing query over TLS";
1416     const bool dotQuickFallback =
1417             (mode == PrivateDnsMode::STRICT)
1418                     ? 0
1419                     : Experiments::getInstance()->getFlag("dot_quick_fallback", 1);
1420     int resplen = 0;
1421     const auto response = DnsTlsDispatcher::getInstance().query(tlsServers, statp, query, answer,
1422                                                                 &resplen, dotQuickFallback);
1423 
1424     LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
1425     if (mode == PrivateDnsMode::OPPORTUNISTIC) {
1426         // In opportunistic mode, handle falling back to cleartext in some
1427         // cases (DNS shouldn't fail if a validated opportunistic mode server
1428         // becomes unreachable for some reason).
1429         switch (response) {
1430             case DnsTlsTransport::Response::success:
1431                 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
1432                 return resplen;
1433             // It's OPPORTUNISTIC mode,
1434             // hence it's not required to do anything because it'll fallback to UDP.
1435             case DnsTlsTransport::Response::network_error:
1436             case DnsTlsTransport::Response::internal_error:
1437             default:
1438                 return -1;
1439         }
1440     } else {
1441         // Strict mode
1442         switch (response) {
1443             case DnsTlsTransport::Response::success:
1444                 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
1445                 return resplen;
1446             case DnsTlsTransport::Response::network_error:
1447                 // This case happens when the query stored in DnsTlsTransport is expired since
1448                 // either 1) the query has been tried for 3 times but no response or 2) fail to
1449                 // establish the connection with the server.
1450                 *rcode = RCODE_TIMEOUT;
1451                 [[fallthrough]];
1452             default:
1453                 return -1;
1454         }
1455     }
1456 }
1457 
resolv_res_nsend(const android_net_context * netContext,span<const uint8_t> msg,span<uint8_t> ans,int * rcode,uint32_t flags,NetworkDnsEventReported * event)1458 int resolv_res_nsend(const android_net_context* netContext, span<const uint8_t> msg,
1459                      span<uint8_t> ans, int* rcode, uint32_t flags,
1460                      NetworkDnsEventReported* event) {
1461     assert(event != nullptr);
1462     ResState res(netContext, event);
1463     resolv_populate_res_for_net(&res);
1464     *rcode = NOERROR;
1465     return res_nsend(&res, msg, ans, rcode, flags);
1466 }
1467 
1468 // Returns the elapsed time in milliseconds since the given time `from`.
elapsedTimeInMs(const timespec & from)1469 int elapsedTimeInMs(const timespec& from) {
1470     const timespec now = evNowTime();
1471     return res_stats_calculate_rtt(&now, &from);
1472 }
1473