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<ResponseBody>
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<ResponseBody> =
400 Vec::with_capacity((total_len / MAX_FRAME_SIZE) + 1);
401 let mut is_first_frame: bool = true;
402 let is_valid_utf8: bool = from_utf8(data_ref).is_ok();
403 let base_opcode: WebSocketOpcode = if is_valid_utf8 {
404 WebSocketOpcode::Text
405 } else {
406 WebSocketOpcode::Binary
407 };
408 while offset < total_len {
409 let remaining: usize = total_len - offset;
410 let mut frame_size: usize = remaining.min(MAX_FRAME_SIZE);
411 if is_valid_utf8 && frame_size < remaining {
412 while frame_size > 0 && (data_ref[offset + frame_size] & 0xC0) == 0x80 {
413 frame_size -= 1;
414 }
415 if frame_size == 0 {
416 frame_size = remaining.min(MAX_FRAME_SIZE);
417 }
418 }
419 let mut frame: ResponseBody = Vec::with_capacity(frame_size + 10);
420 let opcode: WebSocketOpcode = if is_first_frame {
421 base_opcode
422 } else {
423 WebSocketOpcode::Continuation
424 };
425 let fin: u8 = if remaining > frame_size { 0x00 } else { 0x80 };
426 let opcode_byte: u8 = opcode.to_u8() & 0x0F;
427 frame.push(fin | opcode_byte);
428 if frame_size < 126 {
429 frame.push(frame_size as u8);
430 } else if frame_size <= usize::from(u16::MAX) {
431 frame.push(126);
432 frame.extend_from_slice(&(frame_size as u16).to_be_bytes());
433 } else {
434 frame.push(127);
435 frame.extend_from_slice(&(frame_size as u64).to_be_bytes());
436 }
437 let end: usize = offset + frame_size;
438 frame.extend_from_slice(&data_ref[offset..end]);
439 frames_list.push(frame);
440 offset = end;
441 is_first_frame = false;
442 }
443 frames_list
444 }
445
446 pub fn sha1<D>(data: D) -> [u8; 20]
459 where
460 D: AsRef<[u8]>,
461 {
462 let data_ref: &[u8] = data.as_ref();
463 let mut hash_state: [u32; 5] = HASH_STATE;
464 let mut padded_data: Vec<u8> = Vec::from(data_ref);
465 let original_size_bits: u64 = (padded_data.len() * 8) as u64;
466 padded_data.push(0x80);
467 while !(padded_data.len() + 8).is_multiple_of(64) {
468 padded_data.push(0);
469 }
470 padded_data.extend_from_slice(&original_size_bits.to_be_bytes());
471 for block in padded_data.as_chunks::<64>().0 {
472 let mut message_schedule: [u32; 80] = [0u32; 80];
473 for (chunk_index, block_chunk) in block.as_chunks::<4>().0.iter().enumerate().take(16) {
474 message_schedule[chunk_index] = u32::from_be_bytes([
475 block_chunk[0],
476 block_chunk[1],
477 block_chunk[2],
478 block_chunk[3],
479 ]);
480 }
481 for schedule_index in 16..80 {
482 message_schedule[schedule_index] = (message_schedule[schedule_index - 3]
483 ^ message_schedule[schedule_index - 8]
484 ^ message_schedule[schedule_index - 14]
485 ^ message_schedule[schedule_index - 16])
486 .rotate_left(1);
487 }
488 let [mut hash_a, mut hash_b, mut hash_c, mut hash_d, mut hash_e] = hash_state;
489 for (round_index, &schedule_word) in message_schedule.iter().enumerate() {
490 let (round_function, round_constant): (u32, u32) = match round_index {
491 0..=19 => ((hash_b & hash_c) | (!hash_b & hash_d), 0x5A827999),
492 20..=39 => (hash_b ^ hash_c ^ hash_d, 0x6ED9EBA1),
493 40..=59 => (
494 (hash_b & hash_c) | (hash_b & hash_d) | (hash_c & hash_d),
495 0x8F1BBCDC,
496 ),
497 _ => (hash_b ^ hash_c ^ hash_d, 0xCA62C1D6),
498 };
499 let temp: u32 = hash_a
500 .rotate_left(5)
501 .wrapping_add(round_function)
502 .wrapping_add(hash_e)
503 .wrapping_add(round_constant)
504 .wrapping_add(schedule_word);
505 hash_e = hash_d;
506 hash_d = hash_c;
507 hash_c = hash_b.rotate_left(30);
508 hash_b = hash_a;
509 hash_a = temp;
510 }
511 hash_state[0] = hash_state[0].wrapping_add(hash_a);
512 hash_state[1] = hash_state[1].wrapping_add(hash_b);
513 hash_state[2] = hash_state[2].wrapping_add(hash_c);
514 hash_state[3] = hash_state[3].wrapping_add(hash_d);
515 hash_state[4] = hash_state[4].wrapping_add(hash_e);
516 }
517 let mut result: [u8; 20] = [0u8; 20];
518 for (state_index, &state_value) in hash_state.iter().enumerate() {
519 result[state_index * 4..(state_index + 1) * 4]
520 .copy_from_slice(&state_value.to_be_bytes());
521 }
522 result
523 }
524
525 #[inline(always)]
536 pub fn try_generate_accept_key<K>(key: K) -> Option<String>
537 where
538 K: AsRef<str>,
539 {
540 let key_bytes: &[u8] = key.as_ref().as_bytes();
541 if key_bytes.len() != 24
542 || key_bytes[22] != b'='
543 || key_bytes[23] != b'='
544 || !key_bytes[..22]
545 .iter()
546 .all(|byte: &u8| byte.is_ascii_alphanumeric() || *byte == b'+' || *byte == b'/')
547 {
548 return None;
549 }
550 let mut data: [u8; 60] = [0u8; 60];
551 data[..24].copy_from_slice(key_bytes);
552 data[24..].copy_from_slice(GUID);
553 let hash: [u8; 20] = Self::sha1(data);
554 Self::try_base64_encode(hash)
555 }
556
557 #[inline(always)]
572 pub fn generate_accept_key<K>(key: K) -> String
573 where
574 K: AsRef<str>,
575 {
576 let key_bytes: &[u8] = key.as_ref().as_bytes();
577 if key_bytes.len() <= 24 {
578 let mut data: [u8; 60] = [0u8; 60];
579 let key_len: usize = key_bytes.len();
580 data[..key_len].copy_from_slice(key_bytes);
581 data[key_len..key_len + GUID.len()].copy_from_slice(GUID);
582 let hash: [u8; 20] = Self::sha1(&data[..key_len + GUID.len()]);
583 return Self::base64_encode(hash);
584 }
585 let mut data: Vec<u8> = Vec::with_capacity(key_bytes.len() + GUID.len());
586 data.extend_from_slice(key_bytes);
587 data.extend_from_slice(GUID);
588 let hash: [u8; 20] = Self::sha1(&data);
589 Self::base64_encode(hash)
590 }
591
592 pub fn try_base64_encode<D>(data: D) -> Option<String>
602 where
603 D: AsRef<[u8]>,
604 {
605 let data_ref: &[u8] = data.as_ref();
606 let mut encoded_data: Vec<u8> = Vec::with_capacity(data_ref.len().div_ceil(3) * 4);
607 for chunk in data_ref.chunks(3) {
608 let mut buffer: [u8; 3] = [0u8; 3];
609 buffer[..chunk.len()].copy_from_slice(chunk);
610 let indices: [u8; 4] = [
611 buffer[0] >> 2,
612 ((buffer[0] & 0b11) << 4) | (buffer[1] >> 4),
613 ((buffer[1] & 0b1111) << 2) | (buffer[2] >> 6),
614 buffer[2] & 0b111111,
615 ];
616 for &idx in &indices[..chunk.len() + 1] {
617 encoded_data.push(BASE64_CHARSET_TABLE[idx as usize]);
618 }
619 while !encoded_data.len().is_multiple_of(4) {
620 encoded_data.push(EQUAL_BYTES[0]);
621 }
622 }
623 String::from_utf8(encoded_data).ok()
624 }
625
626 #[inline(always)]
640 pub fn base64_encode<D>(data: D) -> String
641 where
642 D: AsRef<[u8]>,
643 {
644 Self::try_base64_encode(data).unwrap()
645 }
646
647 #[inline(always)]
653 pub fn is_continuation_opcode(&self) -> bool {
654 self.get_opcode().is_continuation()
655 }
656
657 #[inline(always)]
663 pub fn is_text_opcode(&self) -> bool {
664 self.get_opcode().is_text()
665 }
666
667 #[inline(always)]
673 pub fn is_binary_opcode(&self) -> bool {
674 self.get_opcode().is_binary()
675 }
676
677 #[inline(always)]
683 pub fn is_close_opcode(&self) -> bool {
684 self.get_opcode().is_close()
685 }
686
687 #[inline(always)]
693 pub fn is_ping_opcode(&self) -> bool {
694 self.get_opcode().is_ping()
695 }
696
697 #[inline(always)]
703 pub fn is_pong_opcode(&self) -> bool {
704 self.get_opcode().is_pong()
705 }
706
707 #[inline(always)]
713 pub fn is_reserved_opcode(&self) -> bool {
714 self.get_opcode().is_reserved()
715 }
716}