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

WebSocket transport implementation for ACIP protocol. More...

Go to the source code of this file.

Data Structures

struct  websocket_endpoint_t
struct  acip_websocket_runtime

Macros

#define NETWORK_WEBSOCKET_TRANSPORT_SSL_ERR_BUFFER_SIZE   256
#define NETWORK_WEBSOCKET_TRANSPORT_RECV_NAME_BUFFER_SIZE   64
#define NETWORK_WEBSOCKET_TRANSPORT_STATE_NAME_BUFFER_SIZE   64
#define NETWORK_WEBSOCKET_TRANSPORT_SEND_NAME_BUFFER_SIZE   64
#define WEBSOCKET_MESSAGE_QUEUE_SIZE_INCOMING   64
 Maximum incoming message queue size (frames received from peer).
#define WEBSOCKET_MESSAGE_QUEUE_SIZE_OUTGOING   512
 Maximum outgoing message queue size (frames to send to peer).
#define WEBSOCKET_RECV_QUEUE_SIZE   WEBSOCKET_MESSAGE_QUEUE_SIZE_INCOMING
#define WEBSOCKET_SEND_QUEUE_SIZE   WEBSOCKET_MESSAGE_QUEUE_SIZE_OUTGOING

Functions

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.
asciichat_error_t websocket_transport_send (acip_transport_t *transport, const void *data, size_t len)
asciichat_error_t acip_websocket_transport_flush (acip_transport_t *transport, uint64_t timeout_ns)
 Create WebSocket client transport.
asciichat_error_t acip_websocket_runtime_create (acip_websocket_runtime_t **out)
void acip_websocket_runtime_destroy (acip_websocket_runtime_t **runtime)
acip_transport_t * acip_websocket_client_transport_create (const char *name, const char *url, crypto_context_t *crypto_ctx)
 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.

Detailed Description

WebSocket transport implementation for ACIP protocol.

Implements the acip_transport_t interface for WebSocket connections. Enables browser clients to connect via WebSocket protocol.

ARCHITECTURE:

  • Uses libwebsockets for WebSocket protocol handling
  • Async libwebsockets callbacks bridge to sync recv() via ringbuffer
  • Thread-safe receive queue handles async message arrival
  • Same pattern as WebRTC transport for consistency

MESSAGE FLOW:

  1. send(): Synchronous write via lws_write()
  2. LWS callback: Async write to receive ringbuffer
  3. recv(): Blocking read from receive ringbuffer

MEMORY OWNERSHIP:

  • Transport OWNS wsi (WebSocket instance)
  • Receive queue owns buffered message data
  • recv() allocates message buffer, caller must free
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
February 2026

Definition in file websocket/transport.c.

Macro Definition Documentation

◆ NETWORK_WEBSOCKET_TRANSPORT_RECV_NAME_BUFFER_SIZE

#define NETWORK_WEBSOCKET_TRANSPORT_RECV_NAME_BUFFER_SIZE   64

Definition at line 4 of file websocket/transport.c.

◆ NETWORK_WEBSOCKET_TRANSPORT_SEND_NAME_BUFFER_SIZE

#define NETWORK_WEBSOCKET_TRANSPORT_SEND_NAME_BUFFER_SIZE   64

Definition at line 6 of file websocket/transport.c.

◆ NETWORK_WEBSOCKET_TRANSPORT_SSL_ERR_BUFFER_SIZE

#define NETWORK_WEBSOCKET_TRANSPORT_SSL_ERR_BUFFER_SIZE   256

Definition at line 3 of file websocket/transport.c.

◆ NETWORK_WEBSOCKET_TRANSPORT_STATE_NAME_BUFFER_SIZE

#define NETWORK_WEBSOCKET_TRANSPORT_STATE_NAME_BUFFER_SIZE   64

Definition at line 5 of file websocket/transport.c.

◆ WEBSOCKET_MESSAGE_QUEUE_SIZE_INCOMING

#define WEBSOCKET_MESSAGE_QUEUE_SIZE_INCOMING   64

Maximum incoming message queue size (frames received from peer).

Set to 64 for balance: allows buffering across one large frame's fragments while keeping latency reasonable. With ~70 fragments per 291KB frame, we need at least 64 slots to avoid dropping the frame while it's fragmenting.

Definition at line 72 of file websocket/transport.c.

◆ WEBSOCKET_MESSAGE_QUEUE_SIZE_OUTGOING

#define WEBSOCKET_MESSAGE_QUEUE_SIZE_OUTGOING   512

Maximum outgoing message queue size (frames to send to peer).

Set to 64 to match incoming queue and prevent "BINARY after FIN" errors. Large video frames fragment into ~70 chunks; queue must be large enough to buffer one complete message worth of fragments.

Definition at line 81 of file websocket/transport.c.

◆ WEBSOCKET_RECV_QUEUE_SIZE

#define WEBSOCKET_RECV_QUEUE_SIZE   WEBSOCKET_MESSAGE_QUEUE_SIZE_INCOMING

Definition at line 84 of file websocket/transport.c.

◆ WEBSOCKET_SEND_QUEUE_SIZE

#define WEBSOCKET_SEND_QUEUE_SIZE   WEBSOCKET_MESSAGE_QUEUE_SIZE_OUTGOING

Definition at line 85 of file websocket/transport.c.

Function Documentation

◆ acip_websocket_client_transport_create()

acip_transport_t * acip_websocket_client_transport_create ( const char * name,
const char * url,
crypto_context_t * crypto_ctx )

Create WebSocket client transport.

Parameters
urlWebSocket URL (e.g., "ws://localhost:27225")
crypto_ctxOptional encryption context (can be NULL)
Returns
Transport instance or NULL on failure

Definition at line 1484 of file websocket/transport.c.

1484 {
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);
1517 ringbuffer_destroy(ws_data->send_queue);
1518 ringbuffer_destroy(ws_data->recv_queue);
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);
1558 ringbuffer_destroy(ws_data->send_queue);
1559 ringbuffer_destroy(ws_data->recv_queue);
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);
1584 ringbuffer_destroy(ws_data->send_queue);
1585 ringbuffer_destroy(ws_data->recv_queue);
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}
#define SET_ERRNO(code,...)
asciichat_error_t acip_outbound_create(acip_transport_t *transport)
void acip_transport_destroy(acip_transport_t *transport)
Destroy transport and free all resources.
#define SAFE_FREE(ptr)
#define NAMED_REGISTER_WEBSOCKET_IMPL(data, name, parent_ptr)
#define NAMED_REGISTER_TRANSPORT(transport, name, parent_ptr)
Register a transport with automatic format specifier.
@ ERROR_INVALID_STATE
@ ERROR_NETWORK
Definition error_codes.h:76
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_INTERNAL
Definition error_codes.h:91
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
void ringbuffer_destroy(ringbuffer_t *rb)
Destroy a ring buffer and free its memory.
Definition ringbuffer.c:60
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
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
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.
char host[HOSTNAME_BUFFER_SIZE]
char path[URL_BUFFER_SIZE]
Private state for one libwebsockets-backed ACIP transport.
Definition internal.h:51

References acip_outbound_create(), acip_transport_destroy(), ASCIICHAT_OK, websocket_transport_data_t::connection_failed, websocket_transport_data_t::context, acip_transport::crypto_ctx, ERROR_INTERNAL, ERROR_INVALID_PARAM, ERROR_INVALID_STATE, ERROR_NETWORK, websocket_endpoint_t::host, acip_transport::impl_data, websocket_transport_data_t::is_connected, log_debug, log_error, acip_transport::methods, NAMED_REGISTER_TRANSPORT, NAMED_REGISTER_WEBSOCKET_IMPL, websocket_transport_data_t::owns_context, websocket_endpoint_t::path, websocket_endpoint_t::port, websocket_transport_data_t::recv_cond, websocket_transport_data_t::recv_mutex, websocket_transport_data_t::recv_queue, ringbuffer_destroy(), SAFE_FREE, websocket_transport_data_t::send_queue, websocket_transport_data_t::service_running, websocket_transport_data_t::service_thread, SET_ERRNO, websocket_transport_data_t::state_cond, websocket_transport_data_t::state_mutex, acip_transport::stats_peer, stats_runtime_peer_close(), stats_runtime_peer_open(), websocket_endpoint_t::use_ssl, and websocket_transport_data_t::wsi.

Referenced by network_connection_open().

◆ acip_websocket_runtime_create()

asciichat_error_t acip_websocket_runtime_create ( acip_websocket_runtime_t ** out)

Definition at line 1365 of file websocket/transport.c.

1365 {
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}
#define SAFE_CALLOC(count, size, cast)
@ ERROR_MEMORY
Definition error_codes.h:55
struct acip_websocket_runtime acip_websocket_runtime_t
static bool size_t gotel_query_t * out
Definition queries.h:8
struct lws_context * context

References ASCIICHAT_OK, acip_websocket_runtime::context, ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_NETWORK, out, SAFE_CALLOC, SAFE_FREE, and SET_ERRNO.

Referenced by discovery_main().

◆ acip_websocket_runtime_destroy()

void acip_websocket_runtime_destroy ( acip_websocket_runtime_t ** runtime)

Definition at line 1382 of file websocket/transport.c.

1382 {
1383 if (!runtime || !*runtime)
1384 return;
1385 lws_context_destroy((*runtime)->context);
1386 SAFE_FREE(*runtime);
1387 *runtime = NULL;
1388}

References SAFE_FREE.

Referenced by discovery_main().

◆ acip_websocket_server_transport_create()

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.

Wraps an already-established libwebsockets connection (from server accept). Used by websocket_server module to create transports for incoming clients.

Parameters
wsiEstablished libwebsockets connection (not owned by transport)
crypto_ctxOptional crypto context
Returns
Transport instance or NULL on error

Definition at line 1715 of file websocket/transport.c.

1715 {
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}
#define SET_ERRNO_SYS(code,...)
#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 acip_outbound_create(), acip_transport_destroy(), ASCIICHAT_OK, websocket_transport_data_t::context, acip_transport::crypto_ctx, ERROR_INVALID_PARAM, ERROR_INVALID_STATE, ERROR_NETWORK, acip_transport::impl_data, websocket_transport_data_t::is_connected, log_debug, log_debug_every, acip_transport::methods, NAMED_REGISTER_TRANSPORT, NAMED_REGISTER_WEBSOCKET_IMPL, websocket_transport_data_t::owns_context, SET_ERRNO, SET_ERRNO_SYS, acip_transport::stats_peer, stats_runtime_peer_open(), US_PER_SEC_INT, and websocket_transport_data_t::wsi.

◆ acip_websocket_transport_flush()

asciichat_error_t acip_websocket_transport_flush ( acip_transport_t * transport,
uint64_t timeout_ns )

Create WebSocket client transport.

Connects to a WebSocket server at the specified URL and creates a transport for sending/receiving ACIP packets over the WebSocket connection.

Parameters
nameDebug name for tracking this transport (required, e.g., "transport_websocket_client")
urlWebSocket URL (e.g., "ws://localhost:27225" or "wss://example.com/path")
crypto_ctxOptional encryption context (can be NULL)
Returns
Transport instance or NULL on failure
Note
The URL must include the protocol (ws:// or wss://)
Port defaults to 80 for ws:// and 443 for wss:// if not specified
Connection is established synchronously during creation Wait for queued messages to reach their writable completion callback. Call from a worker, never from the libwebsockets service thread.

Definition at line 1037 of file websocket/transport.c.

1037 {
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}
unsigned long long uint64_t
@ ERROR_NETWORK_TIMEOUT
Definition error_codes.h:79
bool ringbuffer_is_empty(const ringbuffer_t *rb)
Check if buffer is empty.
Definition ringbuffer.c:135
@ ACIP_TRANSPORT_WEBSOCKET
WebSocket over TCP.
mutex_t send_mutex
Protect send_queue operations only.
Definition internal.h:59
uint8_t * inflight_buffer
Owned until the next writable callback or teardown.
Definition internal.h:81
ringbuffer_t * send_queue
Send message queue (for server-side transports).
Definition internal.h:56

References ACIP_TRANSPORT_WEBSOCKET, ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, ERROR_NETWORK_TIMEOUT, acip_transport::impl_data, websocket_transport_data_t::inflight_buffer, ringbuffer_is_empty(), websocket_transport_data_t::send_mutex, websocket_transport_data_t::send_queue, and SET_ERRNO.

◆ websocket_transport_send()

asciichat_error_t websocket_transport_send ( acip_transport_t * transport,
const void * data,
size_t len )

Queue one packet, preserving its control budget through encryption and ownership transfer.

Definition at line 614 of file websocket/transport.c.

614 {
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}
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
#define NET_TO_HOST_U16(val)
Definition endian.h:115
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
#define US_PER_MS_INT
Definition time.h:176
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
#define log_dev_every(interval_us, fmt,...)
Rate-limited DEV logging.
Definition log/log.h:740
Fixed prefix shared by every ACIP packet on the wire.
Definition packet.h:641

References ASCIICHAT_OK, buffer_control_domain(), buffer_release, websocket_transport_data_t::connection_failed, ERROR_NETWORK, acip_transport::impl_data, websocket_transport_data_t::is_connected, log_debug, log_dev_every, log_error, NET_TO_HOST_U16, websocket_transport_data_t::owns_context, PACKET_TYPE_ERROR_MESSAGE, SET_ERRNO, websocket_transport_data_t::state_mutex, US_PER_MS_INT, and websocket_transport_data_t::wsi.

◆ websocket_transport_write_pending()

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.

Definition at line 440 of file websocket/transport.c.

440 {
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}
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
bool ringbuffer_read(ringbuffer_t *rb, void *data)
Try to read an element from the ring buffer (non-blocking).
Definition ringbuffer.c:92
websocket_msg_t websocket_recv_msg_t
Definition internal.h:41
size_t len
Frame length in bytes.
Definition internal.h:32
uint8_t * data
Frame data (allocated, caller must free).
Definition internal.h:31
mutex_t state_mutex
Protect state changes.
Definition internal.h:62
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
size_t pending_send_bytes
Includes the inflight owner until writable completion.
Definition internal.h:79
atomic_t is_destroying
True when destruction has started.
Definition internal.h:88

References atomic_load_bool(), buffer_release, websocket_transport_data_t::connection_failed, websocket_msg_t::data, websocket_transport_data_t::inflight_buffer, websocket_transport_data_t::inflight_bytes, websocket_transport_data_t::is_connected, websocket_transport_data_t::is_destroying, websocket_msg_t::len, websocket_transport_data_t::pending_send_bytes, ringbuffer_read(), websocket_transport_data_t::send_mutex, websocket_transport_data_t::send_queue, websocket_transport_data_t::state_cond, and websocket_transport_data_t::state_mutex.