ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
transport.h File Reference

Transport abstraction layer for ACIP protocol. More...

Go to the source code of this file.

Data Structures

struct  acip_transport_capabilities_t
 The useful part of acip transport capabilities is in independent_streams, datagrams, max_datagram_payload: together they describe what is pending, who owns it, and how much data is valid. Keep the object with its parent operation and use the parent cleanup path. application data in one QUIC DATAGRAM frame on the current path, including any transport-specific envelope. Query again after path changes. More...
struct  acip_transport_methods_t
 Transport method table (virtual function table). More...
struct  acip_transport
 Transport instance structure. More...

Typedefs

typedef struct acip_websocket_runtime acip_websocket_runtime_t

Enumerations

enum  acip_transport_type_t {
  ACIP_TRANSPORT_TCP = 1 , ACIP_TRANSPORT_WEBSOCKET = 2 , ACIP_TRANSPORT_WEBRTC = 3 , ACIP_TRANSPORT_HTTP = 4 ,
  ACIP_TRANSPORT_QUIC = 5
}
 Transport method table (virtual function table). More...
enum  acip_transport_ownership_t { ACIP_TRANSPORT_BORROWED , ACIP_TRANSPORT_OWNED }

Functions

void acip_transport_destroy (acip_transport_t *transport)
 Destroy transport and free all resources.
asciichat_error_t acip_transport_sendv (acip_transport_t *transport, const socket_buffer_t *buffers, size_t count)
 Send data through transport.
asciichat_error_t acip_transport_sendv_ex (acip_transport_t *transport, const socket_buffer_t *buffers, size_t count, const acip_send_options_t *options)
asciichat_error_t acip_transport_get_capabilities (acip_transport_t *transport, acip_transport_capabilities_t *out)
asciichat_error_t acip_transport_send (acip_transport_t *transport, const void *data, size_t len)
acip_transport_t * acip_tcp_transport_create (const char *name, socket_t sockfd, crypto_context_t *crypto_ctx)
 Create TCP transport from existing socket.
acip_transport_t * acip_tcp_transport_create_owned (const char *name, socket_t sockfd, crypto_context_t *crypto_ctx)
 Create a TCP transport that owns its connected socket.
asciichat_error_t acip_tcp_transport_set_zerocopy (acip_transport_t *transport, bool enabled)
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.
acip_transport_t * acip_webrtc_transport_create (struct webrtc_peer_connection *peer_conn, struct webrtc_data_channel *data_channel, crypto_context_t *crypto_ctx)

Detailed Description

Transport abstraction layer for ACIP protocol.

Provides a transport-agnostic interface that allows ACIP protocol handlers to work with any underlying transport (TCP, WebSocket, HTTP, etc.).

Transport Layer Design

Architecture

The transport layer abstracts protocol delivery, allowing the same ACIP protocol handlers to work with multiple underlying transports:

  • TCP (acip_tcp_transport_create): Raw TCP sockets, binary packet streaming
  • WebSocket (acip_websocket_client_transport_create): HTTP upgrade, frame-based
  • WebRTC (acip_webrtc_transport_create): P2P data channels, encryption at transport
  • HTTP (reserved): Long-polling, REST-style transport slot
  • QUIC: UDP-based transport with congestion control and optional datagrams

Design Principles

  1. Protocol code never calls socket()/send()/recv() directly
  2. Same ACIP handlers work with any transport implementation
  3. Each transport handles its own connection state and reliability
  4. Clean separation between protocol logic (acip_*) and transport logic

Packet Framing

Transports handle packet framing transparently:

  • TCP: Uses packet_header_t (magic + type + length + CRC32 + client_id)
  • WebSocket: Wraps packets in WebSocket frames
  • WebRTC: Sends packets directly on data channel

Version Information

  • Transport API Version: 1.0 (stable)
  • Supported ACIP Version: 1.0

DESIGN GOALS:

  1. Protocol code never calls socket()/send()/recv() directly
  2. Same ACIP handlers work with TCP, WebSocket, WebRTC, QUIC, or another backend
  3. Transport implementations handle their own connection state
  4. Clean separation between protocol logic and transport logic

USAGE PATTERN:

// Create TCP transport from existing socket
acip_transport_t *tcp = acip_tcp_transport_create(sockfd, crypto_ctx);
// Send packet with type-specific helper
asciichat_error_t result = acip_send_ascii_frame(tcp, frame_data, frame_size, ...);
// Receive packet with dispatcher
// Or create WebSocket client transport
acip_transport_t *ws = acip_websocket_client_transport_create("ws://localhost:27225", crypto_ctx);
asciichat_error_t result = acip_send_ascii_frame(ws, frame_data, frame_size, ...);
// Cleanup
void acip_transport_destroy(acip_transport_t *transport)
Destroy transport and free all resources.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
asciichat_error_t acip_client_receive_and_dispatch(acip_transport_t *transport, const acip_client_callbacks_t *callbacks)
Receive packet from server and dispatch to callbacks.
asciichat_error_t acip_send_ascii_frame(acip_transport_t *transport, acip_frame_workspace_t *workspace, const char *text, size_t length, uint32_t width, uint32_t height, const char *client_id)
acip_transport_t * acip_tcp_transport_create(const char *name, socket_t sockfd, crypto_context_t *crypto_ctx)
Create TCP transport from existing socket.
acip_transport_t * acip_websocket_client_transport_create(const char *name, const char *url, crypto_context_t *crypto_ctx)
Create WebSocket client transport.

MEMORY OWNERSHIP:

  • Transport owns its connection state (socket, pointers, etc.)
  • send() does NOT take ownership of data (caller must keep it valid)
  • recv() allocates buffer, caller must free via out_allocated_buffer
  • destroy() cleans up all transport resources and frees transport structure
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
January 2026
Version
1.0 (Transport API)

Definition in file include/ascii-chat/network/acip/transport.h.

Typedef Documentation

◆ acip_websocket_runtime_t

Application lifetime reference for libwebsockets TLS initialization. Keep it alive across connection contexts and release it after the last user.

Definition at line 466 of file include/ascii-chat/network/acip/transport.h.

Enumeration Type Documentation

◆ acip_transport_ownership_t

Ownership transfers only after successful registration.

Enumerator
ACIP_TRANSPORT_BORROWED 
ACIP_TRANSPORT_OWNED 

Definition at line 132 of file include/ascii-chat/network/acip/transport.h.

◆ acip_transport_type_t

Transport method table (virtual function table).

This is the handoff point for acip transport. Callers fill outbound, stats_peer, methods, crypto_ctx before passing it on; consumers read the values during the operation and return ownership only where the member contract explicitly says they do.

Transport type enumeration

Identifies which transport implementation is being used. Useful for debugging and conditional logic.

Enumerator
ACIP_TRANSPORT_TCP 

Raw TCP socket.

ACIP_TRANSPORT_WEBSOCKET 

WebSocket over TCP.

ACIP_TRANSPORT_WEBRTC 

WebRTC DataChannel (P2P).

ACIP_TRANSPORT_HTTP 

HTTP long-polling (future).

ACIP_TRANSPORT_QUIC 

QUIC/UDP (future).

Definition at line 104 of file include/ascii-chat/network/acip/transport.h.

104 {
acip_transport_type_t
Transport method table (virtual function table).
@ ACIP_TRANSPORT_TCP
Raw TCP socket.
@ ACIP_TRANSPORT_WEBSOCKET
WebSocket over TCP.
@ ACIP_TRANSPORT_WEBRTC
WebRTC DataChannel (P2P).
@ ACIP_TRANSPORT_HTTP
HTTP long-polling (future).
@ ACIP_TRANSPORT_QUIC
QUIC/UDP (future).

Function Documentation

◆ acip_tcp_transport_create()

acip_transport_t * acip_tcp_transport_create ( const char * name,
socket_t sockfd,
crypto_context_t * crypto_ctx )

Create TCP transport from existing socket.

Parameters
nameDebug name for tracking this transport (required, e.g., "transport_client_5")
sockfdConnected socket descriptor
crypto_ctxOptional crypto context (may be NULL)
Returns
Transport instance or NULL on error
Note
Caller retains socket ownership (transport doesn't close on destroy)

Definition at line 285 of file tcp/transport.c.

285 {
286 if (!name) {
287 SET_ERRNO(ERROR_INVALID_STATE, "Transport name is required");
288 return NULL;
289 }
290
291 if (sockfd == INVALID_SOCKET_VALUE) {
292 log_error("[TCP_CREATE_STATE] ❌ INVALID_SOCKET: sockfd=%d", sockfd);
293 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid socket descriptor");
294 return NULL;
295 }
296
297 log_info("[TCP_CREATE_STATE] 🟢 CREATE_START: sockfd=%d, crypto=%s", sockfd, crypto_ctx ? "yes" : "no");
298
299 // Allocate transport structure
301 if (!transport) {
302 log_error("[TCP_CREATE_STATE] ❌ ALLOC_TRANSPORT_FAILED: size=%zu", sizeof(acip_transport_t));
303 SET_ERRNO(ERROR_MEMORY, "Failed to allocate TCP transport");
304 return NULL;
305 }
306
307 log_debug("[TCP_CREATE_STATE] 🟢 TRANSPORT_ALLOCATED: transport=%p", (void *)transport);
308
309 // Allocate TCP-specific data
311 if (!tcp_data) {
312 log_error("[TCP_CREATE_STATE] ❌ ALLOC_TCP_DATA_FAILED: size=%zu", sizeof(tcp_transport_data_t));
313 SAFE_FREE(transport);
314 SET_ERRNO(ERROR_MEMORY, "Failed to allocate TCP transport data");
315 return NULL;
316 }
317
318 log_debug("[TCP_CREATE_STATE] 🟢 TCP_DATA_ALLOCATED: tcp_data=%p", (void *)tcp_data);
319
320 // Initialize TCP data
321 tcp_data->sockfd = sockfd;
322 tcp_data->is_connected = true;
323 tcp_data->owns_socket = false;
324 tcp_data->zerocopy_disabled = false;
325
326 // Initialize send mutex to protect concurrent sends from multiple threads
327 int mutex_result = mutex_init(&tcp_data->send_mutex, "tcp_send");
328 if (mutex_result != 0) {
329 log_error("[TCP_CREATE_STATE] ❌ MUTEX_INIT_FAILED: result=%d", mutex_result);
330 SAFE_FREE(tcp_data);
331 SAFE_FREE(transport);
332 SET_ERRNO(ERROR_MEMORY, "Failed to initialize send mutex");
333 return NULL;
334 }
335
336 log_info("[TCP_CREATE_STATE] 🟢 TCP_DATA_INITIALIZED: sockfd=%d, is_connected=true, send_mutex=initialized", sockfd);
337
338 // Enable TCP_NODELAY to disable Nagle's algorithm
339 // This ensures small packets are sent immediately instead of being buffered
340 int nodelay = 1;
341 if (setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (const char *)&nodelay, sizeof(nodelay)) < 0) {
342 log_warn("[TCP_CREATE_STATE] ⚠️ TCP_NODELAY_FAILED: sockfd=%d, %s", sockfd, SAFE_STRERROR(errno));
343 // Continue anyway - this is not fatal
344 } else {
345 log_debug("[TCP_CREATE_STATE] 🟢 TCP_NODELAY_SET: sockfd=%d", sockfd);
346 }
347
348 // Initialize transport
349 transport->methods = &tcp_methods;
350 transport->stats_peer = stats_runtime_peer_open("TCP");
351 transport->crypto_ctx = crypto_ctx;
352 transport->impl_data = tcp_data;
353 int send_buffer = SOCKET_STREAM_SEND_BUFFER;
354 if (socket_setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &send_buffer, sizeof(send_buffer)) != 0) {
355 acip_transport_destroy(transport);
356 SET_ERRNO_SYS(ERROR_NETWORK, "Cannot bound TCP send buffer");
357 return NULL;
358 }
359
360 // Register transport and impl_data before logging so named replacements work
361 NAMED_REGISTER_TRANSPORT(transport, name, NULL);
362 NAMED_REGISTER(tcp_data, "impl", "tcp_impl", "0x%tx", (uintptr_t)(const void *)(transport));
363
364 log_info("[TCP_CREATE_STATE] ✅ CREATE_COMPLETE: transport=%p, sockfd=%d, is_connected=true, crypto=%s", (void *)transport, sockfd, crypto_ctx ? "enabled" : "disabled");
365
366#ifndef __EMSCRIPTEN__
367 if (transport && acip_outbound_create(transport) != ASCIICHAT_OK) {
368 acip_transport_destroy(transport);
369 return NULL;
370 }
371#endif
372 return transport;
373}
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
asciichat_error_t acip_outbound_create(acip_transport_t *transport)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_STRERROR(errnum)
#define SAFE_CALLOC(count, size, cast)
#define NAMED_REGISTER_TRANSPORT(transport, name, parent_ptr)
Register a transport with automatic format specifier.
#define NAMED_REGISTER(ptr, name, type, fmt, parent_ptr)
Register any pointer with base name, type, format spec, and location (auto-suffix).
@ ERROR_INVALID_STATE
@ ERROR_NETWORK
Definition error_codes.h:77
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
stats_peer_t * stats_runtime_peer_open(const char *transport)
Definition runtime.c:161
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.
tcp transport data is intentionally a small, concrete record. Fields such as sockfd,...
bool owns_socket
Close the socket when this transport is closed or destroyed.
socket_t sockfd
Connected socket descriptor.
bool is_connected
Connection state.
mutex_t send_mutex
Mutex to protect concurrent sends (multiple threads may send packets).
bool zerocopy_disabled
Disable copy avoidance after unsupported or copied completion.
void acip_transport_destroy(acip_transport_t *transport)
Destroy transport and free all resources.

References acip_outbound_create(), acip_transport_destroy(), ASCIICHAT_OK, acip_transport::crypto_ctx, ERROR_INVALID_PARAM, ERROR_INVALID_STATE, ERROR_MEMORY, ERROR_NETWORK, ERROR_NOT_SUPPORTED, acip_transport::impl_data, tcp_transport_data_t::is_connected, log_debug, log_error, log_info, log_warn, acip_transport::methods, NAMED_REGISTER, NAMED_REGISTER_TRANSPORT, tcp_transport_data_t::owns_socket, SAFE_CALLOC, SAFE_FREE, SAFE_MALLOC, SAFE_STRERROR, tcp_transport_data_t::send_mutex, SET_ERRNO, SET_ERRNO_SYS, tcp_transport_data_t::sockfd, acip_transport::stats_peer, stats_runtime_peer_open(), and tcp_transport_data_t::zerocopy_disabled.

Referenced by acip_tcp_transport_create_owned().

◆ acip_tcp_transport_create_owned()

acip_transport_t * acip_tcp_transport_create_owned ( const char * name,
socket_t sockfd,
crypto_context_t * crypto_ctx )

Create a TCP transport that owns its connected socket.

Parameters
nameDebug name for the transport
sockfdConnected socket; ownership transfers only on success
crypto_ctxOptional borrowed crypto context
Returns
Transport instance or NULL on error Closing or destroying the transport closes the socket.

Definition at line 375 of file tcp/transport.c.

375 {
376 acip_transport_t *transport = acip_tcp_transport_create(name, sockfd, crypto_ctx);
377 if (transport)
378 ((tcp_transport_data_t *)transport->impl_data)->owns_socket = true;
379 return transport;
380}

References acip_tcp_transport_create(), and acip_transport::impl_data.

◆ acip_tcp_transport_set_zerocopy()

asciichat_error_t acip_tcp_transport_set_zerocopy ( acip_transport_t * transport,
bool enabled )

Override the automatic kernel copy-avoidance policy for this TCP transport. Large Linux encrypted sends may pin pages; other platforms fall back to vectors. Copy avoidance is attempted automatically and disabled after copied completions.

Definition at line 113 of file tcp/transport.c.

113 {
114 if (!transport || acip_transport_get_type(transport) != ACIP_TRANSPORT_TCP)
115 return SET_ERRNO(ERROR_INVALID_PARAM, "Expected TCP transport");
116 tcp_transport_data_t *tcp = transport->impl_data;
117 mutex_lock(&tcp->send_mutex);
119 mutex_unlock(&tcp->send_mutex);
120 return ASCIICHAT_OK;
121}
bool enabled
Is filtering active?
Definition grep.c:63

References ACIP_TRANSPORT_TCP, ASCIICHAT_OK, enabled, ERROR_INVALID_PARAM, acip_transport::impl_data, tcp_transport_data_t::send_mutex, SET_ERRNO, and tcp_transport_data_t::zerocopy_disabled.

◆ acip_transport_destroy()

void acip_transport_destroy ( acip_transport_t * transport)

Destroy transport and free all resources.

Parameters
transportTransport to destroy (may be NULL)
Note
Calls close() first if still connected
Frees the transport structure itself
Safe to pass NULL

Definition at line 243 of file browser/transport.c.

243 {
244 if (!transport)
245 return;
246 if (transport->methods && transport->methods->close && transport->methods->is_connected && transport->methods->is_connected(transport))
247 transport->methods->close(transport);
248 if (transport->crypto_ctx) {
249 crypto_destroy(transport->crypto_ctx);
250 SAFE_FREE(transport->crypto_ctx);
251 }
253}
void browser_transport_destroy(browser_transport_t *browser)
void crypto_destroy(crypto_context_t *ctx)
Cleanup crypto context with secure memory wiping.
struct browser_transport browser_transport_t
bool(* is_connected)(acip_transport_t *transport)
Check if transport is connected.
asciichat_error_t(* close)(acip_transport_t *transport)
Close this transport.

References acip_outbound_destroy(), ASCIICHAT_OK, browser_transport_destroy(), acip_transport_methods_t::close, acip_transport::crypto_ctx, crypto_destroy(), acip_transport_methods_t::destroy_impl, acip_transport_methods_t::get_type, acip_transport::impl_data, acip_transport_methods_t::is_connected, log_debug, log_warn, acip_transport::methods, NAMED_UNREGISTER, SAFE_FREE, acip_transport::stats_peer, and stats_runtime_peer_close().

Referenced by acip_async_tcp_accepted_create(), acip_async_tcp_client_create(), acip_async_tcp_transport_create(), acip_tcp_transport_create(), acip_websocket_client_transport_create(), acip_websocket_server_transport_create(), network_connection_open(), and quic_release().

◆ acip_transport_get_capabilities()

asciichat_error_t acip_transport_get_capabilities ( acip_transport_t * transport,
acip_transport_capabilities_t * out )

A backend with no capability method reports no optional capabilities. Negotiated backends can return ERROR_INVALID_STATE until negotiation finishes.

Definition at line 101 of file send.c.

101 {
102 if (!out)
103 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing transport capabilities output");
105 if (!transport || !transport->methods)
106 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid transport capabilities query");
107 return transport->methods->get_capabilities ? transport->methods->get_capabilities(transport, out) : ASCIICHAT_OK;
108}
static bool size_t gotel_query_t * out
Definition queries.h:10
The useful part of acip transport capabilities is in independent_streams, datagrams,...
asciichat_error_t(* get_capabilities)(acip_transport_t *transport, acip_transport_capabilities_t *out)

References ASCIICHAT_OK, ERROR_INVALID_PARAM, acip_transport_methods_t::get_capabilities, acip_transport::methods, out, and SET_ERRNO.

Referenced by packet_send_via_transportv().

◆ acip_transport_send()

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

Definition at line 145 of file send.c.

145 {
146 socket_buffer_t buffer = {data, len};
147 return acip_transport_sendv(transport, &buffer, 1);
148}
asciichat_error_t acip_transport_sendv(acip_transport_t *transport, const socket_buffer_t *buffers, size_t count)
Send data through transport.
Definition send.c:135

References acip_transport_sendv().

Referenced by browser_session_send().

◆ acip_transport_sendv()

asciichat_error_t acip_transport_sendv ( acip_transport_t * transport,
const socket_buffer_t * buffers,
size_t count )

Send data through transport.

Convenience wrapper around transport->methods->send().

Parameters
transportTransport instance
dataData to send
lenData length
Returns
ASCIICHAT_OK on success, error code on failure

Definition at line 135 of file send.c.

135 {
136 acip_send_options_t options = {.traffic_class = ACIP_TRAFFIC_CONTROL, .delivery = ACIP_DELIVERY_RELIABLE};
137 if (buffers && count && buffers[0].data && buffers[0].len >= sizeof(packet_header_t)) {
138 packet_header_t header;
139 memcpy(&header, buffers[0].data, sizeof(header));
141 }
142 return acip_transport_sendv_ex(transport, buffers, count, &options);
143}
#define NET_TO_HOST_U16(val)
Definition endian.h:115
asciichat_error_t acip_transport_sendv_ex(acip_transport_t *transport, const socket_buffer_t *buffers, size_t count, const acip_send_options_t *options)
Definition send.c:110
acip_traffic_class_t traffic_class
Definition traffic.h:21
Fixed prefix shared by every ACIP packet on the wire.
Definition packet.h:641
acip_traffic_class_t acip_packet_traffic_class(uint16_t type)
Definition traffic.c:4
@ ACIP_TRAFFIC_CONTROL
Definition traffic.h:10
@ ACIP_DELIVERY_RELIABLE
Definition traffic.h:16

References ACIP_DELIVERY_RELIABLE, acip_packet_traffic_class(), ACIP_TRAFFIC_CONTROL, acip_transport_sendv_ex(), NET_TO_HOST_U16, and acip_send_options_t::traffic_class.

Referenced by acip_transport_send().

◆ acip_transport_sendv_ex()

asciichat_error_t acip_transport_sendv_ex ( acip_transport_t * transport,
const socket_buffer_t * buffers,
size_t count,
const acip_send_options_t * options )

Send with explicit delivery metadata. Unsupported datagrams or deadlines return ERROR_NOT_SUPPORTED and are never silently changed into reliable delivery. A deadline uses time_get_ns()'s monotonic clock.

Definition at line 110 of file send.c.

110 {
111 if (!transport || !transport->methods || !buffers || !count || count > SOCKET_IOV_MAX || !options || (unsigned)options->traffic_class > ACIP_TRAFFIC_VISUAL ||
113 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid transport send options");
114 if (options->delivery != ACIP_DELIVERY_RELIABLE || options->deadline_ns) {
115 if (!transport->methods->sendv_ex || !transport->methods->validate_send_options)
116 return SET_ERRNO(ERROR_NOT_SUPPORTED, "Datagrams and deadlines are not supported by this transport");
117 asciichat_error_t result = transport->methods->validate_send_options(transport, options);
118 if (result != ASCIICHAT_OK)
119 return result;
120 }
121#ifndef __EMSCRIPTEN__
122 if (transport && transport->outbound) {
123 acip_admission_t admission;
124 asciichat_error_t result = acip_outbound_submitv_ex(transport, buffers, count, options, &admission);
125 if (result != ASCIICHAT_OK)
126 return result;
127 if (admission != ACIP_ADMISSION_ACCEPTED)
128 return SET_ERRNO(ERROR_BUFFER_FULL, "Outbound media not admitted (%d)", admission);
129 return ASCIICHAT_OK;
130 }
131#endif
132 return transport_sendv_impl(transport, buffers, count, options);
133}
asciichat_error_t acip_outbound_submitv_ex(acip_transport_t *transport, const socket_buffer_t *buffers, size_t count, const acip_send_options_t *options, acip_admission_t *admission)
acip_admission_t
@ ACIP_ADMISSION_ACCEPTED
@ ERROR_BUFFER_FULL
@ ERROR_NOT_SUPPORTED
Definition error_codes.h:74
uint64_t deadline_ns
Definition traffic.h:23
acip_delivery_t delivery
Definition traffic.h:22
asciichat_error_t(* validate_send_options)(acip_transport_t *transport, const acip_send_options_t *options)
asciichat_error_t(* sendv_ex)(acip_transport_t *transport, const socket_buffer_t *buffers, size_t count, const acip_send_options_t *options)
struct acip_outbound * outbound
Per-connection plaintext admission and scheduling.
@ ACIP_TRAFFIC_VISUAL
Definition traffic.h:12
@ ACIP_DELIVERY_DATAGRAM
Definition traffic.h:17

References ACIP_ADMISSION_ACCEPTED, ACIP_DELIVERY_DATAGRAM, ACIP_DELIVERY_RELIABLE, acip_outbound_submitv_ex(), ACIP_TRAFFIC_VISUAL, ASCIICHAT_OK, acip_send_options_t::deadline_ns, acip_send_options_t::delivery, ERROR_BUFFER_FULL, ERROR_INVALID_PARAM, ERROR_NOT_SUPPORTED, acip_transport::methods, acip_transport::outbound, acip_transport_methods_t::sendv_ex, SET_ERRNO, acip_send_options_t::traffic_class, and acip_transport_methods_t::validate_send_options.

Referenced by acip_transport_sendv(), and packet_send_via_transportv().

◆ acip_webrtc_transport_create()

acip_transport_t * acip_webrtc_transport_create ( struct webrtc_peer_connection * peer_conn,
struct webrtc_data_channel * data_channel,
crypto_context_t * crypto_ctx )

Definition at line 896 of file webrtc/transport.c.

896 {
897 return webrtc_transport_create(peer_conn, data_channel, crypto_ctx, NULL, NULL, NULL);
898}

◆ 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 NAMED_REGISTER_WEBSOCKET_IMPL(data, name, parent_ptr)
@ ERROR_INTERNAL
Definition error_codes.h:94
void ringbuffer_destroy(ringbuffer_t *rb)
Destroy a ring buffer and free its memory.
Definition ringbuffer.c:63
void stats_runtime_peer_close(stats_peer_t *peer)
Definition runtime.c:190
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}
struct acip_websocket_runtime acip_websocket_runtime_t
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 US_PER_SEC_INT
Definition time.h:177
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719

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:80
bool ringbuffer_is_empty(const ringbuffer_t *rb)
Check if buffer is empty.
Definition ringbuffer.c:141
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.