http_type/websocket_frame/
impl.rs1use super::*;
2
3impl Default for WebSocketFrame {
8 #[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 {
26 #[inline(always)]
36 pub fn from_u8(opcode: u8) -> Self {
37 match opcode {
38 0x0 => Self::Continuation,
39 0x1 => Self::Text,
40 0x2 => Self::Binary,
41 0x8 => Self::Close,
42 0x9 => Self::Ping,
43 0xA => Self::Pong,
44 _ => Self::Reserved(opcode),
45 }
46 }
47
48 #[inline(always)]
54 pub fn to_u8(&self) -> u8 {
55 match self {
56 Self::Continuation => 0x0,
57 Self::Text => 0x1,
58 Self::Binary => 0x2,
59 Self::Close => 0x8,
60 Self::Ping => 0x9,
61 Self::Pong => 0xA,
62 Self::Reserved(code) => *code,
63 }
64 }
65
66 #[inline(always)]
72 pub fn is_control(&self) -> bool {
73 matches!(self, Self::Close | Self::Ping | Self::Pong)
74 }
75
76 #[inline(always)]
82 pub fn is_data(&self) -> bool {
83 matches!(self, Self::Text | Self::Binary | Self::Continuation)
84 }
85
86 #[inline(always)]
92 pub fn is_continuation(&self) -> bool {
93 matches!(self, Self::Continuation)
94 }
95
96 #[inline(always)]
102 pub fn is_text(&self) -> bool {
103 matches!(self, Self::Text)
104 }
105
106 #[inline(always)]
112 pub fn is_binary(&self) -> bool {
113 matches!(self, Self::Binary)
114 }
115
116 #[inline(always)]
122 pub fn is_close(&self) -> bool {
123 matches!(self, Self::Close)
124 }
125
126 #[inline(always)]
132 pub fn is_ping(&self) -> bool {
133 matches!(self, Self::Ping)
134 }
135
136 #[inline(always)]
142 pub fn is_pong(&self) -> bool {
143 matches!(self, Self::Pong)
144 }
145
146 #[inline(always)]
152 pub fn is_reserved(&self) -> bool {
153 matches!(self, Self::Reserved(_))
154 }
155}
156
157impl WebSocketFrame {
159 pub fn decode_ws_frame<D>(data: D) -> Option<(WebSocketFrame, usize)>
174 where
175 D: AsRef<[u8]>,
176 {
177 let data_ref: &[u8] = data.as_ref();
178 if data_ref.len() < 2 {
179 return None;
180 }
181 let mut index: usize = 0;
182 let fin: bool = (data_ref[index] & 0b1000_0000) != 0;
183 let opcode: WebSocketOpcode = WebSocketOpcode::from_u8(data_ref[index] & 0b0000_1111);
184 index += 1;
185 let mask: bool = (data_ref[index] & 0b1000_0000) != 0;
186 let mut payload_len: usize = (data_ref[index] & 0b0111_1111) as usize;
187 index += 1;
188 if payload_len == 126 {
189 if data_ref.len() < index + 2 {
190 return None;
191 }
192 payload_len = u16::from_be_bytes(data_ref[index..index + 2].try_into().ok()?) as usize;
193 index += 2;
194 } else if payload_len == 127 {
195 if data_ref.len() < index + 8 {
196 return None;
197 }
198 let raw_len: u64 = u64::from_be_bytes(data_ref[index..index + 8].try_into().ok()?);
199 if (raw_len >> 63) != 0 {
200 return None;
201 }
202 payload_len = usize::try_from(raw_len).ok()?;
203 index += 8;
204 }
205 let mask_key: Option<[u8; 4]> = if mask {
206 if data_ref.len() < index + 4 {
207 return None;
208 }
209 let key: [u8; 4] = data_ref[index..index + 4].try_into().ok()?;
210 index += 4;
211 Some(key)
212 } else {
213 None
214 };
215 let total_len: usize = index.checked_add(payload_len)?;
216 if data_ref.len() < total_len {
217 return None;
218 }
219 let mut payload: Vec<u8> = data_ref[index..total_len].to_vec();
220 if let Some(mask_key) = mask_key {
221 Self::apply_mask(&mut payload, mask_key);
222 }
223 let frame: WebSocketFrame = WebSocketFrame {
224 fin,
225 opcode,
226 mask,
227 payload_data: payload,
228 };
229 Some((frame, total_len))
230 }
231
232 pub(crate) fn decode_ws_frame_checked(
248 data_ref: &[u8],
249 max_payload_size: usize,
250 ) -> Result<Option<(WebSocketFrame, usize)>, RequestError> {
251 if data_ref.len() < 2 {
252 return Ok(None);
253 }
254 let first_byte: u8 = data_ref[0];
255 let second_byte: u8 = data_ref[1];
256 if (first_byte & 0b0111_0000) != 0 {
257 return Err(RequestError::WebSocketInvalidExtension(
258 HttpStatus::BadRequest,
259 ));
260 }
261 let fin: bool = (first_byte & 0b1000_0000) != 0;
262 let opcode: WebSocketOpcode = WebSocketOpcode::from_u8(first_byte & 0b0000_1111);
263 if opcode.is_reserved() {
264 return Err(RequestError::WebSocketOpcodeUnsupported(
265 HttpStatus::NotImplemented,
266 ));
267 }
268 let mask: bool = (second_byte & 0b1000_0000) != 0;
269 let len_code: u8 = second_byte & 0b0111_1111;
270 if opcode.is_control() && (!fin || len_code >= 126) {
271 return Err(RequestError::WebSocketPayloadCorrupted(
272 HttpStatus::BadRequest,
273 ));
274 }
275 let mut index: usize = 2;
276 let payload_len: usize = if len_code == 126 {
277 if data_ref.len() < index + 2 {
278 return Ok(None);
279 }
280 let raw_len: u16 = u16::from_be_bytes([data_ref[index], data_ref[index + 1]]);
281 if raw_len < 126 {
282 return Err(RequestError::WebSocketPayloadCorrupted(
283 HttpStatus::BadRequest,
284 ));
285 }
286 index += 2;
287 usize::from(raw_len)
288 } else if len_code == 127 {
289 if data_ref.len() < index + 8 {
290 return Ok(None);
291 }
292 let raw_len: u64 = u64::from_be_bytes([
293 data_ref[index],
294 data_ref[index + 1],
295 data_ref[index + 2],
296 data_ref[index + 3],
297 data_ref[index + 4],
298 data_ref[index + 5],
299 data_ref[index + 6],
300 data_ref[index + 7],
301 ]);
302 if (raw_len >> 63) != 0 || raw_len <= u64::from(u16::MAX) {
303 return Err(RequestError::WebSocketPayloadCorrupted(
304 HttpStatus::BadRequest,
305 ));
306 }
307 index += 8;
308 usize::try_from(raw_len)
309 .map_err(|_| RequestError::WebSocketFrameTooLarge(HttpStatus::PayloadTooLarge))?
310 } else {
311 usize::from(len_code)
312 };
313 if max_payload_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE && payload_len > max_payload_size
314 {
315 return Err(RequestError::WebSocketFrameTooLarge(
316 HttpStatus::PayloadTooLarge,
317 ));
318 }
319 let mask_key: Option<[u8; 4]> = if mask {
320 if data_ref.len() < index + 4 {
321 return Ok(None);
322 }
323 let key: [u8; 4] = [
324 data_ref[index],
325 data_ref[index + 1],
326 data_ref[index + 2],
327 data_ref[index + 3],
328 ];
329 index += 4;
330 Some(key)
331 } else {
332 None
333 };
334 let total_len: usize =
335 index
336 .checked_add(payload_len)
337 .ok_or(RequestError::WebSocketFrameTooLarge(
338 HttpStatus::PayloadTooLarge,
339 ))?;
340 if data_ref.len() < total_len {
341 return Ok(None);
342 }
343 let mut payload: Vec<u8> = data_ref[index..total_len].to_vec();
344 if let Some(mask_key) = mask_key {
345 Self::apply_mask(&mut payload, mask_key);
346 }
347 let frame: WebSocketFrame = WebSocketFrame {
348 fin,
349 opcode,
350 mask,
351 payload_data: payload,
352 };
353 Ok(Some((frame, total_len)))
354 }
355
356 #[inline(always)]
363 fn apply_mask(payload: &mut [u8], mask_key: [u8; 4]) {
364 let mask_u32: u32 = u32::from_ne_bytes(mask_key);
365 let (chunks, remainder): (&mut [[u8; 4]], &mut [u8]) = payload.as_chunks_mut::<4>();
366 for chunk in chunks {
367 let word: u32 = u32::from_ne_bytes(*chunk) ^ mask_u32;
368 *chunk = word.to_ne_bytes();
369 }
370 for (idx, byte) in remainder.iter_mut().enumerate() {
371 *byte ^= mask_key[idx];
372 }
373 }
374
375 pub fn create_frame_list<D>(data: D) -> Vec<Vec<u8>>
390 where
391 D: AsRef<[u8]>,
392 {
393 let data_ref: &[u8] = data.as_ref();
394 let total_len: usize = data_ref.len();
395 if total_len == 0 {
396 return vec![vec![0x81, 0x00]];
397 }
398 let mut offset: usize = 0;
399 let mut frames_list: Vec<Vec<u8>> = Vec::with_capacity((total_len / MAX_FRAME_SIZE) + 1);
400 let mut is_first_frame: bool = true;
401 let is_valid_utf8: bool = from_utf8(data_ref).is_ok();
402 let base_opcode: WebSocketOpcode = if is_valid_utf8 {
403 WebSocketOpcode::Text
404 } else {
405 WebSocketOpcode::Binary
406 };
407 while offset < total_len {
408 let remaining: usize = total_len - offset;
409 let mut frame_size: usize = remaining.min(MAX_FRAME_SIZE);
410 if is_valid_utf8 && frame_size < remaining {
411 while frame_size > 0 && (data_ref[offset + frame_size] & 0xC0) == 0x80 {
412 frame_size -= 1;
413 }
414 if frame_size == 0 {
415 frame_size = remaining.min(MAX_FRAME_SIZE);
416 }
417 }
418 let mut frame: Vec<u8> = Vec::with_capacity(frame_size + 10);
419 let opcode: WebSocketOpcode = if is_first_frame {
420 base_opcode
421 } else {
422 WebSocketOpcode::Continuation
423 };
424 let fin: u8 = if remaining > frame_size { 0x00 } else { 0x80 };
425 let opcode_byte: u8 = opcode.to_u8() & 0x0F;
426 frame.push(fin | opcode_byte);
427 if frame_size < 126 {
428 frame.push(frame_size as u8);
429 } else if frame_size <= usize::from(u16::MAX) {
430 frame.push(126);
431 frame.extend_from_slice(&(frame_size as u16).to_be_bytes());
432 } else {
433 frame.push(127);
434 frame.extend_from_slice(&(frame_size as u64).to_be_bytes());
435 }
436 let end: usize = offset + frame_size;
437 frame.extend_from_slice(&data_ref[offset..end]);
438 frames_list.push(frame);
439 offset = end;
440 is_first_frame = false;
441 }
442 frames_list
443 }
444
445 #[inline(always)]
452 fn sha1_compress_block(hash_state: &mut [u32; 5], block: &[u8; 64]) {
453 let mut message_schedule: [u32; 80] = [0u32; 80];
454 let (words, _): (&[[u8; 4]], &[u8]) = block.as_chunks::<4>();
455 for (chunk_index, block_chunk) in words.iter().enumerate() {
456 message_schedule[chunk_index] = u32::from_be_bytes(*block_chunk);
457 }
458 for schedule_index in 16..80 {
459 message_schedule[schedule_index] = (message_schedule[schedule_index - 3]
460 ^ message_schedule[schedule_index - 8]
461 ^ message_schedule[schedule_index - 14]
462 ^ message_schedule[schedule_index - 16])
463 .rotate_left(1);
464 }
465 let [mut hash_a, mut hash_b, mut hash_c, mut hash_d, mut hash_e] = *hash_state;
466 for &schedule_word in &message_schedule[0..20] {
467 let round_function: u32 = (hash_b & hash_c) | (!hash_b & hash_d);
468 let temp: u32 = hash_a
469 .rotate_left(5)
470 .wrapping_add(round_function)
471 .wrapping_add(hash_e)
472 .wrapping_add(0x5A82_7999)
473 .wrapping_add(schedule_word);
474 hash_e = hash_d;
475 hash_d = hash_c;
476 hash_c = hash_b.rotate_left(30);
477 hash_b = hash_a;
478 hash_a = temp;
479 }
480 for &schedule_word in &message_schedule[20..40] {
481 let round_function: u32 = hash_b ^ hash_c ^ hash_d;
482 let temp: u32 = hash_a
483 .rotate_left(5)
484 .wrapping_add(round_function)
485 .wrapping_add(hash_e)
486 .wrapping_add(0x6ED9_EBA1)
487 .wrapping_add(schedule_word);
488 hash_e = hash_d;
489 hash_d = hash_c;
490 hash_c = hash_b.rotate_left(30);
491 hash_b = hash_a;
492 hash_a = temp;
493 }
494 for &schedule_word in &message_schedule[40..60] {
495 let round_function: u32 = (hash_b & hash_c) | (hash_b & hash_d) | (hash_c & hash_d);
496 let temp: u32 = hash_a
497 .rotate_left(5)
498 .wrapping_add(round_function)
499 .wrapping_add(hash_e)
500 .wrapping_add(0x8F1B_BCDC)
501 .wrapping_add(schedule_word);
502 hash_e = hash_d;
503 hash_d = hash_c;
504 hash_c = hash_b.rotate_left(30);
505 hash_b = hash_a;
506 hash_a = temp;
507 }
508 for &schedule_word in &message_schedule[60..80] {
509 let round_function: u32 = hash_b ^ hash_c ^ hash_d;
510 let temp: u32 = hash_a
511 .rotate_left(5)
512 .wrapping_add(round_function)
513 .wrapping_add(hash_e)
514 .wrapping_add(0xCA62_C1D6)
515 .wrapping_add(schedule_word);
516 hash_e = hash_d;
517 hash_d = hash_c;
518 hash_c = hash_b.rotate_left(30);
519 hash_b = hash_a;
520 hash_a = temp;
521 }
522 hash_state[0] = hash_state[0].wrapping_add(hash_a);
523 hash_state[1] = hash_state[1].wrapping_add(hash_b);
524 hash_state[2] = hash_state[2].wrapping_add(hash_c);
525 hash_state[3] = hash_state[3].wrapping_add(hash_d);
526 hash_state[4] = hash_state[4].wrapping_add(hash_e);
527 }
528
529 pub fn sha1<D>(data: D) -> [u8; 20]
543 where
544 D: AsRef<[u8]>,
545 {
546 let data_ref: &[u8] = data.as_ref();
547 let mut hash_state: [u32; 5] = HASH_STATE;
548 let original_size_bits: u64 = (data_ref.len() as u64).wrapping_mul(8);
549 let (blocks, remainder): (&[[u8; 64]], &[u8]) = data_ref.as_chunks::<64>();
550 for block in blocks {
551 Self::sha1_compress_block(&mut hash_state, block);
552 }
553 let mut final_block: [u8; 64] = [0u8; 64];
554 let rem_len: usize = remainder.len();
555 final_block[..rem_len].copy_from_slice(remainder);
556 final_block[rem_len] = 0x80;
557 if rem_len >= 56 {
558 Self::sha1_compress_block(&mut hash_state, &final_block);
559 final_block = [0u8; 64];
560 }
561 final_block[56..64].copy_from_slice(&original_size_bits.to_be_bytes());
562 Self::sha1_compress_block(&mut hash_state, &final_block);
563 let mut result: [u8; 20] = [0u8; 20];
564 for (state_index, &state_value) in hash_state.iter().enumerate() {
565 result[state_index * 4..(state_index + 1) * 4]
566 .copy_from_slice(&state_value.to_be_bytes());
567 }
568 result
569 }
570
571 #[inline(always)]
582 pub fn try_generate_accept_key<K>(key: K) -> Option<String>
583 where
584 K: AsRef<str>,
585 {
586 let key_bytes: &[u8] = key.as_ref().as_bytes();
587 if key_bytes.len() != 24
588 || key_bytes[22] != WS_KEY_PAD_BYTE
589 || key_bytes[23] != WS_KEY_PAD_BYTE
590 {
591 return None;
592 }
593 if !key_bytes[..22].iter().all(|byte: &u8| {
594 byte.is_ascii_alphanumeric() || *byte == WS_KEY_PLUS_BYTE || *byte == WS_KEY_SLASH_BYTE
595 }) {
596 return None;
597 }
598 let mut data: [u8; 60] = [0u8; 60];
599 data[..24].copy_from_slice(key_bytes);
600 data[24..].copy_from_slice(GUID);
601 let hash: [u8; 20] = Self::sha1(data);
602 Self::try_base64_encode(hash)
603 }
604
605 #[inline(always)]
620 pub fn generate_accept_key<K>(key: K) -> String
621 where
622 K: AsRef<str>,
623 {
624 let key_bytes: &[u8] = key.as_ref().as_bytes();
625 if key_bytes.len() <= 24 {
626 let mut data: [u8; 60] = [0u8; 60];
627 let key_len: usize = key_bytes.len();
628 data[..key_len].copy_from_slice(key_bytes);
629 data[key_len..key_len + GUID.len()].copy_from_slice(GUID);
630 let hash: [u8; 20] = Self::sha1(&data[..key_len + GUID.len()]);
631 return Self::base64_encode(hash);
632 }
633 let mut data: Vec<u8> = Vec::with_capacity(key_bytes.len() + GUID.len());
634 data.extend_from_slice(key_bytes);
635 data.extend_from_slice(GUID);
636 let hash: [u8; 20] = Self::sha1(&data);
637 Self::base64_encode(hash)
638 }
639
640 pub fn try_base64_encode<D>(data: D) -> Option<String>
650 where
651 D: AsRef<[u8]>,
652 {
653 let data_ref: &[u8] = data.as_ref();
654 let out_len: usize = data_ref.len().div_ceil(3) * 4;
655 let mut encoded_data: Vec<u8> = Vec::with_capacity(out_len);
656 let (chunks, remainder): (&[[u8; 3]], &[u8]) = data_ref.as_chunks::<3>();
657 for &[b0, b1, b2] in chunks {
658 encoded_data.push(BASE64_CHARSET_TABLE[(b0 >> 2) as usize]);
659 encoded_data.push(BASE64_CHARSET_TABLE[(((b0 & 0b11) << 4) | (b1 >> 4)) as usize]);
660 encoded_data.push(BASE64_CHARSET_TABLE[(((b1 & 0b1111) << 2) | (b2 >> 6)) as usize]);
661 encoded_data.push(BASE64_CHARSET_TABLE[(b2 & 0b11_1111) as usize]);
662 }
663 let pad: u8 = EQUAL_BYTES[0];
664 match remainder {
665 [b0] => {
666 encoded_data.push(BASE64_CHARSET_TABLE[(*b0 >> 2) as usize]);
667 encoded_data.push(BASE64_CHARSET_TABLE[((*b0 & 0b11) << 4) as usize]);
668 encoded_data.push(pad);
669 encoded_data.push(pad);
670 }
671 [b0, b1] => {
672 encoded_data.push(BASE64_CHARSET_TABLE[(*b0 >> 2) as usize]);
673 encoded_data
674 .push(BASE64_CHARSET_TABLE[(((*b0 & 0b11) << 4) | (*b1 >> 4)) as usize]);
675 encoded_data.push(BASE64_CHARSET_TABLE[((*b1 & 0b1111) << 2) as usize]);
676 encoded_data.push(pad);
677 }
678 _ => {}
679 }
680 Some(unsafe { String::from_utf8_unchecked(encoded_data) })
682 }
683
684 #[inline(always)]
698 pub fn base64_encode<D>(data: D) -> String
699 where
700 D: AsRef<[u8]>,
701 {
702 Self::try_base64_encode(data).unwrap()
703 }
704
705 #[inline(always)]
711 pub fn is_continuation_opcode(&self) -> bool {
712 self.get_opcode().is_continuation()
713 }
714
715 #[inline(always)]
721 pub fn is_text_opcode(&self) -> bool {
722 self.get_opcode().is_text()
723 }
724
725 #[inline(always)]
731 pub fn is_binary_opcode(&self) -> bool {
732 self.get_opcode().is_binary()
733 }
734
735 #[inline(always)]
741 pub fn is_close_opcode(&self) -> bool {
742 self.get_opcode().is_close()
743 }
744
745 #[inline(always)]
751 pub fn is_ping_opcode(&self) -> bool {
752 self.get_opcode().is_ping()
753 }
754
755 #[inline(always)]
761 pub fn is_pong_opcode(&self) -> bool {
762 self.get_opcode().is_pong()
763 }
764
765 #[inline(always)]
771 pub fn is_reserved_opcode(&self) -> bool {
772 self.get_opcode().is_reserved()
773 }
774}