add UPnP IGD for automatic port mapping and external address discovery
This commit is contained in:
@@ -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
758
src/network/upnp.zig
Normal 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(¶ms_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(¶ms_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());
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user