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-service/server.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define DISCOVERY_SERVICE_SERVER_SESSION_STRING_BUFFER_SIZE 49
4
7#include <ascii-chat/otel.h>
11/* Discovery application state, session persistence, and ACIP callbacks.
12 * Connection establishment and execution belong to the shared network runtime. */
13
30#include <ascii-chat/log/log.h>
31#include <libplatform/socket.h>
33#include <ascii-chat/buffer.h>
36#include <ascii-chat/util/ip.h>
39#include <string.h>
44
56
57static asciichat_error_t acds_handoff_tick(acds_server_t *, consensus_handoff_t *);
58
59static void *cleanup_thread_func(void *arg) {
60 acds_server_t *server = (acds_server_t *)arg;
61 if (!server) {
62 return NULL;
63 }
64
65 log_info("Cleanup thread started (rate limits + expired sessions)");
66
67 while (!atomic_load_bool(&server->shutdown)) {
68 // Sleep for 5 minutes (or until shutdown)
69 // Use 100ms sleep intervals for responsive shutdown on timeout
70 for (int i = 0; i < 3000 && !atomic_load_bool(&server->shutdown); i++) {
71 APP_CALLBACK_VOID(platform_pump_events);
72 mutex_lock(&server->handoff_mutex);
73 for (acds_handoff_entry_t *entry = server->handoffs; entry; entry = entry->next) {
74 asciichat_error_t tick_result = acds_handoff_tick(server, &entry->state);
75 if (tick_result != ASCIICHAT_OK)
76 log_warn("Periodic handoff failed %s", asciichat_error_format(NULL, tick_result));
77 }
78 mutex_unlock(&server->handoff_mutex);
79 platform_sleep_ms(100); // Sleep 100ms at a time for responsive shutdown
80 }
81
82 if (atomic_load_bool(&server->shutdown)) {
83 break;
84 }
85
86 // Run rate limit cleanup (delete events older than 1 hour)
87 log_debug("Running rate limit cleanup...");
89 if (result != ASCIICHAT_OK) {
90 log_warn("Rate limit cleanup failed");
91 }
92
93 // Run expired session cleanup
94 log_debug("Running expired session cleanup...");
96 }
97
98 log_info("Cleanup thread exiting");
99 return NULL;
100}
101
103 ASCII_OTEL_SCOPE(DISCOVERY_INIT);
104 if (!server || !config) {
105 return SET_ERRNO(ERROR_INVALID_PARAM, "server or config is NULL");
106 }
107
108 memset(server, 0, sizeof(*server));
109 asciichat_error_t lock_result = mutex_init(&server->handoff_mutex, "acds_handoff");
110 if (lock_result != ASCIICHAT_OK)
111 return lock_result;
112 server->handoff_mutex_initialized = true;
113 memcpy(&server->config, config, sizeof(acds_config_t));
114
115 // Initialize stats
116 atomic_store_u64(&server->stats.bytes_sent, 0);
120 server->stats.start_time = time(NULL);
121
122 // Open database (SQLite as single source of truth)
123 asciichat_error_t result = database_init(config->database_path, &server->db);
124 if (result != ASCIICHAT_OK) {
125 goto init_failed;
126 }
127
128 // Initialize rate limiter with SQLite backend
129 server->rate_limiter = rate_limiter_create_sqlite(NULL); // NULL = externally managed DB
130 if (!server->rate_limiter) {
131 result = SET_ERRNO(ERROR_MEMORY, "Failed to create rate limiter");
132 goto init_failed;
133 }
134
135 // Set the database handle for the rate limiter
137
138 // Get TCP server from server_like (it owns the lifecycle)
140 if (!server->network_server) {
141 result = SET_ERRNO(ERROR_INVALID_STATE, "TCP server not available from server_like");
142 goto init_failed;
143 }
144
145 // Initialize background worker thread pool
146 atomic_store_bool(&server->shutdown, false);
147 server->worker_pool = thread_pool_create("acds_workers");
148 if (!server->worker_pool) {
149 log_warn("Failed to create worker thread pool");
150 result = SET_ERRNO(ERROR_MEMORY, "Failed to create worker thread pool");
151 goto init_failed;
152 }
153
154 // Spawn cleanup thread in worker pool
155 if (thread_pool_spawn(server->worker_pool, cleanup_thread_func, server, 0, "cleanup") != ASCIICHAT_OK) {
156 log_warn("Failed to spawn cleanup thread (continuing without cleanup)");
157 }
158
159 log_info("Discovery server initialized successfully");
160 return ASCIICHAT_OK;
161
162init_failed:
163 acds_server_shutdown(server);
164 return result;
165}
166
168 ASCII_OTEL_SCOPE(DISCOVERY_SHUTDOWN);
169 if (!server) {
170 return;
171 }
172
173 // Signal shutdown to worker threads
174 atomic_store_bool(&server->shutdown, true);
175
176 // Stop and destroy worker thread pool (cleanup thread, etc.)
177 if (server->worker_pool) {
179 server->worker_pool = NULL;
180 log_debug("Worker thread pool stopped");
181 }
182
183 if (server->handoff_mutex_initialized) {
184 mutex_lock(&server->handoff_mutex);
185 while (server->handoffs) {
186 acds_handoff_entry_t *entry = server->handoffs;
187 server->handoffs = entry->next;
188 SAFE_FREE(entry);
189 }
190 mutex_unlock(&server->handoff_mutex);
191 mutex_destroy(&server->handoff_mutex);
192 server->handoff_mutex_initialized = false;
193 }
194
195 // Destroy rate limiter
196 if (server->rate_limiter) {
198 server->rate_limiter = NULL;
199 }
200
201 // Close database
202 if (server->db) {
203 database_close(server->db);
204 server->db = NULL;
205 }
206
207 log_info("Server shutdown complete");
208}
209
210// =============================================================================
211// ACIP Transport Helper Macros for ACDS - REMOVED
212// =============================================================================
213// Transport is now passed to callbacks as a parameter, no need for temp creation
214
215// =============================================================================
216// Stats Tracking Helper
217// =============================================================================
218
219static inline void acds_track_packet_sent(acds_server_t *server, size_t payload_size) {
220 if (server) {
221 // Packet size includes header (same as receive)
222 size_t total_packet_size = payload_size + sizeof(packet_header_t);
223 atomic_fetch_add_u64(&server->stats.bytes_sent, total_packet_size);
225 }
226}
227
228// =============================================================================
229// ACIP Callback Wrappers for ACDS
230// =============================================================================
231// These callbacks are invoked by acip_handle_acds_packet() via O(1) array dispatch.
232// Each callback implements: Rate Limit → Crypto Verify → Business Logic → DB Save
233
234// Publish complete connection membership atomically with respect to host fanout.
235static void acds_client_joined(acds_server_t *server, acds_client_data_t *client, const uint8_t session_id[SESSION_ID_SIZE], const uint8_t participant_id[SESSION_ID_SIZE]) {
236 if (!client) {
237 SET_ERRNO(ERROR_INVALID_PARAM, "Missing discovery client membership");
238 return;
239 }
240 mutex_lock(&server->handoff_mutex);
241 memcpy(client->session_id, session_id, sizeof(client->session_id));
242 memcpy(client->participant_id, participant_id, sizeof(client->participant_id));
243 client->joined_session = true;
244 client->session_established = true;
245 mutex_unlock(&server->handoff_mutex);
246}
247
248static void acds_on_session_create(const acip_session_create_t *req, acip_transport_t *transport, const char *client_ip, const uint8_t *extension, size_t extension_length, void *app_ctx) {
249 ASCII_OTEL_SCOPE(DISCOVERY_CREATE);
250 acds_server_t *server = (acds_server_t *)app_ctx;
251 acds_client_data_t *client_data = (acds_client_data_t *)transport->user_data;
252
253 log_debug("SESSION_CREATE packet from %s", client_ip);
254
255 if (!client_data) {
256 acip_send_error(transport, ERROR_INVALID_PARAM, "Client data not found");
257 return;
258 }
259
260 // Rate-limit each new sequence, including legacy single-key requests.
261 if (req->key_index == 0) {
262
263 bool allowed = false;
264 asciichat_error_t rate_check = rate_limiter_check(server->rate_limiter, client_ip, RATE_EVENT_SESSION_CREATE, NULL, &allowed);
265 if (rate_check != ASCIICHAT_OK || !allowed) {
266 memset(&client_data->create_keys, 0, sizeof(client_data->create_keys));
267 acip_send_error(transport, ERROR_RATE_LIMITED, "Rate limit exceeded. Please try again later.");
268 return;
269 }
271 }
272 if (req->key_index == 0) {
273 client_data->create_transport_length = extension_length;
274 if (extension_length)
275 memcpy(client_data->create_transport_metadata, extension, extension_length);
276 } else if (extension_length != client_data->create_transport_length || (extension_length && memcmp(extension, client_data->create_transport_metadata, extension_length))) {
277 memset(&client_data->create_keys, 0, sizeof(client_data->create_keys));
278 acip_send_error(transport, ERROR_INVALID_PARAM, "Transport endpoints changed during session creation");
279 return;
280 }
281 bool complete = false;
282 asciichat_error_t result = acds_create_key_set_collect(&client_data->create_keys, req, server->config.require_server_identity, &complete);
283 if (result != ASCIICHAT_OK) {
284 acip_send_error(transport, result, "Invalid session key sequence or identity proof");
285 return;
286 }
287 if (!complete)
288 return;
289
290 acip_session_create_t *pending = &client_data->create_keys.request;
291 if (pending->server_address[0] == '\0')
292 SAFE_STRNCPY(pending->server_address, client_ip, sizeof(pending->server_address));
293 if (pending->session_type == SESSION_TYPE_DIRECT_TCP && strcmp(pending->server_address, client_ip) != 0) {
294 memset(&client_data->create_keys, 0, sizeof(client_data->create_keys));
295 acip_send_error(transport, ERROR_INVALID_PARAM, "Direct TCP address must match the connection source");
296 return;
297 }
298 acip_session_created_t resp = {0};
299 asciichat_error_t create_result =
300 database_session_create_keys_with_transport(server->db, pending, client_data->create_keys.keys, client_data->create_keys.count, &server->config, &resp, extension, extension_length);
301 if (create_result == ASCIICHAT_OK) {
303 // Build complete payload: fixed response + variable STUN/TURN servers
304 size_t stun_size = (size_t)resp.stun_count * sizeof(stun_server_t);
305 size_t turn_size = (size_t)resp.turn_count * sizeof(turn_server_t);
306 size_t total_size = sizeof(resp) + stun_size + turn_size;
307
308 uint8_t *payload = SAFE_MALLOC(total_size, uint8_t *);
309 if (!payload) {
310 acip_send_error(transport, ERROR_MEMORY, "Out of memory building response");
311 memset(&client_data->create_keys, 0, sizeof(client_data->create_keys));
312 return;
313 }
314
315 // Copy fixed response
316 memcpy(payload, &resp, sizeof(resp));
317
318 // Append STUN servers
319 if (resp.stun_count > 0) {
320 memcpy(payload + sizeof(resp), server->config.stun_servers, stun_size);
321 }
322
323 // Append TURN servers
324 if (resp.turn_count > 0) {
325 memcpy(payload + sizeof(resp) + stun_size, server->config.turn_servers, turn_size);
326 }
327
328 // Send complete response with variable-length data
329 packet_send_via_transport(transport, PACKET_TYPE_ACIP_SESSION_CREATED, payload, total_size, 0);
330 acds_track_packet_sent(server, total_size);
331 SAFE_FREE(payload);
332
333 log_info("Session created: %.*s (UUID: %02x%02x..., %zu keys, %d STUN, %d TURN servers)", resp.session_string_len, resp.session_string, resp.session_id[0], resp.session_id[1],
334 client_data->create_keys.count, resp.stun_count, resp.turn_count);
335
336 acds_client_joined(server, client_data, resp.session_id, resp.participant_id);
337 } else {
338 // Error - send error response using proper error code
339 acip_send_error(transport, create_result, "Failed to create session");
340 log_warn("Session creation failed for %s: %s", client_ip, asciichat_error_format(NULL, create_result));
341 }
342
343 memset(&client_data->create_keys, 0, sizeof(client_data->create_keys));
344}
345
346static void acds_on_session_lookup(const acip_session_lookup_t *req, acip_transport_t *transport, const char *client_ip, void *app_ctx) {
347 ASCII_OTEL_SCOPE(DISCOVERY_LOOKUP);
348 acds_server_t *server = (acds_server_t *)app_ctx;
349
350 log_debug("SESSION_LOOKUP packet from %s", client_ip);
351
352 // Rate limiting check
353 {
354 bool allowed = false;
355 asciichat_error_t rate_check = rate_limiter_check(server->rate_limiter, client_ip, RATE_EVENT_SESSION_LOOKUP, NULL, &allowed);
356 if (rate_check != ASCIICHAT_OK || !allowed) {
357 acip_send_error(transport, ERROR_RATE_LIMITED, "Rate limit exceeded. Please try again later.");
358 log_warn("Rate limit exceeded for SESSION_LOOKUP from %s", client_ip);
359 return;
360 }
362 }
363
365 memset(&resp, 0, sizeof(resp));
366
367 // Null-terminate session string for lookup
369 size_t copy_len = (req->session_string_len < sizeof(session_string) - 1) ? req->session_string_len : sizeof(session_string) - 1;
370 memcpy(session_string, req->session_string, copy_len);
371
372 asciichat_error_t lookup_result = database_session_lookup(server->db, session_string, &server->config, &resp);
373 if (lookup_result == ASCIICHAT_OK) {
375 acip_send_session_info(transport, &resp);
376 log_info("Session lookup for '%s' from %s: %s", session_string, client_ip, resp.found ? "found" : "not found");
377 } else {
378 acip_send_error(transport, lookup_result, "Session lookup failed");
379 log_warn("Session lookup failed for %s: %s", client_ip, asciichat_error_format(NULL, lookup_result));
380 }
381}
382
383static void acds_on_session_join(const acip_session_join_t *req, acip_transport_t *transport, const char *client_ip, void *app_ctx) {
384 ASCII_OTEL_SCOPE(DISCOVERY_JOIN);
385 acds_server_t *server = (acds_server_t *)app_ctx;
386 acds_client_data_t *client_data = (acds_client_data_t *)transport->user_data;
387
388 log_debug("SESSION_JOIN packet from %s", client_ip);
389
390 // Rate limiting check
391 {
392 bool allowed = false;
393 asciichat_error_t rate_check = rate_limiter_check(server->rate_limiter, client_ip, RATE_EVENT_SESSION_JOIN, NULL, &allowed);
394 if (rate_check != ASCIICHAT_OK || !allowed) {
395 acip_send_error(transport, ERROR_RATE_LIMITED, "Rate limit exceeded. Please try again later.");
396 log_warn("Rate limit exceeded for SESSION_JOIN from %s", client_ip);
397 return;
398 }
400 }
401
403 memset(&resp, 0, sizeof(resp));
404
405 asciichat_error_t join_result = database_session_join(server->db, req, &server->config, &resp);
406 if (join_result == ASCIICHAT_OK && resp.success) {
408 uint8_t metadata[521];
409 size_t metadata_length = 0;
410 asciichat_error_t metadata_result = resp.server_address[0] ? database_session_transport_get(server->db, resp.session_id, metadata, sizeof(metadata), &metadata_length) : ASCIICHAT_OK;
411 if (metadata_result != ASCIICHAT_OK) {
412 database_session_leave(server->db, resp.session_id, resp.participant_id);
413 acip_send_error(transport, metadata_result, "Cannot read session transport endpoints");
414 return;
415 }
416 if (metadata_length) {
417 uint8_t response[sizeof(resp) + sizeof(metadata)];
418 memcpy(response, &resp, sizeof(resp));
419 memcpy(response + sizeof(resp), metadata, metadata_length);
420 packet_send_via_transport(transport, PACKET_TYPE_ACIP_SESSION_JOINED, response, sizeof(resp) + metadata_length, 0);
421 } else {
422 acip_send_session_joined(transport, &resp);
423 }
424
425 acds_client_joined(server, client_data, resp.session_id, resp.participant_id);
426
427 log_info("Client %s joined session (participant %02x%02x...)", client_ip, resp.participant_id[0], resp.participant_id[1]);
428
429 acds_send_current_host(server, transport, resp.session_id);
430
431 // Broadcast PARTICIPANT_JOINED notification to all other participants in the session
432 acip_participant_joined_t participant_joined;
433 memset(&participant_joined, 0, sizeof(participant_joined));
434 memcpy(participant_joined.session_id, resp.session_id, SESSION_ID_SIZE);
435 memcpy(participant_joined.new_participant_id, resp.participant_id, SESSION_ID_SIZE);
436 memcpy(participant_joined.new_participant_pubkey, req->identity_pubkey, ED25519_PUBLIC_KEY_SIZE);
437 // peer_count is the number of OTHER participants; total = peer_count + 1 (the new one)
438 participant_joined.current_participant_count = resp.peer_count + 1;
439
440 asciichat_error_t broadcast_result =
441 signaling_broadcast(server->db, server->network_server, resp.session_id, PACKET_TYPE_ACIP_PARTICIPANT_JOINED, &participant_joined, sizeof(participant_joined), resp.participant_id);
442
443 if (broadcast_result != ASCIICHAT_OK) {
444 log_warn("Failed to broadcast PARTICIPANT_JOINED for session %02x%02x...: %d", resp.session_id[0], resp.session_id[1], broadcast_result);
445 } else {
446 log_debug("Broadcasted PARTICIPANT_JOINED to other participants in session");
447 }
448 } else {
449 acip_send_session_joined(transport, &resp);
450 log_warn("Session join failed for %s: %s", client_ip, resp.error_message);
451 }
452}
453
454static consensus_handoff_t *acds_handoff_find(acds_server_t *, const uint8_t[16], bool);
455static asciichat_error_t acds_handoff_tick(acds_server_t *, consensus_handoff_t *);
456
457static asciichat_error_t acds_remove_client_from_session(acds_server_t *server, acds_client_data_t *client_data) {
458 if (!server || !client_data || !client_data->joined_session) {
459 return ASCIICHAT_OK;
460 }
461
462 session_entry_t *session = database_session_find_by_id(server->db, client_data->session_id);
463 bool was_host = false;
464 if (session) {
465 const uint8_t *host_id = session->host_established ? session->host_participant_id : session->initiator_id;
466 was_host = memcmp(host_id, client_data->participant_id, sizeof(client_data->participant_id)) == 0;
467 session_entry_destroy(session);
468 }
469
470 asciichat_error_t result = database_session_leave(server->db, client_data->session_id, client_data->participant_id);
471 if (result != ASCIICHAT_OK) {
472 return SET_ERRNO(result, "Failed to remove disconnected participant from session");
473 }
474
475 mutex_lock(&server->handoff_mutex);
476 client_data->joined_session = false;
477 consensus_handoff_t *handoff = acds_handoff_find(server, client_data->session_id, false);
478 if (handoff) {
479 consensus_handoff_leave(handoff, client_data->participant_id);
480 asciichat_error_t handoff_result = acds_handoff_tick(server, handoff);
481 if (handoff_result != ASCIICHAT_OK)
482 log_warn("Handoff after departure failed %s", asciichat_error_format(NULL, handoff_result));
483 if (!handoff->count) {
484 acds_handoff_entry_t **link = &server->handoffs;
485 while (*link && &(*link)->state != handoff)
486 link = &(*link)->next;
487 if (*link) {
488 acds_handoff_entry_t *entry = *link;
489 *link = entry->next;
490 SAFE_FREE(entry);
491 }
492 }
493 }
494 mutex_unlock(&server->handoff_mutex);
495
496 // A closed connection can no longer send SESSION_LEAVE. Notify peers after
497 // deleting the participant so reconnects do not try signaling this socket.
498 session = database_session_find_by_id(server->db, client_data->session_id);
499 if (session) {
500 acip_participant_left_t participant_left = {0};
501 memcpy(participant_left.session_id, client_data->session_id, sizeof(participant_left.session_id));
502 memcpy(participant_left.left_participant_id, client_data->participant_id, sizeof(participant_left.left_participant_id));
503 participant_left.was_host = was_host ? 1 : 0;
504 participant_left.remaining_count = session->current_participants;
505 result =
506 signaling_broadcast(server->db, server->network_server, client_data->session_id, PACKET_TYPE_ACIP_PARTICIPANT_LEFT, &participant_left, sizeof(participant_left), client_data->participant_id);
507 if (result != ASCIICHAT_OK) {
508 log_warn("Failed to notify peers that participant left: %s", asciichat_error_format(NULL, result));
509 }
510 session_entry_destroy(session);
511 }
512
513 return ASCIICHAT_OK;
514}
515
516static void acds_on_session_leave(const acip_session_leave_t *req, acip_transport_t *transport, const char *client_ip, void *app_ctx) {
517 ASCII_OTEL_SCOPE(DISCOVERY_LEAVE);
518 acds_server_t *server = (acds_server_t *)app_ctx;
519 acds_client_data_t *client_data = (acds_client_data_t *)transport->user_data;
520
521 log_debug("SESSION_LEAVE packet from %s", client_ip);
522
523 if (!client_data || !client_data->joined_session || memcmp(req->session_id, client_data->session_id, sizeof(client_data->session_id)) != 0 ||
524 memcmp(req->participant_id, client_data->participant_id, sizeof(client_data->participant_id)) != 0) {
525 acip_send_error(transport, ERROR_INVALID_PARAM, "SESSION_LEAVE does not match this connection");
526 log_warn("Rejected SESSION_LEAVE from %s because it did not match the joined participant", client_ip);
527 return;
528 }
529
530 asciichat_error_t leave_result = acds_remove_client_from_session(server, client_data);
531 if (leave_result == ASCIICHAT_OK) {
532 log_info("Client %s left session", client_ip);
533 } else {
534 acip_send_error(transport, leave_result, asciichat_error_string(leave_result));
535 log_warn("Session leave failed for %s: %s", client_ip, asciichat_error_format(NULL, leave_result));
536 }
537}
538
539static void acds_on_webrtc_sdp(const acip_webrtc_sdp_t *sdp, size_t payload_len, acip_transport_t *transport, const char *client_ip, void *app_ctx) {
540 acds_server_t *server = (acds_server_t *)app_ctx;
541 (void)transport; // Transport not needed for relay
542
543 log_debug("WEBRTC_SDP packet from %s", client_ip);
544
545 // Validation is done in the library handler (lib/network/acip/acds_handlers.c)
546 asciichat_error_t relay_result = signaling_relay_sdp(server->db, server->network_server, sdp, payload_len);
547 if (relay_result != ASCIICHAT_OK) {
548 acip_send_error(transport, relay_result, "SDP relay failed");
549 log_warn("SDP relay failed from %s: %s", client_ip, asciichat_error_format(NULL, relay_result));
550 }
551}
552
553static void acds_on_webrtc_ice(const acip_webrtc_ice_t *ice, size_t payload_len, acip_transport_t *transport, const char *client_ip, void *app_ctx) {
554 acds_server_t *server = (acds_server_t *)app_ctx;
555 (void)transport; // Transport not needed for relay
556
557 log_debug("WEBRTC_ICE packet from %s", client_ip);
558
559 // Validation is done in the library handler (lib/network/acip/acds_handlers.c)
560 asciichat_error_t relay_result = signaling_relay_ice(server->db, server->network_server, ice, payload_len);
561 if (relay_result != ASCIICHAT_OK) {
562 acip_send_error(transport, relay_result, "ICE relay failed");
563 log_warn("ICE relay failed from %s: %s", client_ip, asciichat_error_format(NULL, relay_result));
564 }
565}
566
567static acip_host_designated_t acds_host_designation(const session_entry_t *session, uint32_t generation, uint32_t sequence) {
568 acip_host_designated_t designated = {0};
569 memcpy(designated.session_id, session->session_id, sizeof(designated.session_id));
570 memcpy(designated.host_id, session->host_participant_id, sizeof(designated.host_id));
571 if (session->has_password || session->expose_ip_publicly)
572 SAFE_STRNCPY(designated.host_address, session->host_address, sizeof(designated.host_address));
573 designated.host_port = session->host_port;
574 designated.connection_type = session->host_connection_type;
575 designated.generation = HOST_TO_NET_U32(generation);
576 designated.sequence = HOST_TO_NET_U32(sequence);
577 return designated;
578}
579
580/* Send the optional extension first, then the legacy fixed-size designation.
581 * New peers accept the first authority update and ignore its duplicate; old
582 * peers can continue using the fixed-size message and TCP/WebRTC endpoint. */
583static asciichat_error_t acds_send_designation(acds_server_t *server, const session_entry_t *stored, uint32_t generation, uint32_t sequence, acip_transport_t *recipient) {
584 acip_host_designated_t designated = acds_host_designation(stored, generation, sequence);
585 uint8_t payload[sizeof(designated) + ACDS_TRANSPORT_METADATA_MAX];
586 size_t length = 0;
588 if (designated.host_address[0])
589 result = database_session_transport_get(server->db, stored->session_id, payload + sizeof(designated), ACDS_TRANSPORT_METADATA_MAX, &length);
590 if (result != ASCIICHAT_OK)
591 return result;
592 if (length) {
593 memcpy(payload, &designated, sizeof(designated));
594 result = recipient ? packet_send_via_transport(recipient, PACKET_TYPE_ACIP_HOST_DESIGNATED, payload, sizeof(designated) + length, 0)
595 : signaling_broadcast(server->db, server->network_server, stored->session_id, PACKET_TYPE_ACIP_HOST_DESIGNATED, payload, sizeof(designated) + length, NULL);
596 }
597 asciichat_error_t legacy = recipient ? packet_send_via_transport(recipient, PACKET_TYPE_ACIP_HOST_DESIGNATED, &designated, sizeof(designated), 0)
598 : signaling_broadcast(server->db, server->network_server, stored->session_id, PACKET_TYPE_ACIP_HOST_DESIGNATED, &designated, sizeof(designated), NULL);
599 return result != ASCIICHAT_OK ? result : legacy;
600}
601
602static bool acds_host_endpoint_conflicts(const session_entry_t *stored, const acip_host_announcement_t *announcement, const char *address) {
603 // Accepted endpoints are immutable within a committed decision; duplicates can repair delivery.
604 return stored->host_established && stored->host_address[0] &&
605 (memcmp(stored->host_participant_id, announcement->host_id, SESSION_ID_SIZE) || strcmp(stored->host_address, address) || stored->host_port != announcement->host_port ||
606 stored->host_connection_type != announcement->connection_type);
607}
608
609// Caller holds handoff_mutex through validation, persistence and delivery.
610static asciichat_error_t acds_update_announced_host(acds_server_t *server, const acip_host_announcement_t *announcement, const char *address, const void *metadata, size_t metadata_length) {
611 ASCII_OTEL_SCOPE(DISCOVERY_HOST_DESIGNATION);
612 ASCII_OTEL_ATTR_STRING("host.update.source", "announcement");
613 ASCII_OTEL_ATTR_STRING("host.update.outcome", "rejected");
614 uint32_t generation = NET_TO_HOST_U32(announcement->generation);
615 ASCII_OTEL_ATTR_INT("host.generation", generation);
616 consensus_handoff_t *handoff = acds_handoff_find(server, announcement->session_id, true);
617 if (!handoff || memcmp(handoff->host, announcement->host_id, SESSION_ID_SIZE) || generation != handoff->generation || NET_TO_HOST_U32(announcement->sequence) != handoff->host_sequence)
618 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Obsolete or unauthorized host announcement");
619 session_entry_t *stored = database_session_find_by_id(server->db, announcement->session_id);
620 if (!stored)
621 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Host announcement session not found");
622 if (acds_host_endpoint_conflicts(stored, announcement, address)) {
623 session_entry_destroy(stored);
624 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Conflicting host endpoint");
625 }
627 size_t previous_length = 0;
628 asciichat_error_t result = database_session_transport_get(server->db, announcement->session_id, previous, sizeof(previous), &previous_length);
629 if (result == ASCIICHAT_OK && metadata_length && previous_length && (previous_length != metadata_length || memcmp(previous, metadata, metadata_length)))
630 result = SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Conflicting host transport endpoints");
631 if (result == ASCIICHAT_OK)
632 result = database_session_update_host_with_transport(server->db, announcement->session_id, announcement->host_id, address, announcement->host_port, announcement->connection_type, metadata,
633 metadata_length);
634 if (result == ASCIICHAT_OK) {
635 memcpy(stored->host_participant_id, announcement->host_id, sizeof(stored->host_participant_id));
636 SAFE_STRNCPY(stored->host_address, address, sizeof(stored->host_address));
637 stored->host_port = announcement->host_port;
638 stored->host_connection_type = announcement->connection_type;
639 result = acds_send_designation(server, stored, generation, handoff->host_sequence, NULL);
640 }
641 ASCII_OTEL_ATTR_STRING("host.update.outcome", result == ASCIICHAT_OK ? "broadcast_attempted" : "failed");
642 ASCII_OTEL_ATTR_INT("host.update.error_code", result);
643 session_entry_destroy(stored);
644 return result;
645}
646
647void acds_on_host_announcement(const acip_host_announcement_t *announcement, acip_transport_t *transport, const char *client_ip, void *app_ctx) {
648 acds_on_host_announcement_ex(announcement, NULL, 0, transport, client_ip, app_ctx);
649}
650
651void acds_on_host_announcement_ex(const acip_host_announcement_t *announcement, const void *metadata, size_t metadata_length, acip_transport_t *transport, const char *client_ip, void *app_ctx) {
652
653 ASCII_OTEL_SCOPE(DISCOVERY_HOST_ANNOUNCE);
654 acds_server_t *server = (acds_server_t *)app_ctx;
655 ASCII_OTEL_ATTR_INT("host.generation", NET_TO_HOST_U32(announcement->generation));
656 ASCII_OTEL_ATTR_INT("host.decision.sequence", NET_TO_HOST_U32(announcement->sequence));
657 ASCII_OTEL_ATTR_STRING("host.update.outcome", "rejected");
658
659 log_info("HOST_ANNOUNCEMENT from %s: host_id=%02x%02x..., address=%.64s:%u, conn_type=%d", client_ip, announcement->host_id[0], announcement->host_id[1], announcement->host_address,
660 announcement->host_port, announcement->connection_type);
661
662 acds_client_data_t *client = transport ? transport->user_data : NULL;
663 if (!client || !client->joined_session || memcmp(client->participant_id, announcement->host_id, SESSION_ID_SIZE) || memcmp(client->session_id, announcement->session_id, SESSION_ID_SIZE)) {
664 ASCII_OTEL_ATTR_STRING("host.update.reason", "identity_mismatch");
665 acip_send_error(transport, ERROR_NETWORK_PROTOCOL, "Host announcement identity mismatch");
666 return;
667 }
668 if (!memchr(announcement->host_address, 0, sizeof(announcement->host_address)) || !announcement->host_port || announcement->connection_type > ACIP_CONNECTION_TYPE_TURN) {
669 ASCII_OTEL_ATTR_STRING("host.update.reason", "invalid_endpoint");
670 acip_send_error(transport, ERROR_NETWORK_PROTOCOL, "Invalid host endpoint");
671 return;
672 }
673 uint16_t quic_port;
674 char webtransport_url[512];
675 if (acds_transport_metadata_decode(metadata, metadata_length, &quic_port, webtransport_url, sizeof(webtransport_url)) != ASCIICHAT_OK) {
676 acip_send_error(transport, ERROR_NETWORK_PROTOCOL, "Invalid host transport metadata");
677 return;
678 }
679 const char *host_address = announcement->host_address[0] ? announcement->host_address : client_ip;
680 // Serialize authority validation, persistence and delivery with handoff commits.
681 mutex_lock(&server->handoff_mutex);
682 asciichat_error_t result = acds_update_announced_host(server, announcement, host_address, metadata, metadata_length);
683 mutex_unlock(&server->handoff_mutex);
684 ASCII_OTEL_ATTR_STRING("host.update.outcome", result == ASCIICHAT_OK ? "accepted" : "failed");
685 ASCII_OTEL_ATTR_INT("host.update.error_code", result);
686 if (result != ASCIICHAT_OK) {
687 acip_send_error(transport, result, "Host designation failed");
688 log_warn("Host designation failed: %s", asciichat_error_format(NULL, result));
689 return;
690 }
691 log_info("Session host updated via HOST_ANNOUNCEMENT from %s", client_ip);
692}
693
700static void acds_on_host_lost(const acip_host_lost_t *host_lost, acip_transport_t *transport, const char *client_ip, void *app_ctx) {
701 ASCII_OTEL_SCOPE(DISCOVERY_HOST_LOST);
702 acds_server_t *server = (acds_server_t *)app_ctx;
703
704 log_info("HOST_LOST from %s: session=%02x%02x..., participant=%02x%02x..., last_host=%02x%02x..., reason=%u", client_ip, host_lost->session_id[0], host_lost->session_id[1],
705 host_lost->participant_id[0], host_lost->participant_id[1], host_lost->last_host_id[0], host_lost->last_host_id[1], host_lost->disconnect_reason);
706
707 acds_client_data_t *client = transport ? transport->user_data : NULL;
708 if (!client || !client->joined_session || memcmp(client->session_id, host_lost->session_id, sizeof(client->session_id)) ||
709 memcmp(client->participant_id, host_lost->participant_id, sizeof(client->participant_id))) {
710 acip_send_error(transport, ERROR_NETWORK_PROTOCOL, "Host loss transport identity mismatch");
711 return;
712 }
713 mutex_lock(&server->handoff_mutex);
714 consensus_handoff_t *state = acds_handoff_find(server, host_lost->session_id, false);
715 if (state) {
716 consensus_handoff_host_lost(state, host_lost->last_host_id);
717 asciichat_error_t result = acds_handoff_tick(server, state);
718 if (result != ASCIICHAT_OK)
719 log_warn("Host loss recovery failed: %s", asciichat_error_format(NULL, result));
720 }
721 mutex_unlock(&server->handoff_mutex);
722}
723
724static consensus_handoff_t *acds_handoff_find(acds_server_t *server, const uint8_t session[SESSION_ID_SIZE], bool create) {
725 for (acds_handoff_entry_t *entry = server->handoffs; entry; entry = entry->next)
726 if (!memcmp(entry->state.session, session, SESSION_ID_SIZE))
727 return &entry->state;
728 if (!create)
729 return NULL;
731 if (!session_entry)
732 return NULL;
733 acds_handoff_entry_t *entry = SAFE_CALLOC(1, sizeof(*entry), acds_handoff_entry_t *);
736 entry->next = server->handoffs;
737 server->handoffs = entry;
738 return &entry->state;
739}
740// Replay authority after SESSION_JOINED, including after reconnect.
742 ASCII_OTEL_SCOPE(DISCOVERY_HOST_DESIGNATION);
743 ASCII_OTEL_ATTR_STRING("host.update.source", "replay");
744 ASCII_OTEL_ATTR_STRING("host.update.outcome", "unavailable");
745 mutex_lock(&server->handoff_mutex);
746 consensus_handoff_t *state = acds_handoff_find(server, id, true);
747 session_entry_t *stored = database_session_find_by_id(server->db, id);
748 if (state && stored && stored->host_established) {
749 ASCII_OTEL_ATTR_INT("host.generation", state->generation);
750 asciichat_error_t result = acds_send_designation(server, stored, state->generation, state->host_sequence, transport);
751 ASCII_OTEL_ATTR_STRING("host.update.outcome", result == ASCIICHAT_OK ? "admitted" : "failed");
752 ASCII_OTEL_ATTR_INT("host.update.error_code", result);
753 if (result != ASCIICHAT_OK)
754 log_warn("Could not replay host designation: %s", asciichat_error_format(NULL, result));
755 }
756 if (stored)
757 session_entry_destroy(stored);
758 mutex_unlock(&server->handoff_mutex);
759}
760
761static asciichat_error_t acds_handoff_broadcast(acds_server_t *server, consensus_handoff_message_t *message) {
763 consensus_handoff_encode(message, bytes);
764 log_info("Handoff action=%u generation=%u round=%u candidate=%02x%02x", message->kind, message->generation, message->sequence, message->participant[0], message->participant[1]);
765 return signaling_broadcast(server->db, server->network_server, message->session, (packet_type_t)CONSENSUS_HANDOFF_PACKET, bytes, sizeof(bytes), NULL);
766}
767static asciichat_error_t acds_handoff_tick(acds_server_t *server, consensus_handoff_t *state) {
769 if (!consensus_handoff_tick(state, time_get_ns() / NS_PER_MS_INT, &action))
770 return ASCIICHAT_OK;
771 ASCII_OTEL_SCOPE(DISCOVERY_HANDOFF);
772 if (action.kind == HANDOFF_COMMIT) {
774 if (result != ASCIICHAT_OK)
775 return result;
776 }
777 if (action.kind == HANDOFF_FAILED) {
779 if (result != ASCIICHAT_OK)
780 return result;
781 }
782 return acds_handoff_broadcast(server, &action);
783}
784static asciichat_error_t acds_on_handoff(const void *data, size_t length, acip_transport_t *transport, void *ctx) {
785 acds_server_t *server = ctx;
786 acds_client_data_t *client = transport ? transport->user_data : NULL;
788 asciichat_error_t result = consensus_handoff_decode(data, length, &message);
789 if (result != ASCIICHAT_OK)
790 return result;
791 if (!client || !client->joined_session || memcmp(client->session_id, message.session, SESSION_ID_SIZE) || memcmp(client->participant_id, message.participant, SESSION_ID_SIZE))
792 return SET_ERRNO(ERROR_NETWORK_PROTOCOL, "Handoff transport identity mismatch");
793 mutex_lock(&server->handoff_mutex);
794 consensus_handoff_t *state = acds_handoff_find(server, message.session, true);
795 if (!state) {
796 mutex_unlock(&server->handoff_mutex);
797 return SET_ERRNO(ERROR_INVALID_STATE, "No handoff session");
798 }
799 if ((message.kind == HANDOFF_READY || message.kind == HANDOFF_REJECT) &&
800 (message.generation != state->generation || message.sequence != state->round || memcmp(message.participant, state->successor, SESSION_ID_SIZE))) {
801 mutex_unlock(&server->handoff_mutex);
802 return ASCIICHAT_OK; // Membership changes can overtake a preparation acknowledgment.
803 }
804 result = consensus_handoff_join(state, message.participant);
805 if (result == ASCIICHAT_OK)
806 result = consensus_handoff_receive(state, &message, length, time_get_ns() / NS_PER_MS_INT);
807 if (result == ASCIICHAT_OK && message.kind == HANDOFF_READY && state->ready) {
808 message.kind = HANDOFF_PLAN;
809 result = acds_handoff_broadcast(server, &message);
810 }
811 if (result == ASCIICHAT_OK)
812 result = acds_handoff_tick(server, state);
813 mutex_unlock(&server->handoff_mutex);
814 return result;
815}
816
817// Global ACIP callback structure for ACDS
818static const acip_acds_callbacks_t g_acds_callbacks = {
819 .on_session_create = acds_on_session_create,
820 .on_session_lookup = acds_on_session_lookup,
821 .on_session_join = acds_on_session_join,
822 .on_session_leave = acds_on_session_leave,
823 .on_webrtc_sdp = acds_on_webrtc_sdp,
824 .on_webrtc_ice = acds_on_webrtc_ice,
825 .on_host_announcement = acds_on_host_announcement,
826 .on_host_announcement_ex = acds_on_host_announcement_ex,
827 .on_host_lost = acds_on_host_lost,
828 .on_handoff = acds_on_handoff,
829 .app_ctx = NULL // Set dynamically to server instance
830};
831
832static asciichat_error_t acds_connection_open(network_connection_t *connection, void *arg) {
833 acds_server_t *server = arg;
834 acds_client_data_t *client = SAFE_CALLOC(1, sizeof(*client), acds_client_data_t *);
835 if (!client)
836 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate discovery participant");
837 network_connection_set_context(connection, client);
838 client->transport = network_connection_transport(connection);
839 client->transport->user_data = client;
841 asciichat_error_t result = crypto_handshake_init("discovery", handshake, true);
842 if (result != ASCIICHAT_OK)
843 return result;
845 .handshake = handshake,
846 .initialized = true,
847 .secure = network_connection_secure(connection),
848 .require_auth = server->config.require_client_identity,
849 .require_encryption = GET_OPTION(encrypt_enabled),
850 .forbid_encryption = GET_OPTION(no_encrypt)};
855 memcpy(handshake->server_public_key.key, server->identity_public, sizeof(server->identity_public));
856 memcpy(handshake->server_private_key.key.ed25519, server->identity_secret, sizeof(server->identity_secret));
857 return ASCIICHAT_OK;
858}
859static asciichat_error_t acds_connection_packet(network_connection_t *connection, packet_type_t type, const void *payload, size_t size, void *arg) {
860 acds_server_t *server = arg;
862 acip_transport_t *transport = network_connection_transport(connection);
864 asciichat_error_t result = network_negotiation_receive(&client->negotiation, transport, type, payload, size);
865 if (result == ASCIICHAT_OK && client->negotiation.ready)
866 network_connection_ready(connection);
867 return result;
868 }
871 if (client->create_keys.count > 0 && type != PACKET_TYPE_ACIP_SESSION_CREATE && type != PACKET_TYPE_PING && type != PACKET_TYPE_PONG)
872 return acip_send_error(transport, ERROR_INVALID_PARAM, "Only SESSION_CREATE/PING/PONG allowed during session creation");
873 acip_acds_callbacks_t callbacks = g_acds_callbacks;
874 callbacks.app_ctx = server;
875 return acip_handle_acds_packet(transport, type, payload, size, network_connection_peer(connection), &callbacks);
876}
877static asciichat_error_t acds_connection_closing(network_connection_t *connection, void *arg) {
879 if (client && client->joined_session && acds_remove_client_from_session(arg, client) != ASCIICHAT_OK)
880 log_warn("Failed to remove disconnected discovery participant");
881 return ASCIICHAT_OK;
882}
883static void acds_connection_closed(network_connection_t *connection, void *arg) {
884 (void)arg;
886 if (!client)
887 return;
888 SAFE_FREE(client);
889 network_connection_set_context(connection, NULL);
890}
891const network_connection_callbacks_t acds_network_callbacks = {acds_connection_open, acds_connection_packet, acds_connection_closing, acds_connection_closed};
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)
ACIP client-side protocol library and ACDS client connection API.
#define ACDS_TRANSPORT_METADATA_MAX
asciichat_error_t acip_handle_acds_packet(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, const char *client_ip, const acip_acds_callbacks_t *callbacks)
ACDS packet handler callbacks.
ACIP Discovery Server (ACDS) packet handlers.
Application-level callbacks for library code.
#define APP_CALLBACK_VOID(callback_name)
const char * asciichat_error_format(const char *message, asciichat_error_t code)
#define SET_ERRNO(code,...)
uint64_t atomic_fetch_add_u64(atomic_t *a, uint64_t delta)
Atomically add to a uint64_t and return the previous value.
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
Application limits and constraints.
Hardware-Accelerated CRC32 Checksum Computation.
asciichat_error_t crypto_handshake_init(const char *name, crypto_handshake_context_t *ctx, bool is_server)
Initialize named crypto handshake context.
asciichat_error_t database_session_update_host(sqlite3 *db, const uint8_t session_id[16], const uint8_t host_participant_id[16], const char *host_address, uint16_t host_port, uint8_t connection_type)
Update session host (discovery mode).
asciichat_error_t database_session_create_keys_with_transport(sqlite3 *db, const acip_session_create_t *req, const uint8_t(*keys)[32], size_t count, const acds_config_t *config, acip_session_created_t *resp, const void *metadata, size_t metadata_length)
asciichat_error_t database_session_clear_host(sqlite3 *db, const uint8_t session_id[16])
Clear session host (discovery mode - host migration).
asciichat_error_t database_session_lookup(sqlite3 *db, const char *session_string, const acds_config_t *config, acip_session_info_t *resp)
Lookup session by string.
asciichat_error_t database_session_join(sqlite3 *db, const acip_session_join_t *req, const acds_config_t *config, acip_session_joined_t *resp)
Join existing session.
asciichat_error_t database_session_leave(sqlite3 *db, const uint8_t session_id[16], const uint8_t participant_id[16])
Leave session.
void database_close(sqlite3 *db)
Close database.
session_entry_t * database_session_find_by_id(sqlite3 *db, const uint8_t session_id[16])
Find session by session_id.
asciichat_error_t database_session_transport_get(sqlite3 *db, const uint8_t session_id[16], void *metadata, size_t capacity, size_t *length)
asciichat_error_t database_init(const char *db_path, sqlite3 **db)
Initialize database and create schema.
asciichat_error_t database_session_update_host_with_transport(sqlite3 *db, const uint8_t session[16], const uint8_t host[16], const char *address, uint16_t port, uint8_t type, const void *metadata, size_t length)
void database_session_cleanup_expired(sqlite3 *db)
Clean up inactive sessions.
🔄 Network byte order conversion helpers
#define HOST_TO_NET_U32(val)
Definition endian.h:70
#define NET_TO_HOST_U32(val)
Definition endian.h:85
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_CALLOC(count, size, cast)
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_NETWORK_PROTOCOL
Definition error_codes.h:80
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_RATE_LIMITED
Definition error_codes.h:84
@ ERROR_INVALID_PARAM
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
key_type_t type
Definition key_types.h:77
union private_key_t::@040247167361101132173265304166142033301213115260 key
@ KEY_TYPE_ED25519
Definition key_types.h:58
#define SESSION_ID_SIZE
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#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_join_t
Definition acds.h:408
acip_participant_joined_t
Definition acds.h:497
acip_session_joined_t
Definition acds.h:479
acip_session_lookup_t
Definition acds.h:309
acip_host_designated_t
Definition acds.h:937
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_participant_left_t
Definition acds.h:514
acip_session_create_t
Definition acds.h:226
acip_session_info_t
Definition acds.h:360
acip_session_leave_t
Definition acds.h:529
@ ACIP_CONNECTION_TYPE_TURN
TURN relay (fallback).
Definition acds.h:846
@ ACIP_CONNECTION_TYPE_STUN
STUN hole-punching.
Definition acds.h:845
@ SESSION_TYPE_DIRECT_TCP
Direct TCP connection to server IP:port (default).
Definition acds.h:150
#define NS_PER_MS_INT
Definition time.h:172
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
@ PACKET_TYPE_ACIP_PARTICIPANT_JOINED
Participant joined notification (ACDS -> Existing Participants).
Definition packet.h:507
@ PACKET_TYPE_PONG
Keepalive pong response.
Definition packet.h:423
@ PACKET_TYPE_ACIP_HOST_DESIGNATED
Host designated (ACDS -> All Participants).
Definition packet.h:497
@ PACKET_TYPE_ACIP_SESSION_CREATE
Create new session (Client -> Discovery Server).
Definition packet.h:445
@ PACKET_TYPE_ACIP_PARTICIPANT_LEFT
Participant left notification (ACDS -> Remaining Participants).
Definition packet.h:509
@ PACKET_TYPE_ACIP_SESSION_CREATED
Session created response (Discovery Server -> Client).
Definition packet.h:447
@ PACKET_TYPE_PING
Keepalive ping packet.
Definition packet.h:421
@ PACKET_TYPE_ACIP_SESSION_JOINED
Session joined response (Discovery Server -> Client).
Definition packet.h:455
#define GET_OPTION(field)
Definition options.h:1333
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
stun_server_t
Definition stun.h:78
turn_server_t
Definition turn.h:106
void consensus_handoff_leave(consensus_handoff_t *s, const uint8_t id[SESSION_ID_SIZE])
Definition handoff.c:77
void consensus_handoff_host_lost(consensus_handoff_t *s, const uint8_t host[SESSION_ID_SIZE])
Record loss of the incumbent, ignoring delayed reports about old hosts. The caller authenticates the ...
Definition handoff.c:103
void consensus_handoff_init(consensus_handoff_t *s, const uint8_t session[SESSION_ID_SIZE], const uint8_t host[SESSION_ID_SIZE])
Definition handoff.c:51
bool consensus_handoff_tick(consensus_handoff_t *s, uint64_t now, consensus_handoff_message_t *a)
Advance measured successor selection and bounded host-loss recovery. Fresh eligible peers prepare wit...
Definition handoff.c:194
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_join(consensus_handoff_t *s, const uint8_t id[SESSION_ID_SIZE])
Definition handoff.c:63
asciichat_error_t consensus_handoff_decode(const void *data, size_t length, consensus_handoff_message_t *m)
Definition handoff.c:16
asciichat_error_t consensus_handoff_receive(consensus_handoff_t *s, const consensus_handoff_message_t *m, size_t length, uint64_t now)
Accept a member's probe or preparation reply using receiver-clock time. Probe metadata becomes eligib...
Definition handoff.c:114
#define CONSENSUS_HANDOFF_PACKET
Definition handoff.h:13
#define CONSENSUS_HANDOFF_HEADER
Definition handoff.h:15
@ HANDOFF_REJECT
Definition handoff.h:28
@ HANDOFF_COMMIT
Definition handoff.h:27
@ HANDOFF_FAILED
Definition handoff.h:29
@ HANDOFF_PLAN
Definition handoff.h:26
@ HANDOFF_READY
Definition handoff.h:25
Server-side handshake functions.
struct session_entry session_entry_t
Persisted discovery-session record used to admit and route participants.
Transport abstraction layer for ACIP protocol.
struct network_connection network_connection_t
Network error handling utilities.
🌍 IP Address Parsing and Formatting Utilities
asciichat_error_t acds_create_key_set_collect(acds_create_key_set_t *set, const acip_session_create_t *req, bool require_identity, bool *complete)
Definition key_set.c:6
void session_entry_destroy(session_entry_t *entry)
Free a session entry and all its resources.
void network_connection_ready(network_connection_t *c)
network_connection_state_t network_connection_state(network_connection_t *c)
const char * network_connection_peer(network_connection_t *c)
void network_connection_set_context(network_connection_t *c, void *context)
void * network_connection_context(network_connection_t *c)
crypto_handshake_context_t * network_connection_handshake(network_connection_t *c)
bool network_connection_secure(network_connection_t *c)
acip_transport_t * network_connection_transport(network_connection_t *c)
deferred_action_t action
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
📝 Logging API with multiple log levels and terminal output control
asciichat_error_t network_negotiation_receive(network_negotiation_t *n, acip_transport_t *transport, packet_type_t type, const void *payload, size_t length)
@ NETWORK_PROTOCOL_DISCOVERY
Definition negotiation.h:9
🌐 Core network I/O operations with timeout support
#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 rate_limiter_record(rate_limiter_t *limiter, const char *ip_address, rate_event_type_t event_type)
Record a rate limit event.
Definition rate_limit.c:161
void rate_limiter_destroy(rate_limiter_t *limiter)
Destroy rate limiter and free resources.
Definition rate_limit.c:126
void rate_limiter_set_sqlite_db(rate_limiter_t *limiter, void *db)
Set SQLite database handle for rate limiter.
Definition rate_limit.c:117
rate_limiter_t * rate_limiter_create_sqlite(const char *db_path)
Create SQLite-backed rate limiter.
Definition rate_limit.c:100
asciichat_error_t rate_limiter_check(rate_limiter_t *limiter, const char *ip_address, rate_event_type_t event_type, const rate_limit_config_t *config, bool *allowed)
Check if an event from an IP address should be rate limited.
Definition rate_limit.c:138
asciichat_error_t rate_limiter_prune(rate_limiter_t *limiter, uint32_t max_age_secs)
Clean up old rate limit events.
Definition rate_limit.c:177
🚦 Rate limiting API with pluggable backends
@ RATE_EVENT_SESSION_LOOKUP
Session lookup.
Definition rate_limit.h:55
@ RATE_EVENT_SESSION_JOIN
Session join.
Definition rate_limit.h:56
@ RATE_EVENT_SESSION_CREATE
Session creation.
Definition rate_limit.h:54
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:78
asciichat_error_t acip_send_session_joined(acip_transport_t *transport, const acip_session_joined_t *response)
Send SESSION_JOINED response packet.
Definition send.c:497
asciichat_error_t acip_send_error(acip_transport_t *transport, uint32_t error_code, const char *message)
Send error message packet.
Definition send.c:402
asciichat_error_t acip_send_session_info(acip_transport_t *transport, const acip_session_info_t *info)
Send SESSION_INFO response packet.
Definition send.c:489
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.
network_server_t * session_server_like_get_network_server(void)
asciichat_error_t signaling_relay_ice(sqlite3 *db, network_server_t *network_server, const acip_webrtc_ice_t *ice, size_t total_packet_len)
Relay ICE candidate to recipient.
Definition signaling.c:174
asciichat_error_t signaling_relay_sdp(sqlite3 *db, network_server_t *network_server, const acip_webrtc_sdp_t *sdp, size_t total_packet_len)
Relay SDP offer/answer to recipient.
Definition signaling.c:132
asciichat_error_t signaling_broadcast(sqlite3 *db, network_server_t *network_server, const uint8_t session_id[SESSION_ID_SIZE], packet_type_t packet_type, const void *packet, size_t packet_len, const uint8_t *exclude_participant_id)
Broadcast packet to all session participants.
Definition signaling.c:213
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37
💾 SQLite rate limiting backend interface
uint8_t session_id[SESSION_ID_SIZE]
uint8_t participant_id[SESSION_ID_SIZE]
void acds_on_host_announcement(const acip_host_announcement_t *announcement, acip_transport_t *transport, const char *client_ip, void *app_ctx)
#define DISCOVERY_SERVICE_SERVER_SESSION_STRING_BUFFER_SIZE
const network_connection_callbacks_t acds_network_callbacks
void acds_server_shutdown(acds_server_t *server)
Shutdown discovery server.
void acds_send_current_host(acds_server_t *server, acip_transport_t *transport, const uint8_t id[SESSION_ID_SIZE])
asciichat_error_t acds_server_init(acds_server_t *server, const acds_config_t *config)
acds server is intentionally a small, concrete record. Fields such as network_server,...
struct acds_handoff_entry acds_handoff_entry_t
Background thread for periodic cleanup.
void acds_on_host_announcement_ex(const acip_host_announcement_t *announcement, const void *metadata, size_t metadata_length, acip_transport_t *transport, const char *client_ip, void *app_ctx)
🔤 String Manipulation and Shell Escaping Utilities
Network statistics for both TCP and WebSocket connections.
network_negotiation_t negotiation
acds_create_key_set_t create_keys
Pending connection-local key set.
bool joined_session
Whether client has successfully joined a session.
uint8_t participant_id[SESSION_ID_SIZE]
Participant UUID (valid if joined_session).
acip_transport_t * transport
Persistent transport for this client connection.
uint8_t session_id[SESSION_ID_SIZE]
Session UUID (valid if joined_session).
bool session_established
True after SESSION_CREATE/SESSION_JOIN completes; handler exits loop.
Discovery server configuration.
char database_path[512]
SQLite database path.
bool require_server_identity
Require servers to provide signed identity when creating sessions.
stun_server_t stun_servers[MAX_CONFIGURED_STUN_SERVERS]
STUN server configurations.
bool require_client_identity
Require clients to provide signed identity when joining sessions.
turn_server_t turn_servers[MAX_CONFIGURED_TURN_SERVERS]
TURN server configurations.
Background thread for periodic cleanup.
struct acds_handoff_entry * next
consensus_handoff_t state
Discovery server state.
uint8_t identity_secret[ED25519_PRIVATE_KEY_SIZE]
Ed25519 secret key.
acds_config_t config
Runtime configuration.
atomic_t shutdown
Shutdown flag for worker threads.
uint8_t identity_public[ED25519_PUBLIC_KEY_SIZE]
Ed25519 public key.
bool handoff_mutex_initialized
Whether shutdown owns the handoff mutex.
struct acds_handoff_entry * handoffs
sqlite3 * db
SQLite database handle.
network_server_t * network_server
Network runtime owned by server_like.
acds_stats_t stats
Network statistics for all connections.
struct rate_limiter_s * rate_limiter
SQLite-backed rate limiter.
thread_pool_t * worker_pool
Thread pool for background workers.
atomic_t packets_received
Total packets received (TCP + WebSocket).
atomic_t packets_sent
Total packets sent (TCP + WebSocket).
atomic_t bytes_sent
Total bytes sent (TCP + WebSocket).
atomic_t bytes_received
Total bytes received (TCP + WebSocket).
time_t start_time
Server start time.
ACDS packet handler callbacks.
void * app_ctx
Application context (passed to all callbacks).
void * user_data
Application-specific context (e.g., per-client data).
uint8_t session[SESSION_ID_SIZE]
Definition handoff.h:35
uint8_t participant[SESSION_ID_SIZE]
Definition handoff.h:36
uint32_t host_sequence
Last committed round; preparation does not change host authority.
Definition handoff.h:78
uint8_t session[SESSION_ID_SIZE]
Definition handoff.h:73
uint8_t successor[SESSION_ID_SIZE]
Definition handoff.h:75
uint32_t generation
Definition handoff.h:76
uint8_t host[SESSION_ID_SIZE]
Definition handoff.h:74
Cryptographic handshake context structure.
bool allow_unlisted_client_identity
Require proof of key possession without whitelist membership (discovery).
Callbacks and operations used by network connection callbacks. Packet payloads are borrowed until ret...
When code needs to work with network negotiation, it keeps protocol, handshake, identity_keys,...
Definition negotiation.h:18
Fixed prefix shared by every ACIP packet on the wire.
Definition packet.h:641
Persisted discovery-session record used to admit and route participants.
bool expose_ip_publicly
Allow IP disclosure without verification (explicit opt-in via –acds-expose-ip).
bool has_password
Password protection flag.
char host_address[ACIP_ADDRESS_SIZE]
uint8_t initiator_id[16]
First participant who created/joined the session.
uint16_t host_port
Host's port (valid if host_established).
uint8_t host_participant_id[16]
Current host's participant_id (valid if host_established).
bool host_established
Whether a host has been designated (false = still negotiating).
uint8_t session_id[16]
UUID.
uint8_t current_participants
Active participant count.
uint8_t host_connection_type
acip_connection_type_t: how to reach host
void thread_pool_destroy(thread_pool_t *pool)
Destroy a thread pool.
thread_pool_t * thread_pool_create(const char *pool_name)
Create a new thread pool (long-lived threads mode).
Definition thread_pool.c:92
asciichat_error_t thread_pool_spawn(thread_pool_t *pool, void *(*thread_func)(void *), void *thread_arg, int stop_id, const char *thread_name)
Spawn a worker thread in the pool.
⏱️ High-precision timing utilities using sokol_time.h and uthash