1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
mod decode;
mod frame_head;
mod frame_payload;

pub use decode::*;
pub use frame_head::*;
pub use frame_payload::*;

use crate::message::WsMessageKind;
use futures::prelude::*;
use std::error::Error;
use std::io::Cursor;
use std::io::Write;
use strum::Display;

#[derive(Copy, Clone, Debug)]
pub enum WsFrame {
    Control(WsControlFrame),
    Data(WsDataFrame),
}

impl WsFrame {
    pub fn decode<T: AsyncRead + Unpin>(transport: T) -> FrameDecoder<T> {
        FrameDecoderState::new().restore(transport)
    }
    // Writes the frame `buffer` and returns the number of bytes written. Panics if
    // `buffer` is too small or payload size in frame head does not match provided payload.
    pub fn encode(frame_head: FrameHead, frame_payload: &[u8], buffer: &mut [u8]) -> usize {
        assert_eq!(frame_head.payload_len, frame_payload.len() as u64);
        let total = frame_head.len_bytes() + frame_payload.len();
        frame_head.encode(buffer);
        let payload_buffer = &mut buffer[frame_head.len_bytes()..total];
        payload_buffer.copy_from_slice(frame_payload);
        payload_mask(frame_head.mask, 0, payload_buffer);
        return total;
    }
    pub fn encode_vec(frame_head: FrameHead, frame_payload: &[u8]) -> Vec<u8> {
        let mut buffer = vec![0u8; frame_head.len_bytes() + frame_payload.len()];
        WsFrame::encode(frame_head, frame_payload, &mut *buffer);
        buffer
    }
}

#[derive(Copy, Clone, Debug)]
pub enum WsFrameKind {
    Control(WsControlFrameKind),
    Data(WsDataFrameKind),
}

impl WsFrameKind {
    pub fn max_payload_len(self) -> u64 {
        match self {
            WsFrameKind::Control(_) => 125,
            WsFrameKind::Data(_) => 1073741824,
        }
    }
    pub fn opcode(self) -> WsOpcode {
        match self {
            WsFrameKind::Control(frame) => frame.opcode(),
            WsFrameKind::Data(frame) => frame.opcode(),
        }
    }
    pub fn is_control(self) -> bool {
        match self {
            WsFrameKind::Control(_) => true,
            WsFrameKind::Data(_) => false,
        }
    }
}

#[derive(Display, Copy, Clone, Debug, Eq, PartialEq)]
pub enum WsDataFrameKind {
    Text,
    Binary,
    Continuation,
}

impl WsDataFrameKind {
    pub fn opcode(self) -> WsOpcode {
        match self {
            WsDataFrameKind::Text => WsOpcode::Text,
            WsDataFrameKind::Binary => WsOpcode::Binary,
            WsDataFrameKind::Continuation => WsOpcode::Continuation,
        }
    }
    pub fn message_kind(self) -> Option<WsMessageKind> {
        match self {
            WsDataFrameKind::Text => Some(WsMessageKind::Text),
            WsDataFrameKind::Binary => Some(WsMessageKind::Binary),
            WsDataFrameKind::Continuation => None,
        }
    }
    pub fn frame_kind(self) -> WsFrameKind {
        WsFrameKind::Data(self)
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum WsControlFrameKind {
    Ping,
    Pong,
    Close,
}

impl WsControlFrameKind {
    pub fn opcode(self) -> WsOpcode {
        match self {
            WsControlFrameKind::Ping => WsOpcode::Ping,
            WsControlFrameKind::Pong => WsOpcode::Pong,
            WsControlFrameKind::Close => WsOpcode::Close,
        }
    }
    pub fn frame_kind(self) -> WsFrameKind {
        WsFrameKind::Control(self)
    }
}

#[derive(Copy, Clone, Debug)]
pub struct WsDataFrame {
    pub(crate) kind: WsDataFrameKind,
    pub(crate) fin: bool,
    pub(crate) mask: [u8; 4],
    pub(crate) payload_len: u64,
}

impl WsDataFrame {
    pub fn payload_reader(&self) -> FramePayloadReaderState {
        FramePayloadReaderState::new(self.mask, self.payload_len)
    }
    pub fn kind(&self) -> WsDataFrameKind {
        self.kind
    }
    pub fn fin(&self) -> bool {
        self.fin
    }
    pub fn mask(&self) -> [u8; 4] {
        self.mask
    }
    pub fn payload_len(&self) -> u64 {
        self.payload_len
    }
}

#[derive(Copy, Clone, Debug)]
pub struct WsControlFrame {
    pub(crate) kind: WsControlFrameKind,
    pub(crate) payload: WsControlFramePayload,
}

impl WsControlFrame {
    pub fn new(kind: WsControlFrameKind, payload: &[u8]) -> Self {
        let payload = WsControlFramePayload::new(payload);
        Self { kind, payload }
    }
    pub fn payload(&self) -> &[u8] {
        &self.payload.data()
    }
    pub fn kind(&self) -> WsControlFrameKind {
        self.kind
    }
    pub fn head(&self, mask: [u8; 4]) -> FrameHead {
        FrameHead {
            fin: true,
            opcode: self.kind.opcode(),
            mask,
            payload_len: self.payload().len() as u64,
        }
    }
}

#[derive(Copy, Clone, Debug)]
pub(crate) struct WsControlFramePayload {
    pub(crate) len: u8,
    pub(crate) buffer: [u8; 125],
}

impl WsControlFramePayload {
    pub(crate) fn new(data: &[u8]) -> Self {
        let len = data.len().min(125);
        let payload = &data[0..len];
        let mut buffer = [0u8; 125];
        buffer[0..len].copy_from_slice(payload);
        Self {
            len: len as u8,
            buffer,
        }
    }
    pub(crate) fn data(&self) -> &[u8] {
        &self.buffer[0..self.len()]
    }
    pub(crate) fn len(&self) -> usize {
        self.len as usize
    }
    pub(crate) fn close_body(&self) -> Result<Option<(u16, &str)>, CloseBodyError> {
        match self.len() {
            0 => Ok(None),
            1 => Err(CloseBodyError::BodyTooShort),
            _ => {
                let data = self.data();
                let code = u16::from_be_bytes([data[0], data[1]]);
                match code {
                    0..=999 | 1004..=1006 | 1016..=2999 => Err(CloseBodyError::InvalidCode),
                    code => match std::str::from_utf8(&data[2..]) {
                        Ok(reason) => Ok(Some((code, reason))),
                        Err(_) => Err(CloseBodyError::InvalidUtf8),
                    },
                }
            }
        }
    }
}

#[derive(thiserror::Error, Debug)]
pub enum CloseBodyError {
    #[error("close frame body is too short")]
    BodyTooShort,
    #[error("invalid utf8 in close body reason")]
    InvalidUtf8,
    #[error("invalid close frame body code")]
    InvalidCode,
}

impl<E: Error> From<(u16, &E)> for WsControlFramePayload {
    fn from(err: (u16, &E)) -> Self {
        let mut buffer = [0u8; 125];
        buffer[0..2].copy_from_slice(&err.0.to_be_bytes());
        let mut cursor = Cursor::new(&mut buffer[2..]);
        write!(cursor, "{}", err.1).ok();
        let len = 2 + cursor.position() as u8;
        WsControlFramePayload { len, buffer }
    }
}