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.h File Reference

Go to the source code of this file.

Data Structures

struct  server_context_t
 Server context - encapsulates all server state. More...

Typedefs

typedef struct server_context_t server_context_t
 Server context - encapsulates all server state.

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

atomic_t g_should_exit
 Global application exit flag (shared across all modes).
rate_limiter_t * g_rate_limiter
 Global connection rate limiter.
client_manager_t g_client_manager
 Global client manager.
rwlock_t g_client_manager_rwlock
 Read-write lock protecting client manager.
mixer_t *volatile g_audio_mixer
 Global audio mixer.
h265_server_context_t *volatile g_h265_server
 Global H.265 codec server context.
bool g_server_encryption_enabled
 Server encryption enabled flag.
private_key_t g_server_private_key
 Server's private key.
private_key_t g_server_identity_keys [MAX_SESSION_KEYS]
 Array of server identity keys.
size_t g_num_server_identity_keys
 Number of server identity keys in use.
public_key_t g_client_whitelist [MAX_CLIENTS]
 Whitelist of allowed client public keys.
size_t g_num_whitelisted_clients
 Number of whitelisted clients.

Typedef Documentation

◆ server_context_t

typedef struct server_context_t server_context_t

Server context - encapsulates all server state.

This structure holds all server-wide state that was previously stored in global variables. It's passed to client handlers via network runtime callback context, reducing global state and improving modularity.

DESIGN RATIONALE:

  • Reduces global state: All server state in one place
  • Improves testability: Can create multiple independent server instances
  • Better encapsulation: Clear ownership of resources
  • Thread-safe: Context is read-only after initialization

LIFETIME:

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
extern

Global audio mixer.

Volatile pointer to the multi-client audio mixer instance. Used to mix audio from multiple clients for playback.

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_manager

client_manager_t g_client_manager
extern

Global client manager.

Registry for all connected clients. Used to track client state, routing, and lifecycle management across server threads.

Global client manager.

Global client manager singleton - central coordination point

This is the primary data structure for managing all connected clients. It serves as the bridge between main.c's connection accept loop and the per-client threading architecture.

STRUCTURE COMPONENTS:

  • clients[]: Array backing storage for client_info_t structs
  • client_hashtable: O(1) lookup table for client_id -> client_info_t*
  • client_count: Current number of active clients
  • mutex: Legacy mutex (mostly replaced by rwlock)
  • next_client_id: Monotonic counter for unique client identification

THREAD SAFETY: Protected by g_client_manager_rwlock for concurrent access

Definition at line 192 of file src/server/client.c.

Referenced by add_transport_client(), any_clients_sending_video(), find_client_by_id(), send_server_state_to_client(), server_main(), and stats_logger_thread().

◆ g_client_manager_rwlock

rwlock_t g_client_manager_rwlock
extern

Read-write lock protecting client manager.

Protects concurrent access to g_client_manager from server threads. Use rwlock_rdlock() for reads, rwlock_wrlock() for writes.

Read-write lock protecting client manager.

This lock enables high-performance concurrent access patterns:

  • Multiple threads can read client data simultaneously (stats, rendering)
  • Only one thread can modify client data at a time (add/remove operations)
  • Eliminates contention between read-heavy operations

USAGE PATTERN:

  • Read operations: rwlock_rdlock() for client lookups, stats gathering
  • Write operations: rwlock_wrlock() for add_transport_client(), remove_client()
  • Always acquire THIS lock before per-client mutexes (lock ordering)

Definition at line 207 of file src/server/client.c.

207{0};

Referenced by add_transport_client(), find_client_by_id(), server_main(), and stats_logger_thread().

◆ g_client_whitelist

public_key_t g_client_whitelist[MAX_CLIENTS]
extern

Whitelist of allowed client public keys.

Array of allowed client Ed25519 public keys for authentication. Size is limited by MAX_CLIENTS.

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
extern

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.

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
extern

Number of server identity keys in use.

Tracks how many keys in g_server_identity_keys are valid.

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
extern

Number of whitelisted clients.

Tracks how many keys in g_client_whitelist are valid.

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
extern

Global connection rate limiter.

Shared rate limiter instance used by packet handlers to prevent DoS attacks. Tracks connection attempts and packet rates per IP address.

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
extern

Server encryption enabled flag.

Indicates whether end-to-end encryption is enabled for this server.

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]
extern

Array of server identity keys.

Additional server identity keys for multi-key support. Size is limited by MAX_SESSION_KEYS.

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
extern

Server's private key.

Server's Ed25519 private key used for digital signatures and key exchange.

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_should_exit

atomic_t g_should_exit
extern

Global application exit flag (shared across all modes).

Set by signal handlers to request graceful shutdown. Used by all server threads to check if they should exit their loops.

Global shutdown flag referenced by lib/logging.c and lib/debug/lock.c In production builds, this is defined in main.c and set during shutdown. For tests, we stub it out as false (tests don't perform shutdown).

Definition at line 31 of file globals.c.

31{0};