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, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, int nMaxSolutions)
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, nMaxSolutions, fAllowLookup);
136 vAddr.resize(vIP.size());
137 for (int i = 0; i < vIP.size(); i++)
138 vAddr[i] = CService(vIP[i], port);
142 bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup)
144 std::vector<CService> vService;
145 bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
152 bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
154 return Lookup(pszName, addr, portDefault, false);
157 bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
159 hSocketRet = INVALID_SOCKET;
161 SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
162 if (hSocket == INVALID_SOCKET)
166 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
169 bool fProxy = (fUseProxy && addrDest.IsRoutable());
170 struct sockaddr_in sockaddr;
172 addrProxy.GetSockAddr(&sockaddr);
174 addrDest.GetSockAddr(&sockaddr);
177 u_long fNonblock = 1;
178 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
180 int fFlags = fcntl(hSocket, F_GETFL, 0);
181 if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
184 closesocket(hSocket);
189 if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)
191 // WSAEINVAL is here because some legacy version of winsock uses it
192 if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
194 struct timeval timeout;
195 timeout.tv_sec = nTimeout / 1000;
196 timeout.tv_usec = (nTimeout % 1000) * 1000;
200 FD_SET(hSocket, &fdset);
201 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
204 printf("connection timeout\n");
205 closesocket(hSocket);
208 if (nRet == SOCKET_ERROR)
210 printf("select() for connection failed: %i\n",WSAGetLastError());
211 closesocket(hSocket);
214 socklen_t nRetSize = sizeof(nRet);
216 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
218 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
221 printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
222 closesocket(hSocket);
227 printf("connect() failed after select(): %s\n",strerror(nRet));
228 closesocket(hSocket);
233 else if (WSAGetLastError() != WSAEISCONN)
238 printf("connect() failed: %i\n",WSAGetLastError());
239 closesocket(hSocket);
244 // this isn't even strictly necessary
245 // CNode::ConnectNode immediately turns the socket back to non-blocking
246 // but we'll turn it back to blocking just in case
249 if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
251 fFlags = fcntl(hSocket, F_GETFL, 0);
252 if (fcntl(hSocket, F_SETFL, fFlags & !O_NONBLOCK) == SOCKET_ERROR)
255 closesocket(hSocket);
261 printf("proxy connecting %s\n", addrDest.ToString().c_str());
262 char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
263 struct sockaddr_in addr;
264 addrDest.GetSockAddr(&addr);
265 memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
266 memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
267 char* pszSocks4 = pszSocks4IP;
268 int nSize = sizeof(pszSocks4IP);
270 int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
273 closesocket(hSocket);
274 return error("Error sending to proxy");
277 if (recv(hSocket, pchRet, 8, 0) != 8)
279 closesocket(hSocket);
280 return error("Error reading proxy response");
282 if (pchRet[1] != 0x5a)
284 closesocket(hSocket);
285 if (pchRet[1] != 0x5b)
286 printf("ERROR: Proxy returned error %d\n", pchRet[1]);
289 printf("proxy connected %s\n", addrDest.ToString().c_str());
292 hSocketRet = hSocket;
296 void CNetAddr::Init()
301 void CNetAddr::SetIP(const CNetAddr& ipIn)
303 memcpy(ip, ipIn.ip, sizeof(ip));
311 CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
313 memcpy(ip, pchIPv4, 12);
314 memcpy(ip+12, &ipv4Addr, 4);
318 CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
320 memcpy(ip, &ipv6Addr, 16);
324 CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
327 std::vector<CNetAddr> vIP;
328 if (LookupHost(pszIp, vIP, 1, fAllowLookup))
332 CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
335 std::vector<CNetAddr> vIP;
336 if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
340 int CNetAddr::GetByte(int n) const
345 bool CNetAddr::IsIPv4() const
347 return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
350 bool CNetAddr::IsRFC1918() const
354 (GetByte(3) == 192 && GetByte(2) == 168) ||
355 (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
358 bool CNetAddr::IsRFC3927() const
360 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
363 bool CNetAddr::IsRFC3849() const
365 return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
368 bool CNetAddr::IsRFC3964() const
370 return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
373 bool CNetAddr::IsRFC6052() const
375 static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
376 return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
379 bool CNetAddr::IsRFC4380() const
381 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
384 bool CNetAddr::IsRFC4862() const
386 static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
387 return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
390 bool CNetAddr::IsRFC4193() const
392 return ((GetByte(15) & 0xFE) == 0xFC);
395 bool CNetAddr::IsRFC6145() const
397 static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
398 return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
401 bool CNetAddr::IsRFC4843() const
403 return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && GetByte(12) & 0xF0 == 0x10);
406 bool CNetAddr::IsLocal() const
409 if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
412 // IPv6 loopback (::1/128)
413 static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
414 if (memcmp(ip, pchLocal, 16) == 0)
420 bool CNetAddr::IsMulticast() const
422 return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
423 || (GetByte(15) == 0xFF);
426 bool CNetAddr::IsValid() const
428 // Clean up 3-byte shifted addresses caused by garbage in size field
429 // of addr messages from versions before 0.2.9 checksum.
430 // Two consecutive addr messages look like this:
431 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
432 // so if the first length field is garbled, it reads the second batch
433 // of addr misaligned by 3 bytes.
434 if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
437 // unspecified IPv6 address (::/128)
438 unsigned char ipNone[16] = {};
439 if (memcmp(ip, ipNone, 16) == 0)
442 // documentation IPv6 address
449 uint32_t ipNone = INADDR_NONE;
450 if (memcmp(ip+12, &ipNone, 4) == 0)
455 if (memcmp(ip+12, &ipNone, 4) == 0)
462 bool CNetAddr::IsRoutable() const
464 return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || IsRFC4193() || IsRFC4843() || IsLocal());
467 std::string CNetAddr::ToStringIP() const
470 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
472 return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
473 GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
474 GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
475 GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
476 GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
479 std::string CNetAddr::ToString() const
484 bool operator==(const CNetAddr& a, const CNetAddr& b)
486 return (memcmp(a.ip, b.ip, 16) == 0);
489 bool operator!=(const CNetAddr& a, const CNetAddr& b)
491 return (memcmp(a.ip, b.ip, 16) != 0);
494 bool operator<(const CNetAddr& a, const CNetAddr& b)
496 return (memcmp(a.ip, b.ip, 16) < 0);
499 bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
503 memcpy(pipv4Addr, ip+12, 4);
508 bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
510 memcpy(pipv6Addr, ip, 16);
515 // get canonical identifier of an address' group
516 // no two connections will be attempted to addresses with the same group
517 std::vector<unsigned char> CNetAddr::GetGroup() const
519 std::vector<unsigned char> vchRet;
520 int nClass = 0; // 0=IPv6, 1=IPv4, 255=unroutable
524 // for unroutable addresses, each address is considered different
530 // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
531 // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
532 else if (IsIPv4() || IsRFC6145() || IsRFC6052())
537 // for 6to4 tunneled addresses, use the encapsulated IPv4 address
538 else if (IsRFC3964())
543 // for Teredo-tunneled IPv6 addresses, use the encapsulated IPv4 address
544 else if (IsRFC4380())
547 vchRet.push_back(GetByte(3) ^ 0xFF);
548 vchRet.push_back(GetByte(2) ^ 0xFF);
551 // for he.net, use /36 groups
552 else if (GetByte(15) == 0x20 && GetByte(14) == 0x11 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
554 // for the rest of the IPv6 network, use /32 groups
558 vchRet.push_back(nClass);
561 vchRet.push_back(GetByte(15 - nStartByte));
566 vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
571 int64 CNetAddr::GetHash() const
573 uint256 hash = Hash(&ip[0], &ip[16]);
575 memcpy(&nRet, &hash, sizeof(nRet));
579 void CNetAddr::print() const
581 printf("CNetAddr(%s)\n", ToString().c_str());
584 void CService::Init()
594 CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
598 CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
603 CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
608 CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
610 assert(addr.sin_family == AF_INET);
614 CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
616 assert(addr.sin6_family == AF_INET6);
620 CService::CService(const char *pszIpPort, bool fAllowLookup)
624 if (Lookup(pszIpPort, ip, 0, fAllowLookup))
628 CService::CService(const char *pszIp, int portIn, bool fAllowLookup)
630 std::vector<CNetAddr> ip;
631 if (LookupHost(pszIp, ip, 1, fAllowLookup))
632 *this = CService(ip[0], portIn);
635 CService::CService(const std::string &strIpPort, bool fAllowLookup)
639 if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
643 CService::CService(const std::string &strIp, int portIn, bool fAllowLookup)
645 std::vector<CNetAddr> ip;
646 if (LookupHost(strIp.c_str(), ip, 1, fAllowLookup))
647 *this = CService(ip[0], portIn);
650 unsigned short CService::GetPort() const
655 bool operator==(const CService& a, const CService& b)
657 return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
660 bool operator!=(const CService& a, const CService& b)
662 return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
665 bool operator<(const CService& a, const CService& b)
667 return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
670 bool CService::GetSockAddr(struct sockaddr_in* paddr) const
674 memset(paddr, 0, sizeof(struct sockaddr_in));
675 if (!GetInAddr(&paddr->sin_addr))
677 paddr->sin_family = AF_INET;
678 paddr->sin_port = htons(port);
683 bool CService::GetSockAddr6(struct sockaddr_in6* paddr) const
685 memset(paddr, 0, sizeof(struct sockaddr_in6));
686 if (!GetIn6Addr(&paddr->sin6_addr))
688 paddr->sin6_family = AF_INET6;
689 paddr->sin6_port = htons(port);
694 std::vector<unsigned char> CService::GetKey() const
696 std::vector<unsigned char> vKey;
698 memcpy(&vKey[0], ip, 16);
699 vKey[16] = port / 0x100;
700 vKey[17] = port & 0x0FF;
704 std::string CService::ToStringPort() const
706 return strprintf(":%i", port);
709 std::string CService::ToStringIPPort() const
711 return ToStringIP() + ToStringPort();
714 std::string CService::ToString() const
716 return ToStringIPPort();
719 void CService::print() const
721 printf("CService(%s)\n", ToString().c_str());
724 void CService::SetPort(unsigned short portIn)