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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
use bytes::{Buf, BytesMut};
use crate::{Storage, Parsing, base::{self, Header, MAX_HEADER_SIZE, OpCode}, extension::Extension};
use crate::data::{ByteSlice125, Data, Incoming};
use futures::{io::{ReadHalf, WriteHalf}, lock::BiLock, prelude::*};
use std::{fmt, io, str};
const MAX_MESSAGE_SIZE: usize = 256 * 1024 * 1024;
const MAX_FRAME_SIZE: usize = MAX_MESSAGE_SIZE;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Mode {
Client,
Server
}
impl Mode {
pub fn is_client(self) -> bool {
if let Mode::Client = self {
true
} else {
false
}
}
pub fn is_server(self) -> bool {
!self.is_client()
}
}
#[derive(Clone, Copy, Debug)]
struct Id(u32);
impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:08x}", self.0)
}
}
#[derive(Debug)]
pub struct Sender<T> {
id: Id,
mode: Mode,
codec: base::Codec,
writer: BiLock<WriteHalf<T>>,
mask_buffer: Vec<u8>,
extensions: BiLock<Vec<Box<dyn Extension + Send>>>,
has_extensions: bool
}
#[derive(Debug)]
pub struct Receiver<T> {
id: Id,
mode: Mode,
codec: base::Codec,
reader: ReadHalf<T>,
writer: BiLock<WriteHalf<T>>,
extensions: BiLock<Vec<Box<dyn Extension + Send>>>,
has_extensions: bool,
buffer: BytesMut,
ctrl_buffer: BytesMut,
max_message_size: usize,
is_closed: bool
}
#[derive(Debug)]
pub struct Builder<T> {
id: Id,
mode: Mode,
socket: T,
codec: base::Codec,
extensions: Vec<Box<dyn Extension + Send>>,
buffer: BytesMut,
max_message_size: usize
}
impl<T: AsyncRead + AsyncWrite + Unpin> Builder<T> {
pub fn new(socket: T, mode: Mode) -> Self {
let mut codec = base::Codec::default();
codec.set_max_data_size(MAX_FRAME_SIZE);
Builder {
id: Id(rand::random()),
mode,
socket,
codec,
extensions: Vec::new(),
buffer: BytesMut::new(),
max_message_size: MAX_MESSAGE_SIZE
}
}
pub fn set_buffer(&mut self, b: BytesMut) {
self.buffer = b
}
pub fn add_extensions<I>(&mut self, extensions: I)
where
I: IntoIterator<Item = Box<dyn Extension + Send>>
{
for e in extensions.into_iter().filter(|e| e.is_enabled()) {
log::debug!("{}: using extension: {}", self.id, e.name());
self.codec.add_reserved_bits(e.reserved_bits());
self.extensions.push(e)
}
}
pub fn set_max_message_size(&mut self, max: usize) {
self.max_message_size = max
}
pub fn set_max_frame_size(&mut self, max: usize) {
self.codec.set_max_data_size(max);
}
pub fn finish(self) -> (Sender<T>, Receiver<T>) {
let (rhlf, whlf) = self.socket.split();
let (wrt1, wrt2) = BiLock::new(whlf);
let has_extensions = !self.extensions.is_empty();
let (ext1, ext2) = BiLock::new(self.extensions);
let recv = Receiver {
id: self.id,
mode: self.mode,
reader: rhlf,
writer: wrt1,
codec: self.codec.clone(),
extensions: ext1,
has_extensions,
buffer: self.buffer,
ctrl_buffer: BytesMut::new(),
max_message_size: self.max_message_size,
is_closed: false
};
let send = Sender {
id: self.id,
mode: self.mode,
writer: wrt2,
mask_buffer: Vec::new(),
codec: self.codec,
extensions: ext2,
has_extensions
};
(send, recv)
}
}
impl<T: AsyncRead + AsyncWrite + Unpin> Receiver<T> {
pub async fn receive(&mut self, message: &mut Vec<u8>) -> Result<Incoming<'_>, Error> {
let mut first_fragment_opcode = None;
let mut length: usize = 0;
let message_len = message.len();
loop {
if self.is_closed {
log::debug!("{}: can not receive, connection is closed", self.id);
return Err(Error::Closed)
}
self.ctrl_buffer.clear();
let mut header = self.receive_header().await?;
log::trace!("{}: recv: {}", self.id, header);
if header.opcode().is_control() {
self.read_buffer(&header).await?;
self.ctrl_buffer = self.buffer.split_to(header.payload_len());
base::Codec::apply_mask(&header, &mut self.ctrl_buffer);
if header.opcode() == OpCode::Pong {
return Ok(Incoming::Pong(&self.ctrl_buffer[..]))
}
self.on_control(&header).await?;
continue
}
length = length.saturating_add(header.payload_len());
if length > self.max_message_size {
log::warn!("{}: accumulated message length exceeds maximum", self.id);
return Err(Error::MessageTooLarge { current: length, maximum: self.max_message_size })
}
{
let old_msg_len = message.len();
let bytes_to_read = {
let required = header.payload_len();
let buffered = self.buffer.len();
if buffered == 0 {
required
} else if required > buffered {
message.extend_from_slice(&self.buffer);
self.buffer.clear();
required - buffered
} else {
message.extend_from_slice(&self.buffer.split_to(required));
0
}
};
if bytes_to_read > 0 {
let n = message.len();
message.resize(n + bytes_to_read, 0u8);
self.reader.read_exact(&mut message[n ..]).await?
}
debug_assert_eq!(header.payload_len(), message.len() - old_msg_len);
base::Codec::apply_mask(&header, &mut message[old_msg_len ..]);
}
match (header.is_fin(), header.opcode()) {
(false, OpCode::Continue) => {
if first_fragment_opcode.is_none() {
log::debug!("{}: continue frame while not processing message fragments", self.id);
return Err(Error::UnexpectedOpCode(OpCode::Continue))
}
continue
}
(false, oc) => {
if first_fragment_opcode.is_some() {
log::debug!("{}: initial fragment while processing a fragmented message", self.id);
return Err(Error::UnexpectedOpCode(oc))
}
first_fragment_opcode = Some(oc);
self.decode_with_extensions(&mut header, message).await?;
continue
}
(true, OpCode::Continue) => {
if let Some(oc) = first_fragment_opcode.take() {
header.set_payload_len(message.len());
log::trace!("{}: last fragment: total length = {} bytes", self.id, message.len());
self.decode_with_extensions(&mut header, message).await?;
header.set_opcode(oc);
} else {
log::debug!("{}: last continue frame while not processing message fragments", self.id);
return Err(Error::UnexpectedOpCode(OpCode::Continue))
}
}
(true, oc) => {
if first_fragment_opcode.is_some() {
log::debug!("{}: regular message while processing fragmented message", self.id);
return Err(Error::UnexpectedOpCode(oc))
}
self.decode_with_extensions(&mut header, message).await?
}
}
let num_bytes = message.len() - message_len;
if header.opcode() == OpCode::Text {
return Ok(Incoming::Data(Data::Text(num_bytes)))
} else {
return Ok(Incoming::Data(Data::Binary(num_bytes)))
}
}
}
pub async fn receive_data(&mut self, message: &mut Vec<u8>) -> Result<Data, Error> {
loop {
if let Incoming::Data(d) = self.receive(message).await? {
return Ok(d)
}
}
}
async fn receive_header(&mut self) -> Result<Header, Error> {
loop {
match self.codec.decode_header(&self.buffer)? {
Parsing::Done { value: header, offset } => {
debug_assert!(offset <= MAX_HEADER_SIZE);
self.buffer.advance(offset);
return Ok(header)
}
Parsing::NeedMore(n) => {
crate::read(&mut self.reader, &mut self.buffer, n).await?
}
}
}
}
async fn read_buffer(&mut self, header: &Header) -> Result<(), Error> {
if header.payload_len() <= self.buffer.len() {
return Ok(())
}
let i = self.buffer.len();
let d = header.payload_len() - i;
self.buffer.resize(i + d, 0u8);
self.reader.read_exact(&mut self.buffer[i ..]).await?;
Ok(())
}
async fn on_control(&mut self, header: &Header) -> Result<(), Error> {
match header.opcode() {
OpCode::Ping => {
let mut answer = Header::new(OpCode::Pong);
let mut unused = Vec::new();
let mut data = Storage::Unique(&mut self.ctrl_buffer);
write(self.id, self.mode, &mut self.codec, &mut self.writer, &mut answer, &mut data, &mut unused).await?;
self.flush().await?;
Ok(())
}
OpCode::Pong => Ok(()),
OpCode::Close => {
self.is_closed = true;
let (mut header, code) = close_answer(&self.ctrl_buffer)?;
let mut unused = Vec::new();
if let Some(c) = code {
let mut data = c.to_be_bytes();
let mut data = Storage::Unique(&mut data);
write(self.id, self.mode, &mut self.codec, &mut self.writer, &mut header, &mut data, &mut unused).await?
} else {
let mut data = Storage::Unique(&mut []);
write(self.id, self.mode, &mut self.codec, &mut self.writer, &mut header, &mut data, &mut unused).await?
}
self.flush().await?;
self.writer.lock().await.close().await.or(Err(Error::Closed))
}
OpCode::Binary
| OpCode::Text
| OpCode::Continue
| OpCode::Reserved3
| OpCode::Reserved4
| OpCode::Reserved5
| OpCode::Reserved6
| OpCode::Reserved7
| OpCode::Reserved11
| OpCode::Reserved12
| OpCode::Reserved13
| OpCode::Reserved14
| OpCode::Reserved15 => Err(Error::UnexpectedOpCode(header.opcode()))
}
}
async fn decode_with_extensions(&mut self, header: &mut Header, message: &mut Vec<u8>) -> Result<(), Error> {
if !self.has_extensions {
return Ok(())
}
for e in self.extensions.lock().await.iter_mut() {
log::trace!("{}: decoding with extension: {}", self.id, e.name());
e.decode(header, message).map_err(Error::Extension)?
}
Ok(())
}
async fn flush(&mut self) -> Result<(), Error> {
log::trace!("{}: flushing connection", self.id);
if self.is_closed {
return Ok(())
}
self.writer.lock().await.flush().await.or(Err(Error::Closed))
}
}
impl<T: AsyncRead + AsyncWrite + Unpin> Sender<T> {
pub async fn send_text(&mut self, data: impl AsRef<str>) -> Result<(), Error> {
let mut header = Header::new(OpCode::Text);
self.send_frame(&mut header, &mut Storage::Shared(data.as_ref().as_bytes())).await
}
pub async fn send_binary(&mut self, data: impl AsRef<[u8]>) -> Result<(), Error> {
let mut header = Header::new(OpCode::Binary);
self.send_frame(&mut header, &mut Storage::Shared(data.as_ref())).await
}
pub async fn send_binary_mut(&mut self, mut data: impl AsMut<[u8]>) -> Result<(), Error> {
let mut header = Header::new(OpCode::Binary);
self.send_frame(&mut header, &mut Storage::Unique(data.as_mut())).await
}
pub async fn send_ping(&mut self, data: ByteSlice125<'_>) -> Result<(), Error> {
let mut header = Header::new(OpCode::Ping);
self.write(&mut header, &mut Storage::Shared(data.as_ref())).await
}
pub async fn send_pong(&mut self, data: ByteSlice125<'_>) -> Result<(), Error> {
let mut header = Header::new(OpCode::Pong);
self.write(&mut header, &mut Storage::Shared(data.as_ref())).await
}
pub async fn flush(&mut self) -> Result<(), Error> {
log::trace!("{}: flushing connection", self.id);
self.writer.lock().await.flush().await.or(Err(Error::Closed))
}
pub async fn close(&mut self) -> Result<(), Error> {
log::trace!("{}: closing connection", self.id);
let mut header = Header::new(OpCode::Close);
let code = 1000_u16.to_be_bytes();
self.write(&mut header, &mut Storage::Shared(&code[..])).await?;
self.flush().await?;
self.writer.lock().await.close().await.or(Err(Error::Closed))
}
async fn send_frame(&mut self, header: &mut Header, data: &mut Storage<'_>) -> Result<(), Error> {
if !self.has_extensions {
return self.write(header, data).await
}
for e in self.extensions.lock().await.iter_mut() {
log::trace!("{}: encoding with extension: {}", self.id, e.name());
e.encode(header, data).map_err(Error::Extension)?
}
self.write(header, data).await
}
async fn write(&mut self, header: &mut Header, data: &mut Storage<'_>) -> Result<(), Error> {
write(self.id, self.mode, &mut self.codec, &mut self.writer, header, data, &mut self.mask_buffer).await
}
}
async fn write<T: AsyncWrite + Unpin>
( id: Id
, mode: Mode
, codec: &mut base::Codec
, writer: &mut BiLock<WriteHalf<T>>
, header: &mut Header
, data: &mut Storage<'_>
, mask_buffer: &mut Vec<u8>
) -> Result<(), Error>
{
if mode.is_client() {
header.set_masked(true);
header.set_mask(rand::random());
}
header.set_payload_len(data.as_ref().len());
log::trace!("{}: send: {}", id, header);
let header_bytes = codec.encode_header(&header);
let mut w = writer.lock().await;
w.write_all(&header_bytes).await.or(Err(Error::Closed))?;
if !header.is_masked() {
return w.write_all(data.as_ref()).await.or(Err(Error::Closed))
}
match data {
Storage::Shared(slice) => {
mask_buffer.clear();
mask_buffer.extend_from_slice(slice);
base::Codec::apply_mask(header, mask_buffer);
w.write_all(mask_buffer).await.or(Err(Error::Closed))
}
Storage::Unique(slice) => {
base::Codec::apply_mask(header, slice);
w.write_all(slice).await.or(Err(Error::Closed))
}
Storage::Owned(ref mut bytes) => {
base::Codec::apply_mask(header, bytes);
w.write_all(bytes).await.or(Err(Error::Closed))
}
}
}
fn close_answer(data: &[u8]) -> Result<(Header, Option<u16>), Error> {
let answer = Header::new(OpCode::Close);
if data.len() < 2 {
return Ok((answer, None))
}
std::str::from_utf8(&data[2 ..])?;
let code = u16::from_be_bytes([data[0], data[1]]);
match code {
| 1000 ..= 1003
| 1007 ..= 1011
| 1015
| 3000 ..= 4999 => Ok((answer, Some(code))),
_ => Ok((answer, Some(1002)))
}
}
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
Io(io::Error),
Codec(base::Error),
Extension(crate::BoxedError),
UnexpectedOpCode(OpCode),
Utf8(str::Utf8Error),
MessageTooLarge { current: usize, maximum: usize },
Closed
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Io(e) =>
write!(f, "i/o error: {}", e),
Error::Codec(e) =>
write!(f, "codec error: {}", e),
Error::Extension(e) =>
write!(f, "extension error: {}", e),
Error::UnexpectedOpCode(c) =>
write!(f, "unexpected opcode: {}", c),
Error::Utf8(e) =>
write!(f, "utf-8 error: {}", e),
Error::MessageTooLarge { current, maximum } =>
write!(f, "message too large: len >= {}, maximum = {}", current, maximum),
Error::Closed =>
f.write_str("connection closed")
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io(e) => Some(e),
Error::Codec(e) => Some(e),
Error::Extension(e) => Some(&**e),
Error::Utf8(e) => Some(e),
Error::UnexpectedOpCode(_)
| Error::MessageTooLarge {..}
| Error::Closed
=> None
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Self {
if e.kind() == io::ErrorKind::UnexpectedEof {
Error::Closed
} else {
Error::Io(e)
}
}
}
impl From<str::Utf8Error> for Error {
fn from(e: str::Utf8Error) -> Self {
Error::Utf8(e)
}
}
impl From<base::Error> for Error {
fn from(e: base::Error) -> Self {
Error::Codec(e)
}
}