ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
ice.c File Reference

ICE candidate gathering and exchange. More...

Go to the source code of this file.

Macros

#define NETWORK_WEBRTC_ICE_CANDIDATE_LINE_BUFFER_SIZE   512
#define PCRE2_CODE_UNIT_WIDTH   8

Functions

const char * ice_candidate_type_name (ice_candidate_type_t type)
 Get human-readable candidate type name.
const char * ice_protocol_name (ice_protocol_t protocol)
 Get human-readable protocol name.
uint32_t ice_calculate_priority (ice_candidate_type_t type, uint16_t local_preference, uint8_t component_id)
 Calculate candidate priority.
uint32_t ice_calculate_priority_for_candidate (const ice_candidate_t *candidate)
 Calculate candidate priority with IP-aware local preference.
asciichat_error_t ice_parse_candidate (const char *line, ice_candidate_t *candidate)
 Parse ICE candidate from attribute string.
asciichat_error_t ice_format_candidate (const ice_candidate_t *candidate, char *line, size_t line_size)
 Format ICE candidate to attribute string.
asciichat_error_t ice_gather_candidates (const ice_config_t *config)
 Start ICE candidate gathering.
asciichat_error_t ice_add_remote_candidate (webrtc_peer_connection_t *pc, const ice_candidate_t *candidate, const char *mid)
 Add remote candidate to peer connection.
bool ice_is_connected (webrtc_peer_connection_t *pc)
 Check ICE connection state.
asciichat_error_t ice_get_selected_pair_impl (webrtc_peer_connection_t *pc, ice_candidate_t *local_candidate, ice_candidate_t *remote_candidate)
 Get selected ICE candidate pair (C++ implementation).
asciichat_error_t ice_get_selected_pair (webrtc_peer_connection_t *pc, ice_candidate_t *local_candidate, ice_candidate_t *remote_candidate)
 Get selected candidate pair.

Detailed Description

ICE candidate gathering and exchange.

Implements ICE candidate collection from STUN/TURN servers and relay via ACDS signaling.

Date
January 2026

Definition in file ice.c.

Macro Definition Documentation

◆ NETWORK_WEBRTC_ICE_CANDIDATE_LINE_BUFFER_SIZE

#define NETWORK_WEBRTC_ICE_CANDIDATE_LINE_BUFFER_SIZE   512

Definition at line 12 of file ice.c.

Referenced by ice_add_remote_candidate().

◆ PCRE2_CODE_UNIT_WIDTH

#define PCRE2_CODE_UNIT_WIDTH   8

Definition at line 22 of file ice.c.

Function Documentation

◆ ice_add_remote_candidate()

asciichat_error_t ice_add_remote_candidate ( struct webrtc_peer_connection * pc,
const ice_candidate_t * candidate,
const char * mid )

Add remote candidate to peer connection.

Called when receiving candidate from peer. The WebRTC agent will test connectivity with this candidate.

Parameters
pcPeer connection to add candidate to
candidateRemote candidate from peer
midMedia stream ID
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 420 of file ice.c.

420 {
421 if (!pc || !candidate || !mid) {
422 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid remote candidate parameters");
423 }
424
425 // Validate candidate has required fields
426 if (candidate->ip_address[0] == '\0' || candidate->port == 0) {
427 return SET_ERRNO(ERROR_INVALID_PARAM, "Candidate missing IP address or port");
428 }
429
430 log_debug("ICE: Adding remote candidate %s:%u (type=%s, foundation=%s) on mid=%s", candidate->ip_address, candidate->port, ice_candidate_type_name(candidate->type), candidate->foundation, mid);
431
432 // Format candidate to SDP attribute line for libdatachannel
434 asciichat_error_t err = ice_format_candidate(candidate, candidate_line, sizeof(candidate_line));
435 if (err != ASCIICHAT_OK) {
436 return err;
437 }
438
439 // Delegate to WebRTC layer
440 return webrtc_add_remote_candidate(pc, candidate_line, mid);
441}
#define SET_ERRNO(code,...)
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_debug(...)
Log a DEBUG message.
Definition log/log.h:565
asciichat_error_t webrtc_add_remote_candidate(webrtc_peer_connection_t *pc, const char *candidate, const char *mid)
Add remote ICE candidate.
#define NETWORK_WEBRTC_ICE_CANDIDATE_LINE_BUFFER_SIZE
Definition ice.c:12
asciichat_error_t ice_format_candidate(const ice_candidate_t *candidate, char *line, size_t line_size)
Format ICE candidate to attribute string.
Definition ice.c:322
const char * ice_candidate_type_name(ice_candidate_type_t type)
Get human-readable candidate type name.
Definition ice.c:29
char ip_address[64]
IP address (IPv4 or IPv6).
Definition ice.h:126
char foundation[32]
Unique identifier for candidate (for pairing).
Definition ice.h:120
uint16_t port
Port number.
Definition ice.h:127
ice_candidate_type_t type
host, srflx, prflx, or relay
Definition ice.h:130

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ice_candidate_t::foundation, ice_candidate_type_name(), ice_format_candidate(), ice_candidate_t::ip_address, log_debug, NETWORK_WEBRTC_ICE_CANDIDATE_LINE_BUFFER_SIZE, ice_candidate_t::port, SET_ERRNO, ice_candidate_t::type, and webrtc_add_remote_candidate().

◆ ice_calculate_priority()

uint32_t ice_calculate_priority ( ice_candidate_type_t type,
uint16_t local_preference,
uint8_t component_id )

Calculate candidate priority.

Implements RFC 5245 priority formula: priority = (2^24 * typePreference) + (2^8 * localPreference) + (256 - componentID)

Parameters
typeCandidate type (determines typePreference)
local_preferenceLocal preference (0-65535, higher = preferred)
component_idComponent ID (1 or 2)
Returns
Calculated priority

Definition at line 104 of file ice.c.

104 {
105 // RFC 5245: priority = (2^24 * typePreference) + (2^8 * localPreference) + (256 - componentID)
106
107 // Type preference (higher is better):
108 // - Host: 126 (most preferred, lowest latency)
109 // - SRFLX: 100 (STUN-discovered address)
110 // - PRFLX: 110 (discovered during connectivity checks)
111 // - Relay: 0 (least preferred, uses bandwidth)
112
113 uint8_t type_preference = 0;
114 switch (type) {
116 type_preference = 126;
117 break;
119 type_preference = 100;
120 break;
122 type_preference = 110;
123 break;
125 default:
126 type_preference = 0;
127 break;
128 }
129
130 uint32_t priority = (((uint32_t)type_preference) << 24) | (((uint32_t)local_preference) << 8) | (256 - (uint32_t)component_id);
131
132 return priority;
133}
unsigned int uint32_t
unsigned char uint8_t
@ ICE_CANDIDATE_SRFLX
Server-reflexive (NAT-discovered via STUN).
Definition ice.h:83
@ ICE_CANDIDATE_HOST
Host candidate (local IP address).
Definition ice.h:82
@ ICE_CANDIDATE_RELAY
Relay candidate (TURN server).
Definition ice.h:85
@ ICE_CANDIDATE_PRFLX
Peer-reflexive (discovered during checks).
Definition ice.h:84

References ICE_CANDIDATE_HOST, ICE_CANDIDATE_PRFLX, ICE_CANDIDATE_RELAY, and ICE_CANDIDATE_SRFLX.

Referenced by ice_calculate_priority_for_candidate().

◆ ice_calculate_priority_for_candidate()

uint32_t ice_calculate_priority_for_candidate ( const ice_candidate_t * candidate)

Calculate candidate priority with IP-aware local preference.

Automatically determines local_preference based on IP address classification:

  • LAN addresses (192.168.x.x, 10.x.x.x, etc.): Highest priority (65535)
  • Localhost (127.x.x.x, ::1): High priority (65000)
  • Internet (public IPs): Medium priority (32768)
  • Unknown/invalid: Lowest priority (0)

This prioritization improves connection establishment by preferring:

  1. Local network peers (lowest latency, no NAT)
  2. Public IPs (direct connectivity)
  3. Unknown addresses (fallback)
Parameters
candidateICE candidate with IP address to classify
Returns
Calculated priority using RFC 5245 formula with IP-based local preference
Example
ice_candidate_t candidate = {
.ip_address = "192.168.1.100",
.component_id = 1
};
// Returns high priority due to LAN address
uint32_t ice_calculate_priority_for_candidate(const ice_candidate_t *candidate)
Calculate candidate priority with IP-aware local preference.
Definition ice.c:135
Single ICE candidate for connectivity.
Definition ice.h:118

Definition at line 135 of file ice.c.

135 {
136 if (!candidate) {
137 return 0;
138 }
139
140 // Calculate local preference based on IP classification
141 uint16_t local_pref = ice_calculate_local_preference_by_ip(candidate->ip_address);
142
143 // Use standard RFC 5245 priority formula with IP-aware local preference
144 return ice_calculate_priority(candidate->type, local_pref, (uint8_t)candidate->component_id);
145}
unsigned short uint16_t
uint32_t ice_calculate_priority(ice_candidate_type_t type, uint16_t local_preference, uint8_t component_id)
Calculate candidate priority.
Definition ice.c:104
uint32_t component_id
Component (1=RTP, 2=RTCP; usually 1).
Definition ice.h:121

References ice_candidate_t::component_id, ice_calculate_priority(), ice_candidate_t::ip_address, and ice_candidate_t::type.

◆ ice_candidate_type_name()

const char * ice_candidate_type_name ( ice_candidate_type_t type)

Get human-readable candidate type name.

Parameters
typeCandidate type
Returns
Static string (e.g., "host", "srflx", "relay")

Definition at line 29 of file ice.c.

29 {
30 switch (type) {
32 return "host";
34 return "srflx";
36 return "prflx";
38 return "relay";
39 default:
40 return "unknown";
41 }
42}

References ICE_CANDIDATE_HOST, ICE_CANDIDATE_PRFLX, ICE_CANDIDATE_RELAY, and ICE_CANDIDATE_SRFLX.

Referenced by ice_add_remote_candidate(), and ice_format_candidate().

◆ ice_format_candidate()

asciichat_error_t ice_format_candidate ( const ice_candidate_t * candidate,
char * line,
size_t line_size )

Format ICE candidate to attribute string.

Converts ice_candidate_t structure to SDP attribute line.

Parameters
candidateCandidate to format
lineOutput buffer for SDP line (without "a=candidate:" prefix)
line_sizeSize of output buffer
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 322 of file ice.c.

322 {
323 if (!candidate || !line || line_size == 0) {
324 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid candidate format parameters");
325 }
326
327 // Format: foundation component protocol priority ip port typ type [raddr rport] [tcptype type]
328 // Example: 1 1 udp 2130706431 192.168.1.1 54321 typ host
329 // Example with raddr: 1 1 udp 2130706431 203.0.113.45 54321 typ srflx raddr 192.168.1.1 rport 12345
330
331 int written = safe_snprintf(line, line_size, "%s %u %s %u %s %u typ %s", candidate->foundation, candidate->component_id, ice_protocol_name(candidate->protocol), candidate->priority,
332 candidate->ip_address, candidate->port, ice_candidate_type_name(candidate->type));
333
334 if (written < 0 || (size_t)written >= line_size) {
335 return SET_ERRNO(ERROR_BUFFER_FULL, "Candidate line too large for buffer");
336 }
337
338 size_t remaining = line_size - (size_t)written;
339 char *pos = line + written;
340
341 // 2. If srflx/prflx/relay: append raddr and rport
342 if (candidate->type == ICE_CANDIDATE_SRFLX || candidate->type == ICE_CANDIDATE_PRFLX || candidate->type == ICE_CANDIDATE_RELAY) {
343 if (candidate->raddr[0] != '\0') {
344 int appended = safe_snprintf(pos, remaining, " raddr %s rport %u", candidate->raddr, candidate->rport);
345 if (appended < 0 || (size_t)appended >= remaining) {
346 return SET_ERRNO(ERROR_BUFFER_FULL, "Cannot append raddr/rport to candidate line");
347 }
348 pos += appended;
349 remaining -= (size_t)appended;
350 }
351 }
352
353 // 3. If TCP: append tcptype
354 if (candidate->protocol == ICE_PROTOCOL_TCP) {
355 const char *tcptype_str = "passive"; // default
356 if (candidate->tcp_type == ICE_TCP_TYPE_ACTIVE) {
357 tcptype_str = "active";
358 } else if (candidate->tcp_type == ICE_TCP_TYPE_SO) {
359 tcptype_str = "so";
360 }
361
362 int appended = safe_snprintf(pos, remaining, " tcptype %s", tcptype_str);
363 if (appended < 0 || (size_t)appended >= remaining) {
364 return SET_ERRNO(ERROR_BUFFER_FULL, "Cannot append tcptype to candidate line");
365 }
366 pos += appended;
367 remaining -= (size_t)appended;
368 }
369
370 // 4. Append any extensions
371 if (candidate->extensions[0] != '\0') {
372 int appended = safe_snprintf(pos, remaining, " %s", candidate->extensions);
373 if (appended < 0 || (size_t)appended >= remaining) {
374 return SET_ERRNO(ERROR_BUFFER_FULL, "Cannot append extensions to candidate line");
375 }
376 }
377
378 // 5. Ensure line is null-terminated (snprintf already does this)
379 return ASCIICHAT_OK;
380}
@ ERROR_BUFFER_FULL
const char * ice_protocol_name(ice_protocol_t protocol)
Get human-readable protocol name.
Definition ice.c:44
@ ICE_PROTOCOL_TCP
Definition ice.h:93
@ ICE_TCP_TYPE_SO
Simultaneous open.
Definition ice.h:102
@ ICE_TCP_TYPE_ACTIVE
Actively opens connection.
Definition ice.h:100
uint32_t priority
Candidate priority (used for preference).
Definition ice.h:123
uint16_t rport
Related port.
Definition ice.h:134
ice_protocol_t protocol
UDP or TCP.
Definition ice.h:122
char extensions[256]
Additional extensions (e.g., "tcptype passive").
Definition ice.h:140
ice_tcp_type_t tcp_type
active, passive, so
Definition ice.h:137
char raddr[64]
Related address (for srflx/prflx).
Definition ice.h:133

References ASCIICHAT_OK, ice_candidate_t::component_id, ERROR_BUFFER_FULL, ERROR_INVALID_PARAM, ice_candidate_t::extensions, ice_candidate_t::foundation, ICE_CANDIDATE_PRFLX, ICE_CANDIDATE_RELAY, ICE_CANDIDATE_SRFLX, ice_candidate_type_name(), ice_protocol_name(), ICE_PROTOCOL_TCP, ICE_TCP_TYPE_ACTIVE, ICE_TCP_TYPE_SO, ice_candidate_t::ip_address, ice_candidate_t::port, ice_candidate_t::priority, ice_candidate_t::protocol, ice_candidate_t::raddr, ice_candidate_t::rport, SET_ERRNO, ice_candidate_t::tcp_type, and ice_candidate_t::type.

Referenced by ice_add_remote_candidate().

◆ ice_gather_candidates()

asciichat_error_t ice_gather_candidates ( const ice_config_t * config)

Start ICE candidate gathering.

Initiates gathering of candidates from all sources:

  • Host candidates (network interfaces)
  • STUN server (server-reflexive)
  • TURN relay

Candidates are reported via callback as they're discovered.

Parameters
configICE gathering configuration
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 386 of file ice.c.

386 {
387 if (!config) {
388 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid ICE config");
389 }
390
391 if (!config->send_callback) {
392 return SET_ERRNO(ERROR_INVALID_PARAM, "ICE config missing send_callback");
393 }
394
395 log_debug("ICE: Starting candidate gathering (ufrag=%s, pwd=%s)", config->ufrag, config->pwd);
396
397 // NOTE: libdatachannel (juice) handles ICE candidate gathering internally.
398 // This function is a placeholder for the callback-based API.
399 // The actual gathering happens in the peer_manager when you:
400 // 1. Create peer connection with rtcCreatePeerConnection()
401 // 2. Set ice candidate callback with rtcSetIceCandidateCallback()
402 // 3. libdatachannel automatically gathers candidates from:
403 // - Local interfaces (host candidates)
404 // - STUN servers (server-reflexive candidates)
405 // - TURN servers (relay candidates)
406 // 4. When a candidate is found, rtcSetIceCandidateCallback() is called
407 // 5. Application (webrtc.c) formats and sends via ACDS signaling
408 //
409 // This ice_gather_candidates() function may not be called directly -
410 // the gathering happens automatically when peer connection is created.
411 // Keeping this for API compatibility.
412
413 return ASCIICHAT_OK;
414}
const char * ufrag
Username fragment for ICE (from offer).
Definition ice.h:171
ice_send_candidate_callback_t send_callback
Called for each gathered candidate.
Definition ice.h:173
const char * pwd
Password for ICE (from offer).
Definition ice.h:172

References ASCIICHAT_OK, ERROR_INVALID_PARAM, log_debug, ice_config_t::pwd, ice_config_t::send_callback, SET_ERRNO, and ice_config_t::ufrag.

◆ ice_get_selected_pair()

asciichat_error_t ice_get_selected_pair ( struct webrtc_peer_connection * pc,
ice_candidate_t * local_candidate,
ice_candidate_t * remote_candidate )

Get selected candidate pair.

Returns the local and remote candidates that were selected for data flow. Uses libdatachannel's rtcGetSelectedCandidatePair() API via C++ bindings.

Parameters
pcPeer connection to query
local_candidateSelected local candidate (output, may be NULL)
remote_candidateSelected remote candidate (output, may be NULL)
Returns
ASCIICHAT_OK if pair selected, ERROR_INVALID_STATE if no pair selected yet

Definition at line 456 of file ice.c.

456 {
457 // Delegate to C++ implementation which uses libdatachannel's C++ API
458 return ice_get_selected_pair_impl(pc, local_candidate, remote_candidate);
459}
asciichat_error_t ice_get_selected_pair_impl(webrtc_peer_connection_t *pc, ice_candidate_t *local_candidate, ice_candidate_t *remote_candidate)
Get selected ICE candidate pair (C++ implementation).

References ice_get_selected_pair_impl().

◆ ice_get_selected_pair_impl()

asciichat_error_t ice_get_selected_pair_impl ( webrtc_peer_connection_t * pc,
ice_candidate_t * local_candidate,
ice_candidate_t * remote_candidate )

Get selected ICE candidate pair (C++ implementation).

This function uses libdatachannel's C++ API to retrieve the selected candidate pair, which is not available in the C API.

Definition at line 62 of file ice_selected_pair.cpp.

62 {
63 if (!pc) {
65 }
66
67 try {
68 // Get the libdatachannel peer connection ID using helper function
69 int rtc_id = webrtc_get_rtc_id(pc);
70 if (rtc_id < 0) {
72 }
73
74 // Query selected candidate pair from libdatachannel
75 // Note: This requires libdatachannel to have the selected candidate pair available
78
79 // Try to get the selected local candidate
80 if (rtcGetSelectedCandidatePair(rtc_id, local_buf, sizeof(local_buf), remote_buf, sizeof(remote_buf)) < 0) {
81 // No pair selected yet, or error accessing it
83 }
84
85 // Parse local candidate if requested
86 if (local_candidate) {
87 std::string local_str(local_buf);
88 asciichat_error_t err = parse_datachannel_candidate(local_str, local_candidate);
89 if (err != ASCIICHAT_OK) {
90 return err;
91 }
92 }
93
94 // Parse remote candidate if requested
95 if (remote_candidate) {
96 std::string remote_str(remote_buf);
97 asciichat_error_t err = parse_datachannel_candidate(remote_str, remote_candidate);
98 if (err != ASCIICHAT_OK) {
99 return err;
100 }
101 }
102
103 return ASCIICHAT_OK;
104
105 } catch (const std::exception &) {
106 return ERROR_NETWORK;
107 } catch (...) {
108 return ERROR_NETWORK;
109 }
110}
@ ERROR_INVALID_STATE
@ ERROR_NETWORK
Definition error_codes.h:77
int webrtc_get_rtc_id(webrtc_peer_connection_t *pc)
Get the internal libdatachannel peer connection ID.
#define NETWORK_WEBRTC_ICE_SELECTED_PAIR_REMOTE_BUFFER_SIZE
#define NETWORK_WEBRTC_ICE_SELECTED_PAIR_LOCAL_BUFFER_SIZE

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_INVALID_STATE, ERROR_NETWORK, NETWORK_WEBRTC_ICE_SELECTED_PAIR_LOCAL_BUFFER_SIZE, NETWORK_WEBRTC_ICE_SELECTED_PAIR_REMOTE_BUFFER_SIZE, and webrtc_get_rtc_id().

Referenced by ice_get_selected_pair().

◆ ice_is_connected()

bool ice_is_connected ( struct webrtc_peer_connection * pc)

Check ICE connection state.

Parameters
pcPeer connection to check
Returns
true if connected, false otherwise

Definition at line 443 of file ice.c.

443 {
444 if (!pc) {
445 return false;
446 }
447
448 // Check peer connection state
450 return (state == WEBRTC_STATE_CONNECTED);
451}
webrtc_state_t webrtc_get_state(webrtc_peer_connection_t *pc)
Get current connection state.
webrtc_state_t
ICE, signaling, DataChannel, and callback settings for a WebRTC peer.
@ WEBRTC_STATE_CONNECTED
DataChannel established and ready.

References webrtc_get_state(), and WEBRTC_STATE_CONNECTED.

◆ ice_parse_candidate()

asciichat_error_t ice_parse_candidate ( const char * line,
ice_candidate_t * candidate )

Parse ICE candidate from attribute string.

Converts SDP candidate attribute line to ice_candidate_t structure.

Format: a=candidate:foundation component protocol priority ip port typ type [raddr rport] [extensions]

Parameters
lineSDP candidate line (without "a=candidate:" prefix)
candidateParsed candidate (output)
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 318 of file ice.c.

318 {
319 return ice_parse_candidate_pcre2(line, candidate);
320}

◆ ice_protocol_name()

const char * ice_protocol_name ( ice_protocol_t protocol)

Get human-readable protocol name.

Parameters
protocolProtocol type
Returns
Static string (e.g., "udp", "tcp")

Definition at line 44 of file ice.c.

44 {
45 switch (protocol) {
47 return "udp";
49 return "tcp";
50 default:
51 return "unknown";
52 }
53}
@ ICE_PROTOCOL_UDP
Definition ice.h:92

References ICE_PROTOCOL_TCP, and ICE_PROTOCOL_UDP.

Referenced by ice_format_candidate().