add NAT-PMP for automatic port mapping and external address discovery

This commit is contained in:
2026-02-09 17:05:24 -03:00
parent 7b47ef155c
commit cf5eb0d5fd
11 changed files with 970 additions and 1 deletions

View File

@@ -52,6 +52,7 @@ const DoSProtection = network.DoSProtection;
const KeyPinStore = network.KeyPinStore;
const PinningMode = network.PinningMode;
const VerifyResult = network.VerifyResult;
const NatPmp = network.NatPmp;
// Protocol components (via module import)
const protocol = @import("protocol");
@@ -1099,6 +1100,68 @@ pub const P2P = struct {
}
}
/// Sentinel observer ID for NAT-PMP discovered addresses (hash of "NAT-PMP")
pub const NAT_PMP_OBSERVER_ID: [32]u8 = [_]u8{
0x4e, 0x41, 0x54, 0x2d, 0x50, 0x4d, 0x50, 0x00, // "NAT-PMP\0"
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
/// Try to discover external address via NAT-PMP and request a port mapping.
/// Returns the external IP if successful, null if NAT-PMP is not available.
pub fn tryNatPmpDiscovery(p2p: *P2P, internal_port: u16, lifetime_seconds: u32) ?[4]u8 {
var nat = NatPmp.init(p2p.allocator) catch |err| {
std.log.debug("NAT-PMP: Gateway discovery failed: {}", .{err});
return null;
};
defer nat.deinit();
// First try to get external address
const external_ip = nat.getExternalAddress() catch |err| {
std.log.debug("NAT-PMP: getExternalAddress failed: {}", .{err});
return null;
} orelse return null;
std.log.info("NAT-PMP: External address is {d}.{d}.{d}.{d}", .{
external_ip[0], external_ip[1], external_ip[2], external_ip[3],
});
// Request port mapping (UDP for P2P)
const mapping = nat.mapPort(.udp, internal_port, internal_port, lifetime_seconds) catch |err| {
std.log.debug("NAT-PMP: mapPort failed: {}", .{err});
// Still return external IP even if mapping fails
p2p.addNatPmpAddress(external_ip, internal_port);
return external_ip;
} orelse {
// Mapping returned null but we have external IP
p2p.addNatPmpAddress(external_ip, internal_port);
return external_ip;
};
std.log.info("NAT-PMP: Mapped port {d} -> external port {d} (lifetime: {d}s)", .{
mapping.internal_port, mapping.external_port, mapping.lifetime_seconds,
});
// Add the mapped address to observed addresses
p2p.addNatPmpAddress(mapping.external_ip, mapping.external_port);
return mapping.external_ip;
}
/// Add an address discovered via NAT-PMP
fn addNatPmpAddress(p2p: *P2P, ip: [4]u8, port: u16) void {
// Encode as DHT address format: 4 bytes IP + 2 bytes port (big-endian)
var addr_bytes: [18]u8 = [_]u8{0} ** 18;
addr_bytes[0] = ip[0];
addr_bytes[1] = ip[1];
addr_bytes[2] = ip[2];
addr_bytes[3] = ip[3];
std.mem.writeInt(u16, addr_bytes[4..6], port, .big);
p2p.addObservedAddress(addr_bytes, 6, NAT_PMP_OBSERVER_ID);
}
/// Get the best observed public address (most recent, public, from multiple observers)
pub fn getObservedPublicAddress(p2p: *P2P) ?ObservedAddress {
p2p.observed_addresses_mutex.lock();