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
use std::borrow::Borrow;
use std::io::Cursor;
use std::marker::PhantomData;
use std::mem;
use bytes::BufMut;
use bytes::BytesMut;
use tokio_io::codec::Decoder;
use tokio_io::codec::Encoder;
use dataframe::DataFrame;
use message::OwnedMessage;
use result::WebSocketError;
use ws::dataframe::DataFrame as DataFrameTrait;
use ws::message::Message as MessageTrait;
use ws::util::header::read_header;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Context {
Server,
Client,
}
pub struct DataFrameCodec<D> {
is_server: bool,
frame_type: PhantomData<D>,
}
impl DataFrameCodec<DataFrame> {
pub fn default(context: Context) -> Self {
DataFrameCodec::new(context)
}
}
impl<D> DataFrameCodec<D> {
pub fn new(context: Context) -> DataFrameCodec<D> {
DataFrameCodec {
is_server: context == Context::Server,
frame_type: PhantomData,
}
}
}
impl<D> Decoder for DataFrameCodec<D> {
type Item = DataFrame;
type Error = WebSocketError;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let (header, bytes_read) = {
let mut reader = Cursor::new(src.as_ref());
let header = match read_header(&mut reader) {
Ok(head) => head,
Err(WebSocketError::NoDataAvailable) => return Ok(None),
Err(e) => return Err(e),
};
(header, reader.position())
};
if header.len + bytes_read > src.len() as u64 {
return Ok(None);
}
let _ = src.split_to(bytes_read as usize);
let body = src.split_to(header.len as usize).to_vec();
Ok(Some(DataFrame::read_dataframe_body(
header,
body,
self.is_server,
)?))
}
}
impl<D> Encoder for DataFrameCodec<D>
where
D: Borrow<DataFrameTrait>,
{
type Item = D;
type Error = WebSocketError;
fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
let masked = !self.is_server;
let frame_size = item.borrow().frame_size(masked);
if frame_size > dst.remaining_mut() {
dst.reserve(frame_size);
}
item.borrow().write_to(&mut dst.writer(), masked)
}
}
pub struct MessageCodec<M>
where
M: MessageTrait,
{
buffer: Vec<DataFrame>,
dataframe_codec: DataFrameCodec<DataFrame>,
message_type: PhantomData<fn(M)>,
}
impl MessageCodec<OwnedMessage> {
pub fn default(context: Context) -> Self {
Self::new(context)
}
}
impl<M> MessageCodec<M>
where
M: MessageTrait,
{
pub fn new(context: Context) -> MessageCodec<M> {
MessageCodec {
buffer: Vec::new(),
dataframe_codec: DataFrameCodec::new(context),
message_type: PhantomData,
}
}
}
impl<M> Decoder for MessageCodec<M>
where
M: MessageTrait,
{
type Item = OwnedMessage;
type Error = WebSocketError;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
while let Some(frame) = self.dataframe_codec.decode(src)? {
let is_first = self.buffer.is_empty();
let finished = frame.finished;
match frame.opcode as u8 {
0 if is_first => {
return Err(WebSocketError::ProtocolError(
"Unexpected continuation data frame opcode",
));
}
8...15 => {
return Ok(Some(OwnedMessage::from_dataframes(vec![frame])?));
}
1...7 if !is_first => {
return Err(WebSocketError::ProtocolError(
"Unexpected data frame opcode",
));
}
_ => {
self.buffer.push(frame);
}
};
if finished {
let buffer = mem::replace(&mut self.buffer, Vec::new());
return Ok(Some(OwnedMessage::from_dataframes(buffer)?));
}
}
Ok(None)
}
}
impl<M> Encoder for MessageCodec<M>
where
M: MessageTrait,
{
type Item = M;
type Error = WebSocketError;
fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
let masked = !self.dataframe_codec.is_server;
let frame_size = item.message_size(masked);
if frame_size > dst.remaining_mut() {
dst.reserve(frame_size);
}
item.serialize(&mut dst.writer(), masked)
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::{Future, Sink, Stream};
use message::CloseData;
use message::Message;
use std::io::Cursor;
use stream::ReadWritePair;
use tokio_core::reactor::Core;
use tokio_io::AsyncRead;
#[test]
fn owned_message_predicts_size() {
let messages = vec![
OwnedMessage::Text("nilbog".to_string()),
OwnedMessage::Binary(vec![1, 2, 3, 4]),
OwnedMessage::Binary(vec![42; 256]),
OwnedMessage::Binary(vec![42; 65535]),
OwnedMessage::Binary(vec![42; 65555]),
OwnedMessage::Ping("beep".to_string().into_bytes()),
OwnedMessage::Pong("boop".to_string().into_bytes()),
OwnedMessage::Close(None),
OwnedMessage::Close(Some(CloseData {
status_code: 64,
reason: "because".to_string(),
})),
];
for message in messages.into_iter() {
let masked_predicted = message.message_size(true);
let mut masked_buf = Vec::new();
message.serialize(&mut masked_buf, true).unwrap();
assert_eq!(masked_buf.len(), masked_predicted);
let unmasked_predicted = message.message_size(false);
let mut unmasked_buf = Vec::new();
message.serialize(&mut unmasked_buf, false).unwrap();
assert_eq!(unmasked_buf.len(), unmasked_predicted);
}
}
#[test]
fn cow_message_predicts_size() {
let messages = vec![
Message::binary(vec![1, 2, 3, 4]),
Message::binary(vec![42; 256]),
Message::binary(vec![42; 65535]),
Message::binary(vec![42; 65555]),
Message::text("nilbog".to_string()),
Message::ping("beep".to_string().into_bytes()),
Message::pong("boop".to_string().into_bytes()),
Message::close(),
Message::close_because(64, "because"),
];
for message in messages.iter() {
let masked_predicted = message.message_size(true);
let mut masked_buf = Vec::new();
message.serialize(&mut masked_buf, true).unwrap();
assert_eq!(masked_buf.len(), masked_predicted);
let unmasked_predicted = message.message_size(false);
let mut unmasked_buf = Vec::new();
message.serialize(&mut unmasked_buf, false).unwrap();
assert_eq!(unmasked_buf.len(), unmasked_predicted);
}
}
#[test]
fn message_codec_client_send_receive() {
let mut core = Core::new().unwrap();
let mut input = Vec::new();
Message::text("50 schmeckels")
.serialize(&mut input, false)
.unwrap();
let f = ReadWritePair(Cursor::new(input), Cursor::new(vec![]))
.framed(MessageCodec::new(Context::Client))
.into_future()
.map_err(|e| e.0)
.map(|(m, s)| {
assert_eq!(m, Some(OwnedMessage::Text("50 schmeckels".to_string())));
s
})
.and_then(|s| s.send(Message::text("ethan bradberry")))
.and_then(|s| {
let mut stream = s.into_parts().inner;
stream.1.set_position(0);
println!("buffer: {:?}", stream.1);
ReadWritePair(stream.1, stream.0)
.framed(MessageCodec::default(Context::Server))
.into_future()
.map_err(|e| e.0)
.map(|(message, _)| {
assert_eq!(message, Some(Message::text("ethan bradberry").into()))
})
});
core.run(f).unwrap();
}
#[test]
fn message_codec_server_send_receive() {
let mut core = Core::new().unwrap();
let mut input = Vec::new();
Message::text("50 schmeckels")
.serialize(&mut input, true)
.unwrap();
let f = ReadWritePair(Cursor::new(input.as_slice()), Cursor::new(vec![]))
.framed(MessageCodec::new(Context::Server))
.into_future()
.map_err(|e| e.0)
.map(|(m, s)| {
assert_eq!(m, Some(OwnedMessage::Text("50 schmeckels".to_string())));
s
})
.and_then(|s| s.send(Message::text("ethan bradberry")))
.map(|s| {
let mut written = vec![];
Message::text("ethan bradberry")
.serialize(&mut written, false)
.unwrap();
assert_eq!(written, s.into_parts().inner.1.into_inner());
});
core.run(f).unwrap();
}
}