dmsc/c/
ws.rs

1//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
2//!
3//! This file is part of DMSC.
4//! The DMSC project belongs to the Dunimd Team.
5//!
6//! Licensed under the Apache License, Version 2.0 (the "License");
7//! You may not use this file except in compliance with the License.
8//! You may obtain a copy of the License at
9//!
10//!     http://www.apache.org/licenses/LICENSE-2.0
11//!
12//! Unless required by applicable law or agreed to in writing, software
13//! distributed under the License is distributed on an "AS IS" BASIS,
14//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15//! See the License for the specific language governing permissions and
16//! limitations under the License.
17
18//! # WebSocket Module C API
19//!
20//! This module provides C language bindings for DMSC's WebSocket communication infrastructure. The WebSocket
21//! module delivers full-duplex, real-time communication capabilities for building interactive applications,
22//! live dashboards, chat systems, gaming backends, and streaming services. This C API enables C/C++
23//! applications to leverage DMSC's WebSocket functionality for building responsive, bidirectional communication
24//! layers over persistent connections.
25//!
26//! ## Module Architecture
27//!
28//! The WebSocket module comprises three primary components that together provide complete WebSocket
29//! communication capabilities:
30//!
31//! - **DMSCWSServerConfig**: Configuration container for WebSocket server parameters including connection
32//!   limits, message size limits, heartbeat settings, and security options. The configuration object
33//!   controls server behavior, resource allocation, and operational characteristics.
34//!
35//! - **DMSCWSSession**: Individual WebSocket connection representation, tracking connection state,
36//!   session metadata, message queues, and communication properties. Each session represents a unique
37//!   client connection to the WebSocket server.
38//!
39//! - **DMSCWSSessionManager**: Central manager for all WebSocket sessions, handling session lifecycle,
40//!   broadcasting, routing, and connection administration. The manager handles the complete WebSocket
41//!   communication workflow including connection handling, message distribution, and cleanup.
42//!
43//! ## WebSocket Protocol
44//!
45//! The WebSocket implementation provides complete RFC 6455 compliance:
46//!
47//! - **Handshake Handling**: Complete WebSocket handshake processing with HTTP upgrade mechanism.
48//!   Validates request headers, verifies protocol version, and generates proper responses.
49//!
50//! - **Frame Processing**: Full frame lifecycle management including text frames, binary frames,
51//!   continuation frames, close frames, ping frames, and pong frames. Handles fragmentation
52//!   and reassembly transparently.
53//!
54//! - **Extensions Support**: Configurable WebSocket extensions including per-message deflate
55//!   compression (RFC 7692) for reduced bandwidth usage. Support for custom extensions.
56//!
57//! - **Subprotocol Negotiation**: Support for WebSocket subprotocols for application-specific
58//!   messaging semantics. Includes built-in support for common subprotocols.
59//!
60//! - **Status Codes**: Complete handling of WebSocket status codes including normal closure (1000),
61//!   going away (1001), protocol error (1002), unsupported data (1003), and application codes.
62//!
63//! - **Reason Phrases**: Proper close frame reason phrases for debugging and logging. Includes
64//!   support for custom application reason codes.
65//!
66//! ## Message Types
67//!
68//! The WebSocket module supports comprehensive message types:
69//!
70//! - **Text Messages**: UTF-8 encoded text messages with automatic validation. Supports
71//!   JSON, XML, and other text-based protocols. Validates UTF-8 encoding compliance.
72//!
73//! - **Binary Messages**: Raw binary data transmission for efficiency. Ideal for protocol buffers,
74//!   images, files, and other binary formats. No encoding overhead or validation.
75//!
76//! - **Continuation Messages**: Support for message fragmentation across multiple frames.
77//!   Automatic reassembly of fragmented messages on receive, transparent fragmentation on send.
78//!
79//! - **Control Frames**: Ping and Pong frames for connection health monitoring. Close frames
80//!   for graceful connection termination with configurable reason codes.
81//!
82//! - **Pong Payloads**: Custom payload support in Pong frames for application-specific
83//!   heartbeat data. Includes timestamp and custom application data.
84//!
85//! ## Connection Management
86//!
87//! The session manager provides comprehensive connection handling:
88//!
89//! - **Connection Lifecycle**: Complete connection lifecycle from TCP handshake through WebSocket
90//!   upgrade to graceful close. Handles all intermediate states and transitions.
91//!
92//! - **Keep-Alive Mechanisms**: Configurable keep-alive intervals with automatic Ping/Pong
93//!   exchange. Detects half-open connections and zombie clients.
94//!
95//! - **Heartbeat System**: Application-level heartbeat for more sophisticated connection
96//!   monitoring. Custom heartbeat intervals and timeout values per session.
97//!
98//! - **Graceful Shutdown**: Proper WebSocket close handshake with configurable timeout.
99//!   Ensures all pending messages are sent before connection termination.
100//!
101//! - **Forced Disconnection**: Emergency disconnection capability for abuse prevention
102//!   and resource cleanup. Includes configurable disconnect behavior and cleanup.
103//!
104//! - **Connection Pooling**: Resource pooling for high-connection-count scenarios.
105//!   Reduces memory allocation overhead for large numbers of concurrent connections.
106//!
107//! ## Session Features
108//!
109//! Individual sessions provide rich functionality:
110//!
111//! - **Session Metadata**: Store and retrieve arbitrary session data including user context,
112//!   authentication state, and application-specific information. Key-value storage per session.
113//!
114//! - **Remote Address**: Access client network information including IP address, port,
115//!   and protocol (IPv4/IPv6). Includes proxy protocol header parsing if enabled.
116//!
117//! - **Connection Time**: Track when the session was established for session duration
118//!   calculations and timeout management.
119//!
120//! - **Message Counters**: Statistics tracking including messages sent, messages received,
121//!   bytes sent, bytes received. Useful for monitoring and rate limiting.
122//!
123//! - **Last Activity**: Timestamp of last received message for idle detection and
124//!   timeout management. Updated automatically on message receipt.
125//!
126//! - **Request Information**: Access to original HTTP upgrade request headers. Includes
127//!   cookies, origin, subprotocols, and custom headers.
128//!
129//! ## Broadcasting
130//!
131//! The session manager supports efficient message distribution:
132//!
133//! - **Broadcast to All**: Send message to all connected sessions with single call.
134//!   Optimized for minimal overhead in multi-connection scenarios.
135//!
136//! - **Selective Broadcast**: Target specific sessions using filter criteria.
137//!   Filter by session data, connection time, message counts, or custom predicates.
138//!
139//! - **Room/Channel System**: Group sessions into named rooms for targeted messaging.
140//!   Supports dynamic room membership and room statistics.
141//!
142//! - **Topic-Based Routing**: Subscribe sessions to topics for pub/sub-style messaging.
143//!   Efficient topic-based message routing with automatic topic management.
144//!
145//! - **Exclusion**: Broadcast to all except specific sessions. Useful for acknowledging
146//!   messages back to sender while excluding them from broadcast.
147//!
148//! - **Batching**: Configurable batching for high-volume broadcasting. Reduces system
149//!   calls and improves throughput for mass messaging.
150//!
151//! ## Security Features
152//!
153//! The WebSocket module implements comprehensive security measures:
154//!
155//! - **Origin Validation**: Verify incoming requests against allowed origin list.
156//!   Prevents cross-site WebSocket hijacking (CSWSH) attacks.
157//!
158//! - **Subprotocol Validation**: Validate requested subprotocols against allowed list.
159//!   Ensures only negotiated subprotocols are used.
160//!
161//! - **Request Validation**: Validate HTTP upgrade request headers for security.
162//!   Rejects malformed or suspicious requests.
163//!
164//! - **Rate Limiting**: Per-session and global rate limiting for message frequency.
165//!   Configurable limits with customizable behavior (drop, queue, reject).
166//!
167//! - **Message Size Limits**: Configurable maximum message sizes for text and binary.
168//!   Protects against memory exhaustion from oversized messages.
169//!
170//! - **Connection Limits**: Maximum concurrent connections per server and per IP.
171//!   Prevents resource exhaustion from connection flooding.
172//!
173//! - **TLS/SSL Support**: Complete TLS integration for WSS (WebSocket Secure) connections.
174//!   Modern TLS versions with configurable cipher suites.
175//!
176//! - **Authentication Integration**: Built-in support for token-based authentication.
177//!   WebSocket-specific authentication handshake extensions.
178//!
179//! ## Compression
180//!
181//! Built-in compression reduces bandwidth usage:
182//!
183//! - **Per-Message Deflate**: RFC 7692 compression for WebSocket messages. Transparent
184//!   compression and decompression without application changes.
185//!
186//! - **Compression Level**: Configurable compression levels trading CPU for compression.
187//!   Supports levels from fastest (no compression) to best compression.
188//!
189//! - **Context Takeover**: Optional context takeover for improved compression ratios.
190//!   Memory trade-off for better compression efficiency.
191//!
192//! - **Server Window Bits**: Configurable server window size for compression.
193//!   Tuning for specific bandwidth/CPU requirements.
194//!
195//! ## Performance Characteristics
196//!
197//! WebSocket operations are optimized for high throughput:
198//!
199//! - **Connection Handling**: O(1) for new connections with constant-time session creation
200//! - **Message Sending**: O(1) to O(n) depending on broadcast targets
201//! - **Message Receiving**: O(1) for frame processing, O(n) for large message reassembly
202//! - **Broadcasting**: O(n) where n is number of target sessions
203//! - **Throughput**: Supports millions of messages per second on modern hardware
204//! - **Latency**: Sub-millisecond message processing for local connections
205//!
206//! ## Memory Management
207//!
208//! All C API objects use opaque pointers with manual memory management:
209//!
210//! - Constructor functions allocate new instances on the heap
211//! - Destructor functions must be called to release memory
212//! - Session managers coordinate session cleanup
213//! - Message buffers are recycled for performance
214//!
215//! ## Thread Safety
216//!
217//! The underlying implementations are thread-safe:
218//!
219//! - Concurrent connection handling from multiple threads supported
220//! - Message sending can be done from any thread
221//! - Session operations use internal synchronization
222//! - Broadcasting coordinates access across sessions
223//!
224//! ## Usage Example
225//!
226//! ```c
227//! // Create WebSocket server configuration
228//! DMSCWSServerConfig* config = dmsc_ws_server_config_new();
229//! if (config == NULL) {
230//!     fprintf(stderr, "Failed to create WebSocket config\n");
231//!     return ERROR_INIT;
232//! }
233//!
234//! // Configure server settings
235//! dmsc_ws_server_config_set_host(config, "0.0.0.0");
236//! dmsc_ws_server_config_set_port(config, 8080);
237//! dmsc_ws_server_config_set_max_connections(config, 10000);
238//! dmsc_ws_server_config_set_max_message_size(config, 1024 * 1024);  // 1MB
239//! dmsc_ws_server_config_set_ping_interval(config, 30000);  // 30 seconds
240//! dmsc_ws_server_config_set_ping_timeout(config, 5000);  // 5 seconds
241//!
242//! // Enable compression
243//! dmsc_ws_server_config_set_compression_enabled(config, true);
244//! dmsc_ws_server_config_set_compression_level(config, 6);
245//!
246//! // Enable security features
247//! dmsc_ws_server_config_set_origin_validation(config, true);
248//! dmsc_ws_server_config_add_allowed_origin(config, "https://example.com");
249//! dmsc_ws_server_config_set_rate_limit_enabled(config, true);
250//! dmsc_ws_server_config_set_rate_limit_messages(config, 100);
251//! dmsc_ws_server_config_set_rate_limit_window(config, 1000);  // 1 second
252//!
253//! // Create session manager
254//! DMSCWSSessionManager* manager = dmsc_ws_session_manager_new(config);
255//! if (manager == NULL) {
256//!     fprintf(stderr, "Failed to create session manager\n");
257//!     dmsc_ws_server_config_free(config);
258//!     return ERROR_INIT;
259//! }
260//!
261//! // Start WebSocket server
262//! int result = dmsc_ws_session_manager_start(manager);
263//! if (result != 0) {
264//!     fprintf(stderr, "Failed to start WebSocket server: %d\n", result);
265//!     dmsc_ws_session_manager_free(manager);
266//!     dmsc_ws_server_config_free(config);
267//!     return ERROR_START;
268//! }
269//!
270//! printf("WebSocket server started on port %d\n",
271//!        dmsc_ws_server_config_get_port(config));
272//!
273//! // Set up event callbacks
274//! dmsc_ws_session_manager_set_on_connect(manager, on_connect_callback, NULL);
275//! dmsc_ws_session_manager_set_on_message(manager, on_message_callback, NULL);
276//! dmsc_ws_session_manager_set_on_close(manager, on_close_callback, NULL);
277//! dmsc_ws_session_manager_set_on_error(manager, on_error_callback, NULL);
278//!
279//! // Application main loop - process events
280//! while (running) {
281//!     // Handle events with timeout
282//!     dmsc_ws_session_manager_poll(manager, 1000);  // 1 second timeout
283//!
284//!     // Process pending operations
285//!     process_application_tasks();
286//!
287//!     // Periodic tasks
288//!     if (should_check_health()) {
289//!         uint32_t active_count = dmsc_ws_session_manager_get_active_count(manager);
290//!         uint32_t total_count = dmsc_ws_session_manager_get_total_count(manager);
291//!         uint64_t total_messages = dmsc_ws_session_manager_get_total_messages(manager);
292//!
293//!         printf("Active sessions: %u/%u, Messages: %lu\n",
294//!                active_count, total_count, total_messages);
295//!     }
296//! }
297//!
298//! // Broadcast message to all clients
299//! const char* broadcast_msg = "{\"type\": \"broadcast\", \"message\": \"Hello all!\"}";
300//! int send_count = dmsc_ws_session_manager_broadcast(manager, broadcast_msg, strlen(broadcast_msg));
301//! printf("Broadcast sent to %d clients\n", send_count);
302//!
303//! // Get session information
304//! uint32_t session_count = dmsc_ws_session_manager_get_session_ids(manager, session_ids, max_sessions);
305//!
306//! for (uint32_t i = 0; i < session_count && i < 10; i++) {
307//!     DMSCWSSession* session = dmsc_ws_session_manager_get_session(manager, session_ids[i]);
308//!     if (session != NULL) {
309//!         const char* remote_addr = dmsc_ws_session_get_remote_addr(session);
310//!         uint64_t connected_at = dmsc_ws_session_get_connected_at(session);
311//!         uint64_t messages_sent = dmsc_ws_session_get_messages_sent(session);
312//!         uint64_t bytes_sent = dmsc_ws_session_get_bytes_sent(session);
313//!
314//!         printf("Session %u: %s, connected: %lu, sent: %lu/%lu\n",
315//!                session_ids[i], remote_addr, connected_at, messages_sent, bytes_sent);
316//!
317//!         // Send message to specific session
318//!         dmsc_ws_session_send(session, "Welcome!", 8);
319//!
320//!         dmsc_ws_session_free(session);
321//!     }
322//! }
323//!
324//! // Room management example
325//! const char* room_name = "chat_room_1";
326//! dmsc_ws_session_manager_join_room(manager, session_ids[0], room_name);
327//!
328//! // Send to room members only
329//! const char* room_msg = "{\"type\": \"room\", \"content\": \"Hello room!\"}";
330//! int room_count = dmsc_ws_session_manager_send_to_room(manager, room_name, room_msg, strlen(room_msg));
331//! printf("Room message sent to %d clients\n", room_count);
332//!
333//! // Send to room except sender
334//! dmsc_ws_session_manager_send_to_room_except(
335//!     manager, room_name, session_ids[0],
336//!     room_msg, strlen(room_msg)
337//! );
338//!
339//! // Leave room
340//! dmsc_ws_session_manager_leave_room(manager, session_ids[0], room_name);
341//!
342//! // Get room members
343//! uint32_t room_members[100];
344//! uint32_t room_count = dmsc_ws_session_manager_get_room_members(
345//!     manager, room_name, room_members, 100
346//! );
347//! printf("Room '%s' has %u members\n", room_name, room_count);
348//!
349//! // Graceful shutdown
350//! printf("Shutting down WebSocket server...\n");
351//! dmsc_ws_session_manager_stop(manager, 5000);  // 5 second timeout
352//! dmsc_ws_session_manager_free(manager);
353//! dmsc_ws_server_config_free(config);
354//!
355//! printf("WebSocket server shutdown complete\n");
356//! ```
357//!
358//! ## Event Callback Signatures
359//!
360//! Event handlers must conform to the following signatures:
361//!
362//! ```c
363//! // Connection established
364//! typedef void (*DMSWSConnectCallback)(
365//!     DMSCWSSessionManager* manager,
366//!     DMSCWSSession* session,
367//!     void* user_data
368//! );
369//!
370//! // Message received
371//! typedef void (*DMSWSMessageCallback)(
372//!     DMSCWSSessionManager* manager,
373//!     DMSCWSSession* session,
374//!     DMSWSMessageType type,
375//!     const char* data,
376//!     size_t length,
377//!     void* user_data
378//! );
379//!
380//! // Connection closed
381//! typedef void (*DMSWSCloseCallback)(
382//!     DMSCWSSessionManager* manager,
383//!     DMSCWSSession* session,
384//!     uint16_t code,
385//!     const char* reason,
386//!     void* user_data
387//! );
388//!
389//! // Error occurred
390//! typedef void (*DMSWSErrorCallback)(
391//!     DMSCWSSessionManager* manager,
392//!     DMSCWSSession* session,
393//!     int error_code,
394//!     const char* error_message,
395//!     void* user_data
396//! );
397//! ```
398//!
399//! ## Dependencies
400//!
401//! This module depends on the following DMSC components:
402//!
403//! - `crate::ws`: Rust WebSocket module implementation
404//! - `crate::prelude`: Common types and traits
405//! - tokio for async runtime (when async features enabled)
406//! - tungstenite for WebSocket protocol (when using pure Rust implementation)
407//!
408//! ## Feature Flags
409//!
410//! The WebSocket module is enabled by the "ws" feature flag.
411//! Disable this feature to reduce binary size when WebSocket is not required.
412//!
413//! Additional features:
414//!
415//! - `ws-tungstenite`: Enable Tungstenite-based WebSocket implementation
416//! - `ws-async`: Enable async message handling
417//! - `ws-compression`: Enable per-message deflate compression
418//! - `ws-tls`: Enable TLS/WSS support
419//! - `ws-rate-limit`: Enable rate limiting
420
421use crate::ws::{DMSCWSServerConfig, DMSCWSSession, DMSCWSSessionManager};
422
423
424c_wrapper!(CDMSCWSServerConfig, DMSCWSServerConfig);
425c_wrapper!(CDMSCWSSession, DMSCWSSession);
426c_wrapper!(CDMSCWSSessionManager, DMSCWSSessionManager);
427
428// DMSCWSServerConfig constructors and destructors
429c_constructor!(
430    dmsc_ws_server_config_new,
431    CDMSCWSServerConfig,
432    DMSCWSServerConfig,
433    DMSCWSServerConfig::default()
434);
435c_destructor!(dmsc_ws_server_config_free, CDMSCWSServerConfig);