mapport.cpp
1 // Copyright (c) 2011-2022 The Bitcoin Core developers 2 // Distributed under the MIT software license, see the accompanying 3 // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 5 #include <mapport.h> 6 7 #include <clientversion.h> 8 #include <common/netif.h> 9 #include <common/pcp.h> 10 #include <common/system.h> 11 #include <logging.h> 12 #include <net.h> 13 #include <netaddress.h> 14 #include <netbase.h> 15 #include <random.h> 16 #include <util/thread.h> 17 #include <util/threadinterrupt.h> 18 19 #include <atomic> 20 #include <cassert> 21 #include <chrono> 22 #include <functional> 23 #include <string> 24 #include <thread> 25 26 static CThreadInterrupt g_mapport_interrupt; 27 static std::thread g_mapport_thread; 28 29 using namespace std::chrono_literals; 30 static constexpr auto PORT_MAPPING_REANNOUNCE_PERIOD{20min}; 31 static constexpr auto PORT_MAPPING_RETRY_PERIOD{5min}; 32 33 static void ProcessPCP() 34 { 35 // The same nonce is used for all mappings, this is allowed by the spec, and simplifies keeping track of them. 36 PCPMappingNonce pcp_nonce; 37 GetRandBytes(pcp_nonce); 38 39 bool ret = false; 40 bool no_resources = false; 41 const uint16_t private_port = GetListenPort(); 42 // Multiply the reannounce period by two, as we'll try to renew approximately halfway. 43 const uint32_t requested_lifetime = std::chrono::seconds(PORT_MAPPING_REANNOUNCE_PERIOD * 2).count(); 44 uint32_t actual_lifetime = 0; 45 std::chrono::milliseconds sleep_time; 46 47 // Local functor to handle result from PCP/NATPMP mapping. 48 auto handle_mapping = [&](std::variant<MappingResult, MappingError> &res) -> void { 49 if (MappingResult* mapping = std::get_if<MappingResult>(&res)) { 50 LogPrintLevel(BCLog::NET, BCLog::Level::Info, "portmap: Added mapping %s\n", mapping->ToString()); 51 AddLocal(mapping->external, LOCAL_MAPPED); 52 ret = true; 53 actual_lifetime = std::min(actual_lifetime, mapping->lifetime); 54 } else if (MappingError *err = std::get_if<MappingError>(&res)) { 55 // Detailed error will already have been logged internally in respective Portmap function. 56 if (*err == MappingError::NO_RESOURCES) { 57 no_resources = true; 58 } 59 } 60 }; 61 62 do { 63 actual_lifetime = requested_lifetime; 64 no_resources = false; // Set to true if there was any "no resources" error. 65 ret = false; // Set to true if any mapping succeeds. 66 67 // IPv4 68 std::optional<CNetAddr> gateway4 = QueryDefaultGateway(NET_IPV4); 69 if (!gateway4) { 70 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "portmap: Could not determine IPv4 default gateway\n"); 71 } else { 72 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "portmap: gateway [IPv4]: %s\n", gateway4->ToStringAddr()); 73 74 // Open a port mapping on whatever local address we have toward the gateway. 75 struct in_addr inaddr_any; 76 inaddr_any.s_addr = htonl(INADDR_ANY); 77 auto res = PCPRequestPortMap(pcp_nonce, *gateway4, CNetAddr(inaddr_any), private_port, requested_lifetime); 78 MappingError* pcp_err = std::get_if<MappingError>(&res); 79 if (pcp_err && *pcp_err == MappingError::UNSUPP_VERSION) { 80 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "portmap: Got unsupported PCP version response, falling back to NAT-PMP\n"); 81 res = NATPMPRequestPortMap(*gateway4, private_port, requested_lifetime); 82 } 83 handle_mapping(res); 84 } 85 86 // IPv6 87 std::optional<CNetAddr> gateway6 = QueryDefaultGateway(NET_IPV6); 88 if (!gateway6) { 89 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "portmap: Could not determine IPv6 default gateway\n"); 90 } else { 91 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "portmap: gateway [IPv6]: %s\n", gateway6->ToStringAddr()); 92 93 // Try to open pinholes for all routable local IPv6 addresses. 94 for (const auto &addr: GetLocalAddresses()) { 95 if (!addr.IsRoutable() || !addr.IsIPv6()) continue; 96 auto res = PCPRequestPortMap(pcp_nonce, *gateway6, addr, private_port, requested_lifetime); 97 handle_mapping(res); 98 } 99 } 100 101 // Log message if we got NO_RESOURCES. 102 if (no_resources) { 103 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "portmap: At least one mapping failed because of a NO_RESOURCES error. This usually indicates that the port is already used on the router. If this is the only instance of bitcoin running on the network, this will resolve itself automatically. Otherwise, you might want to choose a different P2P port to prevent this conflict.\n"); 104 } 105 106 // Sanity-check returned lifetime. 107 if (actual_lifetime < 30) { 108 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "portmap: Got impossibly short mapping lifetime of %d seconds\n", actual_lifetime); 109 return; 110 } 111 // RFC6887 11.2.1 recommends that clients send their first renewal packet at a time chosen with uniform random 112 // distribution in the range 1/2 to 5/8 of expiration time. 113 std::chrono::seconds sleep_time_min(actual_lifetime / 2); 114 std::chrono::seconds sleep_time_max(actual_lifetime * 5 / 8); 115 sleep_time = sleep_time_min + FastRandomContext().randrange<std::chrono::milliseconds>(sleep_time_max - sleep_time_min); 116 } while (ret && g_mapport_interrupt.sleep_for(sleep_time)); 117 118 // We don't delete the mappings when the thread is interrupted because this would add additional complexity, so 119 // we rather just choose a fairly short expiry time. 120 } 121 122 static void ThreadMapPort() 123 { 124 do { 125 ProcessPCP(); 126 } while (g_mapport_interrupt.sleep_for(PORT_MAPPING_RETRY_PERIOD)); 127 } 128 129 void StartThreadMapPort() 130 { 131 if (!g_mapport_thread.joinable()) { 132 assert(!g_mapport_interrupt); 133 g_mapport_thread = std::thread(&util::TraceThread, "mapport", &ThreadMapPort); 134 } 135 } 136 137 void StartMapPort(bool enable) 138 { 139 if (enable) { 140 StartThreadMapPort(); 141 } else { 142 InterruptMapPort(); 143 StopMapPort(); 144 } 145 } 146 147 void InterruptMapPort() 148 { 149 if (g_mapport_thread.joinable()) { 150 g_mapport_interrupt(); 151 } 152 } 153 154 void StopMapPort() 155 { 156 if (g_mapport_thread.joinable()) { 157 g_mapport_thread.join(); 158 g_mapport_interrupt.reset(); 159 } 160 }