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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#![allow(clippy::unusual_byte_groupings)]
use crate::frame::*;
use crate::*;
pub mod client;
pub mod server;
pub const SERVER: bool = true;
pub const CLIENT: bool = false;
pub struct WebSocket<const SIDE: bool> {
pub stream: BufReader<TcpStream>,
pub on_event: Box<dyn FnMut(Event) -> Result<()> + Send + Sync>,
fin: bool,
len: usize,
}
impl<const SIDE: bool> WebSocket<SIDE> {
pub async fn send(&mut self, msg: impl Frame) -> Result<()> {
let mut bytes = vec![];
msg.encode::<SIDE>(&mut bytes);
self.stream.get_mut().write_all(&bytes).await
}
pub async fn close(mut self, code: CloseCode, reason: impl AsRef<[u8]>) -> Result<()> {
self.send(Close {
code: code as u16,
reason: reason.as_ref(),
})
.await
}
}
impl<const SIDE: bool> WebSocket<SIDE> {
async fn header(&mut self) -> Result<(bool, u8, usize)> {
loop {
let [b1, b2] = read_buf(&mut self.stream).await?;
let fin = b1 & 0b_1000_0000 != 0;
let rsv = b1 & 0b_111_0000;
let opcode = b1 & 0b_1111;
let len = (b2 & 0b_111_1111) as usize;
let is_masked = b2 & 0b_1000_0000 != 0;
if rsv != 0 {
return proto_err("Reserve bit MUST be `0`");
}
if SERVER == SIDE {
if !is_masked {
return proto_err("Expected masked frame");
}
} else if is_masked {
return proto_err("Expected unmasked frame");
}
if opcode >= 8 {
if !fin {
return proto_err("Control frame MUST NOT be fragmented");
}
if len > 125 {
return proto_err(
"Control frame MUST have a payload length of 125 bytes or less",
);
}
let mut msg = vec![0; len];
if SERVER == SIDE {
let mut mask = Mask::from(read_buf(&mut self.stream).await?);
self.stream.read_exact(&mut msg).await?;
msg.iter_mut()
.zip(&mut mask)
.for_each(|(byte, key)| *byte ^= key);
} else {
self.stream.read_exact(&mut msg).await?;
}
match opcode {
8 => {
let code = u16::from_be_bytes([msg[0], msg[1]]);
let reason = &msg[2..];
self.send(Close { code, reason }).await?;
return err(ErrorKind::NotConnected, "The connection was closed");
}
9 => {
(self.on_event)(Event::Ping(&msg))?;
self.send(Event::Pong(&msg)).await?;
}
10 => (self.on_event)(Event::Pong(&msg))?,
_ => return proto_err("Unknown opcode"),
}
} else {
if !fin && len == 0 {
return proto_err("Fragment length shouldn't be zero");
}
let len = match len {
126 => u16::from_be_bytes(read_buf(&mut self.stream).await?) as usize,
127 => u64::from_be_bytes(read_buf(&mut self.stream).await?) as usize,
len => len,
};
return Ok((fin, opcode, len));
}
}
}
async fn read_fragmented_header(&mut self) -> Result<()> {
let (fin, opcode, len) = self.header().await?;
if opcode != 0 {
return proto_err("Expected fragment frame");
}
self.fin = fin;
self.len = len;
Ok(())
}
async fn discard_old_data(&mut self) -> Result<()> {
loop {
if self.len > 0 {
let amt = read_bytes(&mut self.stream, self.len, |_| {}).await?;
debug_assert!(amt != 0);
self.len -= amt;
continue;
}
if self.fin {
return Ok(());
}
self.read_fragmented_header().await?;
if SERVER == SIDE {
self.len += 4;
}
}
}
#[inline]
async fn read_data_frame_header(&mut self) -> Result<DataType> {
self.discard_old_data().await?;
let (fin, opcode, len) = self.header().await?;
let data_type = match opcode {
1 => DataType::Text,
2 => DataType::Binary,
_ => return proto_err("Expected data frame"),
};
self.fin = fin;
self.len = len;
Ok(data_type)
}
}
macro_rules! cls_if_err {
[$ws:expr, $code:expr] => {
match $code {
Ok(val) => Ok(val),
Err(err) => {
$ws.stream.get_mut().shutdown().await?;
Err(err)
}
}
};
}
macro_rules! read_exect {
[$this:expr, $buf:expr, $code:expr] => {
loop {
if $buf.is_empty() { break }
match $this._read($buf).await? {
0 => match $buf.is_empty() {
true => break,
false => $code,
},
amt => $buf = &mut $buf[amt..],
}
}
};
}
macro_rules! default_impl_for_data {
() => {
impl Data<'_> {
#[inline]
pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
cls_if_err!(self.ws, {
if self.len() == 0 {
if self.ws.fin {
return Ok(0);
}
self._read_next_frag().await?;
}
self._read(buf).await
})
}
pub async fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
cls_if_err!(self.ws, {
Ok(read_exect!(self, buf, {
if self.fin() {
return err(ErrorKind::UnexpectedEof, "failed to fill whole buffer");
}
self._read_next_frag().await?;
}))
})
}
#[inline]
pub async fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
self.read_to_end_with_limit(buf, 8 * 1024 * 1024).await
}
pub async fn read_to_end_with_limit(
&mut self,
buf: &mut Vec<u8>,
limit: usize,
) -> Result<usize> {
cls_if_err!(self.ws, {
let mut amt = 0;
loop {
let additional = self.len();
amt += additional;
if amt > limit {
return err(ErrorKind::Other, "Data read limit exceeded");
}
unsafe {
buf.reserve(additional);
let len = buf.len();
let mut uninit = std::slice::from_raw_parts_mut(
buf.as_mut_ptr().add(len),
additional,
);
read_exect!(self, uninit, {
return err(
ErrorKind::UnexpectedEof,
"failed to fill whole buffer",
);
});
buf.set_len(len + additional);
}
debug_assert!(self.len() == 0);
if self.fin() {
break Ok(amt);
}
self._read_next_frag().await?;
}
})
}
}
impl Data<'_> {
#[inline]
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
self.ws.len
}
#[inline]
pub fn fin(&self) -> bool {
self.ws.fin
}
#[inline]
pub async fn send(&mut self, data: impl Frame) -> Result<()> {
self.ws.send(data).await
}
}
};
}
pub(self) use cls_if_err;
pub(self) use default_impl_for_data;
pub(self) use read_exect;