Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2020 The Bitcoin Core developers
3 : // Distributed under the MIT software license, see the accompanying
4 : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 :
6 : #include <netaddress.h>
7 :
8 : #include <hash.h>
9 : #include <tinyformat.h>
10 : #include <util/strencodings.h>
11 : #include <util/asmap.h>
12 :
13 : #include <algorithm>
14 : #include <array>
15 : #include <cstdint>
16 : #include <iterator>
17 : #include <tuple>
18 :
19 : constexpr size_t CNetAddr::V1_SERIALIZATION_SIZE;
20 :
21 : /**
22 : * Construct an unspecified IPv6 network address (::/128).
23 : *
24 : * @note This address is considered invalid by CNetAddr::IsValid()
25 : */
26 3145687 : CNetAddr::CNetAddr() {}
27 :
28 1 : void CNetAddr::SetIP(const CNetAddr& ipIn)
29 : {
30 : // Size check.
31 1 : switch (ipIn.m_net) {
32 : case NET_IPV4:
33 0 : assert(ipIn.m_addr.size() == ADDR_IPV4_SIZE);
34 : break;
35 : case NET_IPV6:
36 1 : assert(ipIn.m_addr.size() == ADDR_IPV6_SIZE);
37 : break;
38 : case NET_ONION:
39 0 : assert(ipIn.m_addr.size() == ADDR_TORV2_SIZE);
40 : break;
41 : case NET_INTERNAL:
42 0 : assert(ipIn.m_addr.size() == ADDR_INTERNAL_SIZE);
43 : break;
44 : case NET_UNROUTABLE:
45 : case NET_MAX:
46 0 : assert(false);
47 : } // no default case, so the compiler can warn about missing cases
48 :
49 1 : m_net = ipIn.m_net;
50 1 : m_addr = ipIn.m_addr;
51 1 : }
52 :
53 : template <typename T1, size_t PREFIX_LEN>
54 28075132 : inline bool HasPrefix(const T1& obj, const std::array<uint8_t, PREFIX_LEN>& prefix)
55 : {
56 56150264 : return obj.size() >= PREFIX_LEN &&
57 28075132 : std::equal(std::begin(prefix), std::end(prefix), std::begin(obj));
58 : }
59 :
60 30025 : void CNetAddr::SetLegacyIPv6(Span<const uint8_t> ipv6)
61 : {
62 30025 : assert(ipv6.size() == ADDR_IPV6_SIZE);
63 :
64 : size_t skip{0};
65 :
66 30025 : if (HasPrefix(ipv6, IPV4_IN_IPV6_PREFIX)) {
67 : // IPv4-in-IPv6
68 11495 : m_net = NET_IPV4;
69 : skip = sizeof(IPV4_IN_IPV6_PREFIX);
70 30025 : } else if (HasPrefix(ipv6, TORV2_IN_IPV6_PREFIX)) {
71 : // TORv2-in-IPv6
72 4 : m_net = NET_ONION;
73 : skip = sizeof(TORV2_IN_IPV6_PREFIX);
74 18530 : } else if (HasPrefix(ipv6, INTERNAL_IN_IPV6_PREFIX)) {
75 : // Internal-in-IPv6
76 1 : m_net = NET_INTERNAL;
77 : skip = sizeof(INTERNAL_IN_IPV6_PREFIX);
78 1 : } else {
79 : // IPv6
80 18525 : m_net = NET_IPV6;
81 : }
82 :
83 30025 : m_addr.assign(ipv6.begin() + skip, ipv6.end());
84 30025 : }
85 :
86 : /**
87 : * Create an "internal" address that represents a name or FQDN. CAddrMan uses
88 : * these fake addresses to keep track of which DNS seeds were used.
89 : * @returns Whether or not the operation was successful.
90 : * @see NET_INTERNAL, INTERNAL_IN_IPV6_PREFIX, CNetAddr::IsInternal(), CNetAddr::IsRFC4193()
91 : */
92 269 : bool CNetAddr::SetInternal(const std::string &name)
93 : {
94 269 : if (name.empty()) {
95 0 : return false;
96 : }
97 269 : m_net = NET_INTERNAL;
98 2462127 : unsigned char hash[32] = {};
99 269 : CSHA256().Write((const unsigned char*)name.data(), name.size()).Finalize(hash);
100 269 : m_addr.assign(hash, hash + ADDR_INTERNAL_SIZE);
101 : return true;
102 269 : }
103 2461858 :
104 : /**
105 2461858 : * Parse a TORv2 address and set this object to it.
106 : *
107 : * @returns Whether or not the operation was successful.
108 : *
109 : * @see CNetAddr::IsTor()
110 : */
111 263384 : bool CNetAddr::SetSpecial(const std::string &strName)
112 : {
113 263384 : if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") {
114 7 : std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
115 7 : if (vchAddr.size() != ADDR_TORV2_SIZE) {
116 0 : return false;
117 : }
118 7 : m_net = NET_ONION;
119 7 : m_addr.assign(vchAddr.begin(), vchAddr.end());
120 7 : return true;
121 7 : }
122 263377 : return false;
123 263384 : }
124 :
125 525688 : CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
126 262253 : {
127 263435 : m_net = NET_IPV4;
128 263435 : const uint8_t* ptr = reinterpret_cast<const uint8_t*>(&ipv4Addr);
129 263435 : m_addr.assign(ptr, ptr + ADDR_IPV4_SIZE);
130 525688 : }
131 :
132 18698 : CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr, const uint32_t scope)
133 1124 : {
134 17574 : SetLegacyIPv6(Span<const uint8_t>(reinterpret_cast<const uint8_t*>(&ipv6Addr), sizeof(ipv6Addr)));
135 17574 : scopeId = scope;
136 18698 : }
137 :
138 1059 : bool CNetAddr::IsBindAny() const
139 : {
140 1059 : if (!IsIPv4() && !IsIPv6()) {
141 2 : return false;
142 : }
143 10022 : return std::all_of(m_addr.begin(), m_addr.end(), [](uint8_t b) { return b == 0; });
144 1059 : }
145 :
146 38946176 : bool CNetAddr::IsIPv4() const { return m_net == NET_IPV4; }
147 :
148 45145777 : bool CNetAddr::IsIPv6() const { return m_net == NET_IPV6; }
149 :
150 4791454 : bool CNetAddr::IsRFC1918() const
151 : {
152 5157534 : return IsIPv4() && (
153 366080 : m_addr[0] == 10 ||
154 365300 : (m_addr[0] == 192 && m_addr[1] == 168) ||
155 365299 : (m_addr[0] == 172 && m_addr[1] >= 16 && m_addr[1] <= 31));
156 : }
157 :
158 4790674 : bool CNetAddr::IsRFC2544() const
159 : {
160 4790674 : return IsIPv4() && m_addr[0] == 198 && (m_addr[1] == 18 || m_addr[1] == 19);
161 : }
162 :
163 4790673 : bool CNetAddr::IsRFC3927() const
164 : {
165 4790673 : return IsIPv4() && HasPrefix(m_addr, std::array<uint8_t, 2>{169, 254});
166 : }
167 :
168 4790669 : bool CNetAddr::IsRFC6598() const
169 : {
170 4790669 : return IsIPv4() && m_addr[0] == 100 && m_addr[1] >= 64 && m_addr[1] <= 127;
171 : }
172 :
173 4790669 : bool CNetAddr::IsRFC5737() const
174 : {
175 5155964 : return IsIPv4() && (HasPrefix(m_addr, std::array<uint8_t, 3>{192, 0, 2}) ||
176 365295 : HasPrefix(m_addr, std::array<uint8_t, 3>{198, 51, 100}) ||
177 365295 : HasPrefix(m_addr, std::array<uint8_t, 3>{203, 0, 113}));
178 : }
179 :
180 4974135 : bool CNetAddr::IsRFC3849() const
181 : {
182 4974135 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x0D, 0xB8});
183 : }
184 :
185 2065221 : bool CNetAddr::IsRFC3964() const
186 : {
187 2065221 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 2>{0x20, 0x02});
188 : }
189 :
190 2065226 : bool CNetAddr::IsRFC6052() const
191 : {
192 4130440 : return IsIPv6() &&
193 2065214 : HasPrefix(m_addr, std::array<uint8_t, 12>{0x00, 0x64, 0xFF, 0x9B, 0x00, 0x00,
194 : 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
195 : }
196 :
197 2065217 : bool CNetAddr::IsRFC4380() const
198 : {
199 2065217 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x00, 0x00});
200 : }
201 :
202 4790670 : bool CNetAddr::IsRFC4862() const
203 : {
204 4790670 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 8>{0xFE, 0x80, 0x00, 0x00,
205 : 0x00, 0x00, 0x00, 0x00});
206 : }
207 :
208 4790670 : bool CNetAddr::IsRFC4193() const
209 : {
210 4790670 : return IsIPv6() && (m_addr[0] & 0xFE) == 0xFC;
211 : }
212 :
213 2065227 : bool CNetAddr::IsRFC6145() const
214 : {
215 4130442 : return IsIPv6() &&
216 2065215 : HasPrefix(m_addr, std::array<uint8_t, 12>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
217 : 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00});
218 : }
219 :
220 4788276 : bool CNetAddr::IsRFC4843() const
221 : {
222 4788285 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 3>{0x20, 0x01, 0x00}) &&
223 9 : (m_addr[3] & 0xF0) == 0x10;
224 : }
225 :
226 4788276 : bool CNetAddr::IsRFC7343() const
227 : {
228 4788285 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 3>{0x20, 0x01, 0x00}) &&
229 9 : (m_addr[3] & 0xF0) == 0x20;
230 : }
231 :
232 589430 : bool CNetAddr::IsHeNet() const
233 : {
234 589430 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x04, 0x70});
235 : }
236 :
237 : /**
238 : * @returns Whether or not this is a dummy address that maps an onion address
239 : * into IPv6.
240 : *
241 : * @see CNetAddr::SetSpecial(const std::string &)
242 : */
243 2298878 : bool CNetAddr::IsTor() const { return m_net == NET_ONION; }
244 :
245 7117306 : bool CNetAddr::IsLocal() const
246 : {
247 : // IPv4 loopback (127.0.0.0/8 or 0.0.0.0/8)
248 7117306 : if (IsIPv4() && (m_addr[0] == 127 || m_addr[0] == 0)) {
249 71084 : return true;
250 : }
251 :
252 : // IPv6 loopback (::1/128)
253 : static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
254 7046222 : if (IsIPv6() && memcmp(m_addr.data(), pchLocal, sizeof(pchLocal)) == 0) {
255 2 : return true;
256 : }
257 :
258 7046220 : return false;
259 7117306 : }
260 :
261 : /**
262 : * @returns Whether or not this network address is a valid address that @a could
263 : * be used to refer to an actual host.
264 : *
265 : * @note A valid address may or may not be publicly routable on the global
266 : * internet. As in, the set of valid addresses is a superset of the set of
267 : * publicly routable addresses.
268 : *
269 : * @see CNetAddr::IsRoutable()
270 : */
271 5111925 : bool CNetAddr::IsValid() const
272 : {
273 : // unspecified IPv6 address (::/128)
274 5111925 : unsigned char ipNone6[16] = {};
275 5111925 : if (IsIPv6() && memcmp(m_addr.data(), ipNone6, sizeof(ipNone6)) == 0) {
276 137791 : return false;
277 : }
278 :
279 : // documentation IPv6 address
280 4974134 : if (IsRFC3849())
281 0 : return false;
282 :
283 4974134 : if (IsInternal())
284 1 : return false;
285 :
286 4974133 : if (IsIPv4()) {
287 548742 : const uint32_t addr = ReadBE32(m_addr.data());
288 548742 : if (addr == INADDR_ANY || addr == INADDR_NONE) {
289 8 : return false;
290 : }
291 548734 : }
292 :
293 4974125 : return true;
294 5111925 : }
295 :
296 : /**
297 : * @returns Whether or not this network address is publicly routable on the
298 : * global internet.
299 : *
300 : * @note A routable address is always valid. As in, the set of routable addresses
301 : * is a subset of the set of valid addresses.
302 : *
303 : * @see CNetAddr::IsValid()
304 : */
305 4868912 : bool CNetAddr::IsRoutable() const
306 : {
307 4868912 : return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsRFC7343() || IsLocal() || IsInternal());
308 : }
309 :
310 : /**
311 : * @returns Whether or not this is a dummy address that represents a name.
312 : *
313 : * @see CNetAddr::SetInternal(const std::string &)
314 : */
315 12554859 : bool CNetAddr::IsInternal() const
316 : {
317 12554859 : return m_net == NET_INTERNAL;
318 : }
319 :
320 10840 : enum Network CNetAddr::GetNetwork() const
321 : {
322 10840 : if (IsInternal())
323 1 : return NET_INTERNAL;
324 :
325 10839 : if (!IsRoutable())
326 1003 : return NET_UNROUTABLE;
327 :
328 9836 : return m_net;
329 10840 : }
330 :
331 229958 : std::string CNetAddr::ToStringIP() const
332 : {
333 229958 : if (IsTor())
334 5 : return EncodeBase32(m_addr) + ".onion";
335 229953 : if (IsInternal())
336 1 : return EncodeBase32(m_addr) + ".internal";
337 229952 : CService serv(*this, 0);
338 229952 : struct sockaddr_storage sockaddr;
339 229952 : socklen_t socklen = sizeof(sockaddr);
340 229952 : if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
341 229952 : char name[1025] = "";
342 229952 : if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), nullptr, 0, NI_NUMERICHOST))
343 229952 : return std::string(name);
344 229952 : }
345 0 : if (IsIPv4())
346 0 : return strprintf("%u.%u.%u.%u", m_addr[0], m_addr[1], m_addr[2], m_addr[3]);
347 0 : assert(IsIPv6());
348 0 : return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
349 0 : m_addr[0] << 8 | m_addr[1], m_addr[2] << 8 | m_addr[3],
350 0 : m_addr[4] << 8 | m_addr[5], m_addr[6] << 8 | m_addr[7],
351 0 : m_addr[8] << 8 | m_addr[9], m_addr[10] << 8 | m_addr[11],
352 0 : m_addr[12] << 8 | m_addr[13], m_addr[14] << 8 | m_addr[15]);
353 229958 : }
354 :
355 12853 : std::string CNetAddr::ToString() const
356 : {
357 12853 : return ToStringIP();
358 : }
359 :
360 328685 : bool operator==(const CNetAddr& a, const CNetAddr& b)
361 : {
362 328685 : return a.m_net == b.m_net && a.m_addr == b.m_addr;
363 : }
364 :
365 11580180 : bool operator<(const CNetAddr& a, const CNetAddr& b)
366 : {
367 11580180 : return std::tie(a.m_net, a.m_addr) < std::tie(b.m_net, b.m_addr);
368 : }
369 :
370 : /**
371 : * Try to get our IPv4 address.
372 : *
373 : * @param[out] pipv4Addr The in_addr struct to which to copy.
374 : *
375 : * @returns Whether or not the operation was successful, in particular, whether
376 : * or not our address was an IPv4 address.
377 : *
378 : * @see CNetAddr::IsIPv4()
379 : */
380 229593 : bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
381 : {
382 229593 : if (!IsIPv4())
383 0 : return false;
384 229593 : assert(sizeof(*pipv4Addr) == m_addr.size());
385 229593 : memcpy(pipv4Addr, m_addr.data(), m_addr.size());
386 229593 : return true;
387 229593 : }
388 :
389 : /**
390 : * Try to get our IPv6 address.
391 : *
392 : * @param[out] pipv6Addr The in6_addr struct to which to copy.
393 : *
394 : * @returns Whether or not the operation was successful, in particular, whether
395 : * or not our address was an IPv6 address.
396 : *
397 : * @see CNetAddr::IsIPv6()
398 : */
399 1855 : bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
400 : {
401 1855 : if (!IsIPv6()) {
402 0 : return false;
403 : }
404 1855 : assert(sizeof(*pipv6Addr) == m_addr.size());
405 1855 : memcpy(pipv6Addr, m_addr.data(), m_addr.size());
406 1855 : return true;
407 1855 : }
408 :
409 2219673 : bool CNetAddr::HasLinkedIPv4() const
410 : {
411 2219673 : return IsRoutable() && (IsIPv4() || IsRFC6145() || IsRFC6052() || IsRFC3964() || IsRFC4380());
412 : }
413 :
414 44548 : uint32_t CNetAddr::GetLinkedIPv4() const
415 : {
416 44548 : if (IsIPv4()) {
417 44544 : return ReadBE32(m_addr.data());
418 4 : } else if (IsRFC6052() || IsRFC6145()) {
419 : // mapped IPv4, SIIT translated IPv4: the IPv4 address is the last 4 bytes of the address
420 2 : return ReadBE32(MakeSpan(m_addr).last(ADDR_IPV4_SIZE).data());
421 2 : } else if (IsRFC3964()) {
422 : // 6to4 tunneled IPv4: the IPv4 address is in bytes 2-6
423 1 : return ReadBE32(MakeSpan(m_addr).subspan(2, ADDR_IPV4_SIZE).data());
424 1 : } else if (IsRFC4380()) {
425 : // Teredo tunneled IPv4: the IPv4 address is in the last 4 bytes of the address, but bitflipped
426 1 : return ~ReadBE32(MakeSpan(m_addr).last(ADDR_IPV4_SIZE).data());
427 : }
428 0 : assert(false);
429 44548 : }
430 :
431 1665674 : uint32_t CNetAddr::GetNetClass() const {
432 : uint32_t net_class = NET_IPV6;
433 1665674 : if (IsLocal()) {
434 : net_class = 255;
435 29041 : }
436 1665674 : if (IsInternal()) {
437 : net_class = NET_INTERNAL;
438 1665674 : } else if (!IsRoutable()) {
439 : net_class = NET_UNROUTABLE;
440 1665672 : } else if (HasLinkedIPv4()) {
441 : net_class = NET_IPV4;
442 1585691 : } else if (IsTor()) {
443 : net_class = NET_ONION;
444 8 : }
445 1665674 : return net_class;
446 : }
447 :
448 998806 : uint32_t CNetAddr::GetMappedAS(const std::vector<bool> &asmap) const {
449 998806 : uint32_t net_class = GetNetClass();
450 998806 : if (asmap.size() == 0 || (net_class != NET_IPV4 && net_class != NET_IPV6)) {
451 992395 : return 0; // Indicates not found, safe because AS0 is reserved per RFC7607.
452 : }
453 6411 : std::vector<bool> ip_bits(128);
454 6411 : if (HasLinkedIPv4()) {
455 : // For lookup, treat as if it was just an IPv4 address (IPV4_IN_IPV6_PREFIX + IPv4 bits)
456 83343 : for (int8_t byte_i = 0; byte_i < 12; ++byte_i) {
457 692388 : for (uint8_t bit_i = 0; bit_i < 8; ++bit_i) {
458 615456 : ip_bits[byte_i * 8 + bit_i] = (IPV4_IN_IPV6_PREFIX[byte_i] >> (7 - bit_i)) & 1;
459 : }
460 : }
461 6411 : uint32_t ipv4 = GetLinkedIPv4();
462 211563 : for (int i = 0; i < 32; ++i) {
463 205152 : ip_bits[96 + i] = (ipv4 >> (31 - i)) & 1;
464 : }
465 6411 : } else {
466 : // Use all 128 bits of the IPv6 address otherwise
467 0 : assert(IsIPv6());
468 0 : for (int8_t byte_i = 0; byte_i < 16; ++byte_i) {
469 0 : uint8_t cur_byte = m_addr[byte_i];
470 0 : for (uint8_t bit_i = 0; bit_i < 8; ++bit_i) {
471 0 : ip_bits[byte_i * 8 + bit_i] = (cur_byte >> (7 - bit_i)) & 1;
472 : }
473 : }
474 : }
475 6411 : uint32_t mapped_as = Interpret(asmap, ip_bits);
476 : return mapped_as;
477 998806 : }
478 :
479 : /**
480 : * Get the canonical identifier of our network group
481 : *
482 : * The groups are assigned in a way where it should be costly for an attacker to
483 : * obtain addresses with many different group identifiers, even if it is cheap
484 : * to obtain addresses with the same identifier.
485 : *
486 : * @note No two connections will be attempted to addresses with the same network
487 : * group.
488 : */
489 666868 : std::vector<unsigned char> CNetAddr::GetGroup(const std::vector<bool> &asmap) const
490 : {
491 666868 : std::vector<unsigned char> vchRet;
492 666868 : uint32_t net_class = GetNetClass();
493 : // If non-empty asmap is supplied and the address is IPv4/IPv6,
494 : // return ASN to be used for bucketing.
495 666868 : uint32_t asn = GetMappedAS(asmap);
496 666868 : if (asn != 0) { // Either asmap was empty, or address has non-asmappable net class (e.g. TOR).
497 3623 : vchRet.push_back(NET_IPV6); // IPv4 and IPv6 with same ASN should be in the same bucket
498 18115 : for (int i = 0; i < 4; i++) {
499 14492 : vchRet.push_back((asn >> (8 * i)) & 0xFF);
500 : }
501 3623 : return vchRet;
502 : }
503 :
504 663245 : vchRet.push_back(net_class);
505 : int nBits{0};
506 :
507 663245 : if (IsLocal()) {
508 : // all local addresses belong to the same group
509 653042 : } else if (IsInternal()) {
510 : // all internal-usage addresses get their own group
511 : nBits = ADDR_INTERNAL_SIZE * 8;
512 653042 : } else if (!IsRoutable()) {
513 : // all other unroutable addresses belong to the same group
514 627571 : } else if (HasLinkedIPv4()) {
515 : // IPv4 addresses (and mapped IPv4 addresses) use /16 groups
516 38137 : uint32_t ipv4 = GetLinkedIPv4();
517 38137 : vchRet.push_back((ipv4 >> 24) & 0xFF);
518 38137 : vchRet.push_back((ipv4 >> 16) & 0xFF);
519 : return vchRet;
520 589434 : } else if (IsTor()) {
521 : nBits = 4;
522 589434 : } else if (IsHeNet()) {
523 : // for he.net, use /36 groups
524 : nBits = 36;
525 1 : } else {
526 : // for the rest of the IPv6 network, use /32 groups
527 : nBits = 32;
528 : }
529 :
530 : // Push our address onto vchRet.
531 625108 : const size_t num_bytes = nBits / 8;
532 625108 : vchRet.insert(vchRet.end(), m_addr.begin(), m_addr.begin() + num_bytes);
533 625108 : nBits %= 8;
534 : // ...for the last byte, push nBits and for the rest of the byte push 1's
535 625108 : if (nBits > 0) {
536 5 : assert(num_bytes < m_addr.size());
537 5 : vchRet.push_back(m_addr[num_bytes] | ((1 << (8 - nBits)) - 1));
538 5 : }
539 :
540 : return vchRet;
541 666868 : }
542 :
543 4379521 : std::vector<unsigned char> CNetAddr::GetAddrBytes() const
544 : {
545 4379521 : uint8_t serialized[V1_SERIALIZATION_SIZE];
546 4379521 : SerializeV1Array(serialized);
547 4379521 : return {std::begin(serialized), std::end(serialized)};
548 4379521 : }
549 :
550 10 : uint64_t CNetAddr::GetHash() const
551 : {
552 10 : uint256 hash = Hash(m_addr);
553 : uint64_t nRet;
554 10 : memcpy(&nRet, &hash, sizeof(nRet));
555 10 : return nRet;
556 10 : }
557 :
558 : // private extensions to enum Network, only returned by GetExtNetwork,
559 : // and only used in GetReachabilityFrom
560 : static const int NET_UNKNOWN = NET_MAX + 0;
561 : static const int NET_TEREDO = NET_MAX + 1;
562 0 : int static GetExtNetwork(const CNetAddr *addr)
563 : {
564 0 : if (addr == nullptr)
565 0 : return NET_UNKNOWN;
566 0 : if (addr->IsRFC4380())
567 0 : return NET_TEREDO;
568 0 : return addr->GetNetwork();
569 0 : }
570 :
571 : /** Calculates a metric for how reachable (*this) is from a given partner */
572 1 : int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
573 : {
574 : enum Reachability {
575 : REACH_UNREACHABLE,
576 : REACH_DEFAULT,
577 : REACH_TEREDO,
578 : REACH_IPV6_WEAK,
579 : REACH_IPV4,
580 : REACH_IPV6_STRONG,
581 : REACH_PRIVATE
582 : };
583 :
584 1 : if (!IsRoutable() || IsInternal())
585 1 : return REACH_UNREACHABLE;
586 :
587 0 : int ourNet = GetExtNetwork(this);
588 0 : int theirNet = GetExtNetwork(paddrPartner);
589 0 : bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
590 :
591 0 : switch(theirNet) {
592 : case NET_IPV4:
593 0 : switch(ourNet) {
594 0 : default: return REACH_DEFAULT;
595 0 : case NET_IPV4: return REACH_IPV4;
596 : }
597 : case NET_IPV6:
598 0 : switch(ourNet) {
599 0 : default: return REACH_DEFAULT;
600 0 : case NET_TEREDO: return REACH_TEREDO;
601 0 : case NET_IPV4: return REACH_IPV4;
602 0 : case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
603 : }
604 : case NET_ONION:
605 0 : switch(ourNet) {
606 0 : default: return REACH_DEFAULT;
607 0 : case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
608 0 : case NET_ONION: return REACH_PRIVATE;
609 : }
610 : case NET_TEREDO:
611 0 : switch(ourNet) {
612 0 : default: return REACH_DEFAULT;
613 0 : case NET_TEREDO: return REACH_TEREDO;
614 0 : case NET_IPV6: return REACH_IPV6_WEAK;
615 0 : case NET_IPV4: return REACH_IPV4;
616 : }
617 : case NET_UNKNOWN:
618 : case NET_UNROUTABLE:
619 : default:
620 0 : switch(ourNet) {
621 0 : default: return REACH_DEFAULT;
622 0 : case NET_TEREDO: return REACH_TEREDO;
623 0 : case NET_IPV6: return REACH_IPV6_WEAK;
624 0 : case NET_IPV4: return REACH_IPV4;
625 0 : case NET_ONION: return REACH_PRIVATE; // either from Tor, or don't care about our address
626 : }
627 : }
628 1 : }
629 :
630 1958493 : CService::CService() : port(0)
631 1958493 : {
632 1958493 : }
633 :
634 970680 : CService::CService(const CNetAddr& cip, uint16_t portIn) : CNetAddr(cip), port(portIn)
635 970680 : {
636 970680 : }
637 :
638 6 : CService::CService(const struct in_addr& ipv4Addr, uint16_t portIn) : CNetAddr(ipv4Addr), port(portIn)
639 6 : {
640 6 : }
641 :
642 32900 : CService::CService(const struct in6_addr& ipv6Addr, uint16_t portIn) : CNetAddr(ipv6Addr), port(portIn)
643 32900 : {
644 32900 : }
645 :
646 2358 : CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
647 2358 : {
648 1179 : assert(addr.sin_family == AF_INET);
649 2358 : }
650 :
651 0 : CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr, addr.sin6_scope_id), port(ntohs(addr.sin6_port))
652 0 : {
653 0 : assert(addr.sin6_family == AF_INET6);
654 0 : }
655 :
656 1179 : bool CService::SetSockAddr(const struct sockaddr *paddr)
657 : {
658 1179 : switch (paddr->sa_family) {
659 : case AF_INET:
660 1179 : *this = CService(*(const struct sockaddr_in*)paddr);
661 1179 : return true;
662 : case AF_INET6:
663 0 : *this = CService(*(const struct sockaddr_in6*)paddr);
664 0 : return true;
665 : default:
666 0 : return false;
667 : }
668 1179 : }
669 :
670 18136 : uint16_t CService::GetPort() const
671 : {
672 18136 : return port;
673 : }
674 :
675 2781 : bool operator==(const CService& a, const CService& b)
676 : {
677 2781 : return static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port == b.port;
678 0 : }
679 :
680 11992 : bool operator<(const CService& a, const CService& b)
681 : {
682 11992 : return static_cast<CNetAddr>(a) < static_cast<CNetAddr>(b) || (static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port < b.port);
683 0 : }
684 :
685 : /**
686 : * Obtain the IPv4/6 socket address this represents.
687 : *
688 : * @param[out] paddr The obtained socket address.
689 : * @param[in,out] addrlen The size, in bytes, of the address structure pointed
690 : * to by paddr. The value that's pointed to by this
691 : * parameter might change after calling this function if
692 : * the size of the corresponding address structure
693 : * changed.
694 : *
695 : * @returns Whether or not the operation was successful.
696 : */
697 231448 : bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
698 : {
699 231448 : if (IsIPv4()) {
700 229593 : if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
701 0 : return false;
702 229593 : *addrlen = sizeof(struct sockaddr_in);
703 229593 : struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
704 229593 : memset(paddrin, 0, *addrlen);
705 229593 : if (!GetInAddr(&paddrin->sin_addr))
706 0 : return false;
707 229593 : paddrin->sin_family = AF_INET;
708 229593 : paddrin->sin_port = htons(port);
709 229593 : return true;
710 : }
711 1855 : if (IsIPv6()) {
712 1855 : if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
713 0 : return false;
714 1855 : *addrlen = sizeof(struct sockaddr_in6);
715 1855 : struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
716 1855 : memset(paddrin6, 0, *addrlen);
717 1855 : if (!GetIn6Addr(&paddrin6->sin6_addr))
718 0 : return false;
719 1855 : paddrin6->sin6_scope_id = scopeId;
720 1855 : paddrin6->sin6_family = AF_INET6;
721 1855 : paddrin6->sin6_port = htons(port);
722 1855 : return true;
723 : }
724 0 : return false;
725 231448 : }
726 :
727 : /**
728 : * @returns An identifier unique to this service's address and port number.
729 : */
730 4349724 : std::vector<unsigned char> CService::GetKey() const
731 : {
732 4349724 : auto key = GetAddrBytes();
733 4349724 : key.push_back(port / 0x100); // most significant byte of our port
734 4349724 : key.push_back(port & 0x0FF); // least significant byte of our port
735 : return key;
736 4349724 : }
737 :
738 173060 : std::string CService::ToStringPort() const
739 : {
740 173060 : return strprintf("%u", port);
741 : }
742 :
743 173060 : std::string CService::ToStringIPPort() const
744 : {
745 173060 : if (IsIPv4() || IsTor() || IsInternal()) {
746 171749 : return ToStringIP() + ":" + ToStringPort();
747 : } else {
748 1311 : return "[" + ToStringIP() + "]:" + ToStringPort();
749 : }
750 173060 : }
751 :
752 170338 : std::string CService::ToString() const
753 : {
754 170338 : return ToStringIPPort();
755 : }
756 :
757 2932 : CSubNet::CSubNet():
758 1466 : valid(false)
759 1466 : {
760 1466 : memset(netmask, 0, sizeof(netmask));
761 2932 : }
762 :
763 566 : CSubNet::CSubNet(const CNetAddr& addr, uint8_t mask) : CSubNet()
764 : {
765 579 : valid = (addr.IsIPv4() && mask <= ADDR_IPV4_SIZE * 8) ||
766 13 : (addr.IsIPv6() && mask <= ADDR_IPV6_SIZE * 8);
767 566 : if (!valid) {
768 : return;
769 : }
770 :
771 563 : assert(mask <= sizeof(netmask) * 8);
772 :
773 563 : network = addr;
774 :
775 : uint8_t n = mask;
776 2935 : for (size_t i = 0; i < network.m_addr.size(); ++i) {
777 2372 : const uint8_t bits = n < 8 ? n : 8;
778 2372 : netmask[i] = (uint8_t)((uint8_t)0xFF << (8 - bits)); // Set first bits.
779 2372 : network.m_addr[i] &= netmask[i]; // Normalize network according to netmask.
780 2372 : n -= bits;
781 : }
782 566 : }
783 :
784 : /**
785 : * @returns The number of 1-bits in the prefix of the specified subnet mask. If
786 : * the specified subnet mask is not a valid one, -1.
787 : */
788 9409 : static inline int NetmaskBits(uint8_t x)
789 : {
790 9409 : switch(x) {
791 108 : case 0x00: return 0;
792 8 : case 0x80: return 1;
793 8 : case 0xc0: return 2;
794 11 : case 0xe0: return 3;
795 8 : case 0xf0: return 4;
796 8 : case 0xf8: return 5;
797 10 : case 0xfc: return 6;
798 9 : case 0xfe: return 7;
799 9237 : case 0xff: return 8;
800 2 : default: return -1;
801 : }
802 9409 : }
803 :
804 50 : CSubNet::CSubNet(const CNetAddr& addr, const CNetAddr& mask) : CSubNet()
805 : {
806 50 : valid = (addr.IsIPv4() || addr.IsIPv6()) && addr.m_net == mask.m_net;
807 50 : if (!valid) {
808 : return;
809 : }
810 : // Check if `mask` contains 1-bits after 0-bits (which is an invalid netmask).
811 281 : bool zeros_found = false;
812 285 : for (auto b : mask.m_addr) {
813 238 : const int num_bits = NetmaskBits(b);
814 238 : if (num_bits == -1 || (zeros_found && num_bits != 0)) {
815 4 : valid = false;
816 4 : return;
817 : }
818 234 : if (num_bits < 8) {
819 : zeros_found = true;
820 138 : }
821 468 : }
822 :
823 43 : assert(mask.m_addr.size() <= sizeof(netmask));
824 :
825 43 : memcpy(netmask, mask.m_addr.data(), mask.m_addr.size());
826 :
827 43 : network = addr;
828 :
829 : // Normalize network according to netmask
830 263 : for (size_t x = 0; x < network.m_addr.size(); ++x) {
831 220 : network.m_addr[x] &= netmask[x];
832 : }
833 93 : }
834 :
835 616 : CSubNet::CSubNet(const CNetAddr& addr) : CSubNet()
836 : {
837 616 : valid = addr.IsIPv4() || addr.IsIPv6();
838 616 : if (!valid) {
839 : return;
840 : }
841 :
842 615 : assert(addr.m_addr.size() <= sizeof(netmask));
843 :
844 615 : memset(netmask, 0xFF, addr.m_addr.size());
845 :
846 615 : network = addr;
847 616 : }
848 :
849 : /**
850 : * @returns True if this subnet is valid, the specified address is valid, and
851 : * the specified address belongs in this subnet.
852 : */
853 79177 : bool CSubNet::Match(const CNetAddr &addr) const
854 : {
855 79177 : if (!valid || !addr.IsValid() || network.m_net != addr.m_net)
856 8 : return false;
857 79169 : assert(network.m_addr.size() == addr.m_addr.size());
858 395896 : for (size_t x = 0; x < addr.m_addr.size(); ++x) {
859 316735 : if ((addr.m_addr[x] & netmask[x]) != network.m_addr[x]) {
860 8 : return false;
861 : }
862 : }
863 79161 : return true;
864 79177 : }
865 :
866 1118 : std::string CSubNet::ToString() const
867 : {
868 1118 : assert(network.m_addr.size() <= sizeof(netmask));
869 :
870 1118 : uint8_t cidr = 0;
871 :
872 10289 : for (size_t i = 0; i < network.m_addr.size(); ++i) {
873 9740 : if (netmask[i] == 0x00) {
874 569 : break;
875 : }
876 9171 : cidr += NetmaskBits(netmask[i]);
877 : }
878 :
879 1118 : return network.ToString() + strprintf("/%u", cidr);
880 1118 : }
881 :
882 242 : bool CSubNet::IsValid() const
883 : {
884 242 : return valid;
885 : }
886 :
887 2 : bool operator==(const CSubNet& a, const CSubNet& b)
888 : {
889 2 : return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
890 : }
891 :
892 85 : bool operator<(const CSubNet& a, const CSubNet& b)
893 : {
894 85 : return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0));
895 : }
896 :
897 5 : bool SanityCheckASMap(const std::vector<bool>& asmap)
898 : {
899 5 : return SanityCheckASMap(asmap, 128); // For IP address lookups, the input is 128 bits
900 : }
|