• Home
  • History
  • Annotate
  • 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.udpsocks_ts = udpsocks_ts;
111          copy.ndots = ndots;
112          copy.mark = mark;
113          copy.tcp_nssock_ts = tcp_nssock_ts;
114          copy.flags = flags;
115          copy.event = (dnsEvent == nullptr) ? event : dnsEvent;
116          copy.netcontext_flags = netcontext_flags;
117          copy.tc_mode = tc_mode;
118          copy.enforce_dns_uid = enforce_dns_uid;
119          copy.sort_nameservers = sort_nameservers;
120          return copy;
121      }
closeSocketsResState122      void closeSockets() {
123          tcp_nssock.reset();
124          flags &= ~RES_F_VC;
125  
126          for (auto& sock : udpsocks) {
127              sock.reset();
128          }
129      }
130  
nameserverCountResState131      int nameserverCount() { return nsaddrs.size(); }
132  
133      // clang-format off
134      unsigned netid;                             // NetId: cache key and socket mark
135      uid_t uid;                                  // uid of the app that sent the DNS lookup
136      pid_t pid;                                  // pid of the app that sent the DNS lookup
137      std::vector<std::string> search_domains{};  // domains to search
138      std::vector<android::netdutils::IPSockAddr> nsaddrs;
139      std::array<timespec, MAXNS> udpsocks_ts;    // The creation time of the UDP sockets
140      android::base::unique_fd udpsocks[MAXNS];   // UDP sockets to nameservers
141      unsigned ndots : 4 = 1;                     // threshold for initial abs. query
142      unsigned mark;                              // Socket mark to be used by all DNS query sockets
143      android::base::unique_fd tcp_nssock;        // TCP socket (but why not one per nameserver?)
144      timespec tcp_nssock_ts = {};                // The creation time of the TCP socket
145      uint32_t flags = 0;                         // See RES_F_* defines below
146      android::net::NetworkDnsEventReported* event;
147      uint32_t netcontext_flags;
148      int tc_mode = 0;
149      bool enforce_dns_uid = false;
150      bool sort_nameservers = false;              // True if nsaddrs has been sorted.
151      // clang-format on
152  
153    private:
ResStateResState154      ResState() {}
155  };
156  
157  /* End of stats related definitions */
158  
159  /*
160   * Error code extending h_errno codes defined in bionic/libc/include/netdb.h.
161   *
162   * This error code, including legacy h_errno, is returned from res_nquery(), res_nsearch(),
163   * res_nquerydomain(), res_queryN_parallel(), res_searchN() and res_querydomainN() for DNS metrics.
164   *
165   * TODO: Consider mapping legacy and extended h_errno into a unified resolver error code mapping.
166   */
167  #define NETD_RESOLV_H_ERRNO_EXT_TIMEOUT RCODE_TIMEOUT
168  
169  extern const char* const _res_opcodes[];
170  
171  int res_nameinquery(const char*, int, int, const uint8_t*, const uint8_t*);
172  int res_queriesmatch(const uint8_t*, const uint8_t*, const uint8_t*, const uint8_t*);
173  
174  int res_nquery(ResState*, const char*, int, int, std::span<uint8_t>, int*);
175  int res_nsearch(ResState*, const char*, int, int, std::span<uint8_t>, int*);
176  int res_nquerydomain(ResState*, const char*, const char*, int, int, std::span<uint8_t>, int*);
177  int res_nmkquery(int op, const char* qname, int cl, int type, std::span<const uint8_t> data,
178                   std::span<uint8_t> msg, int netcontext_flags);
179  int res_nsend(ResState* statp, std::span<const uint8_t> msg, std::span<uint8_t> ans, int* rcode,
180                uint32_t flags, std::chrono::milliseconds sleepTimeMs = {});
181  int res_nopt(ResState*, int, std::span<uint8_t>, int);
182  
183  int getaddrinfo_numeric(const char* hostname, const char* servname, addrinfo hints,
184                          addrinfo** result);
185  
186  // Helper function for converting h_errno to the error codes visible to netd
187  int herrnoToAiErrno(int herrno);
188  
189  // Helper function to enable MDNS resolution.
190  void setMdnsFlag(std::string_view hostname, unsigned netid, uint32_t* flags);
191  
192  // Helper function for checking MDNS resolution is enabled or not.
193  bool isMdnsResolution(uint32_t flags);
194  
195  // switch resolver log severity
196  android::base::LogSeverity logSeverityStrToEnum(const std::string& logSeverityStr);
197  
198  template <typename Dest>
saturate_cast(int64_t x)199  Dest saturate_cast(int64_t x) {
200      using DestLimits = std::numeric_limits<Dest>;
201      if (x > DestLimits::max()) return DestLimits::max();
202      if (x < DestLimits::min()) return DestLimits::min();
203      return static_cast<Dest>(x);
204  }
205  
is_power_of_2(size_t n)206  constexpr bool is_power_of_2(size_t n) {
207      return n != 0 && (n & (n - 1)) == 0;
208  }
209  
210  // Rounds up a pointer to a char buffer |p| to a multiple of |Alignment| bytes.
211  // Requirements:
212  //   |p| must be a pointer to a byte-sized type (e.g.: uint8_t)
213  //   |Alignment| must be a power of 2
214  template<uintptr_t Alignment = sizeof(void*), typename T>
is_power_of_2(Alignment)215          requires (sizeof(T) == 1) && (is_power_of_2(Alignment))
216  constexpr T* align_ptr(T* const p) {
217      // Written this way to sidestep the performance-no-int-to-ptr clang-tidy warning.
218      constexpr uintptr_t mask = Alignment - 1;
219      const uintptr_t uintptr = reinterpret_cast<uintptr_t>(p);
220      const uintptr_t aligned = (uintptr + mask) & ~mask;
221      const uintptr_t bias = aligned - uintptr;
222      return p + bias;
223  }
224  
225  // Testcases for align_ptr()
226  // TODO: enable when libc++ has std::bit_cast - reinterpret_cast isn't allowed in consteval context
227  // static_assert(align_ptr((char*)1000) == (char*)1000);
228  // static_assert(align_ptr((char*)1001) == (char*)1000 + sizeof(void*));
229  // static_assert(align_ptr((char*)1003) == (char*)1000 + sizeof(void*));
230  // static_assert(align_ptr<sizeof(uint32_t)>((char*)1004) == (char*)1004);
231  // static_assert(align_ptr<sizeof(uint64_t)>((char*)1004) == (char*)1008);
232  
233  android::net::NsType getQueryType(std::span<const uint8_t> msg);
234  
235  android::net::IpVersion ipFamilyToIPVersion(int ipFamily);
236  
resolv_tag_socket(int sock,uid_t uid,pid_t pid)237  inline void resolv_tag_socket(int sock, uid_t uid, pid_t pid) {
238      // This is effectively equivalent to testing for R+
239      if (android::net::gResNetdCallbacks.tagSocket != nullptr) {
240          if (int err = android::net::gResNetdCallbacks.tagSocket(sock, TAG_SYSTEM_DNS, uid, pid)) {
241              LOG(WARNING) << "Failed to tag socket: " << strerror(-err);
242          }
243      }
244  
245      // fchown() apps' uid only in R+, since it's incompatible with Q's ebpf vpn isolation feature.
246      if (fchown(sock, (android::net::gApiLevel >= 30) ? uid : AID_DNS, -1) == -1) {
247          PLOG(WARNING) << "Failed to chown socket";
248      }
249  }
250