26 constexpr uint16_t NATPMP_SERVER_PORT = 5351;
28 constexpr uint8_t NATPMP_VERSION = 0;
30 constexpr uint8_t NATPMP_REQUEST = 0x00;
32 constexpr uint8_t NATPMP_RESPONSE = 0x80;
34 constexpr uint8_t NATPMP_OP_GETEXTERNAL = 0x00;
36 constexpr uint8_t NATPMP_OP_MAP_TCP = 0x02;
38 constexpr
size_t NATPMP_REQUEST_HDR_SIZE = 2;
40 constexpr
size_t NATPMP_RESPONSE_HDR_SIZE = 8;
42 constexpr
size_t NATPMP_GETEXTERNAL_REQUEST_SIZE = NATPMP_REQUEST_HDR_SIZE + 0;
44 constexpr
size_t NATPMP_GETEXTERNAL_RESPONSE_SIZE = NATPMP_RESPONSE_HDR_SIZE + 4;
46 constexpr
size_t NATPMP_MAP_REQUEST_SIZE = NATPMP_REQUEST_HDR_SIZE + 10;
48 constexpr
size_t NATPMP_MAP_RESPONSE_SIZE = NATPMP_RESPONSE_HDR_SIZE + 8;
52 constexpr
size_t NATPMP_HDR_VERSION_OFS = 0;
54 constexpr
size_t NATPMP_HDR_OP_OFS = 1;
56 constexpr
size_t NATPMP_RESPONSE_HDR_RESULT_OFS = 2;
60 constexpr
size_t NATPMP_GETEXTERNAL_RESPONSE_IP_OFS = 8;
64 constexpr
size_t NATPMP_MAP_REQUEST_INTERNAL_PORT_OFS = 4;
66 constexpr
size_t NATPMP_MAP_REQUEST_EXTERNAL_PORT_OFS = 6;
68 constexpr
size_t NATPMP_MAP_REQUEST_LIFETIME_OFS = 8;
72 constexpr
size_t NATPMP_MAP_RESPONSE_INTERNAL_PORT_OFS = 8;
74 constexpr
size_t NATPMP_MAP_RESPONSE_EXTERNAL_PORT_OFS = 10;
76 constexpr
size_t NATPMP_MAP_RESPONSE_LIFETIME_OFS = 12;
80 constexpr uint8_t NATPMP_RESULT_SUCCESS = 0;
82 constexpr uint8_t NATPMP_RESULT_UNSUPP_VERSION = 1;
84 constexpr uint8_t NATPMP_RESULT_NO_RESOURCES = 4;
87 const std::map<uint16_t, std::string> NATPMP_RESULT_STR{
89 {1,
"UNSUPP_VERSION"},
90 {2,
"NOT_AUTHORIZED"},
91 {3,
"NETWORK_FAILURE"},
98 constexpr
size_t PCP_MAX_SIZE = 1100;
100 constexpr uint16_t PCP_SERVER_PORT = NATPMP_SERVER_PORT;
102 constexpr uint8_t PCP_VERSION = 2;
104 constexpr uint8_t PCP_REQUEST = NATPMP_REQUEST;
106 constexpr uint8_t PCP_RESPONSE = NATPMP_RESPONSE;
108 constexpr uint8_t PCP_OP_MAP = 0x01;
110 constexpr uint16_t PCP_PROTOCOL_TCP = 6;
112 constexpr
size_t PCP_HDR_SIZE = 24;
114 constexpr
size_t PCP_MAP_SIZE = 36;
118 constexpr
size_t PCP_HDR_VERSION_OFS = NATPMP_HDR_VERSION_OFS;
120 constexpr
size_t PCP_HDR_OP_OFS = NATPMP_HDR_OP_OFS;
122 constexpr
size_t PCP_HDR_LIFETIME_OFS = 4;
126 constexpr
size_t PCP_REQUEST_HDR_IP_OFS = 8;
130 constexpr
size_t PCP_RESPONSE_HDR_RESULT_OFS = 3;
134 constexpr
size_t PCP_MAP_NONCE_OFS = 0;
136 constexpr
size_t PCP_MAP_PROTOCOL_OFS = 12;
138 constexpr
size_t PCP_MAP_INTERNAL_PORT_OFS = 16;
140 constexpr
size_t PCP_MAP_EXTERNAL_PORT_OFS = 18;
142 constexpr
size_t PCP_MAP_EXTERNAL_IP_OFS = 20;
145 constexpr uint8_t PCP_RESULT_SUCCESS = NATPMP_RESULT_SUCCESS;
147 constexpr uint8_t PCP_RESULT_NO_RESOURCES = 8;
150 const 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"},
168 std::string NATPMPResultString(uint16_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);
175 std::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;
218 std::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())) {
239 auto deadline = cur_time + timeout_per_try;
269 return std::vector<uint8_t>(response, response + recvsz);
274 std::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) {
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) {
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) {
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)) {
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);
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) {
506 if (result_code == PCP_RESULT_NO_RESOURCES) {
517 Assume(version == NATPMP_VERSION || version == PCP_VERSION);
518 return strprintf(
"%s:%s -> %s (for %ds)",
519 version == NATPMP_VERSION ?
"natpmp" :
"pcp",
520 external.ToStringAddrPort(),
521 internal.ToStringAddrPort(),
static time_point now() noexcept
Return current system time or mocked time, if set.
void WriteBE16(B *ptr, uint16_t x)
std::array< uint8_t, PCP_MAP_NONCE_SIZE > PCPMappingNonce
PCP mapping nonce. Arbitrary data chosen by the client to identify a mapping.
uint32_t ReadBE32(const B *ptr)
virtual int Bind(const sockaddr *addr, socklen_t addr_len) const
bind(2) wrapper.
constexpr std::size_t size() const noexcept
static constexpr size_t ADDR_IPV4_SIZE
Size of IPv4 address (in bytes).
memcpy(result.begin(), stream.data(), stream.size())
bool GetInAddr(struct in_addr *pipv4Addr) const
Try to get our IPv4 address.
virtual ssize_t Recv(void *buf, size_t len, int flags) const
recv(2) wrapper.
bool GetIn6Addr(struct in6_addr *pipv6Addr) const
Try to get our IPv6 (or CJDNS) address.
#define WSAGetLastError()
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.
virtual bool Wait(std::chrono::milliseconds timeout, Event requested, Event *occurred=nullptr) const
Wait for readiness for input (recv) or output (send).
Any kind of network-level error.
std::string ToStringAddr() const
uint16_t ReadBE16(const B *ptr)
static constexpr size_t ADDR_IPV6_SIZE
Size of IPv6 address (in bytes).
Any kind of protocol-level error, except unsupported version or no resources.
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
virtual ssize_t Send(const void *data, size_t len, int flags) const
send(2) wrapper.
A combination of a network address (CNetAddr) and a (TCP) port.
bool HasPrefix(const T1 &obj, const std::array< uint8_t, PREFIX_LEN > &prefix)
Check whether a container begins with the given prefix.
#define LogPrintLevel(category, level,...)
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).
#define Assume(val)
Assume is the identity function.
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
void WriteBE32(B *ptr, uint32_t x)
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
constexpr C * data() const noexcept
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
RAII helper class that manages a socket and closes it automatically when it goes out of scope...
static const std::array< uint8_t, 12 > IPV4_IN_IPV6_PREFIX
Prefix of an IPv6 address when it contains an embedded IPv4 address.
std::function< std::unique_ptr< Sock >int, int, int)> CreateSock
Socket factory.
std::string ToString() const
Format mapping as string for logging.
A Span is an object that can refer to a contiguous sequence of objects.
virtual int GetSockName(sockaddr *name, socklen_t *name_len) const
getsockname(2) wrapper.
Unsupported protocol version.
No resources available (port probably already mapped).
Span(T *, EndOrSize) -> Span< T >
virtual int Connect(const sockaddr *addr, socklen_t addr_len) const
connect(2) wrapper.
Successful response to a port mapping.
constexpr size_t PCP_MAP_NONCE_SIZE
Mapping nonce size in bytes (see RFC6887 section 11.1).