ProtoCore v1.0.16
Deterministic, zero-heap network stack for embedded targets
Loading...
Searching...
No Matches
websocket.h
Go to the documentation of this file.
1// ProtoCore v1.0.16 - Copyright (C) 2026 Douglas Quigg (dstroy0) <dquigg123@gmail.com>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4/**
5 * @file websocket.h
6 * @brief Layer 6 (Presentation) -- WebSocket frame parser and connection pool.
7 *
8 * Implements RFC 6455 framing with a fixed-size payload buffer per slot.
9 * Connections are tracked in ws_pool[MAX_WS_CONNS]; each entry maps to one
10 * TCP slot in conn_pool[] via slot_id.
11 *
12 * **Frame format (client to server)**
13 * ```
14 * 0 1 2 3
15 * 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
16 * +-+-+-+-+-------+-+-------------+-------------------------------+
17 * |F|R|R|R| opcode|M| payload len | extended payload length |
18 * |I|S|S|S| (4) |A| (7) | (16/64) |
19 * |N|V|V|V| |S| +-------------------------------+
20 * | |1|2|3| |K| | |
21 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - -+
22 * | extended payload length continued, if payload len == 127 |
23 * + - - - - - - - - - - - - - - -+-------------------------------+
24 * | | masking key, if MASK set |
25 * +-------------------------------+-------------------------------+
26 * | masking key (continued) | payload data |
27 * +-------------------------------- - - - - - - - - - - - - - - -+
28 * : payload data continued :
29 * +---------------------------------------------------------------+
30 * ```
31 *
32 * **State machine**
33 * ```
34 * WS_HEADER1 -- read FIN + opcode byte
35 * WS_HEADER2 -- read MASK + 7-bit payload length
36 * WS_LEN16_HI -- read extended 16-bit length high byte
37 * WS_LEN16_LO -- read extended 16-bit length low byte
38 * WS_LEN64 -- consume 8-byte 64-bit length (reject; too large)
39 * WS_MASK0..3 -- read 4-byte masking key
40 * WS_PAYLOAD -- accumulate payload bytes (unmasked)
41 * WS_FRAME_READY -- complete frame waiting for dispatch
42 * WS_CLOSED -- connection closed; slot may be recycled
43 * WS_ERROR -- protocol error; close frame sent
44 * ```
45 *
46 * **Limitations**
47 * - A reassembled message must fit in WS_FRAME_SIZE bytes; larger closes 1009.
48 * - RSV bits must be zero (no extensions supported).
49 *
50 * **Fragmentation (RFC 6455 §5.4)**
51 * Fragmented data messages are reassembled into `buf` across continuation
52 * frames; the message is delivered only when the FIN frame arrives. Control
53 * frames (ping/pong/close) may be interleaved between fragments and are
54 * handled immediately without disturbing the partial message.
55 *
56 * @author Douglas Quigg (dstroy0)
57 * @date 2026
58 */
59
60#ifndef PROTOCORE_WEBSOCKET_H
61#define PROTOCORE_WEBSOCKET_H
62
63#include "protocore_config.h"
64
65#if PROTOCORE_ENABLE_WEBSOCKET
66
67EMBED_BEGIN_DECLS
68
69#if PROTOCORE_ENABLE_WS_DEFLATE
72
73/**
74 * @brief Scratch borrowed while compressing one outbound message.
75 *
76 * The deflate state and the output buffer are live together. PROTOCORE_WS_DEFLATE_MAX bounds the payload
77 * the compressor will accept, which is what turns `len + len/8 + 16` into a constant.
78 */
79#define PROTOCORE_PLAINTEXT_WORK_WS_SEND \
80 (DEFLATE_SCRATCH_SIZE + PROTOCORE_WS_DEFLATE_MAX + (PROTOCORE_WS_DEFLATE_MAX / 8) + 16)
81
82/**
83 * @brief Scratch borrowed while decompressing one reassembled inbound message.
84 *
85 * Input (message + the RFC 7692 00 00 ff ff marker), output, and the inflate tables are live
86 * together. The parser closes 1009 before a message exceeds WS_FRAME_SIZE, which bounds the input.
87 */
88#define PROTOCORE_PLAINTEXT_WORK_WS_RECV (WS_FRAME_SIZE + 4 + WS_FRAME_SIZE + INFLATE_SCRATCH_SIZE)
89#else
90#define PROTOCORE_PLAINTEXT_WORK_WS_SEND 0
91#define PROTOCORE_PLAINTEXT_WORK_WS_RECV 0
92#endif
93
94// ---------------------------------------------------------------------------
95// WebSocket opcodes (RFC 6455 §5.2)
96// ---------------------------------------------------------------------------
97
98/** @brief WebSocket frame opcodes. */
99EMBED_ENUM_BYTE(WsOpcode,
100 WS_OP_CONTINUATION = 0x0, ///< Continuation frame (data-message fragment; reassembled into buf).
101 WS_OP_TEXT = 0x1, ///< UTF-8 text payload.
102 WS_OP_BINARY = 0x2, ///< Binary payload.
103 WS_OP_CLOSE = 0x8, ///< Connection close.
104 WS_OP_PING = 0x9, ///< Ping (auto-ponged by the library).
105 WS_OP_PONG = 0xA ///< Pong (echoed ping; ignored by library).
106);
107
108/** @brief WebSocket close status codes (RFC 6455 §7.4.1). */
109EMBED_ENUM_BYTE(WsCloseCode,
110 WS_CLOSE_NORMAL = 1000, ///< Normal closure.
111 WS_CLOSE_GOING_AWAY = 1001, ///< Endpoint going away.
112 WS_CLOSE_PROTOCOL = 1002, ///< Protocol error.
113 WS_CLOSE_UNSUPPORTED = 1003, ///< Received a data type the endpoint cannot accept (RFC 6455).
114 WS_CLOSE_INVALID_PAYLOAD = 1007, ///< Text message that is not valid UTF-8 (RFC 6455 8.1).
115 WS_CLOSE_TOO_BIG = 1009 ///< Payload too large for WS_FRAME_SIZE.
116);
117
118// ---------------------------------------------------------------------------
119// Frame parser states
120// ---------------------------------------------------------------------------
121
122/** @brief States of the WebSocket frame parser. */
123EMBED_ENUM_BYTE(WsParseState,
124 WS_HEADER1, ///< Awaiting first header byte (FIN, RSV, opcode).
125 WS_HEADER2, ///< Awaiting second header byte (MASK, 7-bit length).
126 WS_LEN16_HI, ///< Reading extended 16-bit length, high byte.
127 WS_LEN16_LO, ///< Reading extended 16-bit length, low byte.
128 WS_LEN64, ///< Consuming 8-byte 64-bit length (always rejected).
129 WS_MASK0, ///< Reading masking key byte 0.
130 WS_MASK1, ///< Reading masking key byte 1.
131 WS_MASK2, ///< Reading masking key byte 2.
132 WS_MASK3, ///< Reading masking key byte 3.
133 WS_PAYLOAD, ///< Accumulating payload bytes.
134 WS_FRAME_READY, ///< Complete frame ready for dispatch.
135 WS_CLOSED, ///< Connection closed; slot may be recycled.
136 WS_ERROR ///< Protocol error; close frame has been queued.
137);
138
139// ---------------------------------------------------------------------------
140// Per-connection WebSocket state
141// ---------------------------------------------------------------------------
142
143/**
144 * @brief WebSocket connection state stored in ws_pool[].
145 *
146 * Allocated when an HTTP upgrade handshake succeeds. slot_id ties this
147 * entry back to conn_pool[] and the ring buffer.
148 */
149typedef struct
150{
151 uint8_t ws_id; ///< Index into ws_pool[] (set at init).
152 uint8_t slot_id; ///< Owning TCP slot in conn_pool[].
153 uint8_t route_id; ///< The handler set this channel was opened for.
154 embed_bool active; ///< True when this entry is in use.
155
156 WsParseState parse_state; ///< Current frame parser state.
157 WsOpcode opcode; ///< Opcode of the frame being parsed.
158 embed_bool fin; ///< FIN bit of the frame being parsed.
159 embed_bool masked; ///< True if client sent a masking key.
160
161 uint8_t mask_key[4]; ///< Client masking key.
162 uint32_t payload_len; ///< Expected payload byte count (current frame).
163 uint32_t payload_idx; ///< Bytes received so far (current frame).
164 uint8_t len64_count; ///< Bytes consumed from 64-bit length.
165 uint8_t buf[WS_FRAME_SIZE + 1]; ///< Reassembled message payload, null-terminated.
166
167 // Fragmentation state (RFC 6455 §5.4). A data message may span multiple
168 // frames (first text/binary with FIN=0, then continuation frames). Control
169 // frames may be interleaved and use a separate buffer so they never clobber
170 // the partially-assembled data message.
171 embed_bool fragmenting; ///< True between a non-FIN data frame and its FIN.
172 WsOpcode msg_opcode; ///< Opcode of the data message being assembled.
173 uint32_t msg_len; ///< Bytes assembled so far across all fragments.
174 uint8_t ctl_buf[125 + 1]; ///< Control-frame payload (ping/pong/close), null-terminated.
175
176#if PROTOCORE_ENABLE_WS_DEFLATE
177 embed_bool pmd; ///< permessage-deflate negotiated on this connection (RFC 7692).
178 embed_bool msg_compressed; ///< Current data message arrived compressed (RSV1 on its first frame).
179#endif
180} WsConn;
181
182/** @brief Pool of WebSocket connection state, one per MAX_WS_CONNS. */
183extern WsConn ws_pool[MAX_WS_CONNS];
184
185// ---------------------------------------------------------------------------
186// WebSocket API
187// ---------------------------------------------------------------------------
188
189/**
190 * @brief Callback fired when a WebSocket connection is established.
191 *
192 * @param ws_id Index into ws_pool[] for this connection.
193 */
194typedef void (*WsConnectHandler)(uint8_t ws_id);
195
196/**
197 * @brief Callback fired when a WebSocket text or binary frame arrives.
198 *
199 * The payload is in ws_pool[ws_id].buf, null-terminated. Length is in
200 * ws_pool[ws_id].payload_len. Opcode is in ws_pool[ws_id].opcode.
201 *
202 * @param ws_id Index into ws_pool[].
203 */
204typedef void (*WsMessageHandler)(uint8_t ws_id);
205
206/**
207 * @brief Callback fired when a WebSocket connection closes.
208 *
209 * @param ws_id Index into ws_pool[] (slot is still valid during callback).
210 */
211typedef void (*WsCloseHandler)(uint8_t ws_id);
212
213/** @brief The id a route carries when it serves no WebSocket. */
214#define PROTOCORE_WS_NONE 0xFFu
215
216/** @brief The three handlers one route records. */
217typedef struct
218{
219 WsConnectHandler on_connect; ///< the handler recorded for a route's open
220 WsMessageHandler on_message; ///< the handler recorded for a message
221 WsCloseHandler on_close; ///< the handler recorded for a close
222} WsRouteArgs;
223
224/** @brief RFC 6455 sec 5.2 base framing, and the sec 7.4 status a Close carries. */
225typedef struct
226{
227 WsOpcode opcode; ///< the frame type a send emits
228 const uint8_t *payload; ///< its payload bytes; may be NULL for a zero-length frame
229 uint16_t len; ///< how many
230 WsCloseCode code; ///< the status code a close carries
231} WsFrameArgs;
232
233/**
234 * @brief The WebSocket connections this server holds open (RFC 6455).
235 *
236 * A caller sets the members a call takes, invokes it through ::Ws, and reads the outcome off the
237 * same handle.
238 *
239 * The handlers live here, not in the route table: a route decides where a request goes, and what
240 * runs once the socket is open belongs to this module. A route stores the id, so nothing above
241 * holds a pointer into here and the same handler set can serve more than one route.
242 *
243 * @var WsNs::slot the TCP slot a call acts on
244 * @var WsNs::ws_id the socket a call names
245 * @var WsNs::id the route id a lookup names
246 * @var WsNs::route the handlers one route records
247 * @var WsNs::conn the socket a call acts on, when it takes one by pointer
248 * @var WsNs::frame one frame's type, payload and close status (RFC 6455 sec 5.2, 7.4)
249 * @var WsNs::byte one already-plaintext byte for the frame state machine
250 * @var WsNs::frag_size the outbound fragmentation size in payload bytes; 0 = off
251 * @var WsNs::ok a call's true/false outcome
252 * @var WsNs::u8 the route id an add reports, or ::PROTOCORE_WS_NONE when full
253 * @var WsNs::text the reassembled message payload a lookup reports, or NULL
254 * @var WsNs::found the socket an alloc or a find reports, or NULL
255 * @var WsNs::connect_handler the connect handler an id names, or NULL
256 * @var WsNs::message_handler the message handler an id names, or NULL
257 * @var WsNs::close_handler the close handler an id names, or NULL
258 * @var WsNs::route_add record one route's handlers
259 * @var WsNs::route_reset empty the handler table; a route holds the id an add returned, so
260 * this empties with the routes
261 * @var WsNs::route_connect the connect handler an id names
262 * @var WsNs::route_message the message handler an id names
263 * @var WsNs::route_close the close handler an id names
264 * @var WsNs::init set every pool slot inactive; called once from begin()
265 * @var WsNs::active whether ws_id is a valid, in-use socket
266 * @var WsNs::payload_of the reassembled message payload for ws_id
267 * @var WsNs::alloc take a socket and bind it to a TCP slot
268 * @var WsNs::find the socket bound to a TCP slot
269 * @var WsNs::free release the socket bound to a TCP slot
270 * @var WsNs::parse feed the slot's bytes through the frame state machine
271 * @var WsNs::feed_byte feed one already-plaintext byte through it
272 * @var WsNs::reset_frame back to WS_HEADER1, ready for the next frame
273 * @var WsNs::send_frame build and send one frame; server-to-client frames are never masked
274 * @var WsNs::set_frag_size the outbound fragmentation size (RFC 6455 sec 5.4)
275 * @var WsNs::close send a Close frame and mark the socket WS_CLOSED
276 *
277 * Every entry takes the module's borrow. How those bytes are carved is websocket.c's and is never
278 * named here. ::protocore_ws_span is where a caller gets one.
279 *
280 * A caller that needs immediate delivery flushes the connection itself after a send.
281 */
282typedef struct
283{
284 uint8_t slot; ///< the TCP slot a call acts on
285 uint8_t ws_id; ///< the socket a call names
286 uint8_t id; ///< the route id a lookup names
287 WsConn *conn; ///< the socket a call acts on, when it takes one by pointer
288 uint8_t byte; ///< one already-plaintext byte for the frame state machine
289 uint16_t frag_size; ///< the outbound fragmentation size in payload bytes; 0 = off
290#if PROTOCORE_ENABLE_WS_DEFLATE
291 embed_bool pmd; ///< what an alloc records on the new connection: RFC 7692 permessage-deflate,
292 ///< as the handshake negotiated it. The layer that read the Sec-WebSocket-
293 ///< Extensions header is the only one that knows, so it states it here.
294#endif
295 WsRouteArgs route; ///< the handlers one route records
296 WsFrameArgs frame; ///< one frame's type, payload and close status
297 embed_bool ok;
298 uint8_t u8;
299 const char *text;
300 WsConn *found;
301 WsConnectHandler connect_handler;
302 WsMessageHandler message_handler;
303 WsCloseHandler close_handler;
304} WsVars;
305
306/** @brief The operands and the outcome. */
307extern WsVars WsV;
308
309/** @brief The entries. */
310typedef struct
311{
312 void (*const route_add)(uint8_t *work);
313 void (*const route_reset)(uint8_t *work);
314 void (*const route_connect)(uint8_t *work);
315 void (*const route_message)(uint8_t *work);
316 void (*const route_close)(uint8_t *work);
317 void (*const init)(uint8_t *work);
318 void (*const active)(uint8_t *work);
319 void (*const payload_of)(uint8_t *work);
320 void (*const alloc)(uint8_t *work);
321 void (*const find)(uint8_t *work);
322 void (*const free)(uint8_t *work);
323 void (*const parse)(uint8_t *work);
324 void (*const feed_byte)(uint8_t *work);
325 void (*const reset_frame)(uint8_t *work);
326 void (*const send_frame)(uint8_t *work);
327 void (*const set_frag_size)(uint8_t *work);
328 void (*const close)(uint8_t *work);
329} WsNs;
330
331// What the table binds, defined once in the .c and taking one parameter each: everything
332// else an entry needs is an operand in WsV or a region of the borrow at a fixed offset.
333void protocore_ws_route_add(uint8_t *work);
334void protocore_ws_route_reset(uint8_t *work);
335void protocore_ws_route_connect(uint8_t *work);
336void protocore_ws_route_message(uint8_t *work);
337void protocore_ws_route_close(uint8_t *work);
338void protocore_ws_init(uint8_t *work);
339void protocore_ws_active(uint8_t *work);
340void protocore_ws_payload_of(uint8_t *work);
341void protocore_ws_alloc(uint8_t *work);
342void protocore_ws_find(uint8_t *work);
343void protocore_ws_free(uint8_t *work);
344void protocore_ws_parse(uint8_t *work);
345void protocore_ws_feed_byte(uint8_t *work);
346void protocore_ws_reset_frame(uint8_t *work);
347void protocore_ws_send_frame(uint8_t *work);
348void protocore_ws_set_frag_size(uint8_t *work);
349void protocore_ws_close(uint8_t *work);
350
351// `static const`, initialised HERE rather than `extern` against a definition in the .c: a
352// const object whose initializer every translation unit can see is a COMPILE-TIME FACT, so
353// `Ws.route_add(work)` resolves to a named function and becomes a DIRECT call. An extern table
354// leaves the call indirect and the symbol live at every level, -O2 -flto included.
355static const WsNs Ws __attribute__((unused)) = {
356 .route_add = protocore_ws_route_add,
357 .route_reset = protocore_ws_route_reset,
358 .route_connect = protocore_ws_route_connect,
359 .route_message = protocore_ws_route_message,
360 .route_close = protocore_ws_route_close,
361 .init = protocore_ws_init,
362 .active = protocore_ws_active,
363 .payload_of = protocore_ws_payload_of,
364 .alloc = protocore_ws_alloc,
365 .find = protocore_ws_find,
366 .free = protocore_ws_free,
367 .parse = protocore_ws_parse,
368 .feed_byte = protocore_ws_feed_byte,
369 .reset_frame = protocore_ws_reset_frame,
370 .send_frame = protocore_ws_send_frame,
371 .set_frag_size = protocore_ws_set_frag_size,
372 .close = protocore_ws_close,
373};
374
375/** @brief Not an entry: an entry takes a borrow and this is where that borrow comes from. */
376uint8_t *protocore_ws_span(void);
377
378EMBED_END_DECLS
379
380#endif // PROTOCORE_ENABLE_WEBSOCKET
381
382#endif
EMBED_ENUM_BYTE(ProtoConn, PROTO_NONE=0, PROTO_HTTP=1, PROTO_TELNET=2, PROTO_SSH=3, PROTO_MODBUS=4, PROTO_OPCUA=5, PROTO_SSH_RFWD=6, PROTO_RELAY=7, PROTO_BRIDGE=8, PROTO_NTRIP_CASTER=9, PROTO_MESH=10, PROTO_UDP=11,)
Application protocol spoken on a listener port or connection slot.
#define WS_FRAME_SIZE
Maximum WebSocket frame payload in bytes.
#define MAX_WS_CONNS
Maximum simultaneous WebSocket connections.
Bounded RFC 1951 DEFLATE decompressor (INFLATE) - no heap.
Bounded RFC 1951 DEFLATE compressor (DEFLATE) - no heap.