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

WebSocket server implementation. More...

Go to the source code of this file.

Data Structures

struct  websocket_connection_data_t
 Libwebsockets callback state for one ACIP WebSocket connection. More...

Macros

#define NETWORK_WEBSOCKET_SERVER_WS_TRANSPORT_NAME_BUFFER_SIZE   64
#define NETWORK_WEBSOCKET_SERVER_PROTO_VER_BUFFER_SIZE   16
#define NETWORK_WEBSOCKET_SERVER_SSL_ERR_BUFFER_SIZE   256
#define NETWORK_WEBSOCKET_SERVER_WS_PORT_NAME_BUFFER_SIZE   32
#define R_OK   4

Functions

asciichat_error_t websocket_server_init (websocket_server_t *server, const websocket_server_config_t *config)
 Initialize WebSocket server.
asciichat_error_t websocket_server_run (websocket_server_t *server)
 Run WebSocket server event loop.
void websocket_server_cancel_service (websocket_server_t *server)
 Wake the WebSocket server event loop immediately.
void websocket_server_destroy (websocket_server_t *server)
 Destroy WebSocket server and free resources.

Detailed Description

WebSocket server implementation.

Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
February 2026

Definition in file lib/network/websocket/server.c.

Macro Definition Documentation

◆ NETWORK_WEBSOCKET_SERVER_PROTO_VER_BUFFER_SIZE

#define NETWORK_WEBSOCKET_SERVER_PROTO_VER_BUFFER_SIZE   16

Definition at line 12 of file lib/network/websocket/server.c.

◆ NETWORK_WEBSOCKET_SERVER_SSL_ERR_BUFFER_SIZE

#define NETWORK_WEBSOCKET_SERVER_SSL_ERR_BUFFER_SIZE   256

Definition at line 13 of file lib/network/websocket/server.c.

Referenced by websocket_server_init().

◆ NETWORK_WEBSOCKET_SERVER_WS_PORT_NAME_BUFFER_SIZE

#define NETWORK_WEBSOCKET_SERVER_WS_PORT_NAME_BUFFER_SIZE   32

Definition at line 14 of file lib/network/websocket/server.c.

Referenced by websocket_server_init().

◆ NETWORK_WEBSOCKET_SERVER_WS_TRANSPORT_NAME_BUFFER_SIZE

#define NETWORK_WEBSOCKET_SERVER_WS_TRANSPORT_NAME_BUFFER_SIZE   64

Definition at line 11 of file lib/network/websocket/server.c.

◆ R_OK

#define R_OK   4

Definition at line 49 of file lib/network/websocket/server.c.

Referenced by websocket_server_init().

Function Documentation

◆ websocket_server_cancel_service()

void websocket_server_cancel_service ( websocket_server_t * server)

Wake the WebSocket server event loop immediately.

Thread-safe. Wakes lws_service() from its timeout wait, allowing the event loop to check the running flag without waiting for the full service timeout (50ms).

Parameters
serverServer instance (must have a valid context)

Definition at line 835 of file lib/network/websocket/server.c.

835 {
836 if (server && server->context) {
837 lws_cancel_service(server->context);
838 }
839}
struct lws_context * context
libwebsockets context

References websocket_server::context.

Referenced by network_server_stop().

◆ websocket_server_destroy()

void websocket_server_destroy ( websocket_server_t * server)

Destroy WebSocket server and free resources.

Parameters
serverServer instance to destroy

Definition at line 841 of file lib/network/websocket/server.c.

841 {
842 if (!server) {
843 return;
844 }
845
846 atomic_store_bool(&server->running, false);
847
848 // Cancel any pending libwebsockets service calls to interrupt blocking lws_service()
849 // This prevents the event loop from getting stuck in lws_service()
850 if (server->context) {
851 log_debug("Cancelling libwebsockets service");
852 lws_cancel_service(server->context);
853 }
854
855 // Unregister atomic fields
856 NAMED_UNREGISTER(&server->running);
857
858 if (server->context) {
859 NAMED_UNREGISTER(server->context);
860 lws_context_destroy(server->context);
861 server->context = NULL;
862 }
863 if (server->handler_pool) {
865 server->handler_pool = NULL;
866 }
867
868 log_debug("WebSocket server destroyed");
869}
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
struct thread_pool * handler_pool
Thread pool for queueing handler work.
void thread_pool_destroy(thread_pool_t *pool)
Destroy a thread pool.

References atomic_store_bool(), websocket_server::context, websocket_server::handler_pool, log_debug, NAMED_UNREGISTER, websocket_server::running, and thread_pool_destroy().

Referenced by network_server_stop().

◆ websocket_server_init()

asciichat_error_t websocket_server_init ( websocket_server_t * server,
const websocket_server_config_t * config )

Initialize WebSocket server.

Creates libwebsockets context and prepares for accepting connections.

Parameters
serverServer instance to initialize
configServer configuration
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 677 of file lib/network/websocket/server.c.

677 {
678 if (!server || !config || !config->client_handler) {
679 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
680 }
681
682 memset(server, 0, sizeof(*server));
683 server->handler = config->client_handler;
684 server->user_data = config->user_data;
685 server->port = config->port;
686 atomic_store_bool(&server->running, true);
687
688 // Store server pointer in protocol user data so callbacks can access it
689 websocket_protocols[0].user = server; // http protocol
690 websocket_protocols[1].user = server; // acip protocol
691
692 // Enable libwebsockets logging through centralized logging system
694
695 // HTTP mount for /health endpoint (required for LWS_CALLBACK_HTTP to fire)
696 static const struct lws_http_mount health_mount = {
697 .mount_next = NULL,
698 .mountpoint = "/",
699 .mountpoint_len = 1,
700 .origin = "http",
701 .def = NULL,
702 .protocol = "http",
703 .origin_protocol = LWSMPRO_CALLBACK,
704 };
705
706 // Configure libwebsockets context
707 struct lws_context_creation_info info = {0};
708 info.port = config->port;
709 info.iface = config->bind_address;
710 info.protocols = websocket_protocols;
711 info.mounts = &health_mount;
712 info.gid = (gid_t)-1; // Cast to avoid undefined behavior with unsigned type
713 info.uid = (uid_t)-1; // Cast to avoid undefined behavior with unsigned type
714 info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; // Initialize SSL/TLS support (required for server binding)
715 info.extensions = NULL; // Disable permessage-deflate - causing connection issues
716 info.retry_and_idle_policy = &keep_alive_policy; // Configure keep-alive to prevent idle disconnects during handshake
717
718 // Configure TLS/WSS support if certificates are provided (check for non-empty strings)
719 if (config->tls_cert_path && config->tls_cert_path[0] != '\0' && config->tls_key_path && config->tls_key_path[0] != '\0') {
720#ifdef LWS_WITH_TLS
721 // Validate certificate and key files are readable
722 if (platform_access(config->tls_cert_path, R_OK) != 0) {
723 return SET_ERRNO(ERROR_NETWORK_BIND, "TLS certificate file not readable: %s (errno=%d)", config->tls_cert_path, errno);
724 }
725 if (platform_access(config->tls_key_path, R_OK) != 0) {
726 return SET_ERRNO(ERROR_NETWORK_BIND, "TLS key file not readable: %s (errno=%d)", config->tls_key_path, errno);
727 }
728
729 info.ssl_cert_filepath = config->tls_cert_path;
730 info.ssl_private_key_filepath = config->tls_key_path;
731 server->tls_enabled = true;
732 log_info("WebSocket server configured for WSS (TLS): cert=%s, key=%s", config->tls_cert_path, config->tls_key_path);
733#else
734 log_warn("WebSocket server: TLS support not compiled in libwebsockets; WSS unavailable");
735#endif
736 } else if ((config->tls_cert_path && config->tls_cert_path[0] != '\0') || (config->tls_key_path && config->tls_key_path[0] != '\0')) {
737 NOTICE(DANGER, "WEBSOCKET TLS DISABLED", "WebSocket server: Both TLS certificate and key must be provided for WSS; using plain WS");
738 }
739
740 // Increase per-thread service buffer to prevent fragmentation of large messages
741 // Default is 4KB, causing large frames to fragment into many chunks
742 // Video frames are 921KB, so increase to 2MB to handle them without fragmentation
743 info.pt_serv_buf_size = 2 * 1024 * 1024; // 2MB per-thread service buffer
744
745 // Disable ALL default timeouts and keep-alive mechanisms
746 // Use only the explicit retry_and_idle_policy we set above (30/35 seconds)
747 info.ka_time = 0; // Disable TCP keep-alive probes (use WebSocket pings instead)
748 info.ka_probes = 0; // Disable TCP probes
749 info.ka_interval = 0; // Disable TCP probe intervals
750 info.keepalive_timeout = 0; // Disable HTTP keep-alive timeout entirely
751
752 // Explicitly set a very large idle timeout to prevent early disconnection
753 // Without this, libwebsockets defaults to 5 seconds for HTTP connections
754 // Set to effectively infinite (100 hours) since we use retry_and_idle_policy instead
755 info.timeout_secs = 360000; // 100 hours - effectively disabled
756
757 // Create libwebsockets context
758 // Log diagnostic info before attempting creation
759 log_debug("lws_create_context: port=%u, protocols=%p, options=0x%x", info.port, (void *)info.protocols, info.options);
760
761 server->context = lws_create_context(&info);
762 if (!server->context) {
763 // Capture any OpenSSL errors that may have occurred during context creation
764 unsigned long ssl_err = 0;
765 char ssl_err_str[NETWORK_WEBSOCKET_SERVER_SSL_ERR_BUFFER_SIZE] = "no OpenSSL errors in queue";
766
767 // Extract all errors from OpenSSL error queue
768 while ((ssl_err = ERR_get_error()) != 0) {
769 ERR_error_string_n(ssl_err, ssl_err_str, sizeof(ssl_err_str));
770 log_error("OpenSSL error: %lu: %s", ssl_err, ssl_err_str);
771 }
772
773 return SET_ERRNO(ERROR_NETWORK_BIND, "Failed to create libwebsockets context (last OpenSSL error: %s)", ssl_err_str);
774 }
775
776 // Each connection owns a handler until disconnect; provide a worker for every participant.
778
779 if (!server->handler_pool) {
780 lws_context_destroy(server->context);
781 server->context = NULL;
782 return SET_ERRNO(ERROR_THREAD, "Failed to create WebSocket handler thread pool");
783 }
784
785 /* Register WebSocket server with named registry */
787 snprintf(ws_port_name, sizeof(ws_port_name), "ws:%d", server->port);
788 NAMED_REGISTER(server, ws_port_name, "websocket_server", "0x%tx", NULL);
789
790 /* Register server's sync primitives with hierarchical naming */
791 NAMED_REGISTER_ATOMIC(&server->running, "is_running", (uintptr_t)(const void *)(server));
792
793 /* Register WebSocket context as child of server */
794 NAMED_REGISTER_WEBSOCKET(server->context, "context", (uintptr_t)(const void *)(server));
795
796 log_info("WebSocket server initialized on port %d with static file serving", config->port);
797 return ASCIICHAT_OK;
798}
#define SET_ERRNO(code,...)
int platform_access(const char *pathname, int mode)
Definition filesystem.c:95
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
#define NAMED_REGISTER(ptr, name, type, fmt, parent_ptr)
Register any pointer with base name, type, format spec, and location (auto-suffix).
#define NAMED_REGISTER_WEBSOCKET(websocket, name, parent_ptr)
Register a WebSocket connection with automatic format specifier.
@ ERROR_NETWORK_BIND
Definition error_codes.h:77
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_THREAD
#define MAX_SESSION_PARTICIPANTS
#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 NETWORK_WEBSOCKET_SERVER_WS_PORT_NAME_BUFFER_SIZE
#define NETWORK_WEBSOCKET_SERVER_SSL_ERR_BUFFER_SIZE
#define NOTICE(severity, title,...)
Definition notice.h:56
websocket_client_handler_fn client_handler
Handler for new connections.
const char * bind_address
Numeric local address to listen on (never a wildcard by default).
const char * tls_cert_path
TLS certificate file path (optional, for wss://).
const char * tls_key_path
TLS private key file path (optional, for wss://).
websocket_client_handler_fn handler
Client handler function.
bool tls_enabled
True when this listener is configured with TLS credentials.
thread_pool_t * thread_pool_create_with_workers(const char *pool_name, size_t num_workers)
Create a new thread pool in work queue mode.
void lws_log_init_server(void)
Initialize libwebsockets logging for server mode.
Definition websocket.c:87

References ASCIICHAT_OK, atomic_store_bool(), websocket_server_config_t::bind_address, websocket_server_config_t::client_handler, websocket_server::context, ERROR_INVALID_PARAM, ERROR_NETWORK_BIND, ERROR_THREAD, websocket_server::handler, websocket_server::handler_pool, log_debug, log_error, log_info, log_warn, lws_log_init_server(), MAX_SESSION_PARTICIPANTS, NAMED_REGISTER, NAMED_REGISTER_ATOMIC, NAMED_REGISTER_WEBSOCKET, NETWORK_WEBSOCKET_SERVER_SSL_ERR_BUFFER_SIZE, NETWORK_WEBSOCKET_SERVER_WS_PORT_NAME_BUFFER_SIZE, NOTICE, platform_access(), websocket_server::port, websocket_server_config_t::port, R_OK, websocket_server::running, SET_ERRNO, thread_pool_create_with_workers(), websocket_server_config_t::tls_cert_path, websocket_server::tls_enabled, websocket_server_config_t::tls_key_path, websocket_server::user_data, and websocket_server_config_t::user_data.

Referenced by network_server_create().

◆ websocket_server_run()

asciichat_error_t websocket_server_run ( websocket_server_t * server)

Run WebSocket server event loop.

Blocks until server is signaled to stop via running flag.

Parameters
serverServer instance
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 800 of file lib/network/websocket/server.c.

800 {
801 if (!server || !server->context) {
802 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid server");
803 }
804
805 log_info("WebSocket server starting event loop on port %d", server->port);
806
807 // Run libwebsockets event loop
808 uint64_t last_service_ns = 0;
809 int service_call_count = 0;
810 while (atomic_load_bool(&server->running)) {
811 // Service libwebsockets with 16ms timeout to match 60 FPS frame rate.
812 // This provides frequent event processing (~60 callback invocations per second) so that
813 // WebSocket frames queued by the render loop are sent promptly, matching TCP performance.
814 // All client connections share this single server context, so a single lws_service() call
815 // services fragments and events for all clients simultaneously.
816 uint64_t service_start_ns = time_get_ns();
817 if (last_service_ns && service_start_ns - last_service_ns > 30 * US_PER_MS_INT) {
818 // > 30ms gap between service calls
819 double gap_ms = (double)(service_start_ns - last_service_ns) / 1e6;
820 log_debug_every(US_PER_SEC_INT, "[LWS_SERVICE_GAP] %.1fms gap between lws_service calls", gap_ms);
821 }
822 service_call_count++;
823 log_debug_every(500 * US_PER_MS_INT, "[LWS_SERVICE] Call #%d, context=%s", service_call_count, NAMED_DESCRIBE(server->context, "websocket_server"));
824 int result = lws_service(server->context, 1);
825 if (result < 0) {
826 log_error("libwebsockets service error: %d", result);
827 break;
828 }
829 }
830
831 log_info("WebSocket server event loop exited (context will be destroyed by main thread after handler threads complete)");
832 return ASCIICHAT_OK;
833}
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
unsigned long long uint64_t
#define NAMED_DESCRIBE(ptr, hint)
Describe a pointer in log format.
#define US_PER_MS_INT
Definition time.h:176
#define US_PER_SEC_INT
Definition time.h:177
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:743

References ASCIICHAT_OK, atomic_load_bool(), websocket_server::context, ERROR_INVALID_PARAM, log_debug_every, log_error, log_info, NAMED_DESCRIBE, websocket_server::port, websocket_server::running, SET_ERRNO, US_PER_MS_INT, and US_PER_SEC_INT.