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
Go to the documentation of this file.
1
10
11/* Storage capacities in elements; text buffers include the terminating NUL. */
12#define NETWORK_WEBRTC_ICE_CANDIDATE_LINE_BUFFER_SIZE 512
13
16#include <ascii-chat/log/log.h>
18#include <ascii-chat/util/ip.h>
19#include <string.h>
20#include <stdio.h>
21#include <stdlib.h>
22#define PCRE2_CODE_UNIT_WIDTH 8
23#include <pcre2.h>
24
25/* ============================================================================
26 * Utility Functions
27 * ============================================================================ */
28
30 switch (type) {
32 return "host";
34 return "srflx";
36 return "prflx";
38 return "relay";
39 default:
40 return "unknown";
41 }
42}
43
44const char *ice_protocol_name(ice_protocol_t protocol) {
45 switch (protocol) {
47 return "udp";
49 return "tcp";
50 default:
51 return "unknown";
52 }
53}
54
55/* ============================================================================
56 * ICE Candidate Priority
57 * ============================================================================ */
58
75static uint16_t ice_calculate_local_preference_by_ip(const char *ip_address) {
76 if (!ip_address || ip_address[0] == '\0') {
77 return 0; // Invalid/empty
78 }
79
80 // Check for wildcard addresses (should not appear in candidates, but handle gracefully)
81 if (strcmp(ip_address, "0.0.0.0") == 0 || strcmp(ip_address, "::") == 0) {
82 return 0; // Invalid candidate
83 }
84
85 // LAN addresses: Highest priority (same network = lowest latency)
86 if (is_lan_ipv4(ip_address) || is_lan_ipv6(ip_address)) {
87 return 65535;
88 }
89
90 // Localhost: High priority but less useful than LAN for peer-to-peer
91 if (is_localhost_ipv4(ip_address) || is_localhost_ipv6(ip_address)) {
92 return 65000;
93 }
94
95 // Internet (public): Medium priority
96 if (is_internet_ipv4(ip_address) || is_internet_ipv6(ip_address)) {
97 return 32768;
98 }
99
100 // Unknown/unclassified: Lowest priority
101 return 0;
102}
103
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}
134
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}
146
147/* ============================================================================
148 * ICE Candidate Parsing with PCRE2
149 * ============================================================================ */
150
157
158static const char *ICE_CANDIDATE_PATTERN = "^([^ ]+)\\s+" // 1: foundation
159 "(\\d+)\\s+" // 2: component_id
160 "(udp|tcp)\\s+" // 3: protocol
161 "(\\d+)\\s+" // 4: priority
162 "([a-fA-F0-9.:]+)\\s+" // 5: ip_address (IPv4 or IPv6)
163 "(\\d+)\\s+" // 6: port
164 "typ\\s+" // literal "typ"
165 "(host|srflx|prflx|relay)" // 7: candidate_type
166 "(?:\\s+raddr\\s+([a-fA-F0-9.:]+))?" // 8: optional raddr
167 "(?:\\s+rport\\s+(\\d+))?" // 9: optional rport
168 "(?:\\s+tcptype\\s+(active|passive|so))?" // 10: optional tcptype
169 "\\s*$";
170
175static pcre2_code *ice_candidate_regex_get(void) {
176 return asciichat_pcre2_compile(ICE_CANDIDATE_PATTERN, PCRE2_CASELESS);
177}
178
189static asciichat_error_t ice_parse_candidate_pcre2(const char *line, ice_candidate_t *candidate) {
190 if (!line || !candidate) {
191 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid candidate parameters");
192 }
193
194 // Get compiled regex (owned by the caller)
195 pcre2_code *regex = ice_candidate_regex_get();
196
197 // If PCRE2 not available, return error to fall back to manual parser
198 if (!regex) {
199 return ERROR_MEMORY; // Signal to use fallback
200 }
201
202 pcre2_match_data *match_data = pcre2_match_data_create_from_pattern(regex, NULL);
203 if (!match_data) {
204 pcre2_code_free(regex);
205 return ERROR_MEMORY;
206 }
207
208 int rc = asciichat_pcre2_match(regex, (PCRE2_SPTR8)line, strlen(line), 0, 0, match_data, NULL);
209
210 if (rc < 7) {
211 // Must have at least foundation, component, protocol, priority, ip, port, type (7 groups)
212 pcre2_match_data_free(match_data);
213 pcre2_code_free(regex);
214 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid ICE candidate format");
215 }
216
217 memset(candidate, 0, sizeof(ice_candidate_t));
218
219 // Extract foundation (group 1)
220 char *foundation = asciichat_pcre2_extract_group(match_data, 1, line);
221 if (foundation && strlen(foundation) < sizeof(candidate->foundation)) {
222 SAFE_STRNCPY(candidate->foundation, foundation, sizeof(candidate->foundation));
223 }
224 SAFE_FREE(foundation);
225
226 // Extract component_id (group 2)
227 unsigned long component_id;
228 if (asciichat_pcre2_extract_group_ulong(match_data, 2, line, &component_id)) {
229 candidate->component_id = (uint32_t)component_id;
230 }
231
232 // Extract protocol (group 3)
233 char *protocol_str = asciichat_pcre2_extract_group(match_data, 3, line);
234 if (protocol_str) {
235 if (strcmp(protocol_str, "udp") == 0) {
236 candidate->protocol = ICE_PROTOCOL_UDP;
237 } else if (strcmp(protocol_str, "tcp") == 0) {
238 candidate->protocol = ICE_PROTOCOL_TCP;
239 } else {
240 SAFE_FREE(protocol_str);
241 pcre2_match_data_free(match_data);
242 pcre2_code_free(regex);
243 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid protocol");
244 }
245 SAFE_FREE(protocol_str);
246 }
247
248 // Extract priority (group 4)
249 unsigned long priority;
250 if (asciichat_pcre2_extract_group_ulong(match_data, 4, line, &priority)) {
251 candidate->priority = (uint32_t)priority;
252 }
253
254 // Extract IP address (group 5)
255 char *ip_address = asciichat_pcre2_extract_group(match_data, 5, line);
256 if (ip_address && strlen(ip_address) < sizeof(candidate->ip_address)) {
257 SAFE_STRNCPY(candidate->ip_address, ip_address, sizeof(candidate->ip_address));
258 }
259 SAFE_FREE(ip_address);
260
261 // Extract port (group 6)
262 unsigned long port;
263 if (asciichat_pcre2_extract_group_ulong(match_data, 6, line, &port)) {
264 candidate->port = (uint16_t)port;
265 }
266
267 // Extract candidate type (group 7)
268 char *type_str = asciichat_pcre2_extract_group(match_data, 7, line);
269 if (type_str) {
270 if (strcmp(type_str, "host") == 0) {
271 candidate->type = ICE_CANDIDATE_HOST;
272 } else if (strcmp(type_str, "srflx") == 0) {
273 candidate->type = ICE_CANDIDATE_SRFLX;
274 } else if (strcmp(type_str, "prflx") == 0) {
275 candidate->type = ICE_CANDIDATE_PRFLX;
276 } else if (strcmp(type_str, "relay") == 0) {
277 candidate->type = ICE_CANDIDATE_RELAY;
278 } else {
279 SAFE_FREE(type_str);
280 pcre2_match_data_free(match_data);
281 pcre2_code_free(regex);
282 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid candidate type");
283 }
284 SAFE_FREE(type_str);
285 }
286
287 // Extract optional raddr (group 8)
288 char *raddr = asciichat_pcre2_extract_group(match_data, 8, line);
289 if (raddr && strlen(raddr) < sizeof(candidate->raddr)) {
290 SAFE_STRNCPY(candidate->raddr, raddr, sizeof(candidate->raddr));
291 }
292 SAFE_FREE(raddr);
293
294 // Extract optional rport (group 9)
295 unsigned long rport;
296 if (asciichat_pcre2_extract_group_ulong(match_data, 9, line, &rport)) {
297 candidate->rport = (uint16_t)rport;
298 }
299
300 // Extract optional tcptype (group 10)
301 char *tcptype_str = asciichat_pcre2_extract_group(match_data, 10, line);
302 if (tcptype_str) {
303 if (strcmp(tcptype_str, "active") == 0) {
304 candidate->tcp_type = ICE_TCP_TYPE_ACTIVE;
305 } else if (strcmp(tcptype_str, "passive") == 0) {
306 candidate->tcp_type = ICE_TCP_TYPE_PASSIVE;
307 } else if (strcmp(tcptype_str, "so") == 0) {
308 candidate->tcp_type = ICE_TCP_TYPE_SO;
309 }
310 SAFE_FREE(tcptype_str);
311 }
312
313 pcre2_match_data_free(match_data);
314 pcre2_code_free(regex);
315 return ASCIICHAT_OK;
316}
317
319 return ice_parse_candidate_pcre2(line, candidate);
320}
321
322asciichat_error_t ice_format_candidate(const ice_candidate_t *candidate, char *line, size_t line_size) {
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}
381
382/* ============================================================================
383 * ICE Candidate Gathering
384 * ============================================================================ */
385
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}
415
416/* ============================================================================
417 * ICE Connectivity
418 * ============================================================================ */
419
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}
442
444 if (!pc) {
445 return false;
446 }
447
448 // Check peer connection state
450 return (state == WEBRTC_STATE_CONNECTED);
451}
452
453// Forward declaration of C++ implementation (in ice_selected_pair.cpp)
455
457 // Delegate to C++ implementation which uses libdatachannel's C++ API
458 return ice_get_selected_pair_impl(pc, local_candidate, remote_candidate);
459}
#define SET_ERRNO(code,...)
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_BUFFER_FULL
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
int is_lan_ipv6(const char *ip)
Check if IPv6 address is a private/LAN address.
Definition ip.c:1176
int is_localhost_ipv6(const char *ip)
Check if IPv6 address is localhost.
Definition ip.c:1280
int is_internet_ipv4(const char *ip)
Check if IPv4 address is a public internet address.
Definition ip.c:1368
int is_lan_ipv4(const char *ip)
Check if IPv4 address is a private/LAN address.
Definition ip.c:1145
int is_localhost_ipv4(const char *ip)
Check if IPv4 address is localhost.
Definition ip.c:1259
int is_internet_ipv6(const char *ip)
Check if IPv6 address is a public internet address.
Definition ip.c:1450
asciichat_error_t webrtc_add_remote_candidate(webrtc_peer_connection_t *pc, const char *candidate, const char *mid)
Add remote ICE candidate.
struct webrtc_peer_connection webrtc_peer_connection_t
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.
uint32_t ice_calculate_priority_for_candidate(const ice_candidate_t *candidate)
Calculate candidate priority with IP-aware local preference.
Definition ice.c:135
const char * ice_protocol_name(ice_protocol_t protocol)
Get human-readable protocol name.
Definition ice.c:44
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.
Definition ice.c:456
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
bool ice_is_connected(webrtc_peer_connection_t *pc)
Check ICE connection state.
Definition ice.c:443
#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
asciichat_error_t ice_parse_candidate(const char *line, ice_candidate_t *candidate)
Parse ICE candidate from attribute string.
Definition ice.c:318
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).
const char * ice_candidate_type_name(ice_candidate_type_t type)
Get human-readable candidate type name.
Definition ice.c:29
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.
Definition ice.c:420
asciichat_error_t ice_gather_candidates(const ice_config_t *config)
Start ICE candidate gathering.
Definition ice.c:386
ICE (Interactive Connectivity Establishment) for WebRTC.
ice_protocol_t
ICE candidate transport protocol.
Definition ice.h:91
@ ICE_PROTOCOL_UDP
Definition ice.h:92
@ ICE_PROTOCOL_TCP
Definition ice.h:93
ice_candidate_type_t
Credentials and callback used while gathering ICE candidates.
Definition ice.h:81
@ 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
@ ICE_TCP_TYPE_SO
Simultaneous open.
Definition ice.h:102
@ ICE_TCP_TYPE_ACTIVE
Actively opens connection.
Definition ice.h:100
@ ICE_TCP_TYPE_PASSIVE
Passively waits for connection.
Definition ice.h:101
🌍 IP Address Parsing and Formatting Utilities
📝 Logging API with multiple log levels and terminal output control
pcre2_code * asciichat_pcre2_compile(const char *pattern, uint32_t flags)
Definition pcre2.c:16
int asciichat_pcre2_match(const pcre2_code *code, PCRE2_SPTR subject, PCRE2_SIZE length, PCRE2_SIZE startoffset, uint32_t options, pcre2_match_data *match_data, pcre2_match_context *context)
Definition pcre2.c:175
char * asciichat_pcre2_extract_group(pcre2_match_data *match_data, int group_num, const char *subject)
Extract numbered capture group as allocated string.
Definition pcre2.c:79
bool asciichat_pcre2_extract_group_ulong(pcre2_match_data *match_data, int group_num, const char *subject, unsigned long *out_value)
Extract numbered capture group and convert to unsigned long.
Definition pcre2.c:136
PCRE2 compilation and match helpers.
🔤 String Manipulation and Shell Escaping Utilities
Single ICE candidate for connectivity.
Definition ice.h:118
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
uint32_t component_id
Component (1=RTP, 2=RTCP; usually 1).
Definition ice.h:121
ice_candidate_type_t type
host, srflx, prflx, or relay
Definition ice.h:130
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
Credentials and callback used while gathering ICE candidates.
Definition ice.h:170
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