using System; using System.Buffers.Binary; using System.Linq; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; namespace GsDChat.Core.Protocol; /// /// Pure .NET RFC 5389 STUN Binding client for discovering reflexive public UDP endpoints (srflx) /// to enable P2P UDP hole-punching in the C# TUI client without third-party libraries. /// public static class StunClient { public const uint MagicCookie = 0x2112A442; public const ushort BindingRequestType = 0x0001; public const ushort BindingSuccessResponseType = 0x0101; public const ushort AttrMappedAddress = 0x0001; public const ushort AttrXorMappedAddress = 0x0020; public const ushort AttrXorMappedAddressAlt = 0x8020; /// /// Creates a 20-byte RFC 5389 STUN Binding Request packet and outputs the 12-byte transaction ID. /// public static byte[] CreateBindingRequest(out byte[] transactionId) { transactionId = RandomNumberGenerator.GetBytes(12); byte[] packet = new byte[20]; BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(0, 2), BindingRequestType); BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(2, 2), 0); // Message Length = 0 BinaryPrimitives.WriteUInt32BigEndian(packet.AsSpan(4, 4), MagicCookie); Buffer.BlockCopy(transactionId, 0, packet, 8, 12); return packet; } /// /// Builds a valid RFC 5389 STUN Binding Success Response with XOR-MAPPED-ADDRESS (useful for local STUN responder or tests). /// public static byte[] CreateBindingSuccessResponse(ReadOnlySpan transactionId, IPEndPoint reflexiveEndpoint) { if (transactionId.Length != 12) { throw new ArgumentException("Transaction ID must be 12 bytes.", nameof(transactionId)); } byte[] ipBytes = reflexiveEndpoint.Address.GetAddressBytes(); bool isIpv6 = reflexiveEndpoint.Address.AddressFamily == AddressFamily.InterNetworkV6; int attrValueLen = isIpv6 ? 20 : 8; int totalLen = 20 + 4 + attrValueLen; byte[] packet = new byte[totalLen]; BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(0, 2), BindingSuccessResponseType); BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(2, 2), (ushort)(4 + attrValueLen)); BinaryPrimitives.WriteUInt32BigEndian(packet.AsSpan(4, 4), MagicCookie); transactionId.CopyTo(packet.AsSpan(8, 12)); // Attribute header: XOR-MAPPED-ADDRESS (0x0020) BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(20, 2), AttrXorMappedAddress); BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(22, 2), (ushort)attrValueLen); packet[24] = 0; // Reserved packet[25] = (byte)(isIpv6 ? 0x02 : 0x01); ushort xPort = (ushort)(reflexiveEndpoint.Port ^ (ushort)(MagicCookie >> 16)); BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(26, 2), xPort); byte[] cookieBytes = new byte[4]; BinaryPrimitives.WriteUInt32BigEndian(cookieBytes, MagicCookie); if (!isIpv6) { for (int i = 0; i < 4; i++) { packet[28 + i] = (byte)(ipBytes[i] ^ cookieBytes[i]); } } else { for (int i = 0; i < 4; i++) { packet[28 + i] = (byte)(ipBytes[i] ^ cookieBytes[i]); } for (int i = 0; i < 12; i++) { packet[32 + i] = (byte)(ipBytes[4 + i] ^ transactionId[i]); } } return packet; } /// /// Parses a STUN Binding Success Response packet and extracts the reflexive IPEndPoint. /// public static IPEndPoint? ParseBindingResponse(ReadOnlySpan response, ReadOnlySpan expectedTransactionId) { if (response.Length < 20) return null; ushort msgType = BinaryPrimitives.ReadUInt16BigEndian(response.Slice(0, 2)); ushort msgLen = BinaryPrimitives.ReadUInt16BigEndian(response.Slice(2, 2)); uint cookie = BinaryPrimitives.ReadUInt32BigEndian(response.Slice(4, 4)); if (msgType != BindingSuccessResponseType || cookie != MagicCookie) { return null; } if (expectedTransactionId.Length == 12 && !response.Slice(8, 12).SequenceEqual(expectedTransactionId)) { return null; } int offset = 20; int end = Math.Min(response.Length, 20 + msgLen); IPEndPoint? fallbackMapped = null; byte[] cookieBytes = new byte[4]; BinaryPrimitives.WriteUInt32BigEndian(cookieBytes, MagicCookie); while (offset + 4 <= end) { ushort attrType = BinaryPrimitives.ReadUInt16BigEndian(response.Slice(offset, 2)); ushort attrLen = BinaryPrimitives.ReadUInt16BigEndian(response.Slice(offset + 2, 2)); offset += 4; if (offset + attrLen > end) break; var attrVal = response.Slice(offset, attrLen); if ((attrType == AttrXorMappedAddress || attrType == AttrXorMappedAddressAlt) && attrLen >= 8) { byte family = attrVal[1]; ushort xPort = BinaryPrimitives.ReadUInt16BigEndian(attrVal.Slice(2, 2)); int port = xPort ^ (int)(MagicCookie >> 16); if (family == 0x01 && attrLen >= 8) { byte[] ip = new byte[4]; for (int i = 0; i < 4; i++) { ip[i] = (byte)(attrVal[4 + i] ^ cookieBytes[i]); } return new IPEndPoint(new IPAddress(ip), port); } else if (family == 0x02 && attrLen >= 20) { byte[] ip = new byte[16]; for (int i = 0; i < 4; i++) { ip[i] = (byte)(attrVal[4 + i] ^ cookieBytes[i]); } for (int i = 0; i < 12; i++) { ip[4 + i] = (byte)(attrVal[8 + i] ^ response[8 + i]); } return new IPEndPoint(new IPAddress(ip), port); } } else if (attrType == AttrMappedAddress && attrLen >= 8) { byte family = attrVal[1]; int port = BinaryPrimitives.ReadUInt16BigEndian(attrVal.Slice(2, 2)); if (family == 0x01) { byte[] ip = attrVal.Slice(4, 4).ToArray(); fallbackMapped = new IPEndPoint(new IPAddress(ip), port); } } // STUN attributes are padded to 4-byte boundaries int paddedLen = (attrLen + 3) & ~3; offset += paddedLen; } return fallbackMapped; } /// /// Parses a STUN URI (e.g. "stun:stun.cloudflare.com:3478") into host and port. /// public static (string Host, int Port) ParseStunUri(string stunUri) { if (string.IsNullOrWhiteSpace(stunUri)) { return ("stun.cloudflare.com", 3478); } string clean = stunUri.Trim(); if (clean.StartsWith("stun:", StringComparison.OrdinalIgnoreCase)) { clean = clean.Substring(5); } else if (clean.StartsWith("stuns:", StringComparison.OrdinalIgnoreCase)) { clean = clean.Substring(6); } clean = clean.TrimStart('/'); int qIdx = clean.IndexOf('?'); if (qIdx >= 0) clean = clean.Substring(0, qIdx); int colonIdx = clean.LastIndexOf(':'); if (colonIdx > 0 && int.TryParse(clean.Substring(colonIdx + 1), out int port) && port > 0 && port <= 65535) { return (clean.Substring(0, colonIdx), port); } return (clean, 3478); } /// /// Queries a STUN server using the provided UdpClient to discover its public reflexive IP and port. /// public static async Task QueryPublicEndpointAsync(UdpClient udpClient, string stunUri, CancellationToken ct = default) { try { var (host, port) = ParseStunUri(stunUri); IPAddress[] addresses = await Dns.GetHostAddressesAsync(host, ct); var targetIp = addresses.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork) ?? addresses.FirstOrDefault(); if (targetIp == null) return null; var stunEndpoint = new IPEndPoint(targetIp, port); byte[] req = CreateBindingRequest(out byte[] txId); await udpClient.SendAsync(req, stunEndpoint, ct); using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct); timeoutCts.CancelAfter(TimeSpan.FromMilliseconds(1500)); while (!timeoutCts.IsCancellationRequested) { var result = await udpClient.ReceiveAsync(timeoutCts.Token); var parsed = ParseBindingResponse(result.Buffer, txId); if (parsed != null) { return parsed; } } } catch { // STUN unreachable or timed out; caller will fall back to next STUN server or WebSocket relay } return null; } }