ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
websocket/transport.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define NETWORK_WEBSOCKET_TRANSPORT_SSL_ERR_BUFFER_SIZE 256
4#define NETWORK_WEBSOCKET_TRANSPORT_RECV_NAME_BUFFER_SIZE 64
5#define NETWORK_WEBSOCKET_TRANSPORT_STATE_NAME_BUFFER_SIZE 64
6#define NETWORK_WEBSOCKET_TRANSPORT_SEND_NAME_BUFFER_SIZE 64
7
9#include <recast/defer.h>
10#include <ascii-chat/util/url.h>
41
48#include <ascii-chat/log/log.h>
51#include <ascii-chat/buffer.h>
52#include <libplatform/mutex.h>
53#include <libplatform/cond.h>
54#include <libplatform/system.h>
57#include <libwebsockets.h>
58#include <openssl/err.h>
59#include <string.h>
60#include <unistd.h>
61#include <pthread.h>
62#include <errno.h>
63#include <limits.h>
64
72#define WEBSOCKET_MESSAGE_QUEUE_SIZE_INCOMING 64
73
81#define WEBSOCKET_MESSAGE_QUEUE_SIZE_OUTGOING 512
82
83// Legacy names for backward compatibility
84#define WEBSOCKET_RECV_QUEUE_SIZE WEBSOCKET_MESSAGE_QUEUE_SIZE_INCOMING
85#define WEBSOCKET_SEND_QUEUE_SIZE WEBSOCKET_MESSAGE_QUEUE_SIZE_OUTGOING
86
87// Shared internal types (websocket_recv_msg_t, websocket_transport_data_t)
89
90// Forward declaration for libwebsockets callback
91static int websocket_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len);
92
93// REMOVED: lws_service_with_timeout() was creating a race condition
94// by spawning multiple threads that all call lws_service() on the same context.
95// LibWebSockets is NOT thread-safe for concurrent calls.
96//
97// Instead: Service thread calls lws_service(1) directly in a tight loop.
98// timeout=1 means: block up to 1ms on internal poll(), then return.
99// This is fast enough to keep 60fps (16.6ms per frame budget) while
100// letting the TLS state machine progress incrementally.
101
102// =============================================================================
103// Service Thread (Client-side only)
104// =============================================================================
105
109static bool websocket_schedule_client_write(websocket_transport_data_t *ws_data, int loop_count) {
110 // Check if THIS transport (client or server) has data queued to send
111 // Note: we only check for CLIENT transports here (owns_context=true)
112 // because SERVER transports are already handled by the SERVER_WRITEABLE callback.
113 // Clients need explicit triggering via lws_callback_on_writable().
114 if (ws_data->owns_context && ws_data->wsi) {
115 if (loop_count <= 10) {
116 log_debug_every(US_PER_SEC_INT, "[LOOP %d] CLIENT condition TRUE - checking queue", loop_count);
117 }
118
119 // Wait for connection to be established before sending
120 // The CLIENT_ESTABLISHED callback sets is_connected = true
121 // If we try to send before handshake completes, lws_write() fails
122 mutex_lock(&ws_data->state_mutex);
123 bool connected = ws_data->is_connected;
124 mutex_unlock(&ws_data->state_mutex);
125
126 if (!connected) {
127 if (loop_count <= 10) {
128 log_debug_every(US_PER_SEC_INT, "[LOOP %d] CLIENT not connected yet, skipping queue drain", loop_count);
129 }
130
131 // Check if connection attempt failed (CONNECTION_ERROR was called)
132 // If so, break from service loop to avoid indefinite retry
133 mutex_lock(&ws_data->state_mutex);
134 bool failed = ws_data->connection_failed;
135 mutex_unlock(&ws_data->state_mutex);
136
137 if (loop_count <= 50) {
138 log_debug_every(US_PER_SEC_INT, "[LOOP %d] Connection failed check: %d", loop_count, failed);
139 }
140
141 if (failed) {
142 log_debug_every(US_PER_SEC_INT, "[LOOP %d] Connection attempt failed, exiting service thread", loop_count);
143 return false;
144 }
145
146 // Do NOT sleep here - let lws_service() loop control timing
147 // During TLS handshake, lws_service() needs to be called every 100us
148 // Sleeping here blocks that and causes the handshake to stall
149 } else {
150 // This is a CLIENT transport - request WRITEABLE callback to send queued messages
151 // lws_write() must be called from within LWS callbacks, not from external threads
152
153 // Only request writeable callback when there is data queued to send.
154 // Unconditionally requesting on every loop iteration causes a tight spam loop
155 // of LWS_CALLBACK_CLIENT_WRITEABLE callbacks (~300/s), flooding logs and causing
156 // deadlocks when stderr pipe fills and blocks the service thread while holding
157 // the log mutex (other threads that try to log then deadlock).
158 mutex_lock(&ws_data->send_mutex);
159 bool has_data = !ringbuffer_is_empty(ws_data->send_queue);
160
161 if (loop_count <= 10) {
162 log_debug_every(US_PER_SEC_INT, "[LOOP %d] Queue check: has_data=%d", loop_count, has_data);
163 }
164
165 if (has_data) {
166 lws_callback_on_writable(ws_data->wsi);
167 }
168
169 mutex_unlock(&ws_data->send_mutex);
170
171 if (loop_count <= 10 && has_data) {
172 log_debug_every(US_PER_SEC_INT, ">>> SERVICE_THREAD: CLIENT queue has data (callback will process it)");
173 }
174 } // End of if (connected) block
175 } else {
176 if (loop_count <= 10) {
177 log_debug_every(US_PER_SEC_INT, "[LOOP %d] CLIENT condition FALSE (owns_context=%d, wsi=%p)", loop_count, ws_data->owns_context, (void *)ws_data->wsi);
178 }
179 }
180
181 return true;
182}
183
190static void *websocket_service_thread(void *arg) {
192
193 log_debug_every(US_PER_SEC_INT, ">>> SERVICE_THREAD_START: owns_context=%d, wsi=%p, context=%p, send_queue=%p", ws_data->owns_context, (void *)ws_data->wsi, (void *)ws_data->context,
194 (void *)ws_data->send_queue);
195
196 int loop_count = 0;
197 uint64_t last_service_call = 0; // Force lws_service() on first iteration
198
199 while (!atomic_load_bool(&ws_data->is_destroying)) {
200 loop_count++;
201
202 // Check if we're destroying FIRST before doing anything else
203 // This prevents accessing invalid pointers or contexts
204 if (atomic_load_bool(&ws_data->is_destroying) || !ws_data->context) {
205 if (loop_count <= 10) {
206 log_debug_every(US_PER_SEC_INT, "[LOOP %d] Destroying flag set or context NULL, exiting service thread", loop_count);
207 }
208 break;
209 }
210
211 // ALWAYS log first 10 loops to debug why queue checks aren't working
212 if (loop_count <= 10) {
213 log_debug_every(US_PER_SEC_INT, "[LOOP %d] owns_context=%d, wsi=%p, service_running=%d", loop_count, ws_data->owns_context, (void *)ws_data->wsi, ws_data->service_running);
214 }
215
216 if (!websocket_schedule_client_write(ws_data, loop_count)) {
217 break;
218 }
219
220 // Service libwebsockets (processes network events, triggers callbacks)
221 // Call frequently to handle both incoming AND outgoing data responsively
222 // During TLS handshake: every 100us (1/10 of 1ms) for rapid protocol progression
223 // During data transfer: every 1ms to balance responsiveness vs CPU usage
224 uint64_t now_ns = time_get_ns();
225 uint64_t time_since_last_service = now_ns - last_service_call;
226 int result = 0;
227
228 // Call lws_service() frequently during handshake, less frequently after connection
229 // Use 100us interval during handshake, 1ms after connected
230 uint64_t service_interval = ws_data->is_connected ? 1000000ULL : 100000ULL; // 1ms : 100us
231
232 if (loop_count <= 10) {
233 log_debug_every(US_PER_SEC_INT, "[LOOP %d] Timing check: time_since_last=%lu us, interval=%lu us, will_service=%d", loop_count, time_since_last_service / 1000, service_interval / 1000,
234 (int)(time_since_last_service >= service_interval));
235 }
236
237 if (time_since_last_service >= service_interval) {
238 last_service_call = now_ns;
239 uint64_t service_start_ns = now_ns;
240
241 bool is_destroying = atomic_load_bool(&ws_data->is_destroying);
242 if (!ws_data->context || is_destroying) {
243 // Context is invalid or being destroyed, don't call lws_service
244 if (loop_count <= 50) {
245 log_debug_every(US_PER_SEC_INT, "[LOOP %d] Skipping lws_service: context=%p, destroying=%d", loop_count, (void *)ws_data->context, (int)is_destroying);
246 }
247 } else {
248 // Call lws_service with short timeout (1ms)
249 // This lets lws_service() block briefly on internal poll() if there's no socket activity,
250 // but returns quickly to let service loop continue if needed.
251 // 1ms timeout is short enough to maintain 60fps (16.6ms per frame) while being responsive.
252 //
253 // Why timeout=1, not timeout=0?
254 // - timeout=0: select() returns immediately, but TLS state machine might not progress
255 // - timeout=1: select() blocks up to 1ms for socket events, letting TLS negotiate faster
256 // while still being responsive to multiple service calls per frame
257 if (loop_count <= 10) {
258 log_debug_every(US_PER_SEC_INT, "[LOOP %d] >>> CALLING lws_service() NOW (is_connected=%d, wsi=%p, timeout=1ms)", loop_count, ws_data->is_connected, (void *)ws_data->wsi);
259 }
260
261 result = lws_service(ws_data->context, 1);
262
263 if (loop_count <= 10) {
264 log_debug_every(US_PER_SEC_INT, "[LOOP %d] <<< lws_service() RETURNED (result=%d)", loop_count, result);
265 }
266 }
267 uint64_t service_end_ns = time_get_ns();
268
269 if (loop_count <= 50) {
270 char service_duration_str[TIME_DURATION_BUFFER_SIZE];
271 time_pretty(service_end_ns - service_start_ns, -1, service_duration_str, sizeof(service_duration_str));
272 log_debug_every(US_PER_SEC_INT, "[LOOP %d] lws_service() returned %d, duration %s", loop_count, result, service_duration_str);
273 }
274
275 if (result < 0) {
276 log_fatal("🔴 lws_service error: %d at loop %d", result, loop_count);
277 break;
278 }
279 } else {
280 // Sleep briefly between lws_service() calls to avoid busy-waiting
281 // During handshake: 0us sleep (busy-wait for maximum responsiveness during TLS)
282 // lws_service is now non-blocking, so tight polling won't block
283 // During transfer: 100us sleep (normal cadence)
284 uint64_t sleep_us = ws_data->is_connected ? 100 : 0;
285 if (loop_count <= 50) {
286 log_debug_every(US_PER_SEC_INT, "[LOOP %d] Time since service: %lu us, interval: %lu us - sleeping %lu us", loop_count, time_since_last_service / 1000, service_interval / 1000, sleep_us);
287 }
288 if (sleep_us > 0) {
289 platform_sleep_us(sleep_us);
290 }
291 // else: no sleep during handshake - busy-wait with non-blocking lws_service calls
292 }
293
294 // Check if connection is still alive
295 if (loop_count <= 50 && ws_data->is_connected) {
296 log_debug_every(US_PER_SEC_INT, "[LOOP %d] After lws_service: is_connected=true, wsi=%p", loop_count, (void *)ws_data->wsi);
297 } else if (loop_count <= 50) {
298 log_debug_every(US_PER_SEC_INT, "[LOOP %d] After lws_service: is_connected=false, wsi=%p", loop_count, (void *)ws_data->wsi);
299 }
300 }
301
302 // log_debug("WebSocket service thread exiting"); // Disabled: causes AddressSanitizer heap-use-after-free crash
303 return NULL;
304}
305
306// =============================================================================
307// libwebsockets Callbacks
308// =============================================================================
309
313static void websocket_on_established(struct lws *wsi, websocket_transport_data_t *ws_data) {
314 // Don't process if we're in shutdown mode
315 if (atomic_load_bool(&ws_data->is_destroying)) {
316 return;
317 }
318 int send_buffer = SOCKET_STREAM_SEND_BUFFER;
319 if (socket_setsockopt(lws_get_socket_fd(wsi), SOL_SOCKET, SO_SNDBUF, &send_buffer, sizeof(send_buffer)) != 0) {
320 mutex_lock(&ws_data->state_mutex);
321 ws_data->connection_failed = true;
322 mutex_unlock(&ws_data->state_mutex);
323 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, LWS_TO_KILL_ASYNC);
324 return;
325 }
326 uint64_t now_ns = time_get_ns();
327 log_fatal("🟢🟢🟢 WebSocket CLIENT_ESTABLISHED! wsi=%p, ws_data=%p, timestamp=%llu, elapsed_from_start=%llu", (void *)wsi, (void *)ws_data, (unsigned long long)now_ns,
328 (unsigned long long)(now_ns / 1000000000ULL));
329 if (ws_data) {
330 mutex_lock(&ws_data->state_mutex);
331 log_fatal(" [ESTABLISHED] Setting is_connected=true (was %d)", ws_data->is_connected);
332 ws_data->is_connected = true;
333 cond_signal(&ws_data->state_cond);
334 mutex_unlock(&ws_data->state_mutex);
335 log_fatal(" [ESTABLISHED] State updated, wsi=%p ready for send/recv", (void *)wsi);
336 }
337}
338
342static int websocket_on_receive(struct lws *wsi, websocket_transport_data_t *ws_data, void *in, size_t len) {
343 // Received data from server - may be fragmented for large messages
344 if (atomic_load_bool(&ws_data->is_destroying)) {
345 return 0;
346 }
347 uint64_t now_ns = time_get_ns();
348 if (!in || len == 0) {
349 log_debug_every(US_PER_SEC_INT, "CLIENT_RECEIVE: in=%p, len=%zu - skipping", in, len);
350 return 0;
351 }
352
353 // Detect first/final bits from WebSocket frame using the LWS API
354 bool is_first = lws_is_first_fragment(wsi);
355 bool is_final = lws_is_final_fragment(wsi);
356
357 log_debug_every(US_PER_SEC_INT, "🟡 LWS_CALLBACK_CLIENT_RECEIVE: %zu bytes (first=%d, final=%d), wsi=%p, timestamp=%llu", len, is_first, is_final, (void *)wsi, (unsigned long long)now_ns);
358
359 // Queue this fragment immediately with first/final flags.
360 // Per LWS design, each fragment is processed individually by the callback.
361 // We must NOT manually reassemble fragments - that breaks LWS's internal state machine.
362 // Instead, queue each fragment with metadata, and let the receiver decide on reassembly.
363
365 msg.data = buffer_alloc(NULL, len);
366 if (!msg.data) {
367 log_error("Failed to allocate buffer for fragment (%zu bytes)", len);
368 return -1;
369 }
370
371 memcpy(msg.data, in, len);
372 msg.len = len;
373 msg.first = is_first;
374 msg.final = is_final;
375
376 mutex_lock(&ws_data->recv_mutex);
377 bool success = ringbuffer_write(ws_data->recv_queue, &msg);
378 if (!success) {
379 // Closing preserves packet boundaries when a fragment cannot be admitted.
380 log_warn("WebSocket receive queue full - closing connection (len=%zu, first=%d, final=%d)", len, is_first, is_final);
381 buffer_release(msg.data);
382 mutex_unlock(&ws_data->recv_mutex);
383 return -1;
384 }
385
386 // Signal waiting recv() call that a fragment is available
387 cond_signal(&ws_data->recv_cond);
388 mutex_unlock(&ws_data->recv_mutex);
389 return 0;
390}
391
395static void websocket_on_closed(struct lws *wsi, websocket_transport_data_t *ws_data, enum lws_callback_reasons reason) {
396 uint64_t now_ns = time_get_ns();
397 log_fatal("🔴🔴🔴 WebSocket connection CLOSED! reason=%d, wsi=%p, ws_data=%p, is_connected=%d, timestamp=%llu", reason, (void *)wsi, (void *)ws_data, ws_data ? ws_data->is_connected : -1,
398 (unsigned long long)now_ns);
399 if (ws_data) {
400 mutex_lock(&ws_data->state_mutex);
401 log_fatal(" [CLOSE] Setting is_connected=false (was %d)", ws_data->is_connected);
402 ws_data->is_connected = false;
403 mutex_unlock(&ws_data->state_mutex);
404
405 // Wake any blocking recv() calls
406 cond_broadcast(&ws_data->recv_cond);
407 }
408}
409
413static void websocket_on_connection_error(struct lws *wsi, websocket_transport_data_t *ws_data, enum lws_callback_reasons reason, void *in) {
414 uint64_t now_ns = time_get_ns();
415
416 // Get detailed OpenSSL error if available
417 unsigned long ssl_err = ERR_get_error();
418 char ssl_err_str[NETWORK_WEBSOCKET_TRANSPORT_SSL_ERR_BUFFER_SIZE] = "no SSL error";
419 if (ssl_err) {
420 ERR_error_string_n(ssl_err, ssl_err_str, sizeof(ssl_err_str));
421 }
422
423 log_fatal("🔴🔴🔴 WebSocket CONNECTION ERROR! reason=%d, error=%s, wsi=%p, ws_data=%p, ssl_err=%lu (%s), timestamp=%llu", reason, in ? (const char *)in : "unknown", (void *)wsi, (void *)ws_data,
424 ssl_err, ssl_err_str, (unsigned long long)now_ns);
425 if (ws_data) {
426 mutex_lock(&ws_data->state_mutex);
427 ws_data->is_connected = false;
428 ws_data->connection_failed = true; // Signal service thread to exit
429 cond_signal(&ws_data->state_cond); // Wake anyone waiting on connection
430 mutex_unlock(&ws_data->state_mutex);
431
432 // Wake any blocking recv() calls
433 cond_broadcast(&ws_data->recv_cond);
434 }
435}
436
441 if (!ws_data || atomic_load_bool(&ws_data->is_destroying))
442 return;
443 /* lws suppresses writable callbacks until previously buffered output is
444 * consumed. Keep one owner until this completion boundary, or connection
445 * teardown; elapsed service-loop iterations are not a completion signal. */
446 websocket_recv_msg_t msg = {0};
447 mutex_lock(&ws_data->send_mutex);
449 ws_data->inflight_buffer = NULL;
450 ws_data->pending_send_bytes -= ws_data->inflight_bytes;
451 ws_data->inflight_bytes = 0;
452 bool available = ringbuffer_read(ws_data->send_queue, &msg);
453 if (available)
454 ws_data->inflight_buffer = msg.data;
455 ws_data->inflight_bytes = msg.len;
456 mutex_unlock(&ws_data->send_mutex);
457 if (!available)
458 return;
459 int written = lws_write(wsi, msg.data + LWS_PRE, msg.len, LWS_WRITE_BINARY);
460 if (written < 0 || (size_t)written < msg.len) {
461 mutex_lock(&ws_data->state_mutex);
462 ws_data->is_connected = false;
463 ws_data->connection_failed = true;
464 cond_broadcast(&ws_data->state_cond);
465 mutex_unlock(&ws_data->state_mutex);
466 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, LWS_TO_KILL_ASYNC);
467 return;
468 }
469 /* Exactly one write per callback. Request a completion callback even if
470 * there is no next message, so the final owner is promptly released. */
471 lws_callback_on_writable(wsi);
472}
473
474static void websocket_on_writable(struct lws *wsi, websocket_transport_data_t *ws_data) {
476}
477
484static int websocket_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) {
485 websocket_transport_data_t *ws_data = wsi ? lws_get_opaque_user_data(wsi) : NULL;
486 if (!ws_data) {
487 ws_data = (websocket_transport_data_t *)user;
488 }
489
490 // Log all callback reasons for TLS investigation
491 static uint64_t callback_count = 0;
492 uint64_t now_ns = time_get_ns();
493 if (reason == LWS_CALLBACK_PROTOCOL_INIT || reason == LWS_CALLBACK_CLIENT_ESTABLISHED || reason == LWS_CALLBACK_CLIENT_WRITEABLE || reason == LWS_CALLBACK_CLIENT_RECEIVE ||
494 reason == LWS_CALLBACK_CLIENT_CONNECTION_ERROR || reason == LWS_CALLBACK_CLOSED) {
495 callback_count++;
496 log_debug_every(US_PER_SEC_INT, ">>> CALLBACK #%lu: reason=%d (0x%x), wsi=%p, len=%zu, timestamp=%llu", callback_count, reason, reason, (void *)wsi, len, (unsigned long long)now_ns);
497 }
498
499 // Validate ws_data exists before accessing it (prevents heap-buffer-overflow in TLS callbacks)
500 // For unknown callbacks (especially TLS internal callbacks from OpenSSL), return early
501 if (!ws_data) {
502 return 0;
503 }
504
505 switch (reason) {
506 case LWS_CALLBACK_CLIENT_ESTABLISHED:
507 websocket_on_established(wsi, ws_data);
508 break;
509
510 case LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH: {
511 log_debug_every(US_PER_SEC_INT, ">>> CALLBACK: LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH (wsi=%p) - WebSocket upgrade starting", (void *)wsi);
512 break;
513 }
514
515 case LWS_CALLBACK_PROTOCOL_INIT: {
516 log_debug_every(US_PER_SEC_INT, ">>> CALLBACK: LWS_CALLBACK_PROTOCOL_INIT (wsi=%p, ws_data=%p)", (void *)wsi, (void *)ws_data);
517 if (atomic_load_bool(&ws_data->is_destroying)) {
518 return 0;
519 }
520 break;
521 }
522
523 case LWS_CALLBACK_CLIENT_RECEIVE:
524 return websocket_on_receive(wsi, ws_data, in, len);
525
526 case LWS_CALLBACK_CLIENT_CLOSED:
527 case LWS_CALLBACK_CLOSED:
528 websocket_on_closed(wsi, ws_data, reason);
529 break;
530
531 case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
532 websocket_on_connection_error(wsi, ws_data, reason, in);
533 break;
534
535 case LWS_CALLBACK_CLIENT_WRITEABLE:
536 websocket_on_writable(wsi, ws_data);
537 break;
538
539 default:
540 break;
541 }
542
543 return 0;
544}
545
546// =============================================================================
547// WebSocket Transport Methods
548// =============================================================================
549
553static asciichat_error_t websocket_prepare_payload(acip_transport_t *transport, buffer_domain_t *domain, const void *data, size_t len, const void **out_data, size_t *out_len,
554 uint8_t **out_encrypted_packet, size_t *out_encrypted_size) {
555 *out_data = data;
556 *out_len = len;
557 *out_encrypted_packet = NULL;
558 *out_encrypted_size = 0;
559 socket_buffer_t slice = {data, len};
561 asciichat_error_t result = acip_packet_plan(transport->crypto_ctx, &slice, 1, &plan);
562 if (result != ASCIICHAT_OK || !plan.encrypt)
563 return result;
564 size_t capacity = sizeof(packet_header_t) + plan.ciphertext_capacity;
565 uint8_t *packet = buffer_alloc(domain, capacity);
566 if (!packet)
567 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate WebSocket ciphertext");
568 packet_header_t header;
569 size_t length = 0;
570 result = acip_packet_encrypt(transport->crypto_ctx, &plan, domain, packet + sizeof(header), plan.ciphertext_capacity, &header, &length);
571 if (result != ASCIICHAT_OK) {
572 buffer_release(packet);
573 return result;
574 }
575 memcpy(packet, &header, sizeof(header));
576 *out_data = packet;
577 *out_len = sizeof(header) + length;
578 *out_encrypted_packet = packet;
579 *out_encrypted_size = *out_len;
580 return ASCIICHAT_OK;
581}
582
586static asciichat_error_t websocket_queue_payload(websocket_transport_data_t *ws_data, buffer_domain_t *domain, const void *send_data, size_t send_len) {
587 // Both sides retain padded wire data until the owning service callback sends it.
588 websocket_recv_msg_t msg = {.data = buffer_alloc(domain, LWS_PRE + send_len), .len = send_len, .first = 1, .final = 1};
589 if (!msg.data)
590 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate WebSocket send buffer");
591 memcpy(msg.data + LWS_PRE, send_data, send_len);
592 mutex_lock(&ws_data->state_mutex);
593 if (atomic_load_bool(&ws_data->is_destroying) || ws_data->connection_failed || !ws_data->context) {
594 mutex_unlock(&ws_data->state_mutex);
595 buffer_release(msg.data);
596 return SET_ERRNO(ERROR_NETWORK, "WebSocket closed before send admission");
597 }
598 mutex_lock(&ws_data->send_mutex);
599 bool admitted = ringbuffer_write(ws_data->send_queue, &msg);
600 if (admitted)
601 ws_data->pending_send_bytes += send_len;
602 mutex_unlock(&ws_data->send_mutex);
603 // Context detachment takes state_mutex too; cancellation cannot use a stale context.
604 if (admitted)
605 lws_cancel_service(ws_data->context);
606 mutex_unlock(&ws_data->state_mutex);
607 if (!admitted) {
608 buffer_release(msg.data);
609 return SET_ERRNO(ERROR_NETWORK, "WebSocket send queue full");
610 }
611 return ASCIICHAT_OK;
612}
613
614asciichat_error_t websocket_transport_send(acip_transport_t *transport, const void *data, size_t len) {
615 // NOTE: Disabled START_TIMER/STOP_TIMER due to thread safety issues with timer hashtable
616 // causing heap-use-after-free crashes in ASAN. The timer system has race conditions
617 // when accessed from the service thread context. See: line 325 (similar issue).
619
620 // For server-side transports (owns_context=false), the connection is already established.
621 // For client-side transports, packets may be queued before the asynchronous WebSocket
622 // handshake completes. The service thread drains that queue after CLIENT_ESTABLISHED.
623 if (ws_data->owns_context) {
624 // Check connection state without blocking the service thread.
625 mutex_lock(&ws_data->state_mutex);
626 bool connected = ws_data->is_connected;
627 bool connection_failed = ws_data->connection_failed;
628 mutex_unlock(&ws_data->state_mutex);
629
630 if (connection_failed) {
631 log_error("Connection failed - cannot send");
632 return SET_ERRNO(ERROR_NETWORK, "WebSocket connection failed");
633 }
634
635 if (!connected) {
636 log_debug("Connection is opening; queueing packet for delivery after handshake");
637 }
638
639 log_dev_every(1000000, "websocket_send (client): is_connected=%d, wsi=%p, send_len=%zu", connected, (void *)ws_data->wsi, len);
640 } else {
641 log_dev_every(4500 * US_PER_MS_INT, "[WEBSOCKET_SEND_SERVER] Server transport send: wsi=%p, len=%zu (bypassing is_connected check)", (void *)ws_data->wsi, len);
642 }
643
644 // Classify the original packet before encryption hides its type. Keep this
645 // domain through every allocation, including the asynchronous queue owner.
646 buffer_domain_t *domain = NULL;
647 if (data && len >= sizeof(packet_header_t)) {
648 packet_header_t header;
649 memcpy(&header, data, sizeof(header));
650 packet_type_t type = NET_TO_HOST_U16(header.type);
651 if (packet_is_handshake_type(type) || type == PACKET_TYPE_ERROR_MESSAGE)
652 domain = buffer_control_domain();
653 }
654 const void *send_data = NULL;
655 size_t send_len = 0;
656 uint8_t *encrypted_packet = NULL;
657 size_t encrypted_packet_size = 0;
658 asciichat_error_t result = websocket_prepare_payload(transport, domain, data, len, &send_data, &send_len, &encrypted_packet, &encrypted_packet_size);
659 if (result != ASCIICHAT_OK) {
660 return result;
661 }
662
663 result = websocket_queue_payload(ws_data, domain, send_data, send_len);
664 if (encrypted_packet) {
665 buffer_release(encrypted_packet);
666 }
667 return result;
668}
669
673static asciichat_error_t websocket_wait_for_connection(websocket_transport_data_t *ws_data) {
674 // Client transports are returned before the asynchronous WebSocket upgrade
675 // completes, so their first recv() must wait for the connection state. A
676 // server transport is created from LWS_CALLBACK_ESTABLISHED and may already
677 // have queued the client's first packet before its handler starts; applying
678 // the client-only gate there can hide that packet after an early close.
679 if (ws_data->owns_context) {
680 mutex_lock(&ws_data->state_mutex);
681 bool connected = ws_data->is_connected;
682 bool connection_failed = ws_data->connection_failed;
683 uint64_t start_time = time_get_ns();
684
685 if (!connected && !connection_failed) {
686 // Connection not yet established and hasn't failed - wait for it with timeout
687 log_debug_every(US_PER_SEC_INT, "WEBSOCKET_RECV: Connection not yet established, waiting (timeout=5s)");
688 // Wait up to 5 seconds for the state_cond to signal that is_connected changed
689 int wait_result = cond_timedwait(&ws_data->state_cond, &ws_data->state_mutex, 5 * 1000000000ULL);
690
691 uint64_t elapsed_ns = time_get_ns() - start_time;
692 uint64_t elapsed_ms = elapsed_ns / 1000000ULL;
693
694 log_debug_every(US_PER_SEC_INT, "WEBSOCKET_RECV: Wait returned (result=%d, elapsed=%llums)", wait_result, (unsigned long long)elapsed_ms);
695
696 // Re-check after wait
697 connected = ws_data->is_connected;
698 connection_failed = ws_data->connection_failed;
699
700 log_debug_every(US_PER_SEC_INT, "WEBSOCKET_RECV: After wait: connected=%d, connection_failed=%d", connected, connection_failed);
701 }
702
703 mutex_unlock(&ws_data->state_mutex);
704
705 if (connection_failed && !connected) {
706 log_error("🔴 WEBSOCKET_RECV: Connection failed during establishment");
707 return SET_ERRNO(ERROR_NETWORK, "WebSocket connection failed");
708 }
709
710 if (!connected) {
711 log_error("🔴 WEBSOCKET_RECV: Connection timeout (waited 5 seconds)");
712 return SET_ERRNO(ERROR_NETWORK, "WebSocket connection timeout");
713 }
714 }
715
716 return ASCIICHAT_OK;
717}
718
722static asciichat_error_t websocket_finish_packet_locked(websocket_transport_data_t *ws_data, uint8_t *assembled_buffer, size_t assembled_size, size_t expected_size, void **buffer, size_t *out_len,
723 void **out_allocated_buffer) {
724 // Check for leftover data after this packet
725 size_t leftover_size = assembled_size - expected_size;
726 if (leftover_size > 0) {
727 // Save leftover data for next recv() call
728 log_debug_every(US_PER_SEC_INT, "[WS_REASSEMBLE] Saving %zu bytes leftover for next recv() call", leftover_size);
729
730 // Create buffer for leftover (or reuse if we can)
731 uint8_t *leftover_buffer = buffer_alloc(NULL, leftover_size);
732 if (leftover_buffer) {
733 memcpy(leftover_buffer, assembled_buffer + expected_size, leftover_size);
734 ws_data->partial_buffer = leftover_buffer;
735 ws_data->partial_size = leftover_size;
736 ws_data->partial_capacity = leftover_size;
737 } else {
738 log_error("[WS_REASSEMBLE] Failed to allocate leftover buffer (%zu bytes)", leftover_size);
739 buffer_release(assembled_buffer);
740 mutex_unlock(&ws_data->recv_mutex);
741 return SET_ERRNO(ERROR_MEMORY, "Cannot preserve WebSocket packet boundary");
742 }
743 }
744
745 // Capacity metadata lets the receiver own the original assembly even when
746 // its backing allocation is larger than the logical packet.
747 (void)buffer_set_size(assembled_buffer, expected_size);
748 *buffer = assembled_buffer;
749 *out_len = expected_size;
750 *out_allocated_buffer = assembled_buffer;
751 mutex_unlock(&ws_data->recv_mutex);
752 return ASCIICHAT_OK;
753}
754
758static asciichat_error_t websocket_append_fragment(websocket_recv_msg_t frag, uint8_t **assembly_buffer, size_t *assembly_size, size_t *assembly_capacity) {
759 uint8_t *assembled_buffer = *assembly_buffer;
760 size_t assembled_size = *assembly_size;
761 size_t assembled_capacity = *assembly_capacity;
762 // Grow assembled buffer if needed
763 size_t required_size = assembled_size + frag.len;
764 if (required_size > assembled_capacity) {
765 // Start with 8KB, grow by 1.5x, but cap at 4MB to prevent unbounded allocation
766 const size_t MAX_REASSEMBLY_SIZE = (4 * 1024 * 1024); // 4MB limit
767
768 size_t new_capacity = (assembled_capacity == 0) ? 8192 : (assembled_capacity * 3 / 2);
769 if (new_capacity < required_size) {
770 new_capacity = required_size;
771 }
772
773 // Enforce maximum reassembly buffer size
774 if (new_capacity > MAX_REASSEMBLY_SIZE) {
775 log_error("[WS_REASSEMBLE] Frame too large: need %zu bytes, max allowed is %zu", new_capacity, MAX_REASSEMBLY_SIZE);
776 buffer_release(frag.data);
777 return SET_ERRNO(ERROR_NETWORK, "WebSocket frame exceeds maximum size (4MB)");
778 }
779
780 uint8_t *new_buffer = buffer_alloc(NULL, new_capacity);
781 if (!new_buffer) {
782 log_error("[WS_REASSEMBLE] Failed to allocate reassembly buffer (%zu bytes)", new_capacity);
783 buffer_release(frag.data);
784 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate fragment reassembly buffer");
785 }
786
787 // Copy existing data to new buffer
788 if (assembled_size > 0) {
789 memcpy(new_buffer, assembled_buffer, assembled_size);
790 }
791
792 // Free old buffer
793 if (assembled_buffer) {
794 buffer_release(assembled_buffer);
795 }
796
797 assembled_buffer = new_buffer;
798 assembled_capacity = new_capacity;
799 *assembly_buffer = assembled_buffer;
800 *assembly_capacity = assembled_capacity;
801 }
802
803 // Append fragment data with bounds checking
804 if (frag.len > 0 && frag.data) {
805 // Safety check: ensure we don't overflow the buffer
806 if (assembled_size + frag.len > assembled_capacity) {
807 log_error("[WS_REASSEMBLE] CRITICAL: Buffer overflow detected! assembled_size=%zu, frag.len=%zu, capacity=%zu", assembled_size, frag.len, assembled_capacity);
808 buffer_release(frag.data);
809 return SET_ERRNO(ERROR_MEMORY, "Fragment reassembly buffer overflow");
810 }
811
812 memcpy(assembled_buffer + assembled_size, frag.data, frag.len);
813 assembled_size += frag.len;
814 }
815
816 // Free fragment data after copying (allocated in LWS callback with buffer_alloc)
817 if (frag.data) {
818 // Use the fragment length that was stored when we allocated it
819 // This must match the size passed to buffer_alloc in the LWS callback
820 buffer_release(frag.data);
821 frag.data = NULL; // Prevent accidental double-free
822 }
823
824 *assembly_size = assembled_size;
825 return ASCIICHAT_OK;
826}
827
828static asciichat_error_t websocket_recv(acip_transport_t *transport, void **buffer, size_t *out_len, void **out_allocated_buffer) {
830
831 asciichat_error_t result = websocket_wait_for_connection(ws_data);
832 if (result != ASCIICHAT_OK) {
833 return result;
834 }
835
836 mutex_lock(&ws_data->recv_mutex);
837
838 // Even if connection is closed, we should try to deliver any buffered data
839 // Check if there's data in the queue
840 bool has_queued_data = !ringbuffer_is_empty(ws_data->recv_queue);
841
842 // Connection is established at this point, but might close during data transfer
843 // Deliver buffered data if available, otherwise wait
844 if (!has_queued_data && ws_data->partial_size == 0) {
845 // Check connection state again
846 mutex_lock(&ws_data->state_mutex);
847 bool still_connected = ws_data->is_connected;
848 mutex_unlock(&ws_data->state_mutex);
849
850 if (!still_connected) {
851 uint64_t now_ns = time_get_ns();
852 log_fatal("🔴 WEBSOCKET_RECV: Connection closed! has_queued_data=%d, partial_size=%zu, wsi=%p, "
853 "timestamp=%llu",
854 has_queued_data, ws_data->partial_size, (void *)ws_data->wsi, (unsigned long long)now_ns);
855 mutex_unlock(&ws_data->recv_mutex);
856 return SET_ERRNO(ERROR_NETWORK, "Connection closed");
857 }
858 }
859
860 // Reassemble fragmented WebSocket messages with SHORT timeout
861 // We queue each fragment from the LWS callback with first/final flags.
862 // Key insight: if we wait too long for final fragment, connection times out.
863 // Return partial messages quickly (500ms) to avoid blocking handler thread.
864 //
865 // Use persistent partial_buffer to handle packet boundaries
866 // that don't align with WebSocket frame boundaries. This prevents data loss
867 // when a single WebSocket message contains multiple ACIP packets.
868
869 uint8_t *assembled_buffer = NULL;
870 size_t assembled_size = 0;
871 size_t assembled_capacity = 0;
872 int fragment_count = 0;
873
874 // Start with leftover data from previous recv() call if available
875 if (ws_data->partial_size > 0) {
876 log_debug_every(US_PER_SEC_INT, "[WS_REASSEMBLE] Starting with leftover data from previous packet: %zu bytes", ws_data->partial_size);
877 assembled_buffer = ws_data->partial_buffer;
878 assembled_size = ws_data->partial_size;
879 assembled_capacity = ws_data->partial_capacity;
880
881 // Clear the partial buffer state so next call starts fresh if no more leftovers
882 ws_data->partial_buffer = NULL;
883 ws_data->partial_size = 0;
884 ws_data->partial_capacity = 0;
885 }
886
887 uint64_t started = time_get_ns();
888 uint64_t timeout = transport->receive_timeout_ns ? transport->receive_timeout_ns : NS_PER_SEC_INT;
889 while (true) {
890 // Wait for fragment if queue is empty
891 while (ringbuffer_is_empty(ws_data->recv_queue)) {
892 // Don't timeout waiting for fragments. If the connection is dead, libwebsockets will
893 // set is_connected=false and we'll detect it below. Arbitrary timeouts just cause
894 // unnecessary disconnections while data is actually being transmitted.
895
896 if (time_get_ns() - started >= timeout) {
897 ws_data->partial_buffer = assembled_buffer;
898 ws_data->partial_size = assembled_size;
899 ws_data->partial_capacity = assembled_capacity;
900 mutex_unlock(&ws_data->recv_mutex);
901 // Poll deadlines preserve partial packets and are handled by the receive loop.
902 bool previous = errno_notifications_suppress(true);
903 asciichat_error_t deadline_result = SET_ERRNO(assembled_size ? ERROR_NETWORK_INCOMPLETE : ERROR_NETWORK_TIMEOUT, "WebSocket receive deadline expired");
905 return deadline_result;
906 }
907 // Check connection state - but don't fail immediately if connection closes
908 // while reassembling. Instead, return what we have so the handler can process it.
909 // This prevents losing buffered data due to connection timeouts.
910 mutex_lock(&ws_data->state_mutex);
911 bool still_connected = ws_data->is_connected;
912 mutex_unlock(&ws_data->state_mutex);
913
914 if (!still_connected && assembled_size > 0) {
915 // Connection closed but we have partial data - return it
916 log_debug_every(US_PER_SEC_INT, "[WS_REASSEMBLE] Connection closed mid-reassembly, returning %zu bytes received so far", assembled_size);
917 *buffer = assembled_buffer;
918 *out_len = assembled_size;
919 *out_allocated_buffer = assembled_buffer;
920 mutex_unlock(&ws_data->recv_mutex);
921 return ASCIICHAT_OK;
922 }
923
924 if (!still_connected && assembled_size == 0) {
925 // Connection closed and no data yet
926 if (assembled_buffer) {
927 buffer_release(assembled_buffer);
928 }
929 mutex_unlock(&ws_data->recv_mutex);
930 return SET_ERRNO(ERROR_NETWORK, "Connection closed");
931 }
932
933 // Wait for next fragment with 1ms timeout to allow signals to interrupt
934 cond_timedwait(&ws_data->recv_cond, &ws_data->recv_mutex, 1 * 1000000ULL);
935 }
936
937 // Read next fragment from queue
939 bool success = ringbuffer_read(ws_data->recv_queue, &frag);
940 if (!success) {
941 if (assembled_buffer) {
942 buffer_release(assembled_buffer);
943 }
944 mutex_unlock(&ws_data->recv_mutex);
945 return SET_ERRNO(ERROR_NETWORK, "Failed to read fragment from queue");
946 }
947
948 fragment_count++;
949 if (frag.len > 100 || fragment_count == 1) {
950 log_dev_every(US_PER_SEC_INT, "[WS_REASSEMBLE] Fragment #%d: %zu bytes, first=%d, final=%d, assembled_so_far=%zu", fragment_count, frag.len, frag.first, frag.final, assembled_size);
951 } else {
952 log_debug_every(US_PER_SEC_INT, "[WS_REASSEMBLE] Fragment #%d: %zu bytes, first=%d, final=%d", fragment_count, frag.len, frag.first, frag.final);
953 }
954
955 // Sanity check: first fragment must have first=1, continuations must have first=0
956 if (assembled_size == 0 && !frag.first) {
957 log_error("[WS_REASSEMBLE] ERROR: Expected first=1 for first fragment, got first=%d", frag.first);
958 buffer_release(frag.data);
959 if (assembled_buffer) {
960 buffer_release(assembled_buffer);
961 }
962 mutex_unlock(&ws_data->recv_mutex);
963 return SET_ERRNO(ERROR_NETWORK, "Protocol error: continuation fragment without first fragment");
964 }
965
966 result = websocket_append_fragment(frag, &assembled_buffer, &assembled_size, &assembled_capacity);
967 if (result != ASCIICHAT_OK) {
968 if (assembled_buffer) {
969 buffer_release(assembled_buffer);
970 }
971 mutex_unlock(&ws_data->recv_mutex);
972 return result;
973 }
974
975 // Try to detect packet boundary using protocol structure
976 // ACIP packet header: magic(8) + type(2) + length(4) + crc(4) + client_id(4) = 22 bytes
977 // The length field (bytes 10-13) tells us the payload size
978 if (assembled_size >= 14) { // Need at least 14 bytes to read length field at offset 10
979 const uint8_t *data = assembled_buffer;
980
981 // Parse length field at offset 10 (4 bytes, big-endian)
982 uint32_t msg_payload_len = (data[10] << 24) | (data[11] << 16) | (data[12] << 8) | data[13];
983
984 // Sanity check: payload length should be reasonable (< 5MB)
985 if (msg_payload_len > 0 && msg_payload_len <= 5 * 1024 * 1024) {
986 // Total packet size = header(14 bytes up to and including length field) + payload
987 // Actually full header is 22 bytes but we can work with just the length field
988 const size_t HEADER_SIZE = 22;
989 size_t expected_size = HEADER_SIZE + msg_payload_len;
990
991 if (assembled_size >= expected_size) {
992 // Complete packet assembled based on header length field
993 log_dev_every(1000000, "[WS_REASSEMBLE] Complete message: %zu bytes in %d fragments (payload=%u)", expected_size, fragment_count, msg_payload_len);
994
995 return websocket_finish_packet_locked(ws_data, assembled_buffer, assembled_size, expected_size, buffer, out_len, out_allocated_buffer);
996 }
997 // Need more fragments to complete this message
998 }
999 }
1000
1001 // Fallback: check if we have the final WebSocket fragment
1002 // BUT: Only return if we have a COMPLETE ACIP packet!
1003 // ACIP packets can span multiple WebSocket frames, so final=true doesn't mean
1004 // we have the complete ACIP packet - we must verify using the ACIP header's length field
1005 if (frag.final) {
1006 // Check if this is actually a complete ACIP packet by validating the length field
1007 if (assembled_size >= 14) { // Minimum to read ACIP length field
1008 const uint8_t *data = (const uint8_t *)assembled_buffer;
1009 uint32_t msg_payload_len = (data[10] << 24) | (data[11] << 16) | (data[12] << 8) | data[13];
1010 const size_t HEADER_SIZE = 22;
1011 size_t expected_size = HEADER_SIZE + msg_payload_len;
1012
1013 if (assembled_size >= expected_size) {
1014 // We have a complete ACIP packet
1015 log_dev_every(1000000, "[WS_REASSEMBLE] Complete ACIP packet: %zu bytes in %d fragments", expected_size, fragment_count);
1016
1017 return websocket_finish_packet_locked(ws_data, assembled_buffer, assembled_size, expected_size, buffer, out_len, out_allocated_buffer);
1018 } else {
1019 // ACIP packet is incomplete even though WebSocket frame is final
1020 // This shouldn't happen - WebSocket is delivering corrupt data
1021 log_error("[WS_REASSEMBLE] ERROR: WebSocket final fragment but incomplete ACIP packet (have %zu, need %zu)", assembled_size, expected_size);
1022 buffer_release(assembled_buffer);
1023 mutex_unlock(&ws_data->recv_mutex);
1024 return SET_ERRNO(ERROR_NETWORK, "WebSocket final fragment but incomplete ACIP packet");
1025 }
1026 }
1027 }
1028
1029 // More fragments coming, continue reassembling
1030 }
1031
1032 // Unreachable unless while loop breaks without returning
1033 mutex_unlock(&ws_data->recv_mutex);
1034 return SET_ERRNO(ERROR_NETWORK, "Unexpected exit from fragment reassembly loop");
1035}
1036
1038 if (!transport || acip_transport_get_type(transport) != ACIP_TRANSPORT_WEBSOCKET)
1039 return SET_ERRNO(ERROR_INVALID_PARAM, "Expected WebSocket transport");
1040 websocket_transport_data_t *ws_data = transport->impl_data;
1041 uint64_t started = time_get_ns();
1042 while (acip_transport_is_connected(transport)) {
1043 mutex_lock(&ws_data->send_mutex);
1044 bool drained = ringbuffer_is_empty(ws_data->send_queue) && !ws_data->inflight_buffer;
1045 mutex_unlock(&ws_data->send_mutex);
1046 if (drained)
1047 return ASCIICHAT_OK;
1048 if (time_get_ns() - started >= timeout_ns)
1049 return SET_ERRNO(ERROR_NETWORK_TIMEOUT, "WebSocket send queue did not drain");
1050 platform_sleep_us(1000);
1051 }
1052 return SET_ERRNO(ERROR_NETWORK, "WebSocket closed before send queue drained");
1053}
1054
1055static void websocket_interrupt(acip_transport_t *transport) {
1056 websocket_transport_data_t *ws_data = transport->impl_data;
1057 atomic_store_bool(&ws_data->is_destroying, true);
1058 mutex_lock(&ws_data->state_mutex);
1059 ws_data->is_connected = false;
1060 cond_broadcast(&ws_data->state_cond);
1061 if (ws_data->context)
1062 lws_cancel_service(ws_data->context);
1063 mutex_unlock(&ws_data->state_mutex);
1064 // Receivers release recv_mutex while waiting; acquire it to avoid lost wakes.
1065 mutex_lock(&ws_data->recv_mutex);
1066 cond_broadcast(&ws_data->recv_cond);
1067 mutex_unlock(&ws_data->recv_mutex);
1068}
1069
1070static asciichat_error_t websocket_close(acip_transport_t *transport) {
1071 websocket_interrupt(transport);
1072 // Close can run concurrently from failed-send and connection-stop paths.
1073 // Only destroy_impl owns the service-thread join, after backend users stop.
1074 return ASCIICHAT_OK;
1075}
1076
1077static acip_transport_type_t websocket_get_type(acip_transport_t *transport) {
1078 (void)transport;
1080}
1081
1082static socket_t websocket_get_socket(acip_transport_t *transport) {
1083 (void)transport;
1084 return INVALID_SOCKET_VALUE; // WebSocket has no underlying socket handle we can expose
1085}
1086
1087static bool websocket_is_connected(acip_transport_t *transport) {
1089
1090 mutex_lock(&ws_data->state_mutex);
1091 bool connected = ws_data->is_connected;
1092 mutex_unlock(&ws_data->state_mutex);
1093
1094 return connected;
1095}
1096
1097static bool websocket_has_pending_data(acip_transport_t *transport) {
1099 if (!ws_data || !ws_data->recv_queue) {
1100 return false;
1101 }
1102
1103 mutex_lock(&ws_data->recv_mutex);
1104 bool has_data = !ringbuffer_is_empty(ws_data->recv_queue);
1105 mutex_unlock(&ws_data->recv_mutex);
1106 return has_data;
1107}
1108
1109// =============================================================================
1110// WebSocket Transport Destroy Implementation
1111// =============================================================================
1112
1116static void websocket_discard_buffers(websocket_transport_data_t *ws_data) {
1117 // Clear receive queue and free buffered messages
1118 if (ws_data->recv_queue) {
1119 mutex_lock(&ws_data->recv_mutex);
1120
1121 websocket_recv_msg_t recv_msg;
1122 while (ringbuffer_read(ws_data->recv_queue, &recv_msg)) {
1123 if (recv_msg.data) {
1124 buffer_release(recv_msg.data);
1125 }
1126 }
1127
1128 mutex_unlock(&ws_data->recv_mutex);
1130 ws_data->recv_queue = NULL;
1131
1132 if (ws_data->send_queue) {
1133 // Drain send queue before destroying to free allocated message data
1134 // Use buffer_release to match buffer_alloc used for send messages
1135 websocket_recv_msg_t send_msg;
1136 while (ringbuffer_read(ws_data->send_queue, &send_msg)) {
1137 if (send_msg.data) {
1138 buffer_release(send_msg.data);
1139 }
1140 }
1142 ws_data->send_queue = NULL;
1143 }
1144 }
1145
1146 // Free partial buffer (leftover data from previous recv())
1147 if (ws_data->partial_buffer) {
1149 ws_data->partial_buffer = NULL;
1150 ws_data->partial_size = 0;
1151 ws_data->partial_capacity = 0;
1152 }
1153}
1154
1162static void websocket_destroy_impl(acip_transport_t *transport) {
1163 if (!transport || !transport->impl_data) {
1164 return;
1165 }
1166
1168
1169 // Server transport callbacks retain their storage until CLOSED has detached it.
1171 platform_sleep_ms(1);
1172
1173 // Mark transport as destroying and broadcast condition variables
1174 // This signals all waiting threads to wake and exit naturally.
1175 log_debug("[WEBSOCKET_DESTROY] Marking transport as destroying");
1176 atomic_store_bool(&ws_data->is_destroying, true);
1177
1178 // Broadcast all condition variables to wake waiting threads so they can check
1179 // the is_destroying flag and exit gracefully
1180 cond_broadcast(&ws_data->state_cond);
1181 cond_broadcast(&ws_data->recv_cond);
1182
1183 // Cancel any pending libwebsockets service calls to interrupt blocking lws_service()
1184 // This prevents the service thread from getting stuck in lws_service()
1185 if (ws_data->context) {
1186 log_debug("[WEBSOCKET_DESTROY] Cancelling libwebsockets service");
1187 lws_cancel_service(ws_data->context);
1188 }
1189
1190 // Stop service thread (client-side only)
1191 if (ws_data->service_running) {
1192 log_debug("Stopping WebSocket service thread");
1193 thread_join(&ws_data->service_thread, NULL);
1194 ws_data->service_running = false;
1195 log_debug("WebSocket service thread stopped");
1196 }
1197
1198 // Close WebSocket connection gracefully before destroying context
1199 // Skip lws_wsi_close() to avoid segfault in libwebsockets during cleanup
1200 // The context_destroy below will handle cleanup properly
1201 ws_data->wsi = NULL;
1202
1203 // Destroy WebSocket context (only if we own it - client transports only)
1204 if (ws_data->context && ws_data->owns_context) {
1205 lws_context_destroy(ws_data->context);
1206 ws_data->context = NULL;
1207 }
1208
1210 websocket_discard_buffers(ws_data);
1211
1212 // Destroy synchronization primitives
1213 cond_destroy(&ws_data->state_cond);
1214 mutex_destroy(&ws_data->state_mutex);
1215 cond_destroy(&ws_data->recv_cond);
1216 mutex_destroy(&ws_data->recv_mutex);
1217 mutex_destroy(&ws_data->send_mutex);
1218
1219 // Deregister websocket implementation data
1223 NAMED_UNREGISTER(ws_data);
1224
1225 // Clear impl_data pointer BEFORE freeing to prevent use-after-free in callbacks
1226 transport->impl_data = NULL;
1227
1228 // Free the websocket transport data structure
1229 SAFE_FREE(ws_data);
1230
1231 log_debug("Destroyed WebSocket transport resources");
1232}
1233
1234// =============================================================================
1235// WebSocket Transport Method Table
1236// =============================================================================
1237
1238static size_t websocket_queued_bytes(acip_transport_t *transport) {
1239 websocket_transport_data_t *ws = transport->impl_data;
1240 mutex_lock(&ws->send_mutex);
1241 size_t bytes = ws->pending_send_bytes;
1242 mutex_unlock(&ws->send_mutex);
1243 return bytes;
1244}
1245
1246static const acip_transport_methods_t websocket_methods = {
1248 .queued_bytes = websocket_queued_bytes,
1249 .reserved_bytes = SOCKET_STREAM_SEND_RESERVE,
1250 .recv = websocket_recv,
1251 .close = websocket_close,
1252 .interrupt = websocket_interrupt,
1253 .get_type = websocket_get_type,
1254 .get_socket = websocket_get_socket,
1255 .is_connected = websocket_is_connected,
1256 .has_pending_data = websocket_has_pending_data,
1257 .destroy_impl = websocket_destroy_impl,
1258};
1259
1260// =============================================================================
1261// WebSocket Transport Creation
1262// =============================================================================
1263
1275
1279static asciichat_error_t websocket_parse_endpoint(const char *url, websocket_endpoint_t *endpoint) {
1280 url_parts_t parts = {0};
1281 asciichat_error_t result = url_parse(url, &parts);
1282 if (result != ASCIICHAT_OK)
1283 return result;
1284 const char *host = parts.ipv6 ? parts.ipv6 : parts.host;
1285 const char *path = parts.path ? parts.path : "/";
1286 if (!url_is_websocket_scheme(parts.scheme) || parts.userinfo || parts.port > UINT16_MAX || strlen(host) >= sizeof(endpoint->host) || strlen(path) >= sizeof(endpoint->path)) {
1287 url_parts_destroy(&parts);
1288 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid WebSocket endpoint or insufficient storage capacity");
1289 }
1290 endpoint->use_ssl = strlen(parts.scheme) == 3;
1291 endpoint->port = parts.port ? parts.port : endpoint->use_ssl ? 443 : 27226;
1292 SAFE_STRNCPY(endpoint->host, host, sizeof(endpoint->host));
1293 SAFE_STRNCPY(endpoint->path, path, sizeof(endpoint->path));
1294 url_parts_destroy(&parts);
1295 return ASCIICHAT_OK;
1296}
1297
1301static struct lws_context *websocket_create_client_context(void) {
1302 // Create libwebsockets context
1303 // Protocol array must persist for lifetime of context - use static
1304 // Register "http" protocol for WebSocket connections - matches server-side protocol name
1305 // This ensures libwebsockets will invoke our websocket_callback during upgrade handshake and communication
1306 static struct lws_protocols client_protocols[] = {
1307 {
1308 "http", // Default HTTP protocol - handles WebSocket upgrade and ACIP communication
1309 websocket_callback,
1310 0, // Per-session data - using connect_info.userdata instead
1311 524288, // RX buffer size
1312 0, // ID
1313 NULL, // User pointer (set from connect_info.userdata)
1314 524288 // TX packet size
1315 },
1316 {"acip", // Application subprotocol selected by the ACIP WebSocket client
1317 websocket_callback, 0, 524288, 0, NULL, 524288},
1318 {NULL, NULL, 0, 0, 0, NULL, 0} // Terminator
1319 };
1320
1321 // Disable client compression for now - causes assertion in lws_set_extension_option()
1322 // This is a known issue with libwebsockets permessage-deflate negotiation
1323 // Server-side compression is still enabled, data will be compressed from server to client
1324 // but client->server traffic remains uncompressed (acceptable since client sends less data)
1325 // static const struct lws_extension client_extensions[] = {
1326 // {"permessage-deflate", lws_extension_callback_pm_deflate, "permessage-deflate; client_max_window_bits=15"},
1327 // {NULL, NULL, NULL}};
1328
1329 struct lws_context_creation_info info;
1330 memset(&info, 0, sizeof(info));
1331 info.port = CONTEXT_PORT_NO_LISTEN; // Client mode - no listening
1332 info.protocols = client_protocols;
1333 info.gid = (gid_t)-1; // Cast to avoid undefined behavior with unsigned type
1334 info.uid = (uid_t)-1; // Cast to avoid undefined behavior with unsigned type
1335 // Initialize SSL globally for client (required even for clients to use OpenSSL)
1336 // The LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT flag works for both servers and clients
1337 info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
1338 info.extensions = NULL; // Disable client compression due to lws_set_extension_option() assertion
1339
1340 // Increase per-thread service buffer to prevent fragmentation of large messages
1341 // Default is 4KB, causing 291KB frames to fragment into 73 × 4KB chunks
1342 // Increase to 512KB to match server and allow larger WebSocket frames without fragmentation
1343 info.pt_serv_buf_size = 512 * 1024; // 512KB per-thread service buffer
1344
1345 // Configure keep-alive to prevent idle disconnects during handshake
1346 // PING every 30 seconds if idle, close after 35 seconds total with no response
1347 static const lws_retry_bo_t client_keep_alive_policy = {
1348 .secs_since_valid_ping = 30, // Send PING after 30s idle
1349 .secs_since_valid_hangup = 35, // Hangup if still idle after 35s
1350 };
1351 info.retry_and_idle_policy = &client_keep_alive_policy;
1352
1353 // Enable libwebsockets logging through centralized logging system
1355
1356 return lws_create_context(&info);
1357}
1358
1362 struct lws_context *context;
1363};
1364
1366 if (!out || *out)
1367 return SET_ERRNO(ERROR_INVALID_PARAM, "WebSocket runtime output must be empty");
1368 acip_websocket_runtime_t *runtime = SAFE_CALLOC(1, sizeof(*runtime), acip_websocket_runtime_t *);
1369 if (!runtime)
1370 return SET_ERRNO(ERROR_MEMORY, "Could not allocate WebSocket runtime");
1371 // libwebsockets 4.5 calls OPENSSL_cleanup when its last TLS context goes away.
1372 // An application reference prevents connection teardown from ending TLS lifetime.
1373 runtime->context = websocket_create_client_context();
1374 if (!runtime->context) {
1375 SAFE_FREE(runtime);
1376 return SET_ERRNO(ERROR_NETWORK, "Could not initialize WebSocket runtime");
1377 }
1378 *out = runtime;
1379 return ASCIICHAT_OK;
1380}
1381
1383 if (!runtime || !*runtime)
1384 return;
1385 lws_context_destroy((*runtime)->context);
1386 SAFE_FREE(*runtime);
1387 *runtime = NULL;
1388}
1389
1396static acip_transport_t *websocket_allocate_client_transport(const char *name) {
1397 // Allocate transport structure
1399 if (!transport) {
1400 SET_ERRNO(ERROR_MEMORY, "Failed to allocate WebSocket transport");
1401 return NULL;
1402 }
1403 defer_named(release_transport, SAFE_FREE(transport));
1404
1405 // Allocate WebSocket-specific data
1407 if (!ws_data) {
1408 SET_ERRNO(ERROR_MEMORY, "Failed to allocate WebSocket transport data");
1409 return NULL;
1410 }
1411 defer_named(release_data, SAFE_FREE(ws_data));
1412
1413 // Initialize destruction state flag (CALLOC zero-initializes, but explicit for clarity)
1414 atomic_store_bool(&ws_data->is_destroying, false);
1415
1416 // Create receive queue
1418 if (!ws_data->recv_queue) {
1419 SET_ERRNO(ERROR_MEMORY, "Failed to create receive queue");
1420 return NULL;
1421 }
1422 defer_named(release_recv_queue, ringbuffer_destroy(ws_data->recv_queue));
1423
1424 // Create send queue for client transport to buffer outgoing messages
1426 if (!ws_data->send_queue) {
1427 SET_ERRNO(ERROR_MEMORY, "Failed to create send queue");
1428 return NULL;
1429 }
1430 defer_named(release_send_queue, ringbuffer_destroy(ws_data->send_queue));
1431
1432 // Initialize synchronization primitives with transport-aware names
1434 snprintf(recv_name, sizeof(recv_name), "recv_%s", name);
1435 snprintf(state_name, sizeof(state_name), "state_%s", name);
1436
1437 if (mutex_init(&ws_data->recv_mutex, recv_name) != 0) {
1438 SET_ERRNO(ERROR_INTERNAL, "Failed to initialize recv mutex");
1439 return NULL;
1440 }
1441 defer_named(release_recv_mutex, mutex_destroy(&ws_data->recv_mutex));
1442
1443 if (cond_init(&ws_data->recv_cond, recv_name) != 0) {
1444 SET_ERRNO(ERROR_INTERNAL, "Failed to initialize recv condition variable");
1445 return NULL;
1446 }
1447 defer_named(release_recv_cond, cond_destroy(&ws_data->recv_cond));
1448
1449 if (mutex_init(&ws_data->state_mutex, state_name) != 0) {
1450 SET_ERRNO(ERROR_INTERNAL, "Failed to initialize state mutex");
1451 return NULL;
1452 }
1453 defer_named(release_state_mutex, mutex_destroy(&ws_data->state_mutex));
1454
1455 if (cond_init(&ws_data->state_cond, state_name) != 0) {
1456 SET_ERRNO(ERROR_INTERNAL, "Failed to initialize state condition variable");
1457 return NULL;
1458 }
1459 defer_named(release_state_cond, cond_destroy(&ws_data->state_cond));
1460
1461 transport->impl_data = ws_data;
1462 defer_cancel(release_state_cond);
1463 defer_cancel(release_state_mutex);
1464 defer_cancel(release_recv_cond);
1465 defer_cancel(release_recv_mutex);
1466 defer_cancel(release_send_queue);
1467 defer_cancel(release_recv_queue);
1468 defer_cancel(release_data);
1469 defer_cancel(release_transport);
1470 if (transport->methods && acip_outbound_create(transport) != ASCIICHAT_OK) {
1471 acip_transport_destroy(transport);
1472 return NULL;
1473 }
1474 return transport;
1475}
1476
1484acip_transport_t *acip_websocket_client_transport_create(const char *name, const char *url, crypto_context_t *crypto_ctx) {
1485 if (!name) {
1486 SET_ERRNO(ERROR_INVALID_STATE, "Transport name is required");
1487 return NULL;
1488 }
1489
1490 if (!url) {
1491 SET_ERRNO(ERROR_INVALID_PARAM, "url is required");
1492 return NULL;
1493 }
1494
1495 websocket_endpoint_t endpoint;
1496 if (websocket_parse_endpoint(url, &endpoint) != ASCIICHAT_OK) {
1497 return NULL;
1498 }
1499 const char *host = endpoint.host;
1500 const char *path = endpoint.path;
1501 int port = endpoint.port;
1502 bool use_ssl = endpoint.use_ssl;
1503
1504 acip_transport_t *transport = websocket_allocate_client_transport(name);
1505 if (!transport) {
1506 return NULL;
1507 }
1509
1510 ws_data->context = websocket_create_client_context();
1511
1512 if (!ws_data->context) {
1513 cond_destroy(&ws_data->state_cond);
1514 mutex_destroy(&ws_data->state_mutex);
1515 cond_destroy(&ws_data->recv_cond);
1516 mutex_destroy(&ws_data->recv_mutex);
1519 SAFE_FREE(ws_data);
1520 SAFE_FREE(transport);
1521 SET_ERRNO(ERROR_NETWORK, "Failed to create libwebsockets context");
1522 return NULL;
1523 }
1524
1525 // Initialize connection state flags BEFORE calling lws_client_connect_via_info
1526 // The callback might fire immediately, so all fields must be ready
1527 ws_data->is_connected = false; // Will be set to true in LWS_CALLBACK_CLIENT_ESTABLISHED
1528 ws_data->connection_failed = false; // Set to true in LWS_CALLBACK_CLIENT_CONNECTION_ERROR
1529 ws_data->owns_context = true; // Client transport owns the context
1530
1531 // Connect to WebSocket server
1532 log_debug("Initiating WebSocket connection to %s:%d%s", host, port, path);
1533 struct lws_client_connect_info connect_info;
1534 memset(&connect_info, 0, sizeof(connect_info));
1535 connect_info.context = ws_data->context;
1536 connect_info.address = host;
1537 connect_info.port = port;
1538 connect_info.path = path;
1539 connect_info.host = host;
1540 connect_info.origin = host;
1541 // Request the ACIP subprotocol so server routes to acip_protocol handler
1542 // This ensures WebSocket upgrade includes Sec-WebSocket-Protocol: acip
1543 connect_info.local_protocol_name = "acip";
1544 connect_info.protocol = "acip";
1545 // Use SSL + skip server certificate hostname verification + allow self-signed certs (for development)
1546 connect_info.ssl_connection = use_ssl ? (LCCSCF_USE_SSL | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK | LCCSCF_ALLOW_SELFSIGNED) : 0;
1547 connect_info.opaque_user_data = ws_data;
1548
1549 log_debug("Calling lws_client_connect_via_info...");
1550 ws_data->wsi = lws_client_connect_via_info(&connect_info);
1551 log_debug("lws_client_connect_via_info returned: %p", (void *)ws_data->wsi);
1552 if (!ws_data->wsi) {
1553 lws_context_destroy(ws_data->context);
1554 cond_destroy(&ws_data->state_cond);
1555 mutex_destroy(&ws_data->state_mutex);
1556 cond_destroy(&ws_data->recv_cond);
1557 mutex_destroy(&ws_data->recv_mutex);
1560 SAFE_FREE(ws_data);
1561 SAFE_FREE(transport);
1562 SET_ERRNO(ERROR_NETWORK, "Failed to connect to WebSocket server");
1563 return NULL;
1564 }
1565
1566 // Initialize transport
1567 transport->methods = &websocket_methods;
1568 transport->stats_peer = stats_runtime_peer_open("WebSocket");
1569 transport->crypto_ctx = crypto_ctx;
1570 transport->impl_data = ws_data;
1571
1572 // Start service thread immediately - it will drive TLS handshake with frequent polling
1573 // The service thread checks is_destroying and context validity before calling lws_service,
1574 // so it's safe to start it right away without delays.
1575 ws_data->service_running = true;
1576 if (platform_thread_create(&ws_data->service_thread, "ws_service", websocket_service_thread, ws_data) != 0) {
1577 log_error("Failed to create WebSocket service thread");
1578 ws_data->service_running = false;
1579 lws_context_destroy(ws_data->context);
1580 cond_destroy(&ws_data->state_cond);
1581 mutex_destroy(&ws_data->state_mutex);
1582 cond_destroy(&ws_data->recv_cond);
1583 mutex_destroy(&ws_data->recv_mutex);
1586 SAFE_FREE(ws_data);
1588 SAFE_FREE(transport);
1589 SET_ERRNO(ERROR_INTERNAL, "Failed to create service thread");
1590 return NULL;
1591 }
1592 log_debug("WebSocket service thread started");
1593
1594 // Do NOT block the main thread waiting for connection!
1595 // This prevents stdin/keyboard input from being processed and causes the client to hang.
1596 // The service thread will establish the connection asynchronously.
1597 // The protocol layer (recv) will detect if connection fails and handle it there.
1598 // Return immediately so the main thread can respond to keyboard input.
1599 log_debug("WebSocket transport created, service thread will establish connection asynchronously");
1600
1601 // Register transport
1602 NAMED_REGISTER_TRANSPORT(transport, name, NULL);
1603
1604 // Register websocket implementation data with transport as parent
1605 (void)NAMED_REGISTER_WEBSOCKET_IMPL(ws_data, "impl", (uintptr_t)(const void *)(transport));
1606
1607 // Return transport immediately - connection will be established by service thread
1608 // If connection fails, recv() will detect is_connected=false and return error
1609 if (transport->methods && acip_outbound_create(transport) != ASCIICHAT_OK) {
1610 acip_transport_destroy(transport);
1611 return NULL;
1612 }
1613 return transport;
1614}
1615
1619static acip_transport_t *websocket_allocate_server_transport(const char *name) {
1620 // Allocate transport structure
1622 if (!transport) {
1623 SET_ERRNO(ERROR_MEMORY, "Failed to allocate WebSocket transport");
1624 return NULL;
1625 }
1626 defer_named(release_transport, SAFE_FREE(transport));
1627
1628 // Allocate transport-specific data
1630 if (!ws_data) {
1631 SET_ERRNO(ERROR_MEMORY, "Failed to allocate WebSocket transport data");
1632 return NULL;
1633 }
1634 defer_named(release_data, SAFE_FREE(ws_data));
1635
1636 // Initialize receive queue
1638 if (!ws_data->recv_queue) {
1639 SET_ERRNO(ERROR_MEMORY, "Failed to create receive queue");
1640 return NULL;
1641 }
1642 defer_named(release_recv_queue, ringbuffer_destroy(ws_data->recv_queue));
1643
1644 // Initialize send queue (for server-side transports)
1646 if (!ws_data->send_queue) {
1647 SET_ERRNO(ERROR_MEMORY, "Failed to create send queue");
1648 return NULL;
1649 }
1650 defer_named(release_send_queue, ringbuffer_destroy(ws_data->send_queue));
1651
1652 // Initialize synchronization primitives with transport-aware names
1654 snprintf(recv_name, sizeof(recv_name), "recv_%s", name);
1655 snprintf(send_name, sizeof(send_name), "send_%s", name);
1656 snprintf(state_name, sizeof(state_name), "state_%s", name);
1657
1658 if (mutex_init(&ws_data->recv_mutex, recv_name) != 0) {
1659 SET_ERRNO(ERROR_NETWORK, "Failed to initialize recv mutex");
1660 return NULL;
1661 }
1662 defer_named(release_recv_mutex, mutex_destroy(&ws_data->recv_mutex));
1663
1664 if (cond_init(&ws_data->recv_cond, recv_name) != 0) {
1665 SET_ERRNO(ERROR_NETWORK, "Failed to initialize recv condition variable");
1666 return NULL;
1667 }
1668 defer_named(release_recv_cond, cond_destroy(&ws_data->recv_cond));
1669
1670 if (mutex_init(&ws_data->send_mutex, send_name) != 0) {
1671 SET_ERRNO(ERROR_NETWORK, "Failed to initialize send mutex");
1672 return NULL;
1673 }
1674 defer_named(release_send_mutex, mutex_destroy(&ws_data->send_mutex));
1675
1676 if (mutex_init(&ws_data->state_mutex, state_name) != 0) {
1677 SET_ERRNO(ERROR_NETWORK, "Failed to initialize state mutex");
1678 return NULL;
1679 }
1680 defer_named(release_state_mutex, mutex_destroy(&ws_data->state_mutex));
1681
1682 if (cond_init(&ws_data->state_cond, state_name) != 0) {
1683 SET_ERRNO(ERROR_NETWORK, "Failed to initialize state condition variable");
1684 return NULL;
1685 }
1686 defer_named(release_state_cond, cond_destroy(&ws_data->state_cond));
1687
1688 transport->impl_data = ws_data;
1689 defer_cancel(release_state_cond);
1690 defer_cancel(release_state_mutex);
1691 defer_cancel(release_send_mutex);
1692 defer_cancel(release_recv_cond);
1693 defer_cancel(release_recv_mutex);
1694 defer_cancel(release_send_queue);
1695 defer_cancel(release_recv_queue);
1696 defer_cancel(release_data);
1697 defer_cancel(release_transport);
1698 if (transport->methods && acip_outbound_create(transport) != ASCIICHAT_OK) {
1699 acip_transport_destroy(transport);
1700 return NULL;
1701 }
1702 return transport;
1703}
1704
1715acip_transport_t *acip_websocket_server_transport_create(const char *name, struct lws *wsi, crypto_context_t *crypto_ctx) {
1716 if (!name) {
1717 SET_ERRNO(ERROR_INVALID_STATE, "Transport name is required");
1718 return NULL;
1719 }
1720
1721 if (!wsi) {
1722 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid wsi parameter");
1723 return NULL;
1724 }
1725
1726 acip_transport_t *transport = websocket_allocate_server_transport(name);
1727 if (!transport) {
1728 return NULL;
1729 }
1731
1732 // Store connection info (server-side: no context ownership, connection already established)
1733 ws_data->wsi = wsi;
1734
1735 ws_data->context = lws_get_context(wsi); // Get context from wsi (not owned)
1736 ws_data->owns_context = false; // Server owns context, not transport
1737 ws_data->is_connected = true; // Already connected (server-side)
1738 log_debug_every(US_PER_SEC_INT, "★★★ SERVER TRANSPORT CREATED: is_connected=true, wsi=%p, ws_data=%p", (void *)wsi, (void *)ws_data);
1739 log_debug("Server transport created: is_connected=true, wsi=%p", (void *)wsi);
1740
1741 // Initialize transport
1742 transport->methods = &websocket_methods;
1743 transport->stats_peer = stats_runtime_peer_open("WebSocket");
1744 transport->crypto_ctx = crypto_ctx;
1745 transport->impl_data = ws_data;
1746
1747 log_debug_every(US_PER_SEC_INT, "Created WebSocket server transport (crypto: %s)", crypto_ctx ? "enabled" : "disabled");
1748
1749 // Register transport
1750 NAMED_REGISTER_TRANSPORT(transport, name, NULL);
1751
1752 // Register websocket implementation data with transport as parent
1753 (void)NAMED_REGISTER_WEBSOCKET_IMPL(ws_data, "impl", (uintptr_t)(const void *)(transport));
1754
1755 int send_buffer = SOCKET_STREAM_SEND_BUFFER;
1756 if (socket_setsockopt(lws_get_socket_fd(wsi), SOL_SOCKET, SO_SNDBUF, &send_buffer, sizeof(send_buffer)) != 0) {
1757 acip_transport_destroy(transport);
1758 SET_ERRNO_SYS(ERROR_NETWORK, "Cannot bound WebSocket send buffer");
1759 return NULL;
1760 }
1761
1762 if (transport->methods && acip_outbound_create(transport) != ASCIICHAT_OK) {
1763 acip_transport_destroy(transport);
1764 return NULL;
1765 }
1766 return transport;
1767}
bool errno_notifications_suppress(bool suppress)
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
asciichat_error_t acip_outbound_create(acip_transport_t *transport)
void acip_transport_destroy(acip_transport_t *transport)
Destroy transport and free all resources.
asciichat_error_t buffer_set_size(void *data, size_t size)
Definition buffer.c:285
void * buffer_alloc(buffer_domain_t *domain, size_t size)
Definition buffer.c:272
buffer_domain_t * buffer_control_domain(void)
Definition buffer.c:432
struct buffer_domain buffer_domain_t
Definition buffer.h:28
#define buffer_release(data)
Definition buffer.h:99
Hardware-Accelerated CRC32 Checksum Computation.
Named object registry for debugging — log identifiable resource names.
🔄 Network byte order conversion helpers
#define NET_TO_HOST_U16(val)
Definition endian.h:115
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
unsigned char uint8_t
#define NAMED_REGISTER_WEBSOCKET_IMPL(data, name, parent_ptr)
#define NAMED_REGISTER_TRANSPORT(transport, name, parent_ptr)
Register a transport with automatic format specifier.
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_INVALID_STATE
@ ERROR_NETWORK_INCOMPLETE
Definition error_codes.h:94
@ ERROR_NETWORK
Definition error_codes.h:76
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_INTERNAL
Definition error_codes.h:91
@ ERROR_NETWORK_TIMEOUT
Definition error_codes.h:79
#define URL_BUFFER_SIZE
#define HOSTNAME_BUFFER_SIZE
#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_fatal(...)
Log a FATAL message.
Definition log/log.h:640
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define NS_PER_SEC_INT
Definition time.h:173
int time_pretty(uint64_t nanoseconds, int decimals, char *buffer, size_t buffer_size)
Format nanoseconds as a compact duration with configurable sub-minute precision.
Definition time.c:368
#define TIME_DURATION_BUFFER_SIZE
Definition time.h:40
#define US_PER_MS_INT
Definition time.h:176
#define US_PER_SEC_INT
Definition time.h:177
packet_type_t
Network protocol packet type enumeration.
Definition packet.h:315
@ PACKET_TYPE_ERROR_MESSAGE
Error packet with asciichat_error_t code and human-readable message.
Definition packet.h:388
ringbuffer_t * ringbuffer_create(size_t element_size, size_t capacity)
Create a new ring buffer.
Definition ringbuffer.c:34
void ringbuffer_destroy(ringbuffer_t *rb)
Destroy a ring buffer and free its memory.
Definition ringbuffer.c:60
bool ringbuffer_is_empty(const ringbuffer_t *rb)
Check if buffer is empty.
Definition ringbuffer.c:135
bool ringbuffer_read(ringbuffer_t *rb, void *data)
Try to read an element from the ring buffer (non-blocking).
Definition ringbuffer.c:92
bool ringbuffer_write(ringbuffer_t *rb, const void *data)
Try to write an element to the ring buffer (non-blocking).
Definition ringbuffer.c:70
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
void url_parts_destroy(url_parts_t *parts)
Free parsed URL components.
Definition url.c:299
bool url_is_websocket_scheme(const char *scheme)
Check if URL scheme is WebSocket (ws or wss).
Definition url.c:315
asciichat_error_t url_parse(const char *url, url_parts_t *parts_out)
Parse HTTP(S), WebSocket, and TCP URL into components.
Definition url.c:163
int socket_t
Transport abstraction layer for ACIP protocol.
struct acip_websocket_runtime acip_websocket_runtime_t
acip_transport_type_t
Transport method table (virtual function table).
@ ACIP_TRANSPORT_WEBSOCKET
WebSocket over TCP.
Internal WebSocket implementation types shared between transport.c and server.c.
websocket_msg_t websocket_recv_msg_t
Definition internal.h:41
📝 Logging API with multiple log levels and terminal output control
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:743
#define log_dev_every(interval_us, fmt,...)
Rate-limited DEV logging.
Definition log/log.h:740
asciichat_error_t acip_packet_plan(crypto_context_t *crypto, const socket_buffer_t *buffers, size_t count, acip_packet_plan_t *plan)
Definition prepare.c:9
asciichat_error_t acip_packet_encrypt(crypto_context_t *crypto, const acip_packet_plan_t *plan, buffer_domain_t *domain, void *ciphertext, size_t capacity, packet_header_t *header, size_t *length)
The useful part of acip packet plan is in buffers, count, plaintext_size, ciphertext_capacity: togeth...
Definition prepare.c:53
static bool size_t gotel_query_t * out
Definition queries.h:8
Lock-Free Ring Buffer and Frame Buffer Management.
void stats_runtime_peer_close(stats_peer_t *peer)
Definition runtime.c:177
stats_peer_t * stats_runtime_peer_open(const char *transport)
Definition runtime.c:149
🔤 String Manipulation and Shell Escaping Utilities
size_t ciphertext_capacity
Definition prepare.h:24
Transport method table (virtual function table).
void * impl_data
Transport-specific state.
stats_peer_t * stats_peer
Owned statistics handle, destroyed with transport.
const acip_transport_methods_t * methods
Method table (virtual functions).
crypto_context_t * crypto_ctx
Optional encryption context.
uint64_t receive_timeout_ns
Optional TCP receive timeout override; zero uses the normal polling timeout.
struct lws_context * context
Endpoint cryptographic state for handshake, packet protection, authentication, and rekeying.
Fixed prefix shared by every ACIP packet on the wire.
Definition packet.h:641
Structure containing parsed URL components.
Definition url.h:69
char * userinfo
Optional userinfo (user:pass) - may be NULL (allocated if present).
Definition url.h:71
char * path
Extracted path, query, and fragment (allocated if present, may be NULL).
Definition url.h:75
char * ipv6
IPv6 address if host is bracketed IPv6 - may be NULL (allocated if present).
Definition url.h:73
char * scheme
Extracted scheme: "http" or "https" (allocated).
Definition url.h:70
char * host
Canonical ASCII hostname or IP address (allocated).
Definition url.h:72
int port
Extracted port number (0 if not specified).
Definition url.h:74
char host[HOSTNAME_BUFFER_SIZE]
char path[URL_BUFFER_SIZE]
Owned WebSocket frame queued for sending or reassembly.
Definition internal.h:30
size_t len
Frame length in bytes.
Definition internal.h:32
uint8_t first
1 if first frame of message (or complete message)
Definition internal.h:33
uint8_t final
1 if final frame of message (or complete message)
Definition internal.h:34
uint8_t * data
Frame data (allocated, caller must free).
Definition internal.h:31
Private state for one libwebsockets-backed ACIP transport.
Definition internal.h:51
platform_thread_t service_thread
Thread that services libwebsockets context.
Definition internal.h:66
struct lws_context * context
libwebsockets context (may be owned or borrowed)
Definition internal.h:53
mutex_t send_mutex
Protect send_queue operations only.
Definition internal.h:59
bool owns_context
True if transport owns context (client), false if borrowed (server).
Definition internal.h:54
cond_t recv_cond
Signal when recv_queue messages arrive.
Definition internal.h:58
mutex_t state_mutex
Protect state changes.
Definition internal.h:62
uint8_t * inflight_buffer
Owned until the next writable callback or teardown.
Definition internal.h:81
bool service_running
Owner must join the service thread before freeing storage.
Definition internal.h:67
ringbuffer_t * send_queue
Send message queue (for server-side transports).
Definition internal.h:56
size_t partial_capacity
Capacity of partial buffer.
Definition internal.h:74
struct lws * wsi
libwebsockets instance (owned)
Definition internal.h:52
ringbuffer_t * recv_queue
Receive message queue.
Definition internal.h:55
size_t partial_size
Current size of partial buffer.
Definition internal.h:73
cond_t state_cond
Signal when is_connected changes (for connection wait).
Definition internal.h:63
bool connection_failed
Connection attempt failed (for client-side detection).
Definition internal.h:61
bool is_connected
Connection state.
Definition internal.h:60
mutex_t recv_mutex
Protect recv_queue operations only.
Definition internal.h:57
size_t pending_send_bytes
Includes the inflight owner until writable completion.
Definition internal.h:79
uint8_t * partial_buffer
Partial message buffer being assembled.
Definition internal.h:72
atomic_t is_destroying
True when destruction has started.
Definition internal.h:88
⏱️ High-precision timing utilities using sokol_time.h and uthash
🌐 Production-Grade URL Validation and Parsing
#define NETWORK_WEBSOCKET_TRANSPORT_SEND_NAME_BUFFER_SIZE
#define WEBSOCKET_SEND_QUEUE_SIZE
acip_transport_t * acip_websocket_client_transport_create(const char *name, const char *url, crypto_context_t *crypto_ctx)
Create WebSocket client transport.
asciichat_error_t acip_websocket_runtime_create(acip_websocket_runtime_t **out)
asciichat_error_t websocket_transport_send(acip_transport_t *transport, const void *data, size_t len)
#define NETWORK_WEBSOCKET_TRANSPORT_SSL_ERR_BUFFER_SIZE
#define NETWORK_WEBSOCKET_TRANSPORT_RECV_NAME_BUFFER_SIZE
void websocket_transport_write_pending(struct lws *wsi, websocket_transport_data_t *ws_data)
Drain client messages from the send queue on the service thread.
#define WEBSOCKET_RECV_QUEUE_SIZE
asciichat_error_t acip_websocket_transport_flush(acip_transport_t *transport, uint64_t timeout_ns)
Create WebSocket client transport.
acip_transport_t * acip_websocket_server_transport_create(const char *name, struct lws *wsi, crypto_context_t *crypto_ctx)
Create WebSocket server transport from existing connection.
void acip_websocket_runtime_destroy(acip_websocket_runtime_t **runtime)
#define NETWORK_WEBSOCKET_TRANSPORT_STATE_NAME_BUFFER_SIZE
void lws_log_init_client(void)
Initialize libwebsockets logging for client mode.
Definition websocket.c:99
Libwebsockets logging integration.