• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*	$NetBSD: resolv.h,v 1.31 2005/12/26 19:01:47 perry Exp $	*/
2 
3 /*
4  * Copyright (c) 1983, 1987, 1989
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. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
34  * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
35  *
36  * Permission to use, copy, modify, and distribute this software for any
37  * purpose with or without fee is hereby granted, provided that the above
38  * copyright notice and this permission notice appear in all copies.
39  *
40  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
41  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
42  * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
43  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
44  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
45  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
46  * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
47  */
48 
49 #pragma once
50 
51 #include <android-base/logging.h>
52 #include <android-base/unique_fd.h>
53 #include <private/android_filesystem_config.h>  // AID_DNS
54 
55 #include <net/if.h>
56 #include <time.h>
57 #include <span>
58 #include <string>
59 #include <vector>
60 
61 #include "DnsResolver.h"
62 #include "netd_resolv/resolv.h"
63 #include "params.h"
64 #include "stats.pb.h"
65 
66 // Linux defines MAXHOSTNAMELEN as 64, while the domain name limit in
67 // RFC 1034 and RFC 1035 is 255 octets.
68 #ifdef MAXHOSTNAMELEN
69 #undef MAXHOSTNAMELEN
70 #endif
71 #define MAXHOSTNAMELEN 256
72 
73 /*
74  * Global defines and variables for resolver stub.
75  */
76 #define RES_TIMEOUT 5000 /* min. milliseconds between retries */
77 #define RES_DFLRETRY 2    /* Default #/tries. */
78 
79 // Flags for ResState::flags
80 #define RES_F_VC 0x00000001        // socket is TCP
81 #define RES_F_EDNS0ERR 0x00000004  // EDNS0 caused errors
82 #define RES_F_MDNS 0x00000008      // MDNS packet
83 
84 // Holds either a sockaddr_in or a sockaddr_in6.
85 union sockaddr_union {
86     struct sockaddr sa;
87     struct sockaddr_in sin;
88     struct sockaddr_in6 sin6;
89 };
90 constexpr int MAXPACKET = 8 * 1024;
91 
92 struct ResState {
ResStateResState93     ResState(const android_net_context* netcontext, android::net::NetworkDnsEventReported* dnsEvent)
94         : netid(netcontext->dns_netid),
95           uid(netcontext->uid),
96           pid(netcontext->pid),
97           mark(netcontext->dns_mark),
98           event(dnsEvent),
99           netcontext_flags(netcontext->flags) {}
100 
101     ResState clone(android::net::NetworkDnsEventReported* dnsEvent = nullptr) {
102         // TODO: Separate non-copyable members to other structures and let default copy
103         //       constructor do its work for below copyable members.
104         ResState copy;
105         copy.netid = netid;
106         copy.uid = uid;
107         copy.pid = pid;
108         copy.search_domains = search_domains;
109         copy.nsaddrs = nsaddrs;
110         copy.ndots = ndots;
111         copy.mark = mark;
112         copy.flags = flags;
113         copy.event = (dnsEvent == nullptr) ? event : dnsEvent;
114         copy.netcontext_flags = netcontext_flags;
115         copy.tc_mode = tc_mode;
116         copy.enforce_dns_uid = enforce_dns_uid;
117         copy.sort_nameservers = sort_nameservers;
118         return copy;
119     }
closeSocketsResState120     void closeSockets() {
121         tcp_nssock.reset();
122         flags &= ~RES_F_VC;
123 
124         for (auto& sock : udpsocks) {
125             sock.reset();
126         }
127     }
128 
nameserverCountResState129     int nameserverCount() { return nsaddrs.size(); }
130 
131     // clang-format off
132     unsigned netid;                             // NetId: cache key and socket mark
133     uid_t uid;                                  // uid of the app that sent the DNS lookup
134     pid_t pid;                                  // pid of the app that sent the DNS lookup
135     std::vector<std::string> search_domains{};  // domains to search
136     std::vector<android::netdutils::IPSockAddr> nsaddrs;
137     android::base::unique_fd udpsocks[MAXNS];   // UDP sockets to nameservers
138     unsigned ndots : 4 = 1;                     // threshold for initial abs. query
139     unsigned mark;                              // Socket mark to be used by all DNS query sockets
140     android::base::unique_fd tcp_nssock;        // TCP socket (but why not one per nameserver?)
141     uint32_t flags = 0;                         // See RES_F_* defines below
142     android::net::NetworkDnsEventReported* event;
143     uint32_t netcontext_flags;
144     int tc_mode = 0;
145     bool enforce_dns_uid = false;
146     bool sort_nameservers = false;              // True if nsaddrs has been sorted.
147     // clang-format on
148 
149   private:
ResStateResState150     ResState() {}
151 };
152 
153 /* End of stats related definitions */
154 
155 /*
156  * Error code extending h_errno codes defined in bionic/libc/include/netdb.h.
157  *
158  * This error code, including legacy h_errno, is returned from res_nquery(), res_nsearch(),
159  * res_nquerydomain(), res_queryN(), res_searchN() and res_querydomainN() for DNS metrics.
160  *
161  * TODO: Consider mapping legacy and extended h_errno into a unified resolver error code mapping.
162  */
163 #define NETD_RESOLV_H_ERRNO_EXT_TIMEOUT RCODE_TIMEOUT
164 
165 extern const char* const _res_opcodes[];
166 
167 int res_nameinquery(const char*, int, int, const uint8_t*, const uint8_t*);
168 int res_queriesmatch(const uint8_t*, const uint8_t*, const uint8_t*, const uint8_t*);
169 
170 int res_nquery(ResState*, const char*, int, int, std::span<uint8_t>, int*);
171 int res_nsearch(ResState*, const char*, int, int, std::span<uint8_t>, int*);
172 int res_nquerydomain(ResState*, const char*, const char*, int, int, std::span<uint8_t>, int*);
173 int res_nmkquery(int op, const char* qname, int cl, int type, std::span<const uint8_t> data,
174                  std::span<uint8_t> msg, int netcontext_flags);
175 int res_nsend(ResState* statp, std::span<const uint8_t> msg, std::span<uint8_t> ans, int* rcode,
176               uint32_t flags, std::chrono::milliseconds sleepTimeMs = {});
177 int res_nopt(ResState*, int, std::span<uint8_t>, int);
178 
179 int getaddrinfo_numeric(const char* hostname, const char* servname, addrinfo hints,
180                         addrinfo** result);
181 
182 // Helper function for converting h_errno to the error codes visible to netd
183 int herrnoToAiErrno(int herrno);
184 
185 // Helper function to enable MDNS resolution.
186 void setMdnsFlag(std::string_view hostname, unsigned netid, uint32_t* flags);
187 
188 // Helper function for checking MDNS resolution is enabled or not.
189 bool isMdnsResolution(uint32_t flags);
190 
191 // switch resolver log severity
192 android::base::LogSeverity logSeverityStrToEnum(const std::string& logSeverityStr);
193 
194 template <typename Dest>
saturate_cast(int64_t x)195 Dest saturate_cast(int64_t x) {
196     using DestLimits = std::numeric_limits<Dest>;
197     if (x > DestLimits::max()) return DestLimits::max();
198     if (x < DestLimits::min()) return DestLimits::min();
199     return static_cast<Dest>(x);
200 }
201 
is_power_of_2(size_t n)202 constexpr bool is_power_of_2(size_t n) {
203     return n != 0 && (n & (n - 1)) == 0;
204 }
205 
206 // Rounds up a pointer to a char buffer |p| to a multiple of |Alignment| bytes.
207 // Requirements:
208 //   |p| must be a pointer to a byte-sized type (e.g.: uint8_t)
209 //   |Alignment| must be a power of 2
210 template<uintptr_t Alignment = sizeof(void*), typename T>
is_power_of_2(Alignment)211         requires (sizeof(T) == 1) && (is_power_of_2(Alignment))
212 constexpr T* align_ptr(T* const p) {
213     // Written this way to sidestep the performance-no-int-to-ptr clang-tidy warning.
214     constexpr uintptr_t mask = Alignment - 1;
215     const uintptr_t uintptr = reinterpret_cast<uintptr_t>(p);
216     const uintptr_t aligned = (uintptr + mask) & ~mask;
217     const uintptr_t bias = aligned - uintptr;
218     return p + bias;
219 }
220 
221 // Testcases for align_ptr()
222 // TODO: enable when libc++ has std::bit_cast - reinterpret_cast isn't allowed in consteval context
223 // static_assert(align_ptr((char*)1000) == (char*)1000);
224 // static_assert(align_ptr((char*)1001) == (char*)1000 + sizeof(void*));
225 // static_assert(align_ptr((char*)1003) == (char*)1000 + sizeof(void*));
226 // static_assert(align_ptr<sizeof(uint32_t)>((char*)1004) == (char*)1004);
227 // static_assert(align_ptr<sizeof(uint64_t)>((char*)1004) == (char*)1008);
228 
229 android::net::NsType getQueryType(std::span<const uint8_t> msg);
230 
231 android::net::IpVersion ipFamilyToIPVersion(int ipFamily);
232 
resolv_tag_socket(int sock,uid_t uid,pid_t pid)233 inline void resolv_tag_socket(int sock, uid_t uid, pid_t pid) {
234     // This is effectively equivalent to testing for R+
235     if (android::net::gResNetdCallbacks.tagSocket != nullptr) {
236         if (int err = android::net::gResNetdCallbacks.tagSocket(sock, TAG_SYSTEM_DNS, uid, pid)) {
237             LOG(WARNING) << "Failed to tag socket: " << strerror(-err);
238         }
239     }
240 
241     // fchown() apps' uid only in R+, since it's incompatible with Q's ebpf vpn isolation feature.
242     if (fchown(sock, (android::net::gApiLevel >= 30) ? uid : AID_DNS, -1) == -1) {
243         PLOG(WARNING) << "Failed to chown socket";
244     }
245 }
246