1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
7 #include "config/bitcoin-config.h"
10 #include "netaddress.h"
12 #include "utilstrencodings.h"
13 #include "tinyformat.h"
15 static const unsigned char pchIPv4
[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
16 static const unsigned char pchOnionCat
[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
18 // 0xFD + sha256("bitcoin")[0:5]
19 static const unsigned char g_internal_prefix
[] = { 0xFD, 0x6B, 0x88, 0xC0, 0x87, 0x24 };
23 memset(ip
, 0, sizeof(ip
));
27 void CNetAddr::SetIP(const CNetAddr
& ipIn
)
29 memcpy(ip
, ipIn
.ip
, sizeof(ip
));
32 void CNetAddr::SetRaw(Network network
, const uint8_t *ip_in
)
37 memcpy(ip
, pchIPv4
, 12);
38 memcpy(ip
+12, ip_in
, 4);
41 memcpy(ip
, ip_in
, 16);
44 assert(!"invalid network");
48 bool CNetAddr::SetInternal(const std::string
&name
)
53 unsigned char hash
[32] = {};
54 CSHA256().Write((const unsigned char*)name
.data(), name
.size()).Finalize(hash
);
55 memcpy(ip
, g_internal_prefix
, sizeof(g_internal_prefix
));
56 memcpy(ip
+ sizeof(g_internal_prefix
), hash
, sizeof(ip
) - sizeof(g_internal_prefix
));
60 bool CNetAddr::SetSpecial(const std::string
&strName
)
62 if (strName
.size()>6 && strName
.substr(strName
.size() - 6, 6) == ".onion") {
63 std::vector
<unsigned char> vchAddr
= DecodeBase32(strName
.substr(0, strName
.size() - 6).c_str());
64 if (vchAddr
.size() != 16-sizeof(pchOnionCat
))
66 memcpy(ip
, pchOnionCat
, sizeof(pchOnionCat
));
67 for (unsigned int i
=0; i
<16-sizeof(pchOnionCat
); i
++)
68 ip
[i
+ sizeof(pchOnionCat
)] = vchAddr
[i
];
79 CNetAddr::CNetAddr(const struct in_addr
& ipv4Addr
)
81 SetRaw(NET_IPV4
, (const uint8_t*)&ipv4Addr
);
84 CNetAddr::CNetAddr(const struct in6_addr
& ipv6Addr
, const uint32_t scope
)
86 SetRaw(NET_IPV6
, (const uint8_t*)&ipv6Addr
);
90 unsigned int CNetAddr::GetByte(int n
) const
95 bool CNetAddr::IsIPv4() const
97 return (memcmp(ip
, pchIPv4
, sizeof(pchIPv4
)) == 0);
100 bool CNetAddr::IsIPv6() const
102 return (!IsIPv4() && !IsTor() && !IsInternal());
105 bool CNetAddr::IsRFC1918() const
109 (GetByte(3) == 192 && GetByte(2) == 168) ||
110 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
113 bool CNetAddr::IsRFC2544() const
115 return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);
118 bool CNetAddr::IsRFC3927() const
120 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
123 bool CNetAddr::IsRFC6598() const
125 return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;
128 bool CNetAddr::IsRFC5737() const
130 return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) ||
131 (GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) ||
132 (GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113));
135 bool CNetAddr::IsRFC3849() const
137 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
140 bool CNetAddr::IsRFC3964() const
142 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
145 bool CNetAddr::IsRFC6052() const
147 static const unsigned char pchRFC6052
[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
148 return (memcmp(ip
, pchRFC6052
, sizeof(pchRFC6052
)) == 0);
151 bool CNetAddr::IsRFC4380() const
153 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
156 bool CNetAddr::IsRFC4862() const
158 static const unsigned char pchRFC4862
[] = {0xFE,0x80,0,0,0,0,0,0};
159 return (memcmp(ip
, pchRFC4862
, sizeof(pchRFC4862
)) == 0);
162 bool CNetAddr::IsRFC4193() const
164 return ((GetByte(15) & 0xFE) == 0xFC);
167 bool CNetAddr::IsRFC6145() const
169 static const unsigned char pchRFC6145
[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
170 return (memcmp(ip
, pchRFC6145
, sizeof(pchRFC6145
)) == 0);
173 bool CNetAddr::IsRFC4843() const
175 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
178 bool CNetAddr::IsTor() const
180 return (memcmp(ip
, pchOnionCat
, sizeof(pchOnionCat
)) == 0);
183 bool CNetAddr::IsLocal() const
186 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
189 // IPv6 loopback (::1/128)
190 static const unsigned char pchLocal
[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
191 if (memcmp(ip
, pchLocal
, 16) == 0)
197 bool CNetAddr::IsValid() const
199 // Cleanup 3-byte shifted addresses caused by garbage in size field
200 // of addr messages from versions before 0.2.9 checksum.
201 // Two consecutive addr messages look like this:
202 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
203 // so if the first length field is garbled, it reads the second batch
204 // of addr misaligned by 3 bytes.
205 if (memcmp(ip
, pchIPv4
+3, sizeof(pchIPv4
)-3) == 0)
208 // unspecified IPv6 address (::/128)
209 unsigned char ipNone6
[16] = {};
210 if (memcmp(ip
, ipNone6
, 16) == 0)
213 // documentation IPv6 address
223 uint32_t ipNone
= INADDR_NONE
;
224 if (memcmp(ip
+12, &ipNone
, 4) == 0)
229 if (memcmp(ip
+12, &ipNone
, 4) == 0)
236 bool CNetAddr::IsRoutable() const
238 return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal() || IsInternal());
241 bool CNetAddr::IsInternal() const
243 return memcmp(ip
, g_internal_prefix
, sizeof(g_internal_prefix
)) == 0;
246 enum Network
CNetAddr::GetNetwork() const
252 return NET_UNROUTABLE
;
263 std::string
CNetAddr::ToStringIP() const
266 return EncodeBase32(&ip
[6], 10) + ".onion";
268 return EncodeBase32(ip
+ sizeof(g_internal_prefix
), sizeof(ip
) - sizeof(g_internal_prefix
)) + ".internal";
269 CService
serv(*this, 0);
270 struct sockaddr_storage sockaddr
;
271 socklen_t socklen
= sizeof(sockaddr
);
272 if (serv
.GetSockAddr((struct sockaddr
*)&sockaddr
, &socklen
)) {
273 char name
[1025] = "";
274 if (!getnameinfo((const struct sockaddr
*)&sockaddr
, socklen
, name
, sizeof(name
), nullptr, 0, NI_NUMERICHOST
))
275 return std::string(name
);
278 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
280 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
281 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
282 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
283 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
284 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
287 std::string
CNetAddr::ToString() const
292 bool operator==(const CNetAddr
& a
, const CNetAddr
& b
)
294 return (memcmp(a
.ip
, b
.ip
, 16) == 0);
297 bool operator!=(const CNetAddr
& a
, const CNetAddr
& b
)
299 return (memcmp(a
.ip
, b
.ip
, 16) != 0);
302 bool operator<(const CNetAddr
& a
, const CNetAddr
& b
)
304 return (memcmp(a
.ip
, b
.ip
, 16) < 0);
307 bool CNetAddr::GetInAddr(struct in_addr
* pipv4Addr
) const
311 memcpy(pipv4Addr
, ip
+12, 4);
315 bool CNetAddr::GetIn6Addr(struct in6_addr
* pipv6Addr
) const
317 memcpy(pipv6Addr
, ip
, 16);
321 // get canonical identifier of an address' group
322 // no two connections will be attempted to addresses with the same group
323 std::vector
<unsigned char> CNetAddr::GetGroup() const
325 std::vector
<unsigned char> vchRet
;
326 int nClass
= NET_IPV6
;
330 // all local addresses belong to the same group
336 // all internal-usage addresses get their own group
339 nClass
= NET_INTERNAL
;
340 nStartByte
= sizeof(g_internal_prefix
);
341 nBits
= (sizeof(ip
) - sizeof(g_internal_prefix
)) * 8;
343 // all other unroutable addresses belong to the same group
344 else if (!IsRoutable())
346 nClass
= NET_UNROUTABLE
;
349 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
350 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
351 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
356 // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
357 else if (IsRFC3964())
362 // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
363 else if (IsRFC4380())
365 vchRet
.push_back(NET_IPV4
);
366 vchRet
.push_back(GetByte(3) ^ 0xFF);
367 vchRet
.push_back(GetByte(2) ^ 0xFF);
376 // for he.net, use /36 groups
377 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
379 // for the rest of the IPv6 network, use /32 groups
383 vchRet
.push_back(nClass
);
386 vchRet
.push_back(GetByte(15 - nStartByte
));
391 vchRet
.push_back(GetByte(15 - nStartByte
) | ((1 << (8 - nBits
)) - 1));
396 uint64_t CNetAddr::GetHash() const
398 uint256 hash
= Hash(&ip
[0], &ip
[16]);
400 memcpy(&nRet
, &hash
, sizeof(nRet
));
404 // private extensions to enum Network, only returned by GetExtNetwork,
405 // and only used in GetReachabilityFrom
406 static const int NET_UNKNOWN
= NET_MAX
+ 0;
407 static const int NET_TEREDO
= NET_MAX
+ 1;
408 int static GetExtNetwork(const CNetAddr
*addr
)
412 if (addr
->IsRFC4380())
414 return addr
->GetNetwork();
417 /** Calculates a metric for how reachable (*this) is from a given partner */
418 int CNetAddr::GetReachabilityFrom(const CNetAddr
*paddrPartner
) const
430 if (!IsRoutable() || IsInternal())
431 return REACH_UNREACHABLE
;
433 int ourNet
= GetExtNetwork(this);
434 int theirNet
= GetExtNetwork(paddrPartner
);
435 bool fTunnel
= IsRFC3964() || IsRFC6052() || IsRFC6145();
440 default: return REACH_DEFAULT
;
441 case NET_IPV4
: return REACH_IPV4
;
445 default: return REACH_DEFAULT
;
446 case NET_TEREDO
: return REACH_TEREDO
;
447 case NET_IPV4
: return REACH_IPV4
;
448 case NET_IPV6
: return fTunnel
? REACH_IPV6_WEAK
: REACH_IPV6_STRONG
; // only prefer giving our IPv6 address if it's not tunnelled
452 default: return REACH_DEFAULT
;
453 case NET_IPV4
: return REACH_IPV4
; // Tor users can connect to IPv4 as well
454 case NET_TOR
: return REACH_PRIVATE
;
458 default: return REACH_DEFAULT
;
459 case NET_TEREDO
: return REACH_TEREDO
;
460 case NET_IPV6
: return REACH_IPV6_WEAK
;
461 case NET_IPV4
: return REACH_IPV4
;
467 default: return REACH_DEFAULT
;
468 case NET_TEREDO
: return REACH_TEREDO
;
469 case NET_IPV6
: return REACH_IPV6_WEAK
;
470 case NET_IPV4
: return REACH_IPV4
;
471 case NET_TOR
: return REACH_PRIVATE
; // either from Tor, or don't care about our address
476 void CService::Init()
486 CService::CService(const CNetAddr
& cip
, unsigned short portIn
) : CNetAddr(cip
), port(portIn
)
490 CService::CService(const struct in_addr
& ipv4Addr
, unsigned short portIn
) : CNetAddr(ipv4Addr
), port(portIn
)
494 CService::CService(const struct in6_addr
& ipv6Addr
, unsigned short portIn
) : CNetAddr(ipv6Addr
), port(portIn
)
498 CService::CService(const struct sockaddr_in
& addr
) : CNetAddr(addr
.sin_addr
), port(ntohs(addr
.sin_port
))
500 assert(addr
.sin_family
== AF_INET
);
503 CService::CService(const struct sockaddr_in6
&addr
) : CNetAddr(addr
.sin6_addr
, addr
.sin6_scope_id
), port(ntohs(addr
.sin6_port
))
505 assert(addr
.sin6_family
== AF_INET6
);
508 bool CService::SetSockAddr(const struct sockaddr
*paddr
)
510 switch (paddr
->sa_family
) {
512 *this = CService(*(const struct sockaddr_in
*)paddr
);
515 *this = CService(*(const struct sockaddr_in6
*)paddr
);
522 unsigned short CService::GetPort() const
527 bool operator==(const CService
& a
, const CService
& b
)
529 return (CNetAddr
)a
== (CNetAddr
)b
&& a
.port
== b
.port
;
532 bool operator!=(const CService
& a
, const CService
& b
)
534 return (CNetAddr
)a
!= (CNetAddr
)b
|| a
.port
!= b
.port
;
537 bool operator<(const CService
& a
, const CService
& b
)
539 return (CNetAddr
)a
< (CNetAddr
)b
|| ((CNetAddr
)a
== (CNetAddr
)b
&& a
.port
< b
.port
);
542 bool CService::GetSockAddr(struct sockaddr
* paddr
, socklen_t
*addrlen
) const
545 if (*addrlen
< (socklen_t
)sizeof(struct sockaddr_in
))
547 *addrlen
= sizeof(struct sockaddr_in
);
548 struct sockaddr_in
*paddrin
= (struct sockaddr_in
*)paddr
;
549 memset(paddrin
, 0, *addrlen
);
550 if (!GetInAddr(&paddrin
->sin_addr
))
552 paddrin
->sin_family
= AF_INET
;
553 paddrin
->sin_port
= htons(port
);
557 if (*addrlen
< (socklen_t
)sizeof(struct sockaddr_in6
))
559 *addrlen
= sizeof(struct sockaddr_in6
);
560 struct sockaddr_in6
*paddrin6
= (struct sockaddr_in6
*)paddr
;
561 memset(paddrin6
, 0, *addrlen
);
562 if (!GetIn6Addr(&paddrin6
->sin6_addr
))
564 paddrin6
->sin6_scope_id
= scopeId
;
565 paddrin6
->sin6_family
= AF_INET6
;
566 paddrin6
->sin6_port
= htons(port
);
572 std::vector
<unsigned char> CService::GetKey() const
574 std::vector
<unsigned char> vKey
;
576 memcpy(vKey
.data(), ip
, 16);
577 vKey
[16] = port
/ 0x100;
578 vKey
[17] = port
& 0x0FF;
582 std::string
CService::ToStringPort() const
584 return strprintf("%u", port
);
587 std::string
CService::ToStringIPPort() const
589 if (IsIPv4() || IsTor() || IsInternal()) {
590 return ToStringIP() + ":" + ToStringPort();
592 return "[" + ToStringIP() + "]:" + ToStringPort();
596 std::string
CService::ToString() const
598 return ToStringIPPort();
604 memset(netmask
, 0, sizeof(netmask
));
607 CSubNet::CSubNet(const CNetAddr
&addr
, int32_t mask
)
611 // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
612 memset(netmask
, 255, sizeof(netmask
));
614 // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
615 const int astartofs
= network
.IsIPv4() ? 12 : 0;
618 if(n
>= 0 && n
<= (128 - astartofs
*8)) // Only valid if in range of bits of address
621 // Clear bits [n..127]
623 netmask
[n
>>3] &= ~(1<<(7-(n
&7)));
627 // Normalize network according to netmask
628 for(int x
=0; x
<16; ++x
)
629 network
.ip
[x
] &= netmask
[x
];
632 CSubNet::CSubNet(const CNetAddr
&addr
, const CNetAddr
&mask
)
636 // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
637 memset(netmask
, 255, sizeof(netmask
));
639 // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
640 const int astartofs
= network
.IsIPv4() ? 12 : 0;
642 for(int x
=astartofs
; x
<16; ++x
)
643 netmask
[x
] = mask
.ip
[x
];
645 // Normalize network according to netmask
646 for(int x
=0; x
<16; ++x
)
647 network
.ip
[x
] &= netmask
[x
];
650 CSubNet::CSubNet(const CNetAddr
&addr
):
651 valid(addr
.IsValid())
653 memset(netmask
, 255, sizeof(netmask
));
657 bool CSubNet::Match(const CNetAddr
&addr
) const
659 if (!valid
|| !addr
.IsValid())
661 for(int x
=0; x
<16; ++x
)
662 if ((addr
.ip
[x
] & netmask
[x
]) != network
.ip
[x
])
667 static inline int NetmaskBits(uint8_t x
)
670 case 0x00: return 0; break;
671 case 0x80: return 1; break;
672 case 0xc0: return 2; break;
673 case 0xe0: return 3; break;
674 case 0xf0: return 4; break;
675 case 0xf8: return 5; break;
676 case 0xfc: return 6; break;
677 case 0xfe: return 7; break;
678 case 0xff: return 8; break;
679 default: return -1; break;
683 std::string
CSubNet::ToString() const
685 /* Parse binary 1{n}0{N-n} to see if mask can be represented as /n */
687 bool valid_cidr
= true;
688 int n
= network
.IsIPv4() ? 12 : 0;
689 for (; n
< 16 && netmask
[n
] == 0xff; ++n
)
692 int bits
= NetmaskBits(netmask
[n
]);
699 for (; n
< 16 && valid_cidr
; ++n
)
700 if (netmask
[n
] != 0x00)
704 std::string strNetmask
;
706 strNetmask
= strprintf("%u", cidr
);
708 if (network
.IsIPv4())
709 strNetmask
= strprintf("%u.%u.%u.%u", netmask
[12], netmask
[13], netmask
[14], netmask
[15]);
711 strNetmask
= strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
712 netmask
[0] << 8 | netmask
[1], netmask
[2] << 8 | netmask
[3],
713 netmask
[4] << 8 | netmask
[5], netmask
[6] << 8 | netmask
[7],
714 netmask
[8] << 8 | netmask
[9], netmask
[10] << 8 | netmask
[11],
715 netmask
[12] << 8 | netmask
[13], netmask
[14] << 8 | netmask
[15]);
718 return network
.ToString() + "/" + strNetmask
;
721 bool CSubNet::IsValid() const
726 bool operator==(const CSubNet
& a
, const CSubNet
& b
)
728 return a
.valid
== b
.valid
&& a
.network
== b
.network
&& !memcmp(a
.netmask
, b
.netmask
, 16);
731 bool operator!=(const CSubNet
& a
, const CSubNet
& b
)
736 bool operator<(const CSubNet
& a
, const CSubNet
& b
)
738 return (a
.network
< b
.network
|| (a
.network
== b
.network
&& memcmp(a
.netmask
, b
.netmask
, 16) < 0));