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.h File Reference

NAT quality detection for discovery mode host selection. More...

Go to the source code of this file.

Data Structures

struct  nat_quality_t
 NAT quality assessment result. More...

Functions

void nat_quality_init (nat_quality_t *quality)
 Connectivity measurements collected while judging a peer's NAT path: public-IP and UPnP availability, mapped port, NAT type, reachability, STUN latency, and upload estimate. Discovery uses this value to rank candidates; it owns no live socket.
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.
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.
const char * nat_type_to_string (acip_nat_type_t type)
 Get human-readable description of NAT type.
int nat_compute_tier (const nat_quality_t *quality)
 Compute NAT tier for host selection (0=best, 4=worst).

Detailed Description

NAT quality detection for discovery mode host selection.

Detects NAT characteristics to determine the best host candidate. Uses STUN, UPnP/NAT-PMP, and bandwidth measurements.

Definition in file nat.h.

Function Documentation

◆ nat_compare_quality()

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.

Algorithm is deterministic - both sides get the same result. Uses NAT tier priority with bandwidth as tiebreaker.

Parameters
oursOur NAT quality
theirsPeer's NAT quality
we_are_initiatorTrue if we started the session
Returns
-1 = we host, 0 = equal (initiator wins), 1 = they host

Definition at line 61 of file nat.c.

61 {
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}
unsigned long long uint64_t
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
int nat_compute_tier(const nat_quality_t *quality)
Compute NAT tier for host selection (0=best, 4=worst).
Definition nat.c:46
#define BANDWIDTH_OVERRIDE_RATIO
Definition nat.c:37
uint32_t upload_kbps
Upload bandwidth in Kbps.
Definition nat.h:40
uint64_t rtt_to_acds_ns
Latency to ACDS in nanoseconds.
Definition nat.h:42

References BANDWIDTH_OVERRIDE_RATIO, log_debug, nat_compute_tier(), nat_quality_t::rtt_to_acds_ns, and nat_quality_t::upload_kbps.

Referenced by negotiate_determine_result().

◆ nat_compute_tier()

int nat_compute_tier ( const nat_quality_t * quality)

Compute NAT tier for host selection (0=best, 4=worst).

Parameters
qualityNAT quality
Returns
Tier value

Definition at line 46 of file nat.c.

46 {
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}
@ ACIP_NAT_TYPE_RESTRICTED
Address-restricted cone NAT.
Definition acds.h:833
bool lan_reachable
Same subnet as peer.
Definition nat.h:34
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

References ACIP_NAT_TYPE_RESTRICTED, nat_quality_t::has_public_ip, nat_quality_t::lan_reachable, nat_quality_t::nat_type, and nat_quality_t::upnp_available.

Referenced by nat_compare_quality(), and nat_detect_quality().

◆ nat_detect_quality()

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.

Runs an observational STUN probe and records configured candidate support. Does not create router mappings; those belong to the listening server. Results are stored in the provided nat_quality_t structure.

Parameters
qualityOutput structure for results
stun_serverSTUN server URL (e.g., "stun:stun.l.google.com:19302")
local_portLocal port to use for detection
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 299 of file nat.c.

299 {
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}
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
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
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
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
const char * nat_type_to_string(acip_nat_type_t type)
Get human-readable description of NAT type.
Definition nat.c:351
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
bool detection_complete
All probes finished.
Definition nat.h:52
bool has_host_candidates
Local IP reachable.
Definition nat.h:47
bool has_srflx_candidates
STUN worked.
Definition nat.h:48
bool has_relay_candidates
TURN available.
Definition nat.h:49
char turn_servers[256]
ACDS: Comma-separated list of TURN server URLs.
Definition options.h:1212

References ASCIICHAT_ERRNO_DISMISSED, ASCIICHAT_ERRNO_HANDLED, ASCIICHAT_OK, nat_quality_t::detection_complete, errno_notifications_suppress(), errno_scope_begin(), errno_scope_end(), ERROR_INVALID_PARAM, nat_quality_t::has_host_candidates, nat_quality_t::has_public_ip, nat_quality_t::has_relay_candidates, nat_quality_t::has_srflx_candidates, log_debug, log_info, nat_compute_tier(), nat_quality_init(), nat_quality_t::nat_type, nat_type_to_string(), options_get(), SET_ERRNO, options_state::turn_servers, and nat_quality_t::upnp_available.

◆ nat_quality_init()

void nat_quality_init ( nat_quality_t * quality)

Connectivity measurements collected while judging a peer's NAT path: public-IP and UPnP availability, mapped port, NAT type, reachability, STUN latency, and upload estimate. Discovery uses this value to rank candidates; it owns no live socket.

Initialize NAT quality structure with defaults

Parameters
qualityStructure to initialize

Definition at line 39 of file nat.c.

39 {
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}
@ ACIP_NAT_TYPE_SYMMETRIC
Symmetric NAT (hardest, requires TURN).
Definition acds.h:835
NAT quality assessment result.
Definition nat.h:28

References ACIP_NAT_TYPE_SYMMETRIC, and nat_quality_t::nat_type.

Referenced by nat_detect_quality(), and negotiate_init().

◆ nat_type_to_string()

const char * nat_type_to_string ( acip_nat_type_t type)

Get human-readable description of NAT type.

Parameters
typeNAT type
Returns
String description

Definition at line 351 of file nat.c.

351 {
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}
@ 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

References ACIP_NAT_TYPE_FULL_CONE, ACIP_NAT_TYPE_OPEN, ACIP_NAT_TYPE_PORT_RESTRICTED, ACIP_NAT_TYPE_RESTRICTED, and ACIP_NAT_TYPE_SYMMETRIC.

Referenced by nat_detect_quality().