InetAddress.hpp 15 KB

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