Bitcoin Core 28.99.0
P2P Digital Currency
mapport.cpp
Go to the documentation of this file.
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>
18
19#include <atomic>
20#include <cassert>
21#include <chrono>
22#include <functional>
23#include <string>
24#include <thread>
25
27static std::thread g_mapport_thread;
29static std::atomic<MapPortProtoFlag> g_mapport_current_proto{MapPortProtoFlag::NONE};
30
31using namespace std::chrono_literals;
32static constexpr auto PORT_MAPPING_REANNOUNCE_PERIOD{20min};
33static constexpr auto PORT_MAPPING_RETRY_PERIOD{5min};
34
35static bool ProcessPCP()
36{
37 // The same nonce is used for all mappings, this is allowed by the spec, and simplifies keeping track of them.
38 PCPMappingNonce pcp_nonce;
39 GetRandBytes(pcp_nonce);
40
41 bool ret = false;
42 bool no_resources = false;
43 const uint16_t private_port = GetListenPort();
44 // Multiply the reannounce period by two, as we'll try to renew approximately halfway.
45 const uint32_t requested_lifetime = std::chrono::seconds(PORT_MAPPING_REANNOUNCE_PERIOD * 2).count();
46 uint32_t actual_lifetime = 0;
47 std::chrono::milliseconds sleep_time;
48
49 // Local functor to handle result from PCP/NATPMP mapping.
50 auto handle_mapping = [&](std::variant<MappingResult, MappingError> &res) -> void {
51 if (MappingResult* mapping = std::get_if<MappingResult>(&res)) {
52 LogPrintLevel(BCLog::NET, BCLog::Level::Info, "portmap: Added mapping %s\n", mapping->ToString());
53 AddLocal(mapping->external, LOCAL_MAPPED);
54 ret = true;
55 actual_lifetime = std::min(actual_lifetime, mapping->lifetime);
56 } else if (MappingError *err = std::get_if<MappingError>(&res)) {
57 // Detailed error will already have been logged internally in respective Portmap function.
58 if (*err == MappingError::NO_RESOURCES) {
59 no_resources = true;
60 }
61 }
62 };
63
64 do {
65 actual_lifetime = requested_lifetime;
66 no_resources = false; // Set to true if there was any "no resources" error.
67 ret = false; // Set to true if any mapping succeeds.
68
69 // IPv4
70 std::optional<CNetAddr> gateway4 = QueryDefaultGateway(NET_IPV4);
71 if (!gateway4) {
72 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "portmap: Could not determine IPv4 default gateway\n");
73 } else {
74 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "portmap: gateway [IPv4]: %s\n", gateway4->ToStringAddr());
75
76 // Open a port mapping on whatever local address we have toward the gateway.
77 struct in_addr inaddr_any;
78 inaddr_any.s_addr = htonl(INADDR_ANY);
79 auto res = PCPRequestPortMap(pcp_nonce, *gateway4, CNetAddr(inaddr_any), private_port, requested_lifetime);
80 MappingError* pcp_err = std::get_if<MappingError>(&res);
81 if (pcp_err && *pcp_err == MappingError::UNSUPP_VERSION) {
82 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "portmap: Got unsupported PCP version response, falling back to NAT-PMP\n");
83 res = NATPMPRequestPortMap(*gateway4, private_port, requested_lifetime);
84 }
85 handle_mapping(res);
86 }
87
88 // IPv6
89 std::optional<CNetAddr> gateway6 = QueryDefaultGateway(NET_IPV6);
90 if (!gateway6) {
91 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "portmap: Could not determine IPv6 default gateway\n");
92 } else {
93 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "portmap: gateway [IPv6]: %s\n", gateway6->ToStringAddr());
94
95 // Try to open pinholes for all routable local IPv6 addresses.
96 for (const auto &addr: GetLocalAddresses()) {
97 if (!addr.IsRoutable() || !addr.IsIPv6()) continue;
98 auto res = PCPRequestPortMap(pcp_nonce, *gateway6, addr, private_port, requested_lifetime);
99 handle_mapping(res);
100 }
101 }
102
103 // Log message if we got NO_RESOURCES.
104 if (no_resources) {
105 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");
106 }
107
108 // Sanity-check returned lifetime.
109 if (actual_lifetime < 30) {
110 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "portmap: Got impossibly short mapping lifetime of %d seconds\n", actual_lifetime);
111 return false;
112 }
113 // RFC6887 11.2.1 recommends that clients send their first renewal packet at a time chosen with uniform random
114 // distribution in the range 1/2 to 5/8 of expiration time.
115 std::chrono::seconds sleep_time_min(actual_lifetime / 2);
116 std::chrono::seconds sleep_time_max(actual_lifetime * 5 / 8);
117 sleep_time = sleep_time_min + FastRandomContext().randrange<std::chrono::milliseconds>(sleep_time_max - sleep_time_min);
118 } while (ret && g_mapport_interrupt.sleep_for(sleep_time));
119
120 // We don't delete the mappings when the thread is interrupted because this would add additional complexity, so
121 // we rather just choose a fairly short expiry time.
122
123 return ret;
124}
125
126static void ThreadMapPort()
127{
128 bool ok;
129 do {
130 ok = false;
131
134 ok = ProcessPCP();
135 if (ok) continue;
136 }
137
140 return;
141 }
142
144}
145
147{
148 if (!g_mapport_thread.joinable()) {
150 g_mapport_thread = std::thread(&util::TraceThread, "mapport", &ThreadMapPort);
151 }
152}
153
154static void DispatchMapPort()
155{
157 return;
158 }
159
162 return;
163 }
164
167 StopMapPort();
168 return;
169 }
170
172 return;
173 }
174}
175
176static void MapPortProtoSetEnabled(MapPortProtoFlag proto, bool enabled)
177{
178 if (enabled) {
180 } else {
181 g_mapport_enabled_protos &= ~proto;
182 }
183}
184
185void StartMapPort(bool use_pcp)
186{
189}
190
192{
194 if (g_mapport_thread.joinable()) {
196 }
197}
198
200{
201 if (g_mapport_thread.joinable()) {
202 g_mapport_thread.join();
204 }
205}
int ret
Network address.
Definition: netaddress.h:112
A helper class for interruptible sleeps.
bool sleep_for(Clock::duration rel_time) EXCLUSIVE_LOCKS_REQUIRED(!mut)
Fast randomness source.
Definition: random.h:377
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition: random.h:254
#define LogPrintLevel(category, level,...)
Definition: logging.h:272
static void ThreadMapPort()
Definition: mapport.cpp:126
static std::thread g_mapport_thread
Definition: mapport.cpp:27
void StartMapPort(bool use_pcp)
Definition: mapport.cpp:185
static constexpr auto PORT_MAPPING_REANNOUNCE_PERIOD
Definition: mapport.cpp:32
static CThreadInterrupt g_mapport_interrupt
Definition: mapport.cpp:26
void StopMapPort()
Definition: mapport.cpp:199
static std::atomic< MapPortProtoFlag > g_mapport_current_proto
Definition: mapport.cpp:29
static void DispatchMapPort()
Definition: mapport.cpp:154
static void MapPortProtoSetEnabled(MapPortProtoFlag proto, bool enabled)
Definition: mapport.cpp:176
static constexpr auto PORT_MAPPING_RETRY_PERIOD
Definition: mapport.cpp:33
static bool ProcessPCP()
Definition: mapport.cpp:35
static std::atomic_uint g_mapport_enabled_protos
Definition: mapport.cpp:28
void InterruptMapPort()
Definition: mapport.cpp:191
void StartThreadMapPort()
Definition: mapport.cpp:146
MapPortProtoFlag
Definition: mapport.h:10
@ PCP
Definition: mapport.h:13
@ NONE
Definition: logging.h:42
@ NET
Definition: logging.h:43
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:16
uint16_t GetListenPort()
Definition: net.cpp:140
bool AddLocal(const CService &addr_, int nScore)
Definition: net.cpp:273
@ LOCAL_MAPPED
Definition: net.h:151
@ NET_IPV6
IPv6.
Definition: netaddress.h:40
@ NET_IPV4
IPv4.
Definition: netaddress.h:37
std::vector< CNetAddr > GetLocalAddresses()
Return all local non-loopback IPv4 and IPv6 network addresses.
Definition: netif.cpp:275
std::optional< CNetAddr > QueryDefaultGateway(Network network)
Query the OS for the default gateway for network.
Definition: netif.cpp:251
std::variant< MappingResult, MappingError > PCPRequestPortMap(const PCPMappingNonce &nonce, const CNetAddr &gateway, const CNetAddr &bind, uint16_t port, uint32_t lifetime, int num_tries, std::chrono::milliseconds timeout_per_try)
Try to open a port using RFC 6887 Port Control Protocol (PCP).
Definition: pcp.cpp:387
std::variant< MappingResult, MappingError > NATPMPRequestPortMap(const CNetAddr &gateway, uint16_t port, uint32_t lifetime, int num_tries, std::chrono::milliseconds timeout_per_try)
Try to open a port using RFC 6886 NAT-PMP.
Definition: pcp.cpp:274
std::array< uint8_t, PCP_MAP_NONCE_SIZE > PCPMappingNonce
PCP mapping nonce. Arbitrary data chosen by the client to identify a mapping.
Definition: pcp.h:19
MappingError
Unsuccessful response to a port mapping.
Definition: pcp.h:22
@ NO_RESOURCES
No resources available (port probably already mapped).
@ UNSUPP_VERSION
Unsupported protocol version.
void GetRandBytes(Span< unsigned char > bytes) noexcept
Generate random data via the internal PRNG.
Definition: random.cpp:676
Successful response to a port mapping.
Definition: pcp.h:30
assert(!tx.IsCoinBase())