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
use asynchronous_codec::{Decoder, Encoder};
use bytes::{BufMut, Bytes, BytesMut};
use libp2p_core::Endpoint;
use std::{
fmt,
hash::{Hash, Hasher},
io, mem,
};
use unsigned_varint::{codec, encode};
pub(crate) const MAX_FRAME_SIZE: usize = 1024 * 1024;
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct LocalStreamId {
num: u64,
role: Endpoint,
}
impl fmt::Display for LocalStreamId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.role {
Endpoint::Dialer => write!(f, "({}/initiator)", self.num),
Endpoint::Listener => write!(f, "({}/receiver)", self.num),
}
}
}
impl Hash for LocalStreamId {
#![allow(clippy::derive_hash_xor_eq)]
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_u64(self.num);
}
}
impl nohash_hasher::IsEnabled for LocalStreamId {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct RemoteStreamId {
num: u64,
role: Endpoint,
}
impl LocalStreamId {
pub fn dialer(num: u64) -> Self {
Self {
num,
role: Endpoint::Dialer,
}
}
#[cfg(test)]
pub fn listener(num: u64) -> Self {
Self {
num,
role: Endpoint::Listener,
}
}
pub fn next(self) -> Self {
Self {
num: self
.num
.checked_add(1)
.expect("Mplex substream ID overflowed"),
..self
}
}
#[cfg(test)]
pub fn into_remote(self) -> RemoteStreamId {
RemoteStreamId {
num: self.num,
role: !self.role,
}
}
}
impl RemoteStreamId {
fn dialer(num: u64) -> Self {
Self {
num,
role: Endpoint::Dialer,
}
}
fn listener(num: u64) -> Self {
Self {
num,
role: Endpoint::Listener,
}
}
pub fn into_local(self) -> LocalStreamId {
LocalStreamId {
num: self.num,
role: !self.role,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Frame<T> {
Open { stream_id: T },
Data { stream_id: T, data: Bytes },
Close { stream_id: T },
Reset { stream_id: T },
}
impl Frame<RemoteStreamId> {
pub fn remote_id(&self) -> RemoteStreamId {
match *self {
Frame::Open { stream_id } => stream_id,
Frame::Data { stream_id, .. } => stream_id,
Frame::Close { stream_id, .. } => stream_id,
Frame::Reset { stream_id, .. } => stream_id,
}
}
}
pub struct Codec {
varint_decoder: codec::Uvi<u64>,
decoder_state: CodecDecodeState,
}
#[derive(Debug, Clone)]
enum CodecDecodeState {
Begin,
HasHeader(u64),
HasHeaderAndLen(u64, usize),
Poisoned,
}
impl Codec {
pub fn new() -> Codec {
Codec {
varint_decoder: codec::Uvi::default(),
decoder_state: CodecDecodeState::Begin,
}
}
}
impl Decoder for Codec {
type Item = Frame<RemoteStreamId>;
type Error = io::Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
loop {
match mem::replace(&mut self.decoder_state, CodecDecodeState::Poisoned) {
CodecDecodeState::Begin => match self.varint_decoder.decode(src)? {
Some(header) => {
self.decoder_state = CodecDecodeState::HasHeader(header);
}
None => {
self.decoder_state = CodecDecodeState::Begin;
return Ok(None);
}
},
CodecDecodeState::HasHeader(header) => match self.varint_decoder.decode(src)? {
Some(len) => {
if len as usize > MAX_FRAME_SIZE {
let msg = format!("Mplex frame length {} exceeds maximum", len);
return Err(io::Error::new(io::ErrorKind::InvalidData, msg));
}
self.decoder_state =
CodecDecodeState::HasHeaderAndLen(header, len as usize);
}
None => {
self.decoder_state = CodecDecodeState::HasHeader(header);
return Ok(None);
}
},
CodecDecodeState::HasHeaderAndLen(header, len) => {
if src.len() < len {
self.decoder_state = CodecDecodeState::HasHeaderAndLen(header, len);
let to_reserve = len - src.len();
src.reserve(to_reserve);
return Ok(None);
}
let buf = src.split_to(len);
let num = (header >> 3) as u64;
let out = match header & 7 {
0 => Frame::Open {
stream_id: RemoteStreamId::dialer(num),
},
1 => Frame::Data {
stream_id: RemoteStreamId::listener(num),
data: buf.freeze(),
},
2 => Frame::Data {
stream_id: RemoteStreamId::dialer(num),
data: buf.freeze(),
},
3 => Frame::Close {
stream_id: RemoteStreamId::listener(num),
},
4 => Frame::Close {
stream_id: RemoteStreamId::dialer(num),
},
5 => Frame::Reset {
stream_id: RemoteStreamId::listener(num),
},
6 => Frame::Reset {
stream_id: RemoteStreamId::dialer(num),
},
_ => {
let msg = format!("Invalid mplex header value 0x{:x}", header);
return Err(io::Error::new(io::ErrorKind::InvalidData, msg));
}
};
self.decoder_state = CodecDecodeState::Begin;
return Ok(Some(out));
}
CodecDecodeState::Poisoned => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Mplex codec poisoned",
));
}
}
}
}
}
impl Encoder for Codec {
type Item = Frame<LocalStreamId>;
type Error = io::Error;
fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
let (header, data) = match item {
Frame::Open { stream_id } => (stream_id.num << 3, Bytes::new()),
Frame::Data {
stream_id:
LocalStreamId {
num,
role: Endpoint::Listener,
},
data,
} => (num << 3 | 1, data),
Frame::Data {
stream_id:
LocalStreamId {
num,
role: Endpoint::Dialer,
},
data,
} => (num << 3 | 2, data),
Frame::Close {
stream_id:
LocalStreamId {
num,
role: Endpoint::Listener,
},
} => (num << 3 | 3, Bytes::new()),
Frame::Close {
stream_id:
LocalStreamId {
num,
role: Endpoint::Dialer,
},
} => (num << 3 | 4, Bytes::new()),
Frame::Reset {
stream_id:
LocalStreamId {
num,
role: Endpoint::Listener,
},
} => (num << 3 | 5, Bytes::new()),
Frame::Reset {
stream_id:
LocalStreamId {
num,
role: Endpoint::Dialer,
},
} => (num << 3 | 6, Bytes::new()),
};
let mut header_buf = encode::u64_buffer();
let header_bytes = encode::u64(header, &mut header_buf);
let data_len = data.as_ref().len();
let mut data_buf = encode::usize_buffer();
let data_len_bytes = encode::usize(data_len, &mut data_buf);
if data_len > MAX_FRAME_SIZE {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"data size exceed maximum",
));
}
dst.reserve(header_bytes.len() + data_len_bytes.len() + data_len);
dst.put(header_bytes);
dst.put(data_len_bytes);
dst.put(data);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encode_large_messages_fails() {
let mut enc = Codec::new();
let role = Endpoint::Dialer;
let data = Bytes::from(&[123u8; MAX_FRAME_SIZE + 1][..]);
let bad_msg = Frame::Data {
stream_id: LocalStreamId { num: 123, role },
data,
};
let mut out = BytesMut::new();
match enc.encode(bad_msg, &mut out) {
Err(e) => assert_eq!(e.to_string(), "data size exceed maximum"),
_ => panic!("Can't send a message bigger than MAX_FRAME_SIZE"),
}
let data = Bytes::from(&[123u8; MAX_FRAME_SIZE][..]);
let ok_msg = Frame::Data {
stream_id: LocalStreamId { num: 123, role },
data,
};
assert!(enc.encode(ok_msg, &mut out).is_ok());
}
#[test]
fn test_60bit_stream_id() {
let mut codec = Codec::new();
let id: u64 = u32::MAX as u64 + 1;
let stream_id = LocalStreamId {
num: id,
role: Endpoint::Dialer,
};
let original_frame = Frame::Open { stream_id };
let mut enc_frame = BytesMut::new();
codec
.encode(original_frame, &mut enc_frame)
.expect("Encoding to succeed.");
let dec_string_id = codec
.decode(&mut enc_frame)
.expect("Decoding to succeed.")
.map(|f| f.remote_id())
.unwrap();
assert_eq!(dec_string_id.num, stream_id.num);
}
}