Skip to main content

http_type/websocket_frame/
impl.rs

1use super::*;
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    /// - `Self` - A default `WebSocketFrame` instance.
13    #[inline(always)]
14    fn default() -> Self {
15        Self {
16            fin: false,
17            opcode: WebSocketOpcode::Text,
18            mask: false,
19            payload_data: Vec::new(),
20        }
21    }
22}
23
24impl WebSocketOpcode {
25    /// Creates a `WebSocketOpcode` from a raw u8 value.
26    ///
27    /// # Arguments
28    ///
29    /// - `u8` - The raw opcode value.
30    ///
31    /// # Returns
32    ///
33    /// - `Self` - A `WebSocketOpcode` enum variant corresponding to the raw value.
34    #[inline(always)]
35    pub fn from_u8(opcode: u8) -> Self {
36        match opcode {
37            0x0 => Self::Continuation,
38            0x1 => Self::Text,
39            0x2 => Self::Binary,
40            0x8 => Self::Close,
41            0x9 => Self::Ping,
42            0xA => Self::Pong,
43            _ => Self::Reserved(opcode),
44        }
45    }
46
47    /// Converts the `WebSocketOpcode` to its raw u8 value.
48    ///
49    /// # Returns
50    ///
51    /// - `u8` - The raw u8 value of the opcode.
52    #[inline(always)]
53    pub fn to_u8(&self) -> u8 {
54        match self {
55            Self::Continuation => 0x0,
56            Self::Text => 0x1,
57            Self::Binary => 0x2,
58            Self::Close => 0x8,
59            Self::Ping => 0x9,
60            Self::Pong => 0xA,
61            Self::Reserved(code) => *code,
62        }
63    }
64
65    /// Checks if the opcode is a control frame.
66    ///
67    /// # Returns
68    ///
69    /// - `bool` - `true` if the opcode represents a control frame (Close, Ping, Pong), otherwise `false`.
70    #[inline(always)]
71    pub fn is_control(&self) -> bool {
72        matches!(self, Self::Close | Self::Ping | Self::Pong)
73    }
74
75    /// Checks if the opcode is a data frame.
76    ///
77    /// # Returns
78    ///
79    /// - `bool` - `true` if the opcode represents a data frame (Text, Binary, Continuation), otherwise `false`.
80    #[inline(always)]
81    pub fn is_data(&self) -> bool {
82        matches!(self, Self::Text | Self::Binary | Self::Continuation)
83    }
84
85    /// Checks if the opcode is a continuation frame.
86    ///
87    /// # Returns
88    ///
89    /// - `bool` - `true` if the opcode is `Continuation`, otherwise `false`.
90    #[inline(always)]
91    pub fn is_continuation(&self) -> bool {
92        matches!(self, Self::Continuation)
93    }
94
95    /// Checks if the opcode is a text frame.
96    ///
97    /// # Returns
98    ///
99    /// - `bool` - `true` if the opcode is `Text`, otherwise `false`.
100    #[inline(always)]
101    pub fn is_text(&self) -> bool {
102        matches!(self, Self::Text)
103    }
104
105    /// Checks if the opcode is a binary frame.
106    ///
107    /// # Returns
108    ///
109    /// - `bool` - `true` if the opcode is `Binary`, otherwise `false`.
110    #[inline(always)]
111    pub fn is_binary(&self) -> bool {
112        matches!(self, Self::Binary)
113    }
114
115    /// Checks if the opcode is a close frame.
116    ///
117    /// # Returns
118    ///
119    /// - `bool` - `true` if the opcode is `Close`, otherwise `false`.
120    #[inline(always)]
121    pub fn is_close(&self) -> bool {
122        matches!(self, Self::Close)
123    }
124
125    /// Checks if the opcode is a ping frame.
126    ///
127    /// # Returns
128    ///
129    /// - `bool` - `true` if the opcode is `Ping`, otherwise `false`.
130    #[inline(always)]
131    pub fn is_ping(&self) -> bool {
132        matches!(self, Self::Ping)
133    }
134
135    /// Checks if the opcode is a pong frame.
136    ///
137    /// # Returns
138    ///
139    /// - `bool` - `true` if the opcode is `Pong`, otherwise `false`.
140    #[inline(always)]
141    pub fn is_pong(&self) -> bool {
142        matches!(self, Self::Pong)
143    }
144
145    /// Checks if the opcode is a reserved frame.
146    ///
147    /// # Returns
148    ///
149    /// - `bool` - `true` if the opcode is `Reserved(_)`, otherwise `false`.
150    #[inline(always)]
151    pub fn is_reserved(&self) -> bool {
152        matches!(self, Self::Reserved(_))
153    }
154}
155
156impl WebSocketFrame {
157    /// Decodes a WebSocket frame from the provided data slice.
158    ///
159    /// This function parses the raw bytes from a WebSocket stream according to the WebSocket protocol
160    /// specification to reconstruct a `WebSocketFrame`. It handles FIN bit, opcode, mask bit,
161    /// payload length (including extended lengths), mask key, and the payload data itself.
162    ///
163    /// # Arguments
164    ///
165    /// - `D` - The raw data to decode into a WebSocket frame, which requires the `AsRef<[u8]>` bound.
166    ///
167    /// # Returns
168    ///
169    /// - `Option<(WebSocketFrame, usize)>` - `Some((frame, consumed))` when the frame is
170    ///   successfully decoded, otherwise `None` when the frame is incomplete or malformed.
171    pub fn decode_ws_frame<D>(data: D) -> Option<(WebSocketFrame, usize)>
172    where
173        D: AsRef<[u8]>,
174    {
175        let data_ref: &[u8] = data.as_ref();
176        if data_ref.len() < 2 {
177            return None;
178        }
179        let mut index: usize = 0;
180        let fin: bool = (data_ref[index] & 0b1000_0000) != 0;
181        let opcode: WebSocketOpcode = WebSocketOpcode::from_u8(data_ref[index] & 0b0000_1111);
182        index += 1;
183        let mask: bool = (data_ref[index] & 0b1000_0000) != 0;
184        let mut payload_len: usize = (data_ref[index] & 0b0111_1111) as usize;
185        index += 1;
186        if payload_len == 126 {
187            if data_ref.len() < index + 2 {
188                return None;
189            }
190            payload_len = u16::from_be_bytes(data_ref[index..index + 2].try_into().ok()?) as usize;
191            index += 2;
192        } else if payload_len == 127 {
193            if data_ref.len() < index + 8 {
194                return None;
195            }
196            payload_len = u64::from_be_bytes(data_ref[index..index + 8].try_into().ok()?) as usize;
197            index += 8;
198        }
199        let mask_key: Option<[u8; 4]> = if mask {
200            if data_ref.len() < index + 4 {
201                return None;
202            }
203            let key: [u8; 4] = data_ref[index..index + 4].try_into().ok()?;
204            index += 4;
205            Some(key)
206        } else {
207            None
208        };
209        if data_ref.len() < index + payload_len {
210            return None;
211        }
212        let mut payload: Vec<u8> = data_ref[index..index + payload_len].to_vec();
213        if let Some(mask_key) = mask_key {
214            for (byte_index, payload_byte) in payload.iter_mut().enumerate() {
215                *payload_byte ^= mask_key[byte_index % 4];
216            }
217        }
218        index += payload_len;
219        let frame: WebSocketFrame = WebSocketFrame {
220            fin,
221            opcode,
222            mask,
223            payload_data: payload,
224        };
225        Some((frame, index))
226    }
227
228    /// Creates a list of response frames from the provided body.
229    ///
230    /// This method segments the response body into WebSocket frames, respecting the maximum frame size
231    /// and handling UTF-8 character boundaries for text frames. It determines the appropriate opcode
232    /// (Text or Binary) based on the body's content.
233    ///
234    /// # Arguments
235    ///
236    /// - `D` - A reference to a response body (payload) as a byte slice, which requires the
237    ///   `AsRef<[u8]>` bound.
238    ///
239    /// # Returns
240    ///
241    /// - `Vec<ResponseBody>` - A vector of `ResponseBody` (byte vectors), where each element represents a framed WebSocket message.
242    pub fn create_frame_list<D>(data: D) -> Vec<ResponseBody>
243    where
244        D: AsRef<[u8]>,
245    {
246        let data_ref: &[u8] = data.as_ref();
247        let total_len: usize = data_ref.len();
248        let mut offset: usize = 0;
249        let mut frames_list: Vec<ResponseBody> =
250            Vec::with_capacity((total_len / MAX_FRAME_SIZE) + 1);
251        let mut is_first_frame: bool = true;
252        let is_valid_utf8: bool = from_utf8(data_ref).is_ok();
253        let base_opcode: WebSocketOpcode = if is_valid_utf8 {
254            WebSocketOpcode::Text
255        } else {
256            WebSocketOpcode::Binary
257        };
258        while offset < total_len {
259            let remaining: usize = total_len - offset;
260            let mut frame_size: usize = remaining.min(MAX_FRAME_SIZE);
261            if is_valid_utf8 && frame_size < remaining {
262                while frame_size > 0 && (data_ref[offset + frame_size] & 0xC0) == 0x80 {
263                    frame_size -= 1;
264                }
265                if frame_size == 0 {
266                    frame_size = remaining.min(MAX_FRAME_SIZE);
267                }
268            }
269            let mut frame: ResponseBody = Vec::with_capacity(frame_size + 10);
270            let opcode: WebSocketOpcode = if is_first_frame {
271                base_opcode
272            } else {
273                WebSocketOpcode::Continuation
274            };
275            let fin: u8 = if remaining > frame_size { 0x00 } else { 0x80 };
276            let opcode_byte: u8 = opcode.to_u8() & 0x0F;
277            frame.push(fin | opcode_byte);
278            if frame_size < 126 {
279                frame.push(frame_size as u8);
280            } else if frame_size <= MAX_FRAME_SIZE {
281                frame.push(126);
282                frame.extend_from_slice(&(frame_size as u16).to_be_bytes());
283            } else {
284                frame.push(127);
285                frame.extend_from_slice(&(frame_size as u16).to_be_bytes());
286            }
287            let end: usize = offset + frame_size;
288            frame.extend_from_slice(&data_ref[offset..end]);
289            frames_list.push(frame);
290            offset = end;
291            is_first_frame = false;
292        }
293        frames_list
294    }
295
296    /// Calculates the SHA-1 hash of the input data.
297    ///
298    /// This function implements the SHA-1 cryptographic hash algorithm according to RFC 3174.
299    /// It processes the input data in 512-bit (64-byte) blocks and produces a 160-bit (20-byte) hash.
300    ///
301    /// # Arguments
302    ///
303    /// - `D` - The input data to be hashed, which requires the `AsRef<[u8]>` bound.
304    ///
305    /// # Returns
306    ///
307    /// A 20-byte array representing the SHA-1 hash of the input data.
308    pub fn sha1<D>(data: D) -> [u8; 20]
309    where
310        D: AsRef<[u8]>,
311    {
312        let data_ref: &[u8] = data.as_ref();
313        let mut hash_state: [u32; 5] = HASH_STATE;
314        let mut padded_data: Vec<u8> = Vec::from(data_ref);
315        let original_size_bits: u64 = (padded_data.len() * 8) as u64;
316        padded_data.push(0x80);
317        while !(padded_data.len() + 8).is_multiple_of(64) {
318            padded_data.push(0);
319        }
320        padded_data.extend_from_slice(&original_size_bits.to_be_bytes());
321        for block in padded_data.as_chunks::<64>().0 {
322            let mut message_schedule: [u32; 80] = [0u32; 80];
323            for (chunk_index, block_chunk) in block.as_chunks::<4>().0.iter().enumerate().take(16) {
324                message_schedule[chunk_index] = u32::from_be_bytes([
325                    block_chunk[0],
326                    block_chunk[1],
327                    block_chunk[2],
328                    block_chunk[3],
329                ]);
330            }
331            for schedule_index in 16..80 {
332                message_schedule[schedule_index] = (message_schedule[schedule_index - 3]
333                    ^ message_schedule[schedule_index - 8]
334                    ^ message_schedule[schedule_index - 14]
335                    ^ message_schedule[schedule_index - 16])
336                    .rotate_left(1);
337            }
338            let [mut hash_a, mut hash_b, mut hash_c, mut hash_d, mut hash_e] = hash_state;
339            for (round_index, &schedule_word) in message_schedule.iter().enumerate() {
340                let (round_function, round_constant): (u32, u32) = match round_index {
341                    0..=19 => ((hash_b & hash_c) | (!hash_b & hash_d), 0x5A827999),
342                    20..=39 => (hash_b ^ hash_c ^ hash_d, 0x6ED9EBA1),
343                    40..=59 => (
344                        (hash_b & hash_c) | (hash_b & hash_d) | (hash_c & hash_d),
345                        0x8F1BBCDC,
346                    ),
347                    _ => (hash_b ^ hash_c ^ hash_d, 0xCA62C1D6),
348                };
349                let temp: u32 = hash_a
350                    .rotate_left(5)
351                    .wrapping_add(round_function)
352                    .wrapping_add(hash_e)
353                    .wrapping_add(round_constant)
354                    .wrapping_add(schedule_word);
355                hash_e = hash_d;
356                hash_d = hash_c;
357                hash_c = hash_b.rotate_left(30);
358                hash_b = hash_a;
359                hash_a = temp;
360            }
361            hash_state[0] = hash_state[0].wrapping_add(hash_a);
362            hash_state[1] = hash_state[1].wrapping_add(hash_b);
363            hash_state[2] = hash_state[2].wrapping_add(hash_c);
364            hash_state[3] = hash_state[3].wrapping_add(hash_d);
365            hash_state[4] = hash_state[4].wrapping_add(hash_e);
366        }
367        let mut result: [u8; 20] = [0u8; 20];
368        for (state_index, &state_value) in hash_state.iter().enumerate() {
369            result[state_index * 4..(state_index + 1) * 4]
370                .copy_from_slice(&state_value.to_be_bytes());
371        }
372        result
373    }
374
375    /// Generates a WebSocket accept key from the client-provided key, returning an `Option<String>`.
376    ///
377    /// # Arguments
378    ///
379    /// - `K` - The client-provided key (typically from the `Sec-WebSocket-Key` header), which
380    ///   requires the `AsRef<str>` bound.
381    ///
382    /// # Returns
383    ///
384    /// - `Option<String>` - An optional string representing the generated WebSocket accept key (typically for the `Sec-WebSocket-Accept` header).
385    #[inline(always)]
386    pub fn try_generate_accept_key<K>(key: K) -> Option<String>
387    where
388        K: AsRef<str>,
389    {
390        let key_ref: &str = key.as_ref();
391        let mut data: [u8; 60] = [0u8; 60];
392        data[..24].copy_from_slice(&key_ref.as_bytes()[..24.min(key_ref.len())]);
393        data[24..].copy_from_slice(GUID);
394        let hash: [u8; 20] = Self::sha1(data);
395        Self::try_base64_encode(hash)
396    }
397
398    /// Generates a WebSocket accept key from the client-provided key.
399    ///
400    /// This function is used during the WebSocket handshake to validate the client's request.
401    /// It concatenates the client's key with a specific GUID, calculates the SHA-1 hash of the result,
402    /// and then encodes the hash in base64.
403    ///
404    /// # Arguments
405    ///
406    /// - `K` - The client-provided key (typically from the `Sec-WebSocket-Key` header), which
407    ///   requires the `AsRef<str>` bound.
408    ///
409    /// # Returns
410    ///
411    /// - `String` - The generated WebSocket accept key (typically for the `Sec-WebSocket-Accept` header).
412    ///
413    /// # Panics
414    ///
415    /// This function will panic if the input key cannot be converted to a UTF-8 string.
416    #[inline(always)]
417    pub fn generate_accept_key<K>(key: K) -> String
418    where
419        K: AsRef<str>,
420    {
421        let key_ref: &str = key.as_ref();
422        let mut data: [u8; 60] = [0u8; 60];
423        data[..24].copy_from_slice(&key_ref.as_bytes()[..24.min(key_ref.len())]);
424        data[24..].copy_from_slice(GUID);
425        let hash: [u8; 20] = Self::sha1(data);
426        Self::base64_encode(hash)
427    }
428
429    /// Encodes the input data as a base64 string, returning an `Option<String>`.
430    ///
431    /// # Arguments
432    ///
433    /// - `D` - The data to encode in base64, which requires the `AsRef<[u8]>` bound.
434    ///
435    /// # Returns
436    ///
437    /// - `Option<String>` - An optional string with the base64 encoded representation of the input data.
438    pub fn try_base64_encode<D>(data: D) -> Option<String>
439    where
440        D: AsRef<[u8]>,
441    {
442        let data_ref: &[u8] = data.as_ref();
443        let mut encoded_data: Vec<u8> = Vec::with_capacity(data_ref.len().div_ceil(3) * 4);
444        for chunk in data_ref.chunks(3) {
445            let mut buffer: [u8; 3] = [0u8; 3];
446            buffer[..chunk.len()].copy_from_slice(chunk);
447            let indices: [u8; 4] = [
448                buffer[0] >> 2,
449                ((buffer[0] & 0b11) << 4) | (buffer[1] >> 4),
450                ((buffer[1] & 0b1111) << 2) | (buffer[2] >> 6),
451                buffer[2] & 0b111111,
452            ];
453            for &idx in &indices[..chunk.len() + 1] {
454                encoded_data.push(BASE64_CHARSET_TABLE[idx as usize]);
455            }
456            while !encoded_data.len().is_multiple_of(4) {
457                encoded_data.push(EQUAL_BYTES[0]);
458            }
459        }
460        String::from_utf8(encoded_data).ok()
461    }
462
463    /// Encodes the input data as a base64 string.
464    ///
465    /// # Arguments
466    ///
467    /// - `D` - The data to encode in base64, which requires the `AsRef<[u8]>` bound.
468    ///
469    /// # Returns
470    ///
471    /// - `String` - A string with the base64 encoded representation of the input data.
472    ///
473    /// # Panics
474    ///
475    /// This function will panic if the input data cannot be converted to a UTF-8 string.
476    #[inline(always)]
477    pub fn base64_encode<D>(data: D) -> String
478    where
479        D: AsRef<[u8]>,
480    {
481        Self::try_base64_encode(data).unwrap()
482    }
483
484    /// Checks if the opcode is a continuation frame.
485    ///
486    /// # Returns
487    ///
488    /// - `bool` - `true` if the opcode is `Continuation`, otherwise `false`.
489    #[inline(always)]
490    pub fn is_continuation_opcode(&self) -> bool {
491        self.get_opcode().is_continuation()
492    }
493
494    /// Checks if the opcode is a text frame.
495    ///
496    /// # Returns
497    ///
498    /// - `bool` - `true` if the opcode is `Text`, otherwise `false`.
499    #[inline(always)]
500    pub fn is_text_opcode(&self) -> bool {
501        self.get_opcode().is_text()
502    }
503
504    /// Checks if the opcode is a binary frame.
505    ///
506    /// # Returns
507    ///
508    /// - `bool` - `true` if the opcode is `Binary`, otherwise `false`.
509    #[inline(always)]
510    pub fn is_binary_opcode(&self) -> bool {
511        self.get_opcode().is_binary()
512    }
513
514    /// Checks if the opcode is a close frame.
515    ///
516    /// # Returns
517    ///
518    /// - `bool` - `true` if the opcode is `Close`, otherwise `false`.
519    #[inline(always)]
520    pub fn is_close_opcode(&self) -> bool {
521        self.get_opcode().is_close()
522    }
523
524    /// Checks if the opcode is a ping frame.
525    ///
526    /// # Returns
527    ///
528    /// - `bool` - `true` if the opcode is `Ping`, otherwise `false`.
529    #[inline(always)]
530    pub fn is_ping_opcode(&self) -> bool {
531        self.get_opcode().is_ping()
532    }
533
534    /// Checks if the opcode is a pong frame.
535    ///
536    /// # Returns
537    ///
538    /// - `bool` - `true` if the opcode is `Pong`, otherwise `false`.
539    #[inline(always)]
540    pub fn is_pong_opcode(&self) -> bool {
541        self.get_opcode().is_pong()
542    }
543
544    /// Checks if the opcode is a reserved frame.
545    ///
546    /// # Returns
547    ///
548    /// - `bool` - `true` if the opcode is `Reserved(_)`, otherwise `false`.
549    #[inline(always)]
550    pub fn is_reserved_opcode(&self) -> bool {
551        self.get_opcode().is_reserved()
552    }
553
554    /// Handles a decoded WebSocket Text or Binary frame and accumulates payload data.
555    ///
556    /// # Arguments
557    ///
558    /// - `&mut Vec<u8>` - The accumulated frame data.
559    ///
560    /// # Returns
561    ///
562    /// - `Result<Option<RequestBody>, RequestError>` - Some(request) if frame is complete, None to continue, or error.
563    #[inline(always)]
564    pub(crate) fn build_full_frame(
565        &self,
566        full_frame: &mut Vec<u8>,
567    ) -> Result<Option<RequestBody>, RequestError> {
568        let payload_data: &[u8] = self.get_payload_data();
569        full_frame.extend_from_slice(payload_data);
570        if *self.get_fin() {
571            return Ok(Some(full_frame.clone()));
572        }
573        Ok(None)
574    }
575}