ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
main.c File Reference

Go to the source code of this file.

Data Structures

struct  server_stats_visit_t
struct  server_discovery_policy_t
 server stats visit is intentionally a small, concrete record. Fields such as view, active, queued give callers the identity and current value they need. It is normally borrowed from, or owned by, the surrounding subsystem—not independently managed. More...
struct  server_discovery_startup_t
 This is the handoff point for server discovery policy. Callers fill password, has_password, has_identity, explicit_expose before passing it on; consumers read the values during the operation and return ownership only where the member contract explicitly says they do. More...

Macros

#define SERVER_MAIN_SESSION_STRING_BUFFER_SIZE   64
#define SERVER_MAIN_HEX_BUFFER_SIZE   64
#define SERVER_MAIN_ASCII_BUFFER_SIZE   20
#define SERVER_MAIN_PARTICIPANT_BUFFER_SIZE   33
#define SERVER_MAIN_SESSION_NAME_BUFFER_SIZE   56
#define SERVER_MAIN_TXT_SESSION_STRING_BUFFER_SIZE   512
#define SERVER_MAIN_TXT_HOST_PUBKEY_BUFFER_SIZE   512
#define SERVER_MAIN_LABEL_BUFFER_SIZE   64
#define SERVER_MAIN_TURN_AUTH_USERNAME_BUFFER_SIZE   128
#define SERVER_MAIN_TURN_AUTH_CREDENTIAL_BUFFER_SIZE   128

Functions

int server_main (void)
 server context keeps the values that move through the subsystem: network_server, rate_limiter, client_manager, client_manager_rwlock. Some members are pointers into caller- or subsystem-owned memory, so lifetime follows the API that populated them rather than the struct copy itself.

Variables

mixer_t *volatile g_audio_mixer = NULL
 Global audio mixer instance for multi-client audio processing.
h265_server_context_t *volatile g_h265_server = NULL
 Global H.265 codec server context.
static_cond_t g_shutdown_cond = STATIC_COND_INIT
 Global shutdown condition variable for waking blocked threads.
rate_limiter_t * g_rate_limiter = NULL
 Global rate limiter for connection attempts and packet processing.
bool g_server_encryption_enabled = false
 Global flag indicating if server encryption is enabled.
private_key_t g_server_private_key = {0}
 Global server private key (first identity key, for backward compatibility).
private_key_t g_server_identity_keys [MAX_SESSION_KEYS] = {0}
 Global server identity keys array (multi-key support).
size_t g_num_server_identity_keys = 0
 Number of loaded server identity keys.
public_key_t g_client_whitelist [MAX_CLIENTS] = {0}
 Global client public key whitelist.
size_t g_num_whitelisted_clients = 0
 Number of whitelisted clients.

Macro Definition Documentation

◆ SERVER_MAIN_ASCII_BUFFER_SIZE

#define SERVER_MAIN_ASCII_BUFFER_SIZE   20

Definition at line 5 of file server/main.c.

◆ SERVER_MAIN_HEX_BUFFER_SIZE

#define SERVER_MAIN_HEX_BUFFER_SIZE   64

Definition at line 4 of file server/main.c.

◆ SERVER_MAIN_LABEL_BUFFER_SIZE

#define SERVER_MAIN_LABEL_BUFFER_SIZE   64

Definition at line 10 of file server/main.c.

◆ SERVER_MAIN_PARTICIPANT_BUFFER_SIZE

#define SERVER_MAIN_PARTICIPANT_BUFFER_SIZE   33

Definition at line 6 of file server/main.c.

◆ SERVER_MAIN_SESSION_NAME_BUFFER_SIZE

#define SERVER_MAIN_SESSION_NAME_BUFFER_SIZE   56

Definition at line 7 of file server/main.c.

◆ SERVER_MAIN_SESSION_STRING_BUFFER_SIZE

#define SERVER_MAIN_SESSION_STRING_BUFFER_SIZE   64

Definition at line 3 of file server/main.c.

◆ SERVER_MAIN_TURN_AUTH_CREDENTIAL_BUFFER_SIZE

#define SERVER_MAIN_TURN_AUTH_CREDENTIAL_BUFFER_SIZE   128

Definition at line 12 of file server/main.c.

◆ SERVER_MAIN_TURN_AUTH_USERNAME_BUFFER_SIZE

#define SERVER_MAIN_TURN_AUTH_USERNAME_BUFFER_SIZE   128

Definition at line 11 of file server/main.c.

◆ SERVER_MAIN_TXT_HOST_PUBKEY_BUFFER_SIZE

#define SERVER_MAIN_TXT_HOST_PUBKEY_BUFFER_SIZE   512

Definition at line 9 of file server/main.c.

◆ SERVER_MAIN_TXT_SESSION_STRING_BUFFER_SIZE

#define SERVER_MAIN_TXT_SESSION_STRING_BUFFER_SIZE   512

Definition at line 8 of file server/main.c.

Function Documentation

◆ server_main()

int server_main ( void )

server context keeps the values that move through the subsystem: network_server, rate_limiter, client_manager, client_manager_rwlock. Some members are pointers into caller- or subsystem-owned memory, so lifetime follows the API that populated them rather than the struct copy itself.

Server mode entry point for unified binary

This function implements the complete server lifecycle including:

  • Server-specific initialization (crypto, shutdown callback)
  • Network socket setup and binding
  • Main connection accept loop
  • Client lifecycle management
  • Graceful shutdown and cleanup

Options are already parsed by the main dispatcher before this function is called, so they are available via global opt_* variables.

Returns
0 on success, non-zero error code on failure
Example
# Invoked by dispatcher after options are parsed:
ascii-chat server --port 8080
# Options parsed in main.c, then server_main() called

Definition at line 2050 of file server/main.c.

2050 {
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}
#define LOG_ERRNO_IF_SET(message)
#define ATOMIC_REGISTER_AUTO(name, parent_ptr)
Register an atomic variable for debug tracking with automatic name generation.
Definition atomic.h:469
const network_connection_callbacks_t server_network_callbacks
atomic_t g_should_exit
Global application exit flag (shared across all modes).
Definition globals.c:31
#define FATAL(code,...)
Exit with error code and custom message, with stack trace in debug builds.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_CRYPTO
Definition error_codes.h:97
@ ERROR_THREAD
#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 GET_OPTION(field)
Definition options.h:1333
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.
void shutdown_register_callback(shutdown_check_fn callback)
Register application's shutdown check function.
Definition common.c:78
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.
size_t g_num_whitelisted_clients
Number of whitelisted clients.
rate_limiter_t * g_rate_limiter
Global rate limiter for connection attempts and packet processing.
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.
public_key_t g_client_whitelist[MAX_CLIENTS]
Global client public key whitelist.
private_key_t g_server_private_key
Global server private key (first identity key, for backward compatibility).
asciichat_error_t session_server_like_run(const session_server_like_config_t *config)
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,...
rwlock_t g_client_manager_rwlock
Reader-writer lock protecting the global client manager.
client_manager_t g_client_manager
Hash table entry for client packet dispatch.
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.
Server context - encapsulates all server state.
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.

References ascii_simd_init(), ASCIICHAT_OK, ATOMIC_REGISTER_AUTO, ERROR_CONFIG, ERROR_CRYPTO, ERROR_MEMORY, ERROR_THREAD, FATAL, g_audio_mixer, g_client_manager, g_client_manager_rwlock, g_client_whitelist, g_num_whitelisted_clients, g_rate_limiter, g_server_encryption_enabled, g_server_private_key, g_should_exit, g_stats_mutex, GET_OPTION, log_debug, LOG_ERRNO_IF_SET, log_error, log_info, precalc_rgb_palettes(), server_network_callbacks, session_server_like_run(), shutdown_register_callback(), stats_init(), stats_logger_thread(), thread_pool_create(), thread_pool_spawn(), weight_blue, weight_green, and weight_red.

Variable Documentation

◆ g_audio_mixer

mixer_t* volatile g_audio_mixer = NULL

Global audio mixer instance for multi-client audio processing.

Global audio mixer.

The mixer combines audio streams from multiple clients, excluding each client's own audio from their outbound stream (preventing echo). Created once during server initialization and shared by all audio render threads.

THREAD SAFETY: The mixer itself is thread-safe and can be used concurrently by multiple render.c audio threads without external synchronization. During shutdown, set to NULL before destroying to prevent use-after-free.

Definition at line 204 of file server/main.c.

Referenced by client_audio_render_thread(), and server_main().

◆ g_client_whitelist

public_key_t g_client_whitelist[MAX_CLIENTS] = {0}

Global client public key whitelist.

Whitelist of allowed client public keys.

Array of public keys for clients that are authorized to connect to the server. Used for client authentication when whitelist mode is enabled. Sized to hold up to MAX_CLIENTS entries.

Note
Only used when client authentication is enabled
Accessed from crypto.c for client authentication

Definition at line 430 of file server/main.c.

430{0};

Referenced by server_main().

◆ g_h265_server

h265_server_context_t* volatile g_h265_server = NULL

Global H.265 codec server context.

Shared H.265 decoding context used by all packet handlers to decode client H.265 frames. Each client gets its own decoder instance.

THREAD SAFETY: The h265_server context is thread-safe and can be used concurrently by multiple client handlers. Decoders are per-client. During shutdown, set to NULL before destroying to prevent use-after-free.

Definition at line 216 of file server/main.c.

Referenced by handle_image_frame_h265_packet().

◆ g_num_server_identity_keys

size_t g_num_server_identity_keys = 0

Number of loaded server identity keys.

Number of server identity keys in use.

Tracks how many identity keys were successfully loaded from –key flags. Zero means server is running in simple mode (no identity key).

Definition at line 417 of file server/main.c.

◆ g_num_whitelisted_clients

size_t g_num_whitelisted_clients = 0

Number of whitelisted clients.

Tracks the current number of entries in g_client_whitelist that are valid and active. Used to iterate the whitelist and check authorization.

Definition at line 440 of file server/main.c.

Referenced by server_main().

◆ g_rate_limiter

rate_limiter_t* g_rate_limiter = NULL

Global rate limiter for connection attempts and packet processing.

Global connection rate limiter.

In-memory rate limiter to prevent connection flooding and DoS attacks. Tracks connection attempts and packet rates per IP address with configurable limits.

Default limits (from rate_limit.c):

  • RATE_EVENT_CONNECTION: 50 connections per 60 seconds
  • RATE_EVENT_IMAGE_FRAME: 144 FPS (8640 frames/min)
  • RATE_EVENT_AUDIO: 172 FPS (10320 packets/min)
  • RATE_EVENT_PING: 2 Hz (120 pings/min)
  • RATE_EVENT_CLIENT_JOIN: 10 joins per 60 seconds
  • RATE_EVENT_CONTROL: 100 control packets per 60 seconds

THREAD SAFETY: The rate limiter is thread-safe and can be used concurrently from the main accept loop and packet handlers without external synchronization.

See also
main.h for extern declaration

Definition at line 246 of file server/main.c.

Referenced by process_decrypted_packet(), and server_main().

◆ g_server_encryption_enabled

bool g_server_encryption_enabled = false

Global flag indicating if server encryption is enabled.

Server encryption enabled flag.

Set to true when the server is configured to use encryption and has successfully loaded a private key. Controls whether the server performs cryptographic handshakes with clients.

Note
Accessed from crypto.c for server-side crypto operations

Definition at line 381 of file server/main.c.

Referenced by server_main().

◆ g_server_identity_keys

private_key_t g_server_identity_keys[MAX_SESSION_KEYS] = {0}

Global server identity keys array (multi-key support).

Array of server identity keys.

Stores all server identity keys loaded from multiple –key flags. Enables servers to present different keys (SSH, GPG) based on client expectations. Server selects the appropriate key during handshake based on what the client downloaded from ACDS.

Note
g_server_private_key points to g_server_identity_keys[0] for compatibility

Definition at line 407 of file server/main.c.

407{0};

◆ g_server_private_key

private_key_t g_server_private_key = {0}

Global server private key (first identity key, for backward compatibility).

Server's private key.

Stores the server's primary private key loaded from the first –key flag. Used for cryptographic handshakes and packet encryption/decryption. Initialized during server startup from the configured key file path.

Note
This is an alias to g_server_identity_keys[0] for backward compatibility
Accessed from crypto.c for server-side crypto operations

Definition at line 394 of file server/main.c.

394{0};

Referenced by server_main().

◆ g_shutdown_cond

static_cond_t g_shutdown_cond = STATIC_COND_INIT

Global shutdown condition variable for waking blocked threads.

Used to wake up threads that might be blocked on condition variables (like packet queues) during shutdown. This ensures responsive shutdown even when threads are waiting on blocking operations.

Definition at line 225 of file server/main.c.