ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
server/main.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define SERVER_MAIN_SESSION_STRING_BUFFER_SIZE 64
4#define SERVER_MAIN_HEX_BUFFER_SIZE 64
5#define SERVER_MAIN_ASCII_BUFFER_SIZE 20
6#define SERVER_MAIN_PARTICIPANT_BUFFER_SIZE 33
7#define SERVER_MAIN_SESSION_NAME_BUFFER_SIZE 56
8#define SERVER_MAIN_TXT_SESSION_STRING_BUFFER_SIZE 512
9#define SERVER_MAIN_TXT_HOST_PUBKEY_BUFFER_SIZE 512
10#define SERVER_MAIN_LABEL_BUFFER_SIZE 64
11#define SERVER_MAIN_TURN_AUTH_USERNAME_BUFFER_SIZE 128
12#define SERVER_MAIN_TURN_AUTH_CREDENTIAL_BUFFER_SIZE 128
13
70
73
74#ifdef _WIN32
75#include <io.h>
76#else
77#include <unistd.h> // For write(), STDERR_FILENO (signal handler), dup(), dup2()
78#include <fcntl.h> // For open() and O_WRONLY
79#endif
80
81#include <ascii-chat/network/platform.h> // Consolidates platform-specific network headers
84
85#include <errno.h>
86#include <limits.h>
87#include <signal.h>
88#include <stdbool.h>
89#include <stdio.h>
90#include <stdlib.h>
91#include <stdint.h>
92#include <string.h>
93#include <sys/types.h>
94#include <sys/stat.h>
95#include <time.h>
96
97#include "main.h"
98#include "../main.h" // For should_exit() and signal_exit() API
100#include "connections.h"
101#include <ascii-chat/common.h>
103#include <ascii-chat/util/ip.h>
104#include <ascii-chat/util/time.h>
105#include <libplatform/lifecycle.h>
106#include <ascii-chat/uthash.h>
107#include <libplatform/compiler.h>
108#include <libplatform/system.h>
109#include <libplatform/terminal.h>
110#include <libplatform/socket.h>
112#include <libplatform/question.h>
113#include <libplatform/terminal.h>
124#include <options/options.h>
125#include <options/rcu.h> // For RCU-based options access
126#include <ascii-chat/buffer.h>
129#include "session/h265/server.h"
130#include "client.h"
131#include "stream.h"
132#include "stats.h"
135#include <libplatform/symbols.h>
136#include <libplatform/system.h>
156#include <ascii-chat/log/json.h>
157#include <libplatform/keyboard.h>
160#include <libplatform/atomic.h>
161
162/* ============================================================================
163 * Global State
164 * ============================================================================
165 */
166
181
189static bool check_shutdown(void) {
190 return should_exit();
191}
192
204mixer_t *volatile g_audio_mixer = NULL;
205
217
226
247
248// TCP server is now owned by session_server_like; access via session_server_like_get_network_server().
249
250// WebSocket server is now owned by session_server_like; access via session_server_like_get_websocket_server().
251
258static time_t g_server_start_time = 0;
259
260// Status screen thread, keyboard thread, and SPSC queue are now owned by session_server_like.
261
268static char g_session_string[SERVER_MAIN_SESSION_STRING_BUFFER_SIZE] = {0};
269
273static bool g_session_is_mdns_only = false;
274
275// UPnP and mDNS contexts are now owned by session_server_like; access via accessors.
276
286static acds_client_t *g_acds_client = NULL;
287
296static acip_transport_t *g_acds_transport = NULL;
297
304static uint8_t g_server_participant_id[SESSION_ID_SIZE] = {0};
305static uint8_t g_server_session_id[SESSION_ID_SIZE] = {0};
306
316static webrtc_peer_manager_t *g_webrtc_peer_manager = NULL;
317
327static platform_thread_t g_acds_receive_thread;
328
336static bool g_acds_receive_thread_started = false;
337
347static platform_thread_t g_acds_ping_thread;
348
356static bool g_acds_ping_thread_started = false;
357
364static thread_pool_t *g_server_worker_pool = NULL;
365
366/* ============================================================================
367 * Server Crypto State
368 * ============================================================================
369 */
370
382
395
408
418
431
441
442/* ============================================================================
443 * Signal Handlers
444 * ============================================================================
445 */
446
488static void server_handle_sigint(int sig) {
489 (void)sig;
490 // If in grep input mode, cancel grep instead of shutting down.
491 // Uses atomic reads only (no mutex) - safe from signal context.
494 return;
495 }
496
497 static atomic_t sigint_count = {0};
498 int count = atomic_fetch_add_int(&sigint_count, 1) + 1;
499 if (count > 1) {
501 }
502
503 // STEP 1: Set atomic shutdown flag (checked by all worker threads)
505
506 // STEP 2: Use raw write() for user feedback (async-signal-safe).
507 // log_info_nofile() is NOT safe here - it calls SAFE_MALLOC (via ansi_strip_escapes),
508 // SAFE_FREE, and server_like_status_log_append (mutex). If the signal interrupts a thread
509 // holding the memory tracking lock or log buffer lock, the handler deadlocks.
510 // Since SIGINT auto-masks during handler execution, a second Ctrl+C would be
511 // blocked, preventing platform_force_exit() from ever running.
512 // INFO: commented out because it's too noisy, uncomment to debug
513 // static const char sigint_msg[] = "SIGINT received - shutting down server...\n";
514 // platform_write_all(STDERR_FILENO, sigint_msg, sizeof(sigint_msg) - 1);
515
517
518 // STEP 4: DO NOT access client data structures in signal handler
519 // Signal handlers CANNOT safely use mutexes, rwlocks, or access complex data structures
520 // This causes deadlocks and memory access violations because:
521 // 1. Signal may interrupt a thread that already holds these locks
522 // 2. Attempting to acquire locks in signal handler = instant deadlock
523 // 3. Client array might be in an inconsistent state during modification
524 //
525 // SOLUTION: The listening socket closure above is sufficient to unblock accept_with_timeout()
526 // The main thread will detect g_should_exit and properly close client sockets with timeouts
527
528 // NOTE: Do NOT call log_destroy() here - it's not async-signal-safe
529 // The main thread will handle cleanup when it detects g_should_exit
530}
531
532/* ============================================================================
533 * WebRTC Callbacks
534 * ============================================================================
535 */
536
550static asciichat_error_t server_send_sdp(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) {
551 (void)user_data;
552
553 if (!g_acds_transport) {
554 return SET_ERRNO(ERROR_INVALID_STATE, "ACDS transport not available for SDP relay");
555 }
556
557 // Calculate SDP length
558 size_t sdp_len = strlen(sdp);
559 if (sdp_len == 0 || sdp_len >= 8192) {
560 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid SDP length: %zu", sdp_len);
561 }
562
563 // Allocate packet buffer (header + SDP string)
564 size_t total_len = sizeof(acip_webrtc_sdp_t) + sdp_len;
565 uint8_t *packet = SAFE_MALLOC(total_len, uint8_t *);
566 if (!packet) {
567 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate SDP packet");
568 }
569
570 // Fill header
571 acip_webrtc_sdp_t *header = (acip_webrtc_sdp_t *)packet;
572 memcpy(header->session_id, session_id, SESSION_ID_SIZE);
573 // Use server's participant_id from SESSION_JOIN as sender
574 memcpy(header->sender_id, g_server_participant_id, SESSION_ID_SIZE);
575 memcpy(header->recipient_id, recipient_id, SESSION_ID_SIZE);
576 header->sdp_type = (strcmp(sdp_type, "offer") == 0) ? 0 : 1;
577 header->sdp_len = HOST_TO_NET_U16((uint16_t)sdp_len);
578
579 // Copy SDP string after header (binary data, not null-terminated)
580 // NOLINTNEXTLINE(bugprone-not-null-terminated-result)
581 memcpy(packet + sizeof(acip_webrtc_sdp_t), sdp, sdp_len);
582
583 log_debug("Server sending WebRTC SDP %s to participant (sender=%02x%02x..., recipient=%02x%02x...) via ACDS", sdp_type, g_server_participant_id[0], g_server_participant_id[1], recipient_id[0],
584 recipient_id[1]);
585
586 // Send via ACDS transport using generic packet sender
587 asciichat_error_t result = packet_send_via_transport(g_acds_transport, PACKET_TYPE_ACIP_WEBRTC_SDP, packet, total_len, 0);
588
589 SAFE_FREE(packet);
590
591 if (result != ASCIICHAT_OK) {
592 return SET_ERRNO(result, "Failed to send SDP via ACDS");
593 }
594
595 return ASCIICHAT_OK;
596}
597
611static asciichat_error_t server_send_ice(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) {
612 (void)user_data;
613
614 if (!g_acds_transport) {
615 return SET_ERRNO(ERROR_INVALID_STATE, "ACDS transport not available for ICE relay");
616 }
617
618 // Calculate payload length (candidate + null + mid + null)
619 size_t candidate_len = strlen(candidate);
620 size_t mid_len = strlen(mid);
621 size_t payload_len = candidate_len + 1 + mid_len + 1;
622
623 if (payload_len >= 8192) {
624 return SET_ERRNO(ERROR_INVALID_PARAM, "ICE payload too large: %zu", payload_len);
625 }
626
627 // Allocate packet buffer (header + payload)
628 size_t total_len = sizeof(acip_webrtc_ice_t) + payload_len;
629 uint8_t *packet = SAFE_MALLOC(total_len, uint8_t *);
630 if (!packet) {
631 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate ICE packet");
632 }
633
634 // Fill header
635 acip_webrtc_ice_t *header = (acip_webrtc_ice_t *)packet;
636 memcpy(header->session_id, session_id, SESSION_ID_SIZE);
637 // Use server's participant_id from SESSION_JOIN as sender
638 memcpy(header->sender_id, g_server_participant_id, SESSION_ID_SIZE);
639 memcpy(header->recipient_id, recipient_id, SESSION_ID_SIZE);
640 header->candidate_len = HOST_TO_NET_U16((uint16_t)candidate_len); // FIXED: Use candidate length, not total payload
641
642 // Copy candidate and mid after header
643 uint8_t *payload = packet + sizeof(acip_webrtc_ice_t);
644 memcpy(payload, candidate, candidate_len);
645 payload[candidate_len] = '\0';
646 memcpy(payload + candidate_len + 1, mid, mid_len);
647 payload[candidate_len + 1 + mid_len] = '\0';
648
649 log_debug("Server sending WebRTC ICE candidate to participant (%.8s..., mid=%s) via ACDS", (const char *)recipient_id, mid);
650 log_debug(" [2] Before ACDS send - candidate: '%s' (len=%zu)", candidate, strlen(candidate));
651 log_debug(" [2] Before ACDS send - mid: '%s' (len=%zu)", mid, strlen(mid));
652 log_debug(" [2] Before ACDS send - payload_len=%zu, header.candidate_len=%u", payload_len, NET_TO_HOST_U16(header->candidate_len));
653
654 // Hex dump payload for debugging
655 log_debug(" [2] Hex dump of payload being sent (first 100 bytes):");
656 for (size_t i = 0; i < 100 && i < payload_len; i += 16) {
657 char hex[SERVER_MAIN_HEX_BUFFER_SIZE] = {0};
658 char ascii[SERVER_MAIN_ASCII_BUFFER_SIZE] = {0};
659 for (size_t j = 0; j < 16 && (i + j) < 100 && (i + j) < payload_len; j++) {
660 snprintf(hex + j * 3, sizeof(hex) - j * 3, "%02x ", payload[i + j]);
661 ascii[j] = (payload[i + j] >= 32 && payload[i + j] < 127) ? payload[i + j] : '.';
662 }
663 log_debug(" [%04zx] %-48s %s", i, hex, ascii);
664 }
665
666 // Send via ACDS transport using generic packet sender
667 asciichat_error_t result = packet_send_via_transport(g_acds_transport, PACKET_TYPE_ACIP_WEBRTC_ICE, packet, total_len, 0);
668
669 SAFE_FREE(packet);
670
671 if (result != ASCIICHAT_OK) {
672 return SET_ERRNO(result, "Failed to send ICE via ACDS");
673 }
674
675 return ASCIICHAT_OK;
676}
677
688static void on_webrtc_transport_ready(acip_transport_t *transport, const uint8_t participant_id[SESSION_ID_SIZE], void *user_data) {
689 server_context_t *server_ctx = (server_context_t *)user_data;
690 if (!transport || !participant_id || !server_ctx) {
691 log_error("Invalid parameters");
692 if (transport) {
693 acip_transport_destroy(transport);
694 }
695 return;
696 }
697
698 log_debug("WebRTC transport ready for participant %.8s...", (const char *)participant_id);
699
700 // Convert participant_id to string for logging (ASCII-safe portion)
701 char participant_str[SERVER_MAIN_PARTICIPANT_BUFFER_SIZE];
702 for (int i = 0; i < 16; i++) {
703 safe_snprintf(participant_str + (i * 2), 3, "%02x", participant_id[i]);
704 }
705 participant_str[32] = '\0';
706
707 asciichat_error_t result = network_server_adopt(server_ctx->network_server, transport, participant_str, true);
708 if (result != ASCIICHAT_OK) {
709 log_error("Cannot adopt authenticated peer: %s", asciichat_error_format(NULL, result));
710 acip_transport_destroy(transport);
711 } else {
712 log_info("Authenticated WebRTC connection adopted for %s", participant_str);
713 }
714}
715
726static void on_webrtc_sdp_server(const acip_webrtc_sdp_t *sdp, size_t total_len, void *ctx) {
727 (void)ctx;
728
729 if (!sdp || !g_webrtc_peer_manager) {
730 log_error("Invalid parameters or peer_manager not initialized");
731 return;
732 }
733
734 // Validate packet length
735 uint16_t sdp_len = NET_TO_HOST_U16(sdp->sdp_len);
736 if (total_len < sizeof(acip_webrtc_sdp_t) + sdp_len) {
737 log_error("Invalid packet length (total=%zu, expected>=%zu)", total_len, sizeof(acip_webrtc_sdp_t) + sdp_len);
738 return;
739 }
740
741 // Determine SDP type (offer=0, answer=1)
742 const char *sdp_type = (sdp->sdp_type == 0) ? "offer" : "answer";
743
744 log_debug("Received WebRTC SDP %s from participant %.8s... (len=%u)", sdp_type, (const char *)sdp->sender_id, sdp_len);
745
746 // Forward to peer_manager (pass full packet structure)
747 asciichat_error_t result = webrtc_peer_manager_handle_sdp(g_webrtc_peer_manager, sdp);
748
749 if (result != ASCIICHAT_OK) {
750 log_error("Failed to handle remote SDP from participant %.8s...: %s", (const char *)sdp->sender_id, asciichat_error_format(NULL, result));
751 }
752}
753
764static void on_webrtc_ice_server(const acip_webrtc_ice_t *ice, size_t total_len, void *ctx) {
765 (void)ctx;
766
767 if (!ice || !g_webrtc_peer_manager) {
768 log_error("Invalid parameters or peer_manager not initialized");
769 return;
770 }
771
772 // Validate packet length
773 uint16_t payload_len = NET_TO_HOST_U16(ice->candidate_len);
774 if (total_len < sizeof(acip_webrtc_ice_t) + payload_len) {
775 log_error("Invalid packet length (total=%zu, expected>=%zu)", total_len, sizeof(acip_webrtc_ice_t) + payload_len);
776 return;
777 }
778
779 log_debug("Received WebRTC ICE candidate from participant %02x%02x%02x%02x...", ice->sender_id[0], ice->sender_id[1], ice->sender_id[2], ice->sender_id[3]);
780
781 // Forward to peer_manager (pass full packet structure)
782 asciichat_error_t result = webrtc_peer_manager_handle_ice(g_webrtc_peer_manager, ice);
783
784 if (result != ASCIICHAT_OK) {
785 log_error("Failed to handle remote ICE candidate from participant %02x%02x%02x%02x...: %s", ice->sender_id[0], ice->sender_id[1], ice->sender_id[2], ice->sender_id[3],
786 asciichat_error_format(NULL, result));
787 }
788}
789
799static void __attribute__((unused)) advertise_mdns_with_session(const char *session_string, uint16_t port) {
801 if (!mdns_ctx) {
802 log_debug("mDNS context not initialized, skipping advertisement");
803 return;
804 }
805
806 // Build session name from hostname for mDNS service name
807 char hostname[HOSTNAME_BUFFER_SIZE] = {0};
808 // Reserve the service label suffix for the port used by the mDNS backend.
809 char session_name[SERVER_MAIN_SESSION_NAME_BUFFER_SIZE] = "ascii-chat-Server";
810 if (gethostname(hostname, sizeof(hostname) - 1) == 0 && strlen(hostname) > 0) {
811 safe_snprintf(session_name, sizeof(session_name), "%s", hostname);
812 }
813
814 // Prepare TXT records with session string and host public key
815 char txt_session_string[SERVER_MAIN_TXT_SESSION_STRING_BUFFER_SIZE];
816 char txt_host_pubkey[SERVER_MAIN_TXT_HOST_PUBKEY_BUFFER_SIZE];
817 const char *txt_records[2];
818 int txt_count = 0;
819
820 // Add session string to TXT records (for client discovery)
821 safe_snprintf(txt_session_string, sizeof(txt_session_string), "session_string=%s", session_string);
822 txt_records[txt_count++] = txt_session_string;
823
824 // Add host public key to TXT records (for cryptographic verification)
825 // Convert server's Ed25519 public key to hex format
827 char hex_pubkey[HEX_STRING_SIZE_32];
828 pubkey_to_hex(g_server_private_key.public_key, hex_pubkey);
829 safe_snprintf(txt_host_pubkey, sizeof(txt_host_pubkey), "host_pubkey=%s", hex_pubkey);
830 txt_records[txt_count++] = txt_host_pubkey;
831 log_debug("mDNS: Host pubkey=%s", hex_pubkey);
832 } else {
833 // If encryption is disabled, still advertise a zero pubkey for clients to detect
834 safe_snprintf(txt_host_pubkey, sizeof(txt_host_pubkey), "host_pubkey=");
835 for (int i = 0; i < 32; i++) {
836 safe_snprintf(txt_host_pubkey + strlen(txt_host_pubkey), sizeof(txt_host_pubkey) - strlen(txt_host_pubkey), "00");
837 }
838 txt_records[txt_count++] = txt_host_pubkey;
839 log_debug("mDNS: Encryption disabled, advertising zero pubkey");
840 }
841
842 asciichat_mdns_service_t service = {
843 .name = session_name,
844 .type = "_ascii-chat._tcp",
845 .host = hostname,
846 .port = port,
847 .txt_records = txt_records,
848 .txt_count = txt_count,
849 };
850
851 asciichat_error_t mdns_advertise_result = asciichat_mdns_advertise(mdns_ctx, &service);
852 if (mdns_advertise_result != ASCIICHAT_OK) {
853 LOG_ERRNO_IF_SET("Failed to advertise mDNS service");
854 log_warn("mDNS advertising failed - LAN discovery disabled");
855 } else {
856 log_info("🌐 mDNS: Server advertised as '%s.local' on LAN", session_name);
857 log_debug("mDNS: Service advertised as '%s.local' (name=%s, port=%d, session=%s, txt_count=%d)", service.type, service.name, service.port, session_string, service.txt_count);
858 }
859}
860
869static asciichat_error_t acds_send_host_sample(uint32_t sequence) {
870 consensus_handoff_message_t message = {.kind = HANDOFF_SAMPLE_START, .sequence = sequence, .capabilities = 0, .nat_tier = 255, .port = (uint16_t)GET_OPTION(port)};
871 memcpy(message.session, g_server_session_id, SESSION_ID_SIZE);
872 memcpy(message.participant, g_server_participant_id, SESSION_ID_SIZE);
874 uint8_t *bytes = SAFE_CALLOC(1, length, uint8_t *);
875 if (!bytes)
876 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate discovery host sample");
877 consensus_handoff_encode(&message, bytes);
879 if (result == ASCIICHAT_OK) {
880 message.kind = HANDOFF_SAMPLE_DATA;
881 consensus_handoff_encode(&message, bytes);
882 result = packet_send_via_transport(g_acds_transport, (packet_type_t)CONSENSUS_HANDOFF_PACKET, bytes, length, 0);
883 }
884 SAFE_FREE(bytes);
885 return result;
886}
887
888static void *acds_ping_thread(void *arg) {
889 (void)arg;
890
891 log_debug("ACDS keepalive ping thread started");
892
893 uint32_t sequence = 0, tick = 0;
895 if (!g_acds_transport) {
896 log_debug("ACDS transport destroyed, exiting ping thread");
897 break;
898 }
899
900 // Send a host health sample every five seconds and PING every ten seconds.
901 ++tick;
902 if (acip_transport_is_connected(g_acds_transport)) {
903 if (memcmp(g_server_participant_id, (uint8_t[SESSION_ID_SIZE]){0}, SESSION_ID_SIZE) != 0) {
904 asciichat_error_t sample_result = acds_send_host_sample(++sequence);
905 if (sample_result != ASCIICHAT_OK)
906 log_warn("ACDS host sample failed: %s", asciichat_error_format(NULL, sample_result));
907 }
908 if (tick % 2 == 1) {
909 asciichat_error_t ping_result = packet_send_via_transport(g_acds_transport, PACKET_TYPE_PING, NULL, 0, 0);
910 if (ping_result != ASCIICHAT_OK)
911 log_warn("ACDS keepalive: Failed to send PING: %s", asciichat_error_format(NULL, ping_result));
912 }
913 }
914
915 for (int i = 0; i < 50 && !atomic_load_bool(&g_should_exit); i++) {
916 APP_CALLBACK_VOID(platform_pump_events);
917 platform_sleep_ms(100); // Check exit flag every 100ms
918 }
919 }
920
921 log_debug("ACDS keepalive ping thread exiting");
922 return NULL;
923}
924
937static void on_acds_ping(void *ctx) {
938 (void)ctx;
939 log_debug("ACDS keepalive: Received PING from ACDS, responding with PONG");
940 if (g_acds_transport) {
941 packet_send_via_transport(g_acds_transport, PACKET_TYPE_PONG, NULL, 0, 0);
942 }
943}
944
948static void on_acds_pong(void *ctx) {
949 (void)ctx;
950 log_debug("ACDS keepalive: Received PONG from ACDS server");
951}
952
953static asciichat_error_t acds_signaling_packet(network_connection_t *connection, packet_type_t type, const void *payload, size_t length, void *arg) {
954 (void)arg;
955 if ((unsigned)type == CONSENSUS_HANDOFF_PACKET) {
957 return consensus_handoff_decode(payload, length, &message);
958 }
959 const acip_client_callbacks_t callbacks = {.on_webrtc_sdp = on_webrtc_sdp_server, .on_webrtc_ice = on_webrtc_ice_server, .on_ping = on_acds_ping, .on_pong = on_acds_pong};
960 return acip_handle_client_packet(network_connection_transport(connection), type, payload, length, &callbacks);
961}
962static void *acds_receive_thread(void *arg) {
963 (void)arg;
964 const network_connection_callbacks_t callbacks = {.packet = acds_signaling_packet};
965 asciichat_error_t result = network_connection_run(g_acds_client->connection, &callbacks, NULL);
966 if (result != ASCIICHAT_OK && !atomic_load_bool(&g_should_exit))
967 log_warn("Discovery signaling connection stopped: %s", asciichat_error_format(NULL, result));
968 return NULL;
969}
970
971/* ============================================================================
972 * Signal Handlers
973 * ============================================================================
974 */
975
976// SIGTERM handling is now done by session_server_like (both SIGINT and SIGTERM call interrupt_fn).
977// WebSocket server thread wrapper and status screen thread are now in session_server_like.
978
979/* ============================================================================
980 * Discovery signaling callbacks
981 * ============================================================================
982 */
983
993
994/* ============================================================================
995 * Main Function
996 * ============================================================================
997 */
998
1054
1060static int init_server_crypto(void) {
1061 // Load server identity keys (supports multiple --key flags for multi-key mode)
1062 size_t num_keys = GET_OPTION(num_identity_keys);
1063
1064 if (num_keys > 0) {
1065 // Multi-key mode: load all identity keys from identity_keys[] array
1066 log_info("Loading %zu identity key(s) for multi-key support...", num_keys);
1067
1068 for (size_t i = 0; i < num_keys && i < MAX_SESSION_KEYS; i++) {
1069 const char *key_path = GET_OPTION(identity_keys[i]);
1070
1071 if (strlen(key_path) == 0) {
1072 continue; // Skip empty entries
1073 }
1074
1075 // Validate SSH key file (skip validation for special prefixes)
1076 bool is_special_key = (strncmp(key_path, "gpg:", 4) == 0 || strncmp(key_path, "github:", 7) == 0 || strncmp(key_path, "gitlab:", 7) == 0);
1077
1078 if (!is_special_key) {
1079 if (validate_ssh_key_file(key_path) != 0) {
1080 log_warn("Skipping invalid SSH key file: %s", key_path);
1081 continue;
1082 }
1083 }
1084
1085 // Parse key (handles SSH files and gpg: prefix, rejects github:/gitlab:)
1086 log_debug("Loading identity key #%zu: %s", i + 1, key_path);
1088 log_debug("Successfully loaded identity key #%zu: %s", i + 1, key_path);
1089
1090 // Display key fingerprint for verification
1091 char hex_pubkey[HEX_STRING_SIZE_32];
1093 log_debug(" Key fingerprint: %s", hex_pubkey);
1094
1096 } else {
1097 log_warn("Failed to parse identity key #%zu: %s (skipping)", i + 1, key_path);
1098 }
1099 }
1100
1101 if (g_num_server_identity_keys == 0) {
1102 NOTICE(DANGER, "NO VALID IDENTITY KEYS", "No valid identity keys loaded despite %zu --key flag(s)", num_keys);
1103 SET_ERRNO(ERROR_CRYPTO_KEY, "No valid identity keys loaded");
1104 return -1;
1105 }
1106
1107 // Copy first key to g_server_private_key for backward compatibility
1109 log_info("Loaded %zu identity key(s) total", g_num_server_identity_keys);
1110
1111 } else if (strlen(GET_OPTION(encrypt_key)) > 0) {
1112 // Single-key mode (backward compatibility): load from encrypt_key field
1113 const char *key_path = GET_OPTION(encrypt_key);
1114
1115 // Validate SSH key file (skip validation for special prefixes)
1116 bool is_special_key = (strncmp(key_path, "gpg:", 4) == 0 || strncmp(key_path, "github:", 7) == 0 || strncmp(key_path, "gitlab:", 7) == 0);
1117
1118 if (!is_special_key) {
1119 if (validate_ssh_key_file(key_path) != 0) {
1120 SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid SSH key file: %s", key_path);
1121 return -1;
1122 }
1123 }
1124
1125 // Parse key
1126 log_info("Loading key for authentication: %s", key_path);
1128 log_info("Successfully loaded server key: %s", key_path);
1129
1130 // Also store in identity_keys array for consistency
1133 } else {
1134 log_error("Failed to parse key: %s\n"
1135 "This may be due to:\n"
1136 " - Wrong password for encrypted key\n"
1137 " - Unsupported key type (only Ed25519 is currently supported)\n"
1138 " - Corrupted key file\n"
1139 "\n"
1140 "Note: RSA and ECDSA keys are not yet supported\n"
1141 "To generate an Ed25519 key: ssh-keygen -t ed25519\n",
1142 key_path);
1143 SET_ERRNO(ERROR_CRYPTO_KEY, "Key parsing failed: %s", key_path);
1144 return -1;
1145 }
1146 } else if (strlen(GET_OPTION(password)) == 0) {
1147 // No identity key provided - server will run in simple mode
1148 // The server will still generate ephemeral keys for encryption, but no identity key
1151 log_info("Server running without identity key (simple mode)");
1152 }
1153
1154 for (size_t i = 0; i < g_num_server_identity_keys; ++i) {
1155 public_key_t identity = {.type = KEY_TYPE_ED25519};
1156 memcpy(identity.key, g_server_identity_keys[i].public_key, sizeof(identity.key));
1158 safe_snprintf(label, sizeof(label), "SERVER PUBLIC IDENTITY %zu", i + 1);
1159 key_identity_announce(label, &identity);
1160 }
1161
1162 // Load client whitelist if provided
1163 if (strlen(GET_OPTION(client_keys)) > 0) {
1165 SET_ERRNO(ERROR_CRYPTO_KEY, "Client key parsing failed: %s", GET_OPTION(client_keys));
1166 return -1;
1167 }
1168 log_debug("Loaded %zu whitelisted clients", g_num_whitelisted_clients);
1169 log_info("Server will only accept %zu whitelisted clients", g_num_whitelisted_clients);
1170 }
1171
1173 return 0;
1174}
1175
1176/* ============================================================================
1177 * Static server context (populated during init, used by callbacks)
1178 * ============================================================================ */
1179static server_context_t g_server_ctx;
1180
1181/* ============================================================================
1182 * Status screen callback (populates ui_status_t from server state)
1183 * ============================================================================ */
1184typedef struct {
1186 unsigned active, queued;
1190static void server_stats_connection(network_connection_t *connection, void *arg) {
1191 server_stats_visit_t *visit = arg;
1193 client_info_t *client = state ? atomic_ptr_load(&state->client) : NULL;
1194 if (!client || !atomic_load_bool(&client->event_ready))
1195 return;
1196 ++visit->active;
1197 acip_outbound_stats_t outbound = {0};
1198 acip_transport_t *transport = network_connection_transport(connection);
1199 if (transport->outbound)
1200 acip_outbound_snapshot(transport, &outbound);
1201 size_t queued = outbound.application_bytes + outbound.backend_bytes;
1202 if (queued)
1203 ++visit->queued;
1204 if (!visit->view->page)
1205 return;
1206 mutex_lock(&client->client_state_mutex);
1208 unsigned width = client->width, height = client->height;
1209 mutex_unlock(&client->client_state_mutex);
1210 stats_view_add(visit->view, "%-16.16s %ux%u %8llu %8llu %8llu / %zu", client->client_id, width, height, (unsigned long long)atomic_load_u64(&client->frames_sent_count),
1211 (unsigned long long)received, (unsigned long long)outbound.dropped, queued);
1212}
1213static void server_stats_provider(stats_view_t *view, void *unused) {
1214 (void)unused;
1215 server_stats_visit_t visit = {.view = view};
1216 if (view->page) {
1217 stats_view_add(view, "");
1218 stats_view_add_header(view, "SERVER CLIENTS dimensions sent received outbound drops / queued bytes");
1219 }
1220 network_server_foreach(session_server_like_get_network_server(), server_stats_connection, &visit);
1223 stats_view_add(view, "Connected clients: %u", visit.active);
1224}
1225
1226static void server_status_fn(void *user_data, ui_status_t *out_status) {
1227 (void)user_data;
1228
1230 if (!tcp) {
1231 return;
1232 }
1233
1234 ui_status_gather(tcp, g_session_string, network_server_config(tcp)->ipv4_address, network_server_config(tcp)->ipv6_address, GET_OPTION(port), g_server_start_time, "Server", g_session_is_mdns_only,
1235 out_status);
1236}
1237
1238/* ============================================================================
1239 * Mode-specific initialization callback
1240 * ============================================================================ */
1255
1269
1270static asciichat_error_t server_init_client_manager_lock(void) {
1271 // Initialize synchronization primitives
1272 if (rwlock_init(&g_client_manager_rwlock, "clients") != 0) {
1273 return SET_ERRNO(ERROR_THREAD, "Failed to initialize client manager rwlock");
1274 }
1276
1277 // Register global sync primitives for debugging
1278 NAMED_REGISTER_RWLOCK(&g_client_manager_rwlock, "client_manager_rwlock", NULL);
1279
1280 return ASCIICHAT_OK;
1281}
1282
1283static asciichat_error_t server_init_rate_limiter(void) {
1284 // Initialize connection rate limiter (prevents DoS attacks)
1286 log_debug("Initializing connection rate limiter...");
1288 if (!g_rate_limiter) {
1289 LOG_ERRNO_IF_SET("Failed to initialize rate limiter");
1291 return SET_ERRNO(ERROR_MEMORY, "Failed to create connection rate limiter");
1292 }
1293 } else {
1294 log_info("Connection rate limiter initialized (50 connections/min per IP)");
1295 }
1296 }
1297
1298 return ASCIICHAT_OK;
1299}
1300
1301static asciichat_error_t server_init_audio_mixer(void) {
1302 // Initialize audio mixer (always enabled on server)
1304 log_debug("Initializing audio mixer for per-client audio rendering...");
1306 if (!g_audio_mixer) {
1307 LOG_ERRNO_IF_SET("Failed to initialize audio mixer");
1309 return SET_ERRNO(ERROR_AUDIO, "Failed to initialize audio mixer");
1310 }
1311 } else {
1313 log_debug("Audio mixer initialized successfully for per-client audio rendering");
1314 }
1315 }
1316 }
1317
1318 return ASCIICHAT_OK;
1319}
1320
1321static asciichat_error_t server_init_h265(void) {
1322 // Initialize H.265 codec server context (always enabled on server)
1324 log_debug("Initializing H.265 codec server context...");
1326 if (!g_h265_server) {
1327 LOG_ERRNO_IF_SET("Failed to initialize H.265 codec context");
1329 return SET_ERRNO(ERROR_MEDIA_INIT, "Failed to initialize H.265 codec context");
1330 }
1331 } else {
1333 log_debug("H.265 codec server context initialized successfully");
1334 }
1335 }
1336 }
1337
1338 return ASCIICHAT_OK;
1339}
1340
1341static void server_init_session_host(network_server_t *tcp, int port) {
1342 // Session Host Creation (for discovery mode support)
1343 // Create session_host to track clients in a transport-agnostic way.
1345 const char *ipv4_address = network_server_config(tcp)->ipv4_address;
1346 const char *ipv6_address = network_server_config(tcp)->ipv6_address;
1347
1348 session_host_config_t host_config = {
1349 .port = port,
1350 .ipv4_address = ipv4_address,
1351 .ipv6_address = ipv6_address,
1352 .max_clients = GET_OPTION(max_clients),
1353 .encryption_enabled = g_server_encryption_enabled,
1354 .key_path = GET_OPTION(encrypt_key),
1355 .password = GET_OPTION(password),
1356 .callbacks = {0}, // No callbacks for now
1357 .user_data = NULL,
1358 };
1359
1360 g_server_ctx.session_host = session_host_create(&host_config);
1361 if (!g_server_ctx.session_host) {
1362 // Non-fatal: session_host is optional, server can work without it
1363 log_warn("Failed to create session_host (discovery mode support disabled)");
1364 } else {
1365 log_debug("Session host created for discovery mode support");
1366 }
1367 }
1368}
1369
1370static bool __attribute__((unused)) server_allow_discovery(server_discovery_policy_t *policy) {
1371 if (policy->has_password || policy->has_identity) {
1372 // Auto-enable privacy: IP revealed only after verification
1373 policy->expose_ip = false;
1374 log_plain("ACDS privacy enabled: IP disclosed only after %s verification", policy->has_password ? "password" : "identity");
1375 } else if (policy->explicit_expose) {
1376 // Explicit opt-in to public IP disclosure
1377 // Only prompt if running interactively (can prompt user)
1378 // When non-interactive (automated/scripted), treat explicit flag as confirmation
1379 bool is_interactive = terminal_can_prompt_user(!GET_OPTION(snapshot_mode));
1380
1381 if (is_interactive) {
1382 if (!ui_notice_confirm_kind(UI_PROMPT_IP_DISCLOSURE, UI_NOTICE_DANGER,
1383 "PUBLIC IP DISCLOSURE\nAnyone with the session string will be able to see your IP "
1384 "address.\n\nDo you want to proceed",
1385 30)) {
1386 log_info("IP disclosure not confirmed. Server will run WITHOUT discovery service.");
1387 return false;
1388 }
1389 }
1390
1391 // User confirmed (or running non-interactively with explicit flag) - proceed with public IP disclosure
1392 policy->expose_ip = true;
1393 NOTICE(DANGER, "PUBLIC IP DISCLOSURE ENABLED",
1394 "Public IP disclosure CONFIRMED.\n"
1395 "Your IP address will be visible to anyone with the session string");
1396 } else {
1397 // Security violation: No password, no identity, no explicit opt-in
1398 NOTICE(DANGER, "DISCOVERY DISABLED: SECURITY REQUIRED",
1399 "Cannot create ACDS session: No security configured!\n"
1400 "You must either:\n"
1401 "1. Set a password: --password \"your-secret\"\n"
1402 "2. Use identity key: --key ~/.ssh/id_ed25519\n"
1403 "3. Explicitly allow public IP: --acds-expose-ip (NOT RECOMMENDED)\n"
1404 "\n"
1405 "Server will run WITHOUT discovery service.");
1406 return false;
1407 }
1408
1409 return true;
1410}
1411
1412static void __attribute__((unused)) server_prepare_discovery_request(acds_session_create_params_t *params, const server_discovery_policy_t *policy, int port, nat_upnp_context_t *upnp_ctx,
1413 bool upnp_succeeded) {
1414 // Use server's Ed25519 identity public key if available
1417 memcpy(params->identity_seckey, g_server_private_key.key.ed25519, sizeof(params->identity_seckey));
1418 log_debug("Using server identity key for ACDS session");
1419 } else {
1420 // No identity key available - use zero key
1421 // ACDS will accept this if identity verification is not required
1422 memset(params->identity_pubkey, 0, ED25519_PUBLIC_KEY_SIZE);
1423 log_debug("No server identity key - using zero key for ACDS session");
1424 }
1425
1426 params->capabilities = 0x03; // Video + Audio
1427 params->max_participants = GET_OPTION(max_clients);
1428 log_debug("ACDS: max_clients option value = %d", GET_OPTION(max_clients));
1429
1430 // Set password if configured
1431 params->has_password = policy->has_password;
1432 if (policy->has_password) {
1433 // TODO: Hash password with Argon2id
1434 SAFE_STRNCPY(params->password, policy->password, sizeof(params->password));
1435 }
1436
1437 // Set IP disclosure policy (determined above)
1438 params->acds_expose_ip = policy->expose_ip;
1439 log_debug("Server setting acds_expose_ip=%d (explicit_expose=%d, has_password=%d, has_identity=%d)", params->acds_expose_ip, policy->explicit_expose, policy->has_password, policy->has_identity);
1440
1441 // Set session type (Direct TCP or WebRTC)
1442 // Auto-detect: Use WebRTC if UPnP failed or if WebRTC remains enabled.
1443 // Exception: If bind address is 0.0.0.0, server is on public IP - use Direct TCP
1444 const char *bind_addr = GET_OPTION(address);
1445 bool bind_all_interfaces = (strcmp(bind_addr, "0.0.0.0") == 0);
1446
1447 // Determine session type: prefer WebRTC by default (unless explicitly disabled)
1448 // Priority: connection type detection > UPnP > default; WebRTC is enabled unless --no-webrtc is set.
1449 if (!GET_OPTION(no_webrtc)) {
1450 // Explicit WebRTC request
1452 log_info("ACDS session type: WebRTC (enabled by default; use --no-webrtc to disable)");
1453 } else if (bind_all_interfaces) {
1454 // Bind to 0.0.0.0: use WebRTC as default (better NAT compatibility)
1456 log_info("ACDS session type: WebRTC (default for 0.0.0.0 binding, provides NAT-agnostic connections)");
1457 } else if (upnp_succeeded) {
1458 // UPnP port mapping worked - can use direct TCP
1460 log_info("ACDS session type: Direct TCP (router mapping created; external reachability unverified)");
1461 } else {
1462 // UPnP failed and not on public IP - use WebRTC for NAT traversal
1464 log_info("ACDS session type: WebRTC (no router mapping or direct connection type selected)");
1465 }
1466
1467 // Server connection information (where clients should connect)
1468 // If bind address is 0.0.0.0, leave server_address empty for ACDS to auto-detect public IP
1469 if (bind_all_interfaces) {
1470 params->server_address[0] = '\0'; // Empty - ACDS will use connection source IP
1471 log_debug("Bind address is 0.0.0.0, ACDS will auto-detect public IP from connection");
1472 } else {
1473 SAFE_STRNCPY(params->server_address, bind_addr, sizeof(params->server_address));
1474 }
1475 params->server_port = port;
1476 if (GET_OPTION(quic_bind_address)[0] || (GET_OPTION(webtransport_bind_address)[0] || GET_OPTION(webtransport_origin)[0]))
1477 params->quic_port = (uint16_t)(GET_OPTION(quic_port) ? GET_OPTION(quic_port) : port);
1478 if ((GET_OPTION(webtransport_bind_address)[0] || GET_OPTION(webtransport_origin)[0]))
1479 SAFE_STRNCPY(params->webtransport_url, GET_OPTION(webtransport_public_url), sizeof(params->webtransport_url));
1480 if (params->session_type == SESSION_TYPE_DIRECT_TCP) {
1481 if (nat_upnp_get_endpoint(upnp_ctx, params->server_address, sizeof(params->server_address), &params->server_port) != ASCIICHAT_OK) {
1483 log_info("ACDS session type: WebRTC (router mapping expired before registration)");
1484 }
1485 }
1486
1487 // DEBUG: Log what we're sending to ACDS
1488 log_debug("Before SESSION_CREATE - expose_ip_publicly=%d, server_address='%s' port=%u, session_type=%u", params->acds_expose_ip, params->server_address, params->server_port, params->session_type);
1489}
1490
1491static void __attribute__((unused)) server_join_discovery_session(const acds_session_create_params_t *params, acds_session_create_result_t *result, const char *session_string,
1492 const server_discovery_policy_t *policy) {
1493 // Server must join its own session so ACDS can route signaling messages
1494 log_debug("Server joining session as first participant for WebRTC signaling...");
1495 acds_session_join_params_t join_params = {0};
1496 join_params.session_string = session_string;
1497
1498 // Use same identity key as session creation
1499 memcpy(join_params.identity_pubkey, params->identity_pubkey, ED25519_PUBLIC_KEY_SIZE);
1500 memcpy(join_params.identity_seckey, params->identity_seckey, sizeof(join_params.identity_seckey));
1501
1502 // Include password if session is password-protected
1503 if (policy->has_password) {
1504 join_params.has_password = true;
1505 SAFE_STRNCPY(join_params.password, policy->password, sizeof(join_params.password));
1506 }
1507
1508 acds_session_join_result_t join_result = {0};
1509 asciichat_error_t join_err = acds_session_join(g_acds_client, &join_params, &join_result);
1510 if (join_err != ASCIICHAT_OK || !join_result.success) {
1511 log_error("Failed to join own session: %s (error: %s)", asciichat_error_format(NULL, join_err), join_result.error_message[0] ? join_result.error_message : "unknown");
1512 // Continue anyway - this is not fatal for Direct TCP sessions
1513 } else {
1514 log_debug("Server joined session successfully (participant_id: %02x%02x...)", join_result.participant_id[0], join_result.participant_id[1]);
1515 // Store participant ID for WebRTC signaling (needed to identify server in SDP/ICE messages)
1516 memcpy(g_server_participant_id, join_result.participant_id, SESSION_ID_SIZE);
1517 memcpy(g_server_session_id, join_result.session_id, SESSION_ID_SIZE);
1518 log_debug("Stored server participant_id for signaling: %02x%02x...", g_server_participant_id[0], g_server_participant_id[1]);
1519 memcpy(result->session_id, join_result.session_id, SESSION_ID_SIZE);
1520 }
1521}
1522
1523static void __attribute__((unused)) server_start_discovery_keepalive(void) {
1524 // Keep ACDS connection alive for WebRTC signaling relay
1525 log_debug("Server staying connected to ACDS for signaling relay");
1526
1527 // Signaling shares the authenticated connection and its ordered send scheduler.
1528 g_acds_transport = g_acds_client->transport;
1529 if (!g_acds_transport) {
1530 log_error("Failed to create ACDS transport wrapper");
1531 } else {
1532 log_debug("ACDS transport wrapper created for signaling");
1533
1534 // Start ACDS ping thread to keep connection alive (for ALL session types)
1535 int ping_thread_result = platform_thread_create(&g_acds_ping_thread, "acds_ping", acds_ping_thread, NULL);
1536 if (ping_thread_result != 0) {
1537 log_error("Failed to create ACDS ping thread: %d", ping_thread_result);
1538 } else {
1539 log_debug("ACDS ping thread started to keep connection alive");
1540 g_acds_ping_thread_started = true;
1541 }
1542 }
1543}
1544
1545static int server_configure_stun(stun_server_t stun_servers[MAX_CONFIGURED_STUN_SERVERS]) {
1546 static lifecycle_t g_stun_lc = LIFECYCLE_INIT;
1547 static int stun_count = 0; // Store actual count separately
1548
1549 if (lifecycle_init(&g_stun_lc, "stun")) {
1550 log_debug("Parsing STUN servers from options: '%s'", GET_OPTION(stun_servers));
1551 int count = stun_servers_parse(GET_OPTION(stun_servers), OPT_ENDPOINT_STUN_SERVERS_DEFAULT, stun_servers, 4);
1552 if (count > 0) {
1553 stun_count = count;
1554 log_debug("Parsed %d STUN servers", count);
1555 for (int i = 0; i < count; i++) {
1556 log_debug(" STUN[%d]: '%s' (len=%d)", i, stun_servers[i].host, stun_servers[i].host_len);
1557 }
1558 } else {
1559 log_warn("Failed to parse STUN servers, using defaults");
1561 log_debug("Using default STUN servers, count=%d", stun_count);
1562 for (int i = 0; i < stun_count; i++) {
1563 log_debug(" STUN[%d]: '%s' (len=%d)", i, stun_servers[i].host, stun_servers[i].host_len);
1564 }
1565 }
1566 }
1567
1568 return stun_count;
1569}
1570
1571static size_t server_configure_turn(turn_server_t turn_servers[MAX_CONFIGURED_TURN_SERVERS], const char *turn_username, const char *turn_credential) {
1572 size_t turn_count = 0;
1573 const char *urls = GET_OPTION(turn_servers);
1574 if (!urls || !urls[0] || !turn_username[0] || !turn_credential[0])
1575 return 0;
1576 asciichat_error_t result = webrtc_turn_servers_parse(urls, turn_username, turn_credential, turn_servers, MAX_CONFIGURED_TURN_SERVERS, &turn_count);
1577 if (result != ASCIICHAT_OK) {
1578 log_error("Failed to configure TURN servers: %s", asciichat_error_format(NULL, result));
1579 return 0;
1580 }
1581 return turn_count;
1582}
1583
1584static void __attribute__((unused)) server_init_webrtc(void) {
1585 log_debug("Initializing WebRTC library and peer manager for session (role=CREATOR)...");
1586
1587 // Initialize WebRTC library (libdatachannel)
1588 asciichat_error_t webrtc_init_result = webrtc_init();
1589 if (webrtc_init_result != ASCIICHAT_OK) {
1590 log_error("Failed to initialize WebRTC library: %s", asciichat_error_format(NULL, webrtc_init_result));
1591 g_webrtc_peer_manager = NULL;
1592 } else {
1593 log_debug("WebRTC library initialized successfully");
1594
1595 // Configure STUN servers for ICE gathering (static to persist for peer_manager lifetime)
1596 static stun_server_t stun_servers[MAX_CONFIGURED_STUN_SERVERS] = {0};
1597 int stun_count = server_configure_stun(stun_servers);
1598
1599 static turn_server_t turn_servers[MAX_CONFIGURED_TURN_SERVERS];
1600 static char turn_auth_username[SERVER_MAIN_TURN_AUTH_USERNAME_BUFFER_SIZE];
1601 static char turn_auth_credential[SERVER_MAIN_TURN_AUTH_CREDENTIAL_BUFFER_SIZE];
1602 size_t turn_count = 0;
1603 const char *turn_username = GET_OPTION(turn_username);
1604 const char *turn_credential = GET_OPTION(turn_credential);
1605 SAFE_STRNCPY(turn_auth_username, turn_username, sizeof(turn_auth_username));
1606 SAFE_STRNCPY(turn_auth_credential, turn_credential, sizeof(turn_auth_credential));
1607 turn_count = server_configure_turn(turn_servers, turn_username, turn_credential);
1608
1609 // Configure peer_manager
1610 const char *server_address = GET_OPTION(address);
1611 const char *ice_bind_address = GET_OPTION(webrtc_bind_address);
1612 bool bind_webrtc_to_server_address = server_address && server_address[0] && strcmp(server_address, "0.0.0.0") != 0 && strcmp(server_address, "::") != 0;
1613 webrtc_peer_manager_config_t pm_config = {.role = WEBRTC_ROLE_CREATOR, // Server accepts offers, generates answers
1614 // Honor an explicitly selected server interface for ICE. With a
1615 // wildcard bind, let libdatachannel gather candidates on all interfaces.
1616 .bind_address = ice_bind_address[0] ? ice_bind_address : (bind_webrtc_to_server_address ? server_address : NULL),
1617 .stun_servers = stun_servers,
1618 .stun_count = stun_count,
1619 .turn_servers = turn_servers,
1620 .turn_count = turn_count,
1621 .relay_only = GET_OPTION(webrtc_relay_only),
1622 .turn_username = turn_auth_username,
1623 .turn_credential = turn_auth_credential,
1624 .on_transport_ready = on_webrtc_transport_ready,
1625 .user_data = &g_server_ctx};
1626
1627 // Configure signaling callbacks for relaying SDP/ICE via ACDS
1628 webrtc_signaling_callbacks_t signaling_callbacks = {.send_sdp = server_send_sdp, .send_ice = server_send_ice, .user_data = NULL};
1629
1630 // Create peer_manager
1631 asciichat_error_t pm_result = webrtc_peer_manager_create(&pm_config, &signaling_callbacks, &g_webrtc_peer_manager);
1632 if (pm_result != ASCIICHAT_OK) {
1633 log_error("Failed to create WebRTC peer_manager: %s", asciichat_error_format(NULL, pm_result));
1634 g_webrtc_peer_manager = NULL;
1635 } else {
1636 log_debug("WebRTC peer_manager initialized successfully");
1637
1638 // Start ACDS receive thread for WebRTC signaling relay
1639 int thread_result = platform_thread_create(&g_acds_receive_thread, "acds_recv", acds_receive_thread, NULL);
1640 if (thread_result != 0) {
1641 log_error("Failed to create ACDS receive thread: %d", thread_result);
1642 // Cleanup peer_manager since signaling won't work
1643 webrtc_peer_manager_destroy(g_webrtc_peer_manager);
1644 g_webrtc_peer_manager = NULL;
1645 } else {
1646 log_debug("ACDS receive thread started for WebRTC signaling relay");
1647 g_acds_receive_thread_started = true;
1648 }
1649 }
1650 }
1651}
1652
1653static void server_register_discovery(server_discovery_startup_t *startup, int port, nat_upnp_context_t *upnp_ctx, bool upnp_succeeded) {
1654 /*
1655 * Server mode is a direct listener. Shareable discovery sessions belong to
1656 * discovery mode, which owns the ACDS session lifecycle and only announces a
1657 * code after the discovery connection becomes active.
1658 *
1659 * Keep this hook in place for the server startup sequence so the networking
1660 * setup remains easy to extend, but do not connect to ACDS or create a
1661 * session from server mode.
1662 */
1663 (void)startup;
1664 (void)port;
1665 (void)upnp_ctx;
1666 (void)upnp_succeeded;
1667 return;
1668
1669#if 0
1670 if (!GET_OPTION(discovery)) {
1671 log_info("ACDS registration disabled (use --acds to enable)");
1672 return;
1673 }
1674 const char *password = GET_OPTION(password);
1675 const char *encrypt_key = GET_OPTION(encrypt_key);
1676 server_discovery_policy_t policy = {
1677 .password = password,
1678 .has_password = password && strlen(password) > 0,
1679 .has_identity = encrypt_key && strlen(encrypt_key) > 0,
1680 .explicit_expose = GET_OPTION(discovery_expose_ip) != 0,
1681 };
1682 if (!server_allow_discovery(&policy)) {
1683 return;
1684 }
1685 // Security is configured, proceed with ACDS connection
1686 char discovery_url[URL_BUFFER_SIZE];
1687 const char *acds_server = GET_OPTION(discovery_server);
1689 if (GET_OPTION(discovery_port) != ACIP_DISCOVERY_DEFAULT_PORT) {
1690 asciichat_error_t override_result = connection_endpoint_override_port(acds_server, (uint16_t)GET_OPTION(discovery_port),
1691 discovery_url, sizeof(discovery_url));
1692 if (override_result != ASCIICHAT_OK) {
1693 log_error("Invalid --discovery-service URL for --discovery-service-port override");
1694 return;
1695 }
1696 acds_server = discovery_url;
1697 }
1698
1699 log_info("Attempting to create session on ACDS server at %s...", acds_server);
1700
1701 acds_client_config_t acds_config;
1703 SAFE_STRNCPY(acds_config.server_address, acds_server, sizeof(acds_config.server_address));
1704 acds_config.server_port = acds_port;
1705 acds_config.timeout_ms = 5 * MS_PER_SEC_INT;
1706 acds_config.identity_key = GET_OPTION(encrypt_key);
1707
1708 // Allocate ACDS client on heap for server lifecycle
1709 g_acds_client = SAFE_MALLOC(sizeof(acds_client_t), acds_client_t *);
1710 if (!g_acds_client) {
1711 log_error("Failed to allocate ACDS client");
1712 return;
1713 }
1714
1715 asciichat_error_t acds_connect_result = acds_client_connect(g_acds_client, &acds_config);
1716 if (acds_connect_result != ASCIICHAT_OK) {
1717 log_error("Failed to connect to ACDS server at %s:%d: %s", acds_server, acds_port,
1718 asciichat_error_format(NULL, acds_connect_result));
1719 return;
1720 }
1721 acds_session_create_params_t create_params = {0};
1722 if ((GET_OPTION(webtransport_bind_address)[0] || GET_OPTION(webtransport_origin)[0]) &&
1723 strlen(GET_OPTION(webtransport_public_url)) >= sizeof(create_params.webtransport_url)) {
1724 log_error("WebTransport public URL exceeds the discovery endpoint limit");
1725 return;
1726 }
1727 server_prepare_discovery_request(&create_params, &policy, port, upnp_ctx, upnp_succeeded);
1728 acds_session_create_result_t create_result;
1729 asciichat_error_t result = acds_session_create(g_acds_client, &create_params, &create_result);
1730 if (result != ASCIICHAT_OK) {
1731 log_warn("Failed to create session on ACDS server (server will run without discovery)");
1732 if (g_acds_client) {
1733 acds_client_disconnect(g_acds_client);
1734 SAFE_FREE(g_acds_client);
1735 g_acds_client = NULL;
1736 }
1737 return;
1738 }
1739 SAFE_STRNCPY(startup->session_string, create_result.session_string, sizeof(startup->session_string));
1740 SAFE_STRNCPY(g_session_string, create_result.session_string, sizeof(g_session_string));
1741 startup->mdns_only = false;
1742 log_info("Session created: %s", startup->session_string);
1743 server_join_discovery_session(&create_params, &create_result, startup->session_string, &policy);
1744 server_start_discovery_keepalive();
1745 if (create_params.session_type == SESSION_TYPE_WEBRTC) {
1746 server_init_webrtc();
1747 } else {
1748 log_debug("Session type is DIRECT_TCP, skipping WebRTC peer_manager initialization");
1749 }
1750 advertise_mdns_with_session(startup->session_string, (uint16_t)port);
1751#endif
1752}
1753
1754static asciichat_error_t server_announce_session(server_discovery_startup_t *startup, int port) {
1755 (void)startup;
1756 (void)port;
1757 /* Discovery-mode owns session creation and the share-code announcement. */
1758 return ASCIICHAT_OK;
1759}
1760
1761static void server_tick_fn(void *user_data) {
1762 (void)user_data;
1763 asciichat_error_t result = webrtc_peer_manager_dispatch_ready(g_webrtc_peer_manager);
1764 if (result != ASCIICHAT_OK) {
1765 log_error("WebRTC ready dispatch failed: %s", asciichat_error_format(NULL, result));
1768 if (tcp)
1770 }
1771}
1772
1773static asciichat_error_t server_init_fn(void *user_data) {
1774 (void)user_data;
1775 int port = GET_OPTION(port);
1776
1777 // Get TCP server from server_like (it's already initialized at this point)
1779 if (!tcp) {
1780 return SET_ERRNO(ERROR_INVALID_STATE, "TCP server not available from server_like");
1781 }
1782
1783 // Point server context at the server_like-owned TCP server
1784 g_server_ctx.network_server = tcp;
1785
1786 // A local mapping behind upstream NAT must not suppress WebRTC discovery.
1788 bool upnp_succeeded = nat_upnp_is_active(upnp_ctx) && !upnp_ctx->external_is_private && is_internet_ipv4(upnp_ctx->external_ip);
1789
1790 asciichat_error_t result = server_init_client_manager_lock();
1791 if (result != ASCIICHAT_OK) {
1792 return result;
1793 }
1794 // Check if SIGINT/SIGTERM was received during initialization
1796 log_info("Shutdown signal received during initialization, skipping server startup");
1797 return ASCIICHAT_OK;
1798 }
1799
1800 // NOTE: g_client_manager is already zero-initialized in client.c with = {0}
1801 // We only need to initialize the mutex
1802 mutex_init(&g_client_manager.mutex, "client_manager");
1803
1804 // Initialize uthash head pointer for O(1) lookup (uthash requires NULL initialization)
1805 g_client_manager.clients_by_id = NULL;
1806
1807 result = server_init_rate_limiter();
1808 if (result != ASCIICHAT_OK) {
1809 return result;
1810 }
1811 result = server_init_audio_mixer();
1812 if (result != ASCIICHAT_OK) {
1813 return result;
1814 }
1815 result = server_init_h265();
1816 if (result != ASCIICHAT_OK) {
1817 return result;
1818 }
1819 server_init_session_host(tcp, port);
1820
1821 // Update server context fields that depend on init results
1822 g_server_ctx.rate_limiter = g_rate_limiter;
1823 g_server_ctx.audio_mixer = g_audio_mixer;
1824 g_server_ctx.h265_server = g_h265_server; // Sync H.265 context created in this function
1825
1826 server_discovery_startup_t startup = {0};
1827 server_register_discovery(&startup, port, upnp_ctx, upnp_succeeded);
1828 result = server_announce_session(&startup, port);
1829 if (result != ASCIICHAT_OK) {
1830 return result;
1831 }
1832
1833 // Copy session info to globals for status screen display
1834 SAFE_STRNCPY(g_session_string, startup.session_string, sizeof(g_session_string));
1835 g_session_is_mdns_only = startup.mdns_only;
1836
1837 // Initialize the status screen uptime
1838 g_server_start_time = time(NULL);
1839
1840 stats_runtime_set_provider(server_stats_provider, NULL);
1841 log_debug("Server init_fn complete");
1842 return ASCIICHAT_OK;
1843}
1844
1845/* ============================================================================
1846 * Mode-specific cleanup callback
1847 * ============================================================================ */
1848static void server_stop_workers(void) {
1849 // Stop and destroy server worker thread pool (stats logger, etc.)
1850 if (g_server_worker_pool) {
1851 thread_pool_destroy(g_server_worker_pool);
1852 g_server_worker_pool = NULL;
1853 log_debug("Server worker thread pool stopped");
1854 }
1855
1856 // Destroy rate limiter
1857 if (g_rate_limiter) {
1859 g_rate_limiter = NULL;
1860 }
1861}
1862
1863static void server_wait_for_clients(void) {
1864 // Wait for all client handler threads to exit (only if rwlock was initialized)
1866 int retry_count = 0;
1867 while (retry_count < 50) { // Max 500ms wait
1868 rwlock_rdlock(&g_client_manager_rwlock);
1869 bool all_cleaned = true;
1870 for (int i = 0; i < MAX_CLIENTS; i++) {
1871 if (g_client_manager.clients[i].client_id[0] != '\0') {
1872 all_cleaned = false;
1873 break;
1874 }
1875 }
1876 rwlock_rdunlock(&g_client_manager_rwlock);
1877
1878 if (all_cleaned)
1879 break;
1880 platform_sleep_us(10 * US_PER_MS_INT); // 10ms
1881 retry_count++;
1882 }
1883 log_debug("Client handler threads cleaned up");
1884 }
1885}
1886
1887static void server_remove_remaining_clients(void) {
1888 // Clean up all connected clients (only if rwlock was initialized)
1889 log_debug("Cleaning up connected clients...");
1890 char clients_to_remove[MAX_CLIENTS][MAX_CLIENT_ID_LEN];
1891 int client_count = 0;
1892
1894 rwlock_rdlock(&g_client_manager_rwlock);
1895 for (int i = 0; i < MAX_CLIENTS; i++) {
1896 client_info_t *client = &g_client_manager.clients[i];
1897 if (client->client_id[0] == '\0') {
1898 continue;
1899 }
1900 SAFE_STRNCPY(clients_to_remove[client_count], client->client_id, MAX_CLIENT_ID_LEN - 1);
1901 client_count++;
1902 }
1903 rwlock_rdunlock(&g_client_manager_rwlock);
1904 }
1905
1906 for (int i = 0; i < client_count; i++) {
1907 if (remove_client(&g_server_ctx, clients_to_remove[i]) != 0) {
1908 log_error("Failed to remove client %s during shutdown", clients_to_remove[i]);
1909 }
1910 }
1911
1912 // Clean up hash table
1913 while (g_client_manager.clients_by_id) {
1914 client_info_t *current_client = g_client_manager.clients_by_id;
1915 HASH_DELETE(hh, g_client_manager.clients_by_id, current_client);
1916 }
1917}
1918
1919static void server_destroy_media(void) {
1920 // Clean up audio mixer
1921 if (g_audio_mixer) {
1922 mixer_t *mixer_to_destroy = g_audio_mixer;
1923 g_audio_mixer = NULL;
1924 mixer_destroy(mixer_to_destroy);
1925 }
1926
1927 // Clean up H.265 codec server context
1928 if (g_h265_server) {
1929 h265_server_context_t *h265_to_destroy = g_h265_server;
1930 g_h265_server = NULL;
1931 g_server_ctx.h265_server = NULL;
1932 h265_server_context_destroy(h265_to_destroy);
1933 log_debug("H.265 codec server context shut down");
1934 }
1935}
1936
1937static void server_destroy_session_host(void) {
1938 // Destroy session host
1939 if (g_server_ctx.session_host) {
1940 log_debug("Destroying session host");
1941 session_host_destroy(g_server_ctx.session_host);
1942 g_server_ctx.session_host = NULL;
1943 }
1944
1945 // Destroy H.265 server codec context from server_ctx
1946 if (g_server_ctx.h265_server) {
1947 log_debug("Destroying H.265 server context");
1948 h265_server_context_destroy(g_server_ctx.h265_server);
1949 g_server_ctx.h265_server = NULL;
1950 }
1951}
1952
1953static void server_stop_discovery(void) {
1954 // Join ACDS threads (if started)
1955 if (g_acds_ping_thread_started) {
1956 log_debug("Joining ACDS ping thread");
1957 thread_join(&g_acds_ping_thread, NULL);
1958 g_acds_ping_thread_started = false;
1959 log_debug("ACDS ping thread joined");
1960 }
1961
1962 if (g_acds_client && g_acds_client->connection)
1963 network_connection_request_stop(g_acds_client->connection);
1964 if (g_acds_receive_thread_started) {
1965 log_debug("Joining ACDS receive thread");
1966 thread_join(&g_acds_receive_thread, NULL);
1967 g_acds_receive_thread_started = false;
1968 log_debug("ACDS receive thread joined");
1969 }
1970
1971 // Clean up WebRTC peer manager
1972 if (g_webrtc_peer_manager) {
1973 log_debug("Destroying WebRTC peer manager");
1974 webrtc_peer_manager_destroy(g_webrtc_peer_manager);
1975 g_webrtc_peer_manager = NULL;
1976 }
1977
1978 // Clean up ACDS transport wrapper
1979 if (g_acds_transport) {
1980 log_debug("Destroying ACDS transport wrapper");
1981 g_acds_transport = NULL;
1982 }
1983
1984 // Disconnect from ACDS server
1985 if (g_acds_client) {
1986 log_debug("Disconnecting from ACDS server");
1987 acds_client_disconnect(g_acds_client);
1988 SAFE_FREE(g_acds_client);
1989 g_acds_client = NULL;
1990 }
1991}
1992
1993static void server_cleanup_fn(void *user_data) {
1994 // Initialization can fail before the run loop signals shutdown.
1996 stats_runtime_set_provider(NULL, NULL);
1997 (void)user_data;
1998
1999 log_debug("Server shutting down...");
2000 memset(g_session_string, 0, sizeof(g_session_string)); // Clear session string for status screen
2001
2002 // Wake up any threads that might be blocked on condition variables
2003 // (like packet queues) to ensure responsive shutdown
2004 static_cond_broadcast(&g_shutdown_cond);
2005
2006 log_debug("Signaling all clients to stop (sockets closed, g_should_exit set)...");
2007
2008 server_stop_workers();
2009
2010 server_wait_for_clients();
2011
2012 // Cleanup debug sync BEFORE destroying websocket_server
2013#ifndef NDEBUG
2014 debug_sync_destroy();
2017#endif
2018
2019 server_remove_remaining_clients();
2020
2021 server_destroy_media();
2022
2023 // Clean up synchronization primitives (only if they were initialized)
2025 rwlock_destroy(&g_client_manager_rwlock);
2027 }
2028 mutex_destroy(&g_client_manager.mutex);
2029
2030#ifndef NDEBUG
2031 stats_cleanup();
2032#endif
2033
2034 server_destroy_session_host();
2035
2036 // TCP server, WebSocket server, mDNS, UPnP are destroyed by server_like.
2037
2038 server_stop_discovery();
2039
2040 // Clean up platform-specific resources
2041 socket_cleanup();
2042
2043 log_info("Server shutdown complete");
2045}
2046
2047/* ============================================================================
2048 * server_main() - Entry point, delegates to session_server_like_run()
2049 * ============================================================================ */
2050int server_main(void) {
2051 // Common initialization (options, logging, lock debugging) now happens in main.c before dispatch
2052
2053 // Register atomic for debug tracking
2055
2056 // Register shutdown check callback for library code
2057 shutdown_register_callback(check_shutdown);
2058
2059 // Initialize crypto after logging is ready
2060 log_debug("Initializing crypto...");
2061 if (init_server_crypto() != 0) {
2062 LOG_ERRNO_IF_SET("Crypto initialization failed");
2063 FATAL(ERROR_CRYPTO, "Crypto initialization failed");
2064 }
2065 log_debug("Crypto initialized successfully");
2066
2067 log_info("ascii-chat server starting...");
2068
2069 int port = GET_OPTION(port);
2070 if (port < 1 || port > 65535) {
2071 log_error("Invalid port configuration: %d", port);
2072 FATAL(ERROR_CONFIG, "Invalid port configuration: %d", port);
2073 }
2074
2077
2078#ifndef NDEBUG
2079 if (stats_init() != 0) {
2080 FATAL(ERROR_THREAD, "Statistics system initialization failed");
2081 }
2082#endif
2083
2084 // Create background worker thread pool for server operations
2085 g_server_worker_pool = thread_pool_create("server_workers");
2086 if (!g_server_worker_pool) {
2087 LOG_ERRNO_IF_SET("Failed to create server worker thread pool");
2088 FATAL(ERROR_MEMORY, "Failed to create server worker thread pool");
2089 }
2090
2091 // Spawn statistics logging thread in worker pool
2092 if (thread_pool_spawn(g_server_worker_pool, stats_logger_thread, NULL, 0, "stats_logger") != ASCIICHAT_OK) {
2093 LOG_ERRNO_IF_SET("Statistics logger thread creation failed");
2094 } else {
2095 log_debug("Statistics logger thread started");
2096 }
2097
2098 // Initialize static server context (populated further in server_init_fn)
2099 // H.265 context is initialized in server_init_fn, not here
2100 g_server_ctx = (server_context_t){
2101 .network_server = NULL, // Set in server_init_fn after TCP server is ready
2102 .rate_limiter = g_rate_limiter,
2103 .client_manager = &g_client_manager,
2104 .client_manager_rwlock = &g_client_manager_rwlock,
2105 .server_should_exit = &g_should_exit,
2106 .audio_mixer = g_audio_mixer,
2107 .stats = &g_stats,
2108 .stats_mutex = &g_stats_mutex,
2109 .encryption_enabled = g_server_encryption_enabled,
2110 .server_private_key = &g_server_private_key,
2111 .client_whitelist = g_client_whitelist,
2112 .num_whitelisted_clients = g_num_whitelisted_clients,
2113 .session_host = NULL,
2114 .h265_server = NULL, // Initialized in server_init_fn
2115 };
2116
2118 .init_fn = server_init_fn,
2119 .tick_fn = server_tick_fn,
2120 .init_user_data = NULL,
2121 .interrupt_fn = server_handle_sigint,
2122 .cleanup_fn = server_cleanup_fn,
2123 .cleanup_user_data = NULL,
2124 .status_fn = server_status_fn,
2125 .status_user_data = NULL,
2126 .connections = server_network_callbacks,
2127 .connection_user_data = &g_server_ctx,
2128 .websocket_enabled = true,
2129 .partial_timeout_ms = 30000,
2130 .mdns =
2131 {
2132 .enabled = !GET_OPTION(no_mdns_advertise),
2133 .service_name = NULL, // Deferred: advertised after ACDS or mDNS session string is ready
2134 .service_type = "_ascii-chat._tcp",
2135 },
2136 .upnp =
2137 {
2138 .enabled = GET_OPTION(enable_upnp),
2139 .description = "ascii-chat Server",
2140 },
2141 // Raise FD limit for high-client-count scenarios (matches discovery-service policy)
2142 // Server accepts MAX_CLIENTS connections plus WebSocket, TCP, UPnP, mDNS, etc.
2143 // Each client may use multiple FDs (socket, media buffers, file handles)
2144 // Raising to 65536 ensures we don't hit system limits under load
2145 .raise_fd_limit = true,
2146 .fd_limit_target = 65536,
2147 };
2148
2150 return (result == ASCIICHAT_OK) ? 0 : 1;
2151}
ACIP client-side protocol library and ACDS client connection API.
void acds_client_config_init_defaults(acds_client_config_t *config)
Initialize ACDS client configuration with defaults.
asciichat_error_t acds_session_create(acds_client_t *client, const acds_session_create_params_t *params, acds_session_create_result_t *result)
Create a new session on the discovery server.
asciichat_error_t acds_session_join(acds_client_t *client, const acds_session_join_params_t *params, acds_session_join_result_t *result)
Join an existing session.
asciichat_error_t acds_client_connect(acds_client_t *client, const acds_client_config_t *config)
Connect to ACDS server.
void acds_client_disconnect(acds_client_t *client)
Disconnect from ACDS server.
Application-level callbacks for library code.
#define APP_CALLBACK_VOID(callback_name)
void asciichat_error_stats_print(void)
const char * asciichat_error_format(const char *message, asciichat_error_t code)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
#define LOG_ERRNO_IF_SET(message)
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
int atomic_fetch_add_int(atomic_t *a, int delta)
Atomically add to an int and return the previous value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void * atomic_ptr_load(atomic_ptr_t *a)
Atomically load a pointer.
#define ATOMIC_REGISTER_AUTO(name, parent_ptr)
Register an atomic variable for debug tracking with automatic name generation.
Definition atomic.h:469
uint64_t atomic_load_u64(atomic_t *a)
Atomically load a uint64_t value.
#define AUDIO_SAMPLE_RATE
Definition audio/limits.h:8
#define AUDIO_CHANNELS
Definition audio/limits.h:9
asciichat_error_t acip_outbound_snapshot(acip_transport_t *transport, acip_outbound_stats_t *stats)
void acip_transport_destroy(acip_transport_t *transport)
Destroy transport and free all resources.
Platform initialization and static synchronization helpers.
asciichat_error_t connection_endpoint_override_port(const char *input, uint16_t port, char *output, size_t output_size)
Shared endpoint normalization for TCP and WebSocket connections.
const network_connection_callbacks_t server_network_callbacks
Named object registry for debugging — log identifiable resource names.
void pubkey_to_hex(const uint8_t pubkey[32], char hex_out[(32 *2+1)])
Convert Ed25519 public key to hex string.
Definition discovery.c:58
🔄 Network byte order conversion helpers
#define HOST_TO_NET_U16(val)
Definition endian.h:100
#define NET_TO_HOST_U16(val)
Definition endian.h:115
void debug_errno_destroy(void)
Definition errno.c:125
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
atomic_t g_should_exit
Global application exit flag (shared across all modes).
Definition globals.c:31
mixer_t * mixer_create_channels(int max_sources, int sample_rate, unsigned channels)
Definition mixer.c:208
void mixer_destroy(mixer_t *mixer)
Destroy a mixer and free all resources.
Definition mixer.c:370
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)
#define FATAL(code,...)
Exit with error code and custom message, with stack trace in debug builds.
unsigned long long uint64_t
unsigned char uint8_t
#define NAMED_REGISTER_RWLOCK(lock, name, parent_ptr)
Register an rwlock with automatic format specifier.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_CRYPTO_KEY
Definition error_codes.h:98
@ ERROR_AUDIO
Definition error_codes.h:66
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_MEDIA_INIT
Definition error_codes.h:69
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_CRYPTO
Definition error_codes.h:97
@ ERROR_INVALID_PARAM
@ ERROR_THREAD
uint8_t key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:78
asciichat_error_t parse_private_key(const char *key_path, private_key_t *key_out)
Parse SSH private key from file.
Definition keys.c:212
asciichat_error_t parse_public_keys(const char *input, public_key_t *keys_out, size_t *num_keys, size_t max_keys)
Parse all SSH/GPG public keys from any format (returns all keys).
Definition keys.c:402
asciichat_error_t validate_ssh_key_file(const char *key_path)
Validate SSH key file permissions and format.
Definition ssh_keys.c:1007
@ KEY_TYPE_UNKNOWN
Definition key_types.h:57
@ KEY_TYPE_ED25519
Definition key_types.h:58
#define MAX_CLIENTS
Maximum possible clients (static array size) - actual runtime limit set by –max-clients (1-128).
#define SESSION_ID_SIZE
#define MAX_CONFIGURED_TURN_SERVERS
#define URL_BUFFER_SIZE
#define HOSTNAME_BUFFER_SIZE
#define MAX_CLIENT_ID_LEN
Maximum client ID length - format: "noun.N (transport:port)" e.g., "mountain.0 (tcp:48036)".
#define MAX_CONFIGURED_STUN_SERVERS
#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
#define log_plain(...)
Plain logging - writes to both log file and stderr without timestamps or log levels.
Definition log/log.h:659
int32_t vec_t __attribute__((vector_size(4 *4)))
SESSION_CREATED (PACKET_TYPE_ACIP_SESSION_CREATED) - Session created response.
Definition vector.h:42
#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_webrtc_sdp_t
Definition acds.h:609
@ 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 US_PER_MS_INT
Definition time.h:176
#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_PONG
Keepalive pong response.
Definition packet.h:423
@ PACKET_TYPE_ACIP_WEBRTC_SDP
WebRTC SDP offer/answer (bidirectional).
Definition packet.h:464
@ PACKET_TYPE_PING
Keepalive ping packet.
Definition packet.h:421
#define GET_OPTION(field)
Definition options.h:1333
#define OPT_ENDPOINT_STUN_SERVERS_DEFAULT
Default STUN servers (comma-separated list).
Definition options.h:633
const float weight_blue
Blue weight for luminance calculation.
const float weight_red
Red weight for luminance calculation.
const float weight_green
Green weight for luminance calculation.
#define STATIC_COND_INIT
asciichat_error_t session_host_destroy(session_host_t *host)
Destroy session host and free resources.
Definition host.c:289
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
session_host_t * session_host_create(const session_host_config_t *config)
Create a new session host.
Definition host.c:234
void shutdown_register_callback(shutdown_check_fn callback)
Register application's shutdown check function.
Definition common.c:78
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
int is_internet_ipv4(const char *ip)
Check if IPv4 address is a public internet address.
Definition ip.c:1318
struct client_info client_info_t
void precalc_rgb_palettes(const float red, const float green, const float blue)
Precalculate RGB palettes with color adjustment.
void ascii_simd_init(void)
Initialize SIMD subsystem.
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).
asciichat_error_t webrtc_peer_manager_handle_sdp(webrtc_peer_manager_t *manager, const acip_webrtc_sdp_t *sdp)
Handle incoming SDP message from ACDS.
void webrtc_peer_manager_destroy(webrtc_peer_manager_t *manager)
Destroy peer manager and close all connections.
asciichat_error_t webrtc_peer_manager_dispatch_ready(webrtc_peer_manager_t *manager)
struct webrtc_peer_manager webrtc_peer_manager_t
For pending ice candidate, this is the live record that ties candidate, mid, next together....
@ WEBRTC_ROLE_CREATOR
Session creator - accepts offers, generates answers.
asciichat_error_t acip_handle_client_packet(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, const acip_client_callbacks_t *callbacks)
Client-side packet handler callbacks.
Definition handlers.c:182
ACIP protocol packet handlers (transport-agnostic).
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
@ HANDOFF_SAMPLE_DATA
Definition handoff.h:23
@ HANDOFF_SAMPLE_START
Definition handoff.h:22
🔊 Audio Capture and Playback Interface for ascii-chat
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Common declarations and data structures for cryptographic handshake.
Server-side handshake functions.
Statistics worker for error totals and memory reports. Signal handlers may only request a report.
📝 JSON structured logging output
ACIP client-side protocol API.
ascii-chat Binary Network Protocol (complete system including ACIP discovery service)
ACIP server-side protocol API.
Transport abstraction layer for ACIP protocol.
struct network_server network_server_t
struct network_connection network_connection_t
Network error handling utilities.
struct thread_pool thread_pool_t
One queued function call waiting for a thread-pool worker.
SIMD-optimized ASCII conversion interface.
Capture stdout/stderr and redirect to logging system.
🌍 IP Address Parsing and Formatting Utilities
void key_identity_announce(const char *label, const public_key_t *key)
void debug_stats_destroy(void)
void network_connection_request_stop(network_connection_t *c)
const network_server_config_t * network_server_config(network_server_t *s)
void * network_connection_context(network_connection_t *c)
acip_transport_t * network_connection_transport(network_connection_t *c)
asciichat_error_t network_server_adopt(network_server_t *s, acip_transport_t *transport, const char *peer, bool secure)
void network_server_request_stop(network_server_t *s)
asciichat_error_t network_connection_run(network_connection_t *c, const network_connection_callbacks_t *callbacks, void *context)
void network_server_foreach(network_server_t *s, network_connection_visit_fn visit, void *context)
void stats_gauge_set(stats_scope_t *scope, stats_gauge_id_t id, uint64_t value)
bool should_exit(void)
Definition main.c:248
Global application exit and signal handling API.
void platform_force_exit(int exit_code)
Definition misc.c:129
Multi-Source Audio Mixing and Processing System.
asciichat_error_t asciichat_mdns_advertise(asciichat_mdns_t *mdns, const asciichat_mdns_service_t *service)
Advertise a service on the local network.
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)
🌐 Core network I/O operations with timeout support
bool ui_notice_confirm_kind(ui_prompt_kind_t kind, ui_notice_severity_t severity, const char *text, unsigned timeout_seconds)
Definition notice.c:479
#define NOTICE(severity, title,...)
Definition notice.h:56
@ UI_NOTICE_DANGER
Definition notice.h:13
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
void rate_limiter_destroy(rate_limiter_t *limiter)
Destroy rate limiter and free resources.
Definition rate_limit.c:126
rate_limiter_t * rate_limiter_create_memory(void)
Create in-memory rate limiter.
Definition rate_limit.c:83
🚦 Rate limiting API with pluggable backends
struct rate_limiter_s rate_limiter_t
Opaque rate limiter handle.
Definition rate_limit.h:87
void stats_runtime_set_provider(stats_provider_fn provider, void *data)
Definition runtime.c:123
void stats_view_add_header(stats_view_t *view, const char *format,...)
Definition runtime.c:116
void stats_view_add(stats_view_t *view, const char *format,...)
Definition runtime.c:109
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:78
void log_search_signal_cancel(void)
Cancel grep mode from a signal handler (async-signal-safe).
Definition search.c:399
bool log_search_is_entering_atomic(void)
Check if grep is in entering mode (async-signal-safe).
Definition search.c:395
Interactive search filtering for terminal screens.
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 SERVER_MAIN_SESSION_NAME_BUFFER_SIZE
Definition server/main.c:7
size_t g_num_whitelisted_clients
Number of whitelisted clients.
h265_server_context_t *volatile g_h265_server
Global H.265 codec server context.
#define SERVER_MAIN_TURN_AUTH_CREDENTIAL_BUFFER_SIZE
Definition server/main.c:12
rate_limiter_t * g_rate_limiter
Global rate limiter for connection attempts and packet processing.
#define SERVER_MAIN_TXT_SESSION_STRING_BUFFER_SIZE
Definition server/main.c:8
bool g_server_encryption_enabled
Global flag indicating if server encryption is enabled.
mixer_t *volatile g_audio_mixer
Global audio mixer instance for multi-client audio processing.
int server_main(void)
server context keeps the values that move through the subsystem: network_server, rate_limiter,...
#define SERVER_MAIN_HEX_BUFFER_SIZE
Definition server/main.c:4
#define SERVER_MAIN_LABEL_BUFFER_SIZE
Definition server/main.c:10
#define SERVER_MAIN_TXT_HOST_PUBKEY_BUFFER_SIZE
Definition server/main.c:9
private_key_t g_server_identity_keys[MAX_SESSION_KEYS]
Global server identity keys array (multi-key support).
#define SERVER_MAIN_PARTICIPANT_BUFFER_SIZE
Definition server/main.c:6
public_key_t g_client_whitelist[MAX_CLIENTS]
Global client public key whitelist.
#define SERVER_MAIN_ASCII_BUFFER_SIZE
Definition server/main.c:5
private_key_t g_server_private_key
Global server private key (first identity key, for backward compatibility).
#define SERVER_MAIN_SESSION_STRING_BUFFER_SIZE
Definition server/main.c:3
size_t g_num_server_identity_keys
Number of loaded server identity keys.
static_cond_t g_shutdown_cond
Global shutdown condition variable for waking blocked threads.
#define SERVER_MAIN_TURN_AUTH_USERNAME_BUFFER_SIZE
Definition server/main.c:11
asciichat_mdns_t * session_server_like_get_mdns_ctx(void)
asciichat_error_t session_server_like_run(const session_server_like_config_t *config)
network_server_t * session_server_like_get_network_server(void)
nat_upnp_context_t * session_server_like_get_upnp_ctx(void)
struct session_server_like_config session_server_like_config_t
The useful part of session server like config is in [struct].mdns, [struct].upnp, init_fn,...
#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
uint8_t session_id[SESSION_ID_SIZE]
uint8_t participant_id[SESSION_ID_SIZE]
rwlock_t g_client_manager_rwlock
Reader-writer lock protecting the global client manager.
bool g_client_manager_rwlock_initialized
client_manager_t g_client_manager
Hash table entry for client packet dispatch.
int remove_client(server_context_t *server_ctx, const char *client_id)
Per-client state management and lifecycle orchestration.
void * stats_logger_thread(void *arg)
Main statistics collection and reporting thread function.
int stats_init(void)
Initialize the stats mutex.
mutex_t g_stats_mutex
Mutex protecting global server statistics.
void stats_cleanup(void)
Cleanup the stats mutex.
Server performance statistics tracking.
Multi-client video mixing and ASCII frame generation.
h265_server_context_t * h265_server_context_create(void)
void h265_server_context_destroy(h265_server_context_t *ctx)
struct h265_server_context h265_server_context_t
The useful part of h265 client decoder is in client_id, decoder, last_width, last_height: together th...
Server-side H.265 decoding pipeline for multi-client streams.
bool terminal_can_prompt_user(bool user_setting)
asciichat_error_t ui_status_gather(network_server_t *server, const char *session_string, const char *ipv4_address, const char *ipv6_address, uint16_t port, time_t start_time, const char *mode_name, bool session_is_mdns_only, ui_status_t *out_status)
Gather current status information.
Definition status.c:70
📊 Status screen display and management for server/discovery service modes
🔤 String Manipulation and Shell Escaping Utilities
acds client config is intentionally a small, concrete record. Fields such as server_port,...
char server_address[256]
ACDS server address (e.g., "discovery.ascii.chat" or "127.0.0.1").
uint32_t timeout_ms
Connection timeout in milliseconds.
uint16_t server_port
ACDS server port (default: 27225).
const char * identity_key
Optional private identity key path, borrowed during connect.
ACDS client connection handle.
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).
char server_address[64]
connect
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 creation result.
uint8_t session_id[16]
Session UUID.
char session_string[48+1]
Generated session string (null-terminated).
Session join parameters.
uint8_t identity_pubkey[32]
Participant's Ed25519 public key.
bool has_password
Password provided.
char password[128]
Password (if has_password).
const char * session_string
Session to join.
uint8_t identity_seckey[64]
Ed25519 secret key (for signing).
Session join result.
uint8_t participant_id[16]
Participant UUID (if success).
bool success
Join succeeded.
char error_message[128+1]
Error message (if !success, null-terminated).
uint8_t session_id[16]
Session UUID (if success).
Client-side packet handler callbacks.
Definition handlers.h:55
This is the handoff point for acip outbound stats. Callers fill application_bytes,...
struct acip_outbound * outbound
Per-connection plaintext admission and scheduling.
Service information for advertisement.
Owns one mDNS browse or advertisement session, including its socket, event-loop registration,...
Atomic value wrapper for integral/boolean types.
Definition atomic.h:76
video_frame_buffer_t * incoming_video_buffer
char client_id[MAX_CLIENT_ID_LEN]
uint8_t session[SESSION_ID_SIZE]
Definition handoff.h:35
uint8_t participant[SESSION_ID_SIZE]
Definition handoff.h:36
For ducking, this is the live record that ties threshold_dB, leader_margin_dB, atten_dB,...
Definition mixer.h:342
bool external_is_private
Gateway reported an upstream NAT; mapping remains locally usable.
Definition upnp.h:51
char external_ip[16]
Detected external/public IP (e.g., "203.0.113.42").
Definition upnp.h:35
Callbacks and operations used by network connection callbacks. Packet payloads are borrowed until ret...
Private identity-key material used for server authentication and signing.
Definition key_types.h:101
The normalized public identity used by ascii-chat's crypto and key-management code.
Definition key_types.h:76
Server context - encapsulates all server state.
network_server_t * network_server
Shared connection runtime.
server stats visit is intentionally a small, concrete record. Fields such as view,...
This is the handoff point for server discovery policy. Callers fill password, has_password,...
stats_view_t * view
Host-side event hooks for joins, departures, media, and errors.
Definition host.h:163
Static condition variable structure for global condition variables requiring static initialization.
unsigned page
Status information for server/discovery service modes.
Definition status.h:42
atomic_t total_frames_received
Total frames received (atomic counter).
Peer manager configuration.
Hooks that deliver local SDP offers/answers and ICE candidates to ACDS.
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.
🧵 Generic thread pool abstraction for managing worker threads
⏱️ High-precision timing utilities using sokol_time.h and uthash
asciichat_error_t nat_upnp_get_endpoint(const nat_upnp_context_t *ctx, char *ip, size_t ip_len, uint16_t *port)
Copy the unexpired mapped IP and external port for discovery advertisement.
Definition upnp.c:291
bool nat_upnp_is_active(const nat_upnp_context_t *ctx)
Check if port mapping is still active.
Definition upnp.c:280
UPnP/NAT-PMP port mapping for TCP and UDP connectivity.
struct nat_upnp_context nat_upnp_context_t
Handle to UPnP context.