mtorrent-core 0.4.0

Fundamentals for building asynchronous BitTorrent clients
Documentation
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
use super::seq::Seq;
use bytes::{Buf, BufMut};
use log::log_enabled;
use std::time::{Duration, UNIX_EPOCH};
use std::{cmp, fmt, io, mem};
use thiserror::Error;

#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeVer {
    Data = 0x01,
    Fin = 0x11,
    State = 0x21,
    Reset = 0x31,
    Syn = 0x41,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Header {
    type_ver: TypeVer,
    extension: u8,
    connection_id: u16,
    timestamp_us: u32,
    timestamp_diff_us: u32,
    wnd_size: u32,
    seq_nr: Seq,
    ack_nr: Seq,
}

impl Header {
    pub const MIN_SIZE: usize = 20;

    pub fn type_ver(&self) -> TypeVer {
        self.type_ver
    }

    pub fn seq_nr(&self) -> Seq {
        self.seq_nr
    }

    pub fn ack_nr(&self) -> Seq {
        self.ack_nr
    }

    /// # Errors
    /// Returns error if `dst` buffer is not big enough.
    pub fn encode_to(&self, dst: &mut impl BufMut) -> io::Result<()> {
        if dst.remaining_mut() < Self::MIN_SIZE {
            return Err(io::Error::new(io::ErrorKind::OutOfMemory, "dest buffer too short"));
        }
        dst.put_u8(self.type_ver as u8);
        dst.put_u8(self.extension);
        dst.put_u16(self.connection_id);
        dst.put_u32(self.timestamp_us);
        dst.put_u32(self.timestamp_diff_us);
        dst.put_u32(self.wnd_size);
        dst.put_u16(self.seq_nr.into());
        dst.put_u16(self.ack_nr.into());
        Ok(())
    }

    /// # Errors
    /// Returns error if `src` buffer is not big enough or contains unrecognized type or version.
    pub fn decode_from(src: &mut impl Buf) -> io::Result<Self> {
        if src.remaining() < Self::MIN_SIZE {
            return Err(io::Error::new(io::ErrorKind::WouldBlock, "src buffer too short"));
        }
        let type_ver = match src.get_u8() {
            i if i == TypeVer::Data as u8 => TypeVer::Data,
            i if i == TypeVer::Fin as u8 => TypeVer::Fin,
            i if i == TypeVer::State as u8 => TypeVer::State,
            i if i == TypeVer::Reset as u8 => TypeVer::Reset,
            i if i == TypeVer::Syn as u8 => TypeVer::Syn,
            i => {
                return Err(io::Error::new(
                    io::ErrorKind::Unsupported,
                    format!("unsupported type_ver ({i:#04x})"),
                ));
            }
        };
        let extension = src.get_u8();
        let connection_id = src.get_u16();
        let timestamp_us = src.get_u32();
        let timestamp_diff_us = src.get_u32();
        let wnd_size = src.get_u32();
        let seq_nr = src.get_u16().into();
        let ack_nr = src.get_u16().into();
        Ok(Header {
            type_ver,
            extension,
            connection_id,
            timestamp_us,
            timestamp_diff_us,
            wnd_size,
            seq_nr,
            ack_nr,
        })
    }
}

#[derive(Debug)]
pub struct Extension<'d> {
    #[cfg_attr(not(test), expect(dead_code))]
    pub ext_type: u8,
    #[cfg_attr(not(test), expect(dead_code))]
    pub data: &'d [u8],
}

pub struct ExtensionIter<'d> {
    ext_type: u8,
    rest: &'d [u8],
}

impl<'d> ExtensionIter<'d> {
    pub fn new(header: &Header, data: &'d [u8]) -> Self {
        Self {
            ext_type: header.extension,
            rest: data,
        }
    }

    pub fn into_rest(self) -> &'d [u8] {
        self.rest
    }

    fn parse_next_extension(&mut self) -> io::Result<Extension<'d>> {
        let next_ext_type = self.rest.try_get_u8()?;
        let this_ext_len = self.rest.try_get_u8()? as usize;
        let this_ext_data = self.rest.split_off(..this_ext_len).ok_or_else(|| {
            io::Error::new(io::ErrorKind::InvalidData, "buffer not long enough to parse extension")
        })?;
        Ok(Extension {
            ext_type: mem::replace(&mut self.ext_type, next_ext_type),
            data: this_ext_data,
        })
    }
}

impl<'d> Iterator for ExtensionIter<'d> {
    type Item = io::Result<Extension<'d>>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.ext_type == 0 {
            None
        } else {
            Some(self.parse_next_extension().inspect_err(|_e| {
                self.ext_type = 0; // return None next time to avoid inifinite loop
            }))
        }
    }
}

pub fn skip_extensions(buffer: &mut impl Buf, header: &Header) -> io::Result<()> {
    let mut iter = ExtensionIter::new(header, buffer.chunk());
    for parse_result in &mut iter {
        let ext = parse_result?;
        if log_enabled!(log::Level::Trace) {
            log::trace!("Parsed extension: {ext:?}");
        }
    }
    buffer.advance(buffer.chunk().len() - iter.into_rest().len());
    Ok(())
}

pub fn dbg_hdr_and_ext(header: &Header, payload: &[u8]) -> impl fmt::Debug {
    struct Dump<'h, 'b> {
        header: &'h Header,
        payload: &'b [u8],
    }

    impl<'h, 'b> fmt::Debug for Dump<'h, 'b> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_list()
                .entry(self.header)
                .entries(ExtensionIter::new(self.header, self.payload))
                .finish()
        }
    }

    Dump { header, payload }
}

pub struct ConnectionState {
    conn_id_recv: u16,
    conn_id_send: u16,
    last_local_seq: Seq,  // last tx seq_nr
    last_remote_seq: Seq, // last rx seq_nr
    remote_wnd: u32,
    local_wnd: u32,
    reply_micro: u32,
}

#[derive(Error, Debug)]
pub enum ValidationError {
    #[error("invalid packet ({0})")]
    Invalid(&'static str),
    #[error("duplicate packet")]
    Duplicate,
    #[error("seq jump (expected {expected_seq}, got {received_seq})")]
    OutOfOrder {
        expected_seq: Seq,
        received_seq: Seq,
    },
}

impl ConnectionState {
    const MAX_LOCAL_WINDOW: u32 = 1024 * 32;
    const MIN_LOCAL_WINDOW: u32 = 1024;
    const MIN_WINDOW: u32 = 150;

    pub fn new_outbound(conn_id_recv: u16) -> Self {
        let conn_id_send = conn_id_recv.wrapping_add(1);
        Self {
            conn_id_recv,
            conn_id_send,
            last_local_seq: Seq::ZERO,
            last_remote_seq: Seq::ZERO,
            remote_wnd: 0,
            local_wnd: Self::MAX_LOCAL_WINDOW,
            reply_micro: 0,
        }
    }

    pub fn new_inbound(syn: &Header) -> Self {
        debug_assert!(syn.type_ver == TypeVer::Syn);
        Self {
            conn_id_recv: syn.connection_id.wrapping_add(1),
            conn_id_send: syn.connection_id,
            last_local_seq: rand::random::<u16>().into(),
            last_remote_seq: syn.seq_nr,
            remote_wnd: syn.wnd_size,
            local_wnd: Self::MAX_LOCAL_WINDOW,
            reply_micro: 0,
        }
    }

    pub fn max_window_size(&self) -> usize {
        cmp::min(self.remote_wnd, self.local_wnd) as usize
    }

    pub fn shrink_local_window(&mut self) {
        self.local_wnd = cmp::max(self.local_wnd - 1024, Self::MIN_LOCAL_WINDOW);
    }

    pub fn grow_local_window(&mut self) {
        self.local_wnd = cmp::min(self.local_wnd + 1024, Self::MAX_LOCAL_WINDOW);
    }

    pub fn validate_header(&self, received_header: &Header) -> Result<(), ValidationError> {
        if received_header.connection_id != self.conn_id_recv {
            return Err(ValidationError::Invalid("unexpected connection ID"));
        }

        if received_header.ack_nr > self.last_local_seq {
            return Err(ValidationError::Invalid("invalid ack nr"));
        }

        match received_header.type_ver {
            TypeVer::Syn => {
                if received_header.seq_nr != Seq::ONE {
                    return Err(ValidationError::Invalid("SYN must have seq 1"));
                }
            }
            TypeVer::Data => {
                if received_header.seq_nr <= self.last_remote_seq {
                    return Err(ValidationError::Duplicate);
                }
            }
            TypeVer::State | TypeVer::Fin | TypeVer::Reset => {
                if received_header.seq_nr < self.last_remote_seq {
                    return Err(ValidationError::Duplicate);
                }
            }
        }

        if received_header.seq_nr > self.last_remote_seq + Seq::ONE {
            return Err(ValidationError::OutOfOrder {
                expected_seq: self.last_remote_seq + Seq::ONE,
                received_seq: received_header.seq_nr,
            });
        }

        Ok(())
    }

    pub fn process_header(&mut self, received_header: &Header) {
        self.remote_wnd = cmp::max(received_header.wnd_size, Self::MIN_WINDOW);
        if received_header.type_ver != TypeVer::State || self.last_remote_seq == Seq::ZERO {
            self.last_remote_seq = received_header.seq_nr;
        }
        if received_header.timestamp_us != 0 {
            self.reply_micro = current_timestamp_us() - received_header.timestamp_us;
        }
    }

    pub fn generate_header(&mut self, type_ver: TypeVer) -> Header {
        if type_ver != TypeVer::State {
            self.last_local_seq.increment();
        }
        Header {
            type_ver,
            extension: 0,
            connection_id: if type_ver == TypeVer::Syn {
                self.conn_id_recv
            } else {
                self.conn_id_send
            },
            timestamp_us: current_timestamp_us(),
            timestamp_diff_us: self.reply_micro,
            wnd_size: self.local_wnd,
            seq_nr: self.last_local_seq,
            ack_nr: self.last_remote_seq,
        }
    }
}

fn current_timestamp_us() -> u32 {
    #[cfg(test)]
    if let Some(timestamp) = FAKE_CURRENT_TIMESTAMP_US.get() {
        return timestamp;
    }

    UNIX_EPOCH.elapsed().unwrap_or(Duration::ZERO).as_micros() as u32 // truncating cast
}

#[cfg(test)]
thread_local! {
    pub(super) static FAKE_CURRENT_TIMESTAMP_US: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_encode_header() {
        let header = Header {
            type_ver: TypeVer::Syn,
            extension: 0,
            connection_id: 0x1234,
            timestamp_us: 0x56789abc,
            timestamp_diff_us: 0xdef01234,
            wnd_size: 0x456789ab,
            seq_nr: 0x9abc.into(),
            ack_nr: 0xdef0.into(),
        };

        let mut buf = Vec::with_capacity(Header::MIN_SIZE);
        header.encode_to(&mut buf).unwrap();

        let expected_bytes = [
            0x41, 0x00, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x45, 0x67,
            0x89, 0xab, 0x9a, 0xbc, 0xde, 0xf0,
        ];
        assert_eq!(&buf[..], &expected_bytes);
    }

    #[test]
    fn test_decode_header() {
        let bytes = [
            0x21, 0x00, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x45, 0x67,
            0x89, 0xab, 0x9a, 0xbc, 0xde, 0xf0,
        ];
        let mut buf = &bytes[..];
        let header = Header::decode_from(&mut buf).unwrap();

        assert_eq!(header.type_ver, TypeVer::State);
        assert_eq!(header.extension, 0);
        assert_eq!(header.connection_id, 0x1234);
        assert_eq!(header.timestamp_us, 0x56789abc);
        assert_eq!(header.timestamp_diff_us, 0xdef01234);
        assert_eq!(header.wnd_size, 0x456789ab);
        assert_eq!(header.seq_nr, 0x9abc.into());
        assert_eq!(header.ack_nr, 0xdef0.into());
    }

    #[test]
    fn test_encode_decode_header() {
        let original_header = Header {
            type_ver: TypeVer::Fin,
            extension: 1,
            connection_id: 0x4321,
            timestamp_us: 0xabcdef01,
            timestamp_diff_us: 0x23456789,
            wnd_size: 0x89abcdef,
            seq_nr: 0xfedc.into(),
            ack_nr: 0xba98.into(),
        };

        let mut buf = Vec::with_capacity(Header::MIN_SIZE);
        original_header.encode_to(&mut buf).unwrap();

        let mut buf_slice = &buf[..];
        let decoded_header = Header::decode_from(&mut buf_slice).unwrap();

        assert_eq!(original_header, decoded_header);
    }

    #[test]
    fn test_parse_extensions() {
        let data_with_ext = [0x02, 0x02, 0x03, 0x04, 0x00, 0x01, b'x'];
        let header = Header {
            type_ver: TypeVer::Data,
            extension: 1,
            connection_id: 0,
            timestamp_us: 0,
            timestamp_diff_us: 0,
            wnd_size: 0,
            seq_nr: 0.into(),
            ack_nr: 0.into(),
        };

        let mut iter = ExtensionIter::new(&header, data_with_ext.as_slice());
        let ext1 = iter.next().unwrap().unwrap();
        assert_eq!(ext1.ext_type, 1);
        assert_eq!(ext1.data, &[0x03, 0x04]);

        let ext2 = iter.next().unwrap().unwrap();
        assert_eq!(ext2.ext_type, 2);
        assert_eq!(ext2.data, b"x");

        assert!(iter.next().is_none());
        assert!(iter.rest.is_empty());
    }

    #[test]
    fn test_parse_malformed_extensions() {
        let data_with_ext = [0x02, 0x02, 0x03, 0x04, 0x00, 0x01];
        let header = Header {
            type_ver: TypeVer::Data,
            extension: 1,
            connection_id: 0,
            timestamp_us: 0,
            timestamp_diff_us: 0,
            wnd_size: 0,
            seq_nr: 0.into(),
            ack_nr: 0.into(),
        };

        let mut iter = ExtensionIter::new(&header, data_with_ext.as_slice());
        let ext1 = iter.next().unwrap().unwrap();
        assert_eq!(ext1.ext_type, 1);
        assert_eq!(ext1.data, &[0x03, 0x04]);

        let ext2_err = iter.next().unwrap().unwrap_err();
        assert_eq!(ext2_err.kind(), io::ErrorKind::InvalidData);

        assert!(iter.next().is_none());
        assert!(iter.rest.is_empty());
    }

    #[test]
    fn test_skip_extensions() {
        let mut data_with_ext = &[0x00, 0x02, 0x03, 0x04, b'm'][..]; // next_ext_type=0, len=2, data=[0x03, 0x04]
        let header = Header {
            type_ver: TypeVer::Data,
            extension: 1,
            connection_id: 0,
            timestamp_us: 0,
            timestamp_diff_us: 0,
            wnd_size: 0,
            seq_nr: 0.into(),
            ack_nr: 0.into(),
        };

        skip_extensions(&mut data_with_ext, &header).unwrap();
        assert_eq!(data_with_ext, &[b'm'][..]); // All extension bytes should be skipped
    }

    #[test]
    fn test_current_timestamp() {
        assert_ne!(current_timestamp_us(), 0);
    }
}