1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
10 #include <sys/fcntl.h>
18 int fUseProxy
= false;
19 CService
addrProxy("127.0.0.1",9050);
20 int nConnectTimeout
= 5000;
23 static const unsigned char pchIPv4
[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
25 bool static LookupIntern(const char *pszName
, std::vector
<CNetAddr
>& vIP
, int nMaxSolutions
, bool fAllowLookup
)
28 struct addrinfo aiHint
;
29 memset(&aiHint
, 0, sizeof(struct addrinfo
));
31 aiHint
.ai_socktype
= SOCK_STREAM
;
32 aiHint
.ai_protocol
= IPPROTO_TCP
;
35 aiHint
.ai_family
= AF_UNSPEC
;
36 aiHint
.ai_flags
= fAllowLookup
? 0 : AI_NUMERICHOST
;
38 aiHint
.ai_family
= AF_INET
;
39 aiHint
.ai_flags
= fAllowLookup
? 0 : AI_NUMERICHOST
;
43 aiHint
.ai_family
= AF_UNSPEC
;
44 aiHint
.ai_flags
= AI_ADDRCONFIG
| (fAllowLookup
? 0 : AI_NUMERICHOST
);
46 aiHint
.ai_family
= AF_INET
;
47 aiHint
.ai_flags
= AI_ADDRCONFIG
| (fAllowLookup
? 0 : AI_NUMERICHOST
);
50 struct addrinfo
*aiRes
= NULL
;
51 int nErr
= getaddrinfo(pszName
, NULL
, &aiHint
, &aiRes
);
55 struct addrinfo
*aiTrav
= aiRes
;
56 while (aiTrav
!= NULL
&& (nMaxSolutions
== 0 || vIP
.size() < nMaxSolutions
))
58 if (aiTrav
->ai_family
== AF_INET
)
60 assert(aiTrav
->ai_addrlen
>= sizeof(sockaddr_in
));
61 vIP
.push_back(CNetAddr(((struct sockaddr_in
*)(aiTrav
->ai_addr
))->sin_addr
));
65 if (aiTrav
->ai_family
== AF_INET6
)
67 assert(aiTrav
->ai_addrlen
>= sizeof(sockaddr_in6
));
68 vIP
.push_back(CNetAddr(((struct sockaddr_in6
*)(aiTrav
->ai_addr
))->sin6_addr
));
72 aiTrav
= aiTrav
->ai_next
;
77 return (vIP
.size() > 0);
80 bool LookupHost(const char *pszName
, std::vector
<CNetAddr
>& vIP
, int nMaxSolutions
, bool fAllowLookup
)
86 strlcpy(psz
, pszName
, sizeof(psz
));
87 if (psz
[0] == '[' && psz
[strlen(psz
)-1] == ']')
90 psz
[strlen(psz
)-1] = 0;
93 return LookupIntern(pszHost
, vIP
, nMaxSolutions
, fAllowLookup
);
96 bool LookupHostNumeric(const char *pszName
, std::vector
<CNetAddr
>& vIP
, int nMaxSolutions
)
98 return LookupHost(pszName
, vIP
, nMaxSolutions
, false);
101 bool Lookup(const char *pszName
, std::vector
<CService
>& vAddr
, int portDefault
, bool fAllowLookup
, int nMaxSolutions
)
105 int port
= portDefault
;
108 strlcpy(psz
, pszName
, sizeof(psz
));
109 char* pszColon
= strrchr(psz
+1,':');
110 char *pszPortEnd
= NULL
;
111 int portParsed
= pszColon
? strtoul(pszColon
+1, &pszPortEnd
, 10) : 0;
112 if (pszColon
&& pszPortEnd
&& pszPortEnd
[0] == 0)
114 if (psz
[0] == '[' && pszColon
[-1] == ']')
121 if (port
>= 0 && port
<= USHRT_MAX
)
126 if (psz
[0] == '[' && psz
[strlen(psz
)-1] == ']')
129 psz
[strlen(psz
)-1] = 0;
134 std::vector
<CNetAddr
> vIP
;
135 bool fRet
= LookupIntern(pszHost
, vIP
, nMaxSolutions
, fAllowLookup
);
138 vAddr
.resize(vIP
.size());
139 for (int i
= 0; i
< vIP
.size(); i
++)
140 vAddr
[i
] = CService(vIP
[i
], port
);
144 bool Lookup(const char *pszName
, CService
& addr
, int portDefault
, bool fAllowLookup
)
146 std::vector
<CService
> vService
;
147 bool fRet
= Lookup(pszName
, vService
, portDefault
, fAllowLookup
, 1);
154 bool LookupNumeric(const char *pszName
, CService
& addr
, int portDefault
)
156 return Lookup(pszName
, addr
, portDefault
, false);
159 bool ConnectSocket(const CService
&addrDest
, SOCKET
& hSocketRet
, int nTimeout
)
161 hSocketRet
= INVALID_SOCKET
;
163 SOCKET hSocket
= socket(AF_INET
, SOCK_STREAM
, IPPROTO_TCP
);
164 if (hSocket
== INVALID_SOCKET
)
168 setsockopt(hSocket
, SOL_SOCKET
, SO_NOSIGPIPE
, (void*)&set
, sizeof(int));
171 bool fProxy
= (fUseProxy
&& addrDest
.IsRoutable());
172 struct sockaddr_in sockaddr
;
174 addrProxy
.GetSockAddr(&sockaddr
);
176 addrDest
.GetSockAddr(&sockaddr
);
179 u_long fNonblock
= 1;
180 if (ioctlsocket(hSocket
, FIONBIO
, &fNonblock
) == SOCKET_ERROR
)
182 int fFlags
= fcntl(hSocket
, F_GETFL
, 0);
183 if (fcntl(hSocket
, F_SETFL
, fFlags
| O_NONBLOCK
) == -1)
186 closesocket(hSocket
);
191 if (connect(hSocket
, (struct sockaddr
*)&sockaddr
, sizeof(sockaddr
)) == SOCKET_ERROR
)
193 // WSAEINVAL is here because some legacy version of winsock uses it
194 if (WSAGetLastError() == WSAEINPROGRESS
|| WSAGetLastError() == WSAEWOULDBLOCK
|| WSAGetLastError() == WSAEINVAL
)
196 struct timeval timeout
;
197 timeout
.tv_sec
= nTimeout
/ 1000;
198 timeout
.tv_usec
= (nTimeout
% 1000) * 1000;
202 FD_SET(hSocket
, &fdset
);
203 int nRet
= select(hSocket
+ 1, NULL
, &fdset
, NULL
, &timeout
);
206 printf("connection timeout\n");
207 closesocket(hSocket
);
210 if (nRet
== SOCKET_ERROR
)
212 printf("select() for connection failed: %i\n",WSAGetLastError());
213 closesocket(hSocket
);
216 socklen_t nRetSize
= sizeof(nRet
);
218 if (getsockopt(hSocket
, SOL_SOCKET
, SO_ERROR
, (char*)(&nRet
), &nRetSize
) == SOCKET_ERROR
)
220 if (getsockopt(hSocket
, SOL_SOCKET
, SO_ERROR
, &nRet
, &nRetSize
) == SOCKET_ERROR
)
223 printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
224 closesocket(hSocket
);
229 printf("connect() failed after select(): %s\n",strerror(nRet
));
230 closesocket(hSocket
);
235 else if (WSAGetLastError() != WSAEISCONN
)
240 printf("connect() failed: %i\n",WSAGetLastError());
241 closesocket(hSocket
);
246 // this isn't even strictly necessary
247 // CNode::ConnectNode immediately turns the socket back to non-blocking
248 // but we'll turn it back to blocking just in case
251 if (ioctlsocket(hSocket
, FIONBIO
, &fNonblock
) == SOCKET_ERROR
)
253 fFlags
= fcntl(hSocket
, F_GETFL
, 0);
254 if (fcntl(hSocket
, F_SETFL
, fFlags
& !O_NONBLOCK
) == SOCKET_ERROR
)
257 closesocket(hSocket
);
263 printf("proxy connecting %s\n", addrDest
.ToString().c_str());
264 char pszSocks4IP
[] = "\4\1\0\0\0\0\0\0user";
265 struct sockaddr_in addr
;
266 addrDest
.GetSockAddr(&addr
);
267 memcpy(pszSocks4IP
+ 2, &addr
.sin_port
, 2);
268 memcpy(pszSocks4IP
+ 4, &addr
.sin_addr
, 4);
269 char* pszSocks4
= pszSocks4IP
;
270 int nSize
= sizeof(pszSocks4IP
);
272 int ret
= send(hSocket
, pszSocks4
, nSize
, MSG_NOSIGNAL
);
275 closesocket(hSocket
);
276 return error("Error sending to proxy");
279 if (recv(hSocket
, pchRet
, 8, 0) != 8)
281 closesocket(hSocket
);
282 return error("Error reading proxy response");
284 if (pchRet
[1] != 0x5a)
286 closesocket(hSocket
);
287 if (pchRet
[1] != 0x5b)
288 printf("ERROR: Proxy returned error %d\n", pchRet
[1]);
291 printf("proxy connected %s\n", addrDest
.ToString().c_str());
294 hSocketRet
= hSocket
;
298 void CNetAddr::Init()
303 void CNetAddr::SetIP(const CNetAddr
& ipIn
)
305 memcpy(ip
, ipIn
.ip
, sizeof(ip
));
313 CNetAddr::CNetAddr(const struct in_addr
& ipv4Addr
)
315 memcpy(ip
, pchIPv4
, 12);
316 memcpy(ip
+12, &ipv4Addr
, 4);
320 CNetAddr::CNetAddr(const struct in6_addr
& ipv6Addr
)
322 memcpy(ip
, &ipv6Addr
, 16);
326 CNetAddr::CNetAddr(const char *pszIp
, bool fAllowLookup
)
329 std::vector
<CNetAddr
> vIP
;
330 if (LookupHost(pszIp
, vIP
, 1, fAllowLookup
))
334 CNetAddr::CNetAddr(const std::string
&strIp
, bool fAllowLookup
)
337 std::vector
<CNetAddr
> vIP
;
338 if (LookupHost(strIp
.c_str(), vIP
, 1, fAllowLookup
))
342 int CNetAddr::GetByte(int n
) const
347 bool CNetAddr::IsIPv4() const
349 return (memcmp(ip
, pchIPv4
, sizeof(pchIPv4
)) == 0);
352 bool CNetAddr::IsRFC1918() const
356 (GetByte(3) == 192 && GetByte(2) == 168) ||
357 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
360 bool CNetAddr::IsRFC3927() const
362 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
365 bool CNetAddr::IsRFC3849() const
367 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
370 bool CNetAddr::IsRFC3964() const
372 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
375 bool CNetAddr::IsRFC6052() const
377 static const unsigned char pchRFC6052
[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
378 return (memcmp(ip
, pchRFC6052
, sizeof(pchRFC6052
)) == 0);
381 bool CNetAddr::IsRFC4380() const
383 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
386 bool CNetAddr::IsRFC4862() const
388 static const unsigned char pchRFC4862
[] = {0xFE,0x80,0,0,0,0,0,0};
389 return (memcmp(ip
, pchRFC4862
, sizeof(pchRFC4862
)) == 0);
392 bool CNetAddr::IsRFC4193() const
394 return ((GetByte(15) & 0xFE) == 0xFC);
397 bool CNetAddr::IsRFC6145() const
399 static const unsigned char pchRFC6145
[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
400 return (memcmp(ip
, pchRFC6145
, sizeof(pchRFC6145
)) == 0);
403 bool CNetAddr::IsRFC4843() const
405 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
408 bool CNetAddr::IsLocal() const
411 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
414 // IPv6 loopback (::1/128)
415 static const unsigned char pchLocal
[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
416 if (memcmp(ip
, pchLocal
, 16) == 0)
422 bool CNetAddr::IsMulticast() const
424 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
425 || (GetByte(15) == 0xFF);
428 bool CNetAddr::IsValid() const
430 // Clean up 3-byte shifted addresses caused by garbage in size field
431 // of addr messages from versions before 0.2.9 checksum.
432 // Two consecutive addr messages look like this:
433 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
434 // so if the first length field is garbled, it reads the second batch
435 // of addr misaligned by 3 bytes.
436 if (memcmp(ip
, pchIPv4
+3, sizeof(pchIPv4
)-3) == 0)
439 // unspecified IPv6 address (::/128)
440 unsigned char ipNone
[16] = {};
441 if (memcmp(ip
, ipNone
, 16) == 0)
444 // documentation IPv6 address
451 uint32_t ipNone
= INADDR_NONE
;
452 if (memcmp(ip
+12, &ipNone
, 4) == 0)
457 if (memcmp(ip
+12, &ipNone
, 4) == 0)
464 bool CNetAddr::IsRoutable() const
466 return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || IsRFC4193() || IsRFC4843() || IsLocal());
469 std::string
CNetAddr::ToStringIP() const
472 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
474 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
475 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
476 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
477 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
478 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
481 std::string
CNetAddr::ToString() const
486 bool operator==(const CNetAddr
& a
, const CNetAddr
& b
)
488 return (memcmp(a
.ip
, b
.ip
, 16) == 0);
491 bool operator!=(const CNetAddr
& a
, const CNetAddr
& b
)
493 return (memcmp(a
.ip
, b
.ip
, 16) != 0);
496 bool operator<(const CNetAddr
& a
, const CNetAddr
& b
)
498 return (memcmp(a
.ip
, b
.ip
, 16) < 0);
501 bool CNetAddr::GetInAddr(struct in_addr
* pipv4Addr
) const
505 memcpy(pipv4Addr
, ip
+12, 4);
510 bool CNetAddr::GetIn6Addr(struct in6_addr
* pipv6Addr
) const
512 memcpy(pipv6Addr
, ip
, 16);
517 // get canonical identifier of an address' group
518 // no two connections will be attempted to addresses with the same group
519 std::vector
<unsigned char> CNetAddr::GetGroup() const
521 std::vector
<unsigned char> vchRet
;
522 int nClass
= 0; // 0=IPv6, 1=IPv4, 255=unroutable
526 // for unroutable addresses, each address is considered different
532 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
533 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
534 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
539 // for 6to4 tunneled addresses, use the encapsulated IPv4 address
540 else if (IsRFC3964())
545 // for Teredo-tunneled IPv6 addresses, use the encapsulated IPv4 address
546 else if (IsRFC4380())
549 vchRet
.push_back(GetByte(3) ^ 0xFF);
550 vchRet
.push_back(GetByte(2) ^ 0xFF);
553 // for he.net, use /36 groups
554 else if (GetByte(15) == 0x20 && GetByte(14) == 0x11 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
556 // for the rest of the IPv6 network, use /32 groups
560 vchRet
.push_back(nClass
);
563 vchRet
.push_back(GetByte(15 - nStartByte
));
568 vchRet
.push_back(GetByte(15 - nStartByte
) | ((1 << nBits
) - 1));
573 int64
CNetAddr::GetHash() const
575 uint256 hash
= Hash(&ip
[0], &ip
[16]);
577 memcpy(&nRet
, &hash
, sizeof(nRet
));
581 void CNetAddr::print() const
583 printf("CNetAddr(%s)\n", ToString().c_str());
586 void CService::Init()
596 CService::CService(const CNetAddr
& cip
, unsigned short portIn
) : CNetAddr(cip
), port(portIn
)
600 CService::CService(const struct in_addr
& ipv4Addr
, unsigned short portIn
) : CNetAddr(ipv4Addr
), port(portIn
)
605 CService::CService(const struct in6_addr
& ipv6Addr
, unsigned short portIn
) : CNetAddr(ipv6Addr
), port(portIn
)
610 CService::CService(const struct sockaddr_in
& addr
) : CNetAddr(addr
.sin_addr
), port(ntohs(addr
.sin_port
))
612 assert(addr
.sin_family
== AF_INET
);
616 CService::CService(const struct sockaddr_in6
&addr
) : CNetAddr(addr
.sin6_addr
), port(ntohs(addr
.sin6_port
))
618 assert(addr
.sin6_family
== AF_INET6
);
622 CService::CService(const char *pszIpPort
, bool fAllowLookup
)
626 if (Lookup(pszIpPort
, ip
, 0, fAllowLookup
))
630 CService::CService(const char *pszIpPort
, int portDefault
, bool fAllowLookup
)
634 if (Lookup(pszIpPort
, ip
, portDefault
, fAllowLookup
))
638 CService::CService(const std::string
&strIpPort
, bool fAllowLookup
)
642 if (Lookup(strIpPort
.c_str(), ip
, 0, fAllowLookup
))
646 CService::CService(const std::string
&strIpPort
, int portDefault
, bool fAllowLookup
)
650 if (Lookup(strIpPort
.c_str(), ip
, portDefault
, fAllowLookup
))
654 unsigned short CService::GetPort() const
659 bool operator==(const CService
& a
, const CService
& b
)
661 return (CNetAddr
)a
== (CNetAddr
)b
&& a
.port
== b
.port
;
664 bool operator!=(const CService
& a
, const CService
& b
)
666 return (CNetAddr
)a
!= (CNetAddr
)b
|| a
.port
!= b
.port
;
669 bool operator<(const CService
& a
, const CService
& b
)
671 return (CNetAddr
)a
< (CNetAddr
)b
|| ((CNetAddr
)a
== (CNetAddr
)b
&& a
.port
< b
.port
);
674 bool CService::GetSockAddr(struct sockaddr_in
* paddr
) const
678 memset(paddr
, 0, sizeof(struct sockaddr_in
));
679 if (!GetInAddr(&paddr
->sin_addr
))
681 paddr
->sin_family
= AF_INET
;
682 paddr
->sin_port
= htons(port
);
687 bool CService::GetSockAddr6(struct sockaddr_in6
* paddr
) const
689 memset(paddr
, 0, sizeof(struct sockaddr_in6
));
690 if (!GetIn6Addr(&paddr
->sin6_addr
))
692 paddr
->sin6_family
= AF_INET6
;
693 paddr
->sin6_port
= htons(port
);
698 std::vector
<unsigned char> CService::GetKey() const
700 std::vector
<unsigned char> vKey
;
702 memcpy(&vKey
[0], ip
, 16);
703 vKey
[16] = port
/ 0x100;
704 vKey
[17] = port
& 0x0FF;
708 std::string
CService::ToStringPort() const
710 return strprintf(":%i", port
);
713 std::string
CService::ToStringIPPort() const
715 return ToStringIP() + ToStringPort();
718 std::string
CService::ToString() const
720 return ToStringIPPort();
723 void CService::print() const
725 printf("CService(%s)\n", ToString().c_str());
728 void CService::SetPort(unsigned short portIn
)