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 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, CService& addr, int portDefault, bool fAllowLookup)
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, 1, fAllowLookup);
138 addr = CService(vIP[0], port);
142 bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
144 return Lookup(pszName, addr, portDefault, false);
147 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
149 hSocketRet = INVALID_SOCKET;
151 SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
152 if (hSocket == INVALID_SOCKET)
156 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
159 bool fProxy = (fUseProxy && addrDest.IsRoutable());
160 struct sockaddr_in sockaddr;
162 addrProxy.GetSockAddr(&sockaddr);
164 addrDest.GetSockAddr(&sockaddr);
167 u_long fNonblock = 1;
168 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
170 int fFlags = fcntl(hSocket, F_GETFL, 0);
171 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
174 closesocket(hSocket);
179 if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)
181 // WSAEINVAL is here because some legacy version of winsock uses it
182 if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
184 struct timeval timeout;
185 timeout.tv_sec = nTimeout / 1000;
186 timeout.tv_usec = (nTimeout % 1000) * 1000;
190 FD_SET(hSocket, &fdset);
191 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
194 printf("connection timeout\n");
195 closesocket(hSocket);
198 if (nRet == SOCKET_ERROR)
200 printf("select() for connection failed: %i\n",WSAGetLastError());
201 closesocket(hSocket);
204 socklen_t nRetSize = sizeof(nRet);
206 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
208 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
211 printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
212 closesocket(hSocket);
217 printf("connect() failed after select(): %s\n",strerror(nRet));
218 closesocket(hSocket);
223 else if (WSAGetLastError() != WSAEISCONN)
228 printf("connect() failed: %i\n",WSAGetLastError());
229 closesocket(hSocket);
234 // this isn't even strictly necessary
235 // CNode::ConnectNode immediately turns the socket back to non-blocking
236 // but we'll turn it back to blocking just in case
239 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
241 fFlags = fcntl(hSocket, F_GETFL, 0);
242 if (fcntl(hSocket, F_SETFL, fFlags & !O_NONBLOCK) == SOCKET_ERROR)
245 closesocket(hSocket);
251 printf("proxy connecting %s\n", addrDest.ToString().c_str());
252 char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
253 struct sockaddr_in addr;
254 addrDest.GetSockAddr(&addr);
255 memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
256 memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
257 char* pszSocks4 = pszSocks4IP;
258 int nSize = sizeof(pszSocks4IP);
260 int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
263 closesocket(hSocket);
264 return error("Error sending to proxy");
267 if (recv(hSocket, pchRet, 8, 0) != 8)
269 closesocket(hSocket);
270 return error("Error reading proxy response");
272 if (pchRet[1] != 0x5a)
274 closesocket(hSocket);
275 if (pchRet[1] != 0x5b)
276 printf("ERROR: Proxy returned error %d\n", pchRet[1]);
279 printf("proxy connected %s\n", addrDest.ToString().c_str());
282 hSocketRet = hSocket;
286 void CNetAddr::Init()
291 void CNetAddr::SetIP(const CNetAddr& ipIn)
293 memcpy(ip, ipIn.ip, sizeof(ip));
301 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
303 memcpy(ip, pchIPv4, 12);
304 memcpy(ip+12, &ipv4Addr, 4);
308 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
310 memcpy(ip, &ipv6Addr, 16);
314 CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
317 std::vector<CNetAddr> vIP;
318 if (LookupHost(pszIp, vIP, 1, fAllowLookup))
322 CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
325 std::vector<CNetAddr> vIP;
326 if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
330 int CNetAddr::GetByte(int n) const
335 bool CNetAddr::IsIPv4() const
337 return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
340 bool CNetAddr::IsRFC1918() const
344 (GetByte(3) == 192 && GetByte(2) == 168) ||
345 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
348 bool CNetAddr::IsRFC3927() const
350 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
353 bool CNetAddr::IsRFC3849() const
355 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
358 bool CNetAddr::IsRFC3964() const
360 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
363 bool CNetAddr::IsRFC6052() const
365 static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
366 return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
369 bool CNetAddr::IsRFC4380() const
371 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
374 bool CNetAddr::IsRFC4862() const
376 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
377 return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
380 bool CNetAddr::IsRFC4193() const
382 return ((GetByte(15) & 0xFE) == 0xFC);
385 bool CNetAddr::IsRFC6145() const
387 static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
388 return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
391 bool CNetAddr::IsRFC4843() const
393 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && GetByte(12) & 0xF0 == 0x10);
396 bool CNetAddr::IsLocal() const
399 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
402 // IPv6 loopback (::1/128)
403 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
404 if (memcmp(ip, pchLocal, 16) == 0)
410 bool CNetAddr::IsMulticast() const
412 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
413 || (GetByte(15) == 0xFF);
416 bool CNetAddr::IsValid() const
418 // Clean up 3-byte shifted addresses caused by garbage in size field
419 // of addr messages from versions before 0.2.9 checksum.
420 // Two consecutive addr messages look like this:
421 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
422 // so if the first length field is garbled, it reads the second batch
423 // of addr misaligned by 3 bytes.
424 if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
427 // unspecified IPv6 address (::/128)
428 unsigned char ipNone[16] = {};
429 if (memcmp(ip, ipNone, 16) == 0)
432 // documentation IPv6 address
439 uint32_t ipNone = INADDR_NONE;
440 if (memcmp(ip+12, &ipNone, 4) == 0)
445 if (memcmp(ip+12, &ipNone, 4) == 0)
452 bool CNetAddr::IsRoutable() const
454 return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || IsRFC4193() || IsRFC4843() || IsLocal());
457 std::string CNetAddr::ToStringIP() const
460 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
462 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
463 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
464 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
465 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
466 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
469 std::string CNetAddr::ToString() const
474 bool operator==(const CNetAddr& a, const CNetAddr& b)
476 return (memcmp(a.ip, b.ip, 16) == 0);
479 bool operator!=(const CNetAddr& a, const CNetAddr& b)
481 return (memcmp(a.ip, b.ip, 16) != 0);
484 bool operator<(const CNetAddr& a, const CNetAddr& b)
486 return (memcmp(a.ip, b.ip, 16) < 0);
489 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
493 memcpy(pipv4Addr, ip+12, 4);
498 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
500 memcpy(pipv6Addr, ip, 16);
505 // get canonical identifier of an address' group
506 // no two connections will be attempted to addresses with the same group
507 std::vector<unsigned char> CNetAddr::GetGroup() const
509 std::vector<unsigned char> vchRet;
510 int nClass = 0; // 0=IPv6, 1=IPv4, 255=unroutable
514 // for unroutable addresses, each address is considered different
520 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
521 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
522 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
527 // for 6to4 tunneled addresses, use the encapsulated IPv4 address
528 else if (IsRFC3964())
533 // for Teredo-tunneled IPv6 addresses, use the encapsulated IPv4 address
534 else if (IsRFC4380())
537 vchRet.push_back(GetByte(3) ^ 0xFF);
538 vchRet.push_back(GetByte(2) ^ 0xFF);
541 // for he.net, use /36 groups
542 else if (GetByte(15) == 0x20 && GetByte(14) == 0x11 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
544 // for the rest of the IPv6 network, use /32 groups
548 vchRet.push_back(nClass);
551 vchRet.push_back(GetByte(15 - nStartByte));
556 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
561 int64 CNetAddr::GetHash() const
563 uint256 hash = Hash(&ip[0], &ip[16]);
565 memcpy(&nRet, &hash, sizeof(nRet));
569 void CNetAddr::print() const
571 printf("CNetAddr(%s)\n", ToString().c_str());
574 void CService::Init()
584 CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
588 CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
593 CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
598 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
600 assert(addr.sin_family == AF_INET);
604 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
606 assert(addr.sin6_family == AF_INET6);
610 CService::CService(const char *pszIpPort, bool fAllowLookup)
614 if (Lookup(pszIpPort, ip, 0, fAllowLookup))
618 CService::CService(const char *pszIp, int portIn, bool fAllowLookup)
620 std::vector<CNetAddr> ip;
621 if (LookupHost(pszIp, ip, 1, fAllowLookup))
622 *this = CService(ip[0], portIn);
625 CService::CService(const std::string &strIpPort, bool fAllowLookup)
629 if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
633 CService::CService(const std::string &strIp, int portIn, bool fAllowLookup)
635 std::vector<CNetAddr> ip;
636 if (LookupHost(strIp.c_str(), ip, 1, fAllowLookup))
637 *this = CService(ip[0], portIn);
640 unsigned short CService::GetPort() const
645 bool operator==(const CService& a, const CService& b)
647 return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
650 bool operator!=(const CService& a, const CService& b)
652 return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
655 bool operator<(const CService& a, const CService& b)
657 return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
660 bool CService::GetSockAddr(struct sockaddr_in* paddr) const
664 memset(paddr, 0, sizeof(struct sockaddr_in));
665 if (!GetInAddr(&paddr->sin_addr))
667 paddr->sin_family = AF_INET;
668 paddr->sin_port = htons(port);
673 bool CService::GetSockAddr6(struct sockaddr_in6* paddr) const
675 memset(paddr, 0, sizeof(struct sockaddr_in6));
676 if (!GetIn6Addr(&paddr->sin6_addr))
678 paddr->sin6_family = AF_INET6;
679 paddr->sin6_port = htons(port);
684 std::vector<unsigned char> CService::GetKey() const
686 std::vector<unsigned char> vKey;
688 memcpy(&vKey[0], ip, 16);
689 vKey[16] = port / 0x100;
690 vKey[17] = port & 0x0FF;
694 std::string CService::ToStringPort() const
696 return strprintf(":%i", port);
699 std::string CService::ToStringIPPort() const
701 return ToStringIP() + ToStringPort();
704 std::string CService::ToString() const
706 return ToStringIPPort();
709 void CService::print() const
711 printf("CService(%s)\n", ToString().c_str());
714 void CService::SetPort(unsigned short portIn)