ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
peer_manager.c
Go to the documentation of this file.
1
13
14/* Storage capacities in elements; text buffers include the terminating NUL. */
15#define NETWORK_WEBRTC_PEER_MANAGER_REMOTE_ICE_UFRAG_BUFFER_SIZE 257
16#define NETWORK_WEBRTC_PEER_MANAGER_INCOMING_ICE_UFRAG_BUFFER_SIZE 257
17#define NETWORK_WEBRTC_PEER_MANAGER_HEX_BUFFER_SIZE 64
18#define NETWORK_WEBRTC_PEER_MANAGER_ASCII_BUFFER_SIZE 20
19
22#include <options/options.h>
25#include <ascii-chat/log/log.h>
26#include <libplatform/mutex.h>
27#include <libplatform/thread.h>
28#include <libplatform/system.h>
31#include <ascii-chat/uthash.h>
32#include <string.h>
33
65
75
93
94#define MAX_PENDING_ICE_CANDIDATES 64
95
96static void free_pending_ice_candidate(pending_ice_candidate_t *candidate) {
97 if (!candidate) {
98 return;
99 }
100 SAFE_FREE(candidate->candidate);
101 SAFE_FREE(candidate->mid);
102 SAFE_FREE(candidate);
103}
104
105static asciichat_error_t queue_pending_ice_candidate(webrtc_peer_manager_t *manager, const uint8_t participant_id[SESSION_ID_SIZE], const char *candidate, const char *mid) {
107 return SET_ERRNO(ERROR_NETWORK, "Too many ICE candidates arrived before remote SDP");
108 }
109
110 pending_ice_candidate_t *pending = SAFE_CALLOC(1, sizeof(*pending), pending_ice_candidate_t *);
111 if (!pending) {
112 return SET_ERRNO(ERROR_MEMORY, "Failed to queue early ICE candidate");
113 }
114 memcpy(pending->participant_id, participant_id, sizeof(pending->participant_id));
115 SAFE_STRDUP(pending->candidate, candidate);
116 SAFE_STRDUP(pending->mid, mid);
117 if (!pending->candidate || !pending->mid) {
118 free_pending_ice_candidate(pending);
119 return SET_ERRNO(ERROR_MEMORY, "Failed to copy early ICE candidate");
120 }
121
122 pending_ice_candidate_t **tail = &manager->pending_ice;
123 while (*tail) {
124 tail = &(*tail)->next;
125 }
126 *tail = pending;
127 manager->pending_ice_count++;
128 return ASCIICHAT_OK;
129}
130
131static asciichat_error_t apply_pending_ice_candidates(webrtc_peer_manager_t *manager, peer_entry_t *peer) {
132 pending_ice_candidate_t **link = &manager->pending_ice;
133 while (*link) {
134 pending_ice_candidate_t *pending = *link;
135 if (memcmp(pending->participant_id, peer->participant_id, sizeof(peer->participant_id)) != 0) {
136 link = &pending->next;
137 continue;
138 }
139
140 asciichat_error_t result = webrtc_add_remote_candidate(peer->pc, pending->candidate, pending->mid);
141 if (result != ASCIICHAT_OK) {
142 // A candidate queued before a retry offer can belong to the previous ICE
143 // generation. Discard that candidate, but keep processing the new SDP and
144 // the remaining trickled candidates.
145 log_warn("Discarding queued ICE candidate rejected by the new SDP: %s", asciichat_error_format(NULL, result));
146 }
147
148 *link = pending->next;
149 manager->pending_ice_count--;
150 free_pending_ice_candidate(pending);
151 }
152 return ASCIICHAT_OK;
153}
154
155static bool extract_ice_ufrag(const char *sdp, char *ufrag, size_t capacity) {
156 if (!sdp || !ufrag || capacity == 0) {
157 return false;
158 }
159
160 static const char prefix[] = "a=ice-ufrag:";
161 const char *value = strstr(sdp, prefix);
162 if (!value) {
163 ufrag[0] = '\0';
164 return false;
165 }
166
167 value += sizeof(prefix) - 1;
168 size_t length = strcspn(value, "\r\n");
169 if (length == 0 || length >= capacity) {
170 ufrag[0] = '\0';
171 return false;
172 }
173
174 memcpy(ufrag, value, length);
175 ufrag[length] = '\0';
176 return true;
177}
178
179// =============================================================================
180// Helper Functions
181// =============================================================================
182
187static peer_entry_t *find_peer_locked(webrtc_peer_manager_t *manager, const uint8_t participant_id[SESSION_ID_SIZE]) {
188 peer_entry_t *peer = NULL;
189 HASH_FIND(hh, manager->peers, participant_id, 16, peer);
190 return peer;
191}
192
197static void add_peer_locked(webrtc_peer_manager_t *manager, peer_entry_t *peer) {
198 HASH_ADD(hh, manager->peers, participant_id, 16, peer);
199}
200
205static void remove_peer_locked(webrtc_peer_manager_t *manager, peer_entry_t *peer) {
206 if (!peer) {
207 return;
208 }
209
210 HASH_DEL(manager->peers, peer);
212 if (pending)
213 acip_transport_destroy(pending);
214
215 if (peer->dc) {
217 }
218 if (peer->pc) {
220 }
221
222 if (peer->security) {
224 SAFE_FREE(peer->security);
225 }
226 SAFE_FREE(peer);
227}
228
229// =============================================================================
230// WebRTC Callbacks
231// =============================================================================
232
233static void on_peer_security_ready(acip_transport_t *transport, void *user_data) {
234 peer_entry_t *peer = user_data;
235 atomic_store_bool(&peer->security_ready, true);
236 (void)transport;
237}
238
240 if (!manager)
241 return ASCIICHAT_OK;
242 if (!thread_equal(manager->owner_thread, thread_self()))
243 return SET_ERRNO(ERROR_INVALID_STATE, "Ready transport dispatch requires the manager owner thread");
244 if (!manager->config.on_transport_ready)
245 return ASCIICHAT_OK;
246 for (;;) {
247 acip_transport_t *transport = NULL;
249 mutex_lock(&manager->peers_mutex);
250 peer_entry_t *peer, *tmp;
251 HASH_ITER(hh, manager->peers, peer, tmp) {
252 if (!atomic_load_bool(&peer->security_ready))
253 continue;
254 transport = atomic_ptr_exchange(&peer->pending_transport, NULL);
255 if (transport) {
256 memcpy(participant_id, peer->participant_id, sizeof(participant_id));
257 peer->is_connected = true;
258 break;
259 }
260 }
261 mutex_unlock(&manager->peers_mutex);
262 if (!transport)
263 return ASCIICHAT_OK;
264 manager->config.on_transport_ready(transport, participant_id, manager->config.user_data);
265 }
266}
267
271static void on_datachannel_open(webrtc_data_channel_t *dc, void *user_data) {
272 peer_entry_t *peer = (peer_entry_t *)user_data;
273
274 log_info("WebRTC DataChannel opened for participant");
275
276 // Get manager to access crypto context
277 webrtc_peer_manager_t *manager = peer->manager;
278 if (!manager) {
279 log_error("No manager found for peer");
280 return;
281 }
282
283 // For CREATOR role (server), peer->dc is NULL because the DataChannel is received, not created
284 // Update peer->dc from the dc parameter passed to this callback
285 if (!peer->dc) {
286 peer->dc = dc;
287 log_debug("Updated peer->dc from DataChannel callback (dc=%p)", (void *)peer->dc);
288 }
289
290 acip_security_t *security = peer->security;
291 if (!security)
292 return;
293 acip_transport_t *transport = acip_webrtc_transport_create_secure(peer->pc, peer->dc, security, on_peer_security_ready, peer);
294 if (!transport) {
295 return;
296 }
297 peer->security = NULL;
298 atomic_ptr_store(&peer->pending_transport, transport);
299 atomic_store_u64(&peer->handshake_started_ns, time_get_ns());
300 if (atomic_load_bool(&peer->security_ready)) {
301 on_peer_security_ready(transport, peer);
302 return;
303 }
304 asciichat_error_t result = security->handshake.is_server ? ASCIICHAT_OK : acip_security_start(security, transport);
305 if (result != ASCIICHAT_OK) {
306 log_error("Cannot start WebRTC peer security: %s", asciichat_error_format(NULL, result));
308 }
309}
310
314static void on_local_description(webrtc_peer_connection_t *pc, const char *sdp, const char *type, void *user_data) {
315 (void)pc; // Unused
316 peer_entry_t *peer = (peer_entry_t *)user_data;
317 webrtc_peer_manager_t *manager = peer->manager;
318
319 if (!manager || !manager->signaling.send_sdp) {
320 log_error("No signaling callback registered for SDP");
321 return;
322 }
323
324 log_debug("peer->session_id=%02x%02x%02x%02x..., peer->participant_id=%02x%02x%02x%02x...", peer->session_id[0], peer->session_id[1], peer->session_id[2], peer->session_id[3],
325 peer->participant_id[0], peer->participant_id[1], peer->participant_id[2], peer->participant_id[3]);
326
327 log_debug("Sending SDP %s to remote peer via ACDS", type);
328
329 asciichat_error_t result = manager->signaling.send_sdp(peer->session_id, peer->participant_id, type, sdp, manager->signaling.user_data);
330
331 if (result != ASCIICHAT_OK) {
332 log_error("Failed to send SDP via signaling: %s", asciichat_error_format(NULL, result));
333 }
334}
335
339static void on_local_candidate(webrtc_peer_connection_t *pc, const char *candidate, const char *mid, void *user_data) {
340 (void)pc; // Unused
341 peer_entry_t *peer = (peer_entry_t *)user_data;
342 webrtc_peer_manager_t *manager = peer->manager;
343
344 if (!manager || !manager->signaling.send_ice) {
345 log_error("No signaling callback registered for ICE");
346 return;
347 }
348
349 // Filter out host candidates if --webrtc-skip-host is enabled (for testing STUN/TURN)
350 if (GET_OPTION(webrtc_skip_host) && strstr(candidate, "typ host") != NULL) {
351 log_debug("Skipping host candidate (--webrtc-skip-host enabled): '%s'", candidate);
352 return;
353 }
354
355 log_debug("Sending ICE candidate to remote peer via ACDS");
356 log_debug(" [1] libdatachannel gave us candidate: '%s' (len=%zu)", candidate, strlen(candidate));
357 log_debug(" [1] libdatachannel gave us mid: '%s' (len=%zu)", mid, strlen(mid));
358
359 asciichat_error_t result = manager->signaling.send_ice(peer->session_id, peer->participant_id, candidate, mid, manager->signaling.user_data);
360
361 if (result != ASCIICHAT_OK) {
362 log_error("Failed to send ICE candidate via signaling: %s", asciichat_error_format(NULL, result));
363 }
364}
365
369static void on_state_change(webrtc_peer_connection_t *pc, webrtc_state_t state, void *user_data) {
370 (void)user_data;
371 (void)pc;
372
373 const char *state_str = "UNKNOWN";
374 switch (state) {
375 case WEBRTC_STATE_NEW:
376 state_str = "NEW";
377 break;
379 state_str = "CONNECTING";
380 break;
382 state_str = "CONNECTED";
383 break;
385 state_str = "DISCONNECTED";
386 break;
388 state_str = "FAILED";
389 break;
391 state_str = "CLOSED";
392 break;
393 }
394
395 log_debug("WebRTC peer connection state: %s", state_str);
396}
397
398// =============================================================================
399// Peer Connection Creation
400// =============================================================================
401
406static asciichat_error_t create_peer_connection_locked(webrtc_peer_manager_t *manager, const uint8_t session_id[SESSION_ID_SIZE], const uint8_t participant_id[SESSION_ID_SIZE],
407 peer_entry_t **peer_out) {
408 // Check if peer already exists
409 peer_entry_t *existing = find_peer_locked(manager, participant_id);
410 if (existing) {
411 *peer_out = existing;
412 return ASCIICHAT_OK;
413 }
414
415 // Allocate peer entry
416 peer_entry_t *peer = SAFE_CALLOC(1, sizeof(peer_entry_t), peer_entry_t *);
417 if (!peer) {
418 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate peer entry");
419 }
420
422 memcpy(peer->session_id, session_id, SESSION_ID_SIZE);
423 peer->pc = NULL;
424 peer->dc = NULL;
425 peer->is_connected = false;
426 peer->remote_sdp_attempted = false;
427 peer->remote_description_set = false;
428 peer->gathering_timeout_reported = false;
429 peer->manager = manager;
431 if (!peer->security) {
432 SAFE_FREE(peer);
433 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate peer security");
434 }
435 asciichat_error_t security_result = acip_security_init_options(peer->security, manager->role == WEBRTC_ROLE_CREATOR, true, NULL);
436 if (security_result != ASCIICHAT_OK) {
437 SAFE_FREE(peer->security);
438 SAFE_FREE(peer);
439 return security_result;
440 }
441
442 // Create WebRTC configuration
443 webrtc_config_t webrtc_config = {
444 .bind_address = manager->config.bind_address,
445 .stun_servers = manager->config.stun_servers,
446 .stun_count = manager->config.stun_count,
447 .turn_servers = manager->config.turn_servers,
448 .turn_count = manager->config.turn_count,
449 .relay_only = manager->config.relay_only,
450 .port_forwarding = GET_OPTION(enable_upnp),
451 .turn_username = manager->config.turn_username,
452 .turn_credential = manager->config.turn_credential,
453 .on_state_change = on_state_change,
454 .on_local_description = on_local_description,
455 .on_local_candidate = on_local_candidate,
456 .on_datachannel_open = on_datachannel_open,
457 .on_datachannel_message = NULL, // Handled by transport layer
458 .on_datachannel_error = NULL, // Handled by transport layer
459 .user_data = peer, // Pass peer for callbacks
460 };
461
462 // Create peer connection
463 asciichat_error_t result = webrtc_create_peer_connection(&webrtc_config, &peer->pc);
464 if (result != ASCIICHAT_OK) {
465 if (peer->security) {
467 SAFE_FREE(peer->security);
468 }
469 SAFE_FREE(peer);
470 return SET_ERRNO(result, "Failed to create WebRTC peer connection");
471 }
472
473 // The joiner creates the negotiated channel before making its offer. The
474 // creator waits for the remote offer; webrtc_set_remote_description creates
475 // its matching channel after applying that offer to avoid offer glare.
476 if (manager->role == WEBRTC_ROLE_JOINER) {
477 result = webrtc_create_datachannel(peer->pc, "acip", &peer->dc);
478 if (result != ASCIICHAT_OK) {
480 if (peer->security) {
482 SAFE_FREE(peer->security);
483 }
484 SAFE_FREE(peer);
485 return SET_ERRNO(result, "Failed to create WebRTC data channel");
486 }
487
488 webrtc_datachannel_callbacks_t dc_callbacks = {
489 .on_open = on_datachannel_open,
490 .on_close = NULL,
491 .on_error = NULL,
492 .on_message = NULL, // Handled by transport
493 .user_data = peer,
494 };
495
496 result = webrtc_datachannel_set_callbacks(peer->dc, &dc_callbacks);
497 if (result != ASCIICHAT_OK) {
500 if (peer->security) {
502 SAFE_FREE(peer->security);
503 }
504 SAFE_FREE(peer);
505 return SET_ERRNO(result, "Failed to set datachannel callbacks");
506 }
507 }
508
509 // Add to hash table
510 add_peer_locked(manager, peer);
511
512 log_debug("Created WebRTC peer connection for participant (role: %s)", manager->role == WEBRTC_ROLE_CREATOR ? "creator" : "joiner");
513
514 *peer_out = peer;
515 return ASCIICHAT_OK;
516}
517
518// =============================================================================
519// Public API
520// =============================================================================
521
523 if (!config || !signaling_callbacks || !manager_out) {
524 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
525 }
526 *manager_out = NULL;
527
528 if (!signaling_callbacks->send_sdp || !signaling_callbacks->send_ice) {
529 return SET_ERRNO(ERROR_INVALID_PARAM, "Signaling callbacks required");
530 }
531 if (config->relay_only && config->turn_count == 0) {
532 return SET_ERRNO(ERROR_INVALID_PARAM, "Relay only requires a TURN server with credentials");
533 }
534
535 // Allocate manager
537 if (!manager) {
538 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate peer manager");
539 }
540
541 memcpy(&manager->config, config, sizeof(*config));
542 memcpy(&manager->signaling, signaling_callbacks, sizeof(*signaling_callbacks));
543 manager->role = config->role;
544 manager->owner_thread = thread_self();
545 manager->peers = NULL;
546 manager->pending_ice = NULL;
547 manager->pending_ice_count = 0;
548
549 if (mutex_init(&manager->peers_mutex, "peers") != 0) {
550 SAFE_FREE(manager);
551 return SET_ERRNO(ERROR_INTERNAL, "Failed to initialize peers mutex");
552 }
553 if (mutex_init(&manager->signaling_mutex, "webrtc_signaling") != 0) {
554 mutex_destroy(&manager->peers_mutex);
555 SAFE_FREE(manager);
556 return SET_ERRNO(ERROR_INTERNAL, "Failed to initialize WebRTC signaling mutex");
557 }
558
559 log_info("Created WebRTC peer manager (role: %s)", manager->role == WEBRTC_ROLE_CREATOR ? "creator" : "joiner");
560
561 *manager_out = manager;
562 return ASCIICHAT_OK;
563}
564
566 if (!manager) {
567 return;
568 }
569
570 mutex_lock(&manager->signaling_mutex);
571 mutex_lock(&manager->peers_mutex);
572
573 // Close all peer connections
574 peer_entry_t *peer = NULL, *tmp = NULL;
575 HASH_ITER(hh, manager->peers, peer, tmp) {
576 remove_peer_locked(manager, peer);
577 }
578
579 mutex_unlock(&manager->peers_mutex);
580 pending_ice_candidate_t *pending = manager->pending_ice;
581 while (pending) {
582 pending_ice_candidate_t *next = pending->next;
583 free_pending_ice_candidate(pending);
584 pending = next;
585 }
586 mutex_unlock(&manager->signaling_mutex);
587 mutex_destroy(&manager->signaling_mutex);
588 mutex_destroy(&manager->peers_mutex);
589
590 SAFE_FREE(manager);
591
592 log_debug("Destroyed WebRTC peer manager");
593}
594
596 if (!manager || !sdp) {
597 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
598 }
599
600 // Extract SDP string and type
601 const uint8_t *sdp_data = (const uint8_t *)(sdp + 1); // After header
602 const char *sdp_type = (sdp->sdp_type == 0) ? "offer" : "answer";
603 uint16_t sdp_len = NET_TO_HOST_U16(sdp->sdp_len);
604
605 // ACDS can deliver ICE immediately after SDP. Keep both operations ordered
606 // until libdatachannel has installed the remote description and ICE transport.
607 mutex_lock(&manager->signaling_mutex);
608
609 // Allocate null-terminated buffer for SDP string (libdatachannel requires C string)
610 char *sdp_str = SAFE_MALLOC(sdp_len + 1, char *);
611 if (!sdp_str) {
612 mutex_unlock(&manager->signaling_mutex);
613 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate remote SDP buffer");
614 }
615 memcpy(sdp_str, sdp_data, sdp_len);
616 sdp_str[sdp_len] = '\0'; // Null-terminate
617
619 bool has_incoming_ice_ufrag = extract_ice_ufrag(sdp_str, incoming_ice_ufrag, sizeof(incoming_ice_ufrag));
620
621 log_debug("Handling incoming SDP %s from remote peer (len=%u)", sdp_type, sdp_len);
622
623 mutex_lock(&manager->peers_mutex);
624
625 // Find or create peer connection
626 peer_entry_t *peer;
627
628 // Special case: If receiving an answer and we're a joiner, we may have created
629 // a peer with broadcast ID (00000000...) and need to update it to the real sender_id
630 if (sdp->sdp_type == 1 && manager->role == WEBRTC_ROLE_JOINER) {
631 static const uint8_t broadcast_id[SESSION_ID_SIZE] = {0};
632 peer = find_peer_locked(manager, broadcast_id);
633 if (peer) {
634 log_debug("Updating broadcast peer with real participant_id from answer");
635 // Remove from hash with old ID
636 HASH_DEL(manager->peers, peer);
637 // Update to real participant_id
638 memcpy(peer->participant_id, sdp->sender_id, SESSION_ID_SIZE);
639 // Re-add with new ID
640 HASH_ADD(hh, manager->peers, participant_id, 16, peer);
641 }
642 }
643
644 // libdatachannel cannot apply an ICE restart to an existing peer connection.
645 // Repeated signaling can also redeliver the same offer, which must not be
646 // mistaken for a new ICE generation or applied twice.
647 if (sdp->sdp_type == 0 && manager->role == WEBRTC_ROLE_CREATOR) {
648 peer_entry_t *existing = find_peer_locked(manager, sdp->sender_id);
649 if (existing && existing->remote_sdp_attempted && existing->pc) {
650 webrtc_state_t state = webrtc_get_state(existing->pc);
651 bool comparable_ice_generation = has_incoming_ice_ufrag && existing->remote_ice_ufrag[0] != '\0';
652 bool new_ice_generation = comparable_ice_generation && strcmp(incoming_ice_ufrag, existing->remote_ice_ufrag) != 0;
653 bool terminal_state = state == WEBRTC_STATE_FAILED || state == WEBRTC_STATE_CLOSED;
654 if (!terminal_state && comparable_ice_generation && !new_ice_generation && existing->remote_description_set) {
655 log_debug("Ignoring duplicate WebRTC offer for existing ICE generation");
656 mutex_unlock(&manager->peers_mutex);
657 SAFE_FREE(sdp_str);
658 mutex_unlock(&manager->signaling_mutex);
659 return ASCIICHAT_OK;
660 }
661 if (terminal_state || new_ice_generation) {
662 log_info("Replacing WebRTC peer for %s", new_ice_generation ? "new ICE generation" : "terminal connection state");
663 remove_peer_locked(manager, existing);
664 }
665 }
666 }
667
668 asciichat_error_t result = create_peer_connection_locked(manager, sdp->session_id, sdp->sender_id, &peer);
669 if (result != ASCIICHAT_OK) {
670 mutex_unlock(&manager->peers_mutex);
671 SAFE_FREE(sdp_str);
672 mutex_unlock(&manager->signaling_mutex);
673 return SET_ERRNO(result, "Failed to create peer connection for SDP");
674 }
675
676 if (sdp->sdp_type == 0 && manager->role == WEBRTC_ROLE_CREATOR) {
677 peer->remote_sdp_attempted = true;
678 }
679
680 mutex_unlock(&manager->peers_mutex);
681
682 // Set remote SDP
683 result = webrtc_set_remote_description(peer->pc, sdp_str, sdp_type);
684 SAFE_FREE(sdp_str); // Free after use
685
686 if (result != ASCIICHAT_OK) {
687 mutex_unlock(&manager->signaling_mutex);
688 return SET_ERRNO(result, "Failed to set remote SDP");
689 }
690
691 // A peer entry can be created before its offer arrives (for example when
692 // ACDS reports a participant join). Do not treat that entry as ready for
693 // trickle ICE until libdatachannel has accepted its remote description.
694 peer->remote_description_set = true;
695 if (sdp->sdp_type == 0 && has_incoming_ice_ufrag) {
696 memcpy(peer->remote_ice_ufrag, incoming_ice_ufrag, strlen(incoming_ice_ufrag) + 1);
697 }
698
699 result = apply_pending_ice_candidates(manager, peer);
700 if (result != ASCIICHAT_OK) {
701 mutex_unlock(&manager->signaling_mutex);
702 return SET_ERRNO(result, "Failed to apply ICE candidates queued before remote SDP");
703 }
704
705 // If this is an offer and we're the creator, generate answer automatically
706 // (libdatachannel triggers on_local_description callback with answer)
707 if (sdp->sdp_type == 0 && manager->role == WEBRTC_ROLE_CREATOR) {
708 log_debug("Offer received, answer will be generated automatically");
709 }
710
711 mutex_unlock(&manager->signaling_mutex);
712 return ASCIICHAT_OK;
713}
714
716 if (!manager || !ice) {
717 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
718 }
719
720 // Extract ICE candidate and mid (both are null-terminated in the packet)
721 const char *candidate = (const char *)(ice + 1); // After header
722 size_t candidate_str_len = strlen(candidate);
723 const char *mid = candidate + candidate_str_len + 1; // After candidate + null terminator
724
725 log_debug("Handling incoming ICE candidate from remote peer (mid=%s)", mid);
726 log_debug(" [3] After ACDS recv - candidate: '%s' (len=%zu)", candidate, strlen(candidate));
727 log_debug(" [3] After ACDS recv - mid: '%s' (len=%zu)", mid, strlen(mid));
728 log_debug(" [3] After ACDS recv - header.candidate_len=%u", NET_TO_HOST_U16(ice->candidate_len));
729
730 // Hex dump first 100 bytes of payload for debugging
731 const uint8_t *payload = (const uint8_t *)(ice + 1);
732 log_debug(" [3] Hex dump of payload (first 100 bytes):");
733 for (int i = 0; i < 100 && i < (int)candidate_str_len + 20; i += 16) {
736 for (int j = 0; j < 16 && (i + j) < 100; j++) {
737 snprintf(hex + j * 3, sizeof(hex) - j * 3, "%02x ", payload[i + j]);
738 ascii[j] = (payload[i + j] >= 32 && payload[i + j] < 127) ? payload[i + j] : '.';
739 }
740 log_debug(" [%04x] %-48s %s", i, hex, ascii);
741 }
742
743 // Do not pass a candidate to libdatachannel until a preceding SDP packet has
744 // finished installing the remote ICE transport.
745 mutex_lock(&manager->signaling_mutex);
746 mutex_lock(&manager->peers_mutex);
747
748 // Find peer connection
749 peer_entry_t *peer = find_peer_locked(manager, ice->sender_id);
750 if (!peer || !peer->remote_description_set) {
751 mutex_unlock(&manager->peers_mutex);
752 asciichat_error_t result = queue_pending_ice_candidate(manager, ice->sender_id, candidate, mid);
753 mutex_unlock(&manager->signaling_mutex);
754 if (result == ASCIICHAT_OK) {
755 log_debug("Queued ICE candidate received before remote SDP was installed");
756 }
757 return result;
758 }
759
760 mutex_unlock(&manager->peers_mutex);
761
762 // Add remote ICE candidate
763 asciichat_error_t result = webrtc_add_remote_candidate(peer->pc, candidate, mid);
764 if (result != ASCIICHAT_OK) {
765 mutex_unlock(&manager->signaling_mutex);
766 return SET_ERRNO(result, "Failed to add remote ICE candidate");
767 }
768
769 mutex_unlock(&manager->signaling_mutex);
770 return ASCIICHAT_OK;
771}
772
774 if (!manager || !session_id || !participant_id) {
775 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
776 }
777
778 if (manager->role != WEBRTC_ROLE_JOINER) {
779 return SET_ERRNO(ERROR_INVALID_PARAM, "Only joiners can initiate connections");
780 }
781
782 log_debug("session_id=%02x%02x%02x%02x..., participant_id=%02x%02x%02x%02x...", session_id[0], session_id[1], session_id[2], session_id[3], participant_id[0], participant_id[1], participant_id[2],
783 participant_id[3]);
784
785 mutex_lock(&manager->peers_mutex);
786
787 // Create peer connection
788 peer_entry_t *peer;
789 asciichat_error_t result = create_peer_connection_locked(manager, session_id, participant_id, &peer);
790 if (result != ASCIICHAT_OK) {
791 mutex_unlock(&manager->peers_mutex);
792 return SET_ERRNO(result, "Failed to create peer connection");
793 }
794
795 mutex_unlock(&manager->peers_mutex);
796
797 // Note: SDP offer is automatically created by libdatachannel when rtcCreateDataChannel() is called
798 // The on_local_description callback will be triggered automatically with the offer
799 // No need to manually call webrtc_create_offer() - doing so causes "Unexpected local description" error
800
801 log_info("Initiated WebRTC connection to participant (offer auto-created by DataChannel)");
802
803 return ASCIICHAT_OK;
804}
805
807 if (!manager || !participant_id || !state_out) {
808 return false;
809 }
810
811 mutex_lock(&manager->peers_mutex);
812 peer_entry_t *peer = find_peer_locked(manager, participant_id);
813 bool found = peer && peer->pc;
814 if (found) {
815 *state_out = webrtc_get_state(peer->pc);
816 }
817 mutex_unlock(&manager->peers_mutex);
818 return found;
819}
820
822 if (!manager || !participant_id) {
823 return SET_ERRNO(ERROR_INVALID_PARAM, "Peer manager and participant ID are required");
824 }
825
826 // SDP and ICE handlers retain peer pointers after releasing peers_mutex.
827 // Serialize removal with those handlers before freeing the peer wrappers.
828 mutex_lock(&manager->signaling_mutex);
829 mutex_lock(&manager->peers_mutex);
830 peer_entry_t *peer = find_peer_locked(manager, participant_id);
831 if (peer) {
832 remove_peer_locked(manager, peer);
833 }
834 mutex_unlock(&manager->peers_mutex);
835 mutex_unlock(&manager->signaling_mutex);
836 return ASCIICHAT_OK;
837}
838
840 if (!manager) {
841 return 0;
842 }
843
844 int timeout_count = 0;
845 peer_entry_t *peer = NULL, *tmp = NULL;
846
847 mutex_lock(&manager->signaling_mutex);
848 mutex_lock(&manager->peers_mutex);
849
850 // Iterate through all peers and check for gathering timeout
851 HASH_ITER(hh, manager->peers, peer, tmp) {
852 if (!peer || !peer->pc) {
853 continue;
854 }
855
856 // Trickle ICE can connect before gathering completes. Report a slow gather,
857 // but keep the peer alive until libdatachannel reports a failed connection.
858 webrtc_state_t connection_state = webrtc_get_state(peer->pc);
859 bool gathering_timed_out = webrtc_is_gathering_timed_out(peer->pc, timeout_ms);
860 if (gathering_timed_out && !peer->gathering_timeout_reported) {
861 peer->gathering_timeout_reported = true;
862 if (manager->config.on_gathering_timeout) {
863 manager->config.on_gathering_timeout(peer->participant_id, timeout_ms, timeout_ms, manager->config.user_data);
864 }
865 log_warn("ICE gathering exceeded %ums; keeping peer alive while trickle ICE continues", timeout_ms);
866 }
867
868 uint64_t handshake_started = atomic_load_u64(&peer->handshake_started_ns);
869 bool handshake_expired = handshake_started && !atomic_load_bool(&peer->security_ready) && time_elapsed_ns(handshake_started, time_get_ns()) > 30 * NS_PER_SEC_INT;
870 if (handshake_expired || connection_state == WEBRTC_STATE_FAILED || connection_state == WEBRTC_STATE_CLOSED) {
872
873 log_error("WebRTC negotiation failed for peer (participant_id=%02x%02x%02x%02x..., timeout=%ums, "
874 "gathering=%d, connection=%d)",
875 peer->participant_id[0], peer->participant_id[1], peer->participant_id[2], peer->participant_id[3], timeout_ms, state, connection_state);
876
877 // Remove and close peers whose ICE connection has actually failed.
878 remove_peer_locked(manager, peer);
879 timeout_count++;
880
881 log_info("Closed and removed timed-out peer connection (count: %d)", timeout_count);
882 }
883 }
884
885 mutex_unlock(&manager->peers_mutex);
886 mutex_unlock(&manager->signaling_mutex);
887
888 return timeout_count;
889}
const char * asciichat_error_format(const char *message, asciichat_error_t code)
#define SET_ERRNO(code,...)
void * atomic_ptr_exchange(atomic_ptr_t *a, void *new_value)
Atomically exchange a pointer and return the old value.
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
void atomic_ptr_store(atomic_ptr_t *a, void *value)
Atomically store a pointer.
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.
void acip_transport_destroy(acip_transport_t *transport)
Destroy transport and free all resources.
🔄 Network byte order conversion helpers
#define NET_TO_HOST_U16(val)
Definition endian.h:115
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
unsigned char uint8_t
#define SAFE_STRDUP(dst, src)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_NETWORK
Definition error_codes.h:76
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_INTERNAL
Definition error_codes.h:91
#define SESSION_ID_SIZE
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
acip_webrtc_ice_t
Definition acds.h:655
acip_webrtc_sdp_t
Definition acds.h:609
#define NS_PER_SEC_INT
Definition time.h:173
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:117
#define GET_OPTION(field)
Definition options.h:1333
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
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).
bool webrtc_peer_manager_get_state(webrtc_peer_manager_t *manager, const uint8_t participant_id[16], webrtc_state_t *state_out)
asciichat_error_t webrtc_datachannel_set_callbacks(webrtc_data_channel_t *dc, const webrtc_datachannel_callbacks_t *callbacks)
Set DataChannel callbacks.
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.
asciichat_error_t webrtc_peer_manager_remove_peer(webrtc_peer_manager_t *manager, const uint8_t participant_id[16])
asciichat_error_t webrtc_peer_manager_create(const webrtc_peer_manager_config_t *config, const webrtc_signaling_callbacks_t *signaling_callbacks, webrtc_peer_manager_t **manager_out)
Create a WebRTC peer manager.
asciichat_error_t webrtc_peer_manager_handle_ice(webrtc_peer_manager_t *manager, const acip_webrtc_ice_t *ice)
Handle incoming ICE candidate from ACDS.
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.
webrtc_peer_role_t
Peer connection role (server or client).
void webrtc_datachannel_destroy(webrtc_data_channel_t *dc)
Destroy a DataChannel and free resources.
asciichat_error_t webrtc_peer_manager_handle_sdp(webrtc_peer_manager_t *manager, const acip_webrtc_sdp_t *sdp)
Handle incoming SDP message from ACDS.
void webrtc_peer_manager_destroy(webrtc_peer_manager_t *manager)
Destroy peer manager and close all connections.
asciichat_error_t webrtc_create_peer_connection(const webrtc_config_t *config, webrtc_peer_connection_t **pc_out)
Create a new WebRTC peer connection.
webrtc_gathering_state_t
ICE gathering state.
void webrtc_peer_connection_close(webrtc_peer_connection_t *pc)
Close a peer connection.
webrtc_state_t
ICE, signaling, DataChannel, and callback settings for a WebRTC peer.
asciichat_error_t webrtc_peer_manager_dispatch_ready(webrtc_peer_manager_t *manager)
struct webrtc_peer_manager webrtc_peer_manager_t
For pending ice candidate, this is the live record that ties candidate, mid, next together....
asciichat_error_t webrtc_peer_manager_connect(webrtc_peer_manager_t *manager, const uint8_t session_id[16], const uint8_t participant_id[16])
Initiate connection to remote peer (joiner role only).
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.
bool webrtc_is_gathering_timed_out(webrtc_peer_connection_t *pc, uint32_t timeout_ms)
Check if ICE gathering has timed out.
int webrtc_peer_manager_check_gathering_timeouts(webrtc_peer_manager_t *manager, uint32_t timeout_ms)
Report slow ICE gathering and remove failed connections.
@ WEBRTC_ROLE_JOINER
Session joiner - generates offers, receives answers.
@ WEBRTC_ROLE_CREATOR
Session creator - accepts offers, generates answers.
@ 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.
Transport abstraction layer for ACIP protocol.
📝 Logging API with multiple log levels and terminal output control
asciichat_error_t acip_security_start(acip_security_t *security, acip_transport_t *transport)
void acip_security_cleanup(acip_security_t *security)
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
#define NETWORK_WEBRTC_PEER_MANAGER_INCOMING_ICE_UFRAG_BUFFER_SIZE
#define NETWORK_WEBRTC_PEER_MANAGER_HEX_BUFFER_SIZE
#define NETWORK_WEBRTC_PEER_MANAGER_REMOTE_ICE_UFRAG_BUFFER_SIZE
struct pending_ice_candidate pending_ice_candidate_t
Hash-table record for one negotiated WebRTC participant.
#define MAX_PENDING_ICE_CANDIDATES
#define NETWORK_WEBRTC_PEER_MANAGER_ASCII_BUFFER_SIZE
struct acip_security acip_security_t
acip security is intentionally a small, concrete record. Fields such as handshake,...
asciichat_error_t acip_security_init_options(acip_security_t *security, bool server, bool transport_secure, const char *password_override)
uint8_t session_id[SESSION_ID_SIZE]
uint8_t participant_id[SESSION_ID_SIZE]
🔤 String Manipulation and Shell Escaping Utilities
crypto_handshake_context_t handshake
Definition security.h:19
Atomic value wrapper for integral/boolean types.
Definition atomic.h:110
Atomic value wrapper for integral/boolean types.
Definition atomic.h:76
webrtc peer manager is intentionally a small, concrete record. Fields such as role,...
char remote_ice_ufrag[257]
installed on this peer
webrtc_peer_connection_t * pc
WebRTC peer connection.
atomic_t handshake_started_ns
uint8_t participant_id[16]
Remote participant UUID (hash key).
bool is_connected
DataChannel opened.
bool remote_sdp_attempted
A remote description was applied or attempted.
struct webrtc_peer_manager * manager
Back-reference to manager.
bool gathering_timeout_reported
ICE gathering timed out while trickle candidates may still connect.
UT_hash_handle hh
uthash handle
acip_security_t * security
Owned until transferred to the transport.
bool remote_description_set
libdatachannel has installed the remote SDP and ICE transport
uint8_t session_id[16]
Session UUID.
atomic_ptr_t pending_transport
Owned until authenticated and handed to the application.
webrtc_data_channel_t * dc
WebRTC data channel.
atomic_t security_ready
Hash-table record for one negotiated WebRTC participant.
struct pending_ice_candidate * next
uint8_t participant_id[16]
ICE, signaling, DataChannel, and callback settings for a WebRTC peer.
Event hooks and caller context for one WebRTC DataChannel.
Peer manager configuration.
webrtc_peer_role_t role
Session role (creator or joiner).
size_t turn_count
Number of TURN servers.
const char * turn_credential
Optional TURN credential override.
turn_server_t * turn_servers
TURN servers for relay.
const char * turn_username
Optional TURN credential override.
const char * bind_address
Optional local interface address for ICE sockets.
size_t stun_count
Number of STUN servers.
bool relay_only
Restrict ICE to TURN relay candidates.
void * user_data
Passed to callbacks.
webrtc_transport_ready_callback_t on_transport_ready
Called when DataChannel ready.
stun_server_t * stun_servers
STUN servers for ICE.
webrtc_gathering_timeout_callback_t on_gathering_timeout
Called when ICE gathering times out.
For pending ice candidate, this is the live record that ties candidate, mid, next together....
webrtc_peer_role_t role
Session role.
mutex_t peers_mutex
Protect peers hash table.
pending_ice_candidate_t * pending_ice
ICE delivered before the peer's remote SDP.
peer_entry_t * peers
Hash table of peer connections.
webrtc_peer_manager_config_t config
Manager configuration.
webrtc_signaling_callbacks_t signaling
Signaling callbacks.
thread_id_t owner_thread
Thread responsible for delivering ready transports.
mutex_t signaling_mutex
Serialize SDP and ICE updates for each peer.
Hooks that deliver local SDP offers/answers and ICE candidates to ACDS.
void * user_data
Passed to callbacks.
webrtc_send_sdp_callback_t send_sdp
Send SDP via ACDS.
webrtc_send_ice_callback_t send_ice
Send ICE via ACDS.
⏱️ High-precision timing utilities using sokol_time.h and uthash
acip_transport_t * acip_webrtc_transport_create_secure(webrtc_peer_connection_t *peer_conn, webrtc_data_channel_t *data_channel, acip_security_t *security, void(*on_ready)(acip_transport_t *, void *), void *user_data)