Bitcoin Core  29.1.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>
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 
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();
127 }
128 
130 {
131  if (!g_mapport_thread.joinable()) {
133  g_mapport_thread = std::thread(&util::TraceThread, "mapport", &ThreadMapPort);
134  }
135 }
136 
137 void StartMapPort(bool enable)
138 {
139  if (enable) {
141  } else {
143  StopMapPort();
144  }
145 }
146 
148 {
149  if (g_mapport_thread.joinable()) {
151  }
152 }
153 
155 {
156  if (g_mapport_thread.joinable()) {
157  g_mapport_thread.join();
159  }
160 }
int ret
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
assert(!tx.IsCoinBase())
static void ProcessPCP()
Definition: mapport.cpp:33
bool sleep_for(Clock::duration rel_time) EXCLUSIVE_LOCKS_REQUIRED(!mut)
IPv4.
Definition: netaddress.h:37
static constexpr auto PORT_MAPPING_RETRY_PERIOD
Definition: mapport.cpp:31
static constexpr auto PORT_MAPPING_REANNOUNCE_PERIOD
Definition: mapport.cpp:30
static std::thread g_mapport_thread
Definition: mapport.cpp:27
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
uint16_t GetListenPort()
Definition: net.cpp:144
static CThreadInterrupt g_mapport_interrupt
Definition: mapport.cpp:26
bool AddLocal(const CService &addr_, int nScore)
Definition: net.cpp:277
void StartMapPort(bool enable)
Definition: mapport.cpp:137
Fast randomness source.
Definition: random.h:376
MappingError
Unsuccessful response to a port mapping.
Definition: pcp.h:22
#define LogPrintLevel(category, level,...)
Definition: logging.h:372
A helper class for interruptible sleeps.
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::optional< CNetAddr > QueryDefaultGateway(Network network)
Query the OS for the default gateway for network.
Definition: netif.cpp:244
static void ThreadMapPort()
Definition: mapport.cpp:122
Network address.
Definition: netaddress.h:111
void StartThreadMapPort()
Definition: mapport.cpp:129
IPv6.
Definition: netaddress.h:40
std::vector< CNetAddr > GetLocalAddresses()
Return all local non-loopback IPv4 and IPv6 network addresses.
Definition: netif.cpp:268
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition: random.h:254
void GetRandBytes(Span< unsigned char > bytes) noexcept
Generate random data via the internal PRNG.
Definition: random.cpp:603
void InterruptMapPort()
Definition: mapport.cpp:147
Unsupported protocol version.
No resources available (port probably already mapped).
void StopMapPort()
Definition: mapport.cpp:154
Successful response to a port mapping.
Definition: pcp.h:30
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:16