1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 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 aiHint.ai_socktype = SOCK_STREAM;
30 aiHint.ai_protocol = IPPROTO_TCP;
33 aiHint.ai_family = AF_UNSPEC;
34 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
36 aiHint.ai_family = AF_INET;
37 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
41 aiHint.ai_family = AF_UNSPEC;
42 aiHint.ai_flags = AI_ADDRCONFIG | (fAllowLookup ? 0 : AI_NUMERICHOST);
44 aiHint.ai_family = AF_INET;
45 aiHint.ai_flags = AI_ADDRCONFIG | (fAllowLookup ? 0 : AI_NUMERICHOST);
48 struct addrinfo *aiRes = NULL;
49 int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
53 struct addrinfo *aiTrav = aiRes;
54 while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
56 if (aiTrav->ai_family == AF_INET)
58 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
59 vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
63 if (aiTrav->ai_family == AF_INET6)
65 assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
66 vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
70 aiTrav = aiTrav->ai_next;
75 return (vIP.size() > 0);
78 bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, int nMaxSolutions, bool fAllowLookup)
84 strlcpy(psz, pszName, sizeof(psz));
85 if (psz[0] == '[' && psz[strlen(psz)-1] == ']')
88 psz[strlen(psz)-1] = 0;
91 return LookupIntern(pszHost, vIP, nMaxSolutions, fAllowLookup);
94 bool LookupHostNumeric(const char *pszName, std::vector<CNetAddr>& vIP, int nMaxSolutions)
96 return LookupHost(pszName, vIP, nMaxSolutions, false);
99 bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
103 int port = portDefault;
106 strlcpy(psz, pszName, sizeof(psz));
107 char* pszColon = strrchr(psz+1,':');
108 char *pszPortEnd = NULL;
109 int portParsed = pszColon ? strtoul(pszColon+1, &pszPortEnd, 10) : 0;
110 if (pszColon && pszPortEnd && pszPortEnd[0] == 0)
112 if (psz[0] == '[' && pszColon[-1] == ']')
119 if (port >= 0 && port <= USHRT_MAX)
124 if (psz[0] == '[' && psz[strlen(psz)-1] == ']')
127 psz[strlen(psz)-1] = 0;
132 std::vector<CNetAddr> vIP;
133 bool fRet = LookupIntern(pszHost, vIP, 1, fAllowLookup);
136 addr = CService(vIP[0], port);
140 bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
142 return Lookup(pszName, addr, portDefault, false);
145 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
147 hSocketRet = INVALID_SOCKET;
149 SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
150 if (hSocket == INVALID_SOCKET)
154 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
157 bool fProxy = (fUseProxy && addrDest.IsRoutable());
158 struct sockaddr_in sockaddr;
160 addrProxy.GetSockAddr(&sockaddr);
162 addrDest.GetSockAddr(&sockaddr);
165 u_long fNonblock = 1;
166 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
168 int fFlags = fcntl(hSocket, F_GETFL, 0);
169 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
172 closesocket(hSocket);
177 if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)
179 // WSAEINVAL is here because some legacy version of winsock uses it
180 if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
182 struct timeval timeout;
183 timeout.tv_sec = nTimeout / 1000;
184 timeout.tv_usec = (nTimeout % 1000) * 1000;
188 FD_SET(hSocket, &fdset);
189 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
192 printf("connection timeout\n");
193 closesocket(hSocket);
196 if (nRet == SOCKET_ERROR)
198 printf("select() for connection failed: %i\n",WSAGetLastError());
199 closesocket(hSocket);
202 socklen_t nRetSize = sizeof(nRet);
204 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
206 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
209 printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
210 closesocket(hSocket);
215 printf("connect() failed after select(): %s\n",strerror(nRet));
216 closesocket(hSocket);
221 else if (WSAGetLastError() != WSAEISCONN)
226 printf("connect() failed: %i\n",WSAGetLastError());
227 closesocket(hSocket);
232 // this isn't even strictly necessary
233 // CNode::ConnectNode immediately turns the socket back to non-blocking
234 // but we'll turn it back to blocking just in case
237 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
239 fFlags = fcntl(hSocket, F_GETFL, 0);
240 if (fcntl(hSocket, F_SETFL, fFlags & !O_NONBLOCK) == SOCKET_ERROR)
243 closesocket(hSocket);
249 printf("proxy connecting %s\n", addrDest.ToString().c_str());
250 char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
251 struct sockaddr_in addr;
252 addrDest.GetSockAddr(&addr);
253 memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
254 memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
255 char* pszSocks4 = pszSocks4IP;
256 int nSize = sizeof(pszSocks4IP);
258 int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
261 closesocket(hSocket);
262 return error("Error sending to proxy");
265 if (recv(hSocket, pchRet, 8, 0) != 8)
267 closesocket(hSocket);
268 return error("Error reading proxy response");
270 if (pchRet[1] != 0x5a)
272 closesocket(hSocket);
273 if (pchRet[1] != 0x5b)
274 printf("ERROR: Proxy returned error %d\n", pchRet[1]);
277 printf("proxy connected %s\n", addrDest.ToString().c_str());
280 hSocketRet = hSocket;
284 void CNetAddr::Init()
289 void CNetAddr::SetIP(const CNetAddr& ipIn)
291 memcpy(ip, ipIn.ip, sizeof(ip));
299 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
301 memcpy(ip, pchIPv4, 12);
302 memcpy(ip+12, &ipv4Addr, 4);
306 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
308 memcpy(ip, &ipv6Addr, 16);
312 CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
315 std::vector<CNetAddr> vIP;
316 if (LookupHost(pszIp, vIP, 1, fAllowLookup))
320 CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
323 std::vector<CNetAddr> vIP;
324 if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
328 int CNetAddr::GetByte(int n) const
333 bool CNetAddr::IsIPv4() const
335 return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
338 bool CNetAddr::IsRFC1918() const
342 (GetByte(3) == 192 && GetByte(2) == 168) ||
343 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
346 bool CNetAddr::IsRFC3927() const
348 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
351 bool CNetAddr::IsRFC3849() const
353 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
356 bool CNetAddr::IsRFC3964() const
358 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
361 bool CNetAddr::IsRFC6052() const
363 static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
364 return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
367 bool CNetAddr::IsRFC4380() const
369 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
372 bool CNetAddr::IsRFC4862() const
374 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
375 return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
378 bool CNetAddr::IsRFC4193() const
380 return ((GetByte(15) & 0xFE) == 0xFC);
383 bool CNetAddr::IsRFC6145() const
385 static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
386 return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
389 bool CNetAddr::IsRFC4843() const
391 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && GetByte(12) & 0xF0 == 0x10);
394 bool CNetAddr::IsLocal() const
397 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
400 // IPv6 loopback (::1/128)
401 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
402 if (memcmp(ip, pchLocal, 16) == 0)
408 bool CNetAddr::IsMulticast() const
410 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
411 || (GetByte(15) == 0xFF);
414 bool CNetAddr::IsValid() const
416 // Clean up 3-byte shifted addresses caused by garbage in size field
417 // of addr messages from versions before 0.2.9 checksum.
418 // Two consecutive addr messages look like this:
419 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
420 // so if the first length field is garbled, it reads the second batch
421 // of addr misaligned by 3 bytes.
422 if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
425 // unspecified IPv6 address (::/128)
426 unsigned char ipNone[16] = {};
427 if (memcmp(ip, ipNone, 16) == 0)
430 // documentation IPv6 address
437 uint32_t ipNone = INADDR_NONE;
438 if (memcmp(ip+12, &ipNone, 4) == 0)
443 if (memcmp(ip+12, &ipNone, 4) == 0)
450 bool CNetAddr::IsRoutable() const
452 return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || IsRFC4193() || IsRFC4843() || IsLocal());
455 std::string CNetAddr::ToStringIP() const
458 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
460 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
461 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
462 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
463 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
464 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
467 std::string CNetAddr::ToString() const
472 bool operator==(const CNetAddr& a, const CNetAddr& b)
474 return (memcmp(a.ip, b.ip, 16) == 0);
477 bool operator!=(const CNetAddr& a, const CNetAddr& b)
479 return (memcmp(a.ip, b.ip, 16) != 0);
482 bool operator<(const CNetAddr& a, const CNetAddr& b)
484 return (memcmp(a.ip, b.ip, 16) < 0);
487 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
491 memcpy(pipv4Addr, ip+12, 4);
496 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
498 memcpy(pipv6Addr, ip, 16);
503 // get canonical identifier of an address' group
504 // no two connections will be attempted to addresses with the same group
505 std::vector<unsigned char> CNetAddr::GetGroup() const
507 std::vector<unsigned char> vchRet;
508 int nClass = 0; // 0=IPv6, 1=IPv4, 255=unroutable
512 // for unroutable addresses, each address is considered different
518 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
519 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
520 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
525 // for 6to4 tunneled addresses, use the encapsulated IPv4 address
526 else if (IsRFC3964())
531 // for Teredo-tunneled IPv6 addresses, use the encapsulated IPv4 address
532 else if (IsRFC4380())
535 vchRet.push_back(GetByte(3) ^ 0xFF);
536 vchRet.push_back(GetByte(2) ^ 0xFF);
539 // for he.net, use /36 groups
540 else if (GetByte(15) == 0x20 && GetByte(14) == 0x11 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
542 // for the rest of the IPv6 network, use /32 groups
546 vchRet.push_back(nClass);
549 vchRet.push_back(GetByte(15 - nStartByte));
554 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
559 int64 CNetAddr::GetHash() const
561 uint256 hash = Hash(&ip[0], &ip[16]);
563 memcpy(&nRet, &hash, sizeof(nRet));
567 void CNetAddr::print() const
569 printf("CNetAddr(%s)\n", ToString().c_str());
572 void CService::Init()
582 CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
586 CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
591 CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
596 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
598 assert(addr.sin_family == AF_INET);
602 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
604 assert(addr.sin6_family == AF_INET6);
608 CService::CService(const char *pszIpPort, bool fAllowLookup)
612 if (Lookup(pszIpPort, ip, 0, fAllowLookup))
616 CService::CService(const char *pszIp, int portIn, bool fAllowLookup)
618 std::vector<CNetAddr> ip;
619 if (LookupHost(pszIp, ip, 1, fAllowLookup))
620 *this = CService(ip[0], portIn);
623 CService::CService(const std::string &strIpPort, bool fAllowLookup)
627 if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
631 CService::CService(const std::string &strIp, int portIn, bool fAllowLookup)
633 std::vector<CNetAddr> ip;
634 if (LookupHost(strIp.c_str(), ip, 1, fAllowLookup))
635 *this = CService(ip[0], portIn);
638 unsigned short CService::GetPort() const
643 bool operator==(const CService& a, const CService& b)
645 return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
648 bool operator!=(const CService& a, const CService& b)
650 return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
653 bool operator<(const CService& a, const CService& b)
655 return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
658 bool CService::GetSockAddr(struct sockaddr_in* paddr) const
662 memset(paddr, 0, sizeof(struct sockaddr_in));
663 if (!GetInAddr(&paddr->sin_addr))
665 paddr->sin_family = AF_INET;
666 paddr->sin_port = htons(port);
671 bool CService::GetSockAddr6(struct sockaddr_in6* paddr) const
673 memset(paddr, 0, sizeof(struct sockaddr_in6));
674 if (!GetIn6Addr(&paddr->sin6_addr))
676 paddr->sin6_family = AF_INET6;
677 paddr->sin6_port = htons(port);
682 std::vector<unsigned char> CService::GetKey() const
684 std::vector<unsigned char> vKey;
686 memcpy(&vKey[0], ip, 16);
687 vKey[16] = port / 0x100;
688 vKey[17] = port & 0x0FF;
692 std::string CService::ToStringPort() const
694 return strprintf(":%i", port);
697 std::string CService::ToStringIPPort() const
699 return ToStringIP() + ToStringPort();
702 std::string CService::ToString() const
704 return ToStringIPPort();
707 void CService::print() const
709 printf("CService(%s)\n", ToString().c_str());
712 void CService::SetPort(unsigned short portIn)