InetAddress.hpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_INETADDRESS_HPP
  14. #define ZT_INETADDRESS_HPP
  15. #include <cstdlib>
  16. #include <cstring>
  17. #include <cstdint>
  18. #include "Constants.hpp"
  19. #include "Utils.hpp"
  20. #include "MAC.hpp"
  21. #include "TriviallyCopyable.hpp"
  22. namespace ZeroTier {
  23. #define ZT_INETADDRESS_MARSHAL_SIZE_MAX 19
  24. #define ZT_INETADDRESS_STRING_SIZE_MAX 64
  25. /**
  26. * C++ class that overlaps in size with sockaddr_storage and adds convenience methods
  27. *
  28. * This is basically a "mixin" for sockaddr_storage. It adds methods and
  29. * operators, but does not modify the structure. This can be cast to/from
  30. * sockaddr_storage and used interchangeably. DO NOT change this by e.g.
  31. * adding non-static fields, since much code depends on this identity.
  32. */
  33. struct InetAddress : public TriviallyCopyable
  34. {
  35. private:
  36. // Internal function to copy any sockaddr_X structure to this one even if it's smaller and unpadded.
  37. template<typename SA>
  38. ZT_INLINE void copySockaddrToThis(const SA *sa) noexcept
  39. {
  40. Utils::copy<sizeof(SA)>(reinterpret_cast<void *>(this),sa);
  41. if (sizeof(SA) < sizeof(InetAddress))
  42. Utils::zero<sizeof(InetAddress) - sizeof(SA)>(reinterpret_cast<uint8_t *>(this) + sizeof(SA));
  43. }
  44. public:
  45. /**
  46. * Loopback IPv4 address (no port)
  47. */
  48. static const InetAddress LO4;
  49. /**
  50. * Loopback IPV6 address (no port)
  51. */
  52. static const InetAddress LO6;
  53. /**
  54. * Null address
  55. */
  56. static const InetAddress NIL;
  57. /**
  58. * IP address scope
  59. *
  60. * Note that these values are in ascending order of path preference and
  61. * MUST remain that way or Path must be changed to reflect. Also be sure
  62. * to change ZT_INETADDRESS_MAX_SCOPE if the max changes.
  63. */
  64. enum IpScope
  65. {
  66. IP_SCOPE_NONE = 0, // NULL or not an IP address
  67. IP_SCOPE_MULTICAST = 1, // 224.0.0.0 and other V4/V6 multicast IPs
  68. IP_SCOPE_LOOPBACK = 2, // 127.0.0.1, ::1, etc.
  69. IP_SCOPE_PSEUDOPRIVATE = 3, // 28.x.x.x, etc. -- unofficially unrouted IPv4 blocks often "bogarted"
  70. IP_SCOPE_GLOBAL = 4, // globally routable IP address (all others)
  71. IP_SCOPE_LINK_LOCAL = 5, // 169.254.x.x, IPv6 LL
  72. IP_SCOPE_SHARED = 6, // currently unused, formerly used for carrier-grade NAT ranges
  73. IP_SCOPE_PRIVATE = 7 // 10.x.x.x, 192.168.x.x, etc.
  74. };
  75. // Hasher for unordered sets and maps in C++11
  76. struct Hasher { ZT_INLINE std::size_t operator()(const InetAddress &a) const noexcept { return (std::size_t)a.hashCode(); } };
  77. ZT_INLINE InetAddress() noexcept { memoryZero(this); }
  78. ZT_INLINE InetAddress(const InetAddress &a) noexcept { memoryCopy(this,&a); }
  79. explicit ZT_INLINE InetAddress(const sockaddr_storage &ss) noexcept { *this = ss; }
  80. explicit ZT_INLINE InetAddress(const sockaddr_storage *ss) noexcept { *this = ss; }
  81. explicit ZT_INLINE InetAddress(const sockaddr &sa) noexcept { *this = sa; }
  82. explicit ZT_INLINE InetAddress(const sockaddr *sa) noexcept { *this = sa; }
  83. explicit ZT_INLINE InetAddress(const sockaddr_in &sa) noexcept { *this = sa; }
  84. explicit ZT_INLINE InetAddress(const sockaddr_in *sa) noexcept { *this = sa; }
  85. explicit ZT_INLINE InetAddress(const sockaddr_in6 &sa) noexcept { *this = sa; }
  86. explicit ZT_INLINE InetAddress(const sockaddr_in6 *sa) noexcept { *this = sa; }
  87. ZT_INLINE InetAddress(const void *ipBytes,unsigned int ipLen,unsigned int port) noexcept { this->set(ipBytes,ipLen,port); }
  88. ZT_INLINE InetAddress(const uint32_t ipv4,unsigned int port) noexcept { this->set(&ipv4,4,port); }
  89. explicit ZT_INLINE InetAddress(const char *ipSlashPort) noexcept { this->fromString(ipSlashPort); }
  90. ZT_INLINE InetAddress &operator=(const InetAddress &a) noexcept
  91. {
  92. memoryCopy(this,a);
  93. return *this;
  94. }
  95. ZT_INLINE InetAddress &operator=(const sockaddr_storage &ss) noexcept
  96. {
  97. memoryCopyUnsafe(this,&ss);
  98. return *this;
  99. }
  100. ZT_INLINE InetAddress &operator=(const sockaddr_storage *ss) noexcept
  101. {
  102. if (ss)
  103. memoryCopyUnsafe(this,ss);
  104. else memoryZero(this);
  105. return *this;
  106. }
  107. ZT_INLINE InetAddress &operator=(const sockaddr_in &sa) noexcept
  108. {
  109. copySockaddrToThis(&sa);
  110. return *this;
  111. }
  112. ZT_INLINE InetAddress &operator=(const sockaddr_in *sa) noexcept
  113. {
  114. if (sa)
  115. copySockaddrToThis(sa);
  116. else memoryZero(this);
  117. return *this;
  118. }
  119. ZT_INLINE InetAddress &operator=(const sockaddr_in6 &sa) noexcept
  120. {
  121. copySockaddrToThis(&sa);
  122. return *this;
  123. }
  124. ZT_INLINE InetAddress &operator=(const sockaddr_in6 *sa) noexcept
  125. {
  126. if (sa)
  127. copySockaddrToThis(sa);
  128. else memoryZero(this);
  129. return *this;
  130. }
  131. ZT_INLINE InetAddress &operator=(const sockaddr &sa) noexcept
  132. {
  133. if (sa.sa_family == AF_INET)
  134. copySockaddrToThis(reinterpret_cast<const sockaddr_in *>(&sa));
  135. else if (sa.sa_family == AF_INET6)
  136. copySockaddrToThis(reinterpret_cast<const sockaddr_in6 *>(&sa));
  137. else memoryZero(this);
  138. return *this;
  139. }
  140. ZT_INLINE InetAddress &operator=(const sockaddr *sa) noexcept
  141. {
  142. if (sa) {
  143. if (sa->sa_family == AF_INET)
  144. copySockaddrToThis(reinterpret_cast<const sockaddr_in *>(sa));
  145. else if (sa->sa_family == AF_INET6)
  146. copySockaddrToThis(reinterpret_cast<const sockaddr_in6 *>(sa));
  147. else memoryZero(this);
  148. } else {
  149. memoryZero(this);
  150. }
  151. return *this;
  152. }
  153. ZT_INLINE void clear() noexcept { memoryZero(this); }
  154. /**
  155. * @return Address family (ss_family in sockaddr_storage)
  156. */
  157. ZT_INLINE uint8_t family() const noexcept { return _data.ss_family; }
  158. /**
  159. * @return IP scope classification (e.g. loopback, link-local, private, global)
  160. */
  161. IpScope ipScope() const noexcept;
  162. /**
  163. * Set from a raw IP and port number
  164. *
  165. * @param ipBytes Bytes of IP address in network byte order
  166. * @param ipLen Length of IP address: 4 or 16
  167. * @param port Port number or 0 for none
  168. */
  169. void set(const void *ipBytes,unsigned int ipLen,unsigned int port) noexcept;
  170. /**
  171. * Set the port component
  172. *
  173. * @param port Port, 0 to 65535
  174. */
  175. ZT_INLINE void setPort(unsigned int port) noexcept
  176. {
  177. switch(_data.ss_family) {
  178. case AF_INET:
  179. reinterpret_cast<struct sockaddr_in *>(this)->sin_port = Utils::hton((uint16_t)port);
  180. break;
  181. case AF_INET6:
  182. reinterpret_cast<struct sockaddr_in6 *>(this)->sin6_port = Utils::hton((uint16_t)port);
  183. break;
  184. }
  185. }
  186. /**
  187. * @return True if this network/netmask route describes a default route (e.g. 0.0.0.0/0)
  188. */
  189. bool isDefaultRoute() const noexcept;
  190. /**
  191. * @return ASCII IP/port format representation
  192. */
  193. char *toString(char buf[ZT_INETADDRESS_STRING_SIZE_MAX]) const noexcept;
  194. /**
  195. * @return IP portion only, in ASCII string format
  196. */
  197. char *toIpString(char buf[ZT_INETADDRESS_STRING_SIZE_MAX]) const noexcept;
  198. /**
  199. * @param ipSlashPort IP/port (port is optional, will be 0 if not included)
  200. * @return True if address appeared to be valid
  201. */
  202. bool fromString(const char *ipSlashPort) noexcept;
  203. /**
  204. * @return Port or 0 if no port component defined
  205. */
  206. ZT_INLINE unsigned int port() const noexcept
  207. {
  208. switch(_data.ss_family) {
  209. case AF_INET: return Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(this)->sin_port));
  210. case AF_INET6: return Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_port));
  211. default: return 0;
  212. }
  213. }
  214. /**
  215. * Alias for port()
  216. *
  217. * This just aliases port() to make code more readable when netmask bits
  218. * are stuffed there, as they are in Network, EthernetTap, and a few other
  219. * spots.
  220. *
  221. * @return Netmask bits
  222. */
  223. ZT_INLINE unsigned int netmaskBits() const noexcept { return port(); }
  224. /**
  225. * @return True if netmask bits is valid for the address type
  226. */
  227. ZT_INLINE bool netmaskBitsValid() const noexcept
  228. {
  229. const unsigned int n = port();
  230. switch(_data.ss_family) {
  231. case AF_INET: return (n <= 32);
  232. case AF_INET6: return (n <= 128);
  233. }
  234. return false;
  235. }
  236. /**
  237. * Alias for port()
  238. *
  239. * This just aliases port() because for gateways we use this field to
  240. * store the gateway metric.
  241. *
  242. * @return Gateway metric
  243. */
  244. ZT_INLINE unsigned int metric() const noexcept { return port(); }
  245. /**
  246. * Construct a full netmask as an InetAddress
  247. *
  248. * @return Netmask such as 255.255.255.0 if this address is /24 (port field will be unchanged)
  249. */
  250. InetAddress netmask() const noexcept;
  251. /**
  252. * Constructs a broadcast address from a network/netmask address
  253. *
  254. * This is only valid for IPv4 and will return a NULL InetAddress for other
  255. * address families.
  256. *
  257. * @return Broadcast address (only IP portion is meaningful)
  258. */
  259. InetAddress broadcast() const noexcept;
  260. /**
  261. * Return the network -- a.k.a. the IP ANDed with the netmask
  262. *
  263. * @return Network e.g. 10.0.1.0/24 from 10.0.1.200/24
  264. */
  265. InetAddress network() const noexcept;
  266. /**
  267. * Test whether this IPv6 prefix matches the prefix of a given IPv6 address
  268. *
  269. * @param addr Address to check
  270. * @return True if this IPv6 prefix matches the prefix of a given IPv6 address
  271. */
  272. bool isEqualPrefix(const InetAddress &addr) const noexcept;
  273. /**
  274. * Test whether this IP/netmask contains this address
  275. *
  276. * @param addr Address to check
  277. * @return True if this IP/netmask (route) contains this address
  278. */
  279. bool containsAddress(const InetAddress &addr) const noexcept;
  280. /**
  281. * @return True if this is an IPv4 address
  282. */
  283. ZT_INLINE bool isV4() const noexcept { return (family() == AF_INET); }
  284. /**
  285. * @return True if this is an IPv6 address
  286. */
  287. ZT_INLINE bool isV6() const noexcept { return (family() == AF_INET6); }
  288. /**
  289. * @return pointer to raw address bytes or NULL if not available
  290. */
  291. ZT_INLINE const void *rawIpData() const noexcept
  292. {
  293. switch(_data.ss_family) {
  294. case AF_INET: return (const void *)&(reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr);
  295. case AF_INET6: return (const void *)(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
  296. default: return nullptr;
  297. }
  298. }
  299. /**
  300. * @return InetAddress containing only the IP portion of this address and a zero port, or NULL if not IPv4 or IPv6
  301. */
  302. ZT_INLINE InetAddress ipOnly() const noexcept
  303. {
  304. InetAddress r;
  305. switch(_data.ss_family) {
  306. case AF_INET:
  307. reinterpret_cast<struct sockaddr_in *>(&r)->sin_family = AF_INET;
  308. reinterpret_cast<struct sockaddr_in *>(&r)->sin_addr.s_addr = reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr;
  309. break;
  310. case AF_INET6:
  311. reinterpret_cast<struct sockaddr_in6 *>(&r)->sin6_family = AF_INET;
  312. Utils::copy<16>(reinterpret_cast<struct sockaddr_in6 *>(&r)->sin6_addr.s6_addr,reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
  313. break;
  314. }
  315. return r;
  316. }
  317. /**
  318. * Performs an IP-only comparison or, if that is impossible, a memcmp()
  319. *
  320. * @param a InetAddress to compare again
  321. * @return True if only IP portions are equal (false for non-IP or null addresses)
  322. */
  323. ZT_INLINE bool ipsEqual(const InetAddress &a) const noexcept
  324. {
  325. const uint8_t f = _data.ss_family;
  326. if (f == a._data.ss_family) {
  327. if (f == AF_INET)
  328. return (reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr == reinterpret_cast<const struct sockaddr_in *>(&a)->sin_addr.s_addr);
  329. if (f == AF_INET6)
  330. return (memcmp(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr,reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr,16) == 0);
  331. return (memcmp(this,&a,sizeof(InetAddress)) == 0);
  332. }
  333. return false;
  334. }
  335. /**
  336. * Performs an IP-only comparison or, if that is impossible, a memcmp()
  337. *
  338. * This version compares only the first 64 bits of IPv6 addresses.
  339. *
  340. * @param a InetAddress to compare again
  341. * @return True if only IP portions are equal (false for non-IP or null addresses)
  342. */
  343. ZT_INLINE bool ipsEqual2(const InetAddress &a) const noexcept
  344. {
  345. const uint8_t f = _data.ss_family;
  346. if (f == a._data.ss_family) {
  347. if (f == AF_INET)
  348. return (reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr == reinterpret_cast<const struct sockaddr_in *>(&a)->sin_addr.s_addr);
  349. if (f == AF_INET6)
  350. return (memcmp(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr,reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr,8) == 0);
  351. return (memcmp(this,&a,sizeof(InetAddress)) == 0);
  352. }
  353. return false;
  354. }
  355. unsigned long hashCode() const noexcept;
  356. /**
  357. * Fill out a ZT_TraceEventPathAddress from this InetAddress
  358. *
  359. * @param ta ZT_TraceEventPathAddress to fill
  360. */
  361. void forTrace(ZT_TraceEventPathAddress &ta) const noexcept;
  362. /**
  363. * Check whether this is a network/route rather than an IP assignment
  364. *
  365. * A network is an IP/netmask where everything after the netmask is
  366. * zero e.g. 10.0.0.0/8.
  367. *
  368. * @return True if everything after netmask bits is zero
  369. */
  370. bool isNetwork() const noexcept;
  371. /**
  372. * @return True if address family is non-zero
  373. */
  374. explicit ZT_INLINE operator bool() const noexcept { return (family() != 0); }
  375. static constexpr int marshalSizeMax() noexcept { return ZT_INETADDRESS_MARSHAL_SIZE_MAX; }
  376. int marshal(uint8_t data[ZT_INETADDRESS_MARSHAL_SIZE_MAX]) const noexcept;
  377. int unmarshal(const uint8_t *restrict data,int len) noexcept;
  378. bool operator==(const InetAddress &a) const noexcept;
  379. bool operator<(const InetAddress &a) const noexcept;
  380. ZT_INLINE bool operator!=(const InetAddress &a) const noexcept { return !(*this == a); }
  381. ZT_INLINE bool operator>(const InetAddress &a) const noexcept { return (a < *this); }
  382. ZT_INLINE bool operator<=(const InetAddress &a) const noexcept { return !(a < *this); }
  383. ZT_INLINE bool operator>=(const InetAddress &a) const noexcept { return !(*this < a); }
  384. /**
  385. * Compute an IPv6 link-local address
  386. *
  387. * @param mac MAC address seed
  388. * @return IPv6 link-local address
  389. */
  390. static InetAddress makeIpv6LinkLocal(const MAC &mac) noexcept;
  391. /**
  392. * Compute private IPv6 unicast address from network ID and ZeroTier address
  393. *
  394. * This generates a private unicast IPv6 address that is mostly compliant
  395. * with the letter of RFC4193 and certainly compliant in spirit.
  396. *
  397. * RFC4193 specifies a format of:
  398. *
  399. * | 7 bits |1| 40 bits | 16 bits | 64 bits |
  400. * | Prefix |L| Global ID | Subnet ID | Interface ID |
  401. *
  402. * The 'L' bit is set to 1, yielding an address beginning with 0xfd. Then
  403. * the network ID is filled into the global ID, subnet ID, and first byte
  404. * of the "interface ID" field. Since the first 40 bits of the network ID
  405. * is the unique ZeroTier address of its controller, this makes a very
  406. * good random global ID. Since network IDs have 24 more bits, we let it
  407. * overflow into the interface ID.
  408. *
  409. * After that we pad with two bytes: 0x99, 0x93, namely the default ZeroTier
  410. * port in hex.
  411. *
  412. * Finally we fill the remaining 40 bits of the interface ID field with
  413. * the 40-bit unique ZeroTier device ID of the network member.
  414. *
  415. * This yields a valid RFC4193 address with a random global ID, a
  416. * meaningful subnet ID, and a unique interface ID, all mappable back onto
  417. * ZeroTier space.
  418. *
  419. * This in turn could allow us, on networks numbered this way, to emulate
  420. * IPv6 NDP and eliminate all multicast. This could be beneficial for
  421. * small devices and huge networks, e.g. IoT applications.
  422. *
  423. * The returned address is given an odd prefix length of /88, since within
  424. * a given network only the last 40 bits (device ID) are variable. This
  425. * is a bit unusual but as far as we know should not cause any problems with
  426. * any non-braindead IPv6 stack.
  427. *
  428. * @param nwid 64-bit network ID
  429. * @param zeroTierAddress 40-bit device address (in least significant 40 bits, highest 24 bits ignored)
  430. * @return IPv6 private unicast address with /88 netmask
  431. */
  432. static InetAddress makeIpv6rfc4193(uint64_t nwid,uint64_t zeroTierAddress) noexcept;
  433. /**
  434. * Compute a private IPv6 "6plane" unicast address from network ID and ZeroTier address
  435. */
  436. static InetAddress makeIpv66plane(uint64_t nwid,uint64_t zeroTierAddress) noexcept;
  437. private:
  438. sockaddr_storage _data;
  439. };
  440. static ZT_INLINE InetAddress *asInetAddress(sockaddr_in *p) noexcept { return reinterpret_cast<InetAddress *>(p); }
  441. static ZT_INLINE InetAddress *asInetAddress(sockaddr_in6 *p) noexcept { return reinterpret_cast<InetAddress *>(p); }
  442. static ZT_INLINE InetAddress *asInetAddress(sockaddr *p) noexcept { return reinterpret_cast<InetAddress *>(p); }
  443. static ZT_INLINE InetAddress *asInetAddress(sockaddr_storage *p) noexcept { return reinterpret_cast<InetAddress *>(p); }
  444. static ZT_INLINE const InetAddress *asInetAddress(const sockaddr_in *p) noexcept { return reinterpret_cast<const InetAddress *>(p); }
  445. static ZT_INLINE const InetAddress *asInetAddress(const sockaddr_in6 *p) noexcept { return reinterpret_cast<const InetAddress *>(p); }
  446. static ZT_INLINE const InetAddress *asInetAddress(const sockaddr *p) noexcept { return reinterpret_cast<const InetAddress *>(p); }
  447. static ZT_INLINE const InetAddress *asInetAddress(const sockaddr_storage *p) noexcept { return reinterpret_cast<const InetAddress *>(p); }
  448. static ZT_INLINE InetAddress &asInetAddress(sockaddr_in &p) noexcept { return *reinterpret_cast<InetAddress *>(&p); }
  449. static ZT_INLINE InetAddress &asInetAddress(sockaddr_in6 &p) noexcept { return *reinterpret_cast<InetAddress *>(&p); }
  450. static ZT_INLINE InetAddress &asInetAddress(sockaddr &p) noexcept { return *reinterpret_cast<InetAddress *>(&p); }
  451. static ZT_INLINE InetAddress &asInetAddress(sockaddr_storage &p) noexcept { return *reinterpret_cast<InetAddress *>(&p); }
  452. static ZT_INLINE const InetAddress &asInetAddress(const sockaddr_in &p) noexcept { return *reinterpret_cast<const InetAddress *>(&p); }
  453. static ZT_INLINE const InetAddress &asInetAddress(const sockaddr_in6 &p) noexcept { return *reinterpret_cast<const InetAddress *>(&p); }
  454. static ZT_INLINE const InetAddress &asInetAddress(const sockaddr &p) noexcept { return *reinterpret_cast<const InetAddress *>(&p); }
  455. static ZT_INLINE const InetAddress &asInetAddress(const sockaddr_storage &p) noexcept { return *reinterpret_cast<const InetAddress *>(&p); }
  456. } // namespace ZeroTier
  457. #endif