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 /// - `&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(body: &ResponseBody) -> Vec<ResponseBody> {
227 let total_len: usize = body.len();
228 let mut offset: usize = 0;
229 let mut frames_list: Vec<ResponseBody> =
230 Vec::with_capacity((total_len / MAX_FRAME_SIZE) + 1);
231 let mut is_first_frame: bool = true;
232 let is_valid_utf8: bool = std::str::from_utf8(body).is_ok();
233 let base_opcode: WebSocketOpcode = if is_valid_utf8 {
234 WebSocketOpcode::Text
235 } else {
236 WebSocketOpcode::Binary
237 };
238 while offset < total_len {
239 let remaining: usize = total_len - offset;
240 let mut frame_size: usize = remaining.min(MAX_FRAME_SIZE);
241 if is_valid_utf8 && frame_size < remaining {
242 while frame_size > 0 && (body[offset + frame_size] & 0xC0) == 0x80 {
243 frame_size -= 1;
244 }
245 if frame_size == 0 {
246 frame_size = remaining.min(MAX_FRAME_SIZE);
247 }
248 }
249 let mut frame: ResponseBody = Vec::with_capacity(frame_size + 10);
250 let opcode: WebSocketOpcode = if is_first_frame {
251 base_opcode
252 } else {
253 WebSocketOpcode::Continuation
254 };
255 let fin: u8 = if remaining > frame_size { 0x00 } else { 0x80 };
256 let opcode_byte: u8 = opcode.to_u8() & 0x0F;
257 frame.push(fin | opcode_byte);
258 if frame_size < 126 {
259 frame.push(frame_size as u8);
260 } else if frame_size <= MAX_FRAME_SIZE {
261 frame.push(126);
262 frame.extend_from_slice(&(frame_size as u16).to_be_bytes());
263 } else {
264 frame.push(127);
265 frame.extend_from_slice(&(frame_size as u16).to_be_bytes());
266 }
267 let end: usize = offset + frame_size;
268 frame.extend_from_slice(&body[offset..end]);
269 frames_list.push(frame);
270 offset = end;
271 is_first_frame = false;
272 }
273 frames_list
274 }
275
276 /// Calculates the SHA-1 hash of the input data.
277 ///
278 /// This function implements the SHA-1 cryptographic hash algorithm according to RFC 3174.
279 /// It processes the input data in 512-bit (64-byte) blocks and produces a 160-bit (20-byte) hash.
280 ///
281 /// # Arguments
282 ///
283 /// - `&[u8]` - A byte slice containing the input data to be hashed.
284 ///
285 /// # Returns
286 ///
287 /// - A 20-byte array representing the SHA-1 hash of the input data.
288 pub fn sha1(data: &[u8]) -> [u8; 20] {
289 let mut hash_state: [u32; 5] = HASH_STATE;
290 let mut padded_data: Vec<u8> = Vec::from(data);
291 let original_length_bits: u64 = (padded_data.len() * 8) as u64;
292 padded_data.push(0x80);
293 while (padded_data.len() + 8) % 64 != 0 {
294 padded_data.push(0);
295 }
296 padded_data.extend_from_slice(&original_length_bits.to_be_bytes());
297 for block in padded_data.chunks_exact(64) {
298 let mut message_schedule: [u32; 80] = [0u32; 80];
299 for (i, block_chunk) in block.chunks_exact(4).enumerate().take(16) {
300 message_schedule[i] = u32::from_be_bytes([
301 block_chunk[0],
302 block_chunk[1],
303 block_chunk[2],
304 block_chunk[3],
305 ]);
306 }
307 for i in 16..80 {
308 message_schedule[i] = (message_schedule[i - 3]
309 ^ message_schedule[i - 8]
310 ^ message_schedule[i - 14]
311 ^ message_schedule[i - 16])
312 .rotate_left(1);
313 }
314 let [mut a, mut b, mut c, mut d, mut e] = hash_state;
315 for (i, &word) in message_schedule.iter().enumerate() {
316 let (f, k) = match i {
317 0..=19 => ((b & c) | (!b & d), 0x5A827999),
318 20..=39 => (b ^ c ^ d, 0x6ED9EBA1),
319 40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1BBCDC),
320 _ => (b ^ c ^ d, 0xCA62C1D6),
321 };
322 let temp: u32 = a
323 .rotate_left(5)
324 .wrapping_add(f)
325 .wrapping_add(e)
326 .wrapping_add(k)
327 .wrapping_add(word);
328 e = d;
329 d = c;
330 c = b.rotate_left(30);
331 b = a;
332 a = temp;
333 }
334 hash_state[0] = hash_state[0].wrapping_add(a);
335 hash_state[1] = hash_state[1].wrapping_add(b);
336 hash_state[2] = hash_state[2].wrapping_add(c);
337 hash_state[3] = hash_state[3].wrapping_add(d);
338 hash_state[4] = hash_state[4].wrapping_add(e);
339 }
340 let mut result: [u8; 20] = [0u8; 20];
341 for (i, &val) in hash_state.iter().enumerate() {
342 result[i * 4..(i + 1) * 4].copy_from_slice(&val.to_be_bytes());
343 }
344 result
345 }
346
347 /// Generates a WebSocket accept key from the client-provided key.
348 ///
349 /// This function is used during the WebSocket handshake to validate the client's request.
350 /// It concatenates the client's key with a specific GUID, calculates the SHA-1 hash of the result,
351 /// and then encodes the hash in base64.
352 ///
353 /// # Arguments
354 ///
355 /// - `&str` - A string slice containing the client-provided key (typically from the `Sec-WebSocket-Key` header).
356 ///
357 /// # Returns
358 ///
359 /// - A string representing the generated WebSocket accept key (typically for the `Sec-WebSocket-Accept` header).
360 pub fn generate_accept_key(key: &str) -> String {
361 let mut data: [u8; 60] = [0u8; 60];
362 data[..24].copy_from_slice(&key.as_bytes()[..24.min(key.len())]);
363 data[24..].copy_from_slice(GUID);
364 let hash: [u8; 20] = Self::sha1(&data);
365 Self::base64_encode(&hash)
366 }
367
368 /// Encodes the input data as a base64 string.
369 ///
370 /// This function implements the Base64 encoding scheme, converting binary data into an ASCII string format.
371 /// It processes the input data in chunks of 3 bytes and encodes them into 4 base64 characters.
372 /// Padding with '=' characters is applied if necessary.
373 ///
374 /// # Arguments
375 ///
376 /// - `&[u8]` - A byte slice containing the data to encode in base64.
377 ///
378 /// # Returns
379 ///
380 /// - A string with the base64 encoded representation of the input data.
381 pub fn base64_encode(data: &[u8]) -> String {
382 let mut encoded_data: Vec<u8> = Vec::with_capacity((data.len() + 2) / 3 * 4);
383 for chunk in data.chunks(3) {
384 let mut buffer: [u8; 3] = [0u8; 3];
385 buffer[..chunk.len()].copy_from_slice(chunk);
386 let indices: [u8; 4] = [
387 buffer[0] >> 2,
388 ((buffer[0] & 0b11) << 4) | (buffer[1] >> 4),
389 ((buffer[1] & 0b1111) << 2) | (buffer[2] >> 6),
390 buffer[2] & 0b111111,
391 ];
392 for &idx in &indices[..chunk.len() + 1] {
393 encoded_data.push(BASE64_CHARSET_TABLE[idx as usize]);
394 }
395 while encoded_data.len() % 4 != 0 {
396 encoded_data.push(EQUAL_BYTES[0]);
397 }
398 }
399 String::from_utf8(encoded_data).unwrap()
400 }
401
402 /// Checks if the opcode is a continuation frame.
403 ///
404 /// # Returns
405 ///
406 /// `true` if the opcode is `Continuation`, otherwise `false`.
407 pub fn is_continuation_opcode(&self) -> bool {
408 self.opcode.is_continuation()
409 }
410
411 /// Checks if the opcode is a text frame.
412 ///
413 /// # Returns
414 ///
415 /// `true` if the opcode is `Text`, otherwise `false`.
416 pub fn is_text_opcode(&self) -> bool {
417 self.opcode.is_text()
418 }
419
420 /// Checks if the opcode is a binary frame.
421 ///
422 /// # Returns
423 ///
424 /// `true` if the opcode is `Binary`, otherwise `false`.
425 pub fn is_binary_opcode(&self) -> bool {
426 self.opcode.is_binary()
427 }
428
429 /// Checks if the opcode is a close frame.
430 ///
431 /// # Returns
432 ///
433 /// `true` if the opcode is `Close`, otherwise `false`.
434 pub fn is_close_opcode(&self) -> bool {
435 self.opcode.is_close()
436 }
437
438 /// Checks if the opcode is a ping frame.
439 ///
440 /// # Returns
441 ///
442 /// `true` if the opcode is `Ping`, otherwise `false`.
443 pub fn is_ping_opcode(&self) -> bool {
444 self.opcode.is_ping()
445 }
446
447 /// Checks if the opcode is a pong frame.
448 ///
449 /// # Returns
450 ///
451 /// `true` if the opcode is `Pong`, otherwise `false`.
452 pub fn is_pong_opcode(&self) -> bool {
453 self.opcode.is_pong()
454 }
455
456 /// Checks if the opcode is a reserved frame.
457 ///
458 /// # Returns
459 ///
460 /// `true` if the opcode is `Reserved(_)`, otherwise `false`.
461 pub fn is_reserved_opcode(&self) -> bool {
462 self.opcode.is_reserved()
463 }
464}