ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
src/discovery/session.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define DISCOVERY_SESSION_IDENTITY_PATH_BUFFER_SIZE 256
4#define DISCOVERY_SESSION_ERROR_MSG_BUFFER_SIZE 256
5
14#include <ascii-chat/otel.h>
20
22
23#include "session.h"
24
25#include <ascii-chat/common.h>
26#include <options/options.h>
27#include <ascii-chat/log/log.h>
28#include <ascii-chat/buffer.h>
40#include "negotiate.h"
41#include "nat.h"
43#include <libplatform/compiler.h>
44#include <libplatform/system.h>
45#include <libplatform/terminal.h>
46#include <libplatform/filesystem.h>
55
56#ifdef _WIN32
57#include <time.h>
58#else
59#include <sys/time.h>
60#include <time.h>
61#endif
62
63#include <string.h>
64
68static uint64_t session_get_current_time_ms(void) {
69 return APP_CALLBACK_UINT64(platform_get_monotonic_time_us) / 1000;
70}
71
73 if (!config) {
74 SET_ERRNO(ERROR_INVALID_PARAM, "config is NULL");
75 return NULL;
76 }
77
79 if (!session) {
80 SET_ERRNO(ERROR_MEMORY, "Failed to allocate discovery session");
81 return NULL;
82 }
83
84 session->state = DISCOVERY_STATE_INIT;
85 session->handoff_generation = 1; // Match consensus_handoff_init().
86 session->acds_transport = NULL;
87 session->peer_manager = NULL;
88 session->webrtc_transport_ready = false;
89 session->webrtc_connection_initiated = false;
90 session->webrtc_retry_attempt = 0;
91 session->webrtc_last_attempt_time_ms = 0;
93 session->stun_servers = NULL;
94 session->stun_count = 0;
95 session->turn_servers = NULL;
96 session->turn_count = 0;
97
98 // Initialize host liveness detection
99 session->liveness.last_ping_sent_ms = 0;
101 session->liveness.consecutive_failures = 0;
102 session->liveness.max_failures = 3;
103 session->liveness.ping_interval_ms = 3 * MS_PER_SEC_INT; // Ping every 3 seconds
104 session->liveness.timeout_ms = 10 * MS_PER_SEC_INT; // 10 second timeout
105 session->liveness.ping_in_flight = false;
106
107 log_info("After CALLOC - participant_ctx=%p, host_ctx=%p", session->participant_ctx, session->host_ctx);
108
109 // Explicit identity credentials apply to signaling as well as media authentication.
110 const options_t *opts = options_get();
111 bool explicit_identity = opts && opts->encrypt_key[0];
113 asciichat_error_t id_result;
114 if (explicit_identity) {
115 SAFE_STRNCPY(identity_path, opts->encrypt_key, sizeof(identity_path));
116 id_result = ASCIICHAT_OK;
117 } else {
118 id_result = acds_identity_default_path(identity_path, sizeof(identity_path));
119 }
120 if (id_result == ASCIICHAT_OK) {
121 asciichat_errno_scope_t load_scope = {0};
122 bool suppressed = false;
123 if (!explicit_identity) {
124 load_scope = errno_scope_begin();
125 suppressed = errno_notifications_suppress(true);
126 }
127 if (!explicit_identity && platform_access(identity_path, PLATFORM_ACCESS_EXISTS) != 0)
128 id_result = ERROR_CONFIG;
129 else
130 id_result = acds_identity_load(identity_path, session->identity_pubkey, session->identity_seckey);
131 if (!explicit_identity) {
134 }
135 if (id_result != ASCIICHAT_OK && !explicit_identity) {
136 // File doesn't exist or is corrupted - generate new key
137 log_info("Identity key not found, generating new key");
138 id_result = acds_identity_generate(session->identity_pubkey, session->identity_seckey);
139 if (id_result == ASCIICHAT_OK) {
140 // Save for future use
141 acds_identity_save(identity_path, session->identity_pubkey, session->identity_seckey);
142 }
143 }
144 }
145
146 if (id_result != ASCIICHAT_OK && explicit_identity) {
147 SAFE_FREE(session);
148 return NULL;
149 }
150 if (id_result != ASCIICHAT_OK) {
151 NOTICE(DANGER, "DISCOVERY IDENTITY UNAVAILABLE", "Failed to load/generate identity key, using zero key");
152 memset(session->identity_pubkey, 0, sizeof(session->identity_pubkey));
153 memset(session->identity_seckey, 0, sizeof(session->identity_seckey));
154 } else {
155 char fingerprint[HEX_STRING_SIZE_32];
156 acds_identity_fingerprint(session->identity_pubkey, fingerprint);
157 log_info("Using identity key with fingerprint: %.16s...", fingerprint);
158 }
159
160 // Load multiple identity keys from options (multi-key protocol support)
161 if (opts && opts->num_identity_keys > 0) {
162 // Load all identity keys from options
163 for (size_t i = 0; i < opts->num_identity_keys && i < MAX_SESSION_KEYS; i++) {
164 uint8_t pubkey[ED25519_PUBLIC_KEY_SIZE] = {0};
165 uint8_t seckey[ED25519_PRIVATE_KEY_SIZE] = {0};
166 asciichat_error_t key_result = acds_identity_load(opts->identity_keys[i], pubkey, seckey);
167 if (key_result == ASCIICHAT_OK) {
168 memcpy(session->identity_pubkeys[session->num_identity_keys], pubkey, sizeof(pubkey));
169 memcpy(session->identity_seckeys[session->num_identity_keys++], seckey, sizeof(seckey));
170 sodium_memzero(seckey, sizeof(seckey));
171 char fingerprint[HEX_STRING_SIZE_32];
172 acds_identity_fingerprint(pubkey, fingerprint);
173 log_info("Loaded identity key #%zu with fingerprint: %.16s...", i + 1, fingerprint);
174 } else {
175 log_warn("Failed to load identity key #%zu from %s", i + 1, opts->identity_keys[i]);
176 }
177 }
178 if (session->num_identity_keys != opts->num_identity_keys) {
179 sodium_memzero(session->identity_seckey, sizeof(session->identity_seckey));
180 sodium_memzero(session->identity_seckeys, sizeof(session->identity_seckeys));
181 SAFE_FREE(session);
182 SET_ERRNO(ERROR_CRYPTO, "Could not load the complete discovery identity key set");
183 return NULL;
184 }
185 memcpy(session->identity_pubkey, session->identity_pubkeys[0], sizeof(session->identity_pubkey));
186 memcpy(session->identity_seckey, session->identity_seckeys[0], sizeof(session->identity_seckey));
187 log_info("Loaded %zu identity key(s) for multi-key protocol", session->num_identity_keys);
188 } else {
189 // Single-key mode: use only the primary identity key
190 memcpy(session->identity_pubkeys[0], session->identity_pubkey, ED25519_PUBLIC_KEY_SIZE);
191 memcpy(session->identity_seckeys[0], session->identity_seckey, sizeof(session->identity_seckey));
192 session->num_identity_keys = 1;
193 }
194
195 // ACDS connection info
196 if (config->acds_url && config->acds_url[0]) {
197 SAFE_STRNCPY(session->acds_url, config->acds_url, sizeof(session->acds_url));
198 }
199 if (config->acds_address && config->acds_address[0]) {
200 SAFE_STRNCPY(session->acds_address, config->acds_address, sizeof(session->acds_address));
201 } else {
202 SAFE_STRNCPY(session->acds_address, "127.0.0.1", sizeof(session->acds_address));
203 }
204 session->acds_port = config->acds_port > 0 ? config->acds_port : ACIP_DISCOVERY_DEFAULT_PORT;
205
206 // Session string (if joining)
207 if (config->session_string && config->session_string[0]) {
208 SAFE_STRNCPY(session->session_string, config->session_string, sizeof(session->session_string));
209 session->is_initiator = false;
210 } else {
211 session->is_initiator = true;
212 }
213 if (config->password && config->password[0]) {
214 SAFE_STRNCPY(session->password, config->password, sizeof(session->password));
215 }
216
217 // Callbacks
218 session->on_state_change = config->on_state_change;
219 session->on_session_ready = config->on_session_ready;
220 session->on_error = config->on_error;
221 session->callback_user_data = config->callback_user_data;
223 session->exit_callback_data = config->exit_callback_data;
224
225 // Initialize mutex for NAT quality protection
226 if (mutex_init(&session->nat_quality_mutex, "discovery_nat_quality") != 0) {
227 log_warn("Failed to initialize NAT quality mutex");
228 }
229
230 log_debug("Discovery session created (initiator=%d, acds=%s:%u)", session->is_initiator, session->acds_address, session->acds_port);
231
232 NAMED_REGISTER_ATOMIC(&session->liveness.last_pong_received_ms, "discovery.last_pong_received_ms", NULL);
233 return session;
234}
235
236// Join media before releasing the active transport; failed joins retain ownership.
237static asciichat_error_t release_participant_transport(discovery_session_t *session) {
238 session_participant_t *participant = session->participant_ctx;
239 if (!participant)
240 return ASCIICHAT_OK;
242 if (session_participant_has_transport(participant))
243 return SET_ERRNO(ERROR_THREAD, "Participant connection is still stopping");
244 return ASCIICHAT_OK;
245}
246
247static void release_host_control_transport(discovery_session_t *session) {
249 session->host_control_transport = NULL;
250}
251
252// Discovery retains the host control connection when media switches to WebRTC.
253static asciichat_error_t select_participant_transport(discovery_session_t *session, acip_transport_t *transport) {
254 session_participant_t *participant = session->participant_ctx;
255 bool restart_video = session_participant_is_video_active(participant);
256 bool restart_audio = session_participant_is_audio_active(participant);
260 if (previous && acip_transport_get_type(previous) == ACIP_TRANSPORT_TCP && !session->host_control_transport) {
262 if (result != ASCIICHAT_OK)
263 return result;
265 }
267 if (result != ASCIICHAT_OK)
268 return result;
269 // Ownership has transferred; a capture failure must not make the caller free the transport.
270 if (restart_video && session_participant_start_video(participant) != ASCIICHAT_OK)
271 log_warn("Failed to restart video after switching participant transport");
272 if (restart_audio && session_participant_start_audio(participant) != ASCIICHAT_OK)
273 log_warn("Failed to restart audio after switching participant transport");
274 return ASCIICHAT_OK;
275}
276
278 ASCII_OTEL_SCOPE(DISCOVERY_SHUTDOWN);
279 if (!session) {
280 return SET_ERRNO(ERROR_INVALID_PARAM, "session is NULL");
281 }
282
283 asciichat_error_t result = release_participant_transport(session);
284 if (result != ASCIICHAT_OK)
285 return result;
286 // The detector borrows the session and mutex; retain both on a timed join failure.
287 if (session->nat_detection_thread_started) {
288 asciichat_error_t join_result = thread_join_timeout(&session->nat_detection_thread, NULL, 500 * NS_PER_MS_INT);
289 if (join_result != ASCIICHAT_OK)
290 return SET_ERRNO(ERROR_THREAD, "NAT detection worker still owns discovery session");
291 session->nat_detection_thread_started = false;
292 }
293 release_host_control_transport(session);
294
295 // Close ACDS connection
296 if (session->acds_transport) {
298 session->acds_transport = NULL;
299 }
300
301 // Destroy host context if active
302 if (session->host_ctx) {
304 if (result != ASCIICHAT_OK)
305 return result;
306 session->host_ctx = NULL;
307 }
308
309 // Destroy participant context if active
310 if (session->participant_ctx) {
312 session->participant_ctx = NULL;
313 }
314
315 // Clean up WebRTC peer manager (NEW)
316 if (session->peer_manager) {
318 session->peer_manager = NULL;
319 }
320
321 // Clean up STUN/TURN server arrays (NEW)
322 if (session->stun_servers) {
323 SAFE_FREE(session->stun_servers);
324 session->stun_servers = NULL;
325 session->stun_count = 0;
326 }
327
328 if (session->turn_servers) {
329 SAFE_FREE(session->turn_servers);
330 session->turn_servers = NULL;
331 session->turn_count = 0;
332 }
333
334 // Destroy NAT quality mutex
335 mutex_destroy(&session->nat_quality_mutex);
336
338 sodium_memzero(session->password, sizeof(session->password));
339 sodium_memzero(session->identity_seckey, sizeof(session->identity_seckey));
340 sodium_memzero(session->identity_seckeys, sizeof(session->identity_seckeys));
341 SAFE_FREE(session);
342 return ASCIICHAT_OK;
343}
344
345static void set_state(discovery_session_t *session, discovery_state_t new_state) {
346 if (!session) {
347 SET_ERRNO(ERROR_INVALID_PARAM, "session is NULL");
348 return;
349 }
350
351 discovery_state_t old_state = session->state;
352 session->state = new_state;
353
354 // A host enters ACTIVE when it starts listening, before a peer connects.
355 if (new_state == DISCOVERY_STATE_ACTIVE && old_state != DISCOVERY_STATE_ACTIVE && !session->is_host && session->session_string[0]) {
357 }
358
359 // Initialize timing for WAITING_PEER state (to timeout if peer doesn't join)
360 if (new_state == DISCOVERY_STATE_WAITING_PEER) {
361 session->waiting_peer_start_ns = time_get_ns();
362 }
363
364 log_debug("Discovery state: %d -> %d", old_state, new_state);
365
366 if (session->on_state_change) {
367 session->on_state_change(new_state, session->callback_user_data);
368 }
369}
370
371static void set_error(discovery_session_t *session, asciichat_error_t error, const char *message) {
372 if (!session) {
373 SET_ERRNO(ERROR_INVALID_PARAM, "session is NULL");
374 return;
375 }
376
377 session->error = error;
378 set_state(session, DISCOVERY_STATE_FAILED);
379
380 log_error("Discovery error: %s", message ? message : "Unknown error");
381
382 if (session->on_error) {
383 session->on_error(error, message, session->callback_user_data);
384 }
385}
386
391static void *nat_detection_thread_fn(void *arg) {
392 if (!arg) {
393 return NULL;
394 }
395
397
398 stun_server_t probe = {0};
399 const char *probe_host = NULL;
400 if (!GET_OPTION(webrtc_skip_stun) && stun_servers_parse(GET_OPTION(stun_servers), OPT_ENDPOINT_STUN_SERVERS_DEFAULT, &probe, 1) > 0) {
401 probe_host = probe.host;
402 if (strncmp(probe_host, "stun:", 5) == 0)
403 probe_host += 5;
404 }
405
406 // Run blocking NAT detection in this thread (not main thread)
407 nat_quality_t quality;
408 nat_quality_init(&quality);
409 asciichat_error_t result = nat_detect_quality(&quality, probe_host, 0);
410
411 if (result == ASCIICHAT_OK) {
412 // Lock and store result
413 mutex_lock(&session->nat_quality_mutex);
414 memcpy(&session->cached_nat_quality, &quality, sizeof(nat_quality_t));
415 session->nat_quality_cached = true;
416 session->nat_quality_measured_ms = session_get_current_time_ms();
417 mutex_unlock(&session->nat_quality_mutex);
418 log_debug("★ NAT_DETECTION_COMPLETE (thread): tier=%d, nat_type=%s", nat_compute_tier(&quality), nat_type_to_string(quality.nat_type));
419 } else {
420 log_warn("NAT detection failed in background thread; retaining the previous cache");
421 }
422
423 mutex_lock(&session->nat_quality_mutex);
424 session->nat_detection_completed = true;
425 mutex_unlock(&session->nat_quality_mutex);
426 return NULL;
427}
428
435static void start_nat_detection(discovery_session_t *session) {
436 uint64_t now = session_get_current_time_ms();
437 mutex_lock(&session->nat_quality_mutex);
438 bool fresh = session->nat_quality_cached && now - session->nat_quality_measured_ms <= CONSENSUS_HANDOFF_FRESH_MS;
439 bool completed = session->nat_detection_completed;
440 mutex_unlock(&session->nat_quality_mutex);
441 if (fresh)
442 return;
443 if (session->nat_detection_thread_started) {
444 // Never join a detector that may still be doing network I/O. Poll a completed
445 // worker before reusing its handle; a failed join retains ownership for retry.
446 if (!completed || thread_join_timeout(&session->nat_detection_thread, NULL, 0) != 0)
447 return;
448 session->nat_detection_thread_started = false;
449 }
451 return;
452 session->nat_detection_attempted = true;
453 session->nat_detection_last_attempt_ms = now;
454 mutex_lock(&session->nat_quality_mutex);
455 session->nat_detection_completed = false;
456 mutex_unlock(&session->nat_quality_mutex);
457 if (platform_thread_create(&session->nat_detection_thread, "nat_detection", nat_detection_thread_fn, session) == 0) {
458 session->nat_detection_thread_started = true;
459 } else {
460 log_warn("Could not start NAT detection; handoff will use unknown NAT tier");
461 }
462}
463
464static asciichat_error_t connect_to_acds(discovery_session_t *session) {
465 ASCII_OTEL_SCOPE(DISCOVERY_CONNECT);
466 if (!session) {
467 return SET_ERRNO(ERROR_INVALID_PARAM, "null session");
468 }
469
470 set_state(session, DISCOVERY_STATE_CONNECTING_ACDS);
471
472 const char *endpoint_input = session->acds_url[0] != '\0' ? session->acds_url : session->acds_address;
473 uint16_t endpoint_default_port = session->acds_port > 0 ? session->acds_port : ACIP_DISCOVERY_DEFAULT_PORT;
474 connection_endpoint_t endpoint = {0};
475 asciichat_error_t endpoint_result = network_connection_open("discovery_acds", endpoint_input, endpoint_default_port, NULL, &session->acds_connection, &endpoint);
476 if (endpoint_result != ASCIICHAT_OK) {
477 set_error(session, endpoint_result, "Failed to connect to ACDS");
478 return endpoint_result;
479 }
480
482 SAFE_STRNCPY(session->acds_address, endpoint.host, sizeof(session->acds_address));
483 session->acds_port = endpoint.port;
484
485 if (endpoint.protocol == CONNECTION_ENDPOINT_WEBSOCKET) {
486 log_info("Connected to ACDS via WebSocket: %s", endpoint.input);
487 } else {
488 log_info("Connected to ACDS at %s:%u", session->acds_address, session->acds_port);
489 }
490
491 return ASCIICHAT_OK;
492}
493
494static asciichat_error_t discovery_protocol_send(void *transport, packet_type_t type, const void *payload, size_t length) {
495 return packet_send_via_transport(transport, type, payload, length, 0);
496}
497static asciichat_error_t discovery_protocol_receive(discovery_session_t *session, acds_protocol_t *protocol) {
498 packet_type_t type;
499 void *payload = NULL, *allocation = NULL;
500 size_t length = 0;
501 asciichat_error_t result = acds_receive_packet(session->acds_transport, &type, &payload, &length, &allocation);
502 if (result == ASCIICHAT_OK)
503 result = acds_protocol_receive(protocol, type, payload, length);
504 buffer_release(allocation);
505 if (result != ASCIICHAT_OK && !(result == ERROR_INVALID_PASSWORD && session->state == DISCOVERY_STATE_JOINING_SESSION))
506 set_error(session, result, protocol->error[0] ? protocol->error : "Discovery receive failed");
507 return result;
508}
509
510static asciichat_error_t create_session(discovery_session_t *session) {
511 ASCII_OTEL_SCOPE(DISCOVERY_CREATE);
512 if (!session) {
513 return SET_ERRNO(ERROR_INVALID_PARAM, "null session");
514 }
515
516 set_state(session, DISCOVERY_STATE_CREATING_SESSION);
517 log_info("Creating new discovery session...");
518
519 acds_protocol_t protocol;
520 acds_protocol_init(&protocol, discovery_protocol_send, session->acds_transport);
521 for (size_t key_idx = 0; key_idx < session->num_identity_keys; ++key_idx) {
522 acds_session_create_params_t params = {0};
523 memcpy(params.identity_pubkey, session->identity_pubkeys[key_idx], sizeof(params.identity_pubkey));
524 memcpy(params.identity_seckey, session->identity_seckeys[key_idx], sizeof(params.identity_seckey));
525 params.capabilities = 3;
528 params.has_password = session->password[0] != 0;
529 SAFE_STRNCPY(params.password, session->password, sizeof(params.password));
530 // An empty address lets ACDS use the creator's observed source address.
531 params.acds_expose_ip = GET_OPTION(discovery_expose_ip);
532 params.server_port = (uint16_t)GET_OPTION(port);
533 if (GET_OPTION(quic_bind_address)[0] || (GET_OPTION(webtransport_bind_address)[0] || GET_OPTION(webtransport_origin)[0]))
534 params.quic_port = (uint16_t)(GET_OPTION(quic_port) ? GET_OPTION(quic_port) : GET_OPTION(port));
535 if ((GET_OPTION(webtransport_bind_address)[0] || GET_OPTION(webtransport_origin)[0])) {
536 if (strlen(GET_OPTION(webtransport_public_url)) >= sizeof(params.webtransport_url)) {
537 acds_protocol_destroy(&protocol);
538 return SET_ERRNO(ERROR_USAGE, "WebTransport public URL exceeds the discovery endpoint limit");
539 }
540 SAFE_STRNCPY(params.webtransport_url, GET_OPTION(webtransport_public_url), sizeof(params.webtransport_url));
541 }
542 asciichat_error_t result = acds_protocol_create(&protocol, &params, (uint8_t)session->num_identity_keys, (uint8_t)key_idx);
543 sodium_memzero(&params, sizeof(params));
544 if (result != ASCIICHAT_OK) {
545 acds_protocol_destroy(&protocol);
546 return result;
547 }
548 }
549 asciichat_error_t result = discovery_protocol_receive(session, &protocol);
550 if (result != ASCIICHAT_OK) {
551 acds_protocol_destroy(&protocol);
552 return result;
553 }
554 acip_session_created_t created_value = protocol.created;
555 acip_session_created_t *created = &created_value;
556 void *alloc_buffer = NULL;
557 acds_protocol_destroy(&protocol);
558
559 // Store session info
560 memcpy(session->session_id, created->session_id, SESSION_ID_SIZE);
561 SAFE_STRNCPY(session->session_string, created->session_string, sizeof(session->session_string));
562
563 // We're also participant 0 (initiator)
564 memcpy(session->participant_id, created->session_id,
565 SESSION_ID_SIZE); // Use session ID as participant ID for initiator
566 memcpy(session->initiator_id, session->participant_id, SESSION_ID_SIZE);
567
568 log_info("Session created: %s", session->session_string);
569
570 buffer_release(alloc_buffer);
571
572 // Notify that session is ready
573 if (session->on_session_ready) {
574 session->on_session_ready(session->session_string, session->callback_user_data);
575 }
576
577 // Wait for peer to join
578 set_state(session, DISCOVERY_STATE_WAITING_PEER);
579
580 return ASCIICHAT_OK;
581}
582
583// ============================================================================
584// WebRTC Support Functions (NEW)
585// ============================================================================
586
590static asciichat_error_t discovery_send_sdp_via_acds(const uint8_t session_id[SESSION_ID_SIZE], const uint8_t recipient_id[SESSION_ID_SIZE], const char *sdp_type, const char *sdp, void *user_data) {
591 discovery_session_t *session = (discovery_session_t *)user_data;
592
593 if (!session || !session->acds_transport) {
594 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid session or ACDS transport");
595 }
596
597 // Build ACIP SDP packet
598 size_t sdp_len = strlen(sdp);
599 size_t total_len = sizeof(acip_webrtc_sdp_t) + sdp_len;
600
601 uint8_t *packet_data = SAFE_MALLOC(total_len, uint8_t *);
602 if (!packet_data) {
603 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate SDP packet");
604 }
605 acip_webrtc_sdp_t *sdp_msg = (acip_webrtc_sdp_t *)packet_data;
606
607 memcpy(sdp_msg->session_id, session_id, SESSION_ID_SIZE);
608 memcpy(sdp_msg->sender_id, session->participant_id, SESSION_ID_SIZE);
609 memcpy(sdp_msg->recipient_id, recipient_id, SESSION_ID_SIZE);
610 sdp_msg->sdp_type = (strcmp(sdp_type, "offer") == 0) ? 0 : 1;
611 sdp_msg->sdp_len = HOST_TO_NET_U16(sdp_len);
612 // NOLINTNEXTLINE(bugprone-not-null-terminated-result) - binary packet data
613 memcpy(packet_data + sizeof(acip_webrtc_sdp_t), sdp, sdp_len);
614
615 // Send to ACDS
616 asciichat_error_t result = packet_send_via_transport(session->acds_transport, PACKET_TYPE_ACIP_WEBRTC_SDP, packet_data, total_len, 0);
617
618 SAFE_FREE(packet_data);
619
620 if (result != ASCIICHAT_OK) {
621 return SET_ERRNO(ERROR_NETWORK, "Failed to send SDP to ACDS");
622 }
623
624 log_info("Sent SDP %s to ACDS (len=%zu)", sdp_type, sdp_len);
625 return ASCIICHAT_OK;
626}
627
631static asciichat_error_t discovery_send_ice_via_acds(const uint8_t session_id[SESSION_ID_SIZE], const uint8_t recipient_id[SESSION_ID_SIZE], const char *candidate, const char *mid, void *user_data) {
632 discovery_session_t *session = (discovery_session_t *)user_data;
633
634 if (!session || !session->acds_transport) {
635 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid session or ACDS transport");
636 }
637
638 // Calculate payload length (candidate + null + mid + null)
639 size_t candidate_len = strlen(candidate);
640 size_t mid_len = strlen(mid);
641 size_t payload_len = candidate_len + 1 + mid_len + 1;
642
643 // Allocate packet buffer (header + payload)
644 size_t total_len = sizeof(acip_webrtc_ice_t) + payload_len;
645 uint8_t *packet_data = SAFE_MALLOC(total_len, uint8_t *);
646 if (!packet_data) {
647 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate ICE packet");
648 }
649
650 // Fill header
651 acip_webrtc_ice_t *ice_msg = (acip_webrtc_ice_t *)packet_data;
652 memcpy(ice_msg->session_id, session_id, SESSION_ID_SIZE);
653 memcpy(ice_msg->sender_id, session->participant_id, SESSION_ID_SIZE);
654 memcpy(ice_msg->recipient_id, recipient_id, SESSION_ID_SIZE);
655 ice_msg->candidate_len = HOST_TO_NET_U16((uint16_t)candidate_len);
656
657 // Copy candidate and mid after header
658 uint8_t *payload = packet_data + sizeof(acip_webrtc_ice_t);
659 memcpy(payload, candidate, candidate_len);
660 payload[candidate_len] = '\0';
661 memcpy(payload + candidate_len + 1, mid, mid_len);
662 payload[candidate_len + 1 + mid_len] = '\0';
663
664 log_debug("Sending ICE candidate to ACDS (candidate_len=%zu, mid=%s)", candidate_len, mid);
665
666 // Send to ACDS
667 asciichat_error_t result = packet_send_via_transport(session->acds_transport, PACKET_TYPE_ACIP_WEBRTC_ICE, packet_data, total_len, 0);
668
669 SAFE_FREE(packet_data);
670
671 if (result != ASCIICHAT_OK) {
672 return SET_ERRNO(ERROR_NETWORK, "Failed to send ICE to ACDS");
673 }
674
675 log_debug("Sent ICE candidate to ACDS (candidate_len=%zu, mid=%s)", candidate_len, mid);
676 return ASCIICHAT_OK;
677}
678
687static uint32_t calculate_backoff_delay_ms(int attempt) {
688 // Base delay: 2^attempt seconds (clamp attempt to valid range)
689 if (attempt < 0) {
690 attempt = 0;
691 } else if (attempt > 30) {
692 attempt = 30; // Prevent overflow
693 }
694 // Saturate before shifting: a large attempt can wrap a 32-bit delay to zero.
695 uint32_t base_delay_ms = attempt >= 5 ? 30 * MS_PER_SEC_INT : 1000U << attempt;
696
697 // Cap at 30 seconds
698 if (base_delay_ms > 30 * MS_PER_SEC_INT) {
699 base_delay_ms = 30 * MS_PER_SEC_INT;
700 }
701
702 // Add jitter (0-1000ms) to prevent thundering herd
703 // Use monotonic time as pseudo-random seed
704 uint32_t jitter_ms = (uint32_t)(APP_CALLBACK_UINT64(platform_get_monotonic_time_us) % 1000);
705
706 return base_delay_ms + jitter_ms;
707}
708
716static void discovery_on_gathering_timeout(const uint8_t participant_id[SESSION_ID_SIZE], uint32_t timeout_ms, uint64_t elapsed_ms, void *user_data) {
717 (void)user_data; // Session context not needed for logging
718
719 log_warn("ICE candidate gathering is slower than expected; continuing trickle ICE");
720 log_debug(" Participant: %02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", participant_id[0], participant_id[1], participant_id[2], participant_id[3], participant_id[4],
723 log_warn(" Gathering timeout: %u ms (elapsed: %llu ms)", timeout_ms, (unsigned long long)elapsed_ms);
724 log_debug("Possible causes include unreachable STUN/TURN servers or network filtering");
725}
726
741static void discovery_on_transport_ready(acip_transport_t *transport, const uint8_t participant_id[SESSION_ID_SIZE], void *user_data) {
742 discovery_session_t *session = (discovery_session_t *)user_data;
743
744 if (!session) {
745 SET_ERRNO(ERROR_INVALID_STATE, "session is NULL");
746 return;
747 }
748
749 log_info("========== WebRTC DataChannel READY ==========");
750 log_info("WebRTC DataChannel successfully established and wrapped in ACIP transport");
751 log_debug(" Remote participant: %02x%02x%02x%02x-...", participant_id[0], participant_id[1], participant_id[2], participant_id[3]);
752 log_info(" Transport status: READY for media transmission");
753 log_info(" Encryption: DTLS (automatic) + optional ACIP layer encryption");
754
755 // Mark transport as ready
756
757 if (session->session_type != SESSION_TYPE_WEBRTC) {
758 log_warn("WebRTC transport ready but session type is not WebRTC!");
759 return;
760 }
761
762 log_info("========== WebRTC Media Channel ACTIVE ==========");
763 log_info("Switching to WebRTC transport for media transmission...");
764
765 // Implement transport switching for participant/host
766 if (session->is_host && session->host_ctx) {
767 asciichat_error_t result = session_host_accept_peer(session->host_ctx, transport);
768 if (result != ASCIICHAT_OK) {
769 log_error("Cannot admit host peer: %s", asciichat_error_format(NULL, result));
770 acip_transport_destroy(transport);
771 return;
772 }
773 } else if (session->participant_ctx) {
774 // We are a participant - set transport for ourselves
775 asciichat_error_t result = select_participant_transport(session, transport);
776 if (result == ASCIICHAT_OK) {
777 log_info("✓ Participant: Successfully switched to WebRTC transport");
778 log_info(" TCP connection remains open as control/signaling channel");
779 log_info(" Media frames will now be transmitted over WebRTC DataChannel");
780 } else {
781 log_error("✗ Participant: Failed to set WebRTC transport: %d", result);
782 acip_transport_destroy(transport);
783 return;
784 }
785 } else {
787 .address = session->host_address,
788 .port = session->host_port,
789 .enable_video = true,
790 .enable_audio = GET_OPTION(audio_enabled),
791 .encryption_enabled = false,
792 };
793 session->participant_ctx = session_participant_create(&pconfig);
794 if (!session->participant_ctx || select_participant_transport(session, transport) != ASCIICHAT_OK) {
795 acip_transport_destroy(transport);
796 set_error(session, ERROR_INVALID_STATE, "Failed to attach WebRTC participant transport");
797 return;
798 }
799 }
800 session->webrtc_transport_ready = true;
801 session->webrtc_disconnected_since_ms = 0;
802 session->webrtc_retry_attempt = 0;
803}
804
811static asciichat_error_t initialize_webrtc_peer_manager(discovery_session_t *session) {
812 if (!session) {
813 return SET_ERRNO(ERROR_INVALID_PARAM, "session is NULL");
814 }
815
816 // Initialize WebRTC library (idempotent)
817 asciichat_error_t init_result = webrtc_init();
818 if (init_result != ASCIICHAT_OK) {
819 return SET_ERRNO(ERROR_NETWORK, "Failed to initialize WebRTC library");
820 }
821
822 const char *custom_username = GET_OPTION(turn_username);
823 const char *custom_credential = GET_OPTION(turn_credential);
824 bool custom_turn = custom_username[0] || custom_credential[0];
825 if (custom_turn && (!custom_username[0] || !custom_credential[0])) {
826 return SET_ERRNO(ERROR_INVALID_PARAM, "Provide both --turn-username and --turn-credential");
827 }
828 const char *turn_username = custom_turn ? custom_username : session->turn_username;
829 const char *turn_credential = custom_turn ? custom_credential : session->turn_password;
830 if (custom_turn && (strlen(turn_username) >= sizeof(session->turn_username) || strlen(turn_credential) >= sizeof(session->turn_password))) {
831 return SET_ERRNO(ERROR_INVALID_PARAM, "TURN username and credential must each fit 127 bytes");
832 }
833 if (custom_turn) {
834 SAFE_STRNCPY(session->turn_username, custom_username, sizeof(session->turn_username));
835 SAFE_STRNCPY(session->turn_password, custom_credential, sizeof(session->turn_password));
836 }
837 if (GET_OPTION(webrtc_relay_only) && (GET_OPTION(webrtc_disable_turn) || GET_OPTION(no_webrtc))) {
838 return SET_ERRNO(ERROR_INVALID_PARAM, "--webrtc-relay-only conflicts with disabled TURN or WebRTC");
839 }
840
841 const char *stun_servers_option = GET_OPTION(stun_servers);
842 bool default_stun_servers = !stun_servers_option || stun_servers_option[0] == '\0' || strcmp(stun_servers_option, OPT_ENDPOINT_STUN_SERVERS_DEFAULT) == 0;
843 bool tailscale_direct = default_stun_servers && is_tailscale_host(GET_OPTION(discovery_server));
844
845 // A Tailscale discovery service already provides a private mesh path. Avoid
846 // sharing its ICE socket with public STUN when the default servers are used:
847 // some macOS networks reject those UDP sends and libjuice then abandons the
848 // otherwise reachable Tailscale host candidate.
849 if (GET_OPTION(webrtc_skip_stun) || tailscale_direct) {
850 if (tailscale_direct && !GET_OPTION(webrtc_skip_stun)) {
851 log_info("Skipping default STUN for Tailscale discovery service; using mesh host candidates");
852 } else {
853 log_info("Skipping STUN (--webrtc-skip-stun)");
854 }
855 session->stun_servers = NULL;
856 session->stun_count = 0;
857 } else {
858 // Parse STUN servers from options (supports up to 4 servers for redundancy)
859 const int max_stun_servers = 4;
860 session->stun_servers = SAFE_MALLOC(max_stun_servers * sizeof(stun_server_t), stun_server_t *);
861 if (!session->stun_servers) {
862 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate STUN server array");
863 }
864
865 // Parse comma-separated STUN server list from options
866 session->stun_count = stun_servers_parse(GET_OPTION(stun_servers), OPT_ENDPOINT_STUN_SERVERS_DEFAULT, session->stun_servers, max_stun_servers);
867
868 if (session->stun_count == 0) {
869 log_warn("No STUN servers configured, WebRTC may fail with symmetric NAT");
870 SAFE_FREE(session->stun_servers);
871 session->stun_servers = NULL;
872 } else {
873 log_info("Configured %d STUN server(s) for WebRTC", session->stun_count);
874 }
875 }
876
877 // Set up TURN servers (if credentials available from ACDS and not disabled)
878 if (GET_OPTION(webrtc_disable_turn)) {
879 log_info("TURN disabled (--webrtc-disable-turn)");
880 session->turn_servers = NULL;
881 session->turn_count = 0;
882 } else if (turn_username[0] != '\0' && turn_credential[0] != '\0') {
883 // Parse TURN servers from options and apply ACDS credentials to each
884 const char *turn_servers_str = GET_OPTION(turn_servers);
885 if (!turn_servers_str || turn_servers_str[0] == '\0') {
886 turn_servers_str = OPT_ENDPOINT_TURN_SERVERS_DEFAULT;
887 }
888
889 // Allocate array for up to 4 TURN servers
890 const int max_turn_servers = 4;
891 session->turn_servers = SAFE_MALLOC(max_turn_servers * sizeof(turn_server_t), turn_server_t *);
892 if (!session->turn_servers) {
893 SAFE_FREE(session->stun_servers);
894 session->stun_servers = NULL;
895 session->stun_count = 0;
896 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate TURN server array");
897 }
898
899 asciichat_error_t parse_result = webrtc_turn_servers_parse(turn_servers_str, turn_username, turn_credential, session->turn_servers, max_turn_servers, &session->turn_count);
900 if (parse_result != ASCIICHAT_OK) {
901 SAFE_FREE(session->turn_servers);
902 session->turn_servers = NULL;
903 session->turn_count = 0;
904 return parse_result;
905 }
906
907 if (session->turn_count > 0) {
908 log_info("Configured %zu TURN server(s) with %s credentials", session->turn_count, custom_turn ? "custom" : "ACDS");
909 } else {
910 log_warn("No valid TURN servers configured");
911 SAFE_FREE(session->turn_servers);
912 session->turn_servers = NULL;
913 }
914 } else {
915 log_info("No TURN credentials from ACDS - will rely on direct P2P + STUN (sufficient for most NAT scenarios)");
916 session->turn_servers = NULL;
917 session->turn_count = 0;
918 }
919
920 // The session host accepts offers and generates answers. A newly created
921 // session has not set is_host yet when this runs, but its initiator will
922 // become the host during NAT negotiation. Treat that initiator as the
923 // responder now so it does not generate a competing offer for a browser.
925
926 log_info("Initializing WebRTC peer manager (role=%s, stun_count=%zu, turn_count=%zu)", role == WEBRTC_ROLE_JOINER ? "JOINER" : "CREATOR", session->stun_count, session->turn_count);
927
928 // ICE needs its own interface selection: the TCP listener and signaling
929 // service addresses do not determine where a peer can receive UDP.
930 const char *ice_bind_address = GET_OPTION(webrtc_bind_address);
931 // Create peer manager configuration
932 webrtc_peer_manager_config_t pm_config = {.role = role,
933 .bind_address = ice_bind_address[0] ? ice_bind_address : NULL,
934 .stun_servers = session->stun_servers,
935 .stun_count = session->stun_count,
936 .turn_servers = session->turn_servers,
937 .turn_count = session->turn_count,
938 .relay_only = GET_OPTION(webrtc_relay_only),
939 .turn_username = session->turn_username,
940 .turn_credential = session->turn_password,
941 .on_transport_ready = discovery_on_transport_ready,
942 .on_gathering_timeout = discovery_on_gathering_timeout,
943 .user_data = session};
944
945 // Create signaling callbacks
946 webrtc_signaling_callbacks_t signaling = {.send_sdp = discovery_send_sdp_via_acds, .send_ice = discovery_send_ice_via_acds, .user_data = session};
947
948 // Create peer manager
949 asciichat_error_t result = webrtc_peer_manager_create(&pm_config, &signaling, &session->peer_manager);
950 if (result != ASCIICHAT_OK) {
951 // Clean up on error
952 SAFE_FREE(session->stun_servers);
953 session->stun_servers = NULL;
954 session->stun_count = 0;
955 if (session->turn_servers) {
956 SAFE_FREE(session->turn_servers);
957 session->turn_servers = NULL;
958 }
959 session->turn_count = 0;
960 }
961
962 return result;
963}
964
968static void handle_discovery_webrtc_sdp(discovery_session_t *session, void *data, size_t len) {
969 if (len < sizeof(acip_webrtc_sdp_t)) {
970 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid SDP packet size: %zu", len);
971 return;
972 }
973
974 const acip_webrtc_sdp_t *sdp_msg = (const acip_webrtc_sdp_t *)data;
975 uint16_t sdp_len = NET_TO_HOST_U16(sdp_msg->sdp_len);
976
977 if (len != sizeof(acip_webrtc_sdp_t) + sdp_len) {
978 log_error("SDP packet size mismatch: expected %zu, got %zu", sizeof(acip_webrtc_sdp_t) + sdp_len, len);
979 return;
980 }
981
982 // Extract SDP string
983 char *sdp_str = SAFE_MALLOC(sdp_len + 1, char *);
984 if (!sdp_str) {
985 log_error("Failed to allocate SDP string");
986 return;
987 }
988 memcpy(sdp_str, (const uint8_t *)data + sizeof(acip_webrtc_sdp_t), sdp_len);
989 sdp_str[sdp_len] = '\0';
990
991 const char *sdp_type = (sdp_msg->sdp_type == 0) ? "offer" : "answer";
992 log_info("Received SDP %s from ACDS (len=%u)", sdp_type, sdp_len);
993
994 // Forward to peer manager
995 if (session->peer_manager) {
997 if (result != ASCIICHAT_OK) {
998 log_error("Failed to handle SDP: %d", result);
999 }
1000 } else {
1001 log_error("Received SDP but peer manager not initialized");
1002 }
1003
1004 SAFE_FREE(sdp_str);
1005}
1006
1010static void handle_discovery_webrtc_ice(discovery_session_t *session, void *data, size_t len) {
1011 if (len < sizeof(acip_webrtc_ice_t)) {
1012 log_error("Invalid ICE packet size: %zu", len);
1013 return;
1014 }
1015
1016 const acip_webrtc_ice_t *ice_msg = (const acip_webrtc_ice_t *)data;
1017 uint16_t candidate_len = NET_TO_HOST_U16(ice_msg->candidate_len);
1018
1019 log_debug("★ ICE VALIDATION: len=%zu, sizeof(header)=%zu, candidate_len=%u, expected=%zu", len, sizeof(acip_webrtc_ice_t), candidate_len, sizeof(acip_webrtc_ice_t) + candidate_len);
1020
1021 // FIXED: The payload contains candidate + null + mid + null, not just candidate
1022 // So we can't validate the exact size without parsing the strings first
1023 if (len < sizeof(acip_webrtc_ice_t) + candidate_len) {
1024 log_error("ICE packet too small: expected at least %zu, got %zu", sizeof(acip_webrtc_ice_t) + candidate_len, len);
1025 return;
1026 }
1027
1028 log_debug("Received ICE candidate from ACDS (len=%u)", candidate_len);
1029
1030 // Forward to peer manager
1031 if (session->peer_manager) {
1033 if (result != ASCIICHAT_OK) {
1034 log_error("Failed to handle ICE candidate: %d", result);
1035 }
1036 } else {
1037 log_error("Received ICE but peer manager not initialized");
1038 }
1039}
1040
1044static asciichat_error_t discovery_handoff_send(discovery_session_t *session, consensus_handoff_message_t *message, bool probe) {
1045 size_t length = CONSENSUS_HANDOFF_HEADER + (probe ? CONSENSUS_HANDOFF_PROBE_BYTES : 0);
1046 uint8_t *bytes = SAFE_CALLOC(1, length, uint8_t *);
1047 consensus_handoff_encode(message, bytes);
1049 SAFE_FREE(bytes);
1050 return result;
1051}
1052// Membership generation and committed round together order host decisions.
1053static int discovery_compare_host_decision(const discovery_session_t *session, uint32_t generation, uint32_t sequence) {
1054 if (!session->host_authority_received)
1055 return 1;
1056 if (generation != session->host_authority_generation)
1057 return generation > session->host_authority_generation ? 1 : -1;
1058 if (sequence != session->host_authority_sequence)
1059 return sequence > session->host_authority_sequence ? 1 : -1;
1060 return 0;
1061}
1062
1063static void discovery_record_host_decision(discovery_session_t *session, uint32_t generation, uint32_t sequence) {
1064 session->host_authority_received = true;
1065 session->host_authority_generation = generation;
1066 session->host_authority_sequence = sequence;
1067}
1068
1069static void discovery_commit_host(discovery_session_t *session, const consensus_handoff_message_t *message) {
1070 ASCII_OTEL_SCOPE(DISCOVERY_HOST_RECONCILE);
1071 ASCII_OTEL_ATTR_STRING("host.update.source", "commit");
1072 ASCII_OTEL_ATTR_INT("host.generation", message->generation);
1073 ASCII_OTEL_ATTR_STRING("host.update.outcome", "ignored");
1074 ASCII_OTEL_ATTR_INT("host.decision.sequence", message->sequence);
1075 if (discovery_compare_host_decision(session, message->generation, message->sequence) <= 0)
1076 return;
1077 ASCII_OTEL_ATTR_STRING("host.update.outcome", "queued");
1078 discovery_record_host_decision(session, message->generation, message->sequence);
1079 session->host_loss_detected_ms = session_get_current_time_ms();
1080 if (memcmp(session->host_id, message->participant, SESSION_ID_SIZE))
1081 NOTICE_ANNOUNCE("Session host changed", "The session has a new host.");
1082 memcpy(session->host_id, message->participant, SESSION_ID_SIZE);
1083 session->host_port = message->port;
1084 session->host_address[0] = 0;
1085 session->handoff_pending = session->session_type == SESSION_TYPE_WEBRTC || !memcmp(session->host_id, session->participant_id, SESSION_ID_SIZE);
1086 set_state(session, DISCOVERY_STATE_MIGRATING);
1087 log_info("Committed successor %02x%02x generation=%u", message->participant[0], message->participant[1], message->generation);
1088}
1089
1095static void discovery_handoff_receive(discovery_session_t *session, const void *data, size_t length) {
1097 if (consensus_handoff_decode(data, length, &message) != ASCIICHAT_OK || memcmp(message.session, session->session_id, SESSION_ID_SIZE))
1098 return;
1099 if (message.generation < session->handoff_generation)
1100 return;
1101 session->handoff_generation = message.generation;
1102 if (message.kind == HANDOFF_PREPARE && !memcmp(message.participant, session->participant_id, SESSION_ID_SIZE)) {
1104 if (!session->host_ctx) {
1105 session_host_config_t config = {.port = GET_OPTION(port),
1106 .ipv4_address = "0.0.0.0",
1107 .max_clients = MAX_SESSION_PARTICIPANTS,
1108 .encryption_enabled = true,
1109 .configured_quic_listeners = true,
1110 .password = session->password,
1111 .key_path = GET_OPTION(encrypt_key)};
1112 session->host_ctx = session_host_create(&config);
1113 result = session->host_ctx ? session_host_start(session->host_ctx) : ERROR_MEMORY;
1114 }
1115 if (result != ASCIICHAT_OK && session->host_ctx) {
1117 session->host_ctx = NULL;
1118 }
1119 message.kind = result == ASCIICHAT_OK ? HANDOFF_READY : HANDOFF_REJECT;
1120 message.capabilities = session->session_type == SESSION_TYPE_WEBRTC ? 2 : 1;
1121 message.port = (uint16_t)GET_OPTION(port);
1122 if (discovery_handoff_send(session, &message, false) != ASCIICHAT_OK)
1123 log_warn("Could not acknowledge successor preparation");
1124 } else if (message.kind == HANDOFF_PLAN) {
1125 log_info("Prepared successor %02x%02x%02x%02x round=%u", message.participant[0], message.participant[1], message.participant[2], message.participant[3], message.sequence);
1126 } else if (message.kind == HANDOFF_FAILED) {
1127 set_error(session, ERROR_NETWORK, "No eligible successor has fresh measurements and a prepared host");
1128 } else if (message.kind == HANDOFF_COMMIT) {
1129 discovery_commit_host(session, &message);
1130 }
1131}
1139 if (!session || !session->handoff_pending)
1140 return ASCIICHAT_OK;
1141 session->handoff_pending = false;
1142 if (session->participant_ctx) {
1144 session->participant_ctx = NULL;
1145 }
1146 if (session->peer_manager) {
1148 session->peer_manager = NULL;
1149 }
1150 session->is_host = !memcmp(session->host_id, session->participant_id, SESSION_ID_SIZE);
1151 if (!session->is_host && session->host_ctx) {
1153 session->host_ctx = NULL;
1154 }
1155 session->webrtc_transport_ready = false;
1156 session->webrtc_connection_initiated = false;
1157 session->webrtc_retry_attempt = 0;
1158 session->webrtc_disconnected_since_ms = 0;
1159 session->liveness.ping_in_flight = false;
1160 session->liveness.consecutive_failures = 0;
1161 session->liveness.last_ping_sent_ms = session_get_current_time_ms();
1163 if (session->session_type == SESSION_TYPE_WEBRTC) {
1164 asciichat_error_t result = initialize_webrtc_peer_manager(session);
1165 if (result != ASCIICHAT_OK)
1166 return result;
1167 }
1168 ascii_otel_metric(ASCII_OTEL_METRIC_HOST_CHANGES_APPLIED, 1);
1169 session->host_loss_detected_ms = 0;
1170
1172 return ASCIICHAT_OK;
1173}
1174
1181static asciichat_error_t discovery_handoff_sample(discovery_session_t *session) {
1182 uint64_t now = session_get_current_time_ms();
1183 if (session->handoff_last_sample_ms && now - session->handoff_last_sample_ms < 5000)
1184 return ASCIICHAT_OK;
1185 session->handoff_last_sample_ms = now;
1186 start_nat_detection(session);
1187 if (!session->handoff_sequence)
1188 log_info("Handoff identity=%02x%02x%02x%02x", session->participant_id[0], session->participant_id[1], session->participant_id[2], session->participant_id[3]);
1189 consensus_handoff_message_t message = {
1190 .kind = HANDOFF_SAMPLE_START, .sequence = ++session->handoff_sequence, .capabilities = session->session_type == SESSION_TYPE_WEBRTC ? 2 : 0, .nat_tier = 255, .port = (uint16_t)GET_OPTION(port)};
1191 mutex_lock(&session->nat_quality_mutex);
1195 mutex_unlock(&session->nat_quality_mutex);
1196 if ((GET_OPTION(quic_bind_address)[0] || (GET_OPTION(webtransport_bind_address)[0] || GET_OPTION(webtransport_origin)[0])) && GET_OPTION(tls_cert)[0] && GET_OPTION(tls_key)[0])
1197 message.capabilities |= 1; // A configured native listener can prepare a direct successor.
1198 memcpy(message.session, session->session_id, SESSION_ID_SIZE);
1199 memcpy(message.participant, session->participant_id, SESSION_ID_SIZE);
1200 asciichat_error_t result = discovery_handoff_send(session, &message, false);
1201 if (result != ASCIICHAT_OK)
1202 return result;
1203 message.kind = HANDOFF_SAMPLE_DATA;
1204 return discovery_handoff_send(session, &message, true);
1205}
1206
1207static bool discovery_host_designation_is_current(const discovery_session_t *session, const acip_host_designated_t *host, uint32_t generation) {
1208 if (memcmp(host->session_id, session->session_id, SESSION_ID_SIZE) || !memchr(host->host_address, 0, sizeof(host->host_address)) || !host->host_port ||
1209 host->connection_type > ACIP_CONNECTION_TYPE_TURN || generation < session->handoff_generation)
1210 return false;
1211 int order = discovery_compare_host_decision(session, generation, NET_TO_HOST_U32(host->sequence));
1212 if (order != 0)
1213 return order > 0;
1214 // The same authority may supply an endpoint that was not available at join time.
1215 return !memcmp(session->host_id, host->host_id, SESSION_ID_SIZE) && !session->host_address[0] && host->host_address[0];
1216}
1217
1218static bool discovery_host_endpoint_ready(const discovery_session_t *session, const acip_host_designated_t *host) {
1219 return session->session_type == SESSION_TYPE_WEBRTC || host->host_address[0] || !memcmp(host->host_id, session->participant_id, SESSION_ID_SIZE);
1220}
1221
1222static void discovery_receive_host_designated(discovery_session_t *session, const void *data, size_t len) {
1223 ASCII_OTEL_SCOPE(DISCOVERY_HOST_RECONCILE);
1224 ASCII_OTEL_ATTR_STRING("host.update.source", "designation");
1225 ASCII_OTEL_ATTR_STRING("host.update.outcome", "malformed");
1226 if (!data || len < sizeof(acip_host_designated_t))
1227 return;
1228 const acip_host_designated_t *host = data;
1229 uint16_t quic_port = 0;
1230 char webtransport_url[512];
1231 asciichat_errno_scope_t metadata_scope = errno_scope_begin();
1232 asciichat_error_t metadata_result = acds_transport_metadata_decode((const uint8_t *)data + sizeof(*host), len - sizeof(*host), &quic_port, webtransport_url, sizeof(webtransport_url));
1234 if (metadata_result != ASCIICHAT_OK)
1235 return;
1236 uint32_t generation = NET_TO_HOST_U32(host->generation);
1237 ASCII_OTEL_ATTR_INT("host.generation", generation);
1238 ASCII_OTEL_ATTR_INT("host.decision.sequence", NET_TO_HOST_U32(host->sequence));
1239 if (!discovery_host_designation_is_current(session, host, generation)) {
1240 ASCII_OTEL_ATTR_STRING("host.update.outcome", "ignored");
1241 ascii_otel_metric(ASCII_OTEL_METRIC_HOST_DESIGNATIONS_IGNORED, 1);
1242 return;
1243 }
1244 ASCII_OTEL_ATTR_STRING("host.update.outcome", "accepted");
1245 bool changed = memcmp(session->host_id, host->host_id, SESSION_ID_SIZE) != 0;
1246 ASCII_OTEL_ATTR_INT("host.update.changed", changed);
1247 ASCII_OTEL_ATTR_STRING("host.update.role", !memcmp(host->host_id, session->participant_id, SESSION_ID_SIZE) ? "host" : "participant");
1248 bool active = session->state == DISCOVERY_STATE_ACTIVE;
1249 bool connecting = session->state == DISCOVERY_STATE_CONNECTING_HOST;
1250 discovery_record_host_decision(session, generation, NET_TO_HOST_U32(host->sequence));
1251 session->handoff_generation = generation;
1252 memcpy(session->host_id, host->host_id, SESSION_ID_SIZE);
1253 if (changed)
1254 session->host_address[0] = 0;
1255 if (host->host_address[0])
1256 SAFE_STRNCPY(session->host_address, host->host_address, sizeof(session->host_address));
1257 session->host_port = GET_OPTION(discovery_quic) && quic_port ? quic_port : host->host_port;
1258 if (changed && active)
1259 NOTICE_ANNOUNCE("Session host changed", "The session has a new host.");
1260 if ((changed && (active || connecting) && discovery_host_endpoint_ready(session, host)) ||
1261 (session->state == DISCOVERY_STATE_MIGRATING && session->session_type != SESSION_TYPE_WEBRTC && host->host_address[0])) {
1262 // Worker teardown remains deferred to the existing role dispatcher.
1263 session->handoff_pending = true;
1264 set_state(session, DISCOVERY_STATE_MIGRATING);
1265 } else if (session->state == DISCOVERY_STATE_NEGOTIATING && host->host_address[0]) {
1266 session->is_host = !memcmp(host->host_id, session->participant_id, SESSION_ID_SIZE);
1268 }
1269}
1270
1271static void handle_acds_webrtc_packet(discovery_session_t *session, packet_type_t type, void *data, size_t len) {
1272 if ((unsigned)type == CONSENSUS_HANDOFF_PACKET) {
1273 discovery_handoff_receive(session, data, len);
1274 return;
1275 }
1276 switch (type) {
1278 discovery_receive_host_designated(session, data, len);
1279 break;
1281 handle_discovery_webrtc_sdp(session, data, len);
1282 break;
1284 handle_discovery_webrtc_ice(session, data, len);
1285 break;
1286 default:
1287 log_debug("Unhandled WebRTC packet type: 0x%04x", type);
1288 }
1289}
1290
1294static asciichat_error_t join_session(discovery_session_t *session) {
1295 ASCII_OTEL_SCOPE(DISCOVERY_JOIN);
1296 log_info("participant_ctx=%p", session->participant_ctx);
1297
1298 if (!session)
1299 return ERROR_INVALID_PARAM;
1300
1301 set_state(session, DISCOVERY_STATE_JOINING_SESSION);
1302 log_info("Joining session: %s (participant_ctx still=%p)", session->session_string, session->participant_ctx);
1303
1304 acds_protocol_t protocol;
1305 asciichat_error_t result;
1306 for (;;) {
1307 acds_protocol_init(&protocol, discovery_protocol_send, session->acds_transport);
1308 acds_session_join_params_t params = {.session_string = session->session_string, .has_password = session->password[0] != 0};
1309 memcpy(params.identity_pubkey, session->identity_pubkey, sizeof(params.identity_pubkey));
1310 memcpy(params.identity_seckey, session->identity_seckey, sizeof(params.identity_seckey));
1311 SAFE_STRNCPY(params.password, session->password, sizeof(params.password));
1312 result = acds_protocol_join(&protocol, &params);
1313 sodium_memzero(&params, sizeof(params));
1314 if (result == ASCIICHAT_OK)
1315 result = discovery_protocol_receive(session, &protocol);
1316 if (result != ERROR_INVALID_PASSWORD)
1317 break;
1318 acds_protocol_destroy(&protocol);
1319 bool incorrect = session->password[0] != 0;
1320 CLEAR_ERRNO();
1321 result = ui_input_password(session->session_string, session->password, sizeof(session->password), incorrect);
1322 if (result != ASCIICHAT_OK) {
1323 if (!shutdown_is_requested())
1324 set_error(session, result, "Password required to join session");
1325 return result;
1326 }
1327 }
1328 if (result != ASCIICHAT_OK) {
1329 acds_protocol_destroy(&protocol);
1330 return result;
1331 }
1332 uint16_t advertised_quic_port = protocol.quic_port;
1333 acip_session_joined_t joined_value = protocol.joined;
1334 acip_session_joined_t *joined = &joined_value;
1335 void *alloc_buffer = NULL;
1336 acds_protocol_destroy(&protocol);
1337
1338 // Store session info
1339 memcpy(session->session_id, joined->session_id, SESSION_ID_SIZE);
1340 memcpy(session->participant_id, joined->participant_id, SESSION_ID_SIZE);
1341
1342 memcpy(session->host_id, joined->host_established ? joined->host_id : joined->initiator_id, SESSION_ID_SIZE);
1343 session->is_host = memcmp(session->host_id, session->participant_id, sizeof(session->host_id)) == 0;
1344
1345 // Store session type and WebRTC credentials (if WebRTC)
1346 session->session_type = joined->session_type;
1347 if (GET_OPTION(no_webrtc) || GET_OPTION(discovery_quic)) {
1348 if (!session->is_host && (!joined->server_address[0] || joined->server_port == 0)) {
1349 const char *message = GET_OPTION(discovery_quic) ? "Direct QUIC requires a disclosed host endpoint" : "Direct TCP requires a disclosed host endpoint; WebRTC is disabled";
1350 set_error(session, ERROR_NETWORK, message);
1351 buffer_release(alloc_buffer);
1352 return SET_ERRNO(ERROR_NETWORK, "%s", message);
1353 }
1355 if (GET_OPTION(discovery_quic))
1356 log_info("Discovery connection route: direct QUIC (--discovery-quic)");
1357 else
1358 log_info("Discovery connection route: direct TCP (--no-webrtc)");
1359 }
1360 if (session->session_type == SESSION_TYPE_WEBRTC) {
1361 // WebRTC signaling addresses peers by participant ID, so a private server
1362 // address must not send the client through TCP/NAT host election. The
1363 // session initiator is the host for server-created sessions and is already
1364 // available even when IP details are withheld.
1365 session->is_host = memcmp(session->host_id, session->participant_id, sizeof(session->host_id)) == 0;
1366 }
1367 if (GET_OPTION(webrtc_relay_only) && session->session_type != SESSION_TYPE_WEBRTC) {
1368 buffer_release(alloc_buffer);
1369 return SET_ERRNO(ERROR_INVALID_STATE, "Relay only requires a WebRTC session");
1370 }
1371 if (session->session_type == SESSION_TYPE_WEBRTC) {
1372 SAFE_STRNCPY(session->turn_username, joined->turn_username, sizeof(session->turn_username));
1373 SAFE_STRNCPY(session->turn_password, joined->turn_password, sizeof(session->turn_password));
1374 log_info("WebRTC session detected - TURN username: %s", session->turn_username);
1375
1376 // Initialize WebRTC peer manager for WebRTC sessions (NEW)
1377 asciichat_error_t webrtc_result = initialize_webrtc_peer_manager(session);
1378 if (webrtc_result != ASCIICHAT_OK) {
1379 log_error("Failed to initialize WebRTC peer manager: %d", webrtc_result);
1380 buffer_release(alloc_buffer);
1381 return webrtc_result;
1382 }
1383 log_info("WebRTC peer manager initialized successfully");
1384 }
1385
1386 // The initiator also joins its own session. Start its listeners instead of
1387 // treating its newly advertised endpoint as an already running remote host.
1388 if (session->is_host) {
1389 buffer_release(alloc_buffer);
1390 set_state(session, DISCOVERY_STATE_STARTING_HOST);
1391 return ASCIICHAT_OK;
1392 }
1393
1394 // Check if host is already established
1395 if (session->session_type != SESSION_TYPE_WEBRTC && joined->server_address[0] && joined->server_port > 0) {
1396 // Host exists - connect directly
1397 SAFE_STRNCPY(session->host_address, joined->server_address, sizeof(session->host_address));
1398 session->host_port = GET_OPTION(discovery_quic) && advertised_quic_port ? advertised_quic_port : joined->server_port;
1399 session->is_host = false;
1400
1401 log_info("Host already established: %s:%u (session_type=%u, participant_ctx=%p before transition)", session->host_address, session->host_port, session->session_type, session->participant_ctx);
1402 buffer_release(alloc_buffer);
1403
1404 log_info("About to transition to CONNECTING_HOST - participant_ctx=%p", session->participant_ctx);
1405 set_state(session, DISCOVERY_STATE_CONNECTING_HOST);
1406 log_info("Transitioned to CONNECTING_HOST - participant_ctx=%p (returning ASCIICHAT_OK)", session->participant_ctx);
1407 return ASCIICHAT_OK;
1408 }
1409
1410 // WebRTC peers connect through ACDS signaling and never need the host's IP
1411 // address. Use the host participant ID returned above when the address is
1412 // intentionally hidden.
1413 if (session->session_type == SESSION_TYPE_WEBRTC && session->host_id[0]) {
1414 if (session->is_host) {
1415 log_info("WebRTC participant is the session host; starting host transport");
1416 set_state(session, DISCOVERY_STATE_STARTING_HOST);
1417 } else {
1418 log_info("WebRTC host identified by participant ID; connecting without revealing its IP");
1419 set_state(session, DISCOVERY_STATE_CONNECTING_HOST);
1420 }
1421 buffer_release(alloc_buffer);
1422 return ASCIICHAT_OK;
1423 }
1424
1425 // No host yet - need to negotiate
1426 log_info("No host established (server_address='%s' port=%u), starting negotiation...", joined->server_address, joined->server_port);
1427 buffer_release(alloc_buffer);
1428
1429 set_state(session, DISCOVERY_STATE_NEGOTIATING);
1430 return ASCIICHAT_OK;
1431}
1432
1434 log_info("session=%p", session);
1435
1436 if (!session) {
1437 return SET_ERRNO(ERROR_INVALID_PARAM, "session is NULL");
1438 }
1439
1440 log_info("is_initiator=%d, session_string='%s'", session->is_initiator, session->session_string);
1441
1442 // Check if we should exit before starting blocking operations
1443 if (session->should_exit_callback && session->should_exit_callback(session->exit_callback_data)) {
1444 log_info("Exiting early due to should_exit_callback (before ACDS connect)");
1445 return ASCIICHAT_OK; // Return success to allow clean shutdown
1446 }
1447
1448 log_info("Calling connect_to_acds...");
1449 // Connect to ACDS
1450 asciichat_error_t result = connect_to_acds(session);
1451 if (result != ASCIICHAT_OK) {
1452 log_error("connect_to_acds FAILED %s", asciichat_error_format(NULL, result));
1453 set_state(session, DISCOVERY_STATE_FAILED);
1454 return result;
1455 }
1456 log_info("connect_to_acds succeeded");
1457
1458 // Check again after connection
1459 if (session->should_exit_callback && session->should_exit_callback(session->exit_callback_data)) {
1460 log_info("Exiting early due to should_exit_callback (after ACDS connect)");
1461 return ASCIICHAT_OK; // Return success to allow clean shutdown
1462 }
1463
1465
1466 // Perform crypto handshake with ACDS (same as client-server handshake)
1467 log_info("Performing crypto handshake with ACDS...");
1469
1470 result = crypto_handshake_init("discovery_client", handshake_ctx, false);
1471 if (result != ASCIICHAT_OK) {
1472 log_error("Handshake init failed - %s", asciichat_error_format(NULL, result));
1473 set_error(session, result, "Crypto handshake init failed");
1474 return result;
1475 }
1476
1477 bool has_identity = memcmp(session->identity_pubkey, (uint8_t[32]){0}, ED25519_PUBLIC_KEY_SIZE) != 0;
1478 // Store identity key in handshake context
1479 handshake_ctx->client_public_key.type = has_identity ? KEY_TYPE_ED25519 : KEY_TYPE_UNKNOWN;
1480 handshake_ctx->client_private_key.type = handshake_ctx->client_public_key.type;
1481 memcpy(handshake_ctx->client_public_key.key, session->identity_pubkey, ED25519_PUBLIC_KEY_SIZE);
1482 memcpy(handshake_ctx->client_private_key.key.ed25519, session->identity_seckey, ED25519_PRIVATE_KEY_SIZE);
1483 memcpy(handshake_ctx->client_private_key.public_key, session->identity_pubkey, sizeof(session->identity_pubkey));
1484
1485 crypto_policy_t signaling_policy = {
1486 .transport_secure = strncmp(session->acds_url, "wss://", 6) == 0,
1487 .has_identity = has_identity,
1488 };
1489 uint8_t mode;
1490 result = crypto_policy_resolve(&signaling_policy, &mode);
1491 if (result == ASCIICHAT_OK)
1492 result = network_client_negotiate(session->acds_transport, handshake_ctx, mode, NETWORK_PROTOCOL_DISCOVERY);
1493 if (result != ASCIICHAT_OK) {
1494 set_error(session, result, "Discovery handshake failed");
1495 return result;
1496 }
1497
1498 // Check again after handshake
1499 if (session->should_exit_callback && session->should_exit_callback(session->exit_callback_data)) {
1500 log_info("Exiting early due to should_exit_callback (after handshake)");
1501 return ASCIICHAT_OK; // Return success to allow clean shutdown
1502 }
1503
1504 // Create or join session
1505 if (session->is_initiator) {
1506 log_info("Calling create_session - participant_ctx before=%p", session->participant_ctx);
1507 result = create_session(session);
1508 log_info("create_session returned - participant_ctx after=%p, result=%d", session->participant_ctx, result);
1509
1510 if (result == ASCIICHAT_OK) {
1511 // Initiator also needs to register itself as a participant so it can receive PARTICIPANT_JOINED notifications
1512 // when other peers join. This makes the initiator discoverable to other participants.
1513 log_info("Initiator: now registering self as participant in created session");
1514 result = join_session(session);
1515 log_info("Initiator: join_session result=%d", result);
1516 }
1517 return result;
1518 } else {
1519 log_info("Calling join_session - participant_ctx before=%p", session->participant_ctx);
1520 asciichat_error_t result = join_session(session);
1521 log_info("join_session returned - participant_ctx after=%p, state=%d, result=%d", session->participant_ctx, session->state, result);
1522 return result;
1523 }
1524}
1525
1526static asciichat_error_t discovery_session_send_keepalive(discovery_session_t *session) {
1527 // Media traffic uses a separate transport; keep the signaling connection alive.
1528 if (session->acds_transport && acip_transport_is_connected(session->acds_transport)) {
1529 uint64_t now_ns = time_get_ns();
1530 if (now_ns - session->last_acds_keepalive_ns >= 5 * NS_PER_SEC_INT) {
1531 asciichat_error_t ping_result = acip_send_ping(session->acds_transport);
1532 if (ping_result != ASCIICHAT_OK)
1533 return ping_result;
1534 session->last_acds_keepalive_ns = now_ns;
1535 }
1536 }
1537
1538 return ASCIICHAT_OK;
1539}
1540
1541static asciichat_error_t discovery_session_wait_for_peer(discovery_session_t *session, int64_t timeout_ns) {
1542 // Wait for PARTICIPANT_JOINED notification from ACDS
1543 // Note: don't use a hard timeout here - let the outer process timeout (snapshot delay) control max wait
1544 // The discovery_run() loop will keep calling this until session becomes active or process exits
1545 uint64_t now_ns = time_get_ns();
1546 uint64_t wait_duration = now_ns - session->waiting_peer_start_ns;
1547
1548 log_debug("★ WAITING_PEER: duration=%.3fs (no timeout, waiting for peer...)", wait_duration / 1e9);
1549
1550 if (session->acds_transport && timeout_ns > 0) {
1551 // Do not set socket timeout - let receive_packet_secure use its own timeout
1552 // Setting a short socket timeout conflicts with its hardcoded 1-second timeout
1553 packet_type_t type;
1554 void *data = NULL;
1555 size_t len = 0;
1556 void *alloc_buffer = NULL;
1557
1558 // Try to receive a packet
1559 asciichat_error_t recv_result = acds_receive_packet(session->acds_transport, &type, &data, &len, &alloc_buffer);
1560 if (recv_result == ASCIICHAT_OK) {
1562 log_info("Peer joined session, transitioning to negotiation");
1563 set_state(session, DISCOVERY_STATE_NEGOTIATING);
1564 buffer_release(alloc_buffer);
1565 } else {
1566 // Got some other packet, handle it or ignore
1567 log_debug("Received packet type %d while waiting for peer", type);
1568 buffer_release(alloc_buffer);
1569 }
1570 } else if (recv_result == ERROR_NETWORK_TIMEOUT) {
1571 // Timeout is normal, just return
1572 } else {
1573 log_debug("Packet receive error while waiting for peer %s", asciichat_error_format(NULL, recv_result));
1574 }
1575 } else {
1576 // Fallback to sleep if no timeout or invalid transport
1577 platform_sleep_us(timeout_ns / 1000);
1578 }
1579 return ASCIICHAT_OK;
1580}
1581
1583static void discovery_session_begin_negotiation(discovery_session_t *session) {
1584 // Initialize negotiation
1585 negotiate_init(&session->negotiate, session->session_id, session->participant_id, session->is_initiator);
1586 log_info("Starting NAT negotiation (initiator=%d)", session->is_initiator);
1587
1588 start_nat_detection(session);
1589
1590 // Bootstrap the initial TCP host. Subsequent host recovery is decided by ACDS.
1592 session->negotiate.peer_quality_received = true;
1593 memset(&session->negotiate.peer_quality, 0, sizeof(session->negotiate.peer_quality));
1594 // Mark peer quality as detected but with worst NAT type so we win host election
1597}
1598
1599static void discovery_session_receive_host_designation(discovery_session_t *session) {
1600 if (session->acds_transport && !session->is_initiator && !session->host_address[0]) {
1601 packet_type_t type;
1602 void *data = NULL;
1603 size_t len = 0;
1604 void *alloc_buffer = NULL;
1605
1606 asciichat_error_t recv_result = acds_receive_packet(session->acds_transport, &type, &data, &len, &alloc_buffer);
1607 if (recv_result == ASCIICHAT_OK) {
1608 handle_acds_webrtc_packet(session, type, data, len);
1609 buffer_release(alloc_buffer);
1610 }
1611 }
1612}
1613
1614static asciichat_error_t discovery_session_select_host(discovery_session_t *session) {
1615 // Determine host role (now that peer_quality is set)
1617 log_info("Determining host role based on NAT qualities...");
1618 ASCII_OTEL_SCOPE(DISCOVERY_HOST_SELECTION);
1619 ASCII_OTEL_ATTR_STRING("host.selection.phase", "initial");
1621 ASCII_OTEL_ATTR_INT("host.selection.error_code", result);
1622 ASCII_OTEL_ATTR_STRING("host.selection.outcome", result == ASCIICHAT_OK ? "selected" : "failed");
1623 if (result == ASCIICHAT_OK) {
1624 ASCII_OTEL_ATTR_STRING("host.selection.role", session->negotiate.we_are_host ? "host" : "participant");
1625 ASCII_OTEL_ATTR_INT("host.selection.local_nat_tier", nat_compute_tier(&session->negotiate.our_quality));
1626 ASCII_OTEL_ATTR_INT("host.selection.peer_nat_tier", nat_compute_tier(&session->negotiate.peer_quality));
1627 ascii_otel_metric(ASCII_OTEL_METRIC_HOST_SELECTIONS, 1);
1628 session->is_host = session->negotiate.we_are_host;
1629 stats_runtime_connection_state(session->is_host ? "discovery host" : "discovery participant");
1630
1631 if (session->is_host) {
1632 // We become the host
1633 log_info("🏠 NAT negotiation complete: WE ARE HOST (tier:%d vs tier:%d)", nat_compute_tier(&session->negotiate.our_quality), nat_compute_tier(&session->negotiate.peer_quality));
1634 memcpy(session->host_id, session->participant_id, sizeof(session->host_id));
1635 SAFE_STRNCPY(session->host_address, session->negotiate.host_address, sizeof(session->host_address));
1636 session->host_port = session->negotiate.host_port;
1637
1638 // Fallback to localhost if NAT detection failed to determine address
1639 if (!session->host_address[0]) {
1640 log_warn("NAT address empty, using localhost fallback");
1641 SAFE_STRNCPY(session->host_address, "127.0.0.1", sizeof(session->host_address));
1642 }
1643
1644 set_state(session, DISCOVERY_STATE_STARTING_HOST);
1645 } else {
1646 // They are host (shouldn't happen in solo mode, but handle it)
1647 log_info("👤 NAT negotiation complete: THEY ARE HOST at %s:%u (tier:%d vs tier:%d)", session->negotiate.host_address, session->negotiate.host_port,
1649 SAFE_STRNCPY(session->host_address, session->negotiate.host_address, sizeof(session->host_address));
1650 session->host_port = session->negotiate.host_port;
1651
1652 // If host address is empty, wait for HOST_DESIGNATED from ACDS instead of using fallback
1653 if (!session->host_address[0]) {
1654 log_info("Waiting for HOST_DESIGNATED from ACDS to discover host address...");
1655 // Stay in NEGOTIATING state to continue waiting for HOST_DESIGNATED
1656 return ASCIICHAT_OK;
1657 }
1658
1659 set_state(session, DISCOVERY_STATE_CONNECTING_HOST);
1660 }
1661 } else {
1662 log_error("Failed to determine negotiation result %s", asciichat_error_format(NULL, result));
1663 set_error(session, result, "Host election failed");
1664 }
1665 }
1666 return ASCIICHAT_OK;
1667}
1668
1669static asciichat_error_t discovery_session_negotiate(discovery_session_t *session) {
1670 if (session->negotiate.state == NEGOTIATE_STATE_INIT) {
1671 discovery_session_begin_negotiation(session);
1672 }
1673 discovery_session_receive_host_designation(session);
1674 if (session->state != DISCOVERY_STATE_NEGOTIATING)
1675 return ASCIICHAT_OK;
1676 return discovery_session_select_host(session);
1677}
1678
1679static asciichat_error_t discovery_session_start_host(discovery_session_t *session) {
1680 ASCII_OTEL_SCOPE(DISCOVERY_START_HOST);
1681 // Start hosting
1682 if (!session->host_ctx) {
1683 // Create host context with configured port
1684 int host_port = GET_OPTION(port);
1685
1686 session_host_config_t hconfig = {
1687 .port = host_port,
1688 .ipv4_address = "0.0.0.0",
1689 .max_clients = MAX_SESSION_PARTICIPANTS,
1690 .encryption_enabled = true,
1691 .configured_quic_listeners = true,
1692 .password = session->password,
1693 .key_path = GET_OPTION(encrypt_key),
1694 };
1695
1696 session->host_ctx = session_host_create(&hconfig);
1697 if (!session->host_ctx) {
1698 log_error("Failed to create host context");
1699 set_error(session, ERROR_MEMORY, "Failed to create host context");
1700 return ASCIICHAT_OK;
1701 }
1702
1703 // Start listening
1705 if (hstart != ASCIICHAT_OK) {
1706 log_error("Failed to start host: %d", hstart);
1707 set_error(session, hstart, "Failed to start host");
1708 return ASCIICHAT_OK;
1709 }
1710
1711 log_info("Host started, listening for connections");
1712 }
1713
1714 // Notify listeners that we're ready
1715 if (session->on_session_ready) {
1716 session->on_session_ready(session->session_string, session->callback_user_data);
1717 }
1718
1719 // Send HOST_ANNOUNCEMENT to ACDS so participants can discover us
1720 int host_port = GET_OPTION(port);
1721 acip_host_announcement_t announcement = {0};
1722 memcpy(announcement.session_id, session->session_id, sizeof(announcement.session_id));
1723 memcpy(announcement.host_id, session->host_id, sizeof(announcement.host_id));
1724 SAFE_STRNCPY(announcement.host_address, session->host_address, sizeof(announcement.host_address));
1725 announcement.host_port = host_port;
1726 announcement.connection_type = ACIP_CONNECTION_TYPE_DIRECT_PUBLIC;
1727 announcement.generation = HOST_TO_NET_U32(session->handoff_generation);
1728 announcement.sequence = HOST_TO_NET_U32(session->host_authority_sequence);
1729
1730 if (session->acds_transport) {
1731 uint8_t payload[sizeof(announcement) + ACDS_TRANSPORT_METADATA_MAX];
1732 size_t metadata_length = 0;
1733 uint16_t quic_port = (GET_OPTION(quic_bind_address)[0] || (GET_OPTION(webtransport_bind_address)[0] || GET_OPTION(webtransport_origin)[0]))
1734 ? (uint16_t)(GET_OPTION(quic_port) ? GET_OPTION(quic_port) : host_port)
1735 : 0;
1736 const char *url = (GET_OPTION(webtransport_bind_address)[0] || GET_OPTION(webtransport_origin)[0]) ? GET_OPTION(webtransport_public_url) : "";
1738 if (quic_port || *url)
1739 sent = acds_transport_metadata_encode(quic_port, url, payload + sizeof(announcement), ACDS_TRANSPORT_METADATA_MAX, &metadata_length);
1740 if (sent != ASCIICHAT_OK)
1741 return sent;
1742 memcpy(payload, &announcement, sizeof(announcement));
1743 sent = packet_send_via_transport(session->acds_transport, PACKET_TYPE_ACIP_HOST_ANNOUNCEMENT, payload, sizeof(announcement) + metadata_length, 0);
1744 if (sent != ASCIICHAT_OK)
1745 return sent;
1746 log_info("Sent HOST_ANNOUNCEMENT to ACDS at %s:%u", announcement.host_address, announcement.host_port);
1747 }
1748
1749 set_state(session, DISCOVERY_STATE_ACTIVE);
1750 return ASCIICHAT_OK;
1751}
1752
1753static asciichat_error_t discovery_session_retry_webrtc(discovery_session_t *session, int timeout_ms) {
1754 int max_attempts = GET_OPTION(reconnect_attempts);
1755 if (session->webrtc_retry_attempt >= max_attempts) {
1756 log_error("WebRTC connection failed after %d attempts (timeout: %dms)", max_attempts + 1, timeout_ms);
1758 snprintf(error_msg, sizeof(error_msg), "WebRTC connection failed after %d attempts (%dms timeout)", max_attempts + 1, timeout_ms);
1759 set_error(session, ERROR_NETWORK_TIMEOUT, error_msg);
1760 return SET_ERRNO(ERROR_NETWORK_TIMEOUT, "%s", error_msg);
1761 }
1762
1763 uint32_t backoff_ms = calculate_backoff_delay_ms(session->webrtc_retry_attempt);
1764 log_warn("WebRTC connection attempt %d/%d failed, retrying in %ums...", session->webrtc_retry_attempt + 1, max_attempts + 1, backoff_ms);
1765 APP_CALLBACK_VOID(platform_pump_events);
1766 APP_CALLBACK_VOID_UINT(platform_sleep_ms, backoff_ms);
1767
1769 session->peer_manager = NULL;
1770 asciichat_error_t result = initialize_webrtc_peer_manager(session);
1771 if (result != ASCIICHAT_OK) {
1772 log_error("Failed to re-initialize WebRTC for retry: %d", result);
1773 set_error(session, result, "Failed to re-initialize WebRTC for retry");
1774 return result;
1775 }
1776
1777 session->webrtc_connection_initiated = false;
1778 session->webrtc_retry_attempt++;
1779 log_info("WebRTC peer manager re-initialized for attempt %d/%d", session->webrtc_retry_attempt + 1, max_attempts + 1);
1780 return ASCIICHAT_OK;
1781}
1782
1788static asciichat_error_t discovery_session_connect_webrtc(discovery_session_t *session) {
1789 // Check if transport is ready (DataChannel opened)
1790 if (session->webrtc_transport_ready) {
1791 log_info("WebRTC DataChannel established, transitioning to ACTIVE state");
1792 set_state(session, DISCOVERY_STATE_ACTIVE);
1793 return ASCIICHAT_OK;
1794 }
1795
1796 // If not ready and we haven't initiated connection yet, initiate it
1797 if (session->peer_manager && !session->webrtc_connection_initiated) {
1798 log_info("Initiating WebRTC connection to host (attempt %d/%d)...", session->webrtc_retry_attempt + 1, GET_OPTION(reconnect_attempts) + 1);
1799
1800 // Initiate connection (generates offer, triggers SDP exchange)
1801 asciichat_error_t conn_result = webrtc_peer_manager_connect(session->peer_manager, session->session_id, session->host_id);
1802
1803 if (conn_result != ASCIICHAT_OK) {
1804 log_error("Failed to initiate WebRTC connection: %d", conn_result);
1805 set_error(session, conn_result, "Failed to initiate WebRTC connection");
1806 return ASCIICHAT_OK;
1807 }
1808
1809 log_info("WebRTC connection initiated, waiting for DataChannel...");
1810 session->webrtc_connection_initiated = true;
1811 session->webrtc_last_attempt_time_ms = APP_CALLBACK_UINT64(platform_get_monotonic_time_us) / 1000;
1812 }
1813
1814 // Check for ICE gathering timeout on all peers
1815 if (session->webrtc_connection_initiated && session->peer_manager) {
1816 int timeout_ms = GET_OPTION(webrtc_ice_timeout_ms);
1817 int timed_out_count = webrtc_peer_manager_check_gathering_timeouts(session->peer_manager, timeout_ms);
1818
1819 bool attempt_expired = session_get_current_time_ms() - session->webrtc_last_attempt_time_ms >= (uint64_t)timeout_ms;
1820 if (timed_out_count > 0 || attempt_expired) {
1821 log_error("WebRTC negotiation failed: %d peer(s) failed or exceeded the %dms gathering timeout", timed_out_count, timeout_ms);
1822
1823 asciichat_error_t retry_result = discovery_session_retry_webrtc(session, timeout_ms);
1824 if (retry_result != ASCIICHAT_OK) {
1825 if (GET_OPTION(prefer_webrtc) || GET_OPTION(webrtc_relay_only)) {
1826 set_state(session, DISCOVERY_STATE_FAILED);
1827 return SET_ERRNO(ERROR_NETWORK_TIMEOUT, "WebRTC connection failed and direct fallback is disabled");
1828 }
1829 return ASCIICHAT_OK;
1830 }
1831 }
1832 }
1833
1834 // Poll ACDS for WebRTC signaling messages (SDP answer, ICE candidates)
1835 // while waiting for DataChannel to open
1836 if (session->acds_transport && acip_transport_has_pending_data(session->acds_transport)) {
1837 packet_type_t type;
1838 void *data = NULL;
1839 size_t len = 0;
1840 void *alloc_buffer = NULL;
1841
1842 asciichat_error_t recv_result = acds_receive_packet(session->acds_transport, &type, &data, &len, &alloc_buffer);
1843
1844 if (recv_result == ASCIICHAT_OK) {
1845 // Dispatch to appropriate handler
1846 handle_acds_webrtc_packet(session, type, data, len);
1847 buffer_release(alloc_buffer);
1848 } else if (!acip_transport_is_connected(session->acds_transport)) {
1849 set_error(session, recv_result, "Discovery signaling connection closed during WebRTC negotiation");
1850 set_state(session, DISCOVERY_STATE_FAILED);
1851 return recv_result;
1852 } else {
1853 log_debug("Failed to receive ACDS packet: %d", recv_result);
1854 }
1855 }
1856
1857 // Stay in CONNECTING_HOST until DataChannel opens (webrtc_transport_ready becomes true)
1858 // The discovery_on_transport_ready callback will set webrtc_transport_ready=true
1859 return ASCIICHAT_OK;
1860}
1861
1862static asciichat_error_t discovery_session_connect_tcp(discovery_session_t *session) {
1863 ASCII_OTEL_SCOPE(CONNECTION_ATTEMPT);
1864 if (!session->participant_ctx) {
1865 char quic_address[ACIP_ADDRESS_SIZE + 16];
1866 const char *address = session->host_address;
1867 if (GET_OPTION(discovery_quic)) {
1868 if (strchr(address, ':'))
1869 SAFE_SNPRINTF(quic_address, sizeof(quic_address), "quic://[%s]", address);
1870 else
1871 SAFE_SNPRINTF(quic_address, sizeof(quic_address), "quic://%s", address);
1872 address = quic_address;
1873 }
1874 session_participant_config_t config = {.address = address,
1875 .port = session->host_port,
1876 .enable_audio = true,
1877 .enable_video = true,
1878 .encryption_enabled = true,
1879 .password = session->password,
1880 .server_key = GET_OPTION(server_key),
1881 .tls_ca_file = GET_OPTION(tls_ca_file),
1882 .quic_audio_datagrams = GET_OPTION(quic_audio_datagrams),
1883 .quic_visual_datagrams = GET_OPTION(quic_visual_datagrams)};
1884 session->participant_ctx = session_participant_create(&config);
1885 if (!session->participant_ctx)
1886 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate discovery participant");
1887 }
1889 if (result != ASCIICHAT_OK) {
1890 set_error(session, result, "Cannot establish authenticated host connection");
1891 return result;
1892 }
1893 set_state(session, DISCOVERY_STATE_ACTIVE);
1894 return ASCIICHAT_OK;
1895}
1896
1902static asciichat_error_t discovery_session_process_active(discovery_session_t *session, int64_t timeout_ns) {
1903 // All session types dispatch ACDS recovery decisions without a blocking receive.
1904
1905 if (session->acds_transport && acip_transport_has_pending_data(session->acds_transport)) {
1906 packet_type_t type;
1907 void *data = NULL;
1908 size_t len = 0;
1909 void *alloc_buffer = NULL;
1910
1911 asciichat_error_t recv_result = acds_receive_packet(session->acds_transport, &type, &data, &len, &alloc_buffer);
1912
1913 if (recv_result == ASCIICHAT_OK) {
1914 // Dispatch to appropriate handler
1915 handle_acds_webrtc_packet(session, type, data, len);
1916 buffer_release(alloc_buffer);
1917 }
1918 }
1919
1920 if (session->handoff_pending || session->state != DISCOVERY_STATE_ACTIVE)
1921 return ASCIICHAT_OK;
1922
1923 if (session->session_type == SESSION_TYPE_WEBRTC && !session->is_host && session->peer_manager) {
1925 bool peer_found = webrtc_peer_manager_get_state(session->peer_manager, session->host_id, &peer_state);
1926 uint64_t now_ms = session_get_current_time_ms();
1927 bool disconnected_too_long = false;
1928
1929 if (peer_found && peer_state == WEBRTC_STATE_DISCONNECTED) {
1930 if (session->webrtc_disconnected_since_ms == 0) {
1931 session->webrtc_disconnected_since_ms = now_ms;
1932 } else {
1933 disconnected_too_long = now_ms - session->webrtc_disconnected_since_ms >= 5000;
1934 }
1935 } else {
1936 session->webrtc_disconnected_since_ms = 0;
1937 }
1938
1939 bool peer_failed = !peer_found || peer_state == WEBRTC_STATE_FAILED || peer_state == WEBRTC_STATE_CLOSED;
1940 if (session->webrtc_transport_ready && (peer_failed || disconnected_too_long)) {
1941 // Media workers still borrow this transport. The role dispatcher joins them
1942 // before applying the elected successor and releasing the old participant.
1944 }
1945 }
1946
1947 // Session is active - check for host disconnect
1948 if (!session->is_host) {
1949 // We are a participant - check if host is still alive
1951 if (host_check != ASCIICHAT_OK) {
1952 // Report host loss and await the measured ACDS recovery decision.
1953 log_warn("Host disconnect detected during ACTIVE state");
1954
1955 // If --prefer-webrtc is set, WebRTC failure is fatal (no TCP fallback)
1956 const options_t *opts = options_get();
1957 if (opts && (opts->prefer_webrtc || opts->webrtc_relay_only)) {
1958 set_state(session, DISCOVERY_STATE_FAILED);
1959 session->error = ERROR_NETWORK;
1960 return SET_ERRNO(ERROR_NETWORK, "WebRTC connection failed");
1961 }
1962
1963 set_state(session, DISCOVERY_STATE_MIGRATING);
1964 // Reason code: 1 = timeout/disconnect detected during ACTIVE session
1966 }
1967 }
1968 platform_sleep_us(timeout_ns / 1000);
1969 return ASCIICHAT_OK;
1970}
1971
1976static asciichat_error_t discovery_session_process_migration(discovery_session_t *session, int64_t timeout_ns) {
1977 if (session->acds_transport && acip_transport_has_pending_data(session->acds_transport)) {
1978 packet_type_t type;
1979 void *data = NULL, *allocated = NULL;
1980 size_t length = 0;
1981 asciichat_error_t result = packet_receive_via_transport(session->acds_transport, &type, &data, &length, &allocated);
1982 if (result == ASCIICHAT_OK)
1983 handle_acds_webrtc_packet(session, type, data, length);
1984 buffer_release(allocated);
1985 }
1986 if (session->handoff_pending || session->state == DISCOVERY_STATE_FAILED)
1987 return ASCIICHAT_OK;
1988 // ACDS owns successor selection; this deadline also bounds a lost signaling decision.
1989 if (session_get_current_time_ms() - session->host_loss_detected_ms > 30 * MS_PER_SEC_INT) {
1990 set_error(session, ERROR_NETWORK_TIMEOUT, "Timed out waiting for ACDS host recovery");
1991 }
1992 platform_sleep_us(timeout_ns / 1000);
1993 return ASCIICHAT_OK;
1994}
1995
1997 if (!session) {
1998 return SET_ERRNO(ERROR_INVALID_PARAM, "session is NULL");
1999 }
2000
2001 // Transport callbacks publish readiness; ownership changes and worker joins
2002 // execute here on the session's controlling thread.
2004 if (result != ASCIICHAT_OK)
2005 return result;
2006
2007 result = discovery_session_send_keepalive(session);
2008 if (result != ASCIICHAT_OK) {
2009 return result;
2010 }
2011
2013 result = discovery_handoff_sample(session);
2014 if (result != ASCIICHAT_OK)
2015 return result;
2016 }
2017
2018 // State handlers preserve deferred failures: recording a failed state does not
2019 // necessarily return an error until the next iteration processes that state.
2020 switch (session->state) {
2022 return discovery_session_wait_for_peer(session, timeout_ns);
2024 return discovery_session_negotiate(session);
2026 return discovery_session_start_host(session);
2028 return session->session_type == SESSION_TYPE_WEBRTC ? discovery_session_connect_webrtc(session) : discovery_session_connect_tcp(session);
2030 return discovery_session_process_active(session, timeout_ns);
2032 return discovery_session_process_migration(session, timeout_ns);
2034 // Session has failed - return error on further processing
2035 return session->error != ASCIICHAT_OK ? session->error : ERROR_NETWORK;
2036
2038 // Session has ended gracefully - return OK
2039 return ASCIICHAT_OK;
2040
2045 // These states are handled during discovery_session_start(), not in the process loop
2046 // If we reach here, something went wrong - sleep and wait
2047 log_debug("State %d should be handled by discovery_session_start", session->state);
2048 platform_sleep_us(timeout_ns / 1000);
2049 break;
2050
2051 default:
2052 return SET_ERRNO(ERROR_INVALID_STATE, "Invalid session state: %d", session->state);
2053 }
2054
2055 return ASCIICHAT_OK;
2056}
2057
2059 ASCII_OTEL_SCOPE(DISCOVERY_SHUTDOWN);
2060 if (!session) {
2061 SET_ERRNO(ERROR_INVALID_PARAM, "session is NULL");
2062 return;
2063 }
2064
2065 log_info("Stopping discovery session...");
2066
2067 // Send SESSION_LEAVE if connected
2068 if (session->acds_transport && session->session_id[0] != 0) {
2069 acip_session_leave_t leave_msg;
2070 memset(&leave_msg, 0, sizeof(leave_msg));
2071 memcpy(leave_msg.session_id, session->session_id, SESSION_ID_SIZE);
2072 memcpy(leave_msg.participant_id, session->participant_id, SESSION_ID_SIZE);
2073
2074 packet_send_via_transport(session->acds_transport, PACKET_TYPE_ACIP_SESSION_LEAVE, &leave_msg, sizeof(leave_msg), 0);
2075 }
2076
2077 set_state(session, DISCOVERY_STATE_ENDED);
2078}
2079
2081 if (!session) {
2082 SET_ERRNO(ERROR_INVALID_PARAM, "null session");
2084 }
2085 return session->state;
2086}
2087
2089 if (!session) {
2090 SET_ERRNO(ERROR_INVALID_PARAM, "null session");
2091 return false;
2092 }
2093 return session->state == DISCOVERY_STATE_ACTIVE;
2094}
2095
2097 if (!session || session->session_string[0] == '\0') {
2098 SET_ERRNO(ERROR_INVALID_PARAM, "null session or session string is empty");
2099 return NULL;
2100 }
2101 return session->session_string;
2102}
2103
2105 if (!session) {
2106 SET_ERRNO(ERROR_INVALID_PARAM, "null session");
2107 return false;
2108 }
2109 return session->is_host;
2110}
2111
2113 if (!session) {
2114 SET_ERRNO(ERROR_INVALID_PARAM, "null session");
2115 return NULL;
2116 }
2117 return session->host_ctx;
2118}
2119
2121 if (!session) {
2122 SET_ERRNO(ERROR_INVALID_PARAM, "null session");
2123 return NULL;
2124 }
2125 return session->participant_ctx;
2126}
2127
2129 if (session)
2130 atomic_store_u64(&session->liveness.last_pong_received_ms, session_get_current_time_ms());
2131}
2132
2139 if (!session || session->is_host) {
2140 // We are the host, so "host" is always alive
2141 return ASCIICHAT_OK;
2142 }
2143
2144 // For WebRTC sessions, check the WebRTC transport instead of participant_ctx
2145 if (session->session_type == SESSION_TYPE_WEBRTC) {
2146 // If we have a WebRTC transport and it's marked as ready, host is alive
2147 if (session->webrtc_transport_ready) {
2148 return ASCIICHAT_OK;
2149 }
2150 // WebRTC transport not ready yet - might still be connecting
2151 return ERROR_NETWORK;
2152 }
2153
2154 // For TCP sessions, check participant context
2155 // If we don't have a participant context yet, we're not connected
2156 if (!session->participant_ctx) {
2157 return ERROR_NETWORK;
2158 }
2159
2160 // Check migration state - if we're already migrating, host is definitely not alive
2161 if (session->state == DISCOVERY_STATE_MIGRATING) {
2162 return ERROR_NETWORK; // Already detected disconnect
2163 }
2164
2165 uint64_t now_ms = session_get_current_time_ms();
2166
2168 session->liveness.ping_in_flight = false;
2169 session->liveness.consecutive_failures = 0;
2170 }
2171 // Check if we have a ping in flight that timed out
2172 if (session->liveness.ping_in_flight) {
2173 uint64_t ping_age_ms = now_ms - session->liveness.last_ping_sent_ms;
2174 if (ping_age_ms > session->liveness.timeout_ms) {
2175 // Ping timed out
2176 session->liveness.consecutive_failures++;
2177 session->liveness.ping_in_flight = false;
2178 log_warn("Host ping timeout (attempt %u/%u, age=%llu ms)", session->liveness.consecutive_failures, session->liveness.max_failures, (unsigned long long)ping_age_ms);
2179
2180 // Check if we've exceeded failure threshold
2181 if (session->liveness.consecutive_failures >= session->liveness.max_failures) {
2182 log_error("Host declared dead after %u consecutive ping failures", session->liveness.consecutive_failures);
2183 return ERROR_NETWORK;
2184 }
2185 }
2186 }
2187
2188 // Check if it's time to send a new ping
2189 uint64_t time_since_last_ping = now_ms - session->liveness.last_ping_sent_ms;
2190 if (!session->liveness.ping_in_flight && time_since_last_ping >= session->liveness.ping_interval_ms) {
2191 // Send ping to host via participant connection
2193 if (!transport || !acip_transport_is_connected(transport))
2194 return SET_ERRNO(ERROR_NETWORK, "Host transport disconnected");
2195 asciichat_error_t result = acip_send_ping(transport);
2196 if (result == ASCIICHAT_OK) {
2197 session->liveness.last_ping_sent_ms = now_ms;
2198 session->liveness.ping_in_flight = true;
2199 log_debug("Sent ping to host (attempt %u/%u)", session->liveness.consecutive_failures + 1, session->liveness.max_failures);
2200 } else {
2201 log_warn("Failed to send ping to host: %d", result);
2202 session->liveness.consecutive_failures++;
2203 if (session->liveness.consecutive_failures >= session->liveness.max_failures) {
2204 log_error("Host declared dead after %u consecutive send failures", session->liveness.consecutive_failures);
2205 return ERROR_NETWORK;
2206 }
2207 }
2208 }
2209
2210 return ASCIICHAT_OK;
2211}
2212
2220 if (!session) {
2221 SET_ERRNO(ERROR_INVALID_PARAM, "session is NULL");
2222 return ERROR_INVALID_PARAM;
2223 }
2224
2225 log_warn("Host disconnect detected: reason=%u", disconnect_reason);
2226
2227 session->host_loss_detected_ms = session_get_current_time_ms();
2228
2229 // Notify ACDS of host loss (lightweight notification, no NAT data exchanged!)
2230 acip_host_lost_t host_lost = {0};
2231 memcpy(host_lost.session_id, session->session_id, SESSION_ID_SIZE);
2232 memcpy(host_lost.participant_id, session->participant_id, SESSION_ID_SIZE);
2233 memcpy(host_lost.last_host_id, session->host_id, SESSION_ID_SIZE);
2234 host_lost.disconnect_reason = disconnect_reason;
2235 host_lost.disconnect_time_ms = session->host_loss_detected_ms;
2236
2237 asciichat_error_t result = packet_send_via_transport(session->acds_transport, PACKET_TYPE_ACIP_HOST_LOST, &host_lost, sizeof(host_lost), 0);
2238 if (result != ASCIICHAT_OK) {
2239 set_error(session, result, "Could not report host loss to ACDS");
2240 return result;
2241 }
2242
2243 // A PLAN is advisory. Only ACDS COMMIT authorizes a role change after fresh
2244 // measurement and preparation. Continue dispatching while awaiting that decision.
2245 set_state(session, DISCOVERY_STATE_MIGRATING);
2246
2247 return ASCIICHAT_OK;
2248}
ascii-chat Discovery Service (ACDS) Protocol Message Formats
asciichat_error_t acds_transport_metadata_decode(const void *data, size_t length, uint16_t *port, char *url, size_t capacity)
asciichat_error_t acds_protocol_join(acds_protocol_t *p, const acds_session_join_params_t *params)
asciichat_error_t acds_transport_metadata_encode(uint16_t port, const char *url, void *output, size_t capacity, size_t *length)
void acds_protocol_init(acds_protocol_t *p, acds_protocol_send_fn send, void *user_data)
void acds_protocol_destroy(acds_protocol_t *p)
asciichat_error_t acds_protocol_create(acds_protocol_t *p, const acds_session_create_params_t *params, uint8_t total_keys, uint8_t key_index)
asciichat_error_t acds_protocol_receive(acds_protocol_t *p, packet_type_t type, const void *payload, size_t length)
asciichat_error_t acds_receive_packet(acip_transport_t *transport, packet_type_t *type, void **payload, size_t *length, void **allocation)
ACIP client-side protocol library and ACDS client connection API.
#define ACDS_TRANSPORT_METADATA_MAX
struct acds_protocol acds_protocol_t
#define ACIP_ADDRESS_SIZE
Definition acds_sizes.h:11
Application-level callbacks for library code.
#define APP_CALLBACK_UINT64(callback_name)
#define APP_CALLBACK_VOID(callback_name)
#define APP_CALLBACK_VOID_UINT(callback_name, value)
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
bool errno_notifications_suppress(bool suppress)
asciichat_errno_scope_t errno_scope_begin(void)
const char * asciichat_error_format(const char *message, asciichat_error_t code)
#define SET_ERRNO(code,...)
#define CLEAR_ERRNO()
@ ASCIICHAT_ERRNO_HANDLED
@ ASCIICHAT_ERRNO_DISMISSED
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.
#define buffer_release(data)
Definition buffer.h:99
Shared endpoint normalization for TCP and WebSocket connections.
@ CONNECTION_ENDPOINT_WEBSOCKET
asciichat_error_t crypto_handshake_init(const char *name, crypto_handshake_context_t *ctx, bool is_server)
Initialize named crypto handshake context.
Named object registry for debugging — log identifiable resource names.
🔄 Network byte order conversion helpers
#define HOST_TO_NET_U16(val)
Definition endian.h:100
#define HOST_TO_NET_U32(val)
Definition endian.h:70
#define NET_TO_HOST_U16(val)
Definition endian.h:115
#define NET_TO_HOST_U32(val)
Definition endian.h:85
Error and exit codes - unified status values (0-255).
int platform_access(const char *pathname, int mode)
Definition filesystem.c:95
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_SNPRINTF(buffer, buffer_size,...)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
unsigned char uint8_t
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_INVALID_PASSWORD
Definition error_codes.h:87
@ ERROR_NETWORK
Definition error_codes.h:76
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_CRYPTO
Definition error_codes.h:97
@ ERROR_USAGE
Definition error_codes.h:52
@ ERROR_INVALID_PARAM
@ ERROR_NETWORK_TIMEOUT
Definition error_codes.h:79
@ ERROR_THREAD
uint8_t key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:78
uint8_t ed25519[ED25519_PRIVATE_KEY_SIZE]
Definition key_types.h:104
key_type_t type
Definition key_types.h:102
uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:109
key_type_t type
Definition key_types.h:77
union private_key_t::@040247167361101132173265304166142033301213115260 key
@ KEY_TYPE_UNKNOWN
Definition key_types.h:57
@ KEY_TYPE_ED25519
Definition key_types.h:58
#define MAX_SESSION_PARTICIPANTS
#define SESSION_ID_SIZE
#define MAX_SESSION_KEYS
#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_session_joined_t
Definition acds.h:479
acip_host_designated_t
Definition acds.h:937
#define ACIP_DISCOVERY_DEFAULT_PORT
Discovery server default port (use OPT_ACDS_PORT_INT_DEFAULT from options.h).
Definition acds.h:1102
acip_webrtc_ice_t
Definition acds.h:655
acip_host_lost_t
Definition acds.h:961
acip_host_announcement_t
Definition acds.h:917
acip_session_created_t
Definition acds.h:274
acip_webrtc_sdp_t
Definition acds.h:609
acip_session_leave_t
Definition acds.h:529
@ ACIP_CONNECTION_TYPE_TURN
TURN relay (fallback).
Definition acds.h:846
@ ACIP_CONNECTION_TYPE_DIRECT_PUBLIC
Direct public IP connection.
Definition acds.h:843
@ ACIP_NAT_TYPE_SYMMETRIC
Symmetric NAT (hardest, requires TURN).
Definition acds.h:835
@ SESSION_TYPE_WEBRTC
WebRTC P2P mesh with STUN/TURN relay.
Definition acds.h:151
@ SESSION_TYPE_DIRECT_TCP
Direct TCP connection to server IP:port (default).
Definition acds.h:150
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
#define MS_PER_SEC_INT
Definition time.h:180
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
@ PACKET_TYPE_ACIP_WEBRTC_ICE
WebRTC ICE candidate (bidirectional).
Definition packet.h:466
@ PACKET_TYPE_ACIP_PARTICIPANT_JOINED
Participant joined notification (ACDS -> Existing Participants).
Definition packet.h:507
@ PACKET_TYPE_ACIP_HOST_LOST
Host lost notification - lightweight (Participant -> ACDS).
Definition packet.h:503
@ PACKET_TYPE_ACIP_HOST_DESIGNATED
Host designated (ACDS -> All Participants).
Definition packet.h:497
@ PACKET_TYPE_ACIP_HOST_ANNOUNCEMENT
Host announcement (Participant -> ACDS, "I won negotiation").
Definition packet.h:495
@ PACKET_TYPE_ACIP_SESSION_LEAVE
Leave session (Client -> Discovery Server).
Definition packet.h:457
@ PACKET_TYPE_ACIP_WEBRTC_SDP
WebRTC SDP offer/answer (bidirectional).
Definition packet.h:464
#define GET_OPTION(field)
Definition options.h:1333
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
#define OPT_ENDPOINT_STUN_SERVERS_DEFAULT
Default STUN servers (comma-separated list).
Definition options.h:633
const options_t * options_get(void)
Get pointer to current options struct (lock-free, thread-safe).
Definition rcu.c:495
#define OPT_ENDPOINT_TURN_SERVERS_DEFAULT
Default TURN servers (comma-separated list).
Definition options.h:639
void session_participant_stop_video(session_participant_t *p)
Stop and join video capture, then release its resources Also stops audio when it may borrow the video...
bool session_participant_is_audio_active(session_participant_t *p)
Check if audio is streaming.
asciichat_error_t session_host_destroy(session_host_t *host)
Destroy session host and free resources.
Definition host.c:289
struct session_participant session_participant_t
Client session state spanning connection, transport, media workers, and callbacks.
asciichat_error_t session_participant_connect(session_participant_t *p)
Connect to session server.
bool session_participant_is_video_active(session_participant_t *p)
Check if video is streaming.
void session_participant_stop_audio(session_participant_t *p)
Stop audio capture and streaming.
struct session_host session_host_t
Opaque session host handle.
bool session_participant_has_transport(session_participant_t *p)
Check if participant has a selected transport.
acip_transport_t * session_participant_get_transport(session_participant_t *p)
Get the current transport for the participant.
asciichat_error_t session_participant_start_video(session_participant_t *p)
Start video capture and streaming.
void session_participant_destroy(session_participant_t *p)
Destroy session participant and free resources.
asciichat_error_t session_participant_set_transport(session_participant_t *p, acip_transport_t *transport, acip_transport_ownership_t ownership)
Select a transport and its ownership mode for the participant.
session_participant_t * session_participant_create(const session_participant_config_t *config)
Server address, security, media, transport, and callback settings for a participant.
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
asciichat_error_t session_host_start(session_host_t *host)
Start accepting client connections.
Definition host.c:1003
void session_participant_disconnect(session_participant_t *p)
Disconnect from session server.
session_host_t * session_host_create(const session_host_config_t *config)
Create a new session host.
Definition host.c:234
asciichat_error_t session_participant_start_audio(session_participant_t *p)
Start audio capture and streaming.
bool shutdown_is_requested(void)
Check if shutdown has been requested.
Definition common.c:86
stun_server_t
Definition stun.h:78
int stun_servers_parse(const char *csv_servers, const char *default_csv, stun_server_t *out_servers, int max_count)
Parse comma-separated STUN server URLs into stun_server_t array.
Definition stun.c:45
turn_server_t
Definition turn.h:106
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_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.
asciichat_error_t webrtc_init(void)
Initialize WebRTC library (libdatachannel).
webrtc_peer_role_t
Peer connection role (server or client).
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.
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)
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).
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_DISCONNECTED
Connection lost.
@ WEBRTC_STATE_FAILED
Connection failed (fatal).
@ WEBRTC_STATE_CLOSED
Connection closed cleanly.
void consensus_handoff_encode(const consensus_handoff_message_t *m, uint8_t out[CONSENSUS_HANDOFF_HEADER])
Definition handoff.c:36
asciichat_error_t consensus_handoff_decode(const void *data, size_t length, consensus_handoff_message_t *m)
Definition handoff.c:16
#define CONSENSUS_HANDOFF_PACKET
Definition handoff.h:13
#define CONSENSUS_HANDOFF_HEADER
Definition handoff.h:15
#define CONSENSUS_HANDOFF_PROBE_BYTES
Definition handoff.h:16
#define CONSENSUS_HANDOFF_FRESH_MS
Definition handoff.h:17
@ HANDOFF_REJECT
Definition handoff.h:28
@ HANDOFF_SAMPLE_DATA
Definition handoff.h:23
@ HANDOFF_COMMIT
Definition handoff.h:27
@ HANDOFF_FAILED
Definition handoff.h:29
@ HANDOFF_PLAN
Definition handoff.h:26
@ HANDOFF_READY
Definition handoff.h:25
@ HANDOFF_PREPARE
Definition handoff.h:24
@ HANDOFF_SAMPLE_START
Definition handoff.h:22
asciichat_error_t session_host_accept_peer(session_host_t *host, acip_transport_t *transport)
Definition host.c:1071
asciichat_error_t acds_identity_load(const char *path, uint8_t public_key[32], uint8_t secret_key[64])
Load identity from file.
Definition identity.c:36
void acds_identity_fingerprint(const uint8_t public_key[32], char fingerprint[(32 *2+1)])
Compute SHA256 fingerprint of public key.
Definition identity.c:131
asciichat_error_t acds_identity_default_path(char *path_out, size_t path_size)
Get default identity file path for current platform.
Definition identity.c:151
asciichat_error_t acds_identity_save(const char *path, const uint8_t public_key[32], const uint8_t secret_key[64])
Save identity to file.
Definition identity.c:88
asciichat_error_t acds_identity_generate(uint8_t public_key[32], uint8_t secret_key[64])
Generate new Ed25519 keypair.
Definition identity.c:22
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Client-side handshake functions.
Common declarations and data structures for cryptographic handshake.
ACIP client-side protocol API.
Transport abstraction layer for ACIP protocol.
@ ACIP_TRANSPORT_TCP
Raw TCP socket.
void network_connection_destroy(network_connection_t **owner)
asciichat_error_t network_connection_open(const char *name, const char *address, uint16_t port, const network_connect_config_t *settings, network_connection_t **out, connection_endpoint_t *resolved)
crypto_handshake_context_t * network_connection_handshake(network_connection_t *c)
acip_transport_t * network_connection_transport(network_connection_t *c)
📝 Logging API with multiple log levels and terminal output control
void nat_quality_init(nat_quality_t *quality)
Connectivity measurements collected while judging a peer's NAT path: public-IP and UPnP availability,...
Definition nat.c:39
asciichat_error_t nat_detect_quality(nat_quality_t *quality, const char *stun_server, uint16_t local_port)
Detect NAT quality using all available methods.
Definition nat.c:299
int nat_compute_tier(const nat_quality_t *quality)
Compute NAT tier for host selection (0=best, 4=worst).
Definition nat.c:46
const char * nat_type_to_string(acip_nat_type_t type)
Get human-readable description of NAT type.
Definition nat.c:351
NAT quality detection for discovery mode host selection.
asciichat_error_t negotiate_determine_result(negotiate_ctx_t *ctx)
Determine negotiation result.
Definition negotiate.c:61
void negotiate_init(negotiate_ctx_t *ctx, const uint8_t session_id[SESSION_ID_SIZE], const uint8_t participant_id[SESSION_ID_SIZE], bool is_initiator)
negotiate ctx is intentionally a small, concrete record. Fields such as is_initiator,...
Definition negotiate.c:16
Host negotiation logic for discovery mode.
@ NEGOTIATE_STATE_INIT
Initial state.
Definition negotiate.h:31
@ NEGOTIATE_STATE_COMPARING
Comparing qualities.
Definition negotiate.h:34
asciichat_error_t network_client_negotiate(acip_transport_t *transport, crypto_handshake_context_t *ctx, uint8_t mode, network_protocol_t protocol)
@ NETWORK_PROTOCOL_DISCOVERY
Definition negotiation.h:9
asciichat_error_t webrtc_turn_servers_parse(const char *csv_urls, const char *username, const char *credential, turn_server_t *servers, size_t capacity, size_t *count_out)
#define NOTICE(severity, title,...)
Definition notice.h:56
#define NOTICE_ANNOUNCE(title,...)
Definition notice.h:60
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:159
void ascii_otel_call_session_used(const char *session_string)
Definition otel.c:420
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:77
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:72
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:71
asciichat_error_t session_participant_take_connection(session_participant_t *p, network_connection_t **connection)
asciichat_error_t crypto_policy_resolve(const crypto_policy_t *policy, uint8_t *mode)
Definition policy.c:4
void stats_runtime_connection_state(const char *state)
Definition runtime.c:132
asciichat_error_t packet_receive_via_transport(acip_transport_t *transport, packet_type_t *type, void **payload, size_t *payload_len, void **alloc_buffer)
Receive a packet via transport with header parsing and validation.
Definition send.c:192
asciichat_error_t acip_send_ping(acip_transport_t *transport)
Send ping packet.
Definition send.c:372
asciichat_error_t packet_send_via_transport(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, uint32_t client_id)
Definition send.c:183
ACIP shared/bidirectional packet sending functions.
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37
#define HEX_STRING_SIZE_32
Hex string size for 32-byte values (64 hex chars + null terminator).
Definition sizes.h:158
#define ED25519_PRIVATE_KEY_SIZE
Ed25519 private key size (seed + public) in bytes.
Definition sizes.h:39
uint8_t session_id[SESSION_ID_SIZE]
uint8_t participant_id[SESSION_ID_SIZE]
bool discovery_session_is_active(const discovery_session_t *session)
Check if session is active (call in progress).
void discovery_session_stop(discovery_session_t *session)
Stop the discovery session.
bool discovery_session_is_host(const discovery_session_t *session)
Check if we are the host.
void discovery_session_host_pong(discovery_session_t *session)
discovery_session_t * discovery_session_create(const discovery_config_t *config)
Configuration for discovery session.
asciichat_error_t discovery_session_start(discovery_session_t *session)
Start the discovery session.
discovery_state_t discovery_session_get_state(const discovery_session_t *session)
Get current session state.
asciichat_error_t discovery_session_check_host_alive(discovery_session_t *session)
Check host transport availability and advance TCP ping/pong liveness. Uses receiver-clock pong timest...
session_host_t * discovery_session_get_host(discovery_session_t *session)
Get host context (if we are host).
asciichat_error_t discovery_session_process(discovery_session_t *session, int64_t timeout_ns)
Process session events (call in main loop).
const char * discovery_session_get_string(const discovery_session_t *session)
Get session string.
asciichat_error_t discovery_session_handle_host_disconnect(discovery_session_t *session, uint32_t disconnect_reason)
Report host loss and await the authoritative ACDS handoff decision. Records the local recovery deadli...
#define DISCOVERY_SESSION_IDENTITY_PATH_BUFFER_SIZE
#define DISCOVERY_SESSION_ERROR_MSG_BUFFER_SIZE
asciichat_error_t discovery_session_apply_handoff(discovery_session_t *session)
Replace the old role after a committed handoff and media-worker shutdown. Releases borrowed-role reso...
asciichat_error_t discovery_session_destroy(discovery_session_t *session)
Destroy discovery session and free resources.
session_participant_t * discovery_session_get_participant(discovery_session_t *session)
Get participant context (if we are participant).
discovery_state_t
Discovery session state.
@ DISCOVERY_STATE_ENDED
Session ended.
@ DISCOVERY_STATE_JOINING_SESSION
Joining existing session.
@ DISCOVERY_STATE_INIT
Initial state.
@ DISCOVERY_STATE_ACTIVE
Session active (call in progress).
@ DISCOVERY_STATE_MIGRATING
Host migration in progress.
@ DISCOVERY_STATE_NEGOTIATING
NAT negotiation in progress.
@ DISCOVERY_STATE_CONNECTING_HOST
Connecting to host as participant.
@ DISCOVERY_STATE_CREATING_SESSION
Creating new session.
@ DISCOVERY_STATE_CONNECTING_ACDS
Connecting to ACDS.
@ DISCOVERY_STATE_WAITING_PEER
Waiting for peer to join (initiator).
@ DISCOVERY_STATE_FAILED
Session failed.
@ DISCOVERY_STATE_STARTING_HOST
Starting as host.
🔤 String Manipulation and Shell Escaping Utilities
acip_session_joined_t joined
acip_session_created_t created
uint16_t quic_port
char error[256]
Session creation request parameters.
uint16_t server_port
Server port where clients should connect.
bool acds_expose_ip
Explicitly allow public IP disclosure (–acds-expose-ip opt-in).
uint8_t identity_seckey[64]
Ed25519 secret key (for signing).
uint8_t max_participants
Maximum participants (1-128).
uint8_t identity_pubkey[32]
Ed25519 public key (host identity).
bool has_password
Password protection enabled.
uint8_t capabilities
Bit 0: video, Bit 1: audio.
char password[128]
Optional password (if has_password).
uint8_t session_type
acds_session_type_t: 0=DIRECT_TCP (default), 1=WEBRTC
Session join parameters.
uint8_t identity_pubkey[32]
Participant's Ed25519 public key.
char password[128]
Password (if has_password).
uint8_t identity_seckey[64]
Ed25519 secret key (for signing).
uint64_t receive_timeout_ns
Optional TCP receive timeout override; zero uses the normal polling timeout.
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
connection_endpoint_protocol_t protocol
uint8_t session[SESSION_ID_SIZE]
Definition handoff.h:35
uint8_t participant[SESSION_ID_SIZE]
Definition handoff.h:36
Cryptographic handshake context structure.
The useful part of crypto policy is in transport_secure, encrypt, no_encrypt, no_auth: together they ...
Definition policy.h:17
Configuration for discovery session.
const char * acds_address
ACDS address (default: "127.0.0.1").
void(* on_error)(asciichat_error_t error, const char *message, void *user_data)
uint16_t acds_port
ACDS port (default: 27225).
const char * password
Session password (optional).
discovery_should_exit_fn should_exit_callback
void(* on_state_change)(discovery_state_t new_state, void *user_data)
const char * session_string
Session string to join (or NULL to create).
const char * acds_url
ACDS WebSocket URL (ws:// or wss://, mutually exclusive with acds_port).
void(* on_session_ready)(const char *session_string, void *user_data)
Discovery session context.
bool nat_detection_completed
Protected by nat_quality_mutex.
char acds_url[512]
instead of TCP)
uint64_t webrtc_last_attempt_time_ms
Timestamp of last connection attempt (monotonic time).
network_connection_t * host_control_connection
Ownership transferred with the control connection.
uint8_t identity_pubkeys[MAX_SESSION_KEYS][ED25519_PUBLIC_KEY_SIZE]
All public keys for multi-key protocol.
acip_transport_t * host_control_transport
Host control connection retained during WebRTC media.
uint8_t initiator_id[SESSION_ID_SIZE]
uint64_t webrtc_disconnected_since_ms
Start of a transient peer disconnection.
uint8_t identity_pubkey[ED25519_PUBLIC_KEY_SIZE]
Ed25519 public key for this participant (primary key).
uint8_t session_type
0 = DIRECT_TCP, 1 = WEBRTC
uint8_t identity_seckey[ED25519_PRIVATE_KEY_SIZE]
Ed25519 secret key for signing (primary key).
platform_thread_t nat_detection_thread
char password[ACIP_PASSWORD_SIZE]
Session password used when joining password-protected sessions.
uint8_t identity_seckeys[MAX_SESSION_KEYS][ED25519_PRIVATE_KEY_SIZE]
Matching Ed25519 signing keys.
uint8_t participant_id[SESSION_ID_SIZE]
int webrtc_retry_attempt
Current retry attempt number (0 = initial, 1+ = retries).
char turn_password[ACIP_PASSWORD_SIZE]
char turn_username[ACIP_TURN_AUTH_SIZE]
char host_address[ACIP_ADDRESS_SIZE]
uint64_t last_acds_keepalive_ns
Last keepalive sent to the discovery service.
bool webrtc_transport_ready
True when DataChannel is open and transport created.
turn_server_t * turn_servers
TURN servers from ACDS.
uint64_t waiting_peer_start_ns
Timestamp when entered WAITING_PEER state (for timeout).
size_t stun_count
Number of STUN servers.
void(* on_error)(asciichat_error_t error, const char *message, void *user_data)
size_t num_identity_keys
Number of identity keys loaded.
uint8_t session_id[SESSION_ID_SIZE]
stun_server_t * stun_servers
STUN servers from ACDS.
void(* on_session_ready)(const char *session_string, void *user_data)
char session_string[SESSION_STRING_BUFFER_SIZE]
discovery_should_exit_fn should_exit_callback
size_t turn_count
Number of TURN servers.
bool webrtc_connection_initiated
True when we've called webrtc_peer_manager_connect().
acip_transport_t * acds_transport
Persistent transport for ACDS communication.
session_participant_t * participant_ctx
network_connection_t * acds_connection
uint64_t host_loss_detected_ms
Local deadline origin while awaiting ACDS recovery.
void(* on_state_change)(discovery_state_t new_state, void *user_data)
struct webrtc_peer_manager * peer_manager
The useful part of discovery session is in state, error, waiting_peer_start_ns, is_initiator: togethe...
uint8_t host_id[SESSION_ID_SIZE]
uint32_t consecutive_failures
Number of consecutive ping failures.
uint32_t max_failures
Threshold for triggering migration (default: 3).
atomic_t last_pong_received_ms
Timestamp of last pong received (monotonic).
uint64_t ping_interval_ms
Time between pings (default: 3000ms).
uint64_t last_ping_sent_ms
Timestamp of last ping sent (monotonic).
bool ping_in_flight
True if waiting for pong.
uint64_t timeout_ms
Timeout for ping response (default: 10000ms).
NAT quality assessment result.
Definition nat.h:28
bool detection_complete
All probes finished.
Definition nat.h:52
bool lan_reachable
Same subnet as peer.
Definition nat.h:34
acip_nat_type_t nat_type
NAT classification.
Definition nat.h:33
bool has_public_ip
STUN reflexive == local IP.
Definition nat.h:30
bool upnp_available
UPnP/NAT-PMP mapping succeeded.
Definition nat.h:31
bool we_are_host
True if we should become host.
Definition negotiate.h:60
char host_address[64]
Host's address (ours if we_are_host).
Definition negotiate.h:61
nat_quality_t our_quality
Our NAT quality.
Definition negotiate.h:51
bool peer_quality_received
Have we received peer's quality?
Definition negotiate.h:53
nat_quality_t peer_quality
Peer's NAT quality (when received).
Definition negotiate.h:52
negotiate_state_t state
Definition negotiate.h:56
uint16_t host_port
Host's port.
Definition negotiate.h:62
size_t num_identity_keys
Number of identity keys loaded (0 means single-key mode using encrypt_key).
Definition options.h:1183
bool webrtc_relay_only
–webrtc-relay-only: Require TURN relay candidates
Definition options.h:1202
char identity_keys[32][256]
All identity keys (populated when –key is used multiple times).
Definition options.h:1182
bool prefer_webrtc
–prefer-webrtc: Try WebRTC before Direct TCP
Definition options.h:1198
char encrypt_key[256]
SSH/GPG key file path (first –key flag, kept for compatibility).
Definition options.h:1172
Host-side event hooks for joins, departures, media, and errors.
Definition host.h:163
Client-side event hooks for connection, media, settings, and errors.
Peer manager configuration.
Hooks that deliver local SDP offers/answers and ICE candidates to ACDS.
bool is_tailscale_host(const char *address)
Determine whether an address belongs to the local Tailscale tailnet.
Definition tailscale.c:62
Tailscale host identity helpers.
⏱️ High-precision timing utilities using sokol_time.h and uthash
asciichat_error_t ui_input_password(const char *target, char *buffer, size_t capacity, bool incorrect)
Definition tui/input.c:727