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.
6 #include <netaddress.h>
8 #include <utilstrencodings.h>
9 #include <tinyformat.h>
11 static const unsigned char pchIPv4
[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
12 static const unsigned char pchOnionCat
[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
14 // 0xFD + sha256("bitcoin")[0:5]
15 static const unsigned char g_internal_prefix
[] = { 0xFD, 0x6B, 0x88, 0xC0, 0x87, 0x24 };
19 memset(ip
, 0, sizeof(ip
));
23 void CNetAddr::SetIP(const CNetAddr
& ipIn
)
25 memcpy(ip
, ipIn
.ip
, sizeof(ip
));
28 void CNetAddr::SetRaw(Network network
, const uint8_t *ip_in
)
33 memcpy(ip
, pchIPv4
, 12);
34 memcpy(ip
+12, ip_in
, 4);
37 memcpy(ip
, ip_in
, 16);
40 assert(!"invalid network");
44 bool CNetAddr::SetInternal(const std::string
&name
)
49 unsigned char hash
[32] = {};
50 CSHA256().Write((const unsigned char*)name
.data(), name
.size()).Finalize(hash
);
51 memcpy(ip
, g_internal_prefix
, sizeof(g_internal_prefix
));
52 memcpy(ip
+ sizeof(g_internal_prefix
), hash
, sizeof(ip
) - sizeof(g_internal_prefix
));
56 bool CNetAddr::SetSpecial(const std::string
&strName
)
58 if (strName
.size()>6 && strName
.substr(strName
.size() - 6, 6) == ".onion") {
59 std::vector
<unsigned char> vchAddr
= DecodeBase32(strName
.substr(0, strName
.size() - 6).c_str());
60 if (vchAddr
.size() != 16-sizeof(pchOnionCat
))
62 memcpy(ip
, pchOnionCat
, sizeof(pchOnionCat
));
63 for (unsigned int i
=0; i
<16-sizeof(pchOnionCat
); i
++)
64 ip
[i
+ sizeof(pchOnionCat
)] = vchAddr
[i
];
75 CNetAddr::CNetAddr(const struct in_addr
& ipv4Addr
)
77 SetRaw(NET_IPV4
, (const uint8_t*)&ipv4Addr
);
80 CNetAddr::CNetAddr(const struct in6_addr
& ipv6Addr
, const uint32_t scope
)
82 SetRaw(NET_IPV6
, (const uint8_t*)&ipv6Addr
);
86 unsigned int CNetAddr::GetByte(int n
) const
91 bool CNetAddr::IsIPv4() const
93 return (memcmp(ip
, pchIPv4
, sizeof(pchIPv4
)) == 0);
96 bool CNetAddr::IsIPv6() const
98 return (!IsIPv4() && !IsTor() && !IsInternal());
101 bool CNetAddr::IsRFC1918() const
105 (GetByte(3) == 192 && GetByte(2) == 168) ||
106 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
109 bool CNetAddr::IsRFC2544() const
111 return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);
114 bool CNetAddr::IsRFC3927() const
116 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
119 bool CNetAddr::IsRFC6598() const
121 return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;
124 bool CNetAddr::IsRFC5737() const
126 return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) ||
127 (GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) ||
128 (GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113));
131 bool CNetAddr::IsRFC3849() const
133 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
136 bool CNetAddr::IsRFC3964() const
138 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
141 bool CNetAddr::IsRFC6052() const
143 static const unsigned char pchRFC6052
[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
144 return (memcmp(ip
, pchRFC6052
, sizeof(pchRFC6052
)) == 0);
147 bool CNetAddr::IsRFC4380() const
149 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
152 bool CNetAddr::IsRFC4862() const
154 static const unsigned char pchRFC4862
[] = {0xFE,0x80,0,0,0,0,0,0};
155 return (memcmp(ip
, pchRFC4862
, sizeof(pchRFC4862
)) == 0);
158 bool CNetAddr::IsRFC4193() const
160 return ((GetByte(15) & 0xFE) == 0xFC);
163 bool CNetAddr::IsRFC6145() const
165 static const unsigned char pchRFC6145
[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
166 return (memcmp(ip
, pchRFC6145
, sizeof(pchRFC6145
)) == 0);
169 bool CNetAddr::IsRFC4843() const
171 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
174 bool CNetAddr::IsTor() const
176 return (memcmp(ip
, pchOnionCat
, sizeof(pchOnionCat
)) == 0);
179 bool CNetAddr::IsLocal() const
182 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
185 // IPv6 loopback (::1/128)
186 static const unsigned char pchLocal
[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
187 if (memcmp(ip
, pchLocal
, 16) == 0)
193 bool CNetAddr::IsValid() const
195 // Cleanup 3-byte shifted addresses caused by garbage in size field
196 // of addr messages from versions before 0.2.9 checksum.
197 // Two consecutive addr messages look like this:
198 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
199 // so if the first length field is garbled, it reads the second batch
200 // of addr misaligned by 3 bytes.
201 if (memcmp(ip
, pchIPv4
+3, sizeof(pchIPv4
)-3) == 0)
204 // unspecified IPv6 address (::/128)
205 unsigned char ipNone6
[16] = {};
206 if (memcmp(ip
, ipNone6
, 16) == 0)
209 // documentation IPv6 address
219 uint32_t ipNone
= INADDR_NONE
;
220 if (memcmp(ip
+12, &ipNone
, 4) == 0)
225 if (memcmp(ip
+12, &ipNone
, 4) == 0)
232 bool CNetAddr::IsRoutable() const
234 return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal() || IsInternal());
237 bool CNetAddr::IsInternal() const
239 return memcmp(ip
, g_internal_prefix
, sizeof(g_internal_prefix
)) == 0;
242 enum Network
CNetAddr::GetNetwork() const
248 return NET_UNROUTABLE
;
259 std::string
CNetAddr::ToStringIP() const
262 return EncodeBase32(&ip
[6], 10) + ".onion";
264 return EncodeBase32(ip
+ sizeof(g_internal_prefix
), sizeof(ip
) - sizeof(g_internal_prefix
)) + ".internal";
265 CService
serv(*this, 0);
266 struct sockaddr_storage sockaddr
;
267 socklen_t socklen
= sizeof(sockaddr
);
268 if (serv
.GetSockAddr((struct sockaddr
*)&sockaddr
, &socklen
)) {
269 char name
[1025] = "";
270 if (!getnameinfo((const struct sockaddr
*)&sockaddr
, socklen
, name
, sizeof(name
), nullptr, 0, NI_NUMERICHOST
))
271 return std::string(name
);
274 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
276 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
277 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
278 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
279 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
280 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
283 std::string
CNetAddr::ToString() const
288 bool operator==(const CNetAddr
& a
, const CNetAddr
& b
)
290 return (memcmp(a
.ip
, b
.ip
, 16) == 0);
293 bool operator!=(const CNetAddr
& a
, const CNetAddr
& b
)
295 return (memcmp(a
.ip
, b
.ip
, 16) != 0);
298 bool operator<(const CNetAddr
& a
, const CNetAddr
& b
)
300 return (memcmp(a
.ip
, b
.ip
, 16) < 0);
303 bool CNetAddr::GetInAddr(struct in_addr
* pipv4Addr
) const
307 memcpy(pipv4Addr
, ip
+12, 4);
311 bool CNetAddr::GetIn6Addr(struct in6_addr
* pipv6Addr
) const
313 memcpy(pipv6Addr
, ip
, 16);
317 // get canonical identifier of an address' group
318 // no two connections will be attempted to addresses with the same group
319 std::vector
<unsigned char> CNetAddr::GetGroup() const
321 std::vector
<unsigned char> vchRet
;
322 int nClass
= NET_IPV6
;
326 // all local addresses belong to the same group
332 // all internal-usage addresses get their own group
335 nClass
= NET_INTERNAL
;
336 nStartByte
= sizeof(g_internal_prefix
);
337 nBits
= (sizeof(ip
) - sizeof(g_internal_prefix
)) * 8;
339 // all other unroutable addresses belong to the same group
340 else if (!IsRoutable())
342 nClass
= NET_UNROUTABLE
;
345 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
346 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
347 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
352 // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
353 else if (IsRFC3964())
358 // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
359 else if (IsRFC4380())
361 vchRet
.push_back(NET_IPV4
);
362 vchRet
.push_back(GetByte(3) ^ 0xFF);
363 vchRet
.push_back(GetByte(2) ^ 0xFF);
372 // for he.net, use /36 groups
373 else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
375 // for the rest of the IPv6 network, use /32 groups
379 vchRet
.push_back(nClass
);
382 vchRet
.push_back(GetByte(15 - nStartByte
));
387 vchRet
.push_back(GetByte(15 - nStartByte
) | ((1 << (8 - nBits
)) - 1));
392 uint64_t CNetAddr::GetHash() const
394 uint256 hash
= Hash(&ip
[0], &ip
[16]);
396 memcpy(&nRet
, &hash
, sizeof(nRet
));
400 // private extensions to enum Network, only returned by GetExtNetwork,
401 // and only used in GetReachabilityFrom
402 static const int NET_UNKNOWN
= NET_MAX
+ 0;
403 static const int NET_TEREDO
= NET_MAX
+ 1;
404 int static GetExtNetwork(const CNetAddr
*addr
)
408 if (addr
->IsRFC4380())
410 return addr
->GetNetwork();
413 /** Calculates a metric for how reachable (*this) is from a given partner */
414 int CNetAddr::GetReachabilityFrom(const CNetAddr
*paddrPartner
) const
426 if (!IsRoutable() || IsInternal())
427 return REACH_UNREACHABLE
;
429 int ourNet
= GetExtNetwork(this);
430 int theirNet
= GetExtNetwork(paddrPartner
);
431 bool fTunnel
= IsRFC3964() || IsRFC6052() || IsRFC6145();
436 default: return REACH_DEFAULT
;
437 case NET_IPV4
: return REACH_IPV4
;
441 default: return REACH_DEFAULT
;
442 case NET_TEREDO
: return REACH_TEREDO
;
443 case NET_IPV4
: return REACH_IPV4
;
444 case NET_IPV6
: return fTunnel
? REACH_IPV6_WEAK
: REACH_IPV6_STRONG
; // only prefer giving our IPv6 address if it's not tunnelled
448 default: return REACH_DEFAULT
;
449 case NET_IPV4
: return REACH_IPV4
; // Tor users can connect to IPv4 as well
450 case NET_TOR
: return REACH_PRIVATE
;
454 default: return REACH_DEFAULT
;
455 case NET_TEREDO
: return REACH_TEREDO
;
456 case NET_IPV6
: return REACH_IPV6_WEAK
;
457 case NET_IPV4
: return REACH_IPV4
;
463 default: return REACH_DEFAULT
;
464 case NET_TEREDO
: return REACH_TEREDO
;
465 case NET_IPV6
: return REACH_IPV6_WEAK
;
466 case NET_IPV4
: return REACH_IPV4
;
467 case NET_TOR
: return REACH_PRIVATE
; // either from Tor, or don't care about our address
472 void CService::Init()
482 CService::CService(const CNetAddr
& cip
, unsigned short portIn
) : CNetAddr(cip
), port(portIn
)
486 CService::CService(const struct in_addr
& ipv4Addr
, unsigned short portIn
) : CNetAddr(ipv4Addr
), port(portIn
)
490 CService::CService(const struct in6_addr
& ipv6Addr
, unsigned short portIn
) : CNetAddr(ipv6Addr
), port(portIn
)
494 CService::CService(const struct sockaddr_in
& addr
) : CNetAddr(addr
.sin_addr
), port(ntohs(addr
.sin_port
))
496 assert(addr
.sin_family
== AF_INET
);
499 CService::CService(const struct sockaddr_in6
&addr
) : CNetAddr(addr
.sin6_addr
, addr
.sin6_scope_id
), port(ntohs(addr
.sin6_port
))
501 assert(addr
.sin6_family
== AF_INET6
);
504 bool CService::SetSockAddr(const struct sockaddr
*paddr
)
506 switch (paddr
->sa_family
) {
508 *this = CService(*(const struct sockaddr_in
*)paddr
);
511 *this = CService(*(const struct sockaddr_in6
*)paddr
);
518 unsigned short CService::GetPort() const
523 bool operator==(const CService
& a
, const CService
& b
)
525 return (CNetAddr
)a
== (CNetAddr
)b
&& a
.port
== b
.port
;
528 bool operator!=(const CService
& a
, const CService
& b
)
530 return (CNetAddr
)a
!= (CNetAddr
)b
|| a
.port
!= b
.port
;
533 bool operator<(const CService
& a
, const CService
& b
)
535 return (CNetAddr
)a
< (CNetAddr
)b
|| ((CNetAddr
)a
== (CNetAddr
)b
&& a
.port
< b
.port
);
538 bool CService::GetSockAddr(struct sockaddr
* paddr
, socklen_t
*addrlen
) const
541 if (*addrlen
< (socklen_t
)sizeof(struct sockaddr_in
))
543 *addrlen
= sizeof(struct sockaddr_in
);
544 struct sockaddr_in
*paddrin
= (struct sockaddr_in
*)paddr
;
545 memset(paddrin
, 0, *addrlen
);
546 if (!GetInAddr(&paddrin
->sin_addr
))
548 paddrin
->sin_family
= AF_INET
;
549 paddrin
->sin_port
= htons(port
);
553 if (*addrlen
< (socklen_t
)sizeof(struct sockaddr_in6
))
555 *addrlen
= sizeof(struct sockaddr_in6
);
556 struct sockaddr_in6
*paddrin6
= (struct sockaddr_in6
*)paddr
;
557 memset(paddrin6
, 0, *addrlen
);
558 if (!GetIn6Addr(&paddrin6
->sin6_addr
))
560 paddrin6
->sin6_scope_id
= scopeId
;
561 paddrin6
->sin6_family
= AF_INET6
;
562 paddrin6
->sin6_port
= htons(port
);
568 std::vector
<unsigned char> CService::GetKey() const
570 std::vector
<unsigned char> vKey
;
572 memcpy(vKey
.data(), ip
, 16);
573 vKey
[16] = port
/ 0x100;
574 vKey
[17] = port
& 0x0FF;
578 std::string
CService::ToStringPort() const
580 return strprintf("%u", port
);
583 std::string
CService::ToStringIPPort() const
585 if (IsIPv4() || IsTor() || IsInternal()) {
586 return ToStringIP() + ":" + ToStringPort();
588 return "[" + ToStringIP() + "]:" + ToStringPort();
592 std::string
CService::ToString() const
594 return ToStringIPPort();
600 memset(netmask
, 0, sizeof(netmask
));
603 CSubNet::CSubNet(const CNetAddr
&addr
, int32_t mask
)
607 // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
608 memset(netmask
, 255, sizeof(netmask
));
610 // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
611 const int astartofs
= network
.IsIPv4() ? 12 : 0;
614 if(n
>= 0 && n
<= (128 - astartofs
*8)) // Only valid if in range of bits of address
617 // Clear bits [n..127]
619 netmask
[n
>>3] &= ~(1<<(7-(n
&7)));
623 // Normalize network according to netmask
624 for(int x
=0; x
<16; ++x
)
625 network
.ip
[x
] &= netmask
[x
];
628 CSubNet::CSubNet(const CNetAddr
&addr
, const CNetAddr
&mask
)
632 // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
633 memset(netmask
, 255, sizeof(netmask
));
635 // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
636 const int astartofs
= network
.IsIPv4() ? 12 : 0;
638 for(int x
=astartofs
; x
<16; ++x
)
639 netmask
[x
] = mask
.ip
[x
];
641 // Normalize network according to netmask
642 for(int x
=0; x
<16; ++x
)
643 network
.ip
[x
] &= netmask
[x
];
646 CSubNet::CSubNet(const CNetAddr
&addr
):
647 valid(addr
.IsValid())
649 memset(netmask
, 255, sizeof(netmask
));
653 bool CSubNet::Match(const CNetAddr
&addr
) const
655 if (!valid
|| !addr
.IsValid())
657 for(int x
=0; x
<16; ++x
)
658 if ((addr
.ip
[x
] & netmask
[x
]) != network
.ip
[x
])
663 static inline int NetmaskBits(uint8_t x
)
666 case 0x00: return 0; break;
667 case 0x80: return 1; break;
668 case 0xc0: return 2; break;
669 case 0xe0: return 3; break;
670 case 0xf0: return 4; break;
671 case 0xf8: return 5; break;
672 case 0xfc: return 6; break;
673 case 0xfe: return 7; break;
674 case 0xff: return 8; break;
675 default: return -1; break;
679 std::string
CSubNet::ToString() const
681 /* Parse binary 1{n}0{N-n} to see if mask can be represented as /n */
683 bool valid_cidr
= true;
684 int n
= network
.IsIPv4() ? 12 : 0;
685 for (; n
< 16 && netmask
[n
] == 0xff; ++n
)
688 int bits
= NetmaskBits(netmask
[n
]);
695 for (; n
< 16 && valid_cidr
; ++n
)
696 if (netmask
[n
] != 0x00)
700 std::string strNetmask
;
702 strNetmask
= strprintf("%u", cidr
);
704 if (network
.IsIPv4())
705 strNetmask
= strprintf("%u.%u.%u.%u", netmask
[12], netmask
[13], netmask
[14], netmask
[15]);
707 strNetmask
= strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
708 netmask
[0] << 8 | netmask
[1], netmask
[2] << 8 | netmask
[3],
709 netmask
[4] << 8 | netmask
[5], netmask
[6] << 8 | netmask
[7],
710 netmask
[8] << 8 | netmask
[9], netmask
[10] << 8 | netmask
[11],
711 netmask
[12] << 8 | netmask
[13], netmask
[14] << 8 | netmask
[15]);
714 return network
.ToString() + "/" + strNetmask
;
717 bool CSubNet::IsValid() const
722 bool operator==(const CSubNet
& a
, const CSubNet
& b
)
724 return a
.valid
== b
.valid
&& a
.network
== b
.network
&& !memcmp(a
.netmask
, b
.netmask
, 16);
727 bool operator!=(const CSubNet
& a
, const CSubNet
& b
)
732 bool operator<(const CSubNet
& a
, const CSubNet
& b
)
734 return (a
.network
< b
.network
|| (a
.network
== b
.network
&& memcmp(a
.netmask
, b
.netmask
, 16) < 0));