Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
mapport.cpp
Go to the documentation of this file.
1// Copyright (c) 2011-2020 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#if defined(HAVE_CONFIG_H)
6#include <config/bitcoin-config.h>
7#endif
8
9#include <mapport.h>
10
11#include <clientversion.h>
12#include <common/system.h>
13#include <logging.h>
14#include <net.h>
15#include <netaddress.h>
16#include <netbase.h>
17#include <threadinterrupt.h>
18#include <util/thread.h>
19
20#ifdef USE_NATPMP
21#include <compat.h>
22#include <natpmp.h>
23#endif // USE_NATPMP
24
25#ifdef USE_UPNP
26#include <miniupnpc/miniupnpc.h>
27#include <miniupnpc/upnpcommands.h>
28#include <miniupnpc/upnperrors.h>
29// The minimum supported miniUPnPc API version is set to 10. This keeps
30// compatibility with Ubuntu 16.04 LTS and Debian 8 libminiupnpc-dev packages.
31static_assert(MINIUPNPC_API_VERSION >= 10,
32 "miniUPnPc API version >= 10 assumed");
33#endif // USE_UPNP
34
35#include <atomic>
36#include <cassert>
37#include <chrono>
38#include <functional>
39#include <string>
40#include <thread>
41
42#if defined(USE_NATPMP) || defined(USE_UPNP)
44static std::thread g_mapport_thread;
46static std::atomic<MapPortProtoFlag> g_mapport_current_proto{
48
49using namespace std::chrono_literals;
50static constexpr auto PORT_MAPPING_REANNOUNCE_PERIOD{20min};
51static constexpr auto PORT_MAPPING_RETRY_PERIOD{5min};
52
53#ifdef USE_NATPMP
55static bool NatpmpInit(natpmp_t *natpmp) {
56 const int r_init = initnatpmp(natpmp, /* detect gateway automatically */ 0,
57 /* forced gateway - NOT APPLIED*/ 0);
58 if (r_init == 0) {
59 return true;
60 }
61 LogPrintf("natpmp: initnatpmp() failed with %d error.\n", r_init);
62 return false;
63}
64
65static bool NatpmpDiscover(natpmp_t *natpmp,
68 if (r_send == 2 /* OK */) {
69 int r_read;
71 do {
73 } while (r_read == NATPMP_TRYAGAIN);
74
75 if (r_read == 0) {
76 external_ipv4_addr = response.pnu.publicaddress.addr;
77 return true;
78 } else if (r_read == NATPMP_ERR_NOGATEWAYSUPPORT) {
79 LogPrintf("natpmp: The gateway does not support NAT-PMP.\n");
80 } else {
81 LogPrintf("natpmp: readnatpmpresponseorretry() for public address "
82 "failed with %d error.\n",
83 r_read);
84 }
85 } else {
86 LogPrintf("natpmp: sendpublicaddressrequest() failed with %d error.\n",
87 r_send);
88 }
89
90 return false;
91}
92
93static bool NatpmpMapping(natpmp_t *natpmp,
94 const struct in_addr &external_ipv4_addr,
98 const int r_send =
100 suggested_external_port, 3600 /*seconds*/);
101 if (r_send == 12 /* OK */) {
102 int r_read;
104 do {
106 } while (r_read == NATPMP_TRYAGAIN);
107
108 if (r_read == 0) {
109 auto pm = response.pnu.newportmapping;
110 if (private_port == pm.privateport && pm.lifetime > 0) {
111 g_mapport_external_port = pm.mappedpublicport;
113 pm.mappedpublicport};
117 }
118 LogPrintf(
119 "natpmp: Port mapping successful. External address = %s\n",
120 external.ToString());
121 return true;
122 } else {
123 LogPrintf("natpmp: Port mapping failed.\n");
124 }
125 } else if (r_read == NATPMP_ERR_NOGATEWAYSUPPORT) {
126 LogPrintf("natpmp: The gateway does not support NAT-PMP.\n");
127 } else {
128 LogPrintf("natpmp: readnatpmpresponseorretry() for port mapping "
129 "failed with %d error.\n",
130 r_read);
131 }
132 } else {
133 LogPrintf("natpmp: sendnewportmappingrequest() failed with %d error.\n",
134 r_send);
135 }
136
137 return false;
138}
139
140[[maybe_unused]] static bool ProcessNatpmp() {
141 bool ret = false;
145 bool external_ip_discovered = false;
147 do {
150 } while (ret &&
152 g_mapport_interrupt.reset();
153
156 /* remove a port mapping */ 0);
158 if (r_send == 12 /* OK */) {
159 LogPrintf("natpmp: Port mapping removed successfully.\n");
160 } else {
161 LogPrintf(
162 "natpmp: sendnewportmappingrequest(0) failed with %d error.\n",
163 r_send);
164 }
165 }
166
168 return ret;
169}
170#endif // USE_NATPMP
171
172#ifdef USE_UPNP
173static bool ProcessUpnp() {
174 bool ret = false;
175 std::string port = strprintf("%u", GetListenPort());
176 const char *multicastif = nullptr;
177 const char *minissdpdpath = nullptr;
178 struct UPNPDev *devlist = nullptr;
179 char lanaddr[64];
180
181 int error = 0;
182#if MINIUPNPC_API_VERSION < 14
184#else
186#endif
187
188 struct UPNPUrls urls;
189 struct IGDdatas data;
190 int r;
191#if MINIUPNPC_API_VERSION <= 17
192 r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
193#else
194 r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr),
195 nullptr, 0);
196#endif
197 if (r == 1) {
198 if (fDiscover) {
199 char externalIPAddress[40];
201 urls.controlURL, data.first.servicetype, externalIPAddress);
202 if (r != UPNPCOMMAND_SUCCESS) {
203 LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
204 } else {
205 if (externalIPAddress[0]) {
208 LogPrintf("UPnP: ExternalIPAddress = %s\n",
209 resolved.ToString());
211 }
212 } else {
213 LogPrintf("UPnP: GetExternalIPAddress failed.\n");
214 }
215 }
216 }
217
218 std::string strDesc = PACKAGE_NAME " " + FormatFullVersion();
219
220 do {
221 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
222 port.c_str(), port.c_str(), lanaddr,
223 strDesc.c_str(), "TCP", 0, "0");
224
225 if (r != UPNPCOMMAND_SUCCESS) {
226 ret = false;
227 LogPrintf(
228 "AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
229 port, port, lanaddr, r, strupnperror(r));
230 break;
231 } else {
232 ret = true;
233 LogPrintf("UPnP Port Mapping successful.\n");
234 }
236 g_mapport_interrupt.reset();
237
238 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype,
239 port.c_str(), "TCP", 0);
240 LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
242 devlist = nullptr;
244 } else {
245 LogPrintf("No valid UPnP IGDs found\n");
247 devlist = nullptr;
248 if (r != 0) {
250 }
251 }
252
253 return ret;
254}
255#endif // USE_UPNP
256
257static void ThreadMapPort() {
258 bool ok;
259 do {
260 ok = false;
261
262#ifdef USE_UPNP
263 // High priority protocol.
266 ok = ProcessUpnp();
267 if (ok) {
268 continue;
269 }
270 }
271#endif // USE_UPNP
272
273#ifdef USE_NATPMP
274 // Low priority protocol.
277 ok = ProcessNatpmp();
278 if (ok) {
279 continue;
280 }
281 }
282#endif // USE_NATPMP
283
286 return;
287 }
288
289 } while (ok || g_mapport_interrupt.sleep_for(PORT_MAPPING_RETRY_PERIOD));
290}
291
292void StartThreadMapPort() {
293 if (!g_mapport_thread.joinable()) {
296 std::thread(&util::TraceThread, "mapport", &ThreadMapPort);
297 }
298}
299
300static void DispatchMapPort() {
303 return;
304 }
305
309 return;
310 }
311
315 StopMapPort();
316 return;
317 }
318
320 // Enabling another protocol does not cause switching from the currently
321 // used one.
322 return;
323 }
324
325 assert(g_mapport_thread.joinable());
327 // Interrupt a protocol-specific loop in the ThreadUpnp() or in the
328 // ThreadNatpmp() to force trying the next protocol in the ThreadMapPort()
329 // loop.
331}
332
333static void MapPortProtoSetEnabled(MapPortProtoFlag proto, bool enabled) {
334 if (enabled) {
336 } else {
338 }
339}
340
341void StartMapPort(bool use_upnp, bool use_natpmp) {
345}
346
347void InterruptMapPort() {
349 if (g_mapport_thread.joinable()) {
351 }
352}
353
354void StopMapPort() {
355 if (g_mapport_thread.joinable()) {
356 g_mapport_thread.join();
357 g_mapport_interrupt.reset();
358 }
359}
360
361#else // #if defined(USE_NATPMP) || defined(USE_UPNP)
363 // Intentionally left blank.
364}
366 // Intentionally left blank.
367}
369 // Intentionally left blank.
370}
371#endif // #if defined(USE_NATPMP) || defined(USE_UPNP)
Network address.
Definition netaddress.h:121
A combination of a network address (CNetAddr) and a (TCP) port.
Definition netaddress.h:545
A helper class for interruptible sleeps.
std::string FormatFullVersion()
bool error(const char *fmt, const Args &...args)
Definition logging.h:226
#define LogPrintf(...)
Definition logging.h:207
void StartMapPort(bool use_upnp, bool use_natpmp)
Definition mapport.cpp:362
void StopMapPort()
Definition mapport.cpp:368
void InterruptMapPort()
Definition mapport.cpp:365
MapPortProtoFlag
Definition mapport.h:20
@ UPNP
Definition mapport.h:22
@ NAT_PMP
Definition mapport.h:23
@ NONE
Definition mapport.h:21
void TraceThread(const char *thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition thread.cpp:13
uint16_t GetListenPort()
Definition net.cpp:137
bool fDiscover
Definition net.cpp:125
bool AddLocal(const CService &addr, int nScore)
Definition net.cpp:278
@ LOCAL_MAPPED
Definition net.h:237
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
Definition netbase.cpp:191
Response response
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition random.h:85
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
assert(!tx.IsCoinBase())