You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

netaddress.cpp 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2016 The Starwels developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #ifdef HAVE_CONFIG_H
  6. #include "config/starwels-config.h"
  7. #endif
  8. #include "netaddress.h"
  9. #include "hash.h"
  10. #include "utilstrencodings.h"
  11. #include "tinyformat.h"
  12. static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
  13. static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
  14. // 0xFD + sha256("starwels")[0:5]
  15. static const unsigned char g_internal_prefix[] = { 0xFD, 0x6B, 0x88, 0xC0, 0x87, 0x24 };
  16. void CNetAddr::Init()
  17. {
  18. memset(ip, 0, sizeof(ip));
  19. scopeId = 0;
  20. }
  21. void CNetAddr::SetIP(const CNetAddr& ipIn)
  22. {
  23. memcpy(ip, ipIn.ip, sizeof(ip));
  24. }
  25. void CNetAddr::SetRaw(Network network, const uint8_t *ip_in)
  26. {
  27. switch(network)
  28. {
  29. case NET_IPV4:
  30. memcpy(ip, pchIPv4, 12);
  31. memcpy(ip+12, ip_in, 4);
  32. break;
  33. case NET_IPV6:
  34. memcpy(ip, ip_in, 16);
  35. break;
  36. default:
  37. assert(!"invalid network");
  38. }
  39. }
  40. bool CNetAddr::SetInternal(const std::string &name)
  41. {
  42. if (name.empty()) {
  43. return false;
  44. }
  45. unsigned char hash[32] = {};
  46. CSHA256().Write((const unsigned char*)name.data(), name.size()).Finalize(hash);
  47. memcpy(ip, g_internal_prefix, sizeof(g_internal_prefix));
  48. memcpy(ip + sizeof(g_internal_prefix), hash, sizeof(ip) - sizeof(g_internal_prefix));
  49. return true;
  50. }
  51. bool CNetAddr::SetSpecial(const std::string &strName)
  52. {
  53. if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
  54. std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
  55. if (vchAddr.size() != 16-sizeof(pchOnionCat))
  56. return false;
  57. memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
  58. for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
  59. ip[i + sizeof(pchOnionCat)] = vchAddr[i];
  60. return true;
  61. }
  62. return false;
  63. }
  64. CNetAddr::CNetAddr()
  65. {
  66. Init();
  67. }
  68. CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
  69. {
  70. SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);
  71. }
  72. CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr, const uint32_t scope)
  73. {
  74. SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);
  75. scopeId = scope;
  76. }
  77. unsigned int CNetAddr::GetByte(int n) const
  78. {
  79. return ip[15-n];
  80. }
  81. bool CNetAddr::IsIPv4() const
  82. {
  83. return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
  84. }
  85. bool CNetAddr::IsIPv6() const
  86. {
  87. return (!IsIPv4() && !IsTor() && !IsInternal());
  88. }
  89. bool CNetAddr::IsRFC1918() const
  90. {
  91. return IsIPv4() && (
  92. GetByte(3) == 10 ||
  93. (GetByte(3) == 192 && GetByte(2) == 168) ||
  94. (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
  95. }
  96. bool CNetAddr::IsRFC2544() const
  97. {
  98. return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);
  99. }
  100. bool CNetAddr::IsRFC3927() const
  101. {
  102. return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
  103. }
  104. bool CNetAddr::IsRFC6598() const
  105. {
  106. return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;
  107. }
  108. bool CNetAddr::IsRFC5737() const
  109. {
  110. return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) ||
  111. (GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) ||
  112. (GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113));
  113. }
  114. bool CNetAddr::IsRFC3849() const
  115. {
  116. return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
  117. }
  118. bool CNetAddr::IsRFC3964() const
  119. {
  120. return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
  121. }
  122. bool CNetAddr::IsRFC6052() const
  123. {
  124. static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
  125. return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
  126. }
  127. bool CNetAddr::IsRFC4380() const
  128. {
  129. return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
  130. }
  131. bool CNetAddr::IsRFC4862() const
  132. {
  133. static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
  134. return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
  135. }
  136. bool CNetAddr::IsRFC4193() const
  137. {
  138. return ((GetByte(15) & 0xFE) == 0xFC);
  139. }
  140. bool CNetAddr::IsRFC6145() const
  141. {
  142. static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
  143. return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
  144. }
  145. bool CNetAddr::IsRFC4843() const
  146. {
  147. return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
  148. }
  149. bool CNetAddr::IsTor() const
  150. {
  151. return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
  152. }
  153. bool CNetAddr::IsLocal() const
  154. {
  155. // IPv4 loopback
  156. if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
  157. return true;
  158. // IPv6 loopback (::1/128)
  159. static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
  160. if (memcmp(ip, pchLocal, 16) == 0)
  161. return true;
  162. return false;
  163. }
  164. bool CNetAddr::IsValid() const
  165. {
  166. // Cleanup 3-byte shifted addresses caused by garbage in size field
  167. // of addr messages from versions before 0.2.9 checksum.
  168. // Two consecutive addr messages look like this:
  169. // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
  170. // so if the first length field is garbled, it reads the second batch
  171. // of addr misaligned by 3 bytes.
  172. if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
  173. return false;
  174. // unspecified IPv6 address (::/128)
  175. unsigned char ipNone6[16] = {};
  176. if (memcmp(ip, ipNone6, 16) == 0)
  177. return false;
  178. // documentation IPv6 address
  179. if (IsRFC3849())
  180. return false;
  181. if (IsInternal())
  182. return false;
  183. if (IsIPv4())
  184. {
  185. // INADDR_NONE
  186. uint32_t ipNone = INADDR_NONE;
  187. if (memcmp(ip+12, &ipNone, 4) == 0)
  188. return false;
  189. // 0
  190. ipNone = 0;
  191. if (memcmp(ip+12, &ipNone, 4) == 0)
  192. return false;
  193. }
  194. return true;
  195. }
  196. bool CNetAddr::IsRoutable() const
  197. {
  198. return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal() || IsInternal());
  199. }
  200. bool CNetAddr::IsInternal() const
  201. {
  202. return memcmp(ip, g_internal_prefix, sizeof(g_internal_prefix)) == 0;
  203. }
  204. enum Network CNetAddr::GetNetwork() const
  205. {
  206. if (IsInternal())
  207. return NET_INTERNAL;
  208. if (!IsRoutable())
  209. return NET_UNROUTABLE;
  210. if (IsIPv4())
  211. return NET_IPV4;
  212. if (IsTor())
  213. return NET_TOR;
  214. return NET_IPV6;
  215. }
  216. std::string CNetAddr::ToStringIP() const
  217. {
  218. if (IsTor())
  219. return EncodeBase32(&ip[6], 10) + ".onion";
  220. if (IsInternal())
  221. return EncodeBase32(ip + sizeof(g_internal_prefix), sizeof(ip) - sizeof(g_internal_prefix)) + ".internal";
  222. CService serv(*this, 0);
  223. struct sockaddr_storage sockaddr;
  224. socklen_t socklen = sizeof(sockaddr);
  225. if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
  226. char name[1025] = "";
  227. if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), nullptr, 0, NI_NUMERICHOST))
  228. return std::string(name);
  229. }
  230. if (IsIPv4())
  231. return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
  232. else
  233. return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
  234. GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
  235. GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
  236. GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
  237. GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
  238. }
  239. std::string CNetAddr::ToString() const
  240. {
  241. return ToStringIP();
  242. }
  243. bool operator==(const CNetAddr& a, const CNetAddr& b)
  244. {
  245. return (memcmp(a.ip, b.ip, 16) == 0);
  246. }
  247. bool operator!=(const CNetAddr& a, const CNetAddr& b)
  248. {
  249. return (memcmp(a.ip, b.ip, 16) != 0);
  250. }
  251. bool operator<(const CNetAddr& a, const CNetAddr& b)
  252. {
  253. return (memcmp(a.ip, b.ip, 16) < 0);
  254. }
  255. bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
  256. {
  257. if (!IsIPv4())
  258. return false;
  259. memcpy(pipv4Addr, ip+12, 4);
  260. return true;
  261. }
  262. bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
  263. {
  264. memcpy(pipv6Addr, ip, 16);
  265. return true;
  266. }
  267. // get canonical identifier of an address' group
  268. // no two connections will be attempted to addresses with the same group
  269. std::vector<unsigned char> CNetAddr::GetGroup() const
  270. {
  271. std::vector<unsigned char> vchRet;
  272. int nClass = NET_IPV6;
  273. int nStartByte = 0;
  274. int nBits = 16;
  275. // all local addresses belong to the same group
  276. if (IsLocal())
  277. {
  278. nClass = 255;
  279. nBits = 0;
  280. }
  281. // all internal-usage addresses get their own group
  282. if (IsInternal())
  283. {
  284. nClass = NET_INTERNAL;
  285. nStartByte = sizeof(g_internal_prefix);
  286. nBits = (sizeof(ip) - sizeof(g_internal_prefix)) * 8;
  287. }
  288. // all other unroutable addresses belong to the same group
  289. else if (!IsRoutable())
  290. {
  291. nClass = NET_UNROUTABLE;
  292. nBits = 0;
  293. }
  294. // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
  295. // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
  296. else if (IsIPv4() || IsRFC6145() || IsRFC6052())
  297. {
  298. nClass = NET_IPV4;
  299. nStartByte = 12;
  300. }
  301. // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
  302. else if (IsRFC3964())
  303. {
  304. nClass = NET_IPV4;
  305. nStartByte = 2;
  306. }
  307. // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
  308. else if (IsRFC4380())
  309. {
  310. vchRet.push_back(NET_IPV4);
  311. vchRet.push_back(GetByte(3) ^ 0xFF);
  312. vchRet.push_back(GetByte(2) ^ 0xFF);
  313. return vchRet;
  314. }
  315. else if (IsTor())
  316. {
  317. nClass = NET_TOR;
  318. nStartByte = 6;
  319. nBits = 4;
  320. }
  321. // for he.net, use /36 groups
  322. else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
  323. nBits = 36;
  324. // for the rest of the IPv6 network, use /32 groups
  325. else
  326. nBits = 32;
  327. vchRet.push_back(nClass);
  328. while (nBits >= 8)
  329. {
  330. vchRet.push_back(GetByte(15 - nStartByte));
  331. nStartByte++;
  332. nBits -= 8;
  333. }
  334. if (nBits > 0)
  335. vchRet.push_back(GetByte(15 - nStartByte) | ((1 << (8 - nBits)) - 1));
  336. return vchRet;
  337. }
  338. uint64_t CNetAddr::GetHash() const
  339. {
  340. uint256 hash = Hash(&ip[0], &ip[16]);
  341. uint64_t nRet;
  342. memcpy(&nRet, &hash, sizeof(nRet));
  343. return nRet;
  344. }
  345. // private extensions to enum Network, only returned by GetExtNetwork,
  346. // and only used in GetReachabilityFrom
  347. static const int NET_UNKNOWN = NET_MAX + 0;
  348. static const int NET_TEREDO = NET_MAX + 1;
  349. int static GetExtNetwork(const CNetAddr *addr)
  350. {
  351. if (addr == nullptr)
  352. return NET_UNKNOWN;
  353. if (addr->IsRFC4380())
  354. return NET_TEREDO;
  355. return addr->GetNetwork();
  356. }
  357. /** Calculates a metric for how reachable (*this) is from a given partner */
  358. int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
  359. {
  360. enum Reachability {
  361. REACH_UNREACHABLE,
  362. REACH_DEFAULT,
  363. REACH_TEREDO,
  364. REACH_IPV6_WEAK,
  365. REACH_IPV4,
  366. REACH_IPV6_STRONG,
  367. REACH_PRIVATE
  368. };
  369. if (!IsRoutable() || IsInternal())
  370. return REACH_UNREACHABLE;
  371. int ourNet = GetExtNetwork(this);
  372. int theirNet = GetExtNetwork(paddrPartner);
  373. bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
  374. switch(theirNet) {
  375. case NET_IPV4:
  376. switch(ourNet) {
  377. default: return REACH_DEFAULT;
  378. case NET_IPV4: return REACH_IPV4;
  379. }
  380. case NET_IPV6:
  381. switch(ourNet) {
  382. default: return REACH_DEFAULT;
  383. case NET_TEREDO: return REACH_TEREDO;
  384. case NET_IPV4: return REACH_IPV4;
  385. case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
  386. }
  387. case NET_TOR:
  388. switch(ourNet) {
  389. default: return REACH_DEFAULT;
  390. case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
  391. case NET_TOR: return REACH_PRIVATE;
  392. }
  393. case NET_TEREDO:
  394. switch(ourNet) {
  395. default: return REACH_DEFAULT;
  396. case NET_TEREDO: return REACH_TEREDO;
  397. case NET_IPV6: return REACH_IPV6_WEAK;
  398. case NET_IPV4: return REACH_IPV4;
  399. }
  400. case NET_UNKNOWN:
  401. case NET_UNROUTABLE:
  402. default:
  403. switch(ourNet) {
  404. default: return REACH_DEFAULT;
  405. case NET_TEREDO: return REACH_TEREDO;
  406. case NET_IPV6: return REACH_IPV6_WEAK;
  407. case NET_IPV4: return REACH_IPV4;
  408. case NET_TOR: return REACH_PRIVATE; // either from Tor, or don't care about our address
  409. }
  410. }
  411. }
  412. void CService::Init()
  413. {
  414. port = 0;
  415. }
  416. CService::CService()
  417. {
  418. Init();
  419. }
  420. CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
  421. {
  422. }
  423. CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
  424. {
  425. }
  426. CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
  427. {
  428. }
  429. CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
  430. {
  431. assert(addr.sin_family == AF_INET);
  432. }
  433. CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr, addr.sin6_scope_id), port(ntohs(addr.sin6_port))
  434. {
  435. assert(addr.sin6_family == AF_INET6);
  436. }
  437. bool CService::SetSockAddr(const struct sockaddr *paddr)
  438. {
  439. switch (paddr->sa_family) {
  440. case AF_INET:
  441. *this = CService(*(const struct sockaddr_in*)paddr);
  442. return true;
  443. case AF_INET6:
  444. *this = CService(*(const struct sockaddr_in6*)paddr);
  445. return true;
  446. default:
  447. return false;
  448. }
  449. }
  450. unsigned short CService::GetPort() const
  451. {
  452. return port;
  453. }
  454. bool operator==(const CService& a, const CService& b)
  455. {
  456. return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
  457. }
  458. bool operator!=(const CService& a, const CService& b)
  459. {
  460. return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
  461. }
  462. bool operator<(const CService& a, const CService& b)
  463. {
  464. return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
  465. }
  466. bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
  467. {
  468. if (IsIPv4()) {
  469. if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
  470. return false;
  471. *addrlen = sizeof(struct sockaddr_in);
  472. struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
  473. memset(paddrin, 0, *addrlen);
  474. if (!GetInAddr(&paddrin->sin_addr))
  475. return false;
  476. paddrin->sin_family = AF_INET;
  477. paddrin->sin_port = htons(port);
  478. return true;
  479. }
  480. if (IsIPv6()) {
  481. if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
  482. return false;
  483. *addrlen = sizeof(struct sockaddr_in6);
  484. struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
  485. memset(paddrin6, 0, *addrlen);
  486. if (!GetIn6Addr(&paddrin6->sin6_addr))
  487. return false;
  488. paddrin6->sin6_scope_id = scopeId;
  489. paddrin6->sin6_family = AF_INET6;
  490. paddrin6->sin6_port = htons(port);
  491. return true;
  492. }
  493. return false;
  494. }
  495. std::vector<unsigned char> CService::GetKey() const
  496. {
  497. std::vector<unsigned char> vKey;
  498. vKey.resize(18);
  499. memcpy(vKey.data(), ip, 16);
  500. vKey[16] = port / 0x100;
  501. vKey[17] = port & 0x0FF;
  502. return vKey;
  503. }
  504. std::string CService::ToStringPort() const
  505. {
  506. return strprintf("%u", port);
  507. }
  508. std::string CService::ToStringIPPort() const
  509. {
  510. if (IsIPv4() || IsTor() || IsInternal()) {
  511. return ToStringIP() + ":" + ToStringPort();
  512. } else {
  513. return "[" + ToStringIP() + "]:" + ToStringPort();
  514. }
  515. }
  516. std::string CService::ToString() const
  517. {
  518. return ToStringIPPort();
  519. }
  520. CSubNet::CSubNet():
  521. valid(false)
  522. {
  523. memset(netmask, 0, sizeof(netmask));
  524. }
  525. CSubNet::CSubNet(const CNetAddr &addr, int32_t mask)
  526. {
  527. valid = true;
  528. network = addr;
  529. // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
  530. memset(netmask, 255, sizeof(netmask));
  531. // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
  532. const int astartofs = network.IsIPv4() ? 12 : 0;
  533. int32_t n = mask;
  534. if(n >= 0 && n <= (128 - astartofs*8)) // Only valid if in range of bits of address
  535. {
  536. n += astartofs*8;
  537. // Clear bits [n..127]
  538. for (; n < 128; ++n)
  539. netmask[n>>3] &= ~(1<<(7-(n&7)));
  540. } else
  541. valid = false;
  542. // Normalize network according to netmask
  543. for(int x=0; x<16; ++x)
  544. network.ip[x] &= netmask[x];
  545. }
  546. CSubNet::CSubNet(const CNetAddr &addr, const CNetAddr &mask)
  547. {
  548. valid = true;
  549. network = addr;
  550. // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
  551. memset(netmask, 255, sizeof(netmask));
  552. // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
  553. const int astartofs = network.IsIPv4() ? 12 : 0;
  554. for(int x=astartofs; x<16; ++x)
  555. netmask[x] = mask.ip[x];
  556. // Normalize network according to netmask
  557. for(int x=0; x<16; ++x)
  558. network.ip[x] &= netmask[x];
  559. }
  560. CSubNet::CSubNet(const CNetAddr &addr):
  561. valid(addr.IsValid())
  562. {
  563. memset(netmask, 255, sizeof(netmask));
  564. network = addr;
  565. }
  566. bool CSubNet::Match(const CNetAddr &addr) const
  567. {
  568. if (!valid || !addr.IsValid())
  569. return false;
  570. for(int x=0; x<16; ++x)
  571. if ((addr.ip[x] & netmask[x]) != network.ip[x])
  572. return false;
  573. return true;
  574. }
  575. static inline int NetmaskBits(uint8_t x)
  576. {
  577. switch(x) {
  578. case 0x00: return 0; break;
  579. case 0x80: return 1; break;
  580. case 0xc0: return 2; break;
  581. case 0xe0: return 3; break;
  582. case 0xf0: return 4; break;
  583. case 0xf8: return 5; break;
  584. case 0xfc: return 6; break;
  585. case 0xfe: return 7; break;
  586. case 0xff: return 8; break;
  587. default: return -1; break;
  588. }
  589. }
  590. std::string CSubNet::ToString() const
  591. {
  592. /* Parse binary 1{n}0{N-n} to see if mask can be represented as /n */
  593. int cidr = 0;
  594. bool valid_cidr = true;
  595. int n = network.IsIPv4() ? 12 : 0;
  596. for (; n < 16 && netmask[n] == 0xff; ++n)
  597. cidr += 8;
  598. if (n < 16) {
  599. int bits = NetmaskBits(netmask[n]);
  600. if (bits < 0)
  601. valid_cidr = false;
  602. else
  603. cidr += bits;
  604. ++n;
  605. }
  606. for (; n < 16 && valid_cidr; ++n)
  607. if (netmask[n] != 0x00)
  608. valid_cidr = false;
  609. /* Format output */
  610. std::string strNetmask;
  611. if (valid_cidr) {
  612. strNetmask = strprintf("%u", cidr);
  613. } else {
  614. if (network.IsIPv4())
  615. strNetmask = strprintf("%u.%u.%u.%u", netmask[12], netmask[13], netmask[14], netmask[15]);
  616. else
  617. strNetmask = strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
  618. netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3],
  619. netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7],
  620. netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11],
  621. netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]);
  622. }
  623. return network.ToString() + "/" + strNetmask;
  624. }
  625. bool CSubNet::IsValid() const
  626. {
  627. return valid;
  628. }
  629. bool operator==(const CSubNet& a, const CSubNet& b)
  630. {
  631. return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
  632. }
  633. bool operator!=(const CSubNet& a, const CSubNet& b)
  634. {
  635. return !(a==b);
  636. }
  637. bool operator<(const CSubNet& a, const CSubNet& b)
  638. {
  639. return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0));
  640. }