From 60a87bce873ce1f76a80b7b8546e83a0cd4e07a5 Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Sun, 1 Apr 2012 20:25:48 +0200 Subject: [PATCH 1/7] SOCKS5 support by default Add -socks= to select SOCKS version to use. 4 and 5 are supported, 5 is default. --- src/init.cpp | 3 +- src/netbase.cpp | 195 +++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 169 insertions(+), 29 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 3fe6d1b09..aa1399f81 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -178,7 +178,8 @@ bool AppInit2(int argc, char* argv[]) " -dbcache= \t\t " + _("Set database cache size in megabytes (default: 25)") + "\n" + " -dblogsize= \t\t " + _("Set database disk log size in megabytes (default: 100)") + "\n" + " -timeout= \t " + _("Specify connection timeout (in milliseconds)") + "\n" + - " -proxy= \t " + _("Connect through socks4 proxy") + "\n" + + " -proxy= \t " + _("Connect through socks proxy") + "\n" + + " -socks= \t " + _("Select the version of socks proxy to use (4 or 5, 5 is default)") + "\n" + " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" + " -port= \t\t " + _("Listen for connections on (default: 8333 or testnet: 18333)") + "\n" + " -maxconnections=\t " + _("Maintain at most connections to peers (default: 125)") + "\n" + diff --git a/src/netbase.cpp b/src/netbase.cpp index 8b30ffc14..3c818f76f 100644 --- a/src/netbase.cpp +++ b/src/netbase.cpp @@ -156,6 +156,161 @@ bool LookupNumeric(const char *pszName, CService& addr, int portDefault) return Lookup(pszName, addr, portDefault, false); } +bool static Socks4(const CService &addrDest, SOCKET& hSocket) +{ + printf("SOCKS4 connecting %s\n", addrDest.ToString().c_str()); + if (!addrDest.IsIPv4()) + { + closesocket(hSocket); + return error("Proxy destination is not IPv4"); + } + char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user"; + struct sockaddr_in addr; + addrDest.GetSockAddr(&addr); + memcpy(pszSocks4IP + 2, &addr.sin_port, 2); + memcpy(pszSocks4IP + 4, &addr.sin_addr, 4); + char* pszSocks4 = pszSocks4IP; + int nSize = sizeof(pszSocks4IP); + + int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL); + if (ret != nSize) + { + closesocket(hSocket); + return error("Error sending to proxy"); + } + char pchRet[8]; + if (recv(hSocket, pchRet, 8, 0) != 8) + { + closesocket(hSocket); + return error("Error reading proxy response"); + } + if (pchRet[1] != 0x5a) + { + closesocket(hSocket); + if (pchRet[1] != 0x5b) + printf("ERROR: Proxy returned error %d\n", pchRet[1]); + return false; + } + printf("SOCKS4 connected %s\n", addrDest.ToString().c_str()); + return true; +} + +bool static Socks5(const CService &addrDest, SOCKET& hSocket) +{ + printf("SOCKS5 connecting %s\n", addrDest.ToString().c_str()); + char pszSocks5Init[] = "\5\1\0"; + char *pszSocks5 = pszSocks5Init; + int nSize = sizeof(pszSocks5Init); + + int ret = send(hSocket, pszSocks5, nSize, MSG_NOSIGNAL); + if (ret != nSize) + { + closesocket(hSocket); + return error("Error sending to proxy"); + } + char pchRet1[2]; + if (recv(hSocket, pchRet1, 2, 0) != 2) + { + closesocket(hSocket); + return error("Error reading proxy response"); + } + if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00) + { + closesocket(hSocket); + return error("Proxy failed to initialize"); + } + char pszSocks5IPv4[] = "\5\1\0\1\0\0\0\0\0\0"; + char pszSocks5IPv6[] = "\5\1\0\4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; + if (addrDest.IsIPv4()) + { + struct sockaddr_in addr; + addrDest.GetSockAddr(&addr); + memcpy(pszSocks5IPv4 + 4, &addr.sin_addr, 4); + memcpy(pszSocks5IPv4 + 8, &addr.sin_port, 2); + pszSocks5 = pszSocks5IPv4; + nSize = sizeof(pszSocks5IPv4); + } + else + { +#ifdef USE_IPV6 + struct sockaddr_in6 addr; + addrDest.GetSockAddr6(&addr); + memcpy(pszSocks5IPv6 + 4, &addr.sin6_addr, 16); + memcpy(pszSocks5IPv6 + 20, &addr.sin6_port, 2); + pszSocks5 = pszSocks5IPv6; + nSize = sizeof(pszSocks5IPv6); +#else + return error("IPv6 support is not compiled in"); +#endif + } + ret = send(hSocket, pszSocks5, nSize, MSG_NOSIGNAL); + if (ret != nSize) + { + closesocket(hSocket); + return error("Error sending to proxy"); + } + char pchRet2[4]; + if (recv(hSocket, pchRet2, 4, 0) != 4) + { + closesocket(hSocket); + return error("Error reading proxy response"); + } + if (pchRet2[0] != 0x05) + { + closesocket(hSocket); + return error("Proxy failed to accept request"); + } + if (pchRet2[1] != 0x00) + { + closesocket(hSocket); + switch (pchRet2[1]) + { + case 0x01: return error("Proxy error: general failure"); + case 0x02: return error("Proxy error: connection not allowed"); + case 0x03: return error("Proxy error: network unreachable"); + case 0x04: return error("Proxy error: host unreachable"); + case 0x05: return error("Proxy error: connection refused"); + case 0x06: return error("Proxy error: TTL expired"); + case 0x07: return error("Proxy error: protocol error"); + case 0x08: return error("Proxy error: address type not supported"); + default: return error("Proxy error: unknown"); + } + } + if (pchRet2[2] != 0x00) + { + closesocket(hSocket); + return error("Error: malformed proxy response"); + } + char pchRet3[256]; + switch (pchRet2[3]) + { + case 0x01: ret = recv(hSocket, pchRet3, 4, 0) != 4; break; + case 0x04: ret = recv(hSocket, pchRet3, 16, 0) != 16; break; + case 0x03: + { + ret = recv(hSocket, pchRet3, 1, 0) != 1; + if (ret) + return error("Error reading from proxy"); + int nRecv = pchRet3[0]; + ret = recv(hSocket, pchRet3, nRecv, 0) != nRecv; + break; + } + default: closesocket(hSocket); return error("Error: malformed proxy response"); + } + if (ret) + { + closesocket(hSocket); + return error("Error reading from proxy"); + } + if (recv(hSocket, pchRet3, 2, 0) != 2) + { + closesocket(hSocket); + return error("Error reading from proxy"); + } + printf("SOCKS5 connected %s\n", addrDest.ToString().c_str()); + return true; +} + bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout) { hSocketRet = INVALID_SOCKET; @@ -260,35 +415,19 @@ bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout) if (fProxy) { - printf("proxy connecting %s\n", addrDest.ToString().c_str()); - char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user"; - struct sockaddr_in addr; - addrDest.GetSockAddr(&addr); - memcpy(pszSocks4IP + 2, &addr.sin_port, 2); - memcpy(pszSocks4IP + 4, &addr.sin_addr, 4); - char* pszSocks4 = pszSocks4IP; - int nSize = sizeof(pszSocks4IP); + switch(GetArg("-socks", 5)) + { + case 4: + if (!Socks4(addrDest, hSocket)) + return false; + break; - int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL); - if (ret != nSize) - { - closesocket(hSocket); - return error("Error sending to proxy"); - } - char pchRet[8]; - if (recv(hSocket, pchRet, 8, 0) != 8) - { - closesocket(hSocket); - return error("Error reading proxy response"); - } - if (pchRet[1] != 0x5a) - { - closesocket(hSocket); - if (pchRet[1] != 0x5b) - printf("ERROR: Proxy returned error %d\n", pchRet[1]); - return false; - } - printf("proxy connected %s\n", addrDest.ToString().c_str()); + case 5: + default: + if (!Socks5(addrDest, hSocket)) + return false; + break; + } } hSocketRet = hSocket; From 933f2715d8ff9548cdf90cd3cdec3bda79b898c2 Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Thu, 19 Apr 2012 16:13:30 +0200 Subject: [PATCH 2/7] SOCKS5 connect via hostname --- src/netbase.cpp | 35 +++++++++-------------------------- 1 file changed, 9 insertions(+), 26 deletions(-) diff --git a/src/netbase.cpp b/src/netbase.cpp index 3c818f76f..2c131947b 100644 --- a/src/netbase.cpp +++ b/src/netbase.cpp @@ -219,32 +219,15 @@ bool static Socks5(const CService &addrDest, SOCKET& hSocket) closesocket(hSocket); return error("Proxy failed to initialize"); } - char pszSocks5IPv4[] = "\5\1\0\1\0\0\0\0\0\0"; - char pszSocks5IPv6[] = "\5\1\0\4\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; - if (addrDest.IsIPv4()) - { - struct sockaddr_in addr; - addrDest.GetSockAddr(&addr); - memcpy(pszSocks5IPv4 + 4, &addr.sin_addr, 4); - memcpy(pszSocks5IPv4 + 8, &addr.sin_port, 2); - pszSocks5 = pszSocks5IPv4; - nSize = sizeof(pszSocks5IPv4); - } - else - { -#ifdef USE_IPV6 - struct sockaddr_in6 addr; - addrDest.GetSockAddr6(&addr); - memcpy(pszSocks5IPv6 + 4, &addr.sin6_addr, 16); - memcpy(pszSocks5IPv6 + 20, &addr.sin6_port, 2); - pszSocks5 = pszSocks5IPv6; - nSize = sizeof(pszSocks5IPv6); -#else - return error("IPv6 support is not compiled in"); -#endif - } - ret = send(hSocket, pszSocks5, nSize, MSG_NOSIGNAL); - if (ret != nSize) + string strSocks5("\5\1"); + strSocks5 += '\000'; strSocks5 += '\003'; + string strDest = addrDest.ToStringIP(); + strSocks5 += static_cast(std::min((int)strDest.size(), 255)); + strSocks5 += strDest; + strSocks5 += static_cast((addrDest.GetPort() >> 8) & 0xFF); + strSocks5 += static_cast((addrDest.GetPort() >> 0) & 0xFF); + ret = send(hSocket, strSocks5.c_str(), strSocks5.size(), MSG_NOSIGNAL); + if (ret != strSocks5.size()) { closesocket(hSocket); return error("Error sending to proxy"); From a012e2db59585bfa1978615aacade281053e0ae5 Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Thu, 19 Apr 2012 17:02:21 +0200 Subject: [PATCH 3/7] refactor ConnectSocket --- src/netbase.cpp | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/src/netbase.cpp b/src/netbase.cpp index 2c131947b..60f34bbd3 100644 --- a/src/netbase.cpp +++ b/src/netbase.cpp @@ -195,9 +195,14 @@ bool static Socks4(const CService &addrDest, SOCKET& hSocket) return true; } -bool static Socks5(const CService &addrDest, SOCKET& hSocket) +bool static Socks5(string strDest, int port, SOCKET& hSocket) { - printf("SOCKS5 connecting %s\n", addrDest.ToString().c_str()); + printf("SOCKS5 connecting %s\n", strDest.c_str()); + if (strDest.size() > 255) + { + closesocket(hSocket); + return error("Hostname too long"); + } char pszSocks5Init[] = "\5\1\0"; char *pszSocks5 = pszSocks5Init; int nSize = sizeof(pszSocks5Init); @@ -221,11 +226,10 @@ bool static Socks5(const CService &addrDest, SOCKET& hSocket) } string strSocks5("\5\1"); strSocks5 += '\000'; strSocks5 += '\003'; - string strDest = addrDest.ToStringIP(); strSocks5 += static_cast(std::min((int)strDest.size(), 255)); - strSocks5 += strDest; - strSocks5 += static_cast((addrDest.GetPort() >> 8) & 0xFF); - strSocks5 += static_cast((addrDest.GetPort() >> 0) & 0xFF); + strSocks5 += strDest; + strSocks5 += static_cast((port >> 8) & 0xFF); + strSocks5 += static_cast((port >> 0) & 0xFF); ret = send(hSocket, strSocks5.c_str(), strSocks5.size(), MSG_NOSIGNAL); if (ret != strSocks5.size()) { @@ -290,11 +294,11 @@ bool static Socks5(const CService &addrDest, SOCKET& hSocket) closesocket(hSocket); return error("Error reading from proxy"); } - printf("SOCKS5 connected %s\n", addrDest.ToString().c_str()); + printf("SOCKS5 connected %s\n", strDest.c_str()); return true; } -bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout) +bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout) { hSocketRet = INVALID_SOCKET; @@ -396,6 +400,18 @@ bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout) return false; } + hSocketRet = hSocket; + return true; +} + +bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout) +{ + SOCKET hSocket = INVALID_SOCKET; + bool fProxy = (fUseProxy && addrDest.IsRoutable()); + + if (!ConnectSocketDirectly(fProxy ? addrProxy : addrDest, hSocket, nTimeout)) + return false; + if (fProxy) { switch(GetArg("-socks", 5)) @@ -407,7 +423,7 @@ bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout) case 5: default: - if (!Socks5(addrDest, hSocket)) + if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket)) return false; break; } From 9bab521df895c149579b9e64931405c56b008afb Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Thu, 19 Apr 2012 17:38:03 +0200 Subject: [PATCH 4/7] Support connecting by hostnames passed to proxy (-proxydns) --- src/init.cpp | 21 +++----- src/net.cpp | 124 ++++++++++++++++++++++++++++++------------------ src/net.h | 7 +-- src/netbase.cpp | 58 +++++++++++++++++++--- src/netbase.h | 4 ++ 5 files changed, 145 insertions(+), 69 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index aa1399f81..35da20336 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -181,6 +181,7 @@ bool AppInit2(int argc, char* argv[]) " -proxy= \t " + _("Connect through socks proxy") + "\n" + " -socks= \t " + _("Select the version of socks proxy to use (4 or 5, 5 is default)") + "\n" + " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" + + " -proxydns \t " + _("Pass DNS requests to (SOCKS5) proxy") + "\n" + " -port= \t\t " + _("Listen for connections on (default: 8333 or testnet: 18333)") + "\n" + " -maxconnections=\t " + _("Maintain at most connections to peers (default: 125)") + "\n" + " -addnode= \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" + @@ -524,13 +525,16 @@ bool AppInit2(int argc, char* argv[]) // Note: the GetBoolArg() calls for all of these must happen later. SoftSetBoolArg("-listen", false); SoftSetBoolArg("-irc", false); - SoftSetBoolArg("-dnsseed", false); + SoftSetBoolArg("-proxydns", true); SoftSetBoolArg("-upnp", false); - SoftSetBoolArg("-dns", false); } - fAllowDNS = GetBoolArg("-dns"); + fNameLookup = GetBoolArg("-dns"); + fProxyNameLookup = GetBoolArg("-proxydns"); + if (fProxyNameLookup) + fNameLookup = true; fNoListen = !GetBoolArg("-listen", true); + nSocksVersion = GetArg("-socks", 5); // Continue to put "/P2SH/" in the coinbase to monitor // BIP16 support. @@ -548,17 +552,6 @@ bool AppInit2(int argc, char* argv[]) } } - if (mapArgs.count("-addnode")) - { - BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"]) - { - CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS)); - addr.nTime = 0; // so it won't relay unless successfully connected - if (addr.IsValid()) - addrman.Add(addr, CNetAddr("127.0.0.1")); - } - } - if (mapArgs.count("-paytxfee")) { if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee)) diff --git a/src/net.cpp b/src/net.cpp index 92b4a3173..ca137b70f 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -35,7 +35,7 @@ void ThreadOpenAddedConnections2(void* parg); void ThreadMapPort2(void* parg); #endif void ThreadDNSAddressSeed2(void* parg); -bool OpenNetworkConnection(const CAddress& addrConnect); +bool OpenNetworkConnection(const CAddress& addrConnect, const char *strDest = NULL); @@ -43,7 +43,6 @@ bool OpenNetworkConnection(const CAddress& addrConnect); // Global state variables // bool fClient = false; -bool fAllowDNS = false; static bool fUseUPnP = false; uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK); CAddress addrLocalHost(CService("0.0.0.0", 0), nLocalServices); @@ -307,6 +306,15 @@ CNode* FindNode(const CNetAddr& ip) return NULL; } +CNode* FindNode(std::string addrName) +{ + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + if (pnode->addrName == addrName) + return (pnode); + return NULL; +} + CNode* FindNode(const CService& addr) { { @@ -318,35 +326,38 @@ CNode* FindNode(const CService& addr) return NULL; } -CNode* ConnectNode(CAddress addrConnect, int64 nTimeout) +CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout) { - if ((CNetAddr)addrConnect == (CNetAddr)addrLocalHost) - return NULL; + if (pszDest != NULL) { + if ((CNetAddr)addrConnect == (CNetAddr)addrLocalHost) + return NULL; - // Look for an existing connection - CNode* pnode = FindNode((CService)addrConnect); - if (pnode) - { - if (nTimeout != 0) - pnode->AddRef(nTimeout); - else - pnode->AddRef(); - return pnode; + // Look for an existing connection + CNode* pnode = FindNode((CService)addrConnect); + if (pnode) + { + if (nTimeout != 0) + pnode->AddRef(nTimeout); + else + pnode->AddRef(); + return pnode; + } } + /// debug print printf("trying connection %s lastseen=%.1fhrs\n", - addrConnect.ToString().c_str(), - (double)(addrConnect.nTime - GetAdjustedTime())/3600.0); - - addrman.Attempt(addrConnect); + pszDest ? pszDest : addrConnect.ToString().c_str(), + pszDest ? 0 : (double)(addrConnect.nTime - GetAdjustedTime())/3600.0); // Connect SOCKET hSocket; - if (ConnectSocket(addrConnect, hSocket)) + if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket)) { + addrman.Attempt(addrConnect); + /// debug print - printf("connected %s\n", addrConnect.ToString().c_str()); + printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str()); // Set to nonblocking #ifdef WIN32 @@ -359,11 +370,12 @@ CNode* ConnectNode(CAddress addrConnect, int64 nTimeout) #endif // Add node - CNode* pnode = new CNode(hSocket, addrConnect, false); + CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); if (nTimeout != 0) pnode->AddRef(nTimeout); else pnode->AddRef(); + { LOCK(cs_vNodes); vNodes.push_back(pnode); @@ -389,7 +401,7 @@ void CNode::CloseSocketDisconnect() { if (fDebug) printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str()); - printf("disconnecting node %s\n", addr.ToString().c_str()); + printf("disconnecting node %s\n", addrName.c_str()); closesocket(hSocket); hSocket = INVALID_SOCKET; vRecv.clear(); @@ -444,7 +456,7 @@ bool CNode::Misbehaving(int howmuch) { if (addr.IsLocal()) { - printf("Warning: local node %s misbehaving\n", addr.ToString().c_str()); + printf("Warning: local node %s misbehaving\n", addrName.c_str()); return false; } @@ -458,7 +470,7 @@ bool CNode::Misbehaving(int howmuch) setBanned[addr] = banTime; } CloseSocketDisconnect(); - printf("Disconnected %s for misbehavior (score=%d)\n", addr.ToString().c_str(), nMisbehavior); + printf("Disconnected %s for misbehavior (score=%d)\n", addrName.c_str(), nMisbehavior); return true; } return false; @@ -675,7 +687,7 @@ void ThreadSocketHandler2(void* parg) else { printf("accepted connection %s\n", addr.ToString().c_str()); - CNode* pnode = new CNode(hSocket, addr, true); + CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); { LOCK(cs_vNodes); @@ -1025,20 +1037,25 @@ void ThreadDNSAddressSeed2(void* parg) printf("Loading addresses from DNS seeds (could take a while)\n"); for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) { - vector vaddr; - vector vAdd; - if (LookupHost(strDNSSeed[seed_idx][1], vaddr)) - { - BOOST_FOREACH(CNetAddr& ip, vaddr) + if (fProxyNameLookup) { + CAddress addr; + OpenNetworkConnection(addr, strDNSSeed[seed_idx][1]); + } else { + vector vaddr; + vector vAdd; + if (LookupHost(strDNSSeed[seed_idx][1], vaddr)) { - int nOneDay = 24*3600; - CAddress addr = CAddress(CService(ip, GetDefaultPort())); - addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old - vAdd.push_back(addr); - found++; + BOOST_FOREACH(CNetAddr& ip, vaddr) + { + int nOneDay = 24*3600; + CAddress addr = CAddress(CService(ip, GetDefaultPort())); + addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old + vAdd.push_back(addr); + found++; + } } + addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true)); } - addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true)); } } @@ -1199,9 +1216,8 @@ void ThreadOpenConnections2(void* parg) { BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"]) { - CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS)); - if (addr.IsValid()) - OpenNetworkConnection(addr); + CAddress addr(CService("0.0.0.0:0")); + OpenNetworkConnection(addr, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { Sleep(500); @@ -1325,11 +1341,25 @@ void ThreadOpenAddedConnections2(void* parg) if (mapArgs.count("-addnode") == 0) return; + if (fProxyNameLookup) { + while(!fShutdown) { + BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) { + CAddress addr; + OpenNetworkConnection(addr, strAddNode.c_str()); + Sleep(500); + } + vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; + Sleep(120000); // Retry every 2 minutes + vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++; + } + return; + } + vector > vservAddressesToAdd(0); BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) { vector vservNode(0); - if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fAllowDNS, 0)) + if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0)) { vservAddressesToAdd.push_back(vservNode); { @@ -1343,7 +1373,7 @@ void ThreadOpenAddedConnections2(void* parg) { vector > vservConnectAddresses = vservAddressesToAdd; // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry - // (keeping in mind that addnode entries can have many IPs if fAllowDNS) + // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) @@ -1373,19 +1403,23 @@ void ThreadOpenAddedConnections2(void* parg) } } -bool OpenNetworkConnection(const CAddress& addrConnect) +bool OpenNetworkConnection(const CAddress& addrConnect, const char *strDest) { // // Initiate outbound network connection // if (fShutdown) return false; - if ((CNetAddr)addrConnect == (CNetAddr)addrLocalHost || !addrConnect.IsIPv4() || - FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect)) + if (!strDest) + if ((CNetAddr)addrConnect == (CNetAddr)addrLocalHost || !addrConnect.IsIPv4() || + FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || + FindNode(addrConnect.ToStringIPPort().c_str())) + return false; + if (strDest && FindNode(strDest)) return false; vnThreadsRunning[THREAD_OPENCONNECTIONS]--; - CNode* pnode = ConnectNode(addrConnect); + CNode* pnode = ConnectNode(addrConnect, strDest); vnThreadsRunning[THREAD_OPENCONNECTIONS]++; if (fShutdown) return false; diff --git a/src/net.h b/src/net.h index bad49a9f8..0f48c515b 100644 --- a/src/net.h +++ b/src/net.h @@ -35,7 +35,7 @@ bool GetMyExternalIP(CNetAddr& ipRet); void AddressCurrentlyConnected(const CService& addr); CNode* FindNode(const CNetAddr& ip); CNode* FindNode(const CService& ip); -CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0); +CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, int64 nTimeout=0); void MapPort(bool fMapPort); bool BindListenPort(std::string& strError=REF(std::string())); void StartNode(void* parg); @@ -83,7 +83,6 @@ enum threadId }; extern bool fClient; -extern bool fAllowDNS; extern uint64 nLocalServices; extern CAddress addrLocalHost; extern uint64 nLocalHostNonce; @@ -120,6 +119,7 @@ public: int nHeaderStart; unsigned int nMessageStart; CAddress addr; + std::string addrName; int nVersion; std::string strSubVer; bool fClient; @@ -157,7 +157,7 @@ public: CCriticalSection cs_inventory; std::multimap mapAskFor; - CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION) + CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION) { nServices = 0; hSocket = hSocketIn; @@ -168,6 +168,7 @@ public: nHeaderStart = -1; nMessageStart = -1; addr = addrIn; + addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn; nVersion = 0; strSubVer = ""; fClient = false; // set by version message diff --git a/src/netbase.cpp b/src/netbase.cpp index 60f34bbd3..a9cc0cf4d 100644 --- a/src/netbase.cpp +++ b/src/netbase.cpp @@ -15,7 +15,10 @@ using namespace std; // Settings +int nSocksVersion = 5; int fUseProxy = false; +bool fProxyNameLookup = false; +bool fNameLookup = false; CService addrProxy("127.0.0.1",9050); int nConnectTimeout = 5000; @@ -310,12 +313,12 @@ bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRe setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int)); #endif - bool fProxy = (fUseProxy && addrDest.IsRoutable()); struct sockaddr_in sockaddr; - if (fProxy) - addrProxy.GetSockAddr(&sockaddr); - else - addrDest.GetSockAddr(&sockaddr); + if (!addrConnect.GetSockAddr(&sockaddr)) + { + closesocket(hSocket); + return false; + } #ifdef WIN32 u_long fNonblock = 1; @@ -329,7 +332,6 @@ bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRe return false; } - if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR) { // WSAEINVAL is here because some legacy version of winsock uses it @@ -414,7 +416,7 @@ bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout) if (fProxy) { - switch(GetArg("-socks", 5)) + switch(nSocksVersion) { case 4: if (!Socks4(addrDest, hSocket)) @@ -433,6 +435,48 @@ bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout) return true; } +bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout) +{ + string strDest(pszDest); + int port = portDefault; + + size_t colon = strDest.find_last_of(':'); + char *endp = NULL; + int n = strtol(pszDest + colon + 1, &endp, 10); + if (endp && *endp == 0 && n >= 0) { + strDest = strDest.substr(0, colon); + if (n > 0 && n < 0x10000) + port = n; + } + if (strDest[0] == '[' && strDest[strDest.size()-1] == ']') + strDest = strDest.substr(1, strDest.size()-2); + + SOCKET hSocket = INVALID_SOCKET; + CService addrResolved(CNetAddr(strDest, fNameLookup && !fProxyNameLookup), port); + if (addrResolved.IsValid()) { + addr = addrResolved; + return ConnectSocket(addr, hSocketRet, nTimeout); + } + addr = CService("0.0.0.0:0"); + if (!fNameLookup) + return false; + if (!ConnectSocketDirectly(addrProxy, hSocket, nTimeout)) + return false; + + switch(nSocksVersion) + { + case 4: return false; + case 5: + default: + if (!Socks5(strDest, port, hSocket)) + return false; + break; + } + + hSocketRet = hSocket; + return true; +} + void CNetAddr::Init() { memset(ip, 0, 16); diff --git a/src/netbase.h b/src/netbase.h index 00b6850b2..3d2956906 100644 --- a/src/netbase.h +++ b/src/netbase.h @@ -119,9 +119,13 @@ bool Lookup(const char *pszName, CService& addr, int portDefault = 0, bool fAllo bool Lookup(const char *pszName, std::vector& vAddr, int portDefault = 0, bool fAllowLookup = true, unsigned int nMaxSolutions = 0); bool LookupNumeric(const char *pszName, CService& addr, int portDefault = 0); bool ConnectSocket(const CService &addr, SOCKET& hSocketRet, int nTimeout = nConnectTimeout); +bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault = 0, int nTimeout = nConnectTimeout); // Settings +extern int nSocksVersion; extern int fUseProxy; +extern bool fProxyNameLookup; +extern bool fNameLookup; extern CService addrProxy; #endif From 478b01d9a797f3ea41cca141992b161867a5996d Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Tue, 24 Apr 2012 02:15:00 +0200 Subject: [PATCH 5/7] Add -seednode connections, and use this for -dnsseed + -proxydns --- src/init.cpp | 6 +++++- src/main.cpp | 6 ++++-- src/net.cpp | 39 +++++++++++++++++++++++++++++++++------ src/net.h | 3 +++ 4 files changed, 45 insertions(+), 9 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 35da20336..f9ea998ce 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -180,12 +180,13 @@ bool AppInit2(int argc, char* argv[]) " -timeout= \t " + _("Specify connection timeout (in milliseconds)") + "\n" + " -proxy= \t " + _("Connect through socks proxy") + "\n" + " -socks= \t " + _("Select the version of socks proxy to use (4 or 5, 5 is default)") + "\n" + - " -dns \t " + _("Allow DNS lookups for addnode and connect") + "\n" + + " -dns \t " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" + " -proxydns \t " + _("Pass DNS requests to (SOCKS5) proxy") + "\n" + " -port= \t\t " + _("Listen for connections on (default: 8333 or testnet: 18333)") + "\n" + " -maxconnections=\t " + _("Maintain at most connections to peers (default: 125)") + "\n" + " -addnode= \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" + " -connect= \t\t " + _("Connect only to the specified node") + "\n" + + " -seednode= \t\t " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" + " -irc \t " + _("Find peers using internet relay chat (default: 0)") + "\n" + " -listen \t " + _("Accept connections from outside (default: 1)") + "\n" + #ifdef QT_GUI @@ -536,6 +537,9 @@ bool AppInit2(int argc, char* argv[]) fNoListen = !GetBoolArg("-listen", true); nSocksVersion = GetArg("-socks", 5); + BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"]) + AddOneShot(strDest); + // Continue to put "/P2SH/" in the coinbase to monitor // BIP16 support. // This can be removed eventually... diff --git a/src/main.cpp b/src/main.cpp index 427e435a9..6a3cbe710 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2264,7 +2264,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) } // Get recent addresses - if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) + if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; @@ -2280,7 +2280,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) // Ask the first connected node for block updates static int nAskedForBlocks = 0; - if (!pfrom->fClient && + if (!pfrom->fClient && !pfrom->fOneShot && (pfrom->nVersion < NOBLKS_VERSION_START || pfrom->nVersion >= NOBLKS_VERSION_END) && (nAskedForBlocks < 1 || vNodes.size() <= 1)) @@ -2378,6 +2378,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; + if (pfrom->fOneShot) + pfrom->fDisconnect = true; } diff --git a/src/net.cpp b/src/net.cpp index ca137b70f..048320696 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -35,7 +35,7 @@ void ThreadOpenAddedConnections2(void* parg); void ThreadMapPort2(void* parg); #endif void ThreadDNSAddressSeed2(void* parg); -bool OpenNetworkConnection(const CAddress& addrConnect, const char *strDest = NULL); +bool OpenNetworkConnection(const CAddress& addrConnect, const char *strDest = NULL, bool fOneShot = false); @@ -59,6 +59,8 @@ deque > vRelayExpiration; CCriticalSection cs_mapRelay; map mapAlreadyAskedFor; +static deque vOneShots; +CCriticalSection cs_vOneShots; set setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; @@ -68,6 +70,12 @@ static int nOutbound = 0; static CConditionVariable condOutbound; +void AddOneShot(string strDest) +{ + LOCK(cs_vOneShots); + vOneShots.push_back(strDest); +} + unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", GetDefaultPort())); @@ -328,7 +336,7 @@ CNode* FindNode(const CService& addr) CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout) { - if (pszDest != NULL) { + if (pszDest == NULL) { if ((CNetAddr)addrConnect == (CNetAddr)addrLocalHost) return NULL; @@ -1038,8 +1046,7 @@ void ThreadDNSAddressSeed2(void* parg) for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) { if (fProxyNameLookup) { - CAddress addr; - OpenNetworkConnection(addr, strDNSSeed[seed_idx][1]); + AddOneShot(strDNSSeed[seed_idx][1]); } else { vector vaddr; vector vAdd; @@ -1205,6 +1212,21 @@ void ThreadOpenConnections(void* parg) printf("ThreadOpenConnections exiting\n"); } +void static ProcessOneShot() +{ + string strDest; + { + LOCK(cs_vOneShots); + if (vOneShots.empty()) + return; + strDest = vOneShots.front(); + vOneShots.pop_front(); + } + CAddress addr; + if (!OpenNetworkConnection(addr, strDest.c_str(), true)) + AddOneShot(strDest); +} + void ThreadOpenConnections2(void* parg) { printf("ThreadOpenConnections started\n"); @@ -1214,9 +1236,10 @@ void ThreadOpenConnections2(void* parg) { for (int64 nLoop = 0;; nLoop++) { + ProcessOneShot(); BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"]) { - CAddress addr(CService("0.0.0.0:0")); + CAddress addr; OpenNetworkConnection(addr, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { @@ -1232,6 +1255,8 @@ void ThreadOpenConnections2(void* parg) int64 nStart = GetTime(); loop { + ProcessOneShot(); + vnThreadsRunning[THREAD_OPENCONNECTIONS]--; Sleep(500); vnThreadsRunning[THREAD_OPENCONNECTIONS]++; @@ -1403,7 +1428,7 @@ void ThreadOpenAddedConnections2(void* parg) } } -bool OpenNetworkConnection(const CAddress& addrConnect, const char *strDest) +bool OpenNetworkConnection(const CAddress& addrConnect, const char *strDest, bool fOneShot) { // // Initiate outbound network connection @@ -1426,6 +1451,8 @@ bool OpenNetworkConnection(const CAddress& addrConnect, const char *strDest) if (!pnode) return false; pnode->fNetworkNode = true; + if (fOneShot) + pnode->fOneShot = true; return true; } diff --git a/src/net.h b/src/net.h index 0f48c515b..d48512a5d 100644 --- a/src/net.h +++ b/src/net.h @@ -30,6 +30,7 @@ extern int nBestHeight; inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); } inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); } +void AddOneShot(std::string strDest); bool RecvLine(SOCKET hSocket, std::string& strLine); bool GetMyExternalIP(CNetAddr& ipRet); void AddressCurrentlyConnected(const CService& addr); @@ -122,6 +123,7 @@ public: std::string addrName; int nVersion; std::string strSubVer; + bool fOneShot; bool fClient; bool fInbound; bool fNetworkNode; @@ -171,6 +173,7 @@ public: addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn; nVersion = 0; strSubVer = ""; + fOneShot = false; fClient = false; // set by version message fInbound = fInboundIn; fNetworkNode = false; From 39857190dee3ed296112cfcfd79b0a375143b6c6 Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Sun, 12 Feb 2012 13:45:24 +0100 Subject: [PATCH 6/7] Support for multiple local addresses --- src/irc.cpp | 13 ++- src/irc.h | 1 - src/main.cpp | 23 +++-- src/net.cpp | 189 +++++++++++++++++++++++++++-------------- src/net.h | 17 +++- src/netbase.cpp | 23 +++++ src/netbase.h | 1 + src/test/DoS_tests.cpp | 8 +- 8 files changed, 187 insertions(+), 88 deletions(-) diff --git a/src/irc.cpp b/src/irc.cpp index 237497055..f20152495 100644 --- a/src/irc.cpp +++ b/src/irc.cpp @@ -12,7 +12,6 @@ using namespace std; using namespace boost; int nGotIRCAddresses = 0; -bool fGotExternalIP = false; void ThreadIRCSeed2(void* parg); @@ -216,7 +215,6 @@ void ThreadIRCSeed2(void* parg) printf("ThreadIRCSeed started\n"); int nErrorWait = 10; int nRetryWait = 10; - bool fNameInUse = false; while (!fShutdown) { @@ -248,9 +246,10 @@ void ThreadIRCSeed2(void* parg) return; } + CNetAddr addrLocal; string strMyName; - if (addrLocalHost.IsRoutable() && !fUseProxy && !fNameInUse) - strMyName = EncodeAddress(addrLocalHost); + if (GetLocal(addrLocal, &addrConnect)) + strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); else strMyName = strprintf("x%u", GetRand(1000000000)); @@ -265,7 +264,6 @@ void ThreadIRCSeed2(void* parg) if (nRet == 2) { printf("IRC name already in use\n"); - fNameInUse = true; Wait(10); continue; } @@ -285,9 +283,8 @@ void ThreadIRCSeed2(void* parg) if (!fUseProxy && addrFromIRC.IsRoutable()) { // IRC lets you to re-nick - fGotExternalIP = true; - addrLocalHost.SetIP(addrFromIRC); - strMyName = EncodeAddress(addrLocalHost); + AddLocal(addrFromIRC, LOCAL_IRC); + strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); } } diff --git a/src/irc.h b/src/irc.h index 08d62b83d..a6073199e 100644 --- a/src/irc.h +++ b/src/irc.h @@ -8,6 +8,5 @@ void ThreadIRCSeed(void* parg); extern int nGotIRCAddresses; -extern bool fGotExternalIP; #endif diff --git a/src/main.cpp b/src/main.cpp index 6a3cbe710..b5d8f8f27 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2232,6 +2232,12 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; + if (pfrom->fInbound && addrMe.IsRoutable()) + { + pfrom->addrLocal = addrMe; + SeenLocal(addrMe); + } + // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { @@ -2255,12 +2261,11 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) if (!pfrom->fInbound) { // Advertise our address - if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() && - !IsInitialBlockDownload()) + if (!fNoListen && !fUseProxy && !IsInitialBlockDownload()) { - CAddress addr(addrLocalHost); - addr.nTime = GetAdjustedTime(); - pfrom->PushAddress(addr); + CAddress addr = GetLocalAddress(&pfrom->addr); + if (addr.IsRoutable()) + pfrom->PushAddress(addr); } // Get recent addresses @@ -2889,11 +2894,11 @@ bool SendMessages(CNode* pto, bool fSendTrickle) pnode->setAddrKnown.clear(); // Rebroadcast our address - if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable()) + if (!fNoListen && !fUseProxy) { - CAddress addr(addrLocalHost); - addr.nTime = GetAdjustedTime(); - pnode->PushAddress(addr); + CAddress addr = GetLocalAddress(&pnode->addr); + if (addr.IsRoutable()) + pnode->PushAddress(addr); } } } diff --git a/src/net.cpp b/src/net.cpp index 048320696..0a78bc445 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -45,7 +45,8 @@ bool OpenNetworkConnection(const CAddress& addrConnect, const char *strDest = NU bool fClient = false; static bool fUseUPnP = false; uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK); -CAddress addrLocalHost(CService("0.0.0.0", 0), nLocalServices); +CCriticalSection cs_mapLocalHost; +map mapLocalHost; static CNode* pnodeLocalHost = NULL; uint64 nLocalHostNonce = 0; array vnThreadsRunning; @@ -92,7 +93,45 @@ void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd) PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd); } +// find 'best' local address for a particular peer +bool GetLocal(CNetAddr& addr, const CNetAddr *paddrPeer) +{ + if (fUseProxy || mapArgs.count("-connect") || fNoListen) + return false; + int nBestCount = -1; + int nBestReachability = -1; + { + LOCK(cs_mapLocalHost); + for (map::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) + { + int nCount = (*it).second; + int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); + if (nReachability > nBestReachability || (nReachability == nBestReachability && nCount > nBestCount)) + { + addr = (*it).first; + nBestReachability = nReachability; + nBestCount = nCount; + } + } + } + return nBestCount >= 0; +} + +// get best local address for a particular peer as a CAddress +CAddress GetLocalAddress(const CNetAddr *paddrPeer) +{ + CAddress ret(CService("0.0.0.0",0),0); + CNetAddr addr; + if (GetLocal(addr, paddrPeer)) + { + ret.SetIP(addr); + ret.SetPort(GetListenPort()); + ret.nServices = nLocalServices; + ret.nTime = GetAdjustedTime(); + } + return ret; +} bool RecvLine(SOCKET hSocket, string& strLine) { @@ -145,6 +184,64 @@ bool RecvLine(SOCKET hSocket, string& strLine) } } +// used when scores of local addresses may have changed +// pushes better local address to peers +void static AdvertizeLocal() +{ + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + if (pnode->fSuccessfullyConnected) + { + CAddress addrLocal = GetLocalAddress(&pnode->addr); + if (addrLocal.IsRoutable() && (CNetAddr)addrLocal != (CNetAddr)pnode->addrLocal) + { + pnode->PushAddress(addrLocal); + pnode->addrLocal = addrLocal; + } + } + } +} + +// learn a new local address +bool AddLocal(const CNetAddr& addr, int nScore) +{ + if (!addr.IsRoutable()) + return false; + + printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore); + + { + LOCK(cs_mapLocalHost); + mapLocalHost[addr] = std::max(nScore, mapLocalHost[addr]) + (mapLocalHost.count(addr) ? 1 : 0); + } + + AdvertizeLocal(); + + return true; +} + +// vote for a local address +bool SeenLocal(const CNetAddr& addr) +{ + { + LOCK(cs_mapLocalHost); + if (mapLocalHost.count(addr) == 0) + return false; + mapLocalHost[addr]++; + } + + AdvertizeLocal(); + + return true; +} + +// check whether a given address is potentially local +bool IsLocal(const CNetAddr& addr) +{ + LOCK(cs_mapLocalHost); + return mapLocalHost.count(addr) > 0; +} bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet) @@ -258,33 +355,11 @@ bool GetMyExternalIP(CNetAddr& ipRet) void ThreadGetMyExternalIP(void* parg) { - // Wait for IRC to get it first - if (GetBoolArg("-irc", false)) - { - for (int i = 0; i < 2 * 60; i++) - { - Sleep(1000); - if (fGotExternalIP || fShutdown) - return; - } - } - - // Fallback in case IRC fails to get it + CNetAddr addrLocalHost; if (GetMyExternalIP(addrLocalHost)) { printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str()); - if (addrLocalHost.IsRoutable()) - { - // If we already connected to a few before we had our IP, go back and addr them. - // setAddrKnown automatically filters any duplicate sends. - CAddress addr(addrLocalHost); - addr.nTime = GetAdjustedTime(); - { - LOCK(cs_vNodes); - BOOST_FOREACH(CNode* pnode, vNodes) - pnode->PushAddress(addr); - } - } + AddLocal(addrLocalHost, LOCAL_HTTP); } } @@ -337,7 +412,7 @@ CNode* FindNode(const CService& addr) CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout) { if (pszDest == NULL) { - if ((CNetAddr)addrConnect == (CNetAddr)addrLocalHost) + if (IsLocal(addrConnect)) return NULL; // Look for an existing connection @@ -426,7 +501,7 @@ void CNode::PushVersion() /// when NTP implemented, change to just nTime = GetAdjustedTime() int64 nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (fUseProxy ? CAddress(CService("0.0.0.0",0)) : addr); - CAddress addrMe = (fUseProxy || !addrLocalHost.IsRoutable() ? CAddress(CService("0.0.0.0",0)) : addrLocalHost); + CAddress addrMe = GetLocalAddress(&addr); RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector()), nBestHeight); @@ -898,24 +973,19 @@ void ThreadMapPort2(void* parg) r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { - if (!addrLocalHost.IsRoutable()) + char externalIPAddress[40]; + r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); + if(r != UPNPCOMMAND_SUCCESS) + printf("UPnP: GetExternalIPAddress() returned %d\n", r); + else { - char externalIPAddress[40]; - r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); - if(r != UPNPCOMMAND_SUCCESS) - printf("UPnP: GetExternalIPAddress() returned %d\n", r); - else + if(externalIPAddress[0]) { - if(externalIPAddress[0]) - { - printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); - CAddress addrExternalFromUPnP(CService(externalIPAddress, 0), nLocalServices); - if (addrExternalFromUPnP.IsRoutable()) - addrLocalHost = addrExternalFromUPnP; - } - else - printf("UPnP: GetExternalIPAddress failed.\n"); + printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); + AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } + else + printf("UPnP: GetExternalIPAddress failed.\n"); } string strDesc = "Bitcoin " + FormatFullVersion(); @@ -1318,7 +1388,7 @@ void ThreadOpenConnections2(void* parg) CAddress addr = addrman.Select(10 + min(nOutbound,8)*10); // if we selected an invalid address, restart - if (!addr.IsIPv4() || !addr.IsValid() || setConnected.count(addr.GetGroup()) || addr == addrLocalHost) + if (!addr.IsIPv4() || !addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; nTries++; @@ -1436,8 +1506,8 @@ bool OpenNetworkConnection(const CAddress& addrConnect, const char *strDest, boo if (fShutdown) return false; if (!strDest) - if ((CNetAddr)addrConnect == (CNetAddr)addrLocalHost || !addrConnect.IsIPv4() || - FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || + if (IsLocal(addrConnect) || + FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort().c_str())) return false; if (strDest && FindNode(strDest)) @@ -1550,7 +1620,6 @@ bool BindListenPort(string& strError) { strError = ""; int nOne = 1; - addrLocalHost.SetPort(GetListenPort()); #ifdef WIN32 // Initialize Windows Sockets @@ -1649,11 +1718,7 @@ void StartNode(void* parg) { BOOST_FOREACH (const CNetAddr &addr, vaddr) { - if (!addr.IsLocal()) - { - addrLocalHost.SetIP(addr); - break; - } + AddLocal(addr, LOCAL_IF); } } } @@ -1676,32 +1741,26 @@ void StartNode(void* parg) printf("ipv4 %s: %s\n", ifa->ifa_name, pszIP); // Take the first IP that isn't loopback 127.x.x.x - CAddress addr(CService(s4->sin_addr, GetListenPort()), nLocalServices); - if (addr.IsValid() && !addr.IsLocal()) - { - addrLocalHost = addr; - break; - } + CNetAddr addr(s4->sin_addr); + AddLocal(addr, LOCAL_IF); } else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); if (inet_ntop(ifa->ifa_addr->sa_family, (void*)&(s6->sin6_addr), pszIP, sizeof(pszIP)) != NULL) printf("ipv6 %s: %s\n", ifa->ifa_name, pszIP); + +#ifdef USE_IPV6 + CNetAddr addr(s6->sin6_addr); + AddLocal(addr, LOCAL_IF); +#endif } } freeifaddrs(myaddrs); } #endif - printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str()); - if (fUseProxy || mapArgs.count("-connect") || fNoListen) - { - // Proxies can't take incoming connections - addrLocalHost.SetIP(CNetAddr("0.0.0.0")); - printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str()); - } - else + if (!fUseProxy && !mapArgs.count("-connect") && !fNoListen) { CreateThread(ThreadGetMyExternalIP, NULL); } diff --git a/src/net.h b/src/net.h index d48512a5d..239971e2c 100644 --- a/src/net.h +++ b/src/net.h @@ -42,6 +42,21 @@ bool BindListenPort(std::string& strError=REF(std::string())); void StartNode(void* parg); bool StopNode(); +enum +{ + LOCAL_NONE, + LOCAL_IF, + LOCAL_UPNP, + LOCAL_IRC, + LOCAL_HTTP, +}; + +bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE); +bool SeenLocal(const CNetAddr& addr); +bool IsLocal(const CNetAddr& addr); +bool GetLocal(CNetAddr &addr, const CNetAddr *paddrPeer = NULL); +CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL); + enum { MSG_TX = 1, @@ -85,7 +100,6 @@ enum threadId extern bool fClient; extern uint64 nLocalServices; -extern CAddress addrLocalHost; extern uint64 nLocalHostNonce; extern boost::array vnThreadsRunning; extern CAddrMan addrman; @@ -121,6 +135,7 @@ public: unsigned int nMessageStart; CAddress addr; std::string addrName; + CNetAddr addrLocal; int nVersion; std::string strSubVer; bool fOneShot; diff --git a/src/netbase.cpp b/src/netbase.cpp index a9cc0cf4d..4fe3fb61d 100644 --- a/src/netbase.cpp +++ b/src/netbase.cpp @@ -772,6 +772,29 @@ void CNetAddr::print() const printf("CNetAddr(%s)\n", ToString().c_str()); } +// for IPv6 partners: for unknown/Teredo partners: for IPv4 partners: +// 0 - unroutable // 0 - unroutable // 0 - unroutable +// 1 - teredo // 1 - teredo // 1 - ipv4 +// 2 - tunneled ipv6 // 2 - tunneled ipv6 +// 3 - ipv4 // 3 - ipv6 +// 4 - ipv6 // 4 - ipv4 +int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const +{ + if (!IsValid() || !IsRoutable()) + return 0; + if (paddrPartner && paddrPartner->IsIPv4()) + return IsIPv4() ? 1 : 0; + if (IsRFC4380()) + return 1; + if (IsRFC3964() || IsRFC6052()) + return 2; + bool fRealIPv6 = paddrPartner && !paddrPartner->IsRFC4380() && paddrPartner->IsValid() && paddrPartner->IsRoutable(); + if (fRealIPv6) + return IsIPv4() ? 3 : 4; + else + return IsIPv4() ? 4 : 3; +} + void CService::Init() { port = 0; diff --git a/src/netbase.h b/src/netbase.h index 3d2956906..e5c466e4f 100644 --- a/src/netbase.h +++ b/src/netbase.h @@ -51,6 +51,7 @@ class CNetAddr int64 GetHash() const; bool GetInAddr(struct in_addr* pipv4Addr) const; std::vector GetGroup() const; + int GetReachabilityFrom(const CNetAddr *paddrPartner = NULL) const; void print() const; #ifdef USE_IPV6 diff --git a/src/test/DoS_tests.cpp b/src/test/DoS_tests.cpp index e5a8b4f68..04e2a95d7 100644 --- a/src/test/DoS_tests.cpp +++ b/src/test/DoS_tests.cpp @@ -31,13 +31,13 @@ BOOST_AUTO_TEST_CASE(DoS_banning) { CNode::ClearBanned(); CAddress addr1(ip(0xa0b0c001)); - CNode dummyNode1(INVALID_SOCKET, addr1, true); + CNode dummyNode1(INVALID_SOCKET, addr1, "", true); dummyNode1.Misbehaving(100); // Should get banned BOOST_CHECK(CNode::IsBanned(addr1)); BOOST_CHECK(!CNode::IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different ip, not banned CAddress addr2(ip(0xa0b0c002)); - CNode dummyNode2(INVALID_SOCKET, addr2, true); + CNode dummyNode2(INVALID_SOCKET, addr2, "", true); dummyNode2.Misbehaving(50); BOOST_CHECK(!CNode::IsBanned(addr2)); // 2 not banned yet... BOOST_CHECK(CNode::IsBanned(addr1)); // ... but 1 still should be @@ -50,7 +50,7 @@ BOOST_AUTO_TEST_CASE(DoS_banscore) CNode::ClearBanned(); mapArgs["-banscore"] = "111"; // because 11 is my favorite number CAddress addr1(ip(0xa0b0c001)); - CNode dummyNode1(INVALID_SOCKET, addr1, true); + CNode dummyNode1(INVALID_SOCKET, addr1, "", true); dummyNode1.Misbehaving(100); BOOST_CHECK(!CNode::IsBanned(addr1)); dummyNode1.Misbehaving(10); @@ -67,7 +67,7 @@ BOOST_AUTO_TEST_CASE(DoS_bantime) SetMockTime(nStartTime); // Overrides future calls to GetTime() CAddress addr(ip(0xa0b0c001)); - CNode dummyNode(INVALID_SOCKET, addr, true); + CNode dummyNode(INVALID_SOCKET, addr, "", true); dummyNode.Misbehaving(100); BOOST_CHECK(CNode::IsBanned(addr)); From 19b6958cfd5c5207ffe8259ef48ebbd24ca89725 Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Sun, 19 Feb 2012 20:44:35 +0100 Subject: [PATCH 7/7] Added -externalip and -discover -externalip= can be used to explicitly set the public IP address of your node. -discover=0 can be used to disable the automatic public IP discovery system. --- src/init.cpp | 12 +++++++++++ src/net.cpp | 56 +++++++++++++++++++++++++++++++--------------------- src/net.h | 3 +++ 3 files changed, 48 insertions(+), 23 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index f9ea998ce..469642897 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -187,6 +187,8 @@ bool AppInit2(int argc, char* argv[]) " -addnode= \t " + _("Add a node to connect to and attempt to keep the connection open") + "\n" + " -connect= \t\t " + _("Connect only to the specified node") + "\n" + " -seednode= \t\t " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" + + " -externalip= \t " + _("Specify your own public address") + "\n" + + " -discover \t " + _("Try to discover public IP address (default: 1)") + "\n" + " -irc \t " + _("Find peers using internet relay chat (default: 0)") + "\n" + " -listen \t " + _("Accept connections from outside (default: 1)") + "\n" + #ifdef QT_GUI @@ -519,6 +521,9 @@ bool AppInit2(int argc, char* argv[]) } } + if (mapArgs.count("-connect")) + SoftSetBoolArg("-dnsseed", false); + bool fTor = (fUseProxy && addrProxy.GetPort() == 9050); if (fTor) { @@ -528,6 +533,7 @@ bool AppInit2(int argc, char* argv[]) SoftSetBoolArg("-irc", false); SoftSetBoolArg("-proxydns", true); SoftSetBoolArg("-upnp", false); + SoftSetBoolArg("-discover", false); } fNameLookup = GetBoolArg("-dns"); @@ -556,6 +562,12 @@ bool AppInit2(int argc, char* argv[]) } } + if (mapArgs.count("-externalip")) + { + BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) + AddLocal(CNetAddr(strAddr, fNameLookup), LOCAL_MANUAL); + } + if (mapArgs.count("-paytxfee")) { if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee)) diff --git a/src/net.cpp b/src/net.cpp index 0a78bc445..c626e49b1 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -973,19 +973,21 @@ void ThreadMapPort2(void* parg) r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { - char externalIPAddress[40]; - r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); - if(r != UPNPCOMMAND_SUCCESS) - printf("UPnP: GetExternalIPAddress() returned %d\n", r); - else - { - if(externalIPAddress[0]) - { - printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); - AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); - } + if (GetBoolArg("-discover", true)) { + char externalIPAddress[40]; + r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); + if(r != UPNPCOMMAND_SUCCESS) + printf("UPnP: GetExternalIPAddress() returned %d\n", r); else - printf("UPnP: GetExternalIPAddress failed.\n"); + { + if(externalIPAddress[0]) + { + printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); + AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); + } + else + printf("UPnP: GetExternalIPAddress failed.\n"); + } } string strDesc = "Bitcoin " + FormatFullVersion(); @@ -1695,18 +1697,10 @@ bool BindListenPort(string& strError) return true; } -void StartNode(void* parg) +void static Discover() { -#ifdef USE_UPNP -#if USE_UPNP - fUseUPnP = GetBoolArg("-upnp", true); -#else - fUseUPnP = GetBoolArg("-upnp", false); -#endif -#endif - - if (pnodeLocalHost == NULL) - pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); + if (!GetBoolArg("-discover", true)) + return; #ifdef WIN32 // Get local host ip @@ -1764,6 +1758,22 @@ void StartNode(void* parg) { CreateThread(ThreadGetMyExternalIP, NULL); } +} + +void StartNode(void* parg) +{ +#ifdef USE_UPNP +#if USE_UPNP + fUseUPnP = GetBoolArg("-upnp", true); +#else + fUseUPnP = GetBoolArg("-upnp", false); +#endif +#endif + + if (pnodeLocalHost == NULL) + pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); + + Discover(); // // Start threads diff --git a/src/net.h b/src/net.h index 239971e2c..a00dd1b8c 100644 --- a/src/net.h +++ b/src/net.h @@ -49,6 +49,9 @@ enum LOCAL_UPNP, LOCAL_IRC, LOCAL_HTTP, + LOCAL_MANUAL, + + LOCAL_MAX }; bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);