Bitcoin Core 28.99.0
P2P Digital Currency
pcp.cpp
Go to the documentation of this file.
1// Copyright (c) 2024 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or https://www.opensource.org/licenses/mit-license.php.
4
5#include <common/pcp.h>
6
7#include <common/netif.h>
8#include <crypto/common.h>
9#include <logging.h>
10#include <netaddress.h>
11#include <netbase.h>
12#include <random.h>
13#include <span.h>
14#include <util/check.h>
15#include <util/readwritefile.h>
16#include <util/sock.h>
17#include <util/strencodings.h>
18
19namespace {
20
21// RFC6886 NAT-PMP and RFC6887 Port Control Protocol (PCP) implementation.
22// NAT-PMP and PCP use network byte order (big-endian).
23
24// NAT-PMP (v0) protocol constants.
26constexpr uint16_t NATPMP_SERVER_PORT = 5351;
28constexpr uint8_t NATPMP_VERSION = 0;
30constexpr uint8_t NATPMP_REQUEST = 0x00;
32constexpr uint8_t NATPMP_RESPONSE = 0x80;
34constexpr uint8_t NATPMP_OP_GETEXTERNAL = 0x00;
36constexpr uint8_t NATPMP_OP_MAP_TCP = 0x02;
38constexpr size_t NATPMP_REQUEST_HDR_SIZE = 2;
40constexpr size_t NATPMP_RESPONSE_HDR_SIZE = 8;
42constexpr size_t NATPMP_GETEXTERNAL_REQUEST_SIZE = NATPMP_REQUEST_HDR_SIZE + 0;
44constexpr size_t NATPMP_GETEXTERNAL_RESPONSE_SIZE = NATPMP_RESPONSE_HDR_SIZE + 4;
46constexpr size_t NATPMP_MAP_REQUEST_SIZE = NATPMP_REQUEST_HDR_SIZE + 10;
48constexpr size_t NATPMP_MAP_RESPONSE_SIZE = NATPMP_RESPONSE_HDR_SIZE + 8;
49
50// Shared header offsets (RFC6886 3.2, 3.3), relative to start of packet.
52constexpr size_t NATPMP_HDR_VERSION_OFS = 0;
54constexpr size_t NATPMP_HDR_OP_OFS = 1;
56constexpr size_t NATPMP_RESPONSE_HDR_RESULT_OFS = 2;
57
58// GETEXTERNAL response offsets (RFC6886 3.2), relative to start of packet.
60constexpr size_t NATPMP_GETEXTERNAL_RESPONSE_IP_OFS = 8;
61
62// MAP request offsets (RFC6886 3.3), relative to start of packet.
64constexpr size_t NATPMP_MAP_REQUEST_INTERNAL_PORT_OFS = 4;
66constexpr size_t NATPMP_MAP_REQUEST_EXTERNAL_PORT_OFS = 6;
68constexpr size_t NATPMP_MAP_REQUEST_LIFETIME_OFS = 8;
69
70// MAP response offsets (RFC6886 3.3), relative to start of packet.
72constexpr size_t NATPMP_MAP_RESPONSE_INTERNAL_PORT_OFS = 8;
74constexpr size_t NATPMP_MAP_RESPONSE_EXTERNAL_PORT_OFS = 10;
76constexpr size_t NATPMP_MAP_RESPONSE_LIFETIME_OFS = 12;
77
78// Relevant NETPMP result codes (RFC6886 3.5).
80constexpr uint8_t NATPMP_RESULT_SUCCESS = 0;
82constexpr uint8_t NATPMP_RESULT_UNSUPP_VERSION = 1;
84constexpr uint8_t NATPMP_RESULT_NO_RESOURCES = 4;
85
87const std::map<uint8_t, std::string> NATPMP_RESULT_STR{
88 {0, "SUCCESS"},
89 {1, "UNSUPP_VERSION"},
90 {2, "NOT_AUTHORIZED"},
91 {3, "NETWORK_FAILURE"},
92 {4, "NO_RESOURCES"},
93 {5, "UNSUPP_OPCODE"},
94};
95
96// PCP (v2) protocol constants.
98constexpr size_t PCP_MAX_SIZE = 1100;
100constexpr uint16_t PCP_SERVER_PORT = NATPMP_SERVER_PORT;
102constexpr uint8_t PCP_VERSION = 2;
104constexpr uint8_t PCP_REQUEST = NATPMP_REQUEST; // R = 0
106constexpr uint8_t PCP_RESPONSE = NATPMP_RESPONSE; // R = 1
108constexpr uint8_t PCP_OP_MAP = 0x01;
110constexpr uint16_t PCP_PROTOCOL_TCP = 6;
112constexpr size_t PCP_HDR_SIZE = 24;
114constexpr size_t PCP_MAP_SIZE = 36;
115
116// Header offsets shared between request and responses (RFC6887 7.1, 7.2), relative to start of packet.
118constexpr size_t PCP_HDR_VERSION_OFS = NATPMP_HDR_VERSION_OFS;
120constexpr size_t PCP_HDR_OP_OFS = NATPMP_HDR_OP_OFS;
122constexpr size_t PCP_HDR_LIFETIME_OFS = 4;
123
124// Request header offsets (RFC6887 7.1), relative to start of packet.
126constexpr size_t PCP_REQUEST_HDR_IP_OFS = 8;
127
128// Response header offsets (RFC6887 7.2), relative to start of packet.
130constexpr size_t PCP_RESPONSE_HDR_RESULT_OFS = 3;
131
132// MAP request/response offsets (RFC6887 11.1), relative to start of opcode-specific data.
134constexpr size_t PCP_MAP_NONCE_OFS = 0;
136constexpr size_t PCP_MAP_PROTOCOL_OFS = 12;
138constexpr size_t PCP_MAP_INTERNAL_PORT_OFS = 16;
140constexpr size_t PCP_MAP_EXTERNAL_PORT_OFS = 18;
142constexpr size_t PCP_MAP_EXTERNAL_IP_OFS = 20;
143
145constexpr uint8_t PCP_RESULT_SUCCESS = NATPMP_RESULT_SUCCESS;
147constexpr uint8_t PCP_RESULT_NO_RESOURCES = 8;
148
150const std::map<uint8_t, std::string> PCP_RESULT_STR{
151 {0, "SUCCESS"},
152 {1, "UNSUPP_VERSION"},
153 {2, "NOT_AUTHORIZED"},
154 {3, "MALFORMED_REQUEST"},
155 {4, "UNSUPP_OPCODE"},
156 {5, "UNSUPP_OPTION"},
157 {6, "MALFORMED_OPTION"},
158 {7, "NETWORK_FAILURE"},
159 {8, "NO_RESOURCES"},
160 {9, "UNSUPP_PROTOCOL"},
161 {10, "USER_EX_QUOTA"},
162 {11, "CANNOT_PROVIDE_EXTERNAL"},
163 {12, "ADDRESS_MISMATCH"},
164 {13, "EXCESSIVE_REMOTE_PEER"},
165};
166
168std::string NATPMPResultString(uint8_t result_code)
169{
170 auto result_i = NATPMP_RESULT_STR.find(result_code);
171 return strprintf("%s (code %d)", result_i == NATPMP_RESULT_STR.end() ? "(unknown)" : result_i->second, result_code);
172}
173
175std::string PCPResultString(uint8_t result_code)
176{
177 auto result_i = PCP_RESULT_STR.find(result_code);
178 return strprintf("%s (code %d)", result_i == PCP_RESULT_STR.end() ? "(unknown)" : result_i->second, result_code);
179}
180
182[[nodiscard]] bool PCPWrapAddress(Span<uint8_t> wrapped_addr, const CNetAddr &addr)
183{
184 Assume(wrapped_addr.size() == ADDR_IPV6_SIZE);
185 if (addr.IsIPv4()) {
186 struct in_addr addr4;
187 if (!addr.GetInAddr(&addr4)) return false;
188 // Section 5: "When the address field holds an IPv4 address, an IPv4-mapped IPv6 address [RFC4291] is used (::ffff:0:0/96)."
189 std::memcpy(wrapped_addr.data(), IPV4_IN_IPV6_PREFIX.data(), IPV4_IN_IPV6_PREFIX.size());
190 std::memcpy(wrapped_addr.data() + IPV4_IN_IPV6_PREFIX.size(), &addr4, ADDR_IPV4_SIZE);
191 return true;
192 } else if (addr.IsIPv6()) {
193 struct in6_addr addr6;
194 if (!addr.GetIn6Addr(&addr6)) return false;
195 std::memcpy(wrapped_addr.data(), &addr6, ADDR_IPV6_SIZE);
196 return true;
197 } else {
198 return false;
199 }
200}
201
203CNetAddr PCPUnwrapAddress(Span<const uint8_t> wrapped_addr)
204{
205 Assume(wrapped_addr.size() == ADDR_IPV6_SIZE);
206 if (util::HasPrefix(wrapped_addr, IPV4_IN_IPV6_PREFIX)) {
207 struct in_addr addr4;
208 std::memcpy(&addr4, wrapped_addr.data() + IPV4_IN_IPV6_PREFIX.size(), ADDR_IPV4_SIZE);
209 return CNetAddr(addr4);
210 } else {
211 struct in6_addr addr6;
212 std::memcpy(&addr6, wrapped_addr.data(), ADDR_IPV6_SIZE);
213 return CNetAddr(addr6);
214 }
215}
216
218std::optional<std::vector<uint8_t>> PCPSendRecv(Sock &sock, const std::string &protocol, Span<const uint8_t> request, int num_tries,
219 std::chrono::milliseconds timeout_per_try,
220 std::function<bool(Span<const uint8_t>)> check_packet)
221{
222 using namespace std::chrono;
223 // UDP is a potentially lossy protocol, so we try to send again a few times.
224 uint8_t response[PCP_MAX_SIZE];
225 bool got_response = false;
226 int recvsz = 0;
227 for (int ntry = 0; !got_response && ntry < num_tries; ++ntry) {
228 if (ntry > 0) {
229 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "%s: Retrying (%d)\n", protocol, ntry);
230 }
231 // Dispatch packet to gateway.
232 if (sock.Send(request.data(), request.size(), 0) != static_cast<ssize_t>(request.size())) {
233 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "%s: Could not send request: %s\n", protocol, NetworkErrorString(WSAGetLastError()));
234 return std::nullopt; // Network-level error, probably no use retrying.
235 }
236
237 // Wait for response(s) until we get a valid response, a network error, or time out.
238 auto cur_time = time_point_cast<milliseconds>(steady_clock::now());
239 auto deadline = cur_time + timeout_per_try;
240 while ((cur_time = time_point_cast<milliseconds>(steady_clock::now())) < deadline) {
241 Sock::Event occurred = 0;
242 if (!sock.Wait(deadline - cur_time, Sock::RECV, &occurred)) {
243 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "%s: Could not wait on socket: %s\n", protocol, NetworkErrorString(WSAGetLastError()));
244 return std::nullopt; // Network-level error, probably no use retrying.
245 }
246 if (!occurred) {
247 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "%s: Timeout\n", protocol);
248 break; // Retry.
249 }
250
251 // Receive response.
252 recvsz = sock.Recv(response, sizeof(response), MSG_DONTWAIT);
253 if (recvsz < 0) {
254 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "%s: Could not receive response: %s\n", protocol, NetworkErrorString(WSAGetLastError()));
255 return std::nullopt; // Network-level error, probably no use retrying.
256 }
257 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "%s: Received response of %d bytes: %s\n", protocol, recvsz, HexStr(Span(response, recvsz)));
258
259 if (check_packet(Span<uint8_t>(response, recvsz))) {
260 got_response = true; // Got expected response, break from receive loop as well as from retry loop.
261 break;
262 }
263 }
264 }
265 if (!got_response) {
266 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "%s: Giving up after %d tries\n", protocol, num_tries);
267 return std::nullopt;
268 }
269 return std::vector<uint8_t>(response, response + recvsz);
270}
271
272}
273
274std::variant<MappingResult, MappingError> NATPMPRequestPortMap(const CNetAddr &gateway, uint16_t port, uint32_t lifetime, int num_tries, std::chrono::milliseconds timeout_per_try)
275{
276 struct sockaddr_storage dest_addr;
277 socklen_t dest_addrlen = sizeof(struct sockaddr_storage);
278
279 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "natpmp: Requesting port mapping port %d from gateway %s\n", port, gateway.ToStringAddr());
280
281 // Validate gateway, make sure it's IPv4. NAT-PMP does not support IPv6.
282 if (!CService(gateway, PCP_SERVER_PORT).GetSockAddr((struct sockaddr*)&dest_addr, &dest_addrlen)) return MappingError::NETWORK_ERROR;
283 if (dest_addr.ss_family != AF_INET) return MappingError::NETWORK_ERROR;
284
285 // Create IPv4 UDP socket
286 auto sock{CreateSock(AF_INET, SOCK_DGRAM, IPPROTO_UDP)};
287 if (!sock) {
288 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "natpmp: Could not create UDP socket: %s\n", NetworkErrorString(WSAGetLastError()));
290 }
291
292 // Associate UDP socket to gateway.
293 if (sock->Connect((struct sockaddr*)&dest_addr, dest_addrlen) != 0) {
294 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "natpmp: Could not connect to gateway: %s\n", NetworkErrorString(WSAGetLastError()));
296 }
297
298 // Use getsockname to get the address toward the default gateway (the internal address).
299 struct sockaddr_in internal;
300 socklen_t internal_addrlen = sizeof(struct sockaddr_in);
301 if (sock->GetSockName((struct sockaddr*)&internal, &internal_addrlen) != 0) {
302 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "natpmp: Could not get sock name: %s\n", NetworkErrorString(WSAGetLastError()));
304 }
305
306 // Request external IP address (RFC6886 section 3.2).
307 std::vector<uint8_t> request(NATPMP_GETEXTERNAL_REQUEST_SIZE);
308 request[NATPMP_HDR_VERSION_OFS] = NATPMP_VERSION;
309 request[NATPMP_HDR_OP_OFS] = NATPMP_REQUEST | NATPMP_OP_GETEXTERNAL;
310
311 auto recv_res = PCPSendRecv(*sock, "natpmp", request, num_tries, timeout_per_try,
312 [&](const Span<const uint8_t> response) -> bool {
313 if (response.size() < NATPMP_GETEXTERNAL_RESPONSE_SIZE) {
314 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "natpmp: Response too small\n");
315 return false; // Wasn't response to what we expected, try receiving next packet.
316 }
317 if (response[NATPMP_HDR_VERSION_OFS] != NATPMP_VERSION || response[NATPMP_HDR_OP_OFS] != (NATPMP_RESPONSE | NATPMP_OP_GETEXTERNAL)) {
318 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "natpmp: Response to wrong command\n");
319 return false; // Wasn't response to what we expected, try receiving next packet.
320 }
321 return true;
322 });
323
324 struct in_addr external_addr;
325 if (recv_res) {
326 const std::span<const uint8_t> response = *recv_res;
327
328 Assume(response.size() >= NATPMP_GETEXTERNAL_RESPONSE_SIZE);
329 uint16_t result_code = ReadBE16(response.data() + NATPMP_RESPONSE_HDR_RESULT_OFS);
330 if (result_code != NATPMP_RESULT_SUCCESS) {
331 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "natpmp: Getting external address failed with result %s\n", NATPMPResultString(result_code));
333 }
334
335 std::memcpy(&external_addr, response.data() + NATPMP_GETEXTERNAL_RESPONSE_IP_OFS, ADDR_IPV4_SIZE);
336 } else {
338 }
339
340 // Create TCP mapping request (RFC6886 section 3.3).
341 request = std::vector<uint8_t>(NATPMP_MAP_REQUEST_SIZE);
342 request[NATPMP_HDR_VERSION_OFS] = NATPMP_VERSION;
343 request[NATPMP_HDR_OP_OFS] = NATPMP_REQUEST | NATPMP_OP_MAP_TCP;
344 WriteBE16(request.data() + NATPMP_MAP_REQUEST_INTERNAL_PORT_OFS, port);
345 WriteBE16(request.data() + NATPMP_MAP_REQUEST_EXTERNAL_PORT_OFS, port);
346 WriteBE32(request.data() + NATPMP_MAP_REQUEST_LIFETIME_OFS, lifetime);
347
348 recv_res = PCPSendRecv(*sock, "natpmp", request, num_tries, timeout_per_try,
349 [&](const Span<const uint8_t> response) -> bool {
350 if (response.size() < NATPMP_MAP_RESPONSE_SIZE) {
351 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "natpmp: Response too small\n");
352 return false; // Wasn't response to what we expected, try receiving next packet.
353 }
354 if (response[0] != NATPMP_VERSION || response[1] != (NATPMP_RESPONSE | NATPMP_OP_MAP_TCP)) {
355 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "natpmp: Response to wrong command\n");
356 return false; // Wasn't response to what we expected, try receiving next packet.
357 }
358 uint16_t internal_port = ReadBE16(response.data() + NATPMP_MAP_RESPONSE_INTERNAL_PORT_OFS);
359 if (internal_port != port) {
360 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "natpmp: Response port doesn't match request\n");
361 return false; // Wasn't response to what we expected, try receiving next packet.
362 }
363 return true;
364 });
365
366 if (recv_res) {
367 const std::span<uint8_t> response = *recv_res;
368
369 Assume(response.size() >= NATPMP_MAP_RESPONSE_SIZE);
370 uint16_t result_code = ReadBE16(response.data() + NATPMP_RESPONSE_HDR_RESULT_OFS);
371 if (result_code != NATPMP_RESULT_SUCCESS) {
372 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "natpmp: Port mapping failed with result %s\n", NATPMPResultString(result_code));
373 if (result_code == NATPMP_RESULT_NO_RESOURCES) {
375 }
377 }
378
379 uint32_t lifetime_ret = ReadBE32(response.data() + NATPMP_MAP_RESPONSE_LIFETIME_OFS);
380 uint16_t external_port = ReadBE16(response.data() + NATPMP_MAP_RESPONSE_EXTERNAL_PORT_OFS);
381 return MappingResult(NATPMP_VERSION, CService(internal.sin_addr, port), CService(external_addr, external_port), lifetime_ret);
382 } else {
384 }
385}
386
387std::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)
388{
389 struct sockaddr_storage dest_addr, bind_addr;
390 socklen_t dest_addrlen = sizeof(struct sockaddr_storage), bind_addrlen = sizeof(struct sockaddr_storage);
391
392 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "pcp: Requesting port mapping for addr %s port %d from gateway %s\n", bind.ToStringAddr(), port, gateway.ToStringAddr());
393
394 // Validate addresses, make sure they're the same network family.
395 if (!CService(gateway, PCP_SERVER_PORT).GetSockAddr((struct sockaddr*)&dest_addr, &dest_addrlen)) return MappingError::NETWORK_ERROR;
396 if (!CService(bind, 0).GetSockAddr((struct sockaddr*)&bind_addr, &bind_addrlen)) return MappingError::NETWORK_ERROR;
397 if (dest_addr.ss_family != bind_addr.ss_family) return MappingError::NETWORK_ERROR;
398
399 // Create UDP socket (IPv4 or IPv6 based on provided gateway).
400 auto sock{CreateSock(dest_addr.ss_family, SOCK_DGRAM, IPPROTO_UDP)};
401 if (!sock) {
402 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "pcp: Could not create UDP socket: %s\n", NetworkErrorString(WSAGetLastError()));
404 }
405
406 // Make sure that we send from requested destination address, anything else will be
407 // rejected by a security-conscious router.
408 if (sock->Bind((struct sockaddr*)&bind_addr, bind_addrlen) != 0) {
409 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "pcp: Could not bind to address: %s\n", NetworkErrorString(WSAGetLastError()));
411 }
412
413 // Associate UDP socket to gateway.
414 if (sock->Connect((struct sockaddr*)&dest_addr, dest_addrlen) != 0) {
415 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "pcp: Could not connect to gateway: %s\n", NetworkErrorString(WSAGetLastError()));
417 }
418
419 // Use getsockname to get the address toward the default gateway (the internal address),
420 // in case we don't know what address to map
421 // (this is only needed if bind is INADDR_ANY, but it doesn't hurt as an extra check).
422 struct sockaddr_storage internal_addr;
423 socklen_t internal_addrlen = sizeof(struct sockaddr_storage);
424 if (sock->GetSockName((struct sockaddr*)&internal_addr, &internal_addrlen) != 0) {
425 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "pcp: Could not get sock name: %s\n", NetworkErrorString(WSAGetLastError()));
427 }
428 CService internal;
429 if (!internal.SetSockAddr((struct sockaddr*)&internal_addr)) return MappingError::NETWORK_ERROR;
430 LogPrintLevel(BCLog::NET, BCLog::Level::Debug, "pcp: Internal address after connect: %s\n", internal.ToStringAddr());
431
432 // Build request packet. Make sure the packet is zeroed so that reserved fields are zero
433 // as required by the spec (and not potentially leak data).
434 // Make sure there's space for the request header and MAP specific request data.
435 std::vector<uint8_t> request(PCP_HDR_SIZE + PCP_MAP_SIZE);
436 // Fill in request header, See RFC6887 Figure 2.
437 size_t ofs = 0;
438 request[ofs + PCP_HDR_VERSION_OFS] = PCP_VERSION;
439 request[ofs + PCP_HDR_OP_OFS] = PCP_REQUEST | PCP_OP_MAP;
440 WriteBE32(request.data() + ofs + PCP_HDR_LIFETIME_OFS, lifetime);
441 if (!PCPWrapAddress(Span(request).subspan(ofs + PCP_REQUEST_HDR_IP_OFS, ADDR_IPV6_SIZE), internal)) return MappingError::NETWORK_ERROR;
442
443 ofs += PCP_HDR_SIZE;
444
445 // Fill in MAP request packet, See RFC6887 Figure 9.
446 // Randomize mapping nonce (this is repeated in the response, to be able to
447 // correlate requests and responses, and used to authenticate changes to the mapping).
448 std::memcpy(request.data() + ofs + PCP_MAP_NONCE_OFS, nonce.data(), PCP_MAP_NONCE_SIZE);
449 request[ofs + PCP_MAP_PROTOCOL_OFS] = PCP_PROTOCOL_TCP;
450 WriteBE16(request.data() + ofs + PCP_MAP_INTERNAL_PORT_OFS, port);
451 WriteBE16(request.data() + ofs + PCP_MAP_EXTERNAL_PORT_OFS, port);
452 if (!PCPWrapAddress(Span(request).subspan(ofs + PCP_MAP_EXTERNAL_IP_OFS, ADDR_IPV6_SIZE), bind)) return MappingError::NETWORK_ERROR;
453
454 ofs += PCP_MAP_SIZE;
455 Assume(ofs == request.size());
456
457 // Receive loop.
458 bool is_natpmp = false;
459 auto recv_res = PCPSendRecv(*sock, "pcp", request, num_tries, timeout_per_try,
460 [&](const Span<const uint8_t> response) -> bool {
461 // Unsupported version according to RFC6887 appendix A and RFC6886 section 3.5, can fall back to NAT-PMP.
462 if (response.size() == NATPMP_RESPONSE_HDR_SIZE && response[PCP_HDR_VERSION_OFS] == NATPMP_VERSION && response[PCP_RESPONSE_HDR_RESULT_OFS] == NATPMP_RESULT_UNSUPP_VERSION) {
463 is_natpmp = true;
464 return true; // Let it through to caller.
465 }
466 if (response.size() < (PCP_HDR_SIZE + PCP_MAP_SIZE)) {
467 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "pcp: Response too small\n");
468 return false; // Wasn't response to what we expected, try receiving next packet.
469 }
470 if (response[PCP_HDR_VERSION_OFS] != PCP_VERSION || response[PCP_HDR_OP_OFS] != (PCP_RESPONSE | PCP_OP_MAP)) {
471 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "pcp: Response to wrong command\n");
472 return false; // Wasn't response to what we expected, try receiving next packet.
473 }
474 // Handle MAP opcode response. See RFC6887 Figure 10.
475 // Check that returned mapping nonce matches our request.
476 if (!std::ranges::equal(response.subspan(PCP_HDR_SIZE + PCP_MAP_NONCE_OFS, PCP_MAP_NONCE_SIZE), nonce)) {
477 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "pcp: Mapping nonce mismatch\n");
478 return false; // Wasn't response to what we expected, try receiving next packet.
479 }
480 uint8_t protocol = response[PCP_HDR_SIZE + 12];
481 uint16_t internal_port = ReadBE16(response.data() + PCP_HDR_SIZE + 16);
482 if (protocol != PCP_PROTOCOL_TCP || internal_port != port) {
483 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "pcp: Response protocol or port doesn't match request\n");
484 return false; // Wasn't response to what we expected, try receiving next packet.
485 }
486 return true;
487 });
488
489 if (!recv_res) {
491 }
492 if (is_natpmp) {
494 }
495
496 const std::span<const uint8_t> response = *recv_res;
497 // If we get here, we got a valid MAP response to our request.
498 // Check to see if we got the result we expected.
499 Assume(response.size() >= (PCP_HDR_SIZE + PCP_MAP_SIZE));
500 uint8_t result_code = response[PCP_RESPONSE_HDR_RESULT_OFS];
501 uint32_t lifetime_ret = ReadBE32(response.data() + PCP_HDR_LIFETIME_OFS);
502 uint16_t external_port = ReadBE16(response.data() + PCP_HDR_SIZE + PCP_MAP_EXTERNAL_PORT_OFS);
503 CNetAddr external_addr{PCPUnwrapAddress(response.subspan(PCP_HDR_SIZE + PCP_MAP_EXTERNAL_IP_OFS, ADDR_IPV6_SIZE))};
504 if (result_code != PCP_RESULT_SUCCESS) {
505 LogPrintLevel(BCLog::NET, BCLog::Level::Warning, "pcp: Mapping failed with result %s\n", PCPResultString(result_code));
506 if (result_code == PCP_RESULT_NO_RESOURCES) {
508 }
510 }
511
512 return MappingResult(PCP_VERSION, CService(internal, port), CService(external_addr, external_port), lifetime_ret);
513}
514
516{
517 Assume(version == NATPMP_VERSION || version == PCP_VERSION);
518 return strprintf("%s:%s -> %s (for %ds)",
519 version == NATPMP_VERSION ? "natpmp" : "pcp",
523 );
524}
if(!SetupNetworking())
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
Network address.
Definition: netaddress.h:112
std::string ToStringAddr() const
Definition: netaddress.cpp:584
bool GetIn6Addr(struct in6_addr *pipv6Addr) const
Try to get our IPv6 (or CJDNS) address.
Definition: netaddress.cpp:646
bool GetInAddr(struct in_addr *pipv4Addr) const
Try to get our IPv4 address.
Definition: netaddress.cpp:627
bool IsIPv4() const
Definition: netaddress.h:157
bool IsIPv6() const
Definition: netaddress.h:158
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:531
bool SetSockAddr(const struct sockaddr *paddr)
Definition: netaddress.cpp:810
std::string ToStringAddrPort() const
Definition: netaddress.cpp:905
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition: sock.h:27
virtual ssize_t Send(const void *data, size_t len, int flags) const
send(2) wrapper.
Definition: sock.cpp:45
virtual int Bind(const sockaddr *addr, socklen_t addr_len) const
bind(2) wrapper.
Definition: sock.cpp:60
virtual bool Wait(std::chrono::milliseconds timeout, Event requested, Event *occurred=nullptr) const
Wait for readiness for input (recv) or output (send).
Definition: sock.cpp:139
uint8_t Event
Definition: sock.h:138
virtual int GetSockName(sockaddr *name, socklen_t *name_len) const
getsockname(2) wrapper.
Definition: sock.cpp:106
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition: sock.h:143
virtual int Connect(const sockaddr *addr, socklen_t addr_len) const
connect(2) wrapper.
Definition: sock.cpp:55
virtual ssize_t Recv(void *buf, size_t len, int flags) const
recv(2) wrapper.
Definition: sock.cpp:50
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:98
constexpr std::size_t size() const noexcept
Definition: span.h:187
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:195
constexpr C * data() const noexcept
Definition: span.h:174
#define WSAGetLastError()
Definition: compat.h:48
#define MSG_DONTWAIT
Definition: compat.h:112
void WriteBE32(B *ptr, uint32_t x)
Definition: common.h:95
void WriteBE16(B *ptr, uint16_t x)
Definition: common.h:88
uint16_t ReadBE16(const B *ptr)
Definition: common.h:64
uint32_t ReadBE32(const B *ptr)
Definition: common.h:72
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:29
#define LogPrintLevel(category, level,...)
Definition: logging.h:272
unsigned int nonce
Definition: miner_tests.cpp:74
@ NET
Definition: logging.h:43
bool HasPrefix(const T1 &obj, const std::array< uint8_t, PREFIX_LEN > &prefix)
Check whether a container begins with the given prefix.
Definition: string.h:245
static constexpr size_t ADDR_IPV4_SIZE
Size of IPv4 address (in bytes).
Definition: netaddress.h:85
static const std::array< uint8_t, 12 > IPV4_IN_IPV6_PREFIX
Prefix of an IPv6 address when it contains an embedded IPv4 address.
Definition: netaddress.h:61
static constexpr size_t ADDR_IPV6_SIZE
Size of IPv6 address (in bytes).
Definition: netaddress.h:88
std::function< std::unique_ptr< Sock >(int, int, int)> CreateSock
Socket factory.
Definition: netbase.cpp:557
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
constexpr size_t PCP_MAP_NONCE_SIZE
Mapping nonce size in bytes (see RFC6887 section 11.1).
Definition: pcp.h:16
@ PROTOCOL_ERROR
Any kind of protocol-level error, except unsupported version or no resources.
@ NO_RESOURCES
No resources available (port probably already mapped).
@ UNSUPP_VERSION
Unsupported protocol version.
@ NETWORK_ERROR
Any kind of network-level error.
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: sock.cpp:422
Span(T *, EndOrSize) -> Span< T >
Successful response to a port mapping.
Definition: pcp.h:30
CService external
External host:port.
Definition: pcp.h:38
uint32_t lifetime
Granted lifetime of binding (seconds).
Definition: pcp.h:40
CService internal
Internal host:port.
Definition: pcp.h:36
std::string ToString()
Format mapping as string for logging.
Definition: pcp.cpp:515
uint8_t version
Protocol version, one of NATPMP_VERSION or PCP_VERSION.
Definition: pcp.h:34
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172