add UPnP IGD for automatic port mapping and external address discovery

This commit is contained in:
2026-02-09 17:49:44 -03:00
parent cf5eb0d5fd
commit 33730fed8a
13 changed files with 1364 additions and 7 deletions

View File

@@ -78,17 +78,19 @@ zig-p2p is a high-performance, zero-dependency P2P networking library written in
- Large file (>100GB) testing limited
- No built-in compression (application layer concern)
### NAT Traversal (7/10)
### NAT Traversal (8/10)
**Implemented:**
- STUN client for public IP discovery
- NAT-PMP (RFC 6886) - automatic port mapping via 2-packet UDP exchange
- UPnP IGD - SSDP discovery + SOAP port mapping for consumer routers
- IP Reflection - bundled STUN via DHT responses (zero-infrastructure)
- UDP hole punching
- Connection reversal for symmetric NATs
**Limitations:**
- TURN relay not fully implemented
- Some carrier-grade NAT scenarios may fail
- Requires fallback strategy for ~10% of network configurations
- Requires fallback strategy for ~5% of network configurations
### DHT & Discovery (8/10)
@@ -154,9 +156,8 @@ zig-p2p is a high-performance, zero-dependency P2P networking library written in
## Known Limitations
1. **No TCP fallback** - UDP only, some corporate firewalls may block
2. **No UPnP** - Manual port forwarding may be needed
3. **Single-threaded event loop** - By design, but limits single-connection throughput
4. **No streaming API** - Piece-based transfer only
2. **Single-threaded event loop** - By design, but limits single-connection throughput
3. **No streaming API** - Piece-based transfer only
---

View File

@@ -0,0 +1,17 @@
# Peer container for UPnP IGD 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/upnp/peer-test.sh /test.sh
RUN chmod +x /test.sh
WORKDIR /app

View File

@@ -0,0 +1,17 @@
# NAT Router with miniupnpd (UPnP IGD only, NAT-PMP disabled)
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
# UPnP SSDP multicast + HTTP control port
EXPOSE 1900/udp
ENTRYPOINT ["/entrypoint.sh"]

113
docker-tests/upnp/README.md Normal file
View File

@@ -0,0 +1,113 @@
# UPnP IGD Protocol Testing
This directory contains a Docker-based test environment for the UPnP IGD (Internet Gateway Device) implementation.
## Overview
UPnP IGD allows clients behind a NAT to:
1. Discover the gateway via SSDP multicast (239.255.255.250:1900)
2. Fetch the gateway's XML device description
3. Use SOAP to query the external (public) IP address
4. Use SOAP to request port mappings from the NAT gateway
This test uses `miniupnpd` as the UPnP daemon with **NAT-PMP disabled**, so the mwp-demo is forced to use the UPnP IGD path.
## 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` with UPnP IGD enabled, NAT-PMP disabled
- 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/upnp
./run-test.sh
```
## What This Tests
| Component | What's Tested |
|-----------|---------------|
| SSDP discovery | M-SEARCH multicast finds the UPnP gateway |
| XML description | Fetching and parsing the gateway's device XML |
| GetExternalIPAddress | SOAP request to retrieve the public IP |
| AddPortMapping | SOAP request for port forwarding |
| MWP integration | Using UPnP-discovered address in MWP |
| NAT-PMP fallthrough | NAT-PMP fails (disabled), UPnP is tried next |
## Expected Results
### External Address Discovery: PASS
The UPnP implementation discovers the gateway via SSDP, fetches its XML description, and queries the external IP via SOAP.
```
UPnP: External address is 93.184.216.34
Using UPnP IGD: 93.184.216.34:18101
```
### Port Mapping: PARTIAL
Port mapping requests are sent correctly, but miniupnpd may return errors 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.
### NAT-PMP: SKIPPED
NAT-PMP is disabled on the router (`enable_natpmp=no`), so the mwp-demo's NAT-PMP attempt fails silently and falls through to UPnP.
## Files
| File | Purpose |
|------|---------|
| `docker-compose.yml` | Network topology and service definitions |
| `Dockerfile.router` | Router image with miniupnpd (UPnP only) |
| `Dockerfile.peer` | Peer image with mwp-demo binary |
| `router-entrypoint.sh` | Router startup (NAT setup, miniupnpd config with NAT-PMP disabled) |
| `peer-test.sh` | Peer test script |
| `run-test.sh` | Main test orchestrator |
## Troubleshooting
### "miniupnpd not running"
Check router logs:
```bash
docker compose logs router
```
### "UPnP: Gateway discovery failed"
SSDP multicast may not work on all Docker network configurations. Check that the internal bridge network allows multicast traffic.
### "No UPnP messages"
The mwp-demo tries NAT-PMP first. If NAT-PMP somehow succeeds (shouldn't with `enable_natpmp=no`), UPnP will be skipped. Check for `Using NAT-PMP:` in logs.
## See Also
- [UPnP IGD Specification](http://upnp.org/specs/gw/UPnP-gw-WANIPConnection-v1-Service.pdf)
- [miniupnpd](http://miniupnp.free.fr/)
- `src/network/upnp.zig` - Implementation
- `docker-tests/nat-pmp/` - NAT-PMP test (same topology, different protocol)

View File

@@ -0,0 +1,95 @@
# UPnP IGD 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 with UPnP enabled and NAT-PMP disabled.
# Peers discover external address via SSDP multicast + SOAP.
services:
# NAT Router with miniupnpd (UPnP only, no NAT-PMP)
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/upnp/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/upnp/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/upnp/peer-test.sh Executable file
View File

@@ -0,0 +1,25 @@
#!/bin/bash
set -e
echo "=== UPnP IGD 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 UPnP IGD discovery..."
# Run MWP demo (NAT-PMP will fail since it's disabled, then UPnP will be tried)
exec mwp-demo \
--name "$PEER_NAME" \
--port "$PEER_PORT" \
--deterministic \
"$@"

View File

@@ -0,0 +1,66 @@
#!/bin/bash
set -e
echo "=== UPnP IGD 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 UPnP ENABLED and NAT-PMP DISABLED
# This forces peers to use UPnP IGD (SSDP + SOAP) instead of NAT-PMP
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=no
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 "UPnP IGD will listen on $INTERNAL_IF (SSDP multicast + SOAP HTTP)"
echo "NAT-PMP is DISABLED"
# Start miniupnpd in foreground with debug output
exec miniupnpd -d -f /tmp/miniupnpd.conf

143
docker-tests/upnp/run-test.sh Executable file
View File

@@ -0,0 +1,143 @@
#!/bin/bash
# UPnP IGD Integration Test
#
# This test verifies that UPnP IGD works correctly for:
# 1. SSDP multicast discovery of the gateway
# 2. SOAP GetExternalIPAddress
# 3. SOAP AddPortMapping
# 4. Full MWP address discovery through UPnP
#
# NAT-PMP is DISABLED on the router so the mwp-demo falls through to UPnP.
set -e
cd "$(dirname "$0")"
echo "=========================================="
echo " UPnP IGD 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 (UPnP enabled, NAT-PMP disabled)..."
docker compose up -d router
sleep 3
# Check router is running
echo ""
echo "[3/4] Verifying UPnP daemon..."
docker compose exec router pgrep miniupnpd > /dev/null || {
echo "ERROR: miniupnpd not running!"
docker compose logs router
exit 1
}
echo "miniupnpd is running (UPnP mode)"
# 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 UPnP worked for alice
echo ""
echo "Alice's UPnP status:"
docker logs test-peer-a 2>&1 | grep -i "upnp" || echo "(no UPnP messages yet)"
# 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_UPNP=$(docker logs test-peer-a 2>&1 | grep -c "UPnP" || true)
BOB_UPNP=$(docker logs test-peer-b 2>&1 | grep -c "UPnP" || true)
ALICE_NATPMP=$(docker logs test-peer-a 2>&1 | grep -c "Using NAT-PMP:" || true)
BOB_NATPMP=$(docker logs test-peer-b 2>&1 | grep -c "Using NAT-PMP:" || true)
CONNECTION=$(docker logs test-peer-b 2>&1 | grep -c "Connected\|SUCCESS" || true)
echo ""
echo "=========================================="
echo " Summary"
echo "=========================================="
echo "Alice UPnP messages: $ALICE_UPNP"
echo "Bob UPnP messages: $BOB_UPNP"
echo "Alice NAT-PMP used: $([ $ALICE_NATPMP -gt 0 ] && echo 'YES (unexpected!)' || echo 'NO (correct)')"
echo "Bob NAT-PMP used: $([ $BOB_NATPMP -gt 0 ] && echo 'YES (unexpected!)' || echo 'NO (correct)')"
echo "Connection established: $([ $CONNECTION -gt 0 ] && echo 'YES' || echo 'NO')"
# Check for UPnP external address discovery
if docker logs test-peer-a 2>&1 | grep -q "Using UPnP IGD:"; then
echo ""
echo "SUCCESS: UPnP IGD address discovery working!"
EXTERNAL=$(docker logs test-peer-a 2>&1 | grep "Using UPnP IGD:" | head -1)
echo "$EXTERNAL"
else
echo ""
echo "NOTE: UPnP IGD address discovery not confirmed in mwp-demo output"
# Check lower-level UPnP messages
if docker logs test-peer-a 2>&1 | grep -q "UPnP: External address is"; then
echo "But UPnP SOAP GetExternalIPAddress succeeded:"
docker logs test-peer-a 2>&1 | grep "UPnP: External address is" | head -1
fi
fi
# Verify NAT-PMP was NOT used (since it's disabled)
if [ $ALICE_NATPMP -gt 0 ] || [ $BOB_NATPMP -gt 0 ]; then
echo ""
echo "WARNING: NAT-PMP was used despite being disabled on the router!"
echo "This suggests the NAT-PMP disable config is not working correctly."
fi
echo ""
echo "Test complete."

View File

@@ -12,6 +12,7 @@ Comprehensive guide for using the P2P file sharing library. This guide covers tu
- [Best Practices](#best-practices)
- [Performance Optimization](#performance-optimization)
- [Security Considerations](#security-considerations)
- [NAT Traversal](#nat-traversal)
- [Troubleshooting](#troubleshooting)
- [Migration Guide](#migration-guide)
@@ -914,6 +915,49 @@ var p2p_instance = try p2p.P2P.init(allocator, config);
defer p2p_instance.deinit();
```
## NAT Traversal
The library automatically discovers your public address and maps ports through NAT gateways. No manual configuration is needed for most networks — the system tries multiple strategies in order and uses the first one that succeeds.
### Address Discovery Priority
| Priority | Method | Protocol | How It Works |
|----------|--------|----------|-------------|
| 1 | Explicit IP | Manual | `--public-ip` flag (for known static IPs or Docker) |
| 2 | NAT-PMP | RFC 6886 | 2-packet UDP exchange with the gateway on port 5351 |
| 3 | UPnP IGD | SSDP + SOAP | Multicast discovery (239.255.255.250:1900), then HTTP/SOAP for port mapping |
| 4 | IP Reflection | DHT-bundled | Every DHT response includes the requester's observed address (zero-infrastructure STUN) |
Each method both discovers the external IP and requests a port mapping (where applicable). If a method fails (e.g., router doesn't support NAT-PMP), the next one is tried automatically.
### What Happens Automatically
When a P2P node starts and needs to advertise a reachable address (e.g., for MWP hole punching):
1. **NAT-PMP** — Sends a UDP request to the default gateway. If the router supports NAT-PMP (Apple AirPort, many consumer routers), the external IP and port mapping are returned in ~10ms.
2. **UPnP IGD** — If NAT-PMP fails, sends an SSDP M-SEARCH multicast to find UPnP-enabled routers, fetches the XML device description, then uses SOAP to query the external IP and request a port mapping. Works on most consumer routers.
3. **IP Reflection** — If both NAT-PMP and UPnP fail (e.g., on a VPS or network without gateway support), the node learns its public IP from DHT peers. Every DHT response includes an `observed_addr` field containing the sender's view of the requester's IP. Multiple observers build consensus for reliability.
### When You Might Need Manual Configuration
- **Carrier-grade NAT (CGNAT)**: Double-NAT scenarios where your router's "external" IP is still private. Port mapping succeeds but the mapped address isn't publicly reachable.
- **Strict corporate firewalls**: UDP may be blocked entirely. The library is UDP-only (no TCP fallback).
- **Symmetric NAT**: Port mapping works, but hole punching may fail because the NAT assigns different external ports per destination.
In these cases, use `--public-ip` with a known reachable address, or set up a relay node on a public server.
### Implementation Details
| Component | Source File |
|-----------|------------|
| NAT-PMP client | `src/network/nat_pmp.zig` |
| UPnP IGD client | `src/network/upnp.zig` |
| IP Reflection | Built into DHT responses (`src/p2p/dht.zig`) |
| Address discovery orchestration | `src/p2p/p2p.zig` (`tryNatPmpDiscovery`, `tryUpnpDiscovery`) |
| Docker E2E tests | `docker-tests/nat-pmp/`, `docker-tests/upnp/` |
## Troubleshooting
### Common Issues

View File

@@ -303,7 +303,16 @@ pub fn main() !void {
}
}
// Third priority: consensus address from IP Reflection (multi-source)
// Third priority: UPnP IGD (automatic port mapping for most consumer routers)
if (!found_addr) {
if (p2p_node.tryUpnpDiscovery(@intCast(port + 1), 3600)) |external_ip| {
mwp_addrs[0] = mwp.Address.initV4(external_ip, port + 1);
std.debug.print(" Using UPnP IGD: {d}.{d}.{d}.{d}:{d}\n", .{ external_ip[0], external_ip[1], external_ip[2], external_ip[3], port + 1 });
found_addr = true;
}
}
// Fourth priority: consensus address from IP Reflection (multi-source)
if (!found_addr) {
const consensus = p2p_node.getConsensusAddress();
if (consensus.address) |observed| {

View File

@@ -13,6 +13,7 @@ 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 upnp = @import("network/upnp.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");
@@ -73,6 +74,11 @@ pub const NatPmpResultCode = nat_pmp.ResultCode;
pub const NatPmpProtocol = nat_pmp.Protocol;
pub const NatPmpPortMapping = nat_pmp.PortMapping;
// UPnP IGD re-exports
pub const Upnp = upnp.Upnp;
pub const UpnpProtocol = upnp.Protocol;
pub const UpnpPortMapping = upnp.PortMapping;
// TURN integration re-exports
pub const TurnIntegration = turn_integration.TurnIntegration;
pub const ManagedConnection = turn_integration.ManagedConnection;
@@ -114,6 +120,7 @@ test {
_ = network_manager;
_ = nat;
_ = nat_pmp;
_ = upnp;
_ = turn_integration;
_ = dht;
_ = secure_connection;

758
src/network/upnp.zig Normal file
View File

@@ -0,0 +1,758 @@
//! UPnP IGD (Internet Gateway Device) Implementation
//!
//! Discovers UPnP-enabled routers via SSDP multicast and uses SOAP to manage
//! port mappings. Covers most consumer routers (especially Windows-friendly ones
//! and ISP-provided gateways) that don't support NAT-PMP.
//!
//! Protocol flow:
//! 1. SSDP M-SEARCH (UDP multicast) -> discover gateway LOCATION
//! 2. HTTP GET -> fetch XML device description
//! 3. SOAP POST -> call actions (GetExternalIPAddress, AddPortMapping, DeletePortMapping)
//!
//! Usage:
//! ```zig
//! var upnp_client = Upnp.init(allocator) catch |err| {
//! // No UPnP gateway found
//! };
//! defer upnp_client.deinit();
//!
//! const external_ip = try upnp_client.getExternalAddress();
//! const mapping = try upnp_client.mapPort(.udp, 18000, 18000, 3600);
//! ```
const std = @import("std");
const posix = std.posix;
const Allocator = std.mem.Allocator;
/// SSDP multicast address for UPnP discovery
const SSDP_MULTICAST_IP = [4]u8{ 239, 255, 255, 250 };
const SSDP_PORT: u16 = 1900;
/// Search targets for WANIPConnection or WANPPPConnection
const SEARCH_TARGETS = [_][]const u8{
"urn:schemas-upnp-org:service:WANIPConnection:1",
"urn:schemas-upnp-org:service:WANIPConnection:2",
"urn:schemas-upnp-org:service:WANPPPConnection:1",
"urn:schemas-upnp-org:device:InternetGatewayDevice:1",
"urn:schemas-upnp-org:device:InternetGatewayDevice:2",
};
/// Protocol type for port mapping (mirrors NatPmp)
pub const Protocol = enum(u8) {
udp = 1,
tcp = 2,
pub fn toString(self: Protocol) []const u8 {
return switch (self) {
.udp => "UDP",
.tcp => "TCP",
};
}
};
/// Port mapping result (mirrors NatPmp)
pub const PortMapping = struct {
internal_port: u16,
external_port: u16,
lifetime_seconds: u32,
external_ip: [4]u8,
};
/// UPnP IGD client
pub const Upnp = struct {
allocator: Allocator,
control_url: []const u8,
base_url: []const u8,
service_type: []const u8,
gateway_ip: [4]u8,
gateway_port: u16,
/// Discover a UPnP IGD gateway and initialize the client.
/// Returns error if no UPnP gateway is found.
pub fn init(allocator: Allocator) !Upnp {
// Step 1: SSDP discovery
const location = try discoverIgd(allocator);
defer allocator.free(location);
// Step 2: Parse the location URL
const url_info = parseUrl(location) orelse return error.InvalidLocation;
// Step 3: Fetch device description XML
var desc_buf: [8192]u8 = undefined;
const desc_len = try httpRequest(
url_info.ip,
url_info.port,
"GET",
url_info.path,
null,
null,
&desc_buf,
);
if (desc_len == 0) return error.EmptyDescription;
const desc_xml = desc_buf[0..desc_len];
// Step 4: Find the WANIPConnection or WANPPPConnection service control URL
var service_type: []const u8 = undefined;
var relative_control_url: []const u8 = undefined;
// Try each service type
if (findServiceControlUrl(desc_xml, "WANIPConnection")) |result| {
relative_control_url = result.control_url;
service_type = result.service_type;
} else if (findServiceControlUrl(desc_xml, "WANPPPConnection")) |result| {
relative_control_url = result.control_url;
service_type = result.service_type;
} else {
return error.ServiceNotFound;
}
// Build base URL (e.g., "http://192.168.1.1:5000")
var base_buf: [128]u8 = undefined;
const base_str = std.fmt.bufPrint(&base_buf, "http://{d}.{d}.{d}.{d}:{d}", .{
url_info.ip[0], url_info.ip[1], url_info.ip[2], url_info.ip[3], url_info.port,
}) catch return error.BufferOverflow;
// Build full control path - if relative_control_url starts with /, use as-is
// Otherwise, combine with the base path from the location URL
var control_path_buf: [256]u8 = undefined;
const control_path = if (relative_control_url.len > 0 and relative_control_url[0] == '/')
relative_control_url
else blk: {
// Get directory part of location path
const dir_end = if (std.mem.lastIndexOfScalar(u8, url_info.path, '/')) |idx| idx + 1 else 0;
const combined = std.fmt.bufPrint(&control_path_buf, "{s}{s}", .{
url_info.path[0..dir_end], relative_control_url,
}) catch return error.BufferOverflow;
break :blk combined;
};
return .{
.allocator = allocator,
.control_url = try allocator.dupe(u8, control_path),
.base_url = try allocator.dupe(u8, base_str),
.service_type = try allocator.dupe(u8, service_type),
.gateway_ip = url_info.ip,
.gateway_port = url_info.port,
};
}
pub fn deinit(self: *Upnp) void {
self.allocator.free(self.control_url);
self.allocator.free(self.base_url);
self.allocator.free(self.service_type);
}
/// Get the external (public) IP address from the UPnP gateway
pub fn getExternalAddress(self: *Upnp) !?[4]u8 {
var resp_buf: [2048]u8 = undefined;
const resp_len = self.soapAction(
"GetExternalIPAddress",
"",
&resp_buf,
) catch |err| {
std.log.warn("UPnP: GetExternalIPAddress failed: {}", .{err});
return null;
};
if (resp_len == 0) return null;
const response = resp_buf[0..resp_len];
// Extract IP from <NewExternalIPAddress>x.x.x.x</NewExternalIPAddress>
const ip_str = extractXmlTag(response, "NewExternalIPAddress") orelse return null;
const ip = parseIpv4(ip_str) orelse return null;
std.log.info("UPnP: External address is {d}.{d}.{d}.{d}", .{ ip[0], ip[1], ip[2], ip[3] });
return ip;
}
/// Request a port mapping from the UPnP gateway
pub fn mapPort(
self: *Upnp,
protocol_type: Protocol,
internal_port: u16,
external_port: u16,
lifetime_seconds: u32,
) !?PortMapping {
// Get our local IP (the IP the gateway sees us as)
const local_ip = getLocalIp(self.gateway_ip) orelse return null;
var params_buf: [1024]u8 = undefined;
const params = std.fmt.bufPrint(&params_buf,
\\<NewRemoteHost></NewRemoteHost>
\\<NewExternalPort>{d}</NewExternalPort>
\\<NewProtocol>{s}</NewProtocol>
\\<NewInternalPort>{d}</NewInternalPort>
\\<NewInternalClient>{d}.{d}.{d}.{d}</NewInternalClient>
\\<NewEnabled>1</NewEnabled>
\\<NewPortMappingDescription>zig-p2p</NewPortMappingDescription>
\\<NewLeaseDuration>{d}</NewLeaseDuration>
, .{
external_port,
protocol_type.toString(),
internal_port,
local_ip[0], local_ip[1], local_ip[2], local_ip[3],
lifetime_seconds,
}) catch return error.BufferOverflow;
var resp_buf: [2048]u8 = undefined;
const resp_len = self.soapAction(
"AddPortMapping",
params,
&resp_buf,
) catch |err| {
std.log.warn("UPnP: AddPortMapping failed: {}", .{err});
return null;
};
// Check for SOAP fault in response
if (resp_len > 0) {
const response = resp_buf[0..resp_len];
if (std.mem.indexOf(u8, response, "UPnPError") != null) {
if (extractXmlTag(response, "errorDescription")) |desc| {
std.log.warn("UPnP: AddPortMapping error: {s}", .{desc});
}
return null;
}
}
// Get external IP for the result
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("UPnP: Mapped {s} port {d} -> {d}.{d}.{d}.{d}:{d} (lifetime: {d}s)", .{
protocol_type.toString(),
internal_port,
external_ip[0], external_ip[1], external_ip[2], external_ip[3],
external_port,
lifetime_seconds,
});
return PortMapping{
.internal_port = internal_port,
.external_port = external_port,
.lifetime_seconds = lifetime_seconds,
.external_ip = external_ip,
};
}
/// Delete a port mapping
pub fn unmapPort(self: *Upnp, protocol_type: Protocol, external_port: u16) !void {
var params_buf: [512]u8 = undefined;
const params = std.fmt.bufPrint(&params_buf,
\\<NewRemoteHost></NewRemoteHost>
\\<NewExternalPort>{d}</NewExternalPort>
\\<NewProtocol>{s}</NewProtocol>
, .{
external_port,
protocol_type.toString(),
}) catch return error.BufferOverflow;
var resp_buf: [2048]u8 = undefined;
_ = self.soapAction("DeletePortMapping", params, &resp_buf) catch |err| {
std.log.warn("UPnP: DeletePortMapping failed: {}", .{err});
return err;
};
}
/// Check if UPnP IGD is available (try to get external address)
pub fn isAvailable(self: *Upnp) bool {
const result = self.getExternalAddress() catch return false;
return result != null;
}
/// Build and send a SOAP action, return the response body length
fn soapAction(
self: *Upnp,
action: []const u8,
params: []const u8,
resp_buf: []u8,
) !usize {
// Build SOAP envelope
var body_buf: [2048]u8 = undefined;
const body = std.fmt.bufPrint(&body_buf,
\\<?xml version="1.0"?>
\\<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
\\<s:Body>
\\<u:{s} xmlns:u="{s}">
\\{s}
\\</u:{s}>
\\</s:Body>
\\</s:Envelope>
, .{ action, self.service_type, params, action }) catch return error.BufferOverflow;
// Build SOAPAction header value
var soap_action_buf: [256]u8 = undefined;
const soap_action = std.fmt.bufPrint(&soap_action_buf, "\"{s}#{s}\"", .{
self.service_type, action,
}) catch return error.BufferOverflow;
// Build headers
var headers_buf: [512]u8 = undefined;
const headers = std.fmt.bufPrint(&headers_buf,
"Content-Type: text/xml; charset=\"utf-8\"\r\nSOAPAction: {s}",
.{soap_action},
) catch return error.BufferOverflow;
return try httpRequest(
self.gateway_ip,
self.gateway_port,
"POST",
self.control_url,
headers,
body,
resp_buf,
);
}
};
// =============================================================================
// Internal helpers
// =============================================================================
/// SSDP M-SEARCH to discover UPnP IGD gateway. Returns heap-allocated LOCATION URL.
fn discoverIgd(allocator: Allocator) ![]const u8 {
const sock = try posix.socket(posix.AF.INET, posix.SOCK.DGRAM, 0);
defer posix.close(sock);
// Set send/receive timeouts
const timeout = posix.timeval{ .sec = 3, .usec = 0 };
posix.setsockopt(sock, posix.SOL.SOCKET, posix.SO.SNDTIMEO, std.mem.asBytes(&timeout)) catch {};
posix.setsockopt(sock, posix.SOL.SOCKET, posix.SO.RCVTIMEO, std.mem.asBytes(&timeout)) catch {};
const dest_addr = std.net.Address.initIp4(SSDP_MULTICAST_IP, SSDP_PORT);
// Try each search target
for (SEARCH_TARGETS) |st| {
var request_buf: [512]u8 = undefined;
const request = std.fmt.bufPrint(&request_buf,
"M-SEARCH * HTTP/1.1\r\n" ++
"HOST: 239.255.255.250:1900\r\n" ++
"MAN: \"ssdp:discover\"\r\n" ++
"MX: 3\r\n" ++
"ST: {s}\r\n" ++
"\r\n",
.{st},
) catch continue;
_ = posix.sendto(sock, request, 0, &dest_addr.any, dest_addr.getOsSockLen()) catch continue;
}
// Wait for response
var response_buf: [1024]u8 = undefined;
var src_addr: posix.sockaddr.storage = undefined;
var src_len: posix.socklen_t = @sizeOf(posix.sockaddr.storage);
const recv_len = posix.recvfrom(sock, &response_buf, 0, @ptrCast(&src_addr), &src_len) catch {
return error.NoGatewayFound;
};
if (recv_len == 0) return error.NoGatewayFound;
const response = response_buf[0..recv_len];
// Parse LOCATION header (case-insensitive search)
const location = extractHttpHeader(response, "LOCATION") orelse
extractHttpHeader(response, "Location") orelse
extractHttpHeader(response, "location") orelse
return error.NoLocationHeader;
return try allocator.dupe(u8, location);
}
/// Minimal HTTP client - sends request, returns response body length written to buf.
fn httpRequest(
ip: [4]u8,
port: u16,
method: []const u8,
path: []const u8,
extra_headers: ?[]const u8,
body: ?[]const u8,
resp_buf: []u8,
) !usize {
const sock = try posix.socket(posix.AF.INET, posix.SOCK.STREAM, posix.IPPROTO.TCP);
defer posix.close(sock);
// Set connect/read timeouts
const timeout = posix.timeval{ .sec = 5, .usec = 0 };
posix.setsockopt(sock, posix.SOL.SOCKET, posix.SO.SNDTIMEO, std.mem.asBytes(&timeout)) catch {};
posix.setsockopt(sock, posix.SOL.SOCKET, posix.SO.RCVTIMEO, std.mem.asBytes(&timeout)) catch {};
const addr = std.net.Address.initIp4(ip, port);
posix.connect(sock, &addr.any, addr.getOsSockLen()) catch |err| {
std.log.debug("UPnP: HTTP connect failed: {}", .{err});
return error.ConnectionFailed;
};
// Build request
var req_buf: [2048]u8 = undefined;
var req_len: usize = 0;
// Request line
const line = std.fmt.bufPrint(req_buf[req_len..], "{s} {s} HTTP/1.1\r\nHost: {d}.{d}.{d}.{d}:{d}\r\n", .{
method, path, ip[0], ip[1], ip[2], ip[3], port,
}) catch return error.BufferOverflow;
req_len += line.len;
// Extra headers
if (extra_headers) |hdrs| {
const h = std.fmt.bufPrint(req_buf[req_len..], "{s}\r\n", .{hdrs}) catch return error.BufferOverflow;
req_len += h.len;
}
// Content-Length if body present
if (body) |b| {
const cl = std.fmt.bufPrint(req_buf[req_len..], "Content-Length: {d}\r\n", .{b.len}) catch return error.BufferOverflow;
req_len += cl.len;
}
// Close connection after response
const conn_close = "Connection: close\r\n\r\n";
if (req_len + conn_close.len > req_buf.len) return error.BufferOverflow;
@memcpy(req_buf[req_len..][0..conn_close.len], conn_close);
req_len += conn_close.len;
// Send headers
_ = posix.send(sock, req_buf[0..req_len], 0) catch |err| {
std.log.debug("UPnP: HTTP send failed: {}", .{err});
return error.SendFailed;
};
// Send body
if (body) |b| {
_ = posix.send(sock, b, 0) catch |err| {
std.log.debug("UPnP: HTTP body send failed: {}", .{err});
return error.SendFailed;
};
}
// Read response
var total_read: usize = 0;
while (total_read < resp_buf.len) {
const n = posix.recv(sock, resp_buf[total_read..], 0) catch break;
if (n == 0) break;
total_read += n;
}
if (total_read == 0) return error.EmptyResponse;
// Find body start (after \r\n\r\n)
const full_response = resp_buf[0..total_read];
const body_start = if (std.mem.indexOf(u8, full_response, "\r\n\r\n")) |idx| idx + 4 else 0;
// Move body to beginning of buffer
const body_len = total_read - body_start;
if (body_start > 0 and body_len > 0) {
std.mem.copyForwards(u8, resp_buf[0..body_len], full_response[body_start..total_read]);
}
return body_len;
}
/// Extract a header value from an HTTP response
fn extractHttpHeader(response: []const u8, header_name: []const u8) ?[]const u8 {
var lines = std.mem.splitSequence(u8, response, "\r\n");
while (lines.next()) |line| {
if (line.len > header_name.len + 1 and std.ascii.startsWithIgnoreCase(line, header_name)) {
// Check for colon after header name
const after_name = line[header_name.len..];
if (after_name[0] == ':') {
// Skip colon and whitespace
var value = after_name[1..];
while (value.len > 0 and value[0] == ' ') {
value = value[1..];
}
return value;
}
}
}
return null;
}
/// Extract content between XML tags: <tag>content</tag>
/// Simple indexOf-based extraction, no full XML parser needed.
pub fn extractXmlTag(xml: []const u8, tag: []const u8) ?[]const u8 {
// Build "<tag>" and "</tag>"
var open_buf: [64]u8 = undefined;
var close_buf: [64]u8 = undefined;
if (tag.len + 2 > open_buf.len) return null;
const open_tag = std.fmt.bufPrint(&open_buf, "<{s}>", .{tag}) catch return null;
const close_tag = std.fmt.bufPrint(&close_buf, "</{s}>", .{tag}) catch return null;
const start = (std.mem.indexOf(u8, xml, open_tag) orelse return null) + open_tag.len;
const end = std.mem.indexOf(u8, xml[start..], close_tag) orelse return null;
return xml[start..][0..end];
}
/// Service control URL search result
const ServiceResult = struct {
control_url: []const u8,
service_type: []const u8,
};
/// Find the control URL for a WAN*Connection service in UPnP XML description.
/// Returns slices into the input xml buffer.
fn findServiceControlUrl(xml: []const u8, service_needle: []const u8) ?ServiceResult {
// Look for <serviceType> containing the needle
var search_pos: usize = 0;
while (search_pos < xml.len) {
const st_start_tag = "<serviceType>";
const st_end_tag = "</serviceType>";
const type_start = (std.mem.indexOf(u8, xml[search_pos..], st_start_tag) orelse return null) + st_start_tag.len;
const abs_type_start = search_pos + type_start;
const type_end_rel = std.mem.indexOf(u8, xml[abs_type_start..], st_end_tag) orelse return null;
const service_type = xml[abs_type_start..][0..type_end_rel];
// Check if this service type contains our needle
if (std.mem.indexOf(u8, service_type, service_needle) != null) {
// Found the service! Now find the controlURL in the same <service> block.
// Search forward from the serviceType for controlURL
const after_type = abs_type_start + type_end_rel;
const cu_start_tag = "<controlURL>";
const cu_end_tag = "</controlURL>";
// Look within next ~1000 chars for the controlURL
const search_limit = @min(after_type + 1000, xml.len);
const search_slice = xml[after_type..search_limit];
const cu_start = (std.mem.indexOf(u8, search_slice, cu_start_tag) orelse return null) + cu_start_tag.len;
const cu_abs_start = after_type + cu_start;
const cu_end_rel = std.mem.indexOf(u8, xml[cu_abs_start..], cu_end_tag) orelse return null;
return .{
.control_url = xml[cu_abs_start..][0..cu_end_rel],
.service_type = service_type,
};
}
// Move past this serviceType and continue searching
search_pos = abs_type_start + type_end_rel + st_end_tag.len;
}
return null;
}
/// URL parse result - slices or values extracted from a URL string
const UrlInfo = struct {
ip: [4]u8,
port: u16,
path: []const u8,
};
/// Parse "http://ip:port/path" into components
fn parseUrl(url: []const u8) ?UrlInfo {
// Strip "http://" prefix
const after_scheme = if (std.mem.startsWith(u8, url, "http://"))
url[7..]
else
url;
// Find path separator
const path_start = std.mem.indexOfScalar(u8, after_scheme, '/') orelse return null;
const host_port = after_scheme[0..path_start];
const path = after_scheme[path_start..];
// Split host:port
var host: []const u8 = undefined;
var port: u16 = 80;
if (std.mem.indexOfScalar(u8, host_port, ':')) |colon| {
host = host_port[0..colon];
port = std.fmt.parseInt(u16, host_port[colon + 1 ..], 10) catch return null;
} else {
host = host_port;
}
// Parse IP
const ip = parseIpv4(host) orelse return null;
return .{
.ip = ip,
.port = port,
.path = path,
};
}
/// Parse "1.2.3.4" into [4]u8
pub fn parseIpv4(str: []const u8) ?[4]u8 {
var ip: [4]u8 = undefined;
var parts = std.mem.splitScalar(u8, str, '.');
for (0..4) |i| {
const octet = parts.next() orelse return null;
// Trim whitespace
const trimmed = std.mem.trim(u8, octet, &[_]u8{ ' ', '\t', '\r', '\n' });
ip[i] = std.fmt.parseInt(u8, trimmed, 10) catch return null;
}
return ip;
}
/// Get our local IP address facing the gateway (UDP connect trick).
/// Creates a UDP socket, "connects" to the gateway, then reads our bound address.
fn getLocalIp(gateway_ip: [4]u8) ?[4]u8 {
const sock = posix.socket(posix.AF.INET, posix.SOCK.DGRAM, 0) catch return null;
defer posix.close(sock);
const addr = std.net.Address.initIp4(gateway_ip, 80);
posix.connect(sock, &addr.any, addr.getOsSockLen()) catch return null;
var local_addr: posix.sockaddr.storage = undefined;
var addr_len: posix.socklen_t = @sizeOf(posix.sockaddr.storage);
posix.getsockname(sock, @ptrCast(&local_addr), &addr_len) catch return null;
const sa: *const posix.sockaddr.in = @ptrCast(@alignCast(&local_addr));
const addr_bytes: [4]u8 = @bitCast(sa.addr);
return addr_bytes;
}
// =============================================================================
// Case-insensitive string comparison helper
// =============================================================================
/// Check if string starts with prefix (case-insensitive). Zig std doesn't have this.
fn startsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool {
if (haystack.len < needle.len) return false;
for (haystack[0..needle.len], needle) |h, n| {
if (std.ascii.toLower(h) != std.ascii.toLower(n)) return false;
}
return true;
}
// Use std's implementation if available, otherwise our own
const asciiStartsWithIgnoreCase = if (@hasDecl(std.ascii, "startsWithIgnoreCase"))
std.ascii.startsWithIgnoreCase
else
startsWithIgnoreCase;
// =============================================================================
// Tests
// =============================================================================
test "extractXmlTag basic" {
const xml = "<root><NewExternalIPAddress>1.2.3.4</NewExternalIPAddress></root>";
const result = extractXmlTag(xml, "NewExternalIPAddress");
try std.testing.expectEqualStrings("1.2.3.4", result.?);
}
test "extractXmlTag missing" {
const xml = "<root><other>value</other></root>";
try std.testing.expect(extractXmlTag(xml, "missing") == null);
}
test "extractXmlTag nested" {
const xml =
\\<service>
\\<serviceType>urn:schemas-upnp-org:service:WANIPConnection:1</serviceType>
\\<controlURL>/ctl/IPConn</controlURL>
\\</service>
;
const st = extractXmlTag(xml, "serviceType");
try std.testing.expectEqualStrings("urn:schemas-upnp-org:service:WANIPConnection:1", st.?);
const cu = extractXmlTag(xml, "controlURL");
try std.testing.expectEqualStrings("/ctl/IPConn", cu.?);
}
test "parseUrl" {
const result = parseUrl("http://192.168.1.1:5000/rootDesc.xml");
try std.testing.expect(result != null);
const info = result.?;
try std.testing.expectEqual([4]u8{ 192, 168, 1, 1 }, info.ip);
try std.testing.expectEqual(@as(u16, 5000), info.port);
try std.testing.expectEqualStrings("/rootDesc.xml", info.path);
}
test "parseUrl default port" {
const result = parseUrl("http://10.0.0.1/desc.xml");
try std.testing.expect(result != null);
const info = result.?;
try std.testing.expectEqual([4]u8{ 10, 0, 0, 1 }, info.ip);
try std.testing.expectEqual(@as(u16, 80), info.port);
try std.testing.expectEqualStrings("/desc.xml", info.path);
}
test "parseIpv4" {
const ip = parseIpv4("192.168.1.1");
try std.testing.expect(ip != null);
try std.testing.expectEqual([4]u8{ 192, 168, 1, 1 }, ip.?);
}
test "parseIpv4 invalid" {
try std.testing.expect(parseIpv4("not.an.ip") == null);
try std.testing.expect(parseIpv4("256.1.1.1") == null);
try std.testing.expect(parseIpv4("1.2.3") == null);
}
test "parseIpv4 with whitespace" {
const ip = parseIpv4(" 10.0.0.1 ");
try std.testing.expect(ip != null);
try std.testing.expectEqual([4]u8{ 10, 0, 0, 1 }, ip.?);
}
test "findServiceControlUrl" {
const xml =
\\<root>
\\<device>
\\<serviceList>
\\<service>
\\<serviceType>urn:schemas-upnp-org:service:WANIPConnection:1</serviceType>
\\<serviceId>urn:upnp-org:serviceId:WANIPConn1</serviceId>
\\<controlURL>/ctl/IPConn</controlURL>
\\<eventSubURL>/evt/IPConn</eventSubURL>
\\<SCPDURL>/WANIPCn.xml</SCPDURL>
\\</service>
\\</serviceList>
\\</device>
\\</root>
;
const result = findServiceControlUrl(xml, "WANIPConnection");
try std.testing.expect(result != null);
try std.testing.expectEqualStrings("/ctl/IPConn", result.?.control_url);
try std.testing.expect(std.mem.indexOf(u8, result.?.service_type, "WANIPConnection") != null);
}
test "findServiceControlUrl PPP" {
const xml =
\\<service>
\\<serviceType>urn:schemas-upnp-org:service:WANPPPConnection:1</serviceType>
\\<controlURL>/ctl/PPPConn</controlURL>
\\</service>
;
const result = findServiceControlUrl(xml, "WANPPPConnection");
try std.testing.expect(result != null);
try std.testing.expectEqualStrings("/ctl/PPPConn", result.?.control_url);
}
test "findServiceControlUrl not found" {
const xml = "<service><serviceType>other</serviceType></service>";
try std.testing.expect(findServiceControlUrl(xml, "WANIPConnection") == null);
}
test "extractHttpHeader" {
const response = "HTTP/1.1 200 OK\r\nLOCATION: http://192.168.1.1:5000/rootDesc.xml\r\nST: upnp:rootdevice\r\n\r\n";
const location = extractHttpHeader(response, "LOCATION");
try std.testing.expect(location != null);
try std.testing.expectEqualStrings("http://192.168.1.1:5000/rootDesc.xml", location.?);
}
test "extractHttpHeader case insensitive" {
const response = "HTTP/1.1 200 OK\r\nLocation: http://10.0.0.1/desc.xml\r\n\r\n";
const location = extractHttpHeader(response, "Location");
try std.testing.expect(location != null);
try std.testing.expectEqualStrings("http://10.0.0.1/desc.xml", location.?);
}
test "Protocol toString" {
try std.testing.expectEqualStrings("UDP", Protocol.udp.toString());
try std.testing.expectEqualStrings("TCP", Protocol.tcp.toString());
}

View File

@@ -53,6 +53,7 @@ const KeyPinStore = network.KeyPinStore;
const PinningMode = network.PinningMode;
const VerifyResult = network.VerifyResult;
const NatPmp = network.NatPmp;
const Upnp = network.Upnp;
// Protocol components (via module import)
const protocol = @import("protocol");
@@ -1149,6 +1150,67 @@ pub const P2P = struct {
return mapping.external_ip;
}
/// Sentinel observer ID for UPnP IGD discovered addresses (hash of "UPnP-IGD")
pub const UPNP_OBSERVER_ID: [32]u8 = [_]u8{
0x55, 0x50, 0x6e, 0x50, 0x2d, 0x49, 0x47, 0x44, // "UPnP-IGD"
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 UPnP IGD and request a port mapping.
/// Returns the external IP if successful, null if UPnP is not available.
pub fn tryUpnpDiscovery(p2p: *P2P, internal_port: u16, lifetime_seconds: u32) ?[4]u8 {
var upnp_client = Upnp.init(p2p.allocator) catch |err| {
std.log.debug("UPnP: Gateway discovery failed: {}", .{err});
return null;
};
defer upnp_client.deinit();
// First try to get external address
const external_ip = upnp_client.getExternalAddress() catch |err| {
std.log.debug("UPnP: getExternalAddress failed: {}", .{err});
return null;
} orelse return null;
std.log.info("UPnP: 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 = upnp_client.mapPort(.udp, internal_port, internal_port, lifetime_seconds) catch |err| {
std.log.debug("UPnP: mapPort failed: {}", .{err});
// Still return external IP even if mapping fails
p2p.addUpnpAddress(external_ip, internal_port);
return external_ip;
} orelse {
// Mapping returned null but we have external IP
p2p.addUpnpAddress(external_ip, internal_port);
return external_ip;
};
std.log.info("UPnP: 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.addUpnpAddress(mapping.external_ip, mapping.external_port);
return mapping.external_ip;
}
/// Add an address discovered via UPnP IGD
fn addUpnpAddress(p2p: *P2P, ip: [4]u8, port: u16) void {
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, UPNP_OBSERVER_ID);
}
/// 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)