add NAT-PMP for automatic port mapping and external address discovery
This commit is contained in:
17
docker-tests/nat-pmp/Dockerfile.peer
Normal file
17
docker-tests/nat-pmp/Dockerfile.peer
Normal file
@@ -0,0 +1,17 @@
|
||||
# Peer container for NAT-PMP testing
|
||||
# Uses pre-built binary from host (for faster iteration)
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
iproute2 \
|
||||
procps \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Copy pre-built binary (build with: zig build -Doptimize=ReleaseFast -Dtarget=aarch64-linux)
|
||||
COPY zig-out/bin/mwp-demo /usr/local/bin/
|
||||
|
||||
# Test script
|
||||
COPY docker-tests/nat-pmp/peer-test.sh /test.sh
|
||||
RUN chmod +x /test.sh
|
||||
|
||||
WORKDIR /app
|
||||
16
docker-tests/nat-pmp/Dockerfile.router
Normal file
16
docker-tests/nat-pmp/Dockerfile.router
Normal file
@@ -0,0 +1,16 @@
|
||||
# NAT Router with miniupnpd (NAT-PMP + UPnP IGD)
|
||||
FROM alpine:3.19
|
||||
|
||||
RUN apk add --no-cache \
|
||||
miniupnpd \
|
||||
iptables \
|
||||
iproute2 \
|
||||
bash
|
||||
|
||||
# Startup script (generates miniupnpd config dynamically)
|
||||
COPY router-entrypoint.sh /entrypoint.sh
|
||||
RUN chmod +x /entrypoint.sh
|
||||
|
||||
EXPOSE 5351/udp
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
129
docker-tests/nat-pmp/README.md
Normal file
129
docker-tests/nat-pmp/README.md
Normal file
@@ -0,0 +1,129 @@
|
||||
# NAT-PMP Protocol Testing
|
||||
|
||||
This directory contains a Docker-based test environment for the NAT-PMP (RFC 6886) implementation.
|
||||
|
||||
## Overview
|
||||
|
||||
NAT-PMP allows clients behind a NAT to:
|
||||
1. Discover their external (public) IP address
|
||||
2. Request port mappings from the NAT gateway
|
||||
|
||||
This test uses `miniupnpd` as the NAT-PMP daemon running on a simulated router.
|
||||
|
||||
## Network Topology
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ Internal (10.100.0.0/24) │
|
||||
│ │
|
||||
│ ┌─────────┐ ┌─────────┐ ┌───────┐ │
|
||||
│ │ peer-a │ │ peer-b │ │router │ │
|
||||
│ │ .10 │ │ .11 │ │ .1 │ │
|
||||
│ └─────────┘ └─────────┘ └───┬───┘ │
|
||||
└─────────────────────────────────────────────┼──────┘
|
||||
│
|
||||
┌─────────────────────────────────────────────┼──────┐
|
||||
│ External (10.200.0.0/24) │ │
|
||||
│ ┌─────┴────┐ │
|
||||
│ │ router │ │
|
||||
│ │ .1 │ │
|
||||
│ └──────────┘ │
|
||||
└────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
The router:
|
||||
- Runs `miniupnpd` (NAT-PMP + UPnP IGD daemon)
|
||||
- Does NAT (iptables MASQUERADE) for internal clients
|
||||
- Reports a fake "external" IP (93.184.216.34) for testing
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Build Linux binary first (from project root)
|
||||
zig build -Doptimize=ReleaseFast -Dtarget=aarch64-linux
|
||||
|
||||
# Run the test
|
||||
cd docker-tests/nat-pmp
|
||||
./run-test.sh
|
||||
```
|
||||
|
||||
## What This Tests
|
||||
|
||||
| Component | What's Tested |
|
||||
|-----------|---------------|
|
||||
| Gateway discovery | Finding the NAT-PMP daemon on the network |
|
||||
| External address query | Retrieving the public IP from the gateway |
|
||||
| Port mapping request | Requesting a port forwarding rule |
|
||||
| MWP integration | Using NAT-PMP discovered address in MWP |
|
||||
|
||||
## Expected Results
|
||||
|
||||
### External Address Discovery: PASS
|
||||
The NAT-PMP implementation correctly queries miniupnpd and receives the external IP address.
|
||||
|
||||
```
|
||||
info: NAT-PMP: External address is 93.184.216.34
|
||||
Using NAT-PMP: 93.184.216.34:18201
|
||||
```
|
||||
|
||||
### Port Mapping: PARTIAL
|
||||
Port mapping requests are sent correctly, but miniupnpd returns "Network Failure" because:
|
||||
- The fake external IP doesn't match the actual interface
|
||||
- iptables rules can't be created for a non-local address
|
||||
|
||||
This is expected in the Docker test environment. On a real router with NAT-PMP support, port mapping would succeed.
|
||||
|
||||
### Connection: LIMITED
|
||||
Full MWP connection can't complete because:
|
||||
- The fake external IP can't be bound locally
|
||||
- No actual internet routing exists
|
||||
|
||||
The test validates the protocol implementation, not end-to-end connectivity.
|
||||
|
||||
## Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `docker-compose.yml` | Network topology and service definitions |
|
||||
| `Dockerfile.router` | Router image with miniupnpd |
|
||||
| `Dockerfile.peer` | Peer image with mwp-demo binary |
|
||||
| `router-entrypoint.sh` | Router startup (NAT setup, miniupnpd config) |
|
||||
| `peer-test.sh` | Peer test script |
|
||||
| `run-test.sh` | Main test orchestrator |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "miniupnpd not running"
|
||||
Check router logs:
|
||||
```bash
|
||||
docker compose logs router
|
||||
```
|
||||
|
||||
Common issues:
|
||||
- Invalid config options (miniupnpd is picky about format)
|
||||
- Interface detection problems
|
||||
|
||||
### "NAT-PMP: Gateway returned error: Network Failure"
|
||||
This is expected when port mapping fails. External address discovery should still work.
|
||||
|
||||
### "Cannot determine gateway"
|
||||
The NAT-PMP client probes common gateway IPs. Ensure the router is at 10.100.0.1.
|
||||
|
||||
## Real-World Usage
|
||||
|
||||
On a real network with NAT-PMP support (e.g., Apple AirPort, many consumer routers):
|
||||
|
||||
```zig
|
||||
// NAT-PMP is automatically tried during address discovery
|
||||
const external_ip = p2p_node.tryNatPmpDiscovery(18000, 3600);
|
||||
if (external_ip) |ip| {
|
||||
// Port 18000 is now mapped externally
|
||||
std.log.info("External address: {}.{}.{}.{}:18000", .{ip[0], ip[1], ip[2], ip[3]});
|
||||
}
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- [RFC 6886 - NAT-PMP](https://tools.ietf.org/html/rfc6886)
|
||||
- [miniupnpd](http://miniupnp.free.fr/)
|
||||
- `src/network/nat_pmp.zig` - Implementation
|
||||
95
docker-tests/nat-pmp/docker-compose.yml
Normal file
95
docker-tests/nat-pmp/docker-compose.yml
Normal file
@@ -0,0 +1,95 @@
|
||||
# NAT-PMP Test Environment
|
||||
#
|
||||
# Architecture:
|
||||
# ┌─────────────────────────────────────────────────────┐
|
||||
# │ Internal (10.100.0.0/24) │
|
||||
# │ │
|
||||
# │ ┌─────────┐ ┌─────────┐ ┌───────┐ │
|
||||
# │ │ peer-a │ │ peer-b │ │router │ │
|
||||
# │ │ .10 │ │ .11 │ │ .1 │ │
|
||||
# │ └─────────┘ └─────────┘ └───┬───┘ │
|
||||
# └─────────────────────────────────────────────┼──────┘
|
||||
# │
|
||||
# ┌─────────────────────────────────────────────┼──────┐
|
||||
# │ External (10.200.0.0/24) │ │
|
||||
# │ ┌─────┴────┐ │
|
||||
# │ │ router │ │
|
||||
# │ │ .1 │ │
|
||||
# │ └──────────┘ │
|
||||
# └────────────────────────────────────────────────────┘
|
||||
#
|
||||
# The router runs miniupnpd and does NAT for internal clients.
|
||||
# Peers can use NAT-PMP to discover their external address and map ports.
|
||||
|
||||
services:
|
||||
# NAT Router with miniupnpd
|
||||
router:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.router
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
sysctls:
|
||||
- net.ipv4.ip_forward=1
|
||||
networks:
|
||||
internal:
|
||||
ipv4_address: 10.100.0.1
|
||||
external:
|
||||
ipv4_address: 10.200.0.1
|
||||
healthcheck:
|
||||
test: ["CMD", "pgrep", "miniupnpd"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 5
|
||||
|
||||
# Peer A (behind NAT)
|
||||
peer-a:
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: docker-tests/nat-pmp/Dockerfile.peer
|
||||
depends_on:
|
||||
router:
|
||||
condition: service_healthy
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
networks:
|
||||
internal:
|
||||
ipv4_address: 10.100.0.10
|
||||
environment:
|
||||
- PEER_NAME=alice
|
||||
- PEER_PORT=18100
|
||||
- GATEWAY_IP=10.100.0.1
|
||||
command: ["sleep", "infinity"]
|
||||
|
||||
# Peer B (behind NAT)
|
||||
peer-b:
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: docker-tests/nat-pmp/Dockerfile.peer
|
||||
depends_on:
|
||||
router:
|
||||
condition: service_healthy
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
networks:
|
||||
internal:
|
||||
ipv4_address: 10.100.0.11
|
||||
environment:
|
||||
- PEER_NAME=bob
|
||||
- PEER_PORT=18200
|
||||
- GATEWAY_IP=10.100.0.1
|
||||
command: ["sleep", "infinity"]
|
||||
|
||||
networks:
|
||||
internal:
|
||||
driver: bridge
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 10.100.0.0/24
|
||||
gateway: 10.100.0.254
|
||||
external:
|
||||
driver: bridge
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 10.200.0.0/24
|
||||
gateway: 10.200.0.254
|
||||
25
docker-tests/nat-pmp/peer-test.sh
Executable file
25
docker-tests/nat-pmp/peer-test.sh
Executable file
@@ -0,0 +1,25 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
echo "=== NAT-PMP Peer Test ==="
|
||||
echo "Peer: $PEER_NAME"
|
||||
echo "Port: $PEER_PORT"
|
||||
echo "Gateway: $GATEWAY_IP"
|
||||
|
||||
# Set default route through the NAT router
|
||||
echo "Setting default route through NAT router..."
|
||||
ip route del default 2>/dev/null || true
|
||||
ip route add default via $GATEWAY_IP
|
||||
|
||||
echo "Current routes:"
|
||||
ip route
|
||||
|
||||
echo ""
|
||||
echo "Testing NAT-PMP discovery..."
|
||||
|
||||
# Run MWP demo (it will try NAT-PMP automatically)
|
||||
exec mwp-demo \
|
||||
--name "$PEER_NAME" \
|
||||
--port "$PEER_PORT" \
|
||||
--deterministic \
|
||||
"$@"
|
||||
66
docker-tests/nat-pmp/router-entrypoint.sh
Executable file
66
docker-tests/nat-pmp/router-entrypoint.sh
Executable file
@@ -0,0 +1,66 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
echo "=== NAT-PMP Router Starting ==="
|
||||
|
||||
# Wait for interfaces to be ready
|
||||
sleep 1
|
||||
|
||||
# Detect interfaces by IP subnet
|
||||
# Internal network: 10.100.0.0/24, External network: 10.200.0.0/24
|
||||
ETH0_IP=$(ip -4 addr show eth0 | grep 'inet ' | awk '{print $2}' | cut -d'/' -f1)
|
||||
ETH1_IP=$(ip -4 addr show eth1 | grep 'inet ' | awk '{print $2}' | cut -d'/' -f1)
|
||||
|
||||
echo "eth0: $ETH0_IP"
|
||||
echo "eth1: $ETH1_IP"
|
||||
|
||||
# Determine which is internal (10.100.x.x) vs external (10.200.x.x)
|
||||
if echo "$ETH0_IP" | grep -q "^10\.100\."; then
|
||||
INTERNAL_IF="eth0"
|
||||
INTERNAL_IP="$ETH0_IP"
|
||||
EXTERNAL_IF="eth1"
|
||||
EXTERNAL_IP="$ETH1_IP"
|
||||
else
|
||||
INTERNAL_IF="eth1"
|
||||
INTERNAL_IP="$ETH1_IP"
|
||||
EXTERNAL_IF="eth0"
|
||||
EXTERNAL_IP="$ETH0_IP"
|
||||
fi
|
||||
|
||||
echo "Internal interface: $INTERNAL_IF ($INTERNAL_IP)"
|
||||
echo "External interface: $EXTERNAL_IF ($EXTERNAL_IP)"
|
||||
|
||||
# Set up NAT (masquerade internal traffic going out external interface)
|
||||
echo "Setting up NAT..."
|
||||
iptables -t nat -A POSTROUTING -o $EXTERNAL_IF -j MASQUERADE
|
||||
iptables -A FORWARD -i $INTERNAL_IF -o $EXTERNAL_IF -j ACCEPT
|
||||
iptables -A FORWARD -i $EXTERNAL_IF -o $INTERNAL_IF -m state --state RELATED,ESTABLISHED -j ACCEPT
|
||||
|
||||
# Create miniupnpd config with correct interfaces
|
||||
# Note: miniupnpd config format is very specific
|
||||
# ext_ip uses a public-looking IP for testing (doesn't need to route)
|
||||
FAKE_PUBLIC_IP="93.184.216.34" # example.com IP - just needs to look public
|
||||
cat > /tmp/miniupnpd.conf << EOF
|
||||
ext_ifname=$EXTERNAL_IF
|
||||
ext_ip=$FAKE_PUBLIC_IP
|
||||
listening_ip=$INTERNAL_IF
|
||||
enable_natpmp=yes
|
||||
enable_upnp=yes
|
||||
secure_mode=no
|
||||
system_uptime=yes
|
||||
lease_file=/var/lib/miniupnpd/leases
|
||||
allow 1024-65535 10.100.0.0/24 1024-65535
|
||||
EOF
|
||||
|
||||
echo "miniupnpd config:"
|
||||
cat /tmp/miniupnpd.conf
|
||||
|
||||
# Create lease directory
|
||||
mkdir -p /var/lib/miniupnpd
|
||||
|
||||
echo ""
|
||||
echo "Starting miniupnpd..."
|
||||
echo "NAT-PMP will listen on $INTERNAL_IP:5351"
|
||||
|
||||
# Start miniupnpd in foreground with debug output
|
||||
exec miniupnpd -d -f /tmp/miniupnpd.conf
|
||||
125
docker-tests/nat-pmp/run-test.sh
Executable file
125
docker-tests/nat-pmp/run-test.sh
Executable file
@@ -0,0 +1,125 @@
|
||||
#!/bin/bash
|
||||
# NAT-PMP Integration Test
|
||||
#
|
||||
# This test verifies that NAT-PMP works correctly for:
|
||||
# 1. External address discovery
|
||||
# 2. Port mapping
|
||||
# 3. Full MWP connection through NAT
|
||||
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
echo "=========================================="
|
||||
echo " NAT-PMP Integration Test"
|
||||
echo "=========================================="
|
||||
|
||||
# Cleanup function
|
||||
cleanup() {
|
||||
echo ""
|
||||
echo "Cleaning up..."
|
||||
docker compose down -v --remove-orphans 2>/dev/null || true
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
# Build and start
|
||||
echo ""
|
||||
echo "[1/4] Building containers..."
|
||||
docker compose build
|
||||
|
||||
echo ""
|
||||
echo "[2/4] Starting NAT router..."
|
||||
docker compose up -d router
|
||||
sleep 3
|
||||
|
||||
# Check router is running
|
||||
echo ""
|
||||
echo "[3/4] Verifying NAT-PMP daemon..."
|
||||
docker compose exec router pgrep miniupnpd > /dev/null || {
|
||||
echo "ERROR: miniupnpd not running!"
|
||||
docker compose logs router
|
||||
exit 1
|
||||
}
|
||||
echo "miniupnpd is running"
|
||||
|
||||
# Show router state
|
||||
echo ""
|
||||
echo "Router NAT table:"
|
||||
docker compose exec router iptables -t nat -L -n | head -20
|
||||
|
||||
echo ""
|
||||
echo "[4/4] Running peer tests..."
|
||||
|
||||
# Start peer-a in background
|
||||
echo ""
|
||||
echo "--- Starting peer-a (alice) ---"
|
||||
docker compose run -d --name test-peer-a peer-a /test.sh --connect-to bob
|
||||
sleep 2
|
||||
|
||||
# Get alice's DHT ID from logs
|
||||
ALICE_DHT=$(docker logs test-peer-a 2>&1 | grep -o 'DHT Node ID: [0-9a-f]*' | head -1 | cut -d' ' -f4)
|
||||
if [ -z "$ALICE_DHT" ]; then
|
||||
echo "ERROR: Could not get Alice's DHT ID"
|
||||
docker logs test-peer-a
|
||||
exit 1
|
||||
fi
|
||||
echo "Alice DHT ID: $ALICE_DHT"
|
||||
|
||||
# Check if NAT-PMP worked for alice
|
||||
echo ""
|
||||
echo "Alice's NAT-PMP status:"
|
||||
docker logs test-peer-a 2>&1 | grep -i "nat-pmp" || echo "(no NAT-PMP messages)"
|
||||
|
||||
# Start peer-b connecting to alice
|
||||
echo ""
|
||||
echo "--- Starting peer-b (bob) ---"
|
||||
docker compose run --name test-peer-b peer-b /test.sh \
|
||||
--connect-to alice \
|
||||
--bootstrap 10.100.0.10:18100 \
|
||||
--dht-id "$ALICE_DHT" &
|
||||
|
||||
# Wait for connection
|
||||
echo ""
|
||||
echo "Waiting for MWP connection..."
|
||||
sleep 15
|
||||
|
||||
# Check results
|
||||
echo ""
|
||||
echo "=========================================="
|
||||
echo " Test Results"
|
||||
echo "=========================================="
|
||||
|
||||
echo ""
|
||||
echo "--- Alice logs ---"
|
||||
docker logs test-peer-a 2>&1 | tail -30
|
||||
|
||||
echo ""
|
||||
echo "--- Bob logs ---"
|
||||
docker logs test-peer-b 2>&1 | tail -30
|
||||
|
||||
# Check for success indicators
|
||||
ALICE_NATPMP=$(docker logs test-peer-a 2>&1 | grep -c "NAT-PMP:" || true)
|
||||
BOB_NATPMP=$(docker logs test-peer-b 2>&1 | grep -c "NAT-PMP:" || true)
|
||||
CONNECTION=$(docker logs test-peer-b 2>&1 | grep -c "Connected\|SUCCESS" || true)
|
||||
|
||||
echo ""
|
||||
echo "=========================================="
|
||||
echo " Summary"
|
||||
echo "=========================================="
|
||||
echo "Alice NAT-PMP messages: $ALICE_NATPMP"
|
||||
echo "Bob NAT-PMP messages: $BOB_NATPMP"
|
||||
echo "Connection established: $([ $CONNECTION -gt 0 ] && echo 'YES' || echo 'NO')"
|
||||
|
||||
# Check for external address discovery
|
||||
if docker logs test-peer-a 2>&1 | grep -q "Using NAT-PMP:"; then
|
||||
echo ""
|
||||
echo "SUCCESS: NAT-PMP address discovery working!"
|
||||
EXTERNAL=$(docker logs test-peer-a 2>&1 | grep "Using NAT-PMP:" | head -1)
|
||||
echo "$EXTERNAL"
|
||||
else
|
||||
echo ""
|
||||
echo "NOTE: NAT-PMP address discovery not confirmed"
|
||||
echo "(This may be expected if miniupnpd configuration needs adjustment)"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "Test complete."
|
||||
@@ -294,7 +294,16 @@ pub fn main() !void {
|
||||
found_addr = true;
|
||||
}
|
||||
|
||||
// Second priority: consensus address from IP Reflection (multi-source)
|
||||
// Second priority: NAT-PMP (automatic port mapping)
|
||||
if (!found_addr) {
|
||||
if (p2p_node.tryNatPmpDiscovery(@intCast(port + 1), 3600)) |external_ip| {
|
||||
mwp_addrs[0] = mwp.Address.initV4(external_ip, port + 1);
|
||||
std.debug.print(" Using NAT-PMP: {d}.{d}.{d}.{d}:{d}\n", .{ external_ip[0], external_ip[1], external_ip[2], external_ip[3], port + 1 });
|
||||
found_addr = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Third priority: consensus address from IP Reflection (multi-source)
|
||||
if (!found_addr) {
|
||||
const consensus = p2p_node.getConsensusAddress();
|
||||
if (consensus.address) |observed| {
|
||||
|
||||
@@ -12,6 +12,7 @@ pub const routing = @import("network/routing.zig");
|
||||
pub const bridge = @import("network/bridge.zig");
|
||||
pub const network_manager = @import("network/network_manager.zig");
|
||||
pub const nat = @import("network/nat.zig");
|
||||
pub const nat_pmp = @import("network/nat_pmp.zig");
|
||||
pub const turn_integration = @import("network/turn_integration.zig");
|
||||
pub const dht = @import("network/dht.zig");
|
||||
pub const secure_connection = @import("network/secure_connection.zig");
|
||||
@@ -66,6 +67,12 @@ pub const MockStunClient = nat.MockStunClient;
|
||||
pub const MockHolePuncher = nat.MockHolePuncher;
|
||||
pub const MockTurnClient = nat.MockTurnClient;
|
||||
|
||||
// NAT-PMP re-exports
|
||||
pub const NatPmp = nat_pmp.NatPmp;
|
||||
pub const NatPmpResultCode = nat_pmp.ResultCode;
|
||||
pub const NatPmpProtocol = nat_pmp.Protocol;
|
||||
pub const NatPmpPortMapping = nat_pmp.PortMapping;
|
||||
|
||||
// TURN integration re-exports
|
||||
pub const TurnIntegration = turn_integration.TurnIntegration;
|
||||
pub const ManagedConnection = turn_integration.ManagedConnection;
|
||||
@@ -106,6 +113,7 @@ test {
|
||||
_ = bridge;
|
||||
_ = network_manager;
|
||||
_ = nat;
|
||||
_ = nat_pmp;
|
||||
_ = turn_integration;
|
||||
_ = dht;
|
||||
_ = secure_connection;
|
||||
|
||||
416
src/network/nat_pmp.zig
Normal file
416
src/network/nat_pmp.zig
Normal file
@@ -0,0 +1,416 @@
|
||||
//! NAT-PMP (NAT Port Mapping Protocol) Implementation
|
||||
//!
|
||||
//! RFC 6886 - A simple protocol for requesting port mappings from NAT gateways.
|
||||
//! Much simpler than UPnP IGD (2-packet UDP exchange vs 42 packets).
|
||||
//!
|
||||
//! Usage:
|
||||
//! ```zig
|
||||
//! var nat = try NatPmp.init(allocator);
|
||||
//! defer nat.deinit();
|
||||
//!
|
||||
//! // Discover external address
|
||||
//! const external_ip = try nat.getExternalAddress();
|
||||
//!
|
||||
//! // Request a UDP port mapping
|
||||
//! const mapping = try nat.mapPort(.udp, 18000, 18000, 3600);
|
||||
//! // Now external_ip:mapping.external_port maps to our internal port
|
||||
//! ```
|
||||
|
||||
const std = @import("std");
|
||||
const posix = std.posix;
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
/// NAT-PMP protocol port (gateway listens here)
|
||||
const NAT_PMP_PORT: u16 = 5351;
|
||||
|
||||
/// NAT-PMP protocol version
|
||||
const VERSION: u8 = 0;
|
||||
|
||||
/// Opcodes
|
||||
const Opcode = enum(u8) {
|
||||
external_address = 0,
|
||||
map_udp = 1,
|
||||
map_tcp = 2,
|
||||
};
|
||||
|
||||
/// Result codes
|
||||
pub const ResultCode = enum(u16) {
|
||||
success = 0,
|
||||
unsupported_version = 1,
|
||||
not_authorized = 2,
|
||||
network_failure = 3,
|
||||
out_of_resources = 4,
|
||||
unsupported_opcode = 5,
|
||||
_,
|
||||
|
||||
pub fn isSuccess(self: ResultCode) bool {
|
||||
return self == .success;
|
||||
}
|
||||
|
||||
pub fn toString(self: ResultCode) []const u8 {
|
||||
return switch (self) {
|
||||
.success => "Success",
|
||||
.unsupported_version => "Unsupported Version",
|
||||
.not_authorized => "Not Authorized/Refused",
|
||||
.network_failure => "Network Failure",
|
||||
.out_of_resources => "Out of Resources",
|
||||
.unsupported_opcode => "Unsupported Opcode",
|
||||
_ => "Unknown Error",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/// Protocol type for port mapping
|
||||
pub const Protocol = enum(u8) {
|
||||
udp = 1,
|
||||
tcp = 2,
|
||||
};
|
||||
|
||||
/// Port mapping result
|
||||
pub const PortMapping = struct {
|
||||
internal_port: u16,
|
||||
external_port: u16,
|
||||
lifetime_seconds: u32,
|
||||
external_ip: [4]u8,
|
||||
};
|
||||
|
||||
/// NAT-PMP client
|
||||
pub const NatPmp = struct {
|
||||
allocator: Allocator,
|
||||
gateway_ip: [4]u8,
|
||||
socket: ?posix.socket_t,
|
||||
/// Seconds since epoch from gateway (for detecting reboots)
|
||||
gateway_epoch: u32,
|
||||
|
||||
pub fn init(allocator: Allocator) !NatPmp {
|
||||
const gateway = try discoverGateway();
|
||||
|
||||
return .{
|
||||
.allocator = allocator,
|
||||
.gateway_ip = gateway,
|
||||
.socket = null,
|
||||
.gateway_epoch = 0,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn initWithGateway(allocator: Allocator, gateway_ip: [4]u8) NatPmp {
|
||||
return .{
|
||||
.allocator = allocator,
|
||||
.gateway_ip = gateway_ip,
|
||||
.socket = null,
|
||||
.gateway_epoch = 0,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *NatPmp) void {
|
||||
if (self.socket) |sock| {
|
||||
posix.close(sock);
|
||||
self.socket = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the external (public) IP address from the NAT gateway
|
||||
pub fn getExternalAddress(self: *NatPmp) !?[4]u8 {
|
||||
const sock = try self.getSocket();
|
||||
|
||||
// Build request: [version=0, opcode=0]
|
||||
const request = [_]u8{ VERSION, @intFromEnum(Opcode.external_address) };
|
||||
|
||||
// Send to gateway
|
||||
const gateway_addr = std.net.Address.initIp4(self.gateway_ip, NAT_PMP_PORT);
|
||||
_ = posix.sendto(sock, &request, 0, &gateway_addr.any, gateway_addr.getOsSockLen()) catch |err| {
|
||||
std.log.warn("NAT-PMP: Failed to send external address request: {}", .{err});
|
||||
return null;
|
||||
};
|
||||
|
||||
// Receive response (12 bytes)
|
||||
var response: [12]u8 = undefined;
|
||||
var src_addr: posix.sockaddr.storage = undefined;
|
||||
var src_len: posix.socklen_t = @sizeOf(posix.sockaddr.storage);
|
||||
|
||||
// Set timeout
|
||||
const timeout = posix.timeval{ .sec = 3, .usec = 0 };
|
||||
posix.setsockopt(sock, posix.SOL.SOCKET, posix.SO.RCVTIMEO, std.mem.asBytes(&timeout)) catch {};
|
||||
|
||||
const recv_len = posix.recvfrom(sock, &response, 0, @ptrCast(&src_addr), &src_len) catch |err| {
|
||||
std.log.debug("NAT-PMP: No response from gateway ({})", .{err});
|
||||
return null;
|
||||
};
|
||||
|
||||
if (recv_len < 12) {
|
||||
std.log.warn("NAT-PMP: Short response ({} bytes)", .{recv_len});
|
||||
return null;
|
||||
}
|
||||
|
||||
// Parse response
|
||||
const version = response[0];
|
||||
const opcode = response[1];
|
||||
const result_code: ResultCode = @enumFromInt(std.mem.readInt(u16, response[2..4], .big));
|
||||
const epoch = std.mem.readInt(u32, response[4..8], .big);
|
||||
const external_ip = response[8..12].*;
|
||||
|
||||
if (version != VERSION) {
|
||||
std.log.warn("NAT-PMP: Unexpected version {}", .{version});
|
||||
return null;
|
||||
}
|
||||
|
||||
if (opcode != 128 + @intFromEnum(Opcode.external_address)) {
|
||||
std.log.warn("NAT-PMP: Unexpected opcode {}", .{opcode});
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!result_code.isSuccess()) {
|
||||
std.log.warn("NAT-PMP: Gateway returned error: {s}", .{result_code.toString()});
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check for gateway reboot (epoch reset)
|
||||
if (self.gateway_epoch != 0 and epoch < self.gateway_epoch) {
|
||||
std.log.info("NAT-PMP: Gateway rebooted, mappings may be lost", .{});
|
||||
}
|
||||
self.gateway_epoch = epoch;
|
||||
|
||||
std.log.info("NAT-PMP: External address is {d}.{d}.{d}.{d}", .{
|
||||
external_ip[0], external_ip[1], external_ip[2], external_ip[3],
|
||||
});
|
||||
|
||||
return external_ip;
|
||||
}
|
||||
|
||||
/// Request a port mapping from the NAT gateway
|
||||
pub fn mapPort(
|
||||
self: *NatPmp,
|
||||
protocol: Protocol,
|
||||
internal_port: u16,
|
||||
suggested_external_port: u16,
|
||||
lifetime_seconds: u32,
|
||||
) !?PortMapping {
|
||||
const sock = try self.getSocket();
|
||||
|
||||
// Build request (12 bytes)
|
||||
var request: [12]u8 = undefined;
|
||||
request[0] = VERSION;
|
||||
request[1] = @intFromEnum(protocol);
|
||||
request[2] = 0; // Reserved
|
||||
request[3] = 0; // Reserved
|
||||
std.mem.writeInt(u16, request[4..6], internal_port, .big);
|
||||
std.mem.writeInt(u16, request[6..8], suggested_external_port, .big);
|
||||
std.mem.writeInt(u32, request[8..12], lifetime_seconds, .big);
|
||||
|
||||
// Send to gateway
|
||||
const gateway_addr = std.net.Address.initIp4(self.gateway_ip, NAT_PMP_PORT);
|
||||
_ = posix.sendto(sock, &request, 0, &gateway_addr.any, gateway_addr.getOsSockLen()) catch |err| {
|
||||
std.log.warn("NAT-PMP: Failed to send map request: {}", .{err});
|
||||
return null;
|
||||
};
|
||||
|
||||
// Receive response (16 bytes)
|
||||
var response: [16]u8 = undefined;
|
||||
var src_addr: posix.sockaddr.storage = undefined;
|
||||
var src_len: posix.socklen_t = @sizeOf(posix.sockaddr.storage);
|
||||
|
||||
const timeout = posix.timeval{ .sec = 3, .usec = 0 };
|
||||
posix.setsockopt(sock, posix.SOL.SOCKET, posix.SO.RCVTIMEO, std.mem.asBytes(&timeout)) catch {};
|
||||
|
||||
const recv_len = posix.recvfrom(sock, &response, 0, @ptrCast(&src_addr), &src_len) catch |err| {
|
||||
std.log.debug("NAT-PMP: No response from gateway ({})", .{err});
|
||||
return null;
|
||||
};
|
||||
|
||||
if (recv_len < 16) {
|
||||
std.log.warn("NAT-PMP: Short response ({} bytes)", .{recv_len});
|
||||
return null;
|
||||
}
|
||||
|
||||
// Parse response
|
||||
const version = response[0];
|
||||
const opcode = response[1];
|
||||
const result_code: ResultCode = @enumFromInt(std.mem.readInt(u16, response[2..4], .big));
|
||||
const epoch = std.mem.readInt(u32, response[4..8], .big);
|
||||
const resp_internal_port = std.mem.readInt(u16, response[8..10], .big);
|
||||
const mapped_external_port = std.mem.readInt(u16, response[10..12], .big);
|
||||
const actual_lifetime = std.mem.readInt(u32, response[12..16], .big);
|
||||
|
||||
if (version != VERSION) {
|
||||
std.log.warn("NAT-PMP: Unexpected version {}", .{version});
|
||||
return null;
|
||||
}
|
||||
|
||||
const expected_opcode = 128 + @intFromEnum(protocol);
|
||||
if (opcode != expected_opcode) {
|
||||
std.log.warn("NAT-PMP: Unexpected opcode {} (expected {})", .{ opcode, expected_opcode });
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!result_code.isSuccess()) {
|
||||
std.log.warn("NAT-PMP: Gateway returned error: {s}", .{result_code.toString()});
|
||||
return null;
|
||||
}
|
||||
|
||||
self.gateway_epoch = epoch;
|
||||
|
||||
// Get external IP (need to query separately or use cached)
|
||||
const external_ip: [4]u8 = blk: {
|
||||
const maybe_ip = self.getExternalAddress() catch null;
|
||||
break :blk maybe_ip orelse [_]u8{ 0, 0, 0, 0 };
|
||||
};
|
||||
|
||||
std.log.info("NAT-PMP: Mapped {s} port {d} -> {d}.{d}.{d}.{d}:{d} (lifetime: {d}s)", .{
|
||||
if (protocol == .udp) "UDP" else "TCP",
|
||||
resp_internal_port,
|
||||
external_ip[0],
|
||||
external_ip[1],
|
||||
external_ip[2],
|
||||
external_ip[3],
|
||||
mapped_external_port,
|
||||
actual_lifetime,
|
||||
});
|
||||
|
||||
return PortMapping{
|
||||
.internal_port = resp_internal_port,
|
||||
.external_port = mapped_external_port,
|
||||
.lifetime_seconds = actual_lifetime,
|
||||
.external_ip = external_ip,
|
||||
};
|
||||
}
|
||||
|
||||
/// Delete a port mapping (set lifetime to 0)
|
||||
pub fn unmapPort(self: *NatPmp, protocol: Protocol, internal_port: u16) !void {
|
||||
_ = try self.mapPort(protocol, internal_port, 0, 0);
|
||||
}
|
||||
|
||||
/// Check if NAT-PMP is available on this network
|
||||
pub fn isAvailable(self: *NatPmp) bool {
|
||||
const result = self.getExternalAddress() catch return false;
|
||||
return result != null;
|
||||
}
|
||||
|
||||
fn getSocket(self: *NatPmp) !posix.socket_t {
|
||||
if (self.socket) |sock| {
|
||||
return sock;
|
||||
}
|
||||
|
||||
const sock = try posix.socket(posix.AF.INET, posix.SOCK.DGRAM, 0);
|
||||
self.socket = sock;
|
||||
return sock;
|
||||
}
|
||||
};
|
||||
|
||||
/// Discover the default gateway IP address
|
||||
pub fn discoverGateway() ![4]u8 {
|
||||
// Platform-specific gateway discovery
|
||||
if (@import("builtin").os.tag == .macos or @import("builtin").os.tag == .ios) {
|
||||
return discoverGatewayDarwin();
|
||||
} else if (@import("builtin").os.tag == .linux) {
|
||||
return discoverGatewayLinux();
|
||||
} else {
|
||||
return error.UnsupportedPlatform;
|
||||
}
|
||||
}
|
||||
|
||||
fn discoverGatewayDarwin() ![4]u8 {
|
||||
// On macOS, use route command or read from sysctl
|
||||
// For now, try common gateway addresses
|
||||
const common_gateways = [_][4]u8{
|
||||
.{ 192, 168, 1, 1 },
|
||||
.{ 192, 168, 0, 1 },
|
||||
.{ 10, 0, 0, 1 },
|
||||
.{ 172, 16, 0, 1 },
|
||||
};
|
||||
|
||||
for (common_gateways) |gw| {
|
||||
// Try to reach the gateway
|
||||
const sock = posix.socket(posix.AF.INET, posix.SOCK.DGRAM, 0) catch continue;
|
||||
defer posix.close(sock);
|
||||
|
||||
const addr = std.net.Address.initIp4(gw, NAT_PMP_PORT);
|
||||
|
||||
// Non-blocking connect just to check reachability
|
||||
const timeout = posix.timeval{ .sec = 1, .usec = 0 };
|
||||
posix.setsockopt(sock, posix.SOL.SOCKET, posix.SO.SNDTIMEO, std.mem.asBytes(&timeout)) catch {};
|
||||
|
||||
// Send a probe
|
||||
const probe = [_]u8{ 0, 0 }; // External address request
|
||||
_ = posix.sendto(sock, &probe, 0, &addr.any, addr.getOsSockLen()) catch continue;
|
||||
|
||||
// Try to receive
|
||||
posix.setsockopt(sock, posix.SOL.SOCKET, posix.SO.RCVTIMEO, std.mem.asBytes(&timeout)) catch {};
|
||||
|
||||
var response: [16]u8 = undefined;
|
||||
var src_addr: posix.sockaddr.storage = undefined;
|
||||
var src_len: posix.socklen_t = @sizeOf(posix.sockaddr.storage);
|
||||
|
||||
if (posix.recvfrom(sock, &response, 0, @ptrCast(&src_addr), &src_len)) |len| {
|
||||
if (len >= 12 and response[0] == 0 and response[1] == 128) {
|
||||
std.log.info("NAT-PMP: Found gateway at {d}.{d}.{d}.{d}", .{ gw[0], gw[1], gw[2], gw[3] });
|
||||
return gw;
|
||||
}
|
||||
} else |_| {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: assume common gateway
|
||||
return .{ 192, 168, 1, 1 };
|
||||
}
|
||||
|
||||
fn discoverGatewayLinux() ![4]u8 {
|
||||
// On Linux, read /proc/net/route
|
||||
const file = std.fs.openFileAbsolute("/proc/net/route", .{}) catch {
|
||||
return .{ 192, 168, 1, 1 }; // Fallback
|
||||
};
|
||||
defer file.close();
|
||||
|
||||
var buf: [4096]u8 = undefined;
|
||||
const bytes_read = file.readAll(&buf) catch return .{ 192, 168, 1, 1 };
|
||||
|
||||
var lines = std.mem.splitScalar(u8, buf[0..bytes_read], '\n');
|
||||
_ = lines.next(); // Skip header
|
||||
|
||||
while (lines.next()) |line| {
|
||||
var fields = std.mem.splitScalar(u8, line, '\t');
|
||||
_ = fields.next(); // Interface name
|
||||
const dest = fields.next() orelse continue;
|
||||
const gateway = fields.next() orelse continue;
|
||||
|
||||
// Check if destination is 0.0.0.0 (default route)
|
||||
if (std.mem.eql(u8, dest, "00000000")) {
|
||||
// Parse gateway (hex, little-endian on x86)
|
||||
const gw_int = std.fmt.parseInt(u32, gateway, 16) catch continue;
|
||||
return .{
|
||||
@truncate(gw_int),
|
||||
@truncate(gw_int >> 8),
|
||||
@truncate(gw_int >> 16),
|
||||
@truncate(gw_int >> 24),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return .{ 192, 168, 1, 1 }; // Fallback
|
||||
}
|
||||
|
||||
// Tests
|
||||
test "NatPmp packet format" {
|
||||
// External address request
|
||||
const request = [_]u8{ 0, 0 };
|
||||
try std.testing.expectEqual(@as(u8, 0), request[0]); // Version
|
||||
try std.testing.expectEqual(@as(u8, 0), request[1]); // Opcode
|
||||
|
||||
// Port mapping request
|
||||
var map_request: [12]u8 = undefined;
|
||||
map_request[0] = 0; // Version
|
||||
map_request[1] = 1; // Opcode (UDP)
|
||||
map_request[2] = 0; // Reserved
|
||||
map_request[3] = 0; // Reserved
|
||||
std.mem.writeInt(u16, map_request[4..6], 8080, .big);
|
||||
std.mem.writeInt(u16, map_request[6..8], 8080, .big);
|
||||
std.mem.writeInt(u32, map_request[8..12], 3600, .big);
|
||||
|
||||
try std.testing.expectEqual(@as(u16, 8080), std.mem.readInt(u16, map_request[4..6], .big));
|
||||
}
|
||||
|
||||
test "ResultCode" {
|
||||
try std.testing.expect(ResultCode.success.isSuccess());
|
||||
try std.testing.expect(!ResultCode.not_authorized.isSuccess());
|
||||
try std.testing.expectEqualStrings("Success", ResultCode.success.toString());
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user