InetAddress.hpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #ifndef ZT_INETADDRESS_HPP
  19. #define ZT_INETADDRESS_HPP
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <stdint.h>
  23. #include <string>
  24. #include "Constants.hpp"
  25. #include "../include/ZeroTierOne.h"
  26. #include "Utils.hpp"
  27. #include "MAC.hpp"
  28. #include "Buffer.hpp"
  29. namespace ZeroTier {
  30. /**
  31. * Maximum integer value of enum IpScope
  32. */
  33. #define ZT_INETADDRESS_MAX_SCOPE 7
  34. /**
  35. * Extends sockaddr_storage with friendly C++ methods
  36. *
  37. * This is basically a "mixin" for sockaddr_storage. It adds methods and
  38. * operators, but does not modify the structure. This can be cast to/from
  39. * sockaddr_storage and used interchangeably. DO NOT change this by e.g.
  40. * adding non-static fields, since much code depends on this identity.
  41. */
  42. struct InetAddress : public sockaddr_storage
  43. {
  44. /**
  45. * Loopback IPv4 address (no port)
  46. */
  47. static const InetAddress LO4;
  48. /**
  49. * Loopback IPV6 address (no port)
  50. */
  51. static const InetAddress LO6;
  52. /**
  53. * IP address scope
  54. *
  55. * Note that these values are in ascending order of path preference and
  56. * MUST remain that way or Path must be changed to reflect. Also be sure
  57. * to change ZT_INETADDRESS_MAX_SCOPE if the max changes.
  58. */
  59. enum IpScope
  60. {
  61. IP_SCOPE_NONE = 0, // NULL or not an IP address
  62. IP_SCOPE_MULTICAST = 1, // 224.0.0.0 and other V4/V6 multicast IPs
  63. IP_SCOPE_LOOPBACK = 2, // 127.0.0.1, ::1, etc.
  64. IP_SCOPE_PSEUDOPRIVATE = 3, // 28.x.x.x, etc. -- unofficially unrouted IPv4 blocks often "bogarted"
  65. IP_SCOPE_GLOBAL = 4, // globally routable IP address (all others)
  66. IP_SCOPE_LINK_LOCAL = 5, // 169.254.x.x, IPv6 LL
  67. IP_SCOPE_SHARED = 6, // 100.64.0.0/10, shared space for e.g. carrier-grade NAT
  68. IP_SCOPE_PRIVATE = 7 // 10.x.x.x, 192.168.x.x, etc.
  69. };
  70. InetAddress() throw() { memset(this,0,sizeof(InetAddress)); }
  71. InetAddress(const InetAddress &a) throw() { memcpy(this,&a,sizeof(InetAddress)); }
  72. InetAddress(const InetAddress *a) throw() { memcpy(this,a,sizeof(InetAddress)); }
  73. InetAddress(const struct sockaddr_storage &ss) throw() { *this = ss; }
  74. InetAddress(const struct sockaddr_storage *ss) throw() { *this = ss; }
  75. InetAddress(const struct sockaddr &sa) throw() { *this = sa; }
  76. InetAddress(const struct sockaddr *sa) throw() { *this = sa; }
  77. InetAddress(const struct sockaddr_in &sa) throw() { *this = sa; }
  78. InetAddress(const struct sockaddr_in *sa) throw() { *this = sa; }
  79. InetAddress(const struct sockaddr_in6 &sa) throw() { *this = sa; }
  80. InetAddress(const struct sockaddr_in6 *sa) throw() { *this = sa; }
  81. InetAddress(const void *ipBytes,unsigned int ipLen,unsigned int port) throw() { this->set(ipBytes,ipLen,port); }
  82. InetAddress(const uint32_t ipv4,unsigned int port) throw() { this->set(&ipv4,4,port); }
  83. InetAddress(const std::string &ip,unsigned int port) throw() { this->set(ip,port); }
  84. InetAddress(const std::string &ipSlashPort) throw() { this->fromString(ipSlashPort); }
  85. InetAddress(const char *ipSlashPort) throw() { this->fromString(std::string(ipSlashPort)); }
  86. inline InetAddress &operator=(const InetAddress &a)
  87. throw()
  88. {
  89. if (&a != this)
  90. memcpy(this,&a,sizeof(InetAddress));
  91. return *this;
  92. }
  93. inline InetAddress &operator=(const InetAddress *a)
  94. throw()
  95. {
  96. if (a != this)
  97. memcpy(this,a,sizeof(InetAddress));
  98. return *this;
  99. }
  100. inline InetAddress &operator=(const struct sockaddr_storage &ss)
  101. throw()
  102. {
  103. if (reinterpret_cast<const InetAddress *>(&ss) != this)
  104. memcpy(this,&ss,sizeof(InetAddress));
  105. return *this;
  106. }
  107. inline InetAddress &operator=(const struct sockaddr_storage *ss)
  108. throw()
  109. {
  110. if (reinterpret_cast<const InetAddress *>(ss) != this)
  111. memcpy(this,ss,sizeof(InetAddress));
  112. return *this;
  113. }
  114. inline InetAddress &operator=(const struct sockaddr_in &sa)
  115. throw()
  116. {
  117. if (reinterpret_cast<const InetAddress *>(&sa) != this) {
  118. memset(this,0,sizeof(InetAddress));
  119. memcpy(this,&sa,sizeof(struct sockaddr_in));
  120. }
  121. return *this;
  122. }
  123. inline InetAddress &operator=(const struct sockaddr_in *sa)
  124. throw()
  125. {
  126. if (reinterpret_cast<const InetAddress *>(sa) != this) {
  127. memset(this,0,sizeof(InetAddress));
  128. memcpy(this,sa,sizeof(struct sockaddr_in));
  129. }
  130. return *this;
  131. }
  132. inline InetAddress &operator=(const struct sockaddr_in6 &sa)
  133. throw()
  134. {
  135. if (reinterpret_cast<const InetAddress *>(&sa) != this) {
  136. memset(this,0,sizeof(InetAddress));
  137. memcpy(this,&sa,sizeof(struct sockaddr_in6));
  138. }
  139. return *this;
  140. }
  141. inline InetAddress &operator=(const struct sockaddr_in6 *sa)
  142. throw()
  143. {
  144. if (reinterpret_cast<const InetAddress *>(sa) != this) {
  145. memset(this,0,sizeof(InetAddress));
  146. memcpy(this,sa,sizeof(struct sockaddr_in6));
  147. }
  148. return *this;
  149. }
  150. inline InetAddress &operator=(const struct sockaddr &sa)
  151. throw()
  152. {
  153. if (reinterpret_cast<const InetAddress *>(&sa) != this) {
  154. memset(this,0,sizeof(InetAddress));
  155. switch(sa.sa_family) {
  156. case AF_INET:
  157. memcpy(this,&sa,sizeof(struct sockaddr_in));
  158. break;
  159. case AF_INET6:
  160. memcpy(this,&sa,sizeof(struct sockaddr_in6));
  161. break;
  162. }
  163. }
  164. return *this;
  165. }
  166. inline InetAddress &operator=(const struct sockaddr *sa)
  167. throw()
  168. {
  169. if (reinterpret_cast<const InetAddress *>(sa) != this) {
  170. memset(this,0,sizeof(InetAddress));
  171. switch(sa->sa_family) {
  172. case AF_INET:
  173. memcpy(this,sa,sizeof(struct sockaddr_in));
  174. break;
  175. case AF_INET6:
  176. memcpy(this,sa,sizeof(struct sockaddr_in6));
  177. break;
  178. }
  179. }
  180. return *this;
  181. }
  182. /**
  183. * @return IP scope classification (e.g. loopback, link-local, private, global)
  184. */
  185. IpScope ipScope() const
  186. throw();
  187. /**
  188. * Set from a string-format IP and a port
  189. *
  190. * @param ip IP address in V4 or V6 ASCII notation
  191. * @param port Port or 0 for none
  192. */
  193. void set(const std::string &ip,unsigned int port)
  194. throw();
  195. /**
  196. * Set from a raw IP and port number
  197. *
  198. * @param ipBytes Bytes of IP address in network byte order
  199. * @param ipLen Length of IP address: 4 or 16
  200. * @param port Port number or 0 for none
  201. */
  202. void set(const void *ipBytes,unsigned int ipLen,unsigned int port)
  203. throw();
  204. /**
  205. * Set the port component
  206. *
  207. * @param port Port, 0 to 65535
  208. */
  209. inline void setPort(unsigned int port)
  210. {
  211. switch(ss_family) {
  212. case AF_INET:
  213. reinterpret_cast<struct sockaddr_in *>(this)->sin_port = Utils::hton((uint16_t)port);
  214. break;
  215. case AF_INET6:
  216. reinterpret_cast<struct sockaddr_in6 *>(this)->sin6_port = Utils::hton((uint16_t)port);
  217. break;
  218. }
  219. }
  220. /**
  221. * @return True if this network/netmask route describes a default route (e.g. 0.0.0.0/0)
  222. */
  223. inline bool isDefaultRoute() const
  224. {
  225. switch(ss_family) {
  226. case AF_INET:
  227. return ( (reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr == 0) && (reinterpret_cast<const struct sockaddr_in *>(this)->sin_port == 0) );
  228. case AF_INET6:
  229. const uint8_t *ipb = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
  230. for(int i=0;i<16;++i) {
  231. if (ipb[i])
  232. return false;
  233. }
  234. return (reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_port == 0);
  235. }
  236. return false;
  237. }
  238. /**
  239. * @return ASCII IP/port format representation
  240. */
  241. std::string toString() const;
  242. /**
  243. * @return IP portion only, in ASCII string format
  244. */
  245. std::string toIpString() const;
  246. /**
  247. * @param ipSlashPort ASCII IP/port format notation
  248. */
  249. void fromString(const std::string &ipSlashPort);
  250. /**
  251. * @return Port or 0 if no port component defined
  252. */
  253. inline unsigned int port() const
  254. throw()
  255. {
  256. switch(ss_family) {
  257. case AF_INET: return Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(this)->sin_port));
  258. case AF_INET6: return Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_port));
  259. default: return 0;
  260. }
  261. }
  262. /**
  263. * Alias for port()
  264. *
  265. * This just aliases port() to make code more readable when netmask bits
  266. * are stuffed there, as they are in Network, EthernetTap, and a few other
  267. * spots.
  268. *
  269. * @return Netmask bits
  270. */
  271. inline unsigned int netmaskBits() const throw() { return port(); }
  272. /**
  273. * @return True if netmask bits is valid for the address type
  274. */
  275. inline bool netmaskBitsValid() const
  276. {
  277. const unsigned int n = port();
  278. switch(ss_family) {
  279. case AF_INET: return (n <= 32);
  280. case AF_INET6: return (n <= 128);
  281. }
  282. return false;
  283. }
  284. /**
  285. * Alias for port()
  286. *
  287. * This just aliases port() because for gateways we use this field to
  288. * store the gateway metric.
  289. *
  290. * @return Gateway metric
  291. */
  292. inline unsigned int metric() const throw() { return port(); }
  293. /**
  294. * Construct a full netmask as an InetAddress
  295. *
  296. * @return Netmask such as 255.255.255.0 if this address is /24 (port field will be unchanged)
  297. */
  298. InetAddress netmask() const;
  299. /**
  300. * Constructs a broadcast address from a network/netmask address
  301. *
  302. * This is only valid for IPv4 and will return a NULL InetAddress for other
  303. * address families.
  304. *
  305. * @return Broadcast address (only IP portion is meaningful)
  306. */
  307. InetAddress broadcast() const;
  308. /**
  309. * Return the network -- a.k.a. the IP ANDed with the netmask
  310. *
  311. * @return Network e.g. 10.0.1.0/24 from 10.0.1.200/24
  312. */
  313. InetAddress network() const;
  314. /**
  315. * Test whether this IP/netmask contains this address
  316. *
  317. * @param addr Address to check
  318. * @return True if this IP/netmask (route) contains this address
  319. */
  320. bool containsAddress(const InetAddress &addr) const;
  321. /**
  322. * @return True if this is an IPv4 address
  323. */
  324. inline bool isV4() const throw() { return (ss_family == AF_INET); }
  325. /**
  326. * @return True if this is an IPv6 address
  327. */
  328. inline bool isV6() const throw() { return (ss_family == AF_INET6); }
  329. /**
  330. * @return pointer to raw address bytes or NULL if not available
  331. */
  332. inline const void *rawIpData() const
  333. {
  334. switch(ss_family) {
  335. case AF_INET: return (const void *)&(reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr);
  336. case AF_INET6: return (const void *)(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
  337. default: return 0;
  338. }
  339. }
  340. /**
  341. * @return InetAddress containing only the IP portion of this address and a zero port, or NULL if not IPv4 or IPv6
  342. */
  343. inline InetAddress ipOnly() const
  344. {
  345. InetAddress r;
  346. switch(ss_family) {
  347. case AF_INET:
  348. r.ss_family = AF_INET;
  349. reinterpret_cast<struct sockaddr_in *>(&r)->sin_addr.s_addr = reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr;
  350. break;
  351. case AF_INET6:
  352. r.ss_family = AF_INET6;
  353. memcpy(reinterpret_cast<struct sockaddr_in6 *>(&r)->sin6_addr.s6_addr,reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr,16);
  354. break;
  355. }
  356. return r;
  357. }
  358. /**
  359. * Performs an IP-only comparison or, if that is impossible, a memcmp()
  360. *
  361. * @param a InetAddress to compare again
  362. * @return True if only IP portions are equal (false for non-IP or null addresses)
  363. */
  364. inline bool ipsEqual(const InetAddress &a) const
  365. {
  366. if (ss_family == a.ss_family) {
  367. if (ss_family == AF_INET)
  368. return (reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr == reinterpret_cast<const struct sockaddr_in *>(&a)->sin_addr.s_addr);
  369. if (ss_family == AF_INET6)
  370. 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);
  371. return (memcmp(this,&a,sizeof(InetAddress)) == 0);
  372. }
  373. return false;
  374. }
  375. inline unsigned long hashCode() const
  376. {
  377. if (ss_family == AF_INET) {
  378. return ((unsigned long)reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr + (unsigned long)reinterpret_cast<const struct sockaddr_in *>(this)->sin_port);
  379. } else if (ss_family == AF_INET6) {
  380. unsigned long tmp = reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_port;
  381. const uint8_t *a = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr);
  382. for(long i=0;i<16;++i)
  383. reinterpret_cast<uint8_t *>(&tmp)[i % sizeof(tmp)] ^= a[i];
  384. return tmp;
  385. } else {
  386. unsigned long tmp = reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_port;
  387. const uint8_t *a = reinterpret_cast<const uint8_t *>(this);
  388. for(long i=0;i<sizeof(InetAddress);++i)
  389. reinterpret_cast<uint8_t *>(&tmp)[i % sizeof(tmp)] ^= a[i];
  390. return tmp;
  391. }
  392. }
  393. /**
  394. * Set to null/zero
  395. */
  396. inline void zero() throw() { memset(this,0,sizeof(InetAddress)); }
  397. /**
  398. * Check whether this is a network/route rather than an IP assignment
  399. *
  400. * A network is an IP/netmask where everything after the netmask is
  401. * zero e.g. 10.0.0.0/8.
  402. *
  403. * @return True if everything after netmask bits is zero
  404. */
  405. bool isNetwork() const
  406. throw();
  407. /**
  408. * @return True if address family is non-zero
  409. */
  410. inline operator bool() const throw() { return (ss_family != 0); }
  411. template<unsigned int C>
  412. inline void serialize(Buffer<C> &b) const
  413. {
  414. // This is used in the protocol and must be the same as describe in places
  415. // like VERB_HELLO in Packet.hpp.
  416. switch(ss_family) {
  417. case AF_INET:
  418. b.append((uint8_t)0x04);
  419. b.append(&(reinterpret_cast<const struct sockaddr_in *>(this)->sin_addr.s_addr),4);
  420. b.append((uint16_t)port()); // just in case sin_port != uint16_t
  421. return;
  422. case AF_INET6:
  423. b.append((uint8_t)0x06);
  424. b.append(reinterpret_cast<const struct sockaddr_in6 *>(this)->sin6_addr.s6_addr,16);
  425. b.append((uint16_t)port()); // just in case sin_port != uint16_t
  426. return;
  427. default:
  428. b.append((uint8_t)0);
  429. return;
  430. }
  431. }
  432. template<unsigned int C>
  433. inline unsigned int deserialize(const Buffer<C> &b,unsigned int startAt = 0)
  434. {
  435. memset(this,0,sizeof(InetAddress));
  436. unsigned int p = startAt;
  437. switch(b[p++]) {
  438. case 0:
  439. return 1;
  440. case 0x01:
  441. // TODO: Ethernet address (but accept for forward compatibility)
  442. return 7;
  443. case 0x02:
  444. // TODO: Bluetooth address (but accept for forward compatibility)
  445. return 7;
  446. case 0x03:
  447. // TODO: Other address types (but accept for forward compatibility)
  448. // These could be extended/optional things like AF_UNIX, LTE Direct, shared memory, etc.
  449. return (unsigned int)(b.template at<uint16_t>(p) + 3); // other addresses begin with 16-bit non-inclusive length
  450. case 0x04:
  451. ss_family = AF_INET;
  452. memcpy(&(reinterpret_cast<struct sockaddr_in *>(this)->sin_addr.s_addr),b.field(p,4),4); p += 4;
  453. reinterpret_cast<struct sockaddr_in *>(this)->sin_port = Utils::hton(b.template at<uint16_t>(p)); p += 2;
  454. break;
  455. case 0x06:
  456. ss_family = AF_INET6;
  457. memcpy(reinterpret_cast<struct sockaddr_in6 *>(this)->sin6_addr.s6_addr,b.field(p,16),16); p += 16;
  458. reinterpret_cast<struct sockaddr_in *>(this)->sin_port = Utils::hton(b.template at<uint16_t>(p)); p += 2;
  459. break;
  460. default:
  461. throw std::invalid_argument("invalid serialized InetAddress");
  462. }
  463. return (p - startAt);
  464. }
  465. bool operator==(const InetAddress &a) const throw();
  466. bool operator<(const InetAddress &a) const throw();
  467. inline bool operator!=(const InetAddress &a) const throw() { return !(*this == a); }
  468. inline bool operator>(const InetAddress &a) const throw() { return (a < *this); }
  469. inline bool operator<=(const InetAddress &a) const throw() { return !(a < *this); }
  470. inline bool operator>=(const InetAddress &a) const throw() { return !(*this < a); }
  471. /**
  472. * @param mac MAC address seed
  473. * @return IPv6 link-local address
  474. */
  475. static InetAddress makeIpv6LinkLocal(const MAC &mac);
  476. /**
  477. * Compute private IPv6 unicast address from network ID and ZeroTier address
  478. *
  479. * This generates a private unicast IPv6 address that is mostly compliant
  480. * with the letter of RFC4193 and certainly compliant in spirit.
  481. *
  482. * RFC4193 specifies a format of:
  483. *
  484. * | 7 bits |1| 40 bits | 16 bits | 64 bits |
  485. * | Prefix |L| Global ID | Subnet ID | Interface ID |
  486. *
  487. * The 'L' bit is set to 1, yielding an address beginning with 0xfd. Then
  488. * the network ID is filled into the global ID, subnet ID, and first byte
  489. * of the "interface ID" field. Since the first 40 bits of the network ID
  490. * is the unique ZeroTier address of its controller, this makes a very
  491. * good random global ID. Since network IDs have 24 more bits, we let it
  492. * overflow into the interface ID.
  493. *
  494. * After that we pad with two bytes: 0x99, 0x93, namely the default ZeroTier
  495. * port in hex.
  496. *
  497. * Finally we fill the remaining 40 bits of the interface ID field with
  498. * the 40-bit unique ZeroTier device ID of the network member.
  499. *
  500. * This yields a valid RFC4193 address with a random global ID, a
  501. * meaningful subnet ID, and a unique interface ID, all mappable back onto
  502. * ZeroTier space.
  503. *
  504. * This in turn could allow us, on networks numbered this way, to emulate
  505. * IPv6 NDP and eliminate all multicast. This could be beneficial for
  506. * small devices and huge networks, e.g. IoT applications.
  507. *
  508. * The returned address is given an odd prefix length of /88, since within
  509. * a given network only the last 40 bits (device ID) are variable. This
  510. * is a bit unusual but as far as we know should not cause any problems with
  511. * any non-braindead IPv6 stack.
  512. *
  513. * @param nwid 64-bit network ID
  514. * @param zeroTierAddress 40-bit device address (in least significant 40 bits, highest 24 bits ignored)
  515. * @return IPv6 private unicast address with /88 netmask
  516. */
  517. static InetAddress makeIpv6rfc4193(uint64_t nwid,uint64_t zeroTierAddress);
  518. /**
  519. * Compute a private IPv6 "6plane" unicast address from network ID and ZeroTier address
  520. */
  521. static InetAddress makeIpv66plane(uint64_t nwid,uint64_t zeroTierAddress);
  522. };
  523. } // namespace ZeroTier
  524. #endif