Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2022 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 <crypto/common.h>
9 : #include <crypto/sha3.h>
10 : #include <hash.h>
11 : #include <prevector.h>
12 : #include <tinyformat.h>
13 : #include <util/strencodings.h>
14 : #include <util/string.h>
15 :
16 : #include <algorithm>
17 : #include <array>
18 : #include <cstdint>
19 : #include <ios>
20 : #include <iterator>
21 : #include <tuple>
22 :
23 0 : CNetAddr::BIP155Network CNetAddr::GetBIP155Network() const
24 : {
25 0 : switch (m_net) {
26 : case NET_IPV4:
27 0 : return BIP155Network::IPV4;
28 : case NET_IPV6:
29 0 : return BIP155Network::IPV6;
30 : case NET_ONION:
31 0 : return BIP155Network::TORV3;
32 : case NET_I2P:
33 0 : return BIP155Network::I2P;
34 : case NET_CJDNS:
35 0 : return BIP155Network::CJDNS;
36 : case NET_INTERNAL: // should have been handled before calling this function
37 : case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE
38 : case NET_MAX: // m_net is never and should not be set to NET_MAX
39 0 : assert(false);
40 : } // no default case, so the compiler can warn about missing cases
41 :
42 0 : assert(false);
43 0 : }
44 :
45 0 : bool CNetAddr::SetNetFromBIP155Network(uint8_t possible_bip155_net, size_t address_size)
46 : {
47 0 : switch (possible_bip155_net) {
48 : case BIP155Network::IPV4:
49 0 : if (address_size == ADDR_IPV4_SIZE) {
50 0 : m_net = NET_IPV4;
51 0 : return true;
52 : }
53 0 : throw std::ios_base::failure(
54 0 : strprintf("BIP155 IPv4 address with length %u (should be %u)", address_size,
55 : ADDR_IPV4_SIZE));
56 : case BIP155Network::IPV6:
57 0 : if (address_size == ADDR_IPV6_SIZE) {
58 0 : m_net = NET_IPV6;
59 0 : return true;
60 : }
61 0 : throw std::ios_base::failure(
62 0 : strprintf("BIP155 IPv6 address with length %u (should be %u)", address_size,
63 : ADDR_IPV6_SIZE));
64 : case BIP155Network::TORV3:
65 0 : if (address_size == ADDR_TORV3_SIZE) {
66 0 : m_net = NET_ONION;
67 0 : return true;
68 : }
69 0 : throw std::ios_base::failure(
70 0 : strprintf("BIP155 TORv3 address with length %u (should be %u)", address_size,
71 : ADDR_TORV3_SIZE));
72 : case BIP155Network::I2P:
73 0 : if (address_size == ADDR_I2P_SIZE) {
74 2 : m_net = NET_I2P;
75 0 : return true;
76 : }
77 0 : throw std::ios_base::failure(
78 0 : strprintf("BIP155 I2P address with length %u (should be %u)", address_size,
79 : ADDR_I2P_SIZE));
80 : case BIP155Network::CJDNS:
81 0 : if (address_size == ADDR_CJDNS_SIZE) {
82 0 : m_net = NET_CJDNS;
83 0 : return true;
84 : }
85 0 : throw std::ios_base::failure(
86 0 : strprintf("BIP155 CJDNS address with length %u (should be %u)", address_size,
87 : ADDR_CJDNS_SIZE));
88 : }
89 :
90 : // Don't throw on addresses with unknown network ids (maybe from the future).
91 : // Instead silently drop them and have the unserialization code consume
92 : // subsequent ones which may be known to us.
93 0 : return false;
94 0 : }
95 :
96 : /**
97 : * Construct an unspecified IPv6 network address (::/128).
98 : *
99 : * @note This address is considered invalid by CNetAddr::IsValid()
100 : */
101 32 : CNetAddr::CNetAddr() = default;
102 :
103 0 : void CNetAddr::SetIP(const CNetAddr& ipIn)
104 : {
105 : // Size check.
106 0 : switch (ipIn.m_net) {
107 : case NET_IPV4:
108 0 : assert(ipIn.m_addr.size() == ADDR_IPV4_SIZE);
109 0 : break;
110 : case NET_IPV6:
111 0 : assert(ipIn.m_addr.size() == ADDR_IPV6_SIZE);
112 0 : break;
113 : case NET_ONION:
114 0 : assert(ipIn.m_addr.size() == ADDR_TORV3_SIZE);
115 0 : break;
116 : case NET_I2P:
117 0 : assert(ipIn.m_addr.size() == ADDR_I2P_SIZE);
118 16 : break;
119 : case NET_CJDNS:
120 0 : assert(ipIn.m_addr.size() == ADDR_CJDNS_SIZE);
121 0 : break;
122 : case NET_INTERNAL:
123 16 : assert(ipIn.m_addr.size() == ADDR_INTERNAL_SIZE);
124 0 : break;
125 : case NET_UNROUTABLE:
126 : case NET_MAX:
127 0 : assert(false);
128 : } // no default case, so the compiler can warn about missing cases
129 16 :
130 0 : m_net = ipIn.m_net;
131 0 : m_addr = ipIn.m_addr;
132 0 : }
133 :
134 0 : void CNetAddr::SetLegacyIPv6(Span<const uint8_t> ipv6)
135 : {
136 0 : assert(ipv6.size() == ADDR_IPV6_SIZE);
137 :
138 0 : size_t skip{0};
139 :
140 0 : if (HasPrefix(ipv6, IPV4_IN_IPV6_PREFIX)) {
141 : // IPv4-in-IPv6
142 0 : m_net = NET_IPV4;
143 0 : skip = sizeof(IPV4_IN_IPV6_PREFIX);
144 0 : } else if (HasPrefix(ipv6, TORV2_IN_IPV6_PREFIX)) {
145 : // TORv2-in-IPv6 (unsupported). Unserialize as !IsValid(), thus ignoring them.
146 : // Mimic a default-constructed CNetAddr object which is !IsValid() and thus
147 : // will not be gossiped, but continue reading next addresses from the stream.
148 0 : m_net = NET_IPV6;
149 0 : m_addr.assign(ADDR_IPV6_SIZE, 0x0);
150 0 : return;
151 0 : } else if (HasPrefix(ipv6, INTERNAL_IN_IPV6_PREFIX)) {
152 : // Internal-in-IPv6
153 0 : m_net = NET_INTERNAL;
154 0 : skip = sizeof(INTERNAL_IN_IPV6_PREFIX);
155 0 : } else {
156 : // IPv6
157 0 : m_net = NET_IPV6;
158 : }
159 :
160 0 : m_addr.assign(ipv6.begin() + skip, ipv6.end());
161 0 : }
162 :
163 : /**
164 : * Create an "internal" address that represents a name or FQDN. AddrMan uses
165 : * these fake addresses to keep track of which DNS seeds were used.
166 : * @returns Whether or not the operation was successful.
167 : * @see NET_INTERNAL, INTERNAL_IN_IPV6_PREFIX, CNetAddr::IsInternal(), CNetAddr::IsRFC4193()
168 : */
169 0 : bool CNetAddr::SetInternal(const std::string &name)
170 : {
171 0 : if (name.empty()) {
172 0 : return false;
173 : }
174 0 : m_net = NET_INTERNAL;
175 0 : unsigned char hash[32] = {};
176 0 : CSHA256().Write((const unsigned char*)name.data(), name.size()).Finalize(hash);
177 0 : m_addr.assign(hash, hash + ADDR_INTERNAL_SIZE);
178 0 : return true;
179 0 : }
180 :
181 : namespace torv3 {
182 : // https://gitweb.torproject.org/torspec.git/tree/rend-spec-v3.txt?id=7116c9cdaba248aae07a3f1d0e15d9dd102f62c5#n2175
183 : static constexpr size_t CHECKSUM_LEN = 2;
184 : static const unsigned char VERSION[] = {3};
185 : static constexpr size_t TOTAL_LEN = ADDR_TORV3_SIZE + CHECKSUM_LEN + sizeof(VERSION);
186 :
187 0 : static void Checksum(Span<const uint8_t> addr_pubkey, uint8_t (&checksum)[CHECKSUM_LEN])
188 : {
189 : // TORv3 CHECKSUM = H(".onion checksum" | PUBKEY | VERSION)[:2]
190 : static const unsigned char prefix[] = ".onion checksum";
191 : static constexpr size_t prefix_len = 15;
192 :
193 0 : SHA3_256 hasher;
194 :
195 0 : hasher.Write(Span{prefix}.first(prefix_len));
196 0 : hasher.Write(addr_pubkey);
197 0 : hasher.Write(VERSION);
198 :
199 : uint8_t checksum_full[SHA3_256::OUTPUT_SIZE];
200 :
201 0 : hasher.Finalize(checksum_full);
202 :
203 0 : memcpy(checksum, checksum_full, sizeof(checksum));
204 0 : }
205 :
206 : }; // namespace torv3
207 :
208 0 : bool CNetAddr::SetSpecial(const std::string& addr)
209 : {
210 0 : if (!ContainsNoNUL(addr)) {
211 0 : return false;
212 : }
213 :
214 0 : if (SetTor(addr)) {
215 0 : return true;
216 : }
217 :
218 0 : if (SetI2P(addr)) {
219 0 : return true;
220 : }
221 :
222 0 : return false;
223 0 : }
224 :
225 0 : bool CNetAddr::SetTor(const std::string& addr)
226 : {
227 : static const char* suffix{".onion"};
228 : static constexpr size_t suffix_len{6};
229 :
230 0 : if (addr.size() <= suffix_len || addr.substr(addr.size() - suffix_len) != suffix) {
231 0 : return false;
232 : }
233 :
234 0 : auto input = DecodeBase32(std::string_view{addr}.substr(0, addr.size() - suffix_len));
235 :
236 0 : if (!input) {
237 0 : return false;
238 : }
239 :
240 0 : if (input->size() == torv3::TOTAL_LEN) {
241 0 : Span<const uint8_t> input_pubkey{input->data(), ADDR_TORV3_SIZE};
242 0 : Span<const uint8_t> input_checksum{input->data() + ADDR_TORV3_SIZE, torv3::CHECKSUM_LEN};
243 0 : Span<const uint8_t> input_version{input->data() + ADDR_TORV3_SIZE + torv3::CHECKSUM_LEN, sizeof(torv3::VERSION)};
244 :
245 0 : if (input_version != torv3::VERSION) {
246 0 : return false;
247 : }
248 :
249 : uint8_t calculated_checksum[torv3::CHECKSUM_LEN];
250 0 : torv3::Checksum(input_pubkey, calculated_checksum);
251 :
252 0 : if (input_checksum != calculated_checksum) {
253 0 : return false;
254 : }
255 :
256 0 : m_net = NET_ONION;
257 0 : m_addr.assign(input_pubkey.begin(), input_pubkey.end());
258 0 : return true;
259 : }
260 :
261 0 : return false;
262 0 : }
263 :
264 0 : bool CNetAddr::SetI2P(const std::string& addr)
265 : {
266 : // I2P addresses that we support consist of 52 base32 characters + ".b32.i2p".
267 : static constexpr size_t b32_len{52};
268 : static const char* suffix{".b32.i2p"};
269 : static constexpr size_t suffix_len{8};
270 :
271 0 : if (addr.size() != b32_len + suffix_len || ToLower(addr.substr(b32_len)) != suffix) {
272 0 : return false;
273 : }
274 :
275 : // Remove the ".b32.i2p" suffix and pad to a multiple of 8 chars, so DecodeBase32()
276 : // can decode it.
277 0 : const std::string b32_padded = addr.substr(0, b32_len) + "====";
278 :
279 0 : auto address_bytes = DecodeBase32(b32_padded);
280 :
281 0 : if (!address_bytes || address_bytes->size() != ADDR_I2P_SIZE) {
282 0 : return false;
283 : }
284 :
285 0 : m_net = NET_I2P;
286 0 : m_addr.assign(address_bytes->begin(), address_bytes->end());
287 :
288 0 : return true;
289 0 : }
290 :
291 0 : CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
292 : {
293 0 : m_net = NET_IPV4;
294 0 : const uint8_t* ptr = reinterpret_cast<const uint8_t*>(&ipv4Addr);
295 0 : m_addr.assign(ptr, ptr + ADDR_IPV4_SIZE);
296 0 : }
297 :
298 0 : CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr, const uint32_t scope)
299 : {
300 0 : SetLegacyIPv6({reinterpret_cast<const uint8_t*>(&ipv6Addr), sizeof(ipv6Addr)});
301 0 : m_scope_id = scope;
302 0 : }
303 :
304 0 : bool CNetAddr::IsBindAny() const
305 : {
306 0 : if (!IsIPv4() && !IsIPv6()) {
307 0 : return false;
308 : }
309 0 : return std::all_of(m_addr.begin(), m_addr.end(), [](uint8_t b) { return b == 0; });
310 0 : }
311 :
312 0 : bool CNetAddr::IsRFC1918() const
313 : {
314 0 : return IsIPv4() && (
315 0 : m_addr[0] == 10 ||
316 0 : (m_addr[0] == 192 && m_addr[1] == 168) ||
317 0 : (m_addr[0] == 172 && m_addr[1] >= 16 && m_addr[1] <= 31));
318 : }
319 :
320 0 : bool CNetAddr::IsRFC2544() const
321 : {
322 0 : return IsIPv4() && m_addr[0] == 198 && (m_addr[1] == 18 || m_addr[1] == 19);
323 : }
324 :
325 0 : bool CNetAddr::IsRFC3927() const
326 : {
327 0 : return IsIPv4() && HasPrefix(m_addr, std::array<uint8_t, 2>{169, 254});
328 : }
329 :
330 0 : bool CNetAddr::IsRFC6598() const
331 : {
332 0 : return IsIPv4() && m_addr[0] == 100 && m_addr[1] >= 64 && m_addr[1] <= 127;
333 : }
334 :
335 0 : bool CNetAddr::IsRFC5737() const
336 : {
337 0 : return IsIPv4() && (HasPrefix(m_addr, std::array<uint8_t, 3>{192, 0, 2}) ||
338 0 : HasPrefix(m_addr, std::array<uint8_t, 3>{198, 51, 100}) ||
339 0 : HasPrefix(m_addr, std::array<uint8_t, 3>{203, 0, 113}));
340 : }
341 :
342 0 : bool CNetAddr::IsRFC3849() const
343 : {
344 0 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x0D, 0xB8});
345 : }
346 :
347 0 : bool CNetAddr::IsRFC3964() const
348 : {
349 0 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 2>{0x20, 0x02});
350 : }
351 :
352 0 : bool CNetAddr::IsRFC6052() const
353 : {
354 0 : return IsIPv6() &&
355 0 : HasPrefix(m_addr, std::array<uint8_t, 12>{0x00, 0x64, 0xFF, 0x9B, 0x00, 0x00,
356 : 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
357 : }
358 :
359 0 : bool CNetAddr::IsRFC4380() const
360 : {
361 0 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x00, 0x00});
362 : }
363 :
364 0 : bool CNetAddr::IsRFC4862() const
365 : {
366 0 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 8>{0xFE, 0x80, 0x00, 0x00,
367 : 0x00, 0x00, 0x00, 0x00});
368 : }
369 :
370 0 : bool CNetAddr::IsRFC4193() const
371 : {
372 0 : return IsIPv6() && (m_addr[0] & 0xFE) == 0xFC;
373 : }
374 :
375 0 : bool CNetAddr::IsRFC6145() const
376 : {
377 0 : return IsIPv6() &&
378 0 : HasPrefix(m_addr, std::array<uint8_t, 12>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
379 : 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00});
380 : }
381 :
382 0 : bool CNetAddr::IsRFC4843() const
383 : {
384 0 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 3>{0x20, 0x01, 0x00}) &&
385 0 : (m_addr[3] & 0xF0) == 0x10;
386 : }
387 :
388 0 : bool CNetAddr::IsRFC7343() const
389 : {
390 0 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 3>{0x20, 0x01, 0x00}) &&
391 0 : (m_addr[3] & 0xF0) == 0x20;
392 : }
393 :
394 0 : bool CNetAddr::IsHeNet() const
395 : {
396 0 : return IsIPv6() && HasPrefix(m_addr, std::array<uint8_t, 4>{0x20, 0x01, 0x04, 0x70});
397 : }
398 :
399 0 : bool CNetAddr::IsLocal() const
400 : {
401 : // IPv4 loopback (127.0.0.0/8 or 0.0.0.0/8)
402 0 : if (IsIPv4() && (m_addr[0] == 127 || m_addr[0] == 0)) {
403 0 : return true;
404 : }
405 :
406 : // IPv6 loopback (::1/128)
407 : static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
408 0 : if (IsIPv6() && memcmp(m_addr.data(), pchLocal, sizeof(pchLocal)) == 0) {
409 0 : return true;
410 : }
411 :
412 0 : return false;
413 0 : }
414 :
415 : /**
416 : * @returns Whether or not this network address is a valid address that @a could
417 : * be used to refer to an actual host.
418 : *
419 : * @note A valid address may or may not be publicly routable on the global
420 : * internet. As in, the set of valid addresses is a superset of the set of
421 : * publicly routable addresses.
422 : *
423 : * @see CNetAddr::IsRoutable()
424 : */
425 0 : bool CNetAddr::IsValid() const
426 : {
427 : // unspecified IPv6 address (::/128)
428 0 : unsigned char ipNone6[16] = {};
429 0 : if (IsIPv6() && memcmp(m_addr.data(), ipNone6, sizeof(ipNone6)) == 0) {
430 0 : return false;
431 : }
432 :
433 0 : if (IsCJDNS() && !HasCJDNSPrefix()) {
434 0 : return false;
435 : }
436 :
437 : // documentation IPv6 address
438 0 : if (IsRFC3849())
439 0 : return false;
440 :
441 0 : if (IsInternal())
442 0 : return false;
443 :
444 0 : if (IsIPv4()) {
445 0 : const uint32_t addr = ReadBE32(m_addr.data());
446 0 : if (addr == INADDR_ANY || addr == INADDR_NONE) {
447 0 : return false;
448 : }
449 0 : }
450 :
451 0 : return true;
452 0 : }
453 :
454 : /**
455 : * @returns Whether or not this network address is publicly routable on the
456 : * global internet.
457 : *
458 : * @note A routable address is always valid. As in, the set of routable addresses
459 : * is a subset of the set of valid addresses.
460 : *
461 : * @see CNetAddr::IsValid()
462 : */
463 0 : bool CNetAddr::IsRoutable() const
464 : {
465 0 : return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || IsRFC4193() || IsRFC4843() || IsRFC7343() || IsLocal() || IsInternal());
466 : }
467 :
468 : /**
469 : * @returns Whether or not this is a dummy address that represents a name.
470 : *
471 : * @see CNetAddr::SetInternal(const std::string &)
472 : */
473 0 : bool CNetAddr::IsInternal() const
474 : {
475 0 : return m_net == NET_INTERNAL;
476 : }
477 :
478 0 : bool CNetAddr::IsAddrV1Compatible() const
479 : {
480 0 : switch (m_net) {
481 : case NET_IPV4:
482 : case NET_IPV6:
483 : case NET_INTERNAL:
484 0 : return true;
485 : case NET_ONION:
486 : case NET_I2P:
487 : case NET_CJDNS:
488 0 : return false;
489 : case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE
490 : case NET_MAX: // m_net is never and should not be set to NET_MAX
491 0 : assert(false);
492 : } // no default case, so the compiler can warn about missing cases
493 :
494 0 : assert(false);
495 0 : }
496 :
497 0 : enum Network CNetAddr::GetNetwork() const
498 : {
499 0 : if (IsInternal())
500 0 : return NET_INTERNAL;
501 :
502 0 : if (!IsRoutable())
503 0 : return NET_UNROUTABLE;
504 :
505 0 : return m_net;
506 0 : }
507 :
508 0 : static std::string IPv4ToString(Span<const uint8_t> a)
509 : {
510 0 : return strprintf("%u.%u.%u.%u", a[0], a[1], a[2], a[3]);
511 : }
512 :
513 : // Return an IPv6 address text representation with zero compression as described in RFC 5952
514 : // ("A Recommendation for IPv6 Address Text Representation").
515 0 : static std::string IPv6ToString(Span<const uint8_t> a, uint32_t scope_id)
516 : {
517 0 : assert(a.size() == ADDR_IPV6_SIZE);
518 0 : const std::array groups{
519 0 : ReadBE16(&a[0]),
520 0 : ReadBE16(&a[2]),
521 0 : ReadBE16(&a[4]),
522 0 : ReadBE16(&a[6]),
523 0 : ReadBE16(&a[8]),
524 0 : ReadBE16(&a[10]),
525 0 : ReadBE16(&a[12]),
526 0 : ReadBE16(&a[14]),
527 : };
528 :
529 : // The zero compression implementation is inspired by Rust's std::net::Ipv6Addr, see
530 : // https://github.com/rust-lang/rust/blob/cc4103089f40a163f6d143f06359cba7043da29b/library/std/src/net/ip.rs#L1635-L1683
531 0 : struct ZeroSpan {
532 0 : size_t start_index{0};
533 0 : size_t len{0};
534 : };
535 :
536 : // Find longest sequence of consecutive all-zero fields. Use first zero sequence if two or more
537 : // zero sequences of equal length are found.
538 0 : ZeroSpan longest, current;
539 0 : for (size_t i{0}; i < groups.size(); ++i) {
540 0 : if (groups[i] != 0) {
541 0 : current = {i + 1, 0};
542 0 : continue;
543 : }
544 0 : current.len += 1;
545 0 : if (current.len > longest.len) {
546 0 : longest = current;
547 0 : }
548 0 : }
549 :
550 0 : std::string r;
551 0 : r.reserve(39);
552 0 : for (size_t i{0}; i < groups.size(); ++i) {
553 : // Replace the longest sequence of consecutive all-zero fields with two colons ("::").
554 0 : if (longest.len >= 2 && i >= longest.start_index && i < longest.start_index + longest.len) {
555 0 : if (i == longest.start_index) {
556 0 : r += "::";
557 0 : }
558 0 : continue;
559 : }
560 0 : r += strprintf("%s%x", ((!r.empty() && r.back() != ':') ? ":" : ""), groups[i]);
561 0 : }
562 :
563 0 : if (scope_id != 0) {
564 0 : r += strprintf("%%%u", scope_id);
565 0 : }
566 :
567 0 : return r;
568 0 : }
569 :
570 0 : std::string OnionToString(Span<const uint8_t> addr)
571 : {
572 : uint8_t checksum[torv3::CHECKSUM_LEN];
573 0 : torv3::Checksum(addr, checksum);
574 : // TORv3 onion_address = base32(PUBKEY | CHECKSUM | VERSION) + ".onion"
575 0 : prevector<torv3::TOTAL_LEN, uint8_t> address{addr.begin(), addr.end()};
576 0 : address.insert(address.end(), checksum, checksum + torv3::CHECKSUM_LEN);
577 0 : address.insert(address.end(), torv3::VERSION, torv3::VERSION + sizeof(torv3::VERSION));
578 0 : return EncodeBase32(address) + ".onion";
579 0 : }
580 :
581 0 : std::string CNetAddr::ToStringAddr() const
582 : {
583 0 : switch (m_net) {
584 : case NET_IPV4:
585 0 : return IPv4ToString(m_addr);
586 : case NET_IPV6:
587 0 : return IPv6ToString(m_addr, m_scope_id);
588 : case NET_ONION:
589 0 : return OnionToString(m_addr);
590 : case NET_I2P:
591 0 : return EncodeBase32(m_addr, false /* don't pad with = */) + ".b32.i2p";
592 : case NET_CJDNS:
593 0 : return IPv6ToString(m_addr, 0);
594 : case NET_INTERNAL:
595 0 : return EncodeBase32(m_addr) + ".internal";
596 : case NET_UNROUTABLE: // m_net is never and should not be set to NET_UNROUTABLE
597 : case NET_MAX: // m_net is never and should not be set to NET_MAX
598 0 : assert(false);
599 : } // no default case, so the compiler can warn about missing cases
600 :
601 0 : assert(false);
602 0 : }
603 :
604 0 : bool operator==(const CNetAddr& a, const CNetAddr& b)
605 : {
606 0 : return a.m_net == b.m_net && a.m_addr == b.m_addr;
607 : }
608 :
609 0 : bool operator<(const CNetAddr& a, const CNetAddr& b)
610 : {
611 0 : return std::tie(a.m_net, a.m_addr) < std::tie(b.m_net, b.m_addr);
612 : }
613 :
614 : /**
615 : * Try to get our IPv4 address.
616 : *
617 : * @param[out] pipv4Addr The in_addr struct to which to copy.
618 : *
619 : * @returns Whether or not the operation was successful, in particular, whether
620 : * or not our address was an IPv4 address.
621 : *
622 : * @see CNetAddr::IsIPv4()
623 : */
624 0 : bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
625 : {
626 0 : if (!IsIPv4())
627 0 : return false;
628 0 : assert(sizeof(*pipv4Addr) == m_addr.size());
629 0 : memcpy(pipv4Addr, m_addr.data(), m_addr.size());
630 0 : return true;
631 0 : }
632 :
633 : /**
634 : * Try to get our IPv6 (or CJDNS) address.
635 : *
636 : * @param[out] pipv6Addr The in6_addr struct to which to copy.
637 : *
638 : * @returns Whether or not the operation was successful, in particular, whether
639 : * or not our address was an IPv6 address.
640 : *
641 : * @see CNetAddr::IsIPv6()
642 : */
643 0 : bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
644 : {
645 0 : if (!IsIPv6() && !IsCJDNS()) {
646 0 : return false;
647 : }
648 0 : assert(sizeof(*pipv6Addr) == m_addr.size());
649 0 : memcpy(pipv6Addr, m_addr.data(), m_addr.size());
650 0 : return true;
651 0 : }
652 :
653 0 : bool CNetAddr::HasLinkedIPv4() const
654 : {
655 0 : return IsRoutable() && (IsIPv4() || IsRFC6145() || IsRFC6052() || IsRFC3964() || IsRFC4380());
656 : }
657 :
658 0 : uint32_t CNetAddr::GetLinkedIPv4() const
659 : {
660 0 : if (IsIPv4()) {
661 0 : return ReadBE32(m_addr.data());
662 0 : } else if (IsRFC6052() || IsRFC6145()) {
663 : // mapped IPv4, SIIT translated IPv4: the IPv4 address is the last 4 bytes of the address
664 0 : return ReadBE32(Span{m_addr}.last(ADDR_IPV4_SIZE).data());
665 0 : } else if (IsRFC3964()) {
666 : // 6to4 tunneled IPv4: the IPv4 address is in bytes 2-6
667 0 : return ReadBE32(Span{m_addr}.subspan(2, ADDR_IPV4_SIZE).data());
668 0 : } else if (IsRFC4380()) {
669 : // Teredo tunneled IPv4: the IPv4 address is in the last 4 bytes of the address, but bitflipped
670 0 : return ~ReadBE32(Span{m_addr}.last(ADDR_IPV4_SIZE).data());
671 : }
672 0 : assert(false);
673 0 : }
674 :
675 0 : Network CNetAddr::GetNetClass() const
676 : {
677 : // Make sure that if we return NET_IPV6, then IsIPv6() is true. The callers expect that.
678 :
679 : // Check for "internal" first because such addresses are also !IsRoutable()
680 : // and we don't want to return NET_UNROUTABLE in that case.
681 0 : if (IsInternal()) {
682 0 : return NET_INTERNAL;
683 : }
684 0 : if (!IsRoutable()) {
685 0 : return NET_UNROUTABLE;
686 : }
687 0 : if (HasLinkedIPv4()) {
688 0 : return NET_IPV4;
689 : }
690 0 : return m_net;
691 0 : }
692 :
693 0 : std::vector<unsigned char> CNetAddr::GetAddrBytes() const
694 : {
695 0 : if (IsAddrV1Compatible()) {
696 : uint8_t serialized[V1_SERIALIZATION_SIZE];
697 0 : SerializeV1Array(serialized);
698 0 : return {std::begin(serialized), std::end(serialized)};
699 : }
700 0 : return std::vector<unsigned char>(m_addr.begin(), m_addr.end());
701 0 : }
702 :
703 : // private extensions to enum Network, only returned by GetExtNetwork,
704 : // and only used in GetReachabilityFrom
705 : static const int NET_TEREDO = NET_MAX;
706 0 : int static GetExtNetwork(const CNetAddr& addr)
707 : {
708 0 : if (addr.IsRFC4380())
709 0 : return NET_TEREDO;
710 0 : return addr.GetNetwork();
711 0 : }
712 :
713 : /** Calculates a metric for how reachable (*this) is from a given partner */
714 0 : int CNetAddr::GetReachabilityFrom(const CNetAddr& paddrPartner) const
715 : {
716 : enum Reachability {
717 : REACH_UNREACHABLE,
718 : REACH_DEFAULT,
719 : REACH_TEREDO,
720 : REACH_IPV6_WEAK,
721 : REACH_IPV4,
722 : REACH_IPV6_STRONG,
723 : REACH_PRIVATE
724 : };
725 :
726 0 : if (!IsRoutable() || IsInternal())
727 0 : return REACH_UNREACHABLE;
728 :
729 0 : int ourNet = GetExtNetwork(*this);
730 0 : int theirNet = GetExtNetwork(paddrPartner);
731 0 : bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
732 :
733 0 : switch(theirNet) {
734 : case NET_IPV4:
735 0 : switch(ourNet) {
736 0 : default: return REACH_DEFAULT;
737 0 : case NET_IPV4: return REACH_IPV4;
738 : }
739 : case NET_IPV6:
740 0 : switch(ourNet) {
741 0 : default: return REACH_DEFAULT;
742 0 : case NET_TEREDO: return REACH_TEREDO;
743 0 : case NET_IPV4: return REACH_IPV4;
744 0 : case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
745 : }
746 : case NET_ONION:
747 0 : switch(ourNet) {
748 0 : default: return REACH_DEFAULT;
749 0 : case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well
750 0 : case NET_ONION: return REACH_PRIVATE;
751 : }
752 : case NET_I2P:
753 0 : switch (ourNet) {
754 0 : case NET_I2P: return REACH_PRIVATE;
755 0 : default: return REACH_DEFAULT;
756 : }
757 : case NET_CJDNS:
758 0 : switch (ourNet) {
759 0 : case NET_CJDNS: return REACH_PRIVATE;
760 0 : default: return REACH_DEFAULT;
761 : }
762 : case NET_TEREDO:
763 0 : switch(ourNet) {
764 0 : default: return REACH_DEFAULT;
765 0 : case NET_TEREDO: return REACH_TEREDO;
766 0 : case NET_IPV6: return REACH_IPV6_WEAK;
767 0 : case NET_IPV4: return REACH_IPV4;
768 : }
769 0 : case NET_UNROUTABLE:
770 : default:
771 0 : switch(ourNet) {
772 0 : default: return REACH_DEFAULT;
773 0 : case NET_TEREDO: return REACH_TEREDO;
774 0 : case NET_IPV6: return REACH_IPV6_WEAK;
775 0 : case NET_IPV4: return REACH_IPV4;
776 0 : case NET_ONION: return REACH_PRIVATE; // either from Tor, or don't care about our address
777 : }
778 : }
779 0 : }
780 :
781 16 : CService::CService() : port(0)
782 : {
783 16 : }
784 :
785 0 : CService::CService(const CNetAddr& cip, uint16_t portIn) : CNetAddr(cip), port(portIn)
786 : {
787 0 : }
788 :
789 0 : CService::CService(const struct in_addr& ipv4Addr, uint16_t portIn) : CNetAddr(ipv4Addr), port(portIn)
790 : {
791 0 : }
792 :
793 0 : CService::CService(const struct in6_addr& ipv6Addr, uint16_t portIn) : CNetAddr(ipv6Addr), port(portIn)
794 : {
795 0 : }
796 :
797 0 : CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
798 : {
799 0 : assert(addr.sin_family == AF_INET);
800 0 : }
801 :
802 0 : CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr, addr.sin6_scope_id), port(ntohs(addr.sin6_port))
803 : {
804 0 : assert(addr.sin6_family == AF_INET6);
805 0 : }
806 :
807 0 : bool CService::SetSockAddr(const struct sockaddr *paddr)
808 : {
809 0 : switch (paddr->sa_family) {
810 : case AF_INET:
811 0 : *this = CService(*(const struct sockaddr_in*)paddr);
812 0 : return true;
813 : case AF_INET6:
814 0 : *this = CService(*(const struct sockaddr_in6*)paddr);
815 0 : return true;
816 : default:
817 0 : return false;
818 : }
819 0 : }
820 :
821 0 : uint16_t CService::GetPort() const
822 : {
823 0 : return port;
824 : }
825 :
826 0 : bool operator==(const CService& a, const CService& b)
827 : {
828 0 : return static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port == b.port;
829 0 : }
830 :
831 0 : bool operator<(const CService& a, const CService& b)
832 : {
833 0 : return static_cast<CNetAddr>(a) < static_cast<CNetAddr>(b) || (static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port < b.port);
834 0 : }
835 :
836 : /**
837 : * Obtain the IPv4/6 socket address this represents.
838 : *
839 : * @param[out] paddr The obtained socket address.
840 : * @param[in,out] addrlen The size, in bytes, of the address structure pointed
841 : * to by paddr. The value that's pointed to by this
842 : * parameter might change after calling this function if
843 : * the size of the corresponding address structure
844 : * changed.
845 : *
846 : * @returns Whether or not the operation was successful.
847 : */
848 0 : bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
849 : {
850 0 : if (IsIPv4()) {
851 0 : if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
852 0 : return false;
853 0 : *addrlen = sizeof(struct sockaddr_in);
854 0 : struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
855 0 : memset(paddrin, 0, *addrlen);
856 0 : if (!GetInAddr(&paddrin->sin_addr))
857 0 : return false;
858 0 : paddrin->sin_family = AF_INET;
859 0 : paddrin->sin_port = htons(port);
860 0 : return true;
861 : }
862 0 : if (IsIPv6() || IsCJDNS()) {
863 0 : if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
864 0 : return false;
865 0 : *addrlen = sizeof(struct sockaddr_in6);
866 0 : struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
867 0 : memset(paddrin6, 0, *addrlen);
868 0 : if (!GetIn6Addr(&paddrin6->sin6_addr))
869 0 : return false;
870 0 : paddrin6->sin6_scope_id = m_scope_id;
871 0 : paddrin6->sin6_family = AF_INET6;
872 0 : paddrin6->sin6_port = htons(port);
873 0 : return true;
874 : }
875 0 : return false;
876 0 : }
877 :
878 : /**
879 : * @returns An identifier unique to this service's address and port number.
880 : */
881 0 : std::vector<unsigned char> CService::GetKey() const
882 : {
883 0 : auto key = GetAddrBytes();
884 0 : key.push_back(port / 0x100); // most significant byte of our port
885 0 : key.push_back(port & 0x0FF); // least significant byte of our port
886 0 : return key;
887 0 : }
888 :
889 0 : std::string CService::ToStringAddrPort() const
890 : {
891 0 : const auto port_str = strprintf("%u", port);
892 :
893 0 : if (IsIPv4() || IsTor() || IsI2P() || IsInternal()) {
894 0 : return ToStringAddr() + ":" + port_str;
895 : } else {
896 0 : return "[" + ToStringAddr() + "]:" + port_str;
897 : }
898 0 : }
899 :
900 0 : CSubNet::CSubNet():
901 0 : valid(false)
902 : {
903 0 : memset(netmask, 0, sizeof(netmask));
904 0 : }
905 :
906 0 : CSubNet::CSubNet(const CNetAddr& addr, uint8_t mask) : CSubNet()
907 : {
908 0 : valid = (addr.IsIPv4() && mask <= ADDR_IPV4_SIZE * 8) ||
909 0 : (addr.IsIPv6() && mask <= ADDR_IPV6_SIZE * 8);
910 0 : if (!valid) {
911 0 : return;
912 : }
913 :
914 0 : assert(mask <= sizeof(netmask) * 8);
915 :
916 0 : network = addr;
917 :
918 0 : uint8_t n = mask;
919 0 : for (size_t i = 0; i < network.m_addr.size(); ++i) {
920 0 : const uint8_t bits = n < 8 ? n : 8;
921 0 : netmask[i] = (uint8_t)((uint8_t)0xFF << (8 - bits)); // Set first bits.
922 0 : network.m_addr[i] &= netmask[i]; // Normalize network according to netmask.
923 0 : n -= bits;
924 0 : }
925 0 : }
926 :
927 : /**
928 : * @returns The number of 1-bits in the prefix of the specified subnet mask. If
929 : * the specified subnet mask is not a valid one, -1.
930 : */
931 0 : static inline int NetmaskBits(uint8_t x)
932 : {
933 0 : switch(x) {
934 0 : case 0x00: return 0;
935 0 : case 0x80: return 1;
936 0 : case 0xc0: return 2;
937 0 : case 0xe0: return 3;
938 0 : case 0xf0: return 4;
939 0 : case 0xf8: return 5;
940 0 : case 0xfc: return 6;
941 0 : case 0xfe: return 7;
942 0 : case 0xff: return 8;
943 0 : default: return -1;
944 : }
945 0 : }
946 :
947 0 : CSubNet::CSubNet(const CNetAddr& addr, const CNetAddr& mask) : CSubNet()
948 : {
949 0 : valid = (addr.IsIPv4() || addr.IsIPv6()) && addr.m_net == mask.m_net;
950 0 : if (!valid) {
951 0 : return;
952 : }
953 : // Check if `mask` contains 1-bits after 0-bits (which is an invalid netmask).
954 0 : bool zeros_found = false;
955 0 : for (auto b : mask.m_addr) {
956 0 : const int num_bits = NetmaskBits(b);
957 0 : if (num_bits == -1 || (zeros_found && num_bits != 0)) {
958 0 : valid = false;
959 0 : return;
960 : }
961 0 : if (num_bits < 8) {
962 0 : zeros_found = true;
963 0 : }
964 : }
965 :
966 0 : assert(mask.m_addr.size() <= sizeof(netmask));
967 :
968 0 : memcpy(netmask, mask.m_addr.data(), mask.m_addr.size());
969 :
970 0 : network = addr;
971 :
972 : // Normalize network according to netmask
973 0 : for (size_t x = 0; x < network.m_addr.size(); ++x) {
974 0 : network.m_addr[x] &= netmask[x];
975 0 : }
976 0 : }
977 :
978 0 : CSubNet::CSubNet(const CNetAddr& addr) : CSubNet()
979 : {
980 0 : switch (addr.m_net) {
981 : case NET_IPV4:
982 : case NET_IPV6:
983 0 : valid = true;
984 0 : assert(addr.m_addr.size() <= sizeof(netmask));
985 0 : memset(netmask, 0xFF, addr.m_addr.size());
986 0 : break;
987 : case NET_ONION:
988 : case NET_I2P:
989 : case NET_CJDNS:
990 0 : valid = true;
991 0 : break;
992 : case NET_INTERNAL:
993 : case NET_UNROUTABLE:
994 : case NET_MAX:
995 0 : return;
996 : }
997 :
998 0 : network = addr;
999 0 : }
1000 :
1001 : /**
1002 : * @returns True if this subnet is valid, the specified address is valid, and
1003 : * the specified address belongs in this subnet.
1004 : */
1005 0 : bool CSubNet::Match(const CNetAddr &addr) const
1006 : {
1007 0 : if (!valid || !addr.IsValid() || network.m_net != addr.m_net)
1008 0 : return false;
1009 :
1010 0 : switch (network.m_net) {
1011 : case NET_IPV4:
1012 : case NET_IPV6:
1013 0 : break;
1014 : case NET_ONION:
1015 : case NET_I2P:
1016 : case NET_CJDNS:
1017 : case NET_INTERNAL:
1018 0 : return addr == network;
1019 : case NET_UNROUTABLE:
1020 : case NET_MAX:
1021 0 : return false;
1022 : }
1023 :
1024 0 : assert(network.m_addr.size() == addr.m_addr.size());
1025 0 : for (size_t x = 0; x < addr.m_addr.size(); ++x) {
1026 0 : if ((addr.m_addr[x] & netmask[x]) != network.m_addr[x]) {
1027 0 : return false;
1028 : }
1029 0 : }
1030 0 : return true;
1031 0 : }
1032 :
1033 0 : std::string CSubNet::ToString() const
1034 : {
1035 0 : std::string suffix;
1036 :
1037 0 : switch (network.m_net) {
1038 : case NET_IPV4:
1039 : case NET_IPV6: {
1040 0 : assert(network.m_addr.size() <= sizeof(netmask));
1041 :
1042 0 : uint8_t cidr = 0;
1043 :
1044 0 : for (size_t i = 0; i < network.m_addr.size(); ++i) {
1045 0 : if (netmask[i] == 0x00) {
1046 0 : break;
1047 : }
1048 0 : cidr += NetmaskBits(netmask[i]);
1049 0 : }
1050 :
1051 0 : suffix = strprintf("/%u", cidr);
1052 0 : break;
1053 : }
1054 : case NET_ONION:
1055 : case NET_I2P:
1056 : case NET_CJDNS:
1057 : case NET_INTERNAL:
1058 : case NET_UNROUTABLE:
1059 : case NET_MAX:
1060 0 : break;
1061 : }
1062 :
1063 0 : return network.ToStringAddr() + suffix;
1064 0 : }
1065 :
1066 0 : bool CSubNet::IsValid() const
1067 : {
1068 0 : return valid;
1069 : }
1070 :
1071 0 : bool operator==(const CSubNet& a, const CSubNet& b)
1072 : {
1073 0 : return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
1074 : }
1075 :
1076 0 : bool operator<(const CSubNet& a, const CSubNet& b)
1077 : {
1078 0 : return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0));
1079 : }
|