Branch data Line data Source code
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 : : static std::atomic_uint g_mapport_enabled_protos{MapPortProtoFlag::NONE};
29 : : static std::atomic<MapPortProtoFlag> g_mapport_current_proto{MapPortProtoFlag::NONE};
30 : :
31 : : using namespace std::chrono_literals;
32 : : static constexpr auto PORT_MAPPING_REANNOUNCE_PERIOD{20min};
33 : : static constexpr auto PORT_MAPPING_RETRY_PERIOD{5min};
34 : :
35 : 0 : static 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 : 0 : PCPMappingNonce pcp_nonce;
39 : 0 : GetRandBytes(pcp_nonce);
40 : :
41 : 0 : bool ret = false;
42 : 0 : bool no_resources = false;
43 : 0 : const uint16_t private_port = GetListenPort();
44 : : // Multiply the reannounce period by two, as we'll try to renew approximately halfway.
45 : 0 : const uint32_t requested_lifetime = std::chrono::seconds(PORT_MAPPING_REANNOUNCE_PERIOD * 2).count();
46 : 0 : uint32_t actual_lifetime = 0;
47 : 0 : std::chrono::milliseconds sleep_time;
48 : :
49 : : // Local functor to handle result from PCP/NATPMP mapping.
50 : 0 : auto handle_mapping = [&](std::variant<MappingResult, MappingError> &res) -> void {
51 [ # # ]: 0 : if (MappingResult* mapping = std::get_if<MappingResult>(&res)) {
52 [ # # # # ]: 0 : LogPrintLevel(BCLog::NET, BCLog::Level::Info, "portmap: Added mapping %s\n", mapping->ToString());
53 : 0 : AddLocal(mapping->external, LOCAL_MAPPED);
54 : 0 : ret = true;
55 [ # # ]: 0 : actual_lifetime = std::min(actual_lifetime, mapping->lifetime);
56 [ # # ]: 0 : } else if (MappingError *err = std::get_if<MappingError>(&res)) {
57 : : // Detailed error will already have been logged internally in respective Portmap function.
58 [ # # ]: 0 : if (*err == MappingError::NO_RESOURCES) {
59 : 0 : no_resources = true;
60 : : }
61 : : }
62 : 0 : };
63 : :
64 : 0 : do {
65 : 0 : actual_lifetime = requested_lifetime;
66 : 0 : no_resources = false; // Set to true if there was any "no resources" error.
67 : 0 : ret = false; // Set to true if any mapping succeeds.
68 : :
69 : : // IPv4
70 : 0 : std::optional<CNetAddr> gateway4 = QueryDefaultGateway(NET_IPV4);
71 [ # # ]: 0 : if (!gateway4) {
72 [ # # # # : 0 : LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "portmap: Could not determine IPv4 default gateway\n");
# # ]
73 : : } else {
74 [ # # # # : 0 : 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 : 0 : struct in_addr inaddr_any;
78 : 0 : inaddr_any.s_addr = htonl(INADDR_ANY);
79 [ # # # # ]: 0 : auto res = PCPRequestPortMap(pcp_nonce, *gateway4, CNetAddr(inaddr_any), private_port, requested_lifetime);
80 [ # # ]: 0 : MappingError* pcp_err = std::get_if<MappingError>(&res);
81 [ # # ]: 0 : if (pcp_err && *pcp_err == MappingError::UNSUPP_VERSION) {
82 [ # # # # : 0 : LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "portmap: Got unsupported PCP version response, falling back to NAT-PMP\n");
# # ]
83 [ # # ]: 0 : res = NATPMPRequestPortMap(*gateway4, private_port, requested_lifetime);
84 : : }
85 [ # # ]: 0 : handle_mapping(res);
86 : 0 : }
87 : :
88 : : // IPv6
89 [ # # ]: 0 : std::optional<CNetAddr> gateway6 = QueryDefaultGateway(NET_IPV6);
90 [ # # ]: 0 : if (!gateway6) {
91 [ # # # # : 0 : LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "portmap: Could not determine IPv6 default gateway\n");
# # ]
92 : : } else {
93 [ # # # # : 0 : 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 [ # # # # ]: 0 : for (const auto &addr: GetLocalAddresses()) {
97 [ # # # # : 0 : if (!addr.IsRoutable() || !addr.IsIPv6()) continue;
# # ]
98 [ # # ]: 0 : auto res = PCPRequestPortMap(pcp_nonce, *gateway6, addr, private_port, requested_lifetime);
99 [ # # ]: 0 : handle_mapping(res);
100 : 0 : }
101 : : }
102 : :
103 : : // Log message if we got NO_RESOURCES.
104 [ # # ]: 0 : if (no_resources) {
105 [ # # # # : 0 : 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 [ # # ]: 0 : if (actual_lifetime < 30) {
110 [ # # # # : 0 : LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "portmap: Got impossibly short mapping lifetime of %d seconds\n", actual_lifetime);
# # ]
111 : 0 : 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 : 0 : std::chrono::seconds sleep_time_min(actual_lifetime / 2);
116 : 0 : std::chrono::seconds sleep_time_max(actual_lifetime * 5 / 8);
117 : 0 : sleep_time = sleep_time_min + FastRandomContext().randrange<std::chrono::milliseconds>(sleep_time_max - sleep_time_min);
118 [ # # # # : 0 : } 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 : 0 : return ret;
124 : : }
125 : :
126 : 0 : static void ThreadMapPort()
127 : : {
128 : 0 : bool ok;
129 : 0 : do {
130 : 0 : ok = false;
131 : :
132 [ # # ]: 0 : if (g_mapport_enabled_protos & MapPortProtoFlag::PCP) {
133 : 0 : g_mapport_current_proto = MapPortProtoFlag::PCP;
134 : 0 : ok = ProcessPCP();
135 [ # # ]: 0 : if (ok) continue;
136 : : }
137 : :
138 [ # # ]: 0 : g_mapport_current_proto = MapPortProtoFlag::NONE;
139 [ # # ]: 0 : if (g_mapport_enabled_protos == MapPortProtoFlag::NONE) {
140 : : return;
141 : : }
142 : :
143 [ # # # # : 0 : } while (ok || g_mapport_interrupt.sleep_for(PORT_MAPPING_RETRY_PERIOD));
# # ]
144 : : }
145 : :
146 : 0 : void StartThreadMapPort()
147 : : {
148 [ # # ]: 0 : if (!g_mapport_thread.joinable()) {
149 [ # # ]: 0 : assert(!g_mapport_interrupt);
150 : 0 : g_mapport_thread = std::thread(&util::TraceThread, "mapport", &ThreadMapPort);
151 : : }
152 : 0 : }
153 : :
154 : 0 : static void DispatchMapPort()
155 : : {
156 [ # # # # ]: 0 : if (g_mapport_current_proto == MapPortProtoFlag::NONE && g_mapport_enabled_protos == MapPortProtoFlag::NONE) {
157 : : return;
158 : : }
159 : :
160 [ # # # # ]: 0 : if (g_mapport_current_proto == MapPortProtoFlag::NONE && g_mapport_enabled_protos != MapPortProtoFlag::NONE) {
161 : 0 : StartThreadMapPort();
162 : 0 : return;
163 : : }
164 : :
165 [ # # # # ]: 0 : if (g_mapport_current_proto != MapPortProtoFlag::NONE && g_mapport_enabled_protos == MapPortProtoFlag::NONE) {
166 : 0 : InterruptMapPort();
167 : 0 : StopMapPort();
168 : 0 : return;
169 : : }
170 : :
171 : 0 : if (g_mapport_enabled_protos & g_mapport_current_proto) {
172 : 0 : return;
173 : : }
174 : : }
175 : :
176 : 0 : static void MapPortProtoSetEnabled(MapPortProtoFlag proto, bool enabled)
177 : : {
178 [ # # ]: 0 : if (enabled) {
179 : 0 : g_mapport_enabled_protos |= proto;
180 : : } else {
181 : 0 : g_mapport_enabled_protos &= ~proto;
182 : : }
183 : 0 : }
184 : :
185 : 0 : void StartMapPort(bool use_pcp)
186 : : {
187 : 0 : MapPortProtoSetEnabled(MapPortProtoFlag::PCP, use_pcp);
188 : 0 : DispatchMapPort();
189 : 0 : }
190 : :
191 : 0 : void InterruptMapPort()
192 : : {
193 [ # # ]: 0 : g_mapport_enabled_protos = MapPortProtoFlag::NONE;
194 [ # # ]: 0 : if (g_mapport_thread.joinable()) {
195 : 0 : g_mapport_interrupt();
196 : : }
197 : 0 : }
198 : :
199 : 0 : void StopMapPort()
200 : : {
201 [ # # ]: 0 : if (g_mapport_thread.joinable()) {
202 : 0 : g_mapport_thread.join();
203 : 0 : g_mapport_interrupt.reset();
204 : : }
205 : 0 : }
|