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

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());
}