ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
lib/network/webrtc/webrtc.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define NETWORK_WEBRTC_LOCAL_CANDIDATE_BUFFER_SIZE 512
4#define NETWORK_WEBRTC_REMOTE_CANDIDATE_BUFFER_SIZE 512
5#define NETWORK_WEBRTC_PC_NAME_BUFFER_SIZE 64
6#define NETWORK_WEBRTC_LABEL_BUFFER_SIZE 256
7
8/* Existing buffer budgets in bytes, including NUL for text storage. */
9#define WEBRTC_AUTH_INPUT_BUFFER_SIZE 128
10#define WEBRTC_PERCENT_ESCAPE_EXPANSION 3
11#define WEBRTC_ESCAPED_AUTH_BUFFER_SIZE (WEBRTC_AUTH_INPUT_BUFFER_SIZE * WEBRTC_PERCENT_ESCAPE_EXPANSION)
12
13/* Existing buffer budgets in bytes, including NUL for text storage. */
14#define WEBRTC_TURN_URL_BUFFER_SIZE 1024
15
16#include <recast/defer.h>
30
33#include <ascii-chat/common.h>
34#include <ascii-chat/log/log.h>
36#include <libplatform/system.h>
37#include <libplatform/lifecycle.h>
39#include <libplatform/atomic.h>
41#include <libplatform/socket.h>
42#include <libplatform/thread.h>
43#include <ascii-chat/util/ip.h>
45
46#include <string.h>
47#include <rtc/rtc.h>
48
49// ============================================================================
50// Internal Structures
51// ============================================================================
52
73
84 int rtc_id;
87
88 // Per-channel callbacks (set via webrtc_datachannel_set_callbacks)
91 void (*user_on_error)(webrtc_data_channel_t *dc, const char *error, void *user_data);
92 void (*user_on_message)(webrtc_data_channel_t *dc, const uint8_t *data, size_t len,
93 void *user_data);
94 void *user_data;
95};
96
97// Reserve a free UDP port until the first operation that constructs the ICE transport.
98// The port range forces libdatachannel to use the mapped port; a competing bind fails
99// negotiation rather than silently gathering on an unmapped socket.
100static void webrtc_release_port(webrtc_peer_connection_t *pc) {
101 if (pc->port_reservation != INVALID_SOCKET_VALUE) {
103 pc->port_reservation = INVALID_SOCKET_VALUE;
104 }
105}
106
107static void *webrtc_mapping_worker(void *arg) {
108 webrtc_peer_connection_t *pc = arg;
109 while (!atomic_load_bool(&pc->mapping_stop)) {
110 if (time_get_ns() >= pc->mapping->refresh_at_ns) {
113 LOG_ERRNO_IF_SET("WebRTC UDP mapping renewal failed");
115 }
117 }
118 return NULL;
119}
120
121static void webrtc_mapping_close(webrtc_peer_connection_t *pc) {
122 if (pc->mapping_thread_started) {
124 thread_join(&pc->mapping_thread, NULL);
125 pc->mapping_thread_started = false;
126 }
128 webrtc_release_port(pc);
129}
130
131static void webrtc_mapping_prepare(webrtc_peer_connection_t *pc, rtcConfiguration *rtc_config) {
132 if (!pc->config.port_forwarding || pc->config.relay_only) {
133 return;
134 }
135 const char *bind_address = pc->config.bind_address;
136 bool specific = bind_address && bind_address[0] && strcmp(bind_address, "0.0.0.0") != 0;
137 if (specific && (!is_valid_ipv4(bind_address) || is_localhost_ipv4(bind_address))) {
138 log_info("WebRTC UDP mapping skipped for loopback or IPv6-only binding");
139 return;
140 }
141 pc->port_reservation = socket_create("webrtc_mapping_reservation", AF_INET, SOCK_DGRAM, 0);
142 if (pc->port_reservation == INVALID_SOCKET_VALUE) {
143 return;
144 }
145 struct sockaddr_in addr = {0};
146 addr.sin_family = AF_INET;
147 addr.sin_addr.s_addr = htonl(INADDR_ANY);
148 socklen_t length = sizeof(addr);
149 if (socket_bind(pc->port_reservation, (struct sockaddr *)&addr, sizeof(addr)) != 0 || socket_getsockname(pc->port_reservation, (struct sockaddr *)&addr, &length) != 0) {
150 webrtc_release_port(pc);
151 return;
152 }
153 uint16_t port = ntohs(addr.sin_port);
155 if (nat_upnp_open_protocol(port, "ascii-chat WebRTC", NAT_UPNP_UDP, &pc->mapping) != ASCIICHAT_OK) {
157 log_warn("WebRTC UDP mapping unavailable; continuing with normal ICE/STUN/TURN");
158 webrtc_release_port(pc);
159 return;
160 }
162 if (pc->mapping->is_natpmp) {
163 pc->mapping->internal_ip[0] = '\0';
164 struct sockaddr_in gateway = {0};
165 gateway.sin_family = AF_INET;
166 gateway.sin_port = htons(5351);
167 gateway.sin_addr.s_addr = pc->mapping->gateway;
168 if (socket_connect(pc->port_reservation, (struct sockaddr *)&gateway, sizeof(gateway)) == 0 && socket_getsockname(pc->port_reservation, (struct sockaddr *)&addr, &length) == 0) {
169 inet_ntop(AF_INET, &addr.sin_addr, pc->mapping->internal_ip, sizeof(pc->mapping->internal_ip));
170 }
171 }
172 if (!pc->mapping->internal_ip[0] || (specific && strcmp(bind_address, pc->mapping->internal_ip) != 0)) {
173 // Do not map a different interface from the one selected by the caller.
174 webrtc_mapping_close(pc);
175 return;
176 }
177 atomic_store_bool(&pc->mapping_stop, false);
178 if (platform_thread_create(&pc->mapping_thread, "webrtc_mapping", webrtc_mapping_worker, pc) != 0) {
179 webrtc_mapping_close(pc);
180 return;
181 }
182 pc->mapping_thread_started = true;
183 rtc_config->portRangeBegin = port;
184 rtc_config->portRangeEnd = port;
185 rtc_config->bindAddress = pc->mapping->internal_ip;
186 log_info("WebRTC UDP mapping ready before ICE gathering: %s:%u -> %s:%u", pc->mapping->external_ip, pc->mapping->mapped_port, pc->mapping->internal_ip, port);
187}
188
189// ============================================================================
190// Global State
191// ============================================================================
192
193// WebRTC library lifecycle (one-time init/cleanup, no refcounting needed)
194static lifecycle_t g_webrtc_lc = LIFECYCLE_INIT;
195
196// ============================================================================
197// libdatachannel Callback Adapters
198// ============================================================================
199
200static void rtc_log_callback(rtcLogLevel level, const char *message) {
201 switch (level) {
202 case RTC_LOG_FATAL:
203 case RTC_LOG_ERROR:
204 log_error("[libdatachannel] %s", message);
205 break;
206 case RTC_LOG_WARNING:
207 log_warn("[libdatachannel] %s", message);
208 break;
209 case RTC_LOG_INFO:
210 log_info("[libdatachannel] %s", message);
211 break;
212 case RTC_LOG_DEBUG:
213 case RTC_LOG_VERBOSE:
214 log_debug("[libdatachannel] %s", message);
215 break;
216 default:
217 break;
218 }
219}
220
221// Forward declarations for callback functions
222static void on_datachannel_open_adapter(int dc_id, void *user_data);
223static void on_datachannel_closed_adapter(int dc_id, void *user_data);
224static void on_datachannel_message_adapter(int dc_id, const char *data, int size, void *user_data);
225static void on_datachannel_error_adapter(int dc_id, const char *error, void *user_data);
226
227static void on_state_change_adapter(int pc_id, rtcState state, void *user_data) {
229 if (!pc)
230 return;
231
232 // Map libdatachannel state to our enum
233 webrtc_state_t new_state;
234 switch (state) {
235 case RTC_NEW:
236 new_state = WEBRTC_STATE_NEW;
237 break;
238 case RTC_CONNECTING:
239 new_state = WEBRTC_STATE_CONNECTING;
240 break;
241 case RTC_CONNECTED:
242 new_state = WEBRTC_STATE_CONNECTED;
244 if (rtcGetSelectedCandidatePair(pc_id, local_candidate, sizeof(local_candidate), remote_candidate, sizeof(remote_candidate)) >= 0) {
245 log_info("WebRTC selected local candidate: %s", local_candidate);
246 log_info("WebRTC selected remote candidate: %s", remote_candidate);
247 }
248 break;
249 case RTC_DISCONNECTED:
250 new_state = WEBRTC_STATE_DISCONNECTED;
251 break;
252 case RTC_FAILED:
253 new_state = WEBRTC_STATE_FAILED;
254 break;
255 case RTC_CLOSED:
256 new_state = WEBRTC_STATE_CLOSED;
257 break;
258 default:
259 new_state = WEBRTC_STATE_NEW;
260 break;
261 }
262
263 atomic_store_u64(&pc->state, (uint64_t)new_state);
264
265 if (pc->config.on_state_change) {
266 pc->config.on_state_change(pc, new_state, pc->config.user_data);
267 }
268}
269
270static void on_gathering_state_change_adapter(int pc_id, rtcGatheringState state, void *user_data) {
271 (void)pc_id; // Unused - we get peer connection from user_data
273 if (!pc)
274 return;
275
276 // Map libdatachannel gathering state to our enum
277 webrtc_gathering_state_t new_state;
278 switch (state) {
279 case RTC_GATHERING_NEW:
280 new_state = WEBRTC_GATHERING_NEW;
281 break;
282 case RTC_GATHERING_INPROGRESS:
283 new_state = WEBRTC_GATHERING_GATHERING;
284 // Record start time when gathering begins
286 uint64_t start_time_ms = platform_get_monotonic_time_us() / 1000;
287 atomic_store_u64(&pc->gathering_start_time_ms, start_time_ms);
288 log_debug("ICE gathering started at %llu ms", (unsigned long long)start_time_ms);
289 }
290 break;
291 case RTC_GATHERING_COMPLETE:
292 new_state = WEBRTC_GATHERING_COMPLETE;
293 uint64_t gathering_start_time_ms = atomic_load_u64(&pc->gathering_start_time_ms);
294 if (gathering_start_time_ms > 0) {
295 uint64_t duration = (platform_get_monotonic_time_us() / 1000) - gathering_start_time_ms;
296 log_info("ICE gathering completed in %llu ms", (unsigned long long)duration);
297 }
298 break;
299 default:
300 new_state = WEBRTC_GATHERING_NEW;
301 break;
302 }
303
304 atomic_store_u64(&pc->gathering_state, (uint64_t)new_state);
305
307 pc->config.on_gathering_state_change(pc, new_state, pc->config.user_data);
308 }
309}
310
311static void on_local_description_adapter(int pc_id, const char *sdp, const char *type, void *user_data) {
312 (void)pc_id; // Unused - we get peer connection from user_data
314 if (!pc)
315 return;
316
318 pc->config.on_local_description(pc, sdp, type, pc->config.user_data);
319 }
320}
321
322static void on_local_candidate_adapter(int pc_id, const char *candidate, const char *mid, void *user_data) {
323 (void)pc_id; // Unused - we get peer connection from user_data
325 if (!pc)
326 return;
327
328 if (pc->config.on_local_candidate) {
329 pc->config.on_local_candidate(pc, candidate, mid, pc->config.user_data);
330 }
331}
332
333static void on_datachannel_adapter(int pc_id, int dc_id, void *user_data) {
334 (void)pc_id; // Unused - we get peer connection from user_data
335 log_info("pc_id=%d, dc_id=%d, user_data=%p", pc_id, dc_id, user_data);
336
338 if (!pc) {
339 log_error("peer connection user_data is NULL!");
340 return;
341 }
342
343 log_info("received DataChannel (dc_id=%d) from remote peer", dc_id);
344
345 // Allocate data channel wrapper
347 if (!dc) {
348 log_error("Failed to allocate data channel wrapper");
349 rtcDeleteDataChannel(dc_id);
350 return;
351 }
352
353 dc->rtc_id = dc_id;
354 dc->pc = pc;
355 atomic_store_bool(&dc->is_open, false);
356 log_debug("Initialized DataChannel wrapper: dc=%p, is_open=false", (void *)dc);
357
358 // Store in peer connection
359 pc->dc = dc;
360
361 // Set up data channel callbacks for incoming channel
362 rtcSetUserPointer(dc_id, dc);
363 rtcSetOpenCallback(dc_id, on_datachannel_open_adapter);
364 // Keep libdatachannel's receive queue intact until a consumer is installed.
365 // An adapter with no user callback would silently discard early peer hellos.
367 rtcSetMessageCallback(dc_id, on_datachannel_message_adapter);
368 rtcSetErrorCallback(dc_id, on_datachannel_error_adapter);
369
370 log_info("Set up callbacks for incoming DataChannel (dc_id=%d, dc=%p)", dc_id, (void *)dc);
371
372 // Check if DataChannel is already open (can happen if it opened before callbacks were set)
373 // In libdatachannel, negotiated DataChannels may be open immediately when received
374 // We manually trigger the open callback if that's the case
375 if (rtcIsOpen(dc_id)) {
376 log_info("DataChannel was already open when received, manually triggering open callback");
377 on_datachannel_open_adapter(dc_id, dc);
378 }
379}
380
381static void on_datachannel_open_adapter(int dc_id, void *user_data) {
383 log_info("dc_id=%d, dc=%p", dc_id, (void *)dc);
384 if (!dc) {
385 log_error("dc is NULL!");
386 return;
387 }
388
389 atomic_store_bool(&dc->is_open, true);
390 log_info("DataChannel opened (id=%d, dc=%p), set is_open=true", dc_id, (void *)dc);
391
392 // Check per-channel callback first, then fall back to peer connection callback
393 if (dc->user_on_open) {
394 log_debug("Calling per-channel on_open callback");
395 dc->user_on_open(dc, dc->user_data);
396 } else if (dc->pc && dc->pc->config.on_datachannel_open) {
397 log_debug("Calling user on_datachannel_open callback");
399 } else {
400 log_warn("No user on_datachannel_open callback registered");
401 }
402}
403
404static void on_datachannel_closed_adapter(int dc_id, void *user_data) {
406 log_info("dc_id=%d, dc=%p", dc_id, (void *)dc);
407 if (!dc) {
408 log_error("dc is NULL!");
409 return;
410 }
411
412 atomic_store_bool(&dc->is_open, false);
413 log_info("DataChannel closed (id=%d, dc=%p), set is_open=false", dc_id, (void *)dc);
414
415 // Check per-channel callback first
416 if (dc->user_on_close) {
417 log_debug("Calling per-channel on_close callback");
418 dc->user_on_close(dc, dc->user_data);
419 }
420}
421
422static void on_datachannel_message_adapter(int dc_id, const char *data, int size, void *user_data) {
423 (void)dc_id; // Unused - we get data channel from user_data
424
425 // Log at libdatachannel callback level (debug level for normal operation)
426 if (size >= 20 && data) {
427 const uint8_t *pkt = (const uint8_t *)data;
428 log_dev("★ LIBDATACHANNEL_RX: dc_id=%d, size=%d, first_20_bytes: %02x%02x%02x%02x %02x%02x%02x%02x "
429 "%02x%02x%02x%02x %02x%02x%02x%02x %02x%02x%02x%02x",
430 dc_id, size, pkt[0], pkt[1], pkt[2], pkt[3], pkt[4], pkt[5], pkt[6], pkt[7], pkt[8], pkt[9], pkt[10], pkt[11], pkt[12], pkt[13], pkt[14], pkt[15], pkt[16], pkt[17], pkt[18], pkt[19]);
431 } else {
432 log_dev("★ LIBDATACHANNEL_RX: dc_id=%d, size=%d (no data or too small)", dc_id, size);
433 }
434
436 if (!dc) {
437 log_debug("★ LIBDATACHANNEL_RX: dc=NULL, dropping message");
438 return;
439 }
440
441 // Check per-channel callback first, then fall back to peer connection callback
442 if (dc->user_on_message) {
443 dc->user_on_message(dc, (const uint8_t *)data, (size_t)size, dc->user_data);
444 } else if (dc->pc && dc->pc->config.on_datachannel_message) {
445 dc->pc->config.on_datachannel_message(dc, (const uint8_t *)data, (size_t)size, dc->pc->config.user_data);
446 }
447}
448
449static void on_datachannel_error_adapter(int dc_id, const char *error, void *user_data) {
451 if (!dc)
452 return;
453
454 log_error("DataChannel error (id=%d): %s", dc_id, error);
455
456 // Check per-channel callback first, then fall back to peer connection callback
457 if (dc->user_on_error) {
458 dc->user_on_error(dc, error, dc->user_data);
459 } else if (dc->pc && dc->pc->config.on_datachannel_error) {
460 dc->pc->config.on_datachannel_error(dc, error, dc->pc->config.user_data);
461 }
462}
463
464// ============================================================================
465// Initialization and Cleanup
466// ============================================================================
467
475static asciichat_error_t webrtc_ensure_initialized(void) {
476 if (!lifecycle_init_once(&g_webrtc_lc)) {
477 return ASCIICHAT_OK; // Already initialized
478 }
479
480 // First initialization - call library initialization exactly once
481 rtcInitLogger(log_get_level() <= LOG_DEV ? RTC_LOG_VERBOSE : RTC_LOG_INFO, rtc_log_callback);
482 rtcSctpSettings settings = {.sendBufferSize = ACIP_OUTBOUND_SCTP_RESERVE};
483 if (rtcSetSctpSettings(&settings) < 0) {
484 lifecycle_init_abort(&g_webrtc_lc);
485 return SET_ERRNO(ERROR_NETWORK, "Cannot bound SCTP send buffer");
486 }
487 rtcPreload();
488 lifecycle_init_commit(&g_webrtc_lc);
489
490 log_debug("WebRTC library initialized (libdatachannel)");
491 return ASCIICHAT_OK;
492}
493
500static void webrtc_release(void) {
501 if (lifecycle_shutdown(&g_webrtc_lc)) {
502 rtcCleanup();
503 log_info("WebRTC library cleaned up");
504 }
505}
506
508 return webrtc_ensure_initialized();
509}
510
511void webrtc_destroy(void) {
512 webrtc_release();
513}
514
515// ============================================================================
516// Peer Connection Management
517// ============================================================================
518
519// libdatachannel's C API accepts TURN credentials as URL userinfo.
520static void encode_turn_userinfo(const char *value, char *encoded, size_t size) {
521 static const char hex[] = "0123456789ABCDEF";
522 size_t out = 0;
523 for (size_t i = 0; value[i] && out + 3 < size; i++) {
524 unsigned char c = (unsigned char)value[i];
525 encoded[out++] = '%';
526 encoded[out++] = hex[c >> 4];
527 encoded[out++] = hex[c & 15];
528 }
529 encoded[out] = '\0';
530}
531
533 if (!config || !pc_out) {
534 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid config or output parameter");
535 }
536 *pc_out = NULL;
537 if ((config->stun_count && !config->stun_servers) || (config->turn_count && !config->turn_servers)) {
538 return SET_ERRNO(ERROR_INVALID_PARAM, "ICE server counts require server arrays");
539 }
540 if ((config->turn_username != NULL) != (config->turn_credential != NULL)) {
541 return SET_ERRNO(ERROR_INVALID_PARAM, "TURN overrides require both username and credential");
542 }
543
544 if (!lifecycle_is_initialized(&g_webrtc_lc)) {
545 return SET_ERRNO(ERROR_INIT, "WebRTC library not initialized");
546 }
547 if (config->relay_only && config->turn_count == 0) {
548 return SET_ERRNO(ERROR_INVALID_PARAM, "Relay only requires a TURN server with credentials");
549 }
550 for (size_t i = 0; i < config->turn_count; i++) {
551 const turn_server_t *server = &config->turn_servers[i];
552 const char *username = config->turn_username ? config->turn_username : server->username;
553 const char *credential = config->turn_credential ? config->turn_credential : server->credential;
554 if (!username[0] || !credential[0] || strlen(username) > 127 || strlen(credential) > 127) {
555 return SET_ERRNO(ERROR_INVALID_PARAM, "TURN server requires both username and credential");
556 }
557 if (strncmp(server->url, "turn:", 5) != 0 && strncmp(server->url, "turns:", 6) != 0) {
558 return SET_ERRNO(ERROR_INVALID_PARAM, "TURN server URL must start with turn: or turns:");
559 }
560 }
561
562 // Allocate peer connection wrapper
564 if (!pc) {
565 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate peer connection");
566 }
567
568 pc->port_reservation = INVALID_SOCKET_VALUE;
569 pc->config = *config; // Copy config
571 pc->dc = NULL;
572
573 // Build ICE server list for libdatachannel
574 const char **ice_servers = NULL;
575 defer(SAFE_FREE(ice_servers));
576 size_t ice_count = 0;
577 char *turn_urls = NULL;
578 defer(SAFE_FREE(turn_urls));
579
580 if (config->stun_count > 0 || config->turn_count > 0) {
581 ice_count = config->stun_count + config->turn_count;
582 ice_servers = SAFE_MALLOC(ice_count * sizeof(char *), const char **);
583 if (!ice_servers) {
584 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate ICE server list");
585 }
586
587 // Add STUN servers
588 for (size_t i = 0; i < config->stun_count; i++) {
589 ice_servers[i] = config->stun_servers[i].host;
590 }
591
592 // Add TURN servers
593 if (config->turn_count > 0) {
594 turn_urls = SAFE_CALLOC(config->turn_count, WEBRTC_TURN_URL_BUFFER_SIZE, char *);
595 if (!turn_urls) {
596 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate authenticated TURN URLs");
597 }
598 }
599 for (size_t i = 0; i < config->turn_count; i++) {
600 const turn_server_t *server = &config->turn_servers[i];
601 char username[WEBRTC_ESCAPED_AUTH_BUFFER_SIZE];
602 char credential[WEBRTC_ESCAPED_AUTH_BUFFER_SIZE];
603 encode_turn_userinfo(config->turn_username ? config->turn_username : server->username, username, sizeof(username));
604 encode_turn_userinfo(config->turn_credential ? config->turn_credential : server->credential, credential, sizeof(credential));
605 const char *address = strchr(server->url, ':') + 1;
606 while (*address == '/')
607 address++;
608 SAFE_SNPRINTF(turn_urls + i * WEBRTC_TURN_URL_BUFFER_SIZE, WEBRTC_TURN_URL_BUFFER_SIZE, "%.*s%s:%s@%s", (int)(strchr(server->url, ':') - server->url + 1), server->url, username, credential,
609 address);
610 ice_servers[config->stun_count + i] = turn_urls + i * WEBRTC_TURN_URL_BUFFER_SIZE;
611 }
612 }
613
614 // Create libdatachannel configuration
615 rtcConfiguration rtc_config;
616 memset(&rtc_config, 0, sizeof(rtc_config));
617 // libdatachannel raises SO_SNDBUF to at least the local maximum message size.
618 // Keep both limits equal so the fixed SCTP reservation covers retained bytes.
619 rtc_config.maxMessageSize = ACIP_OUTBOUND_SCTP_RESERVE;
620 rtc_config.bindAddress = config->bind_address;
621 rtc_config.iceServers = ice_servers;
622 rtc_config.iceServersCount = (int)ice_count;
623 rtc_config.iceTransportPolicy = config->relay_only ? RTC_TRANSPORT_POLICY_RELAY : RTC_TRANSPORT_POLICY_ALL;
624 if (rtc_config.bindAddress && rtc_config.bindAddress[0]) {
625 log_info("Binding WebRTC ICE sockets to %s", rtc_config.bindAddress);
626 }
627
628 webrtc_mapping_prepare(pc, &rtc_config);
629
630 // Create peer connection
631 int pc_id = rtcCreatePeerConnection(&rtc_config);
632 SAFE_FREE(turn_urls);
633 SAFE_FREE(ice_servers);
634
635 if (pc_id < 0) {
636 webrtc_mapping_close(pc);
637 return SET_ERRNO(ERROR_NETWORK, "Failed to create peer connection (rtc error %d)", pc_id);
638 }
639
640 pc->rtc_id = pc_id;
641
642 // Initialize gathering state
645
646 // Set up callbacks
647 rtcSetUserPointer(pc_id, pc);
648 rtcSetStateChangeCallback(pc_id, on_state_change_adapter);
649 rtcSetGatheringStateChangeCallback(pc_id, on_gathering_state_change_adapter);
650 rtcSetLocalDescriptionCallback(pc_id, on_local_description_adapter);
651 rtcSetLocalCandidateCallback(pc_id, on_local_candidate_adapter);
652 rtcSetDataChannelCallback(pc_id, on_datachannel_adapter);
653
654 /* Register peer connection with named registry */
656 snprintf(pc_name, sizeof(pc_name), "webrtc_peer_connection:%d", pc_id);
657 NAMED_REGISTER(pc, pc_name, "webrtc_peer_connection_t", "0x%tx", NULL);
658
659 *pc_out = pc;
660 pc = NULL;
661 log_debug("Created WebRTC peer connection (id=%d)", pc_id);
662 return ASCIICHAT_OK;
663}
664
666 if (!pc) {
667 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid peer connection");
668 return;
669 }
670
671 // Close data channel if exists
672 if (pc->dc) {
674 pc->dc = NULL;
675 }
676
677 // Close peer connection
678 rtcDeletePeerConnection(pc->rtc_id);
679 webrtc_mapping_close(pc);
680 log_debug("Closed WebRTC peer connection (id=%d)", pc->rtc_id);
681
682 SAFE_FREE(pc);
683}
684
686 if (!pc) {
687 log_warn("Peer connection is NULL");
688 return WEBRTC_STATE_CLOSED;
689 }
691}
692
700
702 if (!pc) {
703 return false;
704 }
705
706 // Only check timeout if we're actively gathering
708 return false;
709 }
710
711 // If gathering hasn't started yet (start_time == 0), no timeout
712 uint64_t gathering_start_time_ms = atomic_load_u64(&pc->gathering_start_time_ms);
713 if (gathering_start_time_ms == 0) {
714 return false;
715 }
716
717 // Check if elapsed time exceeds timeout
718 uint64_t current_time_ms = platform_get_monotonic_time_us() / 1000;
719 uint64_t elapsed_ms = current_time_ms - gathering_start_time_ms;
720
721 if (elapsed_ms > timeout_ms) {
722 return true;
723 }
724
725 return false;
726}
727
729 if (!pc) {
730 log_warn("Peer connection is NULL");
731 return NULL;
732 }
733 return pc->config.user_data;
734}
735
736// ============================================================================
737// SDP Offer/Answer Exchange
738// ============================================================================
739
741 if (!pc) {
742 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid peer connection");
743 }
744
745 // Set local description with NULL type to trigger offer generation
746 webrtc_release_port(pc);
747 int result = rtcSetLocalDescription(pc->rtc_id, NULL);
748 if (result != RTC_ERR_SUCCESS) {
749 return SET_ERRNO(ERROR_NETWORK, "Failed to create SDP offer (rtc error %d)", result);
750 }
751
752 log_debug("Creating SDP offer (pc_id=%d)", pc->rtc_id);
753 return ASCIICHAT_OK;
754}
755
757 if (!pc || !sdp || !type) {
758 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
759 }
760
761 webrtc_release_port(pc);
762 int result = rtcSetRemoteDescription(pc->rtc_id, sdp, type);
763 if (result != RTC_ERR_SUCCESS) {
764 return SET_ERRNO(ERROR_NETWORK, "Failed to set remote SDP (rtc error %d)", result);
765 }
766
767 const char *dcmap = strstr(sdp, "a=dcmap:");
768 if (strcmp(type, "offer") == 0) {
769 log_debug("Remote WebRTC offer DataChannel map: %s", dcmap ? dcmap : "(none)");
770 }
771 if (strcmp(type, "offer") == 0 && strstr(sdp, "\na=dcmap:0 label=\"acip\"") && !pc->dc) {
772 rtcDataChannelInit init = {0};
773 init.negotiated = true;
774 init.manualStream = true;
775 init.stream = 0;
776 int dc_id = rtcCreateDataChannelEx(pc->rtc_id, "acip", &init);
777 if (dc_id < 0)
778 return SET_ERRNO(ERROR_NETWORK, "Failed to create negotiated ACIP channel");
779 on_datachannel_adapter(pc->rtc_id, dc_id, pc);
780 }
781
782 log_debug("Set remote SDP description (pc_id=%d, type=%s)", pc->rtc_id, type);
783 return ASCIICHAT_OK;
784}
785
786// ============================================================================
787// ICE Candidate Exchange
788// ============================================================================
789
790asciichat_error_t webrtc_add_remote_candidate(webrtc_peer_connection_t *pc, const char *candidate, const char *mid) {
791 if (!pc || !candidate) {
792 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
793 }
794
795 log_debug(" [4] Before libdatachannel - candidate: '%s' (len=%zu)", candidate, strlen(candidate));
796 log_debug(" [4] Before libdatachannel - mid: '%s' (len=%zu)", mid ? mid : "(null)", mid ? strlen(mid) : 0);
797
798 int result = rtcAddRemoteCandidate(pc->rtc_id, candidate, mid);
799 if (result != RTC_ERR_SUCCESS) {
800 return SET_ERRNO(ERROR_NETWORK, "Failed to add remote ICE candidate (rtc error %d)", result);
801 }
802
803 log_debug("Added remote ICE candidate (pc_id=%d)", pc->rtc_id);
804 return ASCIICHAT_OK;
805}
806
807// ============================================================================
808// DataChannel Management
809// ============================================================================
810
812 if (!pc || !label || !dc_out) {
813 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
814 }
815
816 // Native peers use DCEP. Browser offers advertise the separately negotiated
817 // ACIP channel and are handled in webrtc_set_remote_description().
818 webrtc_release_port(pc);
819 int dc_id = rtcCreateDataChannel(pc->rtc_id, label);
820 if (dc_id < 0) {
821 return SET_ERRNO(ERROR_NETWORK, "Failed to create data channel (rtc error %d)", dc_id);
822 }
823
824 // Allocate wrapper
826 if (!dc) {
827 rtcDeleteDataChannel(dc_id);
828 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate data channel wrapper");
829 }
830
831 dc->rtc_id = dc_id;
832 dc->pc = pc;
833 atomic_store_bool(&dc->is_open, false);
834
835 // Set up callbacks
836 rtcSetUserPointer(dc_id, dc);
837 rtcSetOpenCallback(dc_id, on_datachannel_open_adapter);
838 // Keep libdatachannel's receive queue intact until a consumer is installed.
839 // An adapter with no user callback would silently discard early peer hellos.
841 rtcSetMessageCallback(dc_id, on_datachannel_message_adapter);
842 rtcSetErrorCallback(dc_id, on_datachannel_error_adapter);
843
844 pc->dc = dc;
845 *dc_out = dc;
846
847 // Register data channel with debug naming system
848 NAMED_REGISTER_DATACHANNEL(dc, label, NULL);
849
850 log_debug("Created DataChannel '%s' (dc_id=%d, pc_id=%d)", label, dc_id, pc->rtc_id);
851 return ASCIICHAT_OK;
852}
853
855 if (!dc || dc->rtc_id < 0 || !amount)
856 return SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel and amount are required");
857 int result = rtcGetBufferedAmount(dc->rtc_id);
858 if (result < 0)
859 return SET_ERRNO(ERROR_NETWORK, "Failed to query DataChannel buffered amount");
860 *amount = (size_t)result;
861 return ASCIICHAT_OK;
862}
863
865 if (!dc || dc->rtc_id < 0 || !size)
866 return SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel and max message size are required");
867 int result = rtcMaxMessageSize(dc->rtc_id);
868 if (result <= 0)
869 return SET_ERRNO(ERROR_NETWORK, "Failed to query DataChannel max message size");
870 *size = (size_t)result;
871 return ASCIICHAT_OK;
872}
873
875 if (!dc || dc->rtc_id < 0 || !data) {
876 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
877 }
878
879 if (!atomic_load_bool(&dc->is_open)) {
880 log_error("★ WEBRTC_DATACHANNEL_SEND: Channel not open! size=%zu, dc->rtc_id=%d", size, dc ? dc->rtc_id : -1);
881 return SET_ERRNO(ERROR_NETWORK, "DataChannel not open");
882 }
883
884 // Log packet details at network layer (debug level for normal operation)
885 if (size >= 20) {
886 const uint8_t *pkt = (const uint8_t *)data;
887 log_dev("★ RTCSENDMESSAGE_BEFORE: dc_id=%d, size=%zu, first_20_bytes: %02x%02x%02x%02x %02x%02x%02x%02x "
888 "%02x%02x%02x%02x %02x%02x%02x%02x %02x%02x%02x%02x",
889 dc->rtc_id, size, pkt[0], pkt[1], pkt[2], pkt[3], pkt[4], pkt[5], pkt[6], pkt[7], pkt[8], pkt[9], pkt[10], pkt[11], pkt[12], pkt[13], pkt[14], pkt[15], pkt[16], pkt[17], pkt[18], pkt[19]);
890 } else {
891 log_dev("★ RTCSENDMESSAGE_BEFORE: dc_id=%d, size=%zu (too small to log content)", dc->rtc_id, size);
892 }
893
894 int result = rtcSendMessage(dc->rtc_id, (const char *)data, (int)size);
895
896 log_dev("★ RTCSENDMESSAGE_AFTER: dc_id=%d, rtcSendMessage returned %d for size=%zu", dc->rtc_id, result, size);
897
898 if (result < 0) {
899 log_error("★ WEBRTC_DATACHANNEL_SEND: FAILED with error code %d", result);
900 return SET_ERRNO(ERROR_NETWORK, "Failed to send data (rtc error %d)", result);
901 }
902
903 log_dev("★ WEBRTC_DATACHANNEL_SEND: SUCCESS - sent %zu bytes", size);
904 return ASCIICHAT_OK;
905}
906
908 if (!dc) {
909 SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel is NULL");
910 return false;
911 }
912 return dc->rtc_id >= 0 && atomic_load_bool(&dc->is_open);
913}
914
916 if (!dc) {
917 SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel is NULL");
918 return;
919 }
920 atomic_store_bool(&dc->is_open, is_open);
921}
922
924 if (!dc || dc->rtc_id < 0) {
925 SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel is NULL");
926 return NULL;
927 }
928
929 static char label[NETWORK_WEBRTC_LABEL_BUFFER_SIZE];
930 int result = rtcGetDataChannelLabel(dc->rtc_id, label, sizeof(label));
931 if (result < 0) {
932 return NULL;
933 }
934
935 return label;
936}
937
939 if (!dc) {
940 SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel is NULL");
941 return;
942 }
943 if (dc->rtc_id < 0) {
944 atomic_store_bool(&dc->is_open, false);
945 return;
946 }
947
948 // Save the ID before deleting the native channel.
949 int dc_id = dc->rtc_id;
950
951 rtcDeleteDataChannel(dc_id);
952 log_debug("Closed DataChannel (dc_id=%d)", dc_id);
953 dc->rtc_id = -1;
954 atomic_store_bool(&dc->is_open, false);
955}
956
957// =============================================================================
958// DataChannel Callbacks
959// =============================================================================
960
962 if (!dc) {
963 return SET_ERRNO(ERROR_INVALID_PARAM, "DataChannel is NULL");
964 }
965
966 if (!callbacks) {
967 return SET_ERRNO(ERROR_INVALID_PARAM, "Callbacks struct is NULL");
968 }
969
970 // Store user callbacks in the data channel struct
971 dc->user_on_open = callbacks->on_open;
972 dc->user_on_close = callbacks->on_close;
973 dc->user_on_error = callbacks->on_error;
974 dc->user_on_message = callbacks->on_message;
975 dc->user_data = callbacks->user_data;
976
977 // Register adapter functions with libdatachannel (adapters use correct signature)
978 // The adapters will look up our stored callbacks and invoke them with proper types
979 if (callbacks->on_open) {
980 rtcSetOpenCallback(dc->rtc_id, on_datachannel_open_adapter);
981 }
982
983 if (callbacks->on_close) {
984 rtcSetClosedCallback(dc->rtc_id, on_datachannel_closed_adapter);
985 }
986
987 if (callbacks->on_error) {
988 rtcSetErrorCallback(dc->rtc_id, on_datachannel_error_adapter);
989 }
990
991 if (callbacks->on_message) {
992 rtcSetMessageCallback(dc->rtc_id, on_datachannel_message_adapter);
993 }
994
995 // Set user pointer to the data channel so adapters can retrieve it
996 rtcSetUserPointer(dc->rtc_id, dc);
997
998 log_debug("Set DataChannel callbacks (dc_id=%d)", dc->rtc_id);
999 return ASCIICHAT_OK;
1000}
1001
1003 if (!dc) {
1004 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid null data channel");
1005 return;
1006 }
1007
1008 // Close if still open, then free the wrapper.
1010 SAFE_FREE(dc);
1011}
1012
1013// =============================================================================
1014// Peer Connection Lifecycle
1015// =============================================================================
1016
1018 if (!pc) {
1019 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid null peer connectiont");
1020 return;
1021 }
1022
1023 rtcClose(pc->rtc_id);
1024 webrtc_mapping_close(pc);
1025 log_debug("Closed peer connection (pc_id=%d)", pc->rtc_id);
1026}
1027
1029 if (!pc) {
1030 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid null peer connectiont");
1031 return;
1032 }
1033
1034 // Close and delete peer connection
1035 rtcDeletePeerConnection(pc->rtc_id);
1036 webrtc_mapping_close(pc);
1037 log_debug("Destroyed peer connection (pc_id=%d)", pc->rtc_id);
1038
1039 SAFE_FREE(pc);
1040}
1041
1052 if (!pc) {
1053 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid null peer connectiont");
1054 return -1;
1055 }
1056 return pc->rtc_id;
1057}
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_errno_scope_t errno_scope_begin(void)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
@ ASCIICHAT_ERRNO_HANDLED
#define LOG_ERRNO_IF_SET(message)
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
uint64_t atomic_load_u64(atomic_t *a)
Atomically load a uint64_t value.
#define ACIP_OUTBOUND_SCTP_RESERVE
Platform initialization and static synchronization helpers.
int socket_close(socket_t sock)
Named object registry for debugging — log identifiable resource names.
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_SNPRINTF(buffer, buffer_size,...)
#define SAFE_CALLOC(count, size, cast)
#define SAFE_CALLOC_DEFER_FREE(name, count, size, cast)
unsigned long long uint64_t
unsigned char uint8_t
#define NAMED_REGISTER(ptr, name, type, fmt, parent_ptr)
Register any pointer with base name, type, format spec, and location (auto-suffix).
#define NAMED_REGISTER_DATACHANNEL(datachannel, name, parent_ptr)
Register a data channel with automatic format specifier.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_NETWORK
Definition error_codes.h:76
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INIT
Definition error_codes.h:60
@ ERROR_INVALID_PARAM
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
log_level_t log_get_level(void)
Get the current minimum log level.
#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
#define NS_PER_MS_INT
Definition time.h:172
void time_sleep_ns(uint64_t ns)
Configuration for adaptive sleep behavior.
Definition time.c:107
turn_server_t
Definition turn.h:106
int is_valid_ipv4(const char *ip)
Check if a string is a valid IPv4 address.
Definition ip.c:32
int is_localhost_ipv4(const char *ip)
Check if IPv4 address is localhost.
Definition ip.c:1209
asciichat_error_t webrtc_create_datachannel(webrtc_peer_connection_t *pc, const char *label, webrtc_data_channel_t **dc_out)
Create a DataChannel (for connection initiator).
void webrtc_close_peer_connection(webrtc_peer_connection_t *pc)
Close and destroy a peer connection.
asciichat_error_t webrtc_create_offer(webrtc_peer_connection_t *pc)
Create and set local SDP offer (for connection initiator).
asciichat_error_t webrtc_datachannel_set_callbacks(webrtc_data_channel_t *dc, const webrtc_datachannel_callbacks_t *callbacks)
Set DataChannel callbacks.
int webrtc_get_rtc_id(webrtc_peer_connection_t *pc)
Get the internal libdatachannel peer connection ID.
struct webrtc_data_channel webrtc_data_channel_t
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_gathering_state_t webrtc_get_gathering_state(webrtc_peer_connection_t *pc)
Get current ICE gathering state.
asciichat_error_t webrtc_init(void)
Initialize WebRTC library (libdatachannel).
asciichat_error_t webrtc_datachannel_get_max_message_size(webrtc_data_channel_t *dc, size_t *size)
void webrtc_datachannel_destroy(webrtc_data_channel_t *dc)
Destroy a DataChannel and free resources.
asciichat_error_t webrtc_create_peer_connection(const webrtc_config_t *config, webrtc_peer_connection_t **pc_out)
Create a new WebRTC peer connection.
const char * webrtc_datachannel_get_label(webrtc_data_channel_t *dc)
Get DataChannel label.
webrtc_gathering_state_t
ICE gathering state.
void * webrtc_get_user_data(webrtc_peer_connection_t *pc)
Get user data pointer from connection.
asciichat_error_t webrtc_datachannel_get_buffered_amount(webrtc_data_channel_t *dc, size_t *amount)
void webrtc_peer_connection_close(webrtc_peer_connection_t *pc)
Close a peer connection.
void webrtc_destroy(void)
Cleanup WebRTC library resources.
webrtc_state_t
ICE, signaling, DataChannel, and callback settings for a WebRTC peer.
void webrtc_peer_connection_destroy(webrtc_peer_connection_t *pc)
Destroy a peer connection and free resources.
asciichat_error_t webrtc_set_remote_description(webrtc_peer_connection_t *pc, const char *sdp, const char *type)
Set remote SDP offer/answer.
void webrtc_close_datachannel(webrtc_data_channel_t *dc)
Close a DataChannel.
bool webrtc_datachannel_is_open(webrtc_data_channel_t *dc)
Check if DataChannel is open and ready.
asciichat_error_t webrtc_datachannel_send(webrtc_data_channel_t *dc, const uint8_t *data, size_t size)
Send data over DataChannel.
bool webrtc_is_gathering_timed_out(webrtc_peer_connection_t *pc, uint32_t timeout_ms)
Check if ICE gathering has timed out.
void webrtc_datachannel_set_open_state(webrtc_data_channel_t *dc, bool is_open)
Set DataChannel open state (internal use).
@ WEBRTC_GATHERING_COMPLETE
All candidates gathered.
@ WEBRTC_GATHERING_GATHERING
Gathering candidates.
@ WEBRTC_GATHERING_NEW
Not started.
@ WEBRTC_STATE_NEW
Connection created but not started.
@ WEBRTC_STATE_DISCONNECTED
Connection lost.
@ WEBRTC_STATE_FAILED
Connection failed (fatal).
@ WEBRTC_STATE_CLOSED
Connection closed cleanly.
@ WEBRTC_STATE_CONNECTING
ICE gathering/connection in progress.
@ WEBRTC_STATE_CONNECTED
DataChannel established and ready.
int socket_t
⚙️ Common definitions, error codes, macros, and types shared throughout the application
🌍 IP Address Parsing and Formatting Utilities
#define NETWORK_WEBRTC_PC_NAME_BUFFER_SIZE
#define NETWORK_WEBRTC_LABEL_BUFFER_SIZE
#define WEBRTC_ESCAPED_AUTH_BUFFER_SIZE
#define NETWORK_WEBRTC_LOCAL_CANDIDATE_BUFFER_SIZE
#define NETWORK_WEBRTC_REMOTE_CANDIDATE_BUFFER_SIZE
#define WEBRTC_TURN_URL_BUFFER_SIZE
📝 Logging API with multiple log levels and terminal output control
static bool size_t gotel_query_t * out
Definition queries.h:8
🔤 String Manipulation and Shell Escaping Utilities
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
Atomic value wrapper for integral/boolean types.
Definition atomic.h:76
uint16_t mapped_port
External port that was mapped (may differ from internal).
Definition upnp.h:36
uint32_t gateway
NAT-PMP gateway, in network byte order.
Definition upnp.h:45
bool is_natpmp
true if NAT-PMP was used, false if UPnP
Definition upnp.h:40
uint64_t refresh_at_ns
Next renewal or retry deadline.
Definition upnp.h:48
char internal_ip[16]
LAN address used by the gateway to reach us.
Definition upnp.h:41
char external_ip[16]
Detected external/public IP (e.g., "203.0.113.42").
Definition upnp.h:35
ICE, signaling, DataChannel, and callback settings for a WebRTC peer.
webrtc_datachannel_message_callback_t on_datachannel_message
webrtc_local_description_callback_t on_local_description
const char * turn_username
Optional credential override, including full ACDS usernames.
webrtc_local_candidate_callback_t on_local_candidate
size_t stun_count
Number of STUN servers.
webrtc_gathering_state_callback_t on_gathering_state_change
bool port_forwarding
Opt-in UDP mapping before ICE gathering (native peers only).
bool relay_only
Restrict ICE to TURN relay candidates.
webrtc_datachannel_error_callback_t on_datachannel_error
turn_server_t * turn_servers
Array of TURN servers.
stun_server_t * stun_servers
Array of STUN servers.
void * user_data
Passed to all callbacks.
size_t turn_count
Number of TURN servers.
const char * bind_address
Optional local interface address for ICE sockets.
const char * turn_credential
Optional credential override.
webrtc_datachannel_open_callback_t on_datachannel_open
When code needs to work with webrtc peer connection, it keeps mapping, port_reservation,...
void(* user_on_message)(webrtc_data_channel_t *dc, const uint8_t *data, size_t len, void *user_data)
Message callback.
void(* user_on_close)(webrtc_data_channel_t *dc, void *user_data)
Close callback.
void(* user_on_open)(webrtc_data_channel_t *dc, void *user_data)
Open callback.
atomic_t is_open
Channel open state.
webrtc_peer_connection_t * pc
Parent peer connection.
int rtc_id
libdatachannel data channel ID
void * user_data
User data for per-channel callbacks.
void(* user_on_error)(webrtc_data_channel_t *dc, const char *error, void *user_data)
Error callback.
Event hooks and caller context for one WebRTC DataChannel.
void(* on_close)(webrtc_data_channel_t *dc, void *user_data)
Channel closed.
void(* on_error)(webrtc_data_channel_t *dc, const char *error, void *user_data)
Error occurred.
void(* on_open)(webrtc_data_channel_t *dc, void *user_data)
Channel opened.
void(* on_message)(webrtc_data_channel_t *dc, const uint8_t *data, size_t len, void *user_data)
Message received.
WebRTC data channel for sending/receiving messages.
webrtc_data_channel_t * dc
Primary data channel (if created/received).
atomic_t gathering_state
Current ICE gathering state.
int rtc_id
libdatachannel peer connection ID
atomic_t gathering_start_time_ms
When gathering started (platform_get_time_ms).
nat_upnp_context_t * mapping
Owned UDP mapping.
socket_t port_reservation
Held until ICE starts binding.
atomic_t state
Current connection state.
webrtc_config_t config
Configuration with callbacks.
⏱️ High-precision timing utilities using sokol_time.h and uthash
#define LOG_DEV
Definition types.h:42
asciichat_error_t nat_upnp_refresh(nat_upnp_context_t *ctx)
Refresh port mapping (e.g., for long-running servers).
Definition upnp.c:303
void nat_upnp_close(nat_upnp_context_t **ctx)
Close port mapping and clean up.
Definition upnp.c:240
asciichat_error_t nat_upnp_open_protocol(uint16_t internal_port, const char *description, nat_upnp_protocol_t protocol, nat_upnp_context_t **ctx)
Open an owned TCP or UDP mapping; close with nat_upnp_close().
Definition upnp.c:198
UPnP/NAT-PMP port mapping for TCP and UDP connectivity.
struct nat_upnp_context nat_upnp_context_t
Handle to UPnP context.
@ NAT_UPNP_UDP
Definition upnp.h:31