1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! WebSocket Protocol Upgrade Implementation
//!
//! This module handles the WebSocket protocol upgrade handshake as defined in
//! [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455) for HTTP/1.1.
//!
//! # WebSocket Protocol Overview
//!
//! The WebSocket protocol enables bidirectional, full-duplex communication between
//! a client and server over a single TCP connection. It starts as an HTTP/1.1
//! upgrade request and then switches to the WebSocket protocol.
//!
//! # Handshake Process
//!
//! 1. **Client sends upgrade request**:
//! ```
//! GET /ws HTTP/1.1
//! Host: localhost:8080
//! Upgrade: websocket
//! Connection: Upgrade
//! Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
//! Sec-WebSocket-Version: 13
//! ```
//!
//! 2. **Server responds with 101 Switching Protocols**:
//! ```
//! HTTP/1.1 101 Switching Protocols
//! Upgrade: websocket
//! Connection: Upgrade
//! Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
//! ```
//!
//! 3. **Connection upgraded to WebSocket protocol**
//!
//! # Security
//!
//! The module implements the required security checks:
//! - Validates `Sec-WebSocket-Key` header presence
//! - Generates proper `Sec-WebSocket-Accept` value using SHA-1 and Base64
//! - Verifies all required headers are present
//! - Supports TLS encryption (wss://)
//!
//! # Secure WebSocket (wss://)
//!
//! When using TLS/HTTPS:
//! - Initial HTTP/1.1 handshake occurs over TLS
//! - WebSocket data frames are encrypted via TLS
//! - All security properties of TLS apply to WebSocket traffic
//!
//! # Examples
//!
//! ## Basic Upgrade Check
//!
//! ```
//! use ignitia::websocket::is_websocket_request;
//! use ignitia::{Request, Method};
//! use http::{HeaderMap, HeaderValue, Version};
//!
//! let mut headers = HeaderMap::new();
//! headers.insert("upgrade", HeaderValue::from_static("websocket"));
//! headers.insert("connection", HeaderValue::from_static("Upgrade"));
//! headers.insert("sec-websocket-key", HeaderValue::from_static("dGhlIHNhbXBsZSBub25jZQ=="));
//!
//! let req = Request::new(
//! Method::GET,
//! "/ws".parse().unwrap(),
//! Version::HTTP_11,
//! headers,
//! bytes::Bytes::new()
//! );
//!
//! assert!(is_websocket_request(&req));
//! ```
//!
//! ## Generate Upgrade Response
//!
//! ```
//! use ignitia::websocket::upgrade_connection;
//! use ignitia::Request;
//!
//! let req = create_websocket_request(); // Your request
//! let response = upgrade_connection(&req).unwrap();
//!
//! assert_eq!(response.status, 101); // Switching Protocols
//! assert!(response.headers.contains_key("sec-websocket-accept"));
//! ```
use WebSocketConnection;
use WebSocketHandler;
use crate::;
use Engine;
use ;
use TokioIo;
use ;
use Arc;
const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
/// Check if a request is a valid WebSocket upgrade request (HTTP/1.1).
///
/// This function validates that the request contains all required headers
/// for a WebSocket upgrade as specified in RFC 6455.
///
/// # Required Headers
///
/// - `Upgrade: websocket` (case-insensitive)
/// - `Connection: Upgrade` (must contain "upgrade", case-insensitive)
/// - `Sec-WebSocket-Key: <base64-encoded-value>`
///
/// # Parameters
///
/// * `req` - The HTTP request to validate
///
/// # Returns
///
/// `true` if the request is a valid WebSocket upgrade request, `false` otherwise
///
/// # Examples
///
/// ```
/// use ignitia::prelude::*;
///
/// fn handle_request(req: Request) {
/// if is_websocket_request(&req) {
/// // Handle WebSocket upgrade
/// } else {
/// // Handle regular HTTP request
/// }
/// }
/// ```
///
/// # Protocol Support
///
/// Currently supports **HTTP/1.1 only**. HTTP/2 WebSocket support (RFC 8441)
/// is not yet implemented due to limitations in the Rust ecosystem.
///
/// # Reference
///
/// - [RFC 6455 - The WebSocket Protocol](https://datatracker.ietf.org/doc/html/rfc6455)
/// - [RFC 6455 Section 4.1 - Client Requirements](https://datatracker.ietf.org/doc/html/rfc6455#section-4.1)
/// Upgrade an HTTP/1.1 connection to WebSocket protocol.
///
/// This function generates the appropriate HTTP response to complete the
/// WebSocket handshake, transitioning from HTTP to WebSocket protocol.
///
/// # Parameters
///
/// * `req` - The HTTP request initiating the WebSocket upgrade
///
/// # Returns
///
/// - `Ok(Response)` - A 101 Switching Protocols response with proper headers
/// - `Err(Error)` - If the request is invalid or missing required headers
///
/// # Response Headers
///
/// The generated response includes:
/// - `Status: 101 Switching Protocols`
/// - `Upgrade: websocket`
/// - `Connection: Upgrade`
/// - `Sec-WebSocket-Accept: <computed-value>`
/// - `Sec-WebSocket-Protocol: <selected-protocol>` (if negotiated)
///
/// # Protocol Negotiation
///
/// If the client sends `Sec-WebSocket-Protocol` header with a list of
/// subprotocols, the server selects the first one and includes it in
/// the response.
///
/// # Errors
///
/// Returns an error if:
/// - The request is not a valid WebSocket upgrade request
/// - `Sec-WebSocket-Key` header is missing
/// - Required headers are malformed
///
/// # Examples
///
/// ## Basic Upgrade
///
/// ```
/// use ignitia::prelude::*;
///
/// async fn handle_upgrade(req: Request) -> Result<Response> {
/// if is_websocket_request(&req) {
/// let response = upgrade_connection(&req)?;
/// // Spawn WebSocket handler after sending response
/// Ok(response)
/// } else {
/// Ok(Response::bad_request("Not a WebSocket request"))
/// }
/// }
/// ```
///
/// ## With Protocol Negotiation
///
/// ```
/// // Client sends: Sec-WebSocket-Protocol: chat, superchat
/// // Server responds with: Sec-WebSocket-Protocol: chat
/// let response = upgrade_connection(&req)?;
/// ```
///
/// # Security Considerations
///
/// - Always validate the origin header in production
/// - Use `wss://` (WebSocket Secure) in production environments
/// - Implement authentication/authorization before upgrading
/// - Validate all headers to prevent injection attacks
///
/// # Reference
///
/// - [RFC 6455 Section 4.2.2 - Sending the Server's Opening Handshake](https://datatracker.ietf.org/doc/html/rfc6455#section-4.2.2)
/// Handle the WebSocket connection after protocol upgrade.
///
/// This function is called after the HTTP upgrade response has been sent.
/// It wraps the upgraded connection in a WebSocket stream and passes it
/// to the user-defined handler.
///
/// # Parameters
///
/// * `req` - The original HTTP request (for context like headers, path, etc.)
/// * `upgraded` - The upgraded connection from Hyper
/// * `handler` - The WebSocket handler to process messages
///
/// # Returns
///
/// A `Response` indicating the result of the WebSocket session. This response
/// is typically used for logging/metrics and is not sent to the client.
///
/// # Flow
///
/// 1. Wrap upgraded connection with `TokioIo` adapter
/// 2. Create WebSocket stream using `tokio-tungstenite`
/// 3. Wrap in `WebSocketConnection` for convenient API
/// 4. Pass to user handler for message processing
/// 5. Return handler's response when connection closes
///
/// # Example Usage (Internal)
///
/// ```
/// // After sending 101 response
/// tokio::spawn(async move {
/// match hyper::upgrade::on(req).await {
/// Ok(upgraded) => {
/// let response = handle_websocket_upgrade(
/// framework_req,
/// upgraded,
/// handler
/// ).await;
///
/// if !response.status.is_success() {
/// tracing::error!("WebSocket error: {}", response.status);
/// }
/// }
/// Err(e) => {
/// tracing::error!("Upgrade failed: {}", e);
/// }
/// }
/// });
/// ```
///
/// # Performance
///
/// The WebSocket stream is configured for optimal performance:
/// - Zero-copy message passing where possible
/// - Efficient framing and masking
/// - Automatic fragmentation handling
/// - Configurable buffer sizes
///
/// # Error Handling
///
/// Errors during the WebSocket session are returned as `Response` objects
/// with appropriate status codes. The handler can return error responses
/// which will close the connection gracefully.
///
/// # Reference
///
/// - [RFC 6455 Section 5 - Data Framing](https://datatracker.ietf.org/doc/html/rfc6455#section-5)
/// - [tokio-tungstenite Documentation](https://docs.rs/tokio-tungstenite)
pub async
/// Generate the `Sec-WebSocket-Accept` value from the client's key.
///
/// This function implements the algorithm specified in RFC 6455:
/// 1. Concatenate the client's `Sec-WebSocket-Key` with the WebSocket GUID
/// 2. Compute SHA-1 hash of the result
/// 3. Base64-encode the hash
///
/// # Parameters
///
/// * `key` - The client's `Sec-WebSocket-Key` header value
///
/// # Returns
///
/// A Base64-encoded string to be sent as `Sec-WebSocket-Accept`
///
/// # Algorithm
///
/// ```
/// Sec-WebSocket-Accept = base64(sha1(Sec-WebSocket-Key + GUID))
/// ```
///
/// where GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
///
/// # Example
///
/// ```
/// let client_key = "dGhlIHNhbXBsZSBub25jZQ==";
/// let accept_key = generate_accept_key(client_key);
/// // accept_key = "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="
/// ```
///
/// # Security Note
///
/// This function uses SHA-1, which is cryptographically weak but acceptable
/// for this specific use case as defined by RFC 6455. The hash is used only
/// for handshake validation, not for cryptographic security.
///
/// # Reference
///
/// [RFC 6455 Section 4.2.2](https://datatracker.ietf.org/doc/html/rfc6455#section-4.2.2)