//! Mock STUN Server for Testing //! //! Provides a localhost STUN server that responds with XOR-MAPPED-ADDRESS //! to exercise NAT traversal code paths without external dependencies. const std = @import("std"); const posix = std.posix; const mem = std.mem; const Allocator = mem.Allocator; const core = @import("core"); const Address = core.Address; const Socket = core.Socket; pub const STUN_MAGIC_COOKIE: u32 = 0x2112A442; pub const STUN_BINDING_REQUEST: u16 = 0x0001; pub const STUN_BINDING_RESPONSE: u16 = 0x0101; pub const STUN_ATTR_MAPPED_ADDRESS: u16 = 0x0001; pub const STUN_ATTR_XOR_MAPPED_ADDRESS: u16 = 0x0020; pub const STUN_HEADER_SIZE: usize = 20; /// Mock STUN server that responds on localhost pub const MockStunServer = struct { allocator: Allocator, socket: ?*Socket, bound_port: u16, running: std.atomic.Value(bool), thread: ?std.Thread, // Configurable response response_address: Address, should_respond: bool, delay_ms: u32, requests_received: std.atomic.Value(u32), const Self = @This(); pub fn init(allocator: Allocator) Self { return Self{ .allocator = allocator, .socket = null, .bound_port = 0, .running = std.atomic.Value(bool).init(false), .thread = null, .response_address = Address.ipv4(.{ 203, 0, 113, 100 }, 12345), .should_respond = true, .delay_ms = 0, .requests_received = std.atomic.Value(u32).init(0), }; } pub fn deinit(self: *Self) void { self.stop(); if (self.socket) |sock| { sock.deinit(); self.allocator.destroy(sock); self.socket = null; } } /// Set the address to return in XOR-MAPPED-ADDRESS pub fn setResponseAddress(self: *Self, addr: Address) void { self.response_address = addr; } /// Set whether to respond (for timeout testing) pub fn setShouldRespond(self: *Self, should: bool) void { self.should_respond = should; } /// Set response delay in milliseconds pub fn setResponseDelay(self: *Self, delay_ms: u32) void { self.delay_ms = delay_ms; } /// Get number of requests received pub fn getRequestCount(self: *Self) u32 { return self.requests_received.load(.acquire); } /// Start the mock server on a random available port pub fn start(self: *Self) !u16 { const sock = self.allocator.create(Socket) catch return error.OutOfMemory; errdefer self.allocator.destroy(sock); sock.* = Socket.init(.udp, self.allocator) catch return error.SocketError; errdefer sock.deinit(); // Bind to any available port on localhost const bind_addr = Address.ipv4(.{ 127, 0, 0, 1 }, 0); sock.bind(bind_addr) catch return error.BindError; // Get the actual bound port using getsockname var addr_storage: posix.sockaddr.in = std.mem.zeroes(posix.sockaddr.in); var addr_len: posix.socklen_t = @sizeOf(posix.sockaddr.in); posix.getsockname(sock.fd, @ptrCast(&addr_storage), &addr_len) catch return error.BindError; self.bound_port = std.mem.bigToNative(u16, addr_storage.port); if (self.bound_port == 0) { return error.BindError; } self.socket = sock; self.running.store(true, .release); // Start server thread self.thread = std.Thread.spawn(.{}, serverLoop, .{self}) catch return error.ThreadError; return self.bound_port; } /// Stop the mock server pub fn stop(self: *Self) void { self.running.store(false, .release); if (self.thread) |t| { t.join(); self.thread = null; } } /// Get the server address for clients to connect to pub fn getServerAddress(self: *Self) Address { return Address.ipv4(.{ 127, 0, 0, 1 }, self.bound_port); } fn serverLoop(self: *Self) void { var buffer: [512]u8 = undefined; while (self.running.load(.acquire)) { if (self.socket) |sock| { // Use poll to wait for data with 100ms timeout var fds = [1]posix.pollfd{ .{ .fd = sock.fd, .events = posix.POLL.IN, .revents = 0, }, }; const poll_result = posix.poll(&fds, 100) catch 0; if (poll_result > 0 and (fds[0].revents & posix.POLL.IN) != 0) { // Data available const result = sock.receiveFrom(&buffer); if (result) |recv| { _ = self.requests_received.fetchAdd(1, .monotonic); if (self.should_respond) { if (self.delay_ms > 0) { std.Thread.sleep(self.delay_ms * std.time.ns_per_ms); } self.handleRequest(sock, recv.address, buffer[0..recv.size]) catch {}; } } else |_| { // Receive error, continue } } // Timeout or no data, continue loop } else { break; } } } fn handleRequest(self: *Self, sock: *Socket, from: Address, data: []const u8) !void { if (data.len < STUN_HEADER_SIZE) return; // Parse STUN header const msg_type = std.mem.readInt(u16, data[0..2], .big); if (msg_type != STUN_BINDING_REQUEST) return; const magic = std.mem.readInt(u32, data[4..8], .big); if (magic != STUN_MAGIC_COOKIE) return; const transaction_id = data[8..20]; // Build response var response: [64]u8 = undefined; const response_len = self.buildResponse(&response, transaction_id, from); _ = sock.sendTo(response[0..response_len], from) catch {}; } fn buildResponse(self: *Self, buffer: []u8, transaction_id: []const u8, client_addr: Address) usize { // Message type: Binding Response std.mem.writeInt(u16, buffer[0..2], STUN_BINDING_RESPONSE, .big); // Message length (will update later) // std.mem.writeInt(u16, buffer[2..4], 0, .big); // Magic cookie std.mem.writeInt(u32, buffer[4..8], STUN_MAGIC_COOKIE, .big); // Transaction ID @memcpy(buffer[8..20], transaction_id); // Add XOR-MAPPED-ADDRESS attribute var offset: usize = 20; // Attribute type std.mem.writeInt(u16, buffer[offset..][0..2], STUN_ATTR_XOR_MAPPED_ADDRESS, .big); offset += 2; // Attribute length (8 bytes for IPv4) std.mem.writeInt(u16, buffer[offset..][0..2], 8, .big); offset += 2; // Reserved byte + family (IPv4 = 0x01) buffer[offset] = 0; buffer[offset + 1] = 0x01; offset += 2; // XOR'd port (port XOR upper 16 bits of magic cookie) const magic_high: u16 = @truncate(STUN_MAGIC_COOKIE >> 16); const addr_to_use = if (self.response_address.port != 0) self.response_address else client_addr; const xor_port = addr_to_use.port ^ magic_high; std.mem.writeInt(u16, buffer[offset..][0..2], xor_port, .big); offset += 2; // XOR'd address (address XOR magic cookie) const magic_bytes = std.mem.toBytes(std.mem.nativeToBig(u32, STUN_MAGIC_COOKIE)); const addr_bytes = if (addr_to_use.family == .ipv4) addr_to_use.data.ipv4.bytes else [4]u8{ 127, 0, 0, 1 }; buffer[offset] = addr_bytes[0] ^ magic_bytes[0]; buffer[offset + 1] = addr_bytes[1] ^ magic_bytes[1]; buffer[offset + 2] = addr_bytes[2] ^ magic_bytes[2]; buffer[offset + 3] = addr_bytes[3] ^ magic_bytes[3]; offset += 4; // Update message length (excluding header) const attr_len: u16 = @intCast(offset - 20); std.mem.writeInt(u16, buffer[2..4], attr_len, .big); return offset; } }; /// Helper to build a raw STUN binding request for testing pub fn buildStunBindingRequest(buffer: []u8, transaction_id: []const u8) usize { // Message type: Binding Request std.mem.writeInt(u16, buffer[0..2], STUN_BINDING_REQUEST, .big); // Message length: 0 (no attributes) std.mem.writeInt(u16, buffer[2..4], 0, .big); // Magic cookie std.mem.writeInt(u32, buffer[4..8], STUN_MAGIC_COOKIE, .big); // Transaction ID @memcpy(buffer[8..20], transaction_id); return STUN_HEADER_SIZE; } /// Parse XOR-MAPPED-ADDRESS from a STUN response pub fn parseXorMappedAddress(data: []const u8, transaction_id: []const u8) ?Address { if (data.len < STUN_HEADER_SIZE) return null; // Verify magic cookie const magic = std.mem.readInt(u32, data[4..8], .big); if (magic != STUN_MAGIC_COOKIE) return null; // Verify transaction ID matches if (!std.mem.eql(u8, data[8..20], transaction_id)) return null; // Parse attributes var offset: usize = STUN_HEADER_SIZE; const msg_len = std.mem.readInt(u16, data[2..4], .big); const end = STUN_HEADER_SIZE + msg_len; while (offset + 4 <= end and offset + 4 <= data.len) { const attr_type = std.mem.readInt(u16, data[offset..][0..2], .big); const attr_len = std.mem.readInt(u16, data[offset + 2 ..][0..2], .big); offset += 4; if (attr_type == STUN_ATTR_XOR_MAPPED_ADDRESS and attr_len >= 8) { const family = data[offset + 1]; if (family == 0x01) { // IPv4 const xor_port = std.mem.readInt(u16, data[offset + 2 ..][0..2], .big); const magic_high: u16 = @truncate(STUN_MAGIC_COOKIE >> 16); const port = xor_port ^ magic_high; const magic_bytes = std.mem.toBytes(std.mem.nativeToBig(u32, STUN_MAGIC_COOKIE)); var addr_bytes: [4]u8 = undefined; addr_bytes[0] = data[offset + 4] ^ magic_bytes[0]; addr_bytes[1] = data[offset + 5] ^ magic_bytes[1]; addr_bytes[2] = data[offset + 6] ^ magic_bytes[2]; addr_bytes[3] = data[offset + 7] ^ magic_bytes[3]; return Address.ipv4(addr_bytes, port); } } // Move to next attribute (4-byte aligned) offset += (attr_len + 3) & ~@as(usize, 3); } return null; } // ============================================================================ // Tests // ============================================================================ test "MockStunServer: basic start and stop" { var server = MockStunServer.init(std.testing.allocator); defer server.deinit(); const port = try server.start(); try std.testing.expect(port > 0); server.stop(); } test "MockStunServer: responds to STUN request" { var server = MockStunServer.init(std.testing.allocator); defer server.deinit(); const port = try server.start(); // Create client socket var client = Socket.init(.udp, std.testing.allocator) catch return error.SkipZigTest; defer client.deinit(); const server_addr = Address.ipv4(.{ 127, 0, 0, 1 }, port); // Build and send request var request: [64]u8 = undefined; var transaction_id: [12]u8 = undefined; std.crypto.random.bytes(&transaction_id); const req_len = buildStunBindingRequest(&request, &transaction_id); _ = client.sendTo(request[0..req_len], server_addr) catch return error.SkipZigTest; // Wait for response using poll var fds = [1]posix.pollfd{ .{ .fd = client.fd, .events = posix.POLL.IN, .revents = 0 }, }; const poll_result = posix.poll(&fds, 1000) catch return error.SkipZigTest; if (poll_result == 0) return error.SkipZigTest; // Timeout var response: [512]u8 = undefined; const recv = client.receiveFrom(&response) catch return error.SkipZigTest; // Parse response const addr = parseXorMappedAddress(response[0..recv.size], &transaction_id); try std.testing.expect(addr != null); } test "MockStunServer: timeout when should_respond is false" { var server = MockStunServer.init(std.testing.allocator); defer server.deinit(); server.setShouldRespond(false); const port = try server.start(); var client = Socket.init(.udp, std.testing.allocator) catch return error.SkipZigTest; defer client.deinit(); const server_addr = Address.ipv4(.{ 127, 0, 0, 1 }, port); var request: [64]u8 = undefined; var transaction_id: [12]u8 = undefined; std.crypto.random.bytes(&transaction_id); const req_len = buildStunBindingRequest(&request, &transaction_id); _ = client.sendTo(request[0..req_len], server_addr) catch return error.SkipZigTest; // Should timeout - poll should return 0 var fds = [1]posix.pollfd{ .{ .fd = client.fd, .events = posix.POLL.IN, .revents = 0 }, }; const poll_result = posix.poll(&fds, 200) catch 0; try std.testing.expectEqual(@as(usize, 0), poll_result); } test "buildStunBindingRequest: creates valid request" { var buffer: [64]u8 = undefined; const transaction_id = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; const len = buildStunBindingRequest(&buffer, &transaction_id); try std.testing.expectEqual(@as(usize, 20), len); try std.testing.expectEqual(@as(u16, STUN_BINDING_REQUEST), std.mem.readInt(u16, buffer[0..2], .big)); try std.testing.expectEqual(STUN_MAGIC_COOKIE, std.mem.readInt(u32, buffer[4..8], .big)); }