ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
nat.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define DISCOVERY_NAT_PORT_BUFFER_SIZE 16
9
10/* Existing buffer budgets in bytes, including NUL for text storage. */
11#define STUN_BINDING_HEADER_SIZE 20
12#define STUN_PROBE_RESPONSE_BUFFER_SIZE 512
13
15#include "nat.h"
16
17#include <ascii-chat/common.h>
19#include <ascii-chat/log/log.h>
21#include <libplatform/compiler.h>
22#include <libplatform/system.h>
23#include <libplatform/terminal.h>
24#include <libplatform/socket.h>
25#include <ascii-chat/util/ip.h>
27
28#include <string.h>
29#ifndef _WIN32
30#include <netdb.h>
31#endif
32#include <stdio.h>
33#include <errno.h>
34#include <limits.h>
35
36// Bandwidth override threshold: 10x difference can override NAT priority
37#define BANDWIDTH_OVERRIDE_RATIO 10
38
40 if (!quality)
41 return;
42 memset(quality, 0, sizeof(nat_quality_t));
43 quality->nat_type = ACIP_NAT_TYPE_SYMMETRIC; // Assume worst case
44}
45
46int nat_compute_tier(const nat_quality_t *quality) {
47 if (!quality)
48 return 4;
49
50 if (quality->lan_reachable)
51 return 0; // LAN - best
52 if (quality->has_public_ip)
53 return 1; // Public IP
54 if (quality->upnp_available)
55 return 2; // UPnP mapping
56 if (quality->nat_type <= ACIP_NAT_TYPE_RESTRICTED)
57 return 3; // STUN hole-punchable
58 return 4; // TURN relay required
59}
60
61int nat_compare_quality(const nat_quality_t *ours, const nat_quality_t *theirs, bool we_are_initiator) {
62 if (!ours || !theirs) {
63 return we_are_initiator ? -1 : 1;
64 }
65
66 int our_tier = nat_compute_tier(ours);
67 int their_tier = nat_compute_tier(theirs);
68
69 // Check for bandwidth override: massive bandwidth advantage can override NAT tier
70 if (ours->upload_kbps > 0 && theirs->upload_kbps > 0) {
72 log_debug("NAT compare: we win by bandwidth override (%u vs %u kbps)", ours->upload_kbps, theirs->upload_kbps);
73 return -1;
74 }
76 log_debug("NAT compare: they win by bandwidth override (%u vs %u kbps)", theirs->upload_kbps, ours->upload_kbps);
77 return 1;
78 }
79 }
80
81 // Compare NAT tiers (lower = better)
82 if (our_tier < their_tier) {
83 log_debug("NAT compare: we win by tier (%d vs %d)", our_tier, their_tier);
84 return -1;
85 }
86 if (our_tier > their_tier) {
87 log_debug("NAT compare: they win by tier (%d vs %d)", our_tier, their_tier);
88 return 1;
89 }
90
91 // Same tier - bandwidth is tiebreaker
92 if (ours->upload_kbps > theirs->upload_kbps) {
93 log_debug("NAT compare: we win by bandwidth (%u vs %u kbps)", ours->upload_kbps, theirs->upload_kbps);
94 return -1;
95 }
96 if (ours->upload_kbps < theirs->upload_kbps) {
97 log_debug("NAT compare: they win by bandwidth (%u vs %u kbps)", theirs->upload_kbps, ours->upload_kbps);
98 return 1;
99 }
100
101 // Same bandwidth - latency is tiebreaker
102 if (ours->rtt_to_acds_ns < theirs->rtt_to_acds_ns) {
103 log_debug("NAT compare: we win by latency (%lu ns vs %lu ns)", ours->rtt_to_acds_ns, theirs->rtt_to_acds_ns);
104 return -1;
105 }
106 if (ours->rtt_to_acds_ns > theirs->rtt_to_acds_ns) {
107 log_debug("NAT compare: they win by latency (%lu ns vs %lu ns)", theirs->rtt_to_acds_ns, ours->rtt_to_acds_ns);
108 return 1;
109 }
110
111 // Everything equal - initiator hosts
112 log_debug("NAT compare: equal quality, initiator wins (we_are_initiator=%d)", we_are_initiator);
113 return we_are_initiator ? -1 : 1;
114}
115
124static asciichat_error_t nat_parse_stun_response(const uint8_t *response, size_t response_len, char *reflexive_addr, uint16_t *reflexive_port) {
125 if (!response || response_len < 20 || !reflexive_addr || !reflexive_port) {
126 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid STUN response parameters");
127 }
128
129 // STUN packets have a 20-byte header followed by attributes
130 // Attributes are TLV (Type-Length-Value) format
131 // Look for XOR_MAPPED_ADDRESS (0x0020) or MAPPED_ADDRESS (0x0001)
132
133 const uint8_t *current = response + 20;
134 const uint8_t *end = response + response_len;
135
136 while (current + 4 <= end) {
137 uint16_t attr_type = (current[0] << 8) | current[1];
138 uint16_t attr_len = (current[2] << 8) | current[3];
139
140 if (current + 4 + attr_len > end) {
141 break;
142 }
143
144 // IPv4 STUN responses can carry MAPPED-ADDRESS or XOR-MAPPED-ADDRESS.
145 if ((attr_type == 0x0001 || attr_type == 0x0020) && attr_len >= 8) {
146 // Format: reserved byte, family (1=IPv4, 2=IPv6), port (2 bytes), address
147 uint8_t family = current[5];
148 if (family == 1) { // IPv4
149 uint16_t port = ((uint16_t)current[6] << 8) | current[7];
150 uint32_t addr = ((uint32_t)current[8] << 24) | ((uint32_t)current[9] << 16) | ((uint32_t)current[10] << 8) | current[11];
151 if (attr_type == 0x0020) {
152 port ^= 0x2112;
153 addr ^= 0x2112a442;
154 }
155
156 // Convert to dotted quad notation
157 safe_snprintf(reflexive_addr, IP_ADDRESS_BUFFER_SIZE, "%u.%u.%u.%u", (addr >> 24) & 0xFF, (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF);
158 *reflexive_port = port;
159 return ASCIICHAT_OK;
160 }
161 }
162
163 // Move to next attribute (with 4-byte alignment padding)
164 uint16_t padded_len = (attr_len + 3) & ~3;
165 current += 4 + padded_len;
166 }
167
168 return SET_ERRNO(ERROR_FORMAT, "STUN response missing a supported mapped address");
169}
170
178static asciichat_error_t nat_stun_probe(nat_quality_t *quality, const char *stun_server, uint16_t local_port) {
179 if (!quality || !stun_server || !stun_server[0]) {
180 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for STUN probe");
181 }
182
183 log_debug("Starting STUN probe to %s (local_port=%u)", stun_server, local_port);
184
185 // Parse stun_server for hostname and port
186 char host_buf[BUFFER_SIZE_SMALL] = {0};
187 uint16_t stun_port = STUN_DEFAULT_PORT;
188
189 SAFE_STRNCPY(host_buf, stun_server, sizeof(host_buf));
190
191 char *colon = strchr(host_buf, ':');
192 if (colon) {
193 *colon = '\0';
194 char *endptr;
195 errno = 0;
196 long port_val = strtol(colon + 1, &endptr, 10);
197 if (*endptr == '\0' && errno == 0 && port_val > 0 && port_val <= 65535) {
198 stun_port = (uint16_t)port_val;
199 } else {
200 log_error("Invalid STUN port: %s", colon + 1);
201 }
202 }
203
204 // Detect address family from STUN server hostname (IPv4 vs IPv6)
205 int stun_family = is_valid_ipv6(host_buf) ? AF_INET6 : AF_INET;
206
207 // Create UDP socket for STUN probe
208 const char *socket_name = stun_family == AF_INET6 ? "probe_ipv6" : "probe_ipv4";
209 socket_t sock = socket_create(socket_name, stun_family, SOCK_DGRAM, 0);
210 if (sock == INVALID_SOCKET_VALUE) {
211 log_warn("Failed to create UDP socket for STUN probe");
212 return SET_ERRNO(ERROR_NETWORK, "Cannot create UDP socket");
213 }
214
215 // Set timeout on socket
216 socket_set_timeout(sock, 5000 * NS_PER_MS_INT); // 5 second timeout
217
218 // Resolve STUN server hostname
219 struct addrinfo hints = {0};
220 hints.ai_family = stun_family;
221 hints.ai_socktype = SOCK_DGRAM;
222
223 struct addrinfo *result = NULL;
224 char port_str[DISCOVERY_NAT_PORT_BUFFER_SIZE];
225 safe_snprintf(port_str, sizeof(port_str), "%u", stun_port);
226
227 int ret = getaddrinfo(host_buf, port_str, &hints, &result);
228 if (ret != 0) {
229 log_warn("Failed to resolve STUN server %s: %s", host_buf, gai_strerror(ret));
230 socket_close(sock);
231 return SET_ERRNO(ERROR_NETWORK_CONNECT, "Cannot resolve STUN server hostname");
232 }
233
234 // Build minimal STUN binding request (RFC 5389)
235 // Header: Magic (0x2112A442) + Transaction ID (96 bits)
236 uint8_t stun_request[STUN_BINDING_HEADER_SIZE];
237 stun_request[0] = 0x00; // Message type: Binding Request (0x0001), bits split
238 stun_request[1] = 0x01;
239 stun_request[2] = 0x00; // Message length: 0 (no attributes for simple probe)
240 stun_request[3] = 0x00;
241
242 // Magic cookie (STUN magic number)
243 stun_request[4] = 0x21;
244 stun_request[5] = 0x12;
245 stun_request[6] = 0xa4;
246 stun_request[7] = 0x42;
247
248 // Transaction ID (96 bits) - use simple pattern for MVP
249 memset(stun_request + 8, 0xAA, 12);
250
251 // Send STUN binding request
252 uint64_t start_time = time_get_ns();
253 ssize_t sent = socket_sendto(sock, stun_request, sizeof(stun_request), 0, result->ai_addr, result->ai_addrlen);
254
255 if (sent < 0) {
256 log_warn("Failed to send STUN request");
257 freeaddrinfo(result);
258 socket_close(sock);
259 return SET_ERRNO(ERROR_NETWORK, "Cannot send STUN request");
260 }
261
262 // Receive STUN response
264 struct sockaddr_in peer_addr;
265 socklen_t peer_addr_len = sizeof(peer_addr);
266
267 ssize_t recv_len = socket_recvfrom(sock, stun_response, sizeof(stun_response), 0, (struct sockaddr *)&peer_addr, &peer_addr_len);
268
269 uint64_t end_time = time_get_ns();
270 uint32_t rtt_ms = (uint32_t)(time_ns_to_ms(end_time - start_time));
271
272 freeaddrinfo(result);
273 socket_close(sock);
274
275 if (recv_len < 20) {
276 log_warn("STUN response too short or timeout");
277 return SET_ERRNO(ERROR_NETWORK_TIMEOUT, "STUN server did not respond");
278 }
279
280 // Parse STUN response to extract reflexive address
281 char reflexive_addr[IP_ADDRESS_BUFFER_SIZE] = {0};
282 uint16_t reflexive_port = 0;
283 asciichat_error_t parse_result = nat_parse_stun_response(stun_response, (size_t)recv_len, reflexive_addr, &reflexive_port);
284
285 if (parse_result != ASCIICHAT_OK) {
286 log_warn("Failed to parse STUN response");
287 return parse_result;
288 }
289
290 SAFE_STRNCPY(quality->public_address, reflexive_addr, sizeof(quality->public_address));
291 quality->public_port = reflexive_port;
292 quality->stun_latency_ns = (uint64_t)rtt_ms * NS_PER_MS_INT;
293
294 log_info("STUN probe successful: reflexive_address=%s:%u, rtt=%u ms", reflexive_addr, reflexive_port, rtt_ms);
295
296 return ASCIICHAT_OK;
297}
298
299asciichat_error_t nat_detect_quality(nat_quality_t *quality, const char *stun_server, uint16_t local_port) {
300 if (!quality) {
301 return SET_ERRNO(ERROR_INVALID_PARAM, "quality is NULL");
302 }
303
304 nat_quality_init(quality);
305 log_info("Starting NAT quality detection (local_port=%u)", local_port);
306
307 // Quality probes run before a listener exists (often with port zero).
308 // Only the listening server lifecycle may create, renew, and remove mappings.
309
310 // Probe STUN when configured.
311 if (stun_server && stun_server[0]) {
312 // A failed probe is an expected fallback; retain diagnostics without
313 // publishing a fatal-looking notification for a successful detection.
315 bool notifications_were_suppressed = errno_notifications_suppress(true);
316 asciichat_error_t stun_result = nat_stun_probe(quality, stun_server, local_port);
317 errno_notifications_suppress(notifications_were_suppressed);
319 if (stun_result == ASCIICHAT_OK) {
320 // Successfully got reflexive address via STUN
321 quality->has_srflx_candidates = true;
322
323 // A server-reflexive address demonstrates STUN reachability, not a public
324 // interface or NAT classification. Those require separate observations.
325 quality->has_public_ip = false;
326
327 } else {
328 log_debug("STUN probe failed, falling back to symmetric NAT assumption");
329 }
330 }
331
332 // Set ICE candidate flags based on what we found
333 quality->has_host_candidates = true; // We always have local IP
334 quality->has_srflx_candidates = quality->upnp_available || quality->has_public_ip || quality->has_srflx_candidates;
335
336 // Check if TURN relay servers are available (configured via options or ACDS)
337 const options_t *opts = options_get();
338 const char *turn_servers = opts ? opts->turn_servers : NULL;
339 quality->has_relay_candidates = (turn_servers && turn_servers[0] != '\0');
340 if (quality->has_relay_candidates) {
341 log_debug("TURN relay servers configured: %s", turn_servers);
342 }
343
344 quality->detection_complete = true;
345 log_info("NAT detection complete: tier=%d, upnp=%d, has_public_ip=%d, nat_type=%s", nat_compute_tier(quality), quality->upnp_available, quality->has_public_ip,
346 nat_type_to_string(quality->nat_type));
347
348 return ASCIICHAT_OK;
349}
350
352 switch (type) {
354 return "Open (Public IP)";
356 return "Full Cone";
358 return "Restricted Cone";
360 return "Port Restricted";
362 return "Symmetric";
363 default:
364 return "Unknown";
365 }
366}
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
bool errno_notifications_suppress(bool suppress)
asciichat_errno_scope_t errno_scope_begin(void)
#define SET_ERRNO(code,...)
@ ASCIICHAT_ERRNO_HANDLED
@ ASCIICHAT_ERRNO_DISMISSED
Common buffer size definitions.
Application limits and constraints.
int socket_close(socket_t sock)
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
unsigned long long uint64_t
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_NETWORK_CONNECT
Definition error_codes.h:78
@ ERROR_NETWORK
Definition error_codes.h:76
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_NETWORK_TIMEOUT
Definition error_codes.h:79
@ ERROR_FORMAT
#define IP_ADDRESS_BUFFER_SIZE
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
acip_nat_type_t
NAT type classification for host selection.
Definition acds.h:830
@ ACIP_NAT_TYPE_RESTRICTED
Address-restricted cone NAT.
Definition acds.h:833
@ ACIP_NAT_TYPE_SYMMETRIC
Symmetric NAT (hardest, requires TURN).
Definition acds.h:835
@ ACIP_NAT_TYPE_FULL_CONE
Full cone NAT (easiest to traverse).
Definition acds.h:832
@ ACIP_NAT_TYPE_OPEN
No NAT (public IP).
Definition acds.h:831
@ ACIP_NAT_TYPE_PORT_RESTRICTED
Port-restricted cone NAT.
Definition acds.h:834
#define NS_PER_MS_INT
Definition time.h:172
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
const options_t * options_get(void)
Get pointer to current options struct (lock-free, thread-safe).
Definition rcu.c:495
#define STUN_DEFAULT_PORT
Standard STUN port (RFC 5389).
Definition stun.h:87
int is_valid_ipv6(const char *ip)
Check if a string is a valid IPv6 address.
Definition ip.c:63
int socket_t
⚙️ Common definitions, error codes, macros, and types shared throughout the application
🌍 IP Address Parsing and Formatting Utilities
📝 Logging API with multiple log levels and terminal output control
#define DISCOVERY_NAT_PORT_BUFFER_SIZE
Definition nat.c:8
#define STUN_PROBE_RESPONSE_BUFFER_SIZE
Definition nat.c:12
int nat_compare_quality(const nat_quality_t *ours, const nat_quality_t *theirs, bool we_are_initiator)
Compare two NAT qualities and determine who should host.
Definition nat.c:61
void nat_quality_init(nat_quality_t *quality)
Connectivity measurements collected while judging a peer's NAT path: public-IP and UPnP availability,...
Definition nat.c:39
asciichat_error_t nat_detect_quality(nat_quality_t *quality, const char *stun_server, uint16_t local_port)
Detect NAT quality using all available methods.
Definition nat.c:299
int nat_compute_tier(const nat_quality_t *quality)
Compute NAT tier for host selection (0=best, 4=worst).
Definition nat.c:46
#define STUN_BINDING_HEADER_SIZE
Definition nat.c:11
const char * nat_type_to_string(acip_nat_type_t type)
Get human-readable description of NAT type.
Definition nat.c:351
#define BANDWIDTH_OVERRIDE_RATIO
Definition nat.c:37
NAT quality detection for discovery mode host selection.
🔤 String Manipulation and Shell Escaping Utilities
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
NAT quality assessment result.
Definition nat.h:28
bool detection_complete
All probes finished.
Definition nat.h:52
bool has_host_candidates
Local IP reachable.
Definition nat.h:47
uint32_t upload_kbps
Upload bandwidth in Kbps.
Definition nat.h:40
bool lan_reachable
Same subnet as peer.
Definition nat.h:34
uint64_t stun_latency_ns
RTT to STUN server in nanoseconds.
Definition nat.h:35
bool has_srflx_candidates
STUN worked.
Definition nat.h:48
bool has_relay_candidates
TURN available.
Definition nat.h:49
acip_nat_type_t nat_type
NAT classification.
Definition nat.h:33
bool has_public_ip
STUN reflexive == local IP.
Definition nat.h:30
bool upnp_available
UPnP/NAT-PMP mapping succeeded.
Definition nat.h:31
char public_address[IP_ADDRESS_BUFFER_SIZE]
Public IP address.
Definition nat.h:36
uint64_t rtt_to_acds_ns
Latency to ACDS in nanoseconds.
Definition nat.h:42
uint16_t public_port
Public port.
Definition nat.h:37
char turn_servers[256]
ACDS: Comma-separated list of TURN server URLs.
Definition options.h:1212
⏱️ High-precision timing utilities using sokol_time.h and uthash