Bitcoin Core 31.0.0
P2P Digital Currency
Loading...
Searching...
No Matches
mapport.cpp
Go to the documentation of this file.
1// Copyright (c) 2011-present 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;
28
29using namespace std::chrono_literals;
30static constexpr auto PORT_MAPPING_REANNOUNCE_PERIOD{20min};
31static constexpr auto PORT_MAPPING_RETRY_PERIOD{5min};
32
33static void ProcessPCP()
34{
35 // The same nonce is used for all mappings, this is allowed by the spec, and simplifies keeping track of them.
38
39 bool ret = false;
40 bool no_resources = false;
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();
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 LogInfo("portmap: Added mapping %s", 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 {
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 LogDebug(BCLog::NET, "portmap: Could not determine IPv4 default gateway\n");
71 } else {
72 LogDebug(BCLog::NET, "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);
78 MappingError* pcp_err = std::get_if<MappingError>(&res);
80 LogDebug(BCLog::NET, "portmap: Got unsupported PCP version response, falling back to NAT-PMP\n");
82 }
84 }
85
86 // IPv6
87 std::optional<CNetAddr> gateway6 = QueryDefaultGateway(NET_IPV6);
88 if (!gateway6) {
89 LogDebug(BCLog::NET, "portmap: Could not determine IPv6 default gateway\n");
90 } else {
91 LogDebug(BCLog::NET, "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;
98 }
99 }
100
101 // Log message if we got NO_RESOURCES.
102 if (no_resources) {
103 LogWarning("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 LogWarning("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);
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
122static 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
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
Network address.
Definition netaddress.h:113
A helper class for interruptible sleeps.
virtual void reset()
Reset to an non-interrupted state.
virtual bool sleep_for(Clock::duration rel_time) EXCLUSIVE_LOCKS_REQUIRED(!mut)
Sleep for the given duration.
Fast randomness source.
Definition random.h:386
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition random.h:254
std::variant< MappingResult, MappingError > NATPMPRequestPortMap(const CNetAddr &gateway, uint16_t port, uint32_t lifetime, CThreadInterrupt &interrupt, int num_tries, std::chrono::milliseconds timeout_per_try)
Try to open a port using RFC 6886 NAT-PMP.
Definition pcp.cpp:282
std::variant< MappingResult, MappingError > PCPRequestPortMap(const PCPMappingNonce &nonce, const CNetAddr &gateway, const CNetAddr &bind, uint16_t port, uint32_t lifetime, CThreadInterrupt &interrupt, int num_tries, std::chrono::milliseconds timeout_per_try)
Try to open a port using RFC 6887 Port Control Protocol (PCP).
Definition pcp.cpp:406
#define LogWarning(...)
Definition log.h:96
#define LogInfo(...)
Definition log.h:95
#define LogDebug(category,...)
Definition log.h:115
static void ThreadMapPort()
Definition mapport.cpp:122
static std::thread g_mapport_thread
Definition mapport.cpp:27
static constexpr auto PORT_MAPPING_REANNOUNCE_PERIOD
Definition mapport.cpp:30
static CThreadInterrupt g_mapport_interrupt
Definition mapport.cpp:26
static void ProcessPCP()
Definition mapport.cpp:33
void StopMapPort()
Definition mapport.cpp:154
static constexpr auto PORT_MAPPING_RETRY_PERIOD
Definition mapport.cpp:31
void InterruptMapPort()
Definition mapport.cpp:147
void StartMapPort(bool enable)
Definition mapport.cpp:137
void StartThreadMapPort()
Definition mapport.cpp:129
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:138
bool AddLocal(const CService &addr_, int nScore)
Definition net.cpp:277
@ LOCAL_MAPPED
Definition net.h:157
@ NET_IPV6
IPv6.
Definition netaddress.h:41
@ NET_IPV4
IPv4.
Definition netaddress.h:38
std::vector< CNetAddr > GetLocalAddresses()
Return all local non-loopback IPv4 and IPv6 network addresses.
Definition netif.cpp:322
std::optional< CNetAddr > QueryDefaultGateway(Network network)
Query the OS for the default gateway for network.
Definition netif.cpp:298
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:20
MappingError
Unsuccessful response to a port mapping.
Definition pcp.h:23
@ NO_RESOURCES
No resources available (port probably already mapped).
@ UNSUPP_VERSION
Unsupported protocol version.
void GetRandBytes(std::span< unsigned char > bytes) noexcept
Generate random data via the internal PRNG.
Definition random.cpp:601
Successful response to a port mapping.
Definition pcp.h:31
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:73
assert(!tx.IsCoinBase())