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;
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;
60constexpr size_t NATPMP_GETEXTERNAL_RESPONSE_IP_OFS = 8;
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;
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;
80constexpr uint8_t NATPMP_RESULT_SUCCESS = 0;
82constexpr uint8_t NATPMP_RESULT_UNSUPP_VERSION = 1;
84constexpr uint8_t NATPMP_RESULT_NO_RESOURCES = 4;
87const std::map<uint8_t, std::string> NATPMP_RESULT_STR{
89 {1,
"UNSUPP_VERSION"},
90 {2,
"NOT_AUTHORIZED"},
91 {3,
"NETWORK_FAILURE"},
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;
106constexpr uint8_t PCP_RESPONSE = NATPMP_RESPONSE;
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;
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;
126constexpr size_t PCP_REQUEST_HDR_IP_OFS = 8;
130constexpr size_t PCP_RESPONSE_HDR_RESULT_OFS = 3;
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;
145constexpr uint8_t PCP_RESULT_SUCCESS = NATPMP_RESULT_SUCCESS;
147constexpr uint8_t PCP_RESULT_NO_RESOURCES = 8;
150const std::map<uint8_t, std::string> PCP_RESULT_STR{
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"},
160 {9,
"UNSUPP_PROTOCOL"},
161 {10,
"USER_EX_QUOTA"},
162 {11,
"CANNOT_PROVIDE_EXTERNAL"},
163 {12,
"ADDRESS_MISMATCH"},
164 {13,
"EXCESSIVE_REMOTE_PEER"},
168std::string NATPMPResultString(uint8_t result_code)
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);
175std::string PCPResultString(uint8_t result_code)
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);
186 struct in_addr addr4;
187 if (!addr.
GetInAddr(&addr4))
return false;
192 }
else if (addr.
IsIPv6()) {
193 struct in6_addr addr6;
207 struct in_addr addr4;
211 struct in6_addr addr6;
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,
222 using namespace std::chrono;
224 uint8_t response[PCP_MAX_SIZE];
225 bool got_response =
false;
227 for (
int ntry = 0; !got_response && ntry < num_tries; ++ntry) {
232 if (sock.
Send(request.
data(), request.
size(), 0) !=
static_cast<ssize_t
>(request.
size())) {
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) {
269 return std::vector<uint8_t>(response, response + recvsz);
274std::variant<MappingResult, MappingError>
NATPMPRequestPortMap(
const CNetAddr &gateway, uint16_t port, uint32_t lifetime,
int num_tries, std::chrono::milliseconds timeout_per_try)
276 struct sockaddr_storage dest_addr;
277 socklen_t dest_addrlen =
sizeof(
struct sockaddr_storage);
286 auto sock{
CreateSock(AF_INET, SOCK_DGRAM, IPPROTO_UDP)};
293 if (sock->
Connect((
struct sockaddr*)&dest_addr, dest_addrlen) != 0) {
299 struct sockaddr_in internal;
300 socklen_t internal_addrlen =
sizeof(
struct sockaddr_in);
301 if (sock->
GetSockName((
struct sockaddr*)&internal, &internal_addrlen) != 0) {
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;
311 auto recv_res = PCPSendRecv(*sock,
"natpmp", request, num_tries, timeout_per_try,
313 if (response.
size() < NATPMP_GETEXTERNAL_RESPONSE_SIZE) {
314 LogPrintLevel(BCLog::NET, BCLog::Level::Warning,
"natpmp: Response too small\n");
317 if (response[NATPMP_HDR_VERSION_OFS] != NATPMP_VERSION || response[NATPMP_HDR_OP_OFS] != (NATPMP_RESPONSE | NATPMP_OP_GETEXTERNAL)) {
324 struct in_addr external_addr;
326 const std::span<const uint8_t> response = *recv_res;
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) {
335 std::memcpy(&external_addr, response.data() + NATPMP_GETEXTERNAL_RESPONSE_IP_OFS,
ADDR_IPV4_SIZE);
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);
348 recv_res = PCPSendRecv(*sock,
"natpmp", request, num_tries, timeout_per_try,
350 if (response.
size() < NATPMP_MAP_RESPONSE_SIZE) {
351 LogPrintLevel(BCLog::NET, BCLog::Level::Warning,
"natpmp: Response too small\n");
354 if (response[0] != NATPMP_VERSION || response[1] != (NATPMP_RESPONSE | NATPMP_OP_MAP_TCP)) {
358 uint16_t internal_port =
ReadBE16(response.
data() + NATPMP_MAP_RESPONSE_INTERNAL_PORT_OFS);
359 if (internal_port != port) {
367 const std::span<uint8_t> response = *recv_res;
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) {
373 if (result_code == NATPMP_RESULT_NO_RESOURCES) {
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);
389 struct sockaddr_storage dest_addr, bind_addr;
390 socklen_t dest_addrlen =
sizeof(
struct sockaddr_storage), bind_addrlen =
sizeof(
struct sockaddr_storage);
400 auto sock{
CreateSock(dest_addr.ss_family, SOCK_DGRAM, IPPROTO_UDP)};
408 if (sock->
Bind((
struct sockaddr*)&bind_addr, bind_addrlen) != 0) {
414 if (sock->
Connect((
struct sockaddr*)&dest_addr, dest_addrlen) != 0) {
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) {
435 std::vector<uint8_t> request(PCP_HDR_SIZE + PCP_MAP_SIZE);
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);
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);
455 Assume(ofs == request.size());
458 bool is_natpmp =
false;
459 auto recv_res = PCPSendRecv(*sock,
"pcp", request, num_tries, timeout_per_try,
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) {
466 if (response.
size() < (PCP_HDR_SIZE + PCP_MAP_SIZE)) {
467 LogPrintLevel(BCLog::NET, BCLog::Level::Warning,
"pcp: Response too small\n");
470 if (response[PCP_HDR_VERSION_OFS] != PCP_VERSION || response[PCP_HDR_OP_OFS] != (PCP_RESPONSE | PCP_OP_MAP)) {
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) {
496 const std::span<const uint8_t> response = *recv_res;
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);
504 if (result_code != PCP_RESULT_SUCCESS) {
506 if (result_code == PCP_RESULT_NO_RESOURCES) {
518 return strprintf(
"%s:%s -> %s (for %ds)",
519 version == NATPMP_VERSION ?
"natpmp" :
"pcp",
#define Assume(val)
Assume is the identity function.
std::string ToStringAddr() const
bool GetIn6Addr(struct in6_addr *pipv6Addr) const
Try to get our IPv6 (or CJDNS) address.
bool GetInAddr(struct in_addr *pipv4Addr) const
Try to get our IPv4 address.
A combination of a network address (CNetAddr) and a (TCP) port.
bool SetSockAddr(const struct sockaddr *paddr)
std::string ToStringAddrPort() const
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
virtual ssize_t Send(const void *data, size_t len, int flags) const
send(2) wrapper.
virtual int Bind(const sockaddr *addr, socklen_t addr_len) const
bind(2) wrapper.
virtual bool Wait(std::chrono::milliseconds timeout, Event requested, Event *occurred=nullptr) const
Wait for readiness for input (recv) or output (send).
virtual int GetSockName(sockaddr *name, socklen_t *name_len) const
getsockname(2) wrapper.
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
virtual int Connect(const sockaddr *addr, socklen_t addr_len) const
connect(2) wrapper.
virtual ssize_t Recv(void *buf, size_t len, int flags) const
recv(2) wrapper.
A Span is an object that can refer to a contiguous sequence of objects.
constexpr std::size_t size() const noexcept
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
constexpr C * data() const noexcept
#define WSAGetLastError()
void WriteBE32(B *ptr, uint32_t x)
void WriteBE16(B *ptr, uint16_t x)
uint16_t ReadBE16(const B *ptr)
uint32_t ReadBE32(const B *ptr)
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
#define LogPrintLevel(category, level,...)
bool HasPrefix(const T1 &obj, const std::array< uint8_t, PREFIX_LEN > &prefix)
Check whether a container begins with the given prefix.
static constexpr size_t ADDR_IPV4_SIZE
Size of IPv4 address (in bytes).
static const std::array< uint8_t, 12 > IPV4_IN_IPV6_PREFIX
Prefix of an IPv6 address when it contains an embedded IPv4 address.
static constexpr size_t ADDR_IPV6_SIZE
Size of IPv6 address (in bytes).
std::function< std::unique_ptr< Sock >(int, int, int)> CreateSock
Socket factory.
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).
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.
std::array< uint8_t, PCP_MAP_NONCE_SIZE > PCPMappingNonce
PCP mapping nonce. Arbitrary data chosen by the client to identify a mapping.
constexpr size_t PCP_MAP_NONCE_SIZE
Mapping nonce size in bytes (see RFC6887 section 11.1).
@ 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.
Span(T *, EndOrSize) -> Span< T >
Successful response to a port mapping.
CService external
External host:port.
uint32_t lifetime
Granted lifetime of binding (seconds).
CService internal
Internal host:port.
std::string ToString()
Format mapping as string for logging.
uint8_t version
Protocol version, one of NATPMP_VERSION or PCP_VERSION.