http_type/websocket_frame/impl.rs
1use crate::*;
2
3/// Implements the `Default` trait for `WebSocketFrame`.
4///
5/// Provides a default `WebSocketFrame` with `fin: false`, `opcode: WebSocketOpcode::Text`,
6/// `mask: false`, and an empty `payload_data`.
7impl Default for WebSocketFrame {
8 /// Returns the default `WebSocketFrame`.
9 ///
10 /// # Returns
11 ///
12 /// A default `WebSocketFrame` instance.
13 fn default() -> Self {
14 Self {
15 fin: false,
16 opcode: WebSocketOpcode::Text,
17 mask: false,
18 payload_data: Vec::new(),
19 }
20 }
21}
22
23impl WebSocketOpcode {
24 /// Creates a `WebSocketOpcode` from a raw u8 value.
25 ///
26 /// # Arguments
27 ///
28 /// - `opcode`: The raw opcode value.
29 ///
30 /// # Returns
31 ///
32 /// A `WebSocketOpcode` enum variant corresponding to the raw value.
33 pub fn from_u8(opcode: u8) -> Self {
34 match opcode {
35 0x0 => Self::Continuation,
36 0x1 => Self::Text,
37 0x2 => Self::Binary,
38 0x8 => Self::Close,
39 0x9 => Self::Ping,
40 0xA => Self::Pong,
41 _ => Self::Reserved(opcode),
42 }
43 }
44
45 /// Converts the `WebSocketOpcode` to its raw u8 value.
46 ///
47 /// # Returns
48 ///
49 /// The raw u8 value of the opcode.
50 pub fn to_u8(&self) -> u8 {
51 match self {
52 Self::Continuation => 0x0,
53 Self::Text => 0x1,
54 Self::Binary => 0x2,
55 Self::Close => 0x8,
56 Self::Ping => 0x9,
57 Self::Pong => 0xA,
58 Self::Reserved(code) => *code,
59 }
60 }
61
62 /// Checks if the opcode is a control frame.
63 ///
64 /// # Returns
65 ///
66 /// `true` if the opcode represents a control frame (Close, Ping, Pong), otherwise `false`.
67 pub fn is_control(&self) -> bool {
68 matches!(self, Self::Close | Self::Ping | Self::Pong)
69 }
70
71 /// Checks if the opcode is a data frame.
72 ///
73 /// # Returns
74 ///
75 /// `true` if the opcode represents a data frame (Text, Binary, Continuation), otherwise `false`.
76 pub fn is_data(&self) -> bool {
77 matches!(self, Self::Text | Self::Binary | Self::Continuation)
78 }
79
80 /// Checks if the opcode is a continuation frame.
81 ///
82 /// # Returns
83 ///
84 /// `true` if the opcode is `Continuation`, otherwise `false`.
85 pub fn is_continuation(&self) -> bool {
86 matches!(self, Self::Continuation)
87 }
88
89 /// Checks if the opcode is a text frame.
90 ///
91 /// # Returns
92 ///
93 /// `true` if the opcode is `Text`, otherwise `false`.
94 pub fn is_text(&self) -> bool {
95 matches!(self, Self::Text)
96 }
97
98 /// Checks if the opcode is a binary frame.
99 ///
100 /// # Returns
101 ///
102 /// `true` if the opcode is `Binary`, otherwise `false`.
103 pub fn is_binary(&self) -> bool {
104 matches!(self, Self::Binary)
105 }
106
107 /// Checks if the opcode is a close frame.
108 ///
109 /// # Returns
110 ///
111 /// `true` if the opcode is `Close`, otherwise `false`.
112 pub fn is_close(&self) -> bool {
113 matches!(self, Self::Close)
114 }
115
116 /// Checks if the opcode is a ping frame.
117 ///
118 /// # Returns
119 ///
120 /// `true` if the opcode is `Ping`, otherwise `false`.
121 pub fn is_ping(&self) -> bool {
122 matches!(self, Self::Ping)
123 }
124
125 /// Checks if the opcode is a pong frame.
126 ///
127 /// # Returns
128 ///
129 /// `true` if the opcode is `Pong`, otherwise `false`.
130 pub fn is_pong(&self) -> bool {
131 matches!(self, Self::Pong)
132 }
133
134 /// Checks if the opcode is a reserved frame.
135 ///
136 /// # Returns
137 ///
138 /// `true` if the opcode is `Reserved(_)`, otherwise `false`.
139 pub fn is_reserved(&self) -> bool {
140 matches!(self, Self::Reserved(_))
141 }
142}
143
144impl WebSocketFrame {
145 /// Decodes a WebSocket frame from the provided data slice.
146 ///
147 /// This function parses the raw bytes from a WebSocket stream according to the WebSocket protocol
148 /// specification to reconstruct a `WebSocketFrame`. It handles FIN bit, opcode, mask bit,
149 /// payload length (including extended lengths), mask key, and the payload data itself.
150 ///
151 /// # Arguments
152 ///
153 /// - `&[u8]` - The raw data slice from the WebSocket stream.
154 ///
155 /// # Returns
156 ///
157 /// - `Some((WebSocketFrame, usize))`: If the frame is successfully decoded, returns the decoded frame
158 /// and the number of bytes consumed from the input slice.
159 /// - `None`: If the frame is incomplete or malformed.
160 pub fn decode_ws_frame(data: &[u8]) -> WebsocketFrameWithLengthOption {
161 if data.len() < 2 {
162 return None;
163 }
164 let mut index: usize = 0;
165 let fin: bool = (data[index] & 0b1000_0000) != 0;
166 let opcode: WebSocketOpcode = WebSocketOpcode::from_u8(data[index] & 0b0000_1111);
167 index += 1;
168 let mask: bool = (data[index] & 0b1000_0000) != 0;
169 let mut payload_len: usize = (data[index] & 0b0111_1111) as usize;
170 index += 1;
171 if payload_len == 126 {
172 if data.len() < index + 2 {
173 return None;
174 }
175 payload_len = u16::from_be_bytes(data[index..index + 2].try_into().ok()?) as usize;
176 index += 2;
177 } else if payload_len == 127 {
178 if data.len() < index + 8 {
179 return None;
180 }
181 payload_len = u64::from_be_bytes(data[index..index + 8].try_into().ok()?) as usize;
182 index += 8;
183 }
184 let mask_key: Option<[u8; 4]> = if mask {
185 if data.len() < index + 4 {
186 return None;
187 }
188 let key: [u8; 4] = data[index..index + 4].try_into().ok()?;
189 index += 4;
190 Some(key)
191 } else {
192 None
193 };
194 if data.len() < index + payload_len {
195 return None;
196 }
197 let mut payload: Vec<u8> = data[index..index + payload_len].to_vec();
198 if let Some(mask_key) = mask_key {
199 for (i, byte) in payload.iter_mut().enumerate() {
200 *byte ^= mask_key[i % 4];
201 }
202 }
203 index += payload_len;
204 let frame: WebSocketFrame = WebSocketFrame {
205 fin,
206 opcode,
207 mask,
208 payload_data: payload,
209 };
210 Some((frame, index))
211 }
212
213 /// Creates a list of response frames from the provided body.
214 ///
215 /// This method segments the response body into WebSocket frames, respecting the maximum frame size
216 /// and handling UTF-8 character boundaries for text frames. It determines the appropriate opcode
217 /// (Text or Binary) based on the body's content.
218 ///
219 /// # Arguments
220 ///
221 /// - `Into<ResponseBody>` - A reference to a response body (payload) as a byte slice.
222 ///
223 /// # Returns
224 ///
225 /// - A vector of `ResponseBody` (byte vectors), where each element represents a framed WebSocket message.
226 pub fn create_response_frame_list<D>(data: D) -> Vec<ResponseBody>
227 where
228 D: Into<ResponseBody>,
229 {
230 let data_into: &[u8] = &data.into();
231 let total_len: usize = data_into.len();
232 let mut offset: usize = 0;
233 let mut frames_list: Vec<ResponseBody> =
234 Vec::with_capacity((total_len / MAX_FRAME_SIZE) + 1);
235 let mut is_first_frame: bool = true;
236 let is_valid_utf8: bool = std::str::from_utf8(data_into).is_ok();
237 let base_opcode: WebSocketOpcode = if is_valid_utf8 {
238 WebSocketOpcode::Text
239 } else {
240 WebSocketOpcode::Binary
241 };
242 while offset < total_len {
243 let remaining: usize = total_len - offset;
244 let mut frame_size: usize = remaining.min(MAX_FRAME_SIZE);
245 if is_valid_utf8 && frame_size < remaining {
246 while frame_size > 0 && (data_into[offset + frame_size] & 0xC0) == 0x80 {
247 frame_size -= 1;
248 }
249 if frame_size == 0 {
250 frame_size = remaining.min(MAX_FRAME_SIZE);
251 }
252 }
253 let mut frame: ResponseBody = Vec::with_capacity(frame_size + 10);
254 let opcode: WebSocketOpcode = if is_first_frame {
255 base_opcode
256 } else {
257 WebSocketOpcode::Continuation
258 };
259 let fin: u8 = if remaining > frame_size { 0x00 } else { 0x80 };
260 let opcode_byte: u8 = opcode.to_u8() & 0x0F;
261 frame.push(fin | opcode_byte);
262 if frame_size < 126 {
263 frame.push(frame_size as u8);
264 } else if frame_size <= MAX_FRAME_SIZE {
265 frame.push(126);
266 frame.extend_from_slice(&(frame_size as u16).to_be_bytes());
267 } else {
268 frame.push(127);
269 frame.extend_from_slice(&(frame_size as u16).to_be_bytes());
270 }
271 let end: usize = offset + frame_size;
272 frame.extend_from_slice(&data_into[offset..end]);
273 frames_list.push(frame);
274 offset = end;
275 is_first_frame = false;
276 }
277 frames_list
278 }
279
280 /// Calculates the SHA-1 hash of the input data.
281 ///
282 /// This function implements the SHA-1 cryptographic hash algorithm according to RFC 3174.
283 /// It processes the input data in 512-bit (64-byte) blocks and produces a 160-bit (20-byte) hash.
284 ///
285 /// # Arguments
286 ///
287 /// - `&[u8]` - A byte slice containing the input data to be hashed.
288 ///
289 /// # Returns
290 ///
291 /// - A 20-byte array representing the SHA-1 hash of the input data.
292 pub fn sha1(data: &[u8]) -> [u8; 20] {
293 let mut hash_state: [u32; 5] = HASH_STATE;
294 let mut padded_data: Vec<u8> = Vec::from(data);
295 let original_length_bits: u64 = (padded_data.len() * 8) as u64;
296 padded_data.push(0x80);
297 while (padded_data.len() + 8) % 64 != 0 {
298 padded_data.push(0);
299 }
300 padded_data.extend_from_slice(&original_length_bits.to_be_bytes());
301 for block in padded_data.chunks_exact(64) {
302 let mut message_schedule: [u32; 80] = [0u32; 80];
303 for (i, block_chunk) in block.chunks_exact(4).enumerate().take(16) {
304 message_schedule[i] = u32::from_be_bytes([
305 block_chunk[0],
306 block_chunk[1],
307 block_chunk[2],
308 block_chunk[3],
309 ]);
310 }
311 for i in 16..80 {
312 message_schedule[i] = (message_schedule[i - 3]
313 ^ message_schedule[i - 8]
314 ^ message_schedule[i - 14]
315 ^ message_schedule[i - 16])
316 .rotate_left(1);
317 }
318 let [mut a, mut b, mut c, mut d, mut e] = hash_state;
319 for (i, &word) in message_schedule.iter().enumerate() {
320 let (f, k) = match i {
321 0..=19 => ((b & c) | (!b & d), 0x5A827999),
322 20..=39 => (b ^ c ^ d, 0x6ED9EBA1),
323 40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1BBCDC),
324 _ => (b ^ c ^ d, 0xCA62C1D6),
325 };
326 let temp: u32 = a
327 .rotate_left(5)
328 .wrapping_add(f)
329 .wrapping_add(e)
330 .wrapping_add(k)
331 .wrapping_add(word);
332 e = d;
333 d = c;
334 c = b.rotate_left(30);
335 b = a;
336 a = temp;
337 }
338 hash_state[0] = hash_state[0].wrapping_add(a);
339 hash_state[1] = hash_state[1].wrapping_add(b);
340 hash_state[2] = hash_state[2].wrapping_add(c);
341 hash_state[3] = hash_state[3].wrapping_add(d);
342 hash_state[4] = hash_state[4].wrapping_add(e);
343 }
344 let mut result: [u8; 20] = [0u8; 20];
345 for (i, &val) in hash_state.iter().enumerate() {
346 result[i * 4..(i + 1) * 4].copy_from_slice(&val.to_be_bytes());
347 }
348 result
349 }
350
351 /// Generates a WebSocket accept key from the client-provided key.
352 ///
353 /// This function is used during the WebSocket handshake to validate the client's request.
354 /// It concatenates the client's key with a specific GUID, calculates the SHA-1 hash of the result,
355 /// and then encodes the hash in base64.
356 ///
357 /// # Arguments
358 ///
359 /// - `&str` - A string slice containing the client-provided key (typically from the `Sec-WebSocket-Key` header).
360 ///
361 /// # Returns
362 ///
363 /// - A string representing the generated WebSocket accept key (typically for the `Sec-WebSocket-Accept` header).
364 pub fn generate_accept_key(key: &str) -> String {
365 let mut data: [u8; 60] = [0u8; 60];
366 data[..24].copy_from_slice(&key.as_bytes()[..24.min(key.len())]);
367 data[24..].copy_from_slice(GUID);
368 let hash: [u8; 20] = Self::sha1(&data);
369 Self::base64_encode(&hash)
370 }
371
372 /// Encodes the input data as a base64 string.
373 ///
374 /// This function implements the Base64 encoding scheme, converting binary data into an ASCII string format.
375 /// It processes the input data in chunks of 3 bytes and encodes them into 4 base64 characters.
376 /// Padding with '=' characters is applied if necessary.
377 ///
378 /// # Arguments
379 ///
380 /// - `&[u8]` - A byte slice containing the data to encode in base64.
381 ///
382 /// # Returns
383 ///
384 /// - A string with the base64 encoded representation of the input data.
385 pub fn base64_encode(data: &[u8]) -> String {
386 let mut encoded_data: Vec<u8> = Vec::with_capacity((data.len() + 2) / 3 * 4);
387 for chunk in data.chunks(3) {
388 let mut buffer: [u8; 3] = [0u8; 3];
389 buffer[..chunk.len()].copy_from_slice(chunk);
390 let indices: [u8; 4] = [
391 buffer[0] >> 2,
392 ((buffer[0] & 0b11) << 4) | (buffer[1] >> 4),
393 ((buffer[1] & 0b1111) << 2) | (buffer[2] >> 6),
394 buffer[2] & 0b111111,
395 ];
396 for &idx in &indices[..chunk.len() + 1] {
397 encoded_data.push(BASE64_CHARSET_TABLE[idx as usize]);
398 }
399 while encoded_data.len() % 4 != 0 {
400 encoded_data.push(EQUAL_BYTES[0]);
401 }
402 }
403 String::from_utf8(encoded_data).unwrap()
404 }
405
406 /// Checks if the opcode is a continuation frame.
407 ///
408 /// # Returns
409 ///
410 /// `true` if the opcode is `Continuation`, otherwise `false`.
411 pub fn is_continuation_opcode(&self) -> bool {
412 self.opcode.is_continuation()
413 }
414
415 /// Checks if the opcode is a text frame.
416 ///
417 /// # Returns
418 ///
419 /// `true` if the opcode is `Text`, otherwise `false`.
420 pub fn is_text_opcode(&self) -> bool {
421 self.opcode.is_text()
422 }
423
424 /// Checks if the opcode is a binary frame.
425 ///
426 /// # Returns
427 ///
428 /// `true` if the opcode is `Binary`, otherwise `false`.
429 pub fn is_binary_opcode(&self) -> bool {
430 self.opcode.is_binary()
431 }
432
433 /// Checks if the opcode is a close frame.
434 ///
435 /// # Returns
436 ///
437 /// `true` if the opcode is `Close`, otherwise `false`.
438 pub fn is_close_opcode(&self) -> bool {
439 self.opcode.is_close()
440 }
441
442 /// Checks if the opcode is a ping frame.
443 ///
444 /// # Returns
445 ///
446 /// `true` if the opcode is `Ping`, otherwise `false`.
447 pub fn is_ping_opcode(&self) -> bool {
448 self.opcode.is_ping()
449 }
450
451 /// Checks if the opcode is a pong frame.
452 ///
453 /// # Returns
454 ///
455 /// `true` if the opcode is `Pong`, otherwise `false`.
456 pub fn is_pong_opcode(&self) -> bool {
457 self.opcode.is_pong()
458 }
459
460 /// Checks if the opcode is a reserved frame.
461 ///
462 /// # Returns
463 ///
464 /// `true` if the opcode is `Reserved(_)`, otherwise `false`.
465 pub fn is_reserved_opcode(&self) -> bool {
466 self.opcode.is_reserved()
467 }
468}