fx-torrent 0.10.3

FX Torrent is a feature rich Bittorrent protocol implementation written in rust supporting Linux, MacOS and Windows.
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
use crate::error::Result;
use crate::operation::TorrentOperationResult;
use crate::{
    File, InfoHash, Piece, PieceError, PieceIndex, TorrentContext, TorrentError, TorrentFileInfo,
    TorrentMetadataInfo, TorrentState,
};
use log::{trace, warn};
use std::time::Instant;

#[derive(Debug)]
pub struct CreatePiecesAndFilesOperation {
    initialized: bool,
    completed: bool,
}

impl CreatePiecesAndFilesOperation {
    pub fn new() -> Self {
        Self {
            initialized: false,
            completed: false,
        }
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    pub async fn execute(&mut self, torrent: &mut TorrentContext) -> TorrentOperationResult {
        self.initialize(torrent).await;

        // check if the pieces have already been created
        // if so, continue the chain
        if self.completed {
            return TorrentOperationResult::Continue;
        }

        // try to create the pieces and files
        if self.create_pieces(torrent).await {
            if self.create_files(&torrent).await {
                self.completed = true;
                self.update_state(torrent).await;
                return TorrentOperationResult::Continue;
            }
        }

        TorrentOperationResult::Stop
    }

    async fn initialize(&mut self, torrent: &TorrentContext) {
        if self.initialized {
            return;
        }

        self.completed = torrent.data_pool().num_of_pieces().await > 0;
        self.initialized = true;
    }

    /// Create the pieces information for the torrent.
    /// This operation can only be done when the metadata of the torrent is known.
    async fn create_pieces(&self, torrent: &mut TorrentContext) -> bool {
        torrent.update_state(TorrentState::Initializing);
        let start_time = Instant::now();
        match self.try_create_pieces(torrent).await {
            Ok(pieces) => {
                let elapsed = start_time.elapsed();
                trace!(
                    "Torrent {} created a total of {} pieces in {:.3}ms",
                    torrent,
                    pieces.len(),
                    elapsed.as_secs_f64() * 1000.0,
                );
                torrent.update_pieces(pieces).await;
                true
            }
            Err(e) => {
                warn!("Torrent {} failed to create torrent pieces, {}", torrent, e);
                false
            }
        }
    }

    /// Try to create the pieces of the torrent.
    /// This operation doesn't store the pieces results.
    ///
    /// # Returns
    ///
    /// Returns the pieces result for the torrent if available, else the error.
    async fn try_create_pieces(&self, context: &TorrentContext) -> Result<Vec<Piece>> {
        let info_hash = context.metadata().info_hash.clone();
        let metadata =
            context
                .metadata()
                .info
                .as_ref()
                .ok_or(PieceError::UnableToDeterminePieces(
                    "metadata is unavailable".to_string(),
                ))?;
        let num_pieces =
            context
                .metadata()
                .total_pieces()
                .ok_or(PieceError::UnableToDeterminePieces(
                    "metadata is unavailable".to_string(),
                ))?;

        let sha1_pieces = if info_hash.has_v1() {
            metadata.sha1_pieces()
        } else {
            Vec::new()
        };
        let sha256_pieces = if info_hash.has_v2() {
            metadata.sha256_pieces()
        } else {
            Vec::new()
        };
        let mut pieces = Vec::with_capacity(num_pieces);
        let total_file_size = metadata.len();
        let piece_length = metadata.piece_length as usize;
        let mut last_piece_length = total_file_size % piece_length;
        let mut offset = 0;

        if last_piece_length == 0 {
            last_piece_length = piece_length;
        }

        for piece_index in 0..num_pieces {
            let hash = if info_hash.has_v2() {
                InfoHash::try_from_bytes(sha256_pieces.get(piece_index).unwrap())?
            } else {
                InfoHash::try_from_bytes(sha1_pieces.get(piece_index).unwrap())?
            };
            let length = if piece_index != num_pieces - 1 {
                piece_length
            } else {
                last_piece_length
            };

            pieces.push(Piece::new(hash, piece_index as PieceIndex, offset, length));
            offset += length;
        }

        Ok(pieces)
    }

    /// Create the torrent files information.
    /// This can only be executed when the torrent metadata is known.
    async fn create_files(&self, torrent: &TorrentContext) -> bool {
        let start_time = Instant::now();
        match self.try_create_files(torrent).await {
            Ok(files) => {
                let total_files = files.len();
                let elapsed = start_time.elapsed();
                torrent.update_files(files).await;
                trace!(
                    "Torrent {} created a total of {} file(s) in {:.3}ms",
                    torrent,
                    total_files,
                    elapsed.as_secs_f64() * 1000.0
                );
                true
            }
            Err(e) => {
                warn!("Torrent {} failed to create files, {}", torrent, e);
                false
            }
        }
    }

    /// Try to create the file information of the torrent.
    /// This operation doesn't store the created files within this torrent.
    async fn try_create_files(&self, torrent: &TorrentContext) -> Result<Vec<File>> {
        let is_v2_metadata: bool = torrent.metadata().info_hash.has_v2();
        let metadata = torrent
            .metadata()
            .info
            .as_ref()
            .ok_or(TorrentError::InvalidMetadata(
                "metadata is missing".to_string(),
            ))?;

        let mut offset = 0usize;
        let mut files = vec![];

        for (index, file_info) in metadata.files().into_iter().enumerate() {
            let file_length = file_info.length as usize;

            files.push(Self::create_file(file_info, &metadata, index, offset));

            if is_v2_metadata {
                offset = (offset + metadata.piece_length as usize - 1)
                    / metadata.piece_length as usize
                    * metadata.piece_length as usize;
            } else {
                offset += file_length;
            }
        }

        Ok(files)
    }

    fn create_file(
        file_info: TorrentFileInfo,
        metadata: &TorrentMetadataInfo,
        index: usize,
        offset: usize,
    ) -> File {
        let file_length = file_info.length as usize;
        let piece_len = metadata.piece_length as usize;
        let torrent_path = metadata.path(&file_info);
        let file_piece_start = offset / piece_len;
        let file_piece_end = offset.saturating_add(file_length + 1) / piece_len;

        File {
            index,
            torrent_path,
            torrent_offset: offset,
            info: file_info,
            priority: Default::default(),
            pieces: file_piece_start..file_piece_end + 1, // as the range is exclusive, add 1 to the end range
        }
    }

    async fn update_state(&self, context: &mut TorrentContext) {
        let state = context.determine_state().await;
        context.update_state(state);
    }
}

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

    mod create_pieces {
        use super::*;

        #[tokio::test]
        async fn test_execute_create_pieces() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let temp_path = temp_dir.path().to_str().unwrap();
            let (mut context, _) = torrent_context!(
                "debian-udp.torrent",
                temp_path,
                TorrentFlags::none(),
                TorrentConfig::builder().build(),
                vec![]
            );
            let mut operation = CreatePiecesAndFilesOperation::new();

            let result = operation.execute(&mut context).await;

            assert_eq!(TorrentOperationResult::Continue, result);
            assert_eq!(
                15237,
                context.data_pool().num_of_pieces().await,
                "expected the pieces to have been created"
            );
        }

        #[tokio::test]
        async fn test_execute_pieces_already_exist() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let temp_path = temp_dir.path().to_str().unwrap();
            let (mut context, _) = torrent_context!(
                "debian-udp.torrent",
                temp_path,
                TorrentFlags::none(),
                TorrentConfig::builder().build(),
                vec![]
            );
            let info_hash = context.metadata().info_hash.clone();
            let mut operation = CreatePiecesAndFilesOperation::new();

            // insert the initial data within the pool
            context
                .update_pieces(vec![Piece::new(info_hash, 0, 0, 1024)])
                .await;
            context
                .update_files(vec![File {
                    index: 0,
                    torrent_path: Default::default(),
                    torrent_offset: 0,
                    info: TorrentFileInfo {
                        length: 0,
                        path: None,
                        path_utf8: None,
                        md5sum: None,
                        attr: None,
                        symlink_path: None,
                        sha1: None,
                    },
                    priority: Default::default(),
                    pieces: Default::default(),
                }])
                .await;

            // execute the operation
            let result = operation.execute(&mut context).await;

            assert_eq!(TorrentOperationResult::Continue, result);
            assert_eq!(
                1,
                context.data_pool().num_of_pieces().await,
                "expected the pieces to not have been updated"
            );
        }
    }

    mod create_files {
        use super::*;

        #[tokio::test]
        async fn test_execute() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let temp_path = temp_dir.path().to_str().unwrap();
            let (mut context, _) = torrent_context!(
                "debian-udp.torrent",
                temp_path,
                TorrentFlags::none(),
                TorrentConfig::builder().build(),
                vec![]
            );
            let mut create_pieces = CreatePiecesAndFilesOperation::new();
            let mut operation = CreatePiecesAndFilesOperation::new();

            let result = create_pieces.execute(&mut context).await;
            assert_eq!(
                TorrentOperationResult::Continue,
                result,
                "expected the pieces to have been created"
            );

            let result = operation.execute(&mut context).await;
            assert_eq!(
                TorrentOperationResult::Continue,
                result,
                "expected the operations chain to continue"
            );
            assert_eq!(
                1,
                context.total_files().await,
                "expected the files to have been created"
            );
        }

        #[tokio::test]
        async fn test_execute_no_metadata() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let temp_path = temp_dir.path().to_str().unwrap();
            let uri = "magnet:?xt=urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7&dn=debian-12.4.0-amd64-DVD-1.iso&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=udp%3A%2F%2Fopen.stealth.si%3A80%2Fannounce&tr=udp%3A%2F%2Ftracker.torrent.eu.org%3A451%2Fannounce&tr=udp%3A%2F%2Ftracker.bittor.pw%3A1337%2Fannounce&tr=udp%3A%2F%2Fpublic.popcorn-tracker.org%3A6969%2Fannounce&tr=udp%3A%2F%2Ftracker.dler.org%3A6969%2Fannounce&tr=udp%3A%2F%2Fexodus.desync.com%3A6969&tr=udp%3A%2F%2Fopen.demonii.com%3A1337%2Fannounce";
            let (mut context, _) = torrent_context!(
                uri,
                temp_path,
                TorrentFlags::none(),
                TorrentConfig::builder().build(),
                vec![]
            );
            let mut operation = CreatePiecesAndFilesOperation::new();

            let result = operation.execute(&mut context).await;

            assert_eq!(
                TorrentOperationResult::Stop,
                result,
                "expected the operations chain to stop"
            );
        }

        #[tokio::test]
        async fn test_try_create_files() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let temp_path = temp_dir.path().to_str().unwrap();
            let (mut context, _) = torrent_context!(
                "multifile.torrent",
                temp_path,
                TorrentFlags::none(),
                TorrentConfig::builder().build(),
                vec![]
            );
            let mut pieces_operation = CreatePiecesAndFilesOperation::new();
            let operation = CreatePiecesAndFilesOperation::new();

            // create the torrent pieces
            let result = pieces_operation.execute(&mut context).await;
            assert_eq!(
                TorrentOperationResult::Continue,
                result,
                "expected the pieces operation to have succeeded"
            );
            let pieces = context.data_pool().pieces().await;

            // create the torrent files
            let files = operation
                .try_create_files(&context)
                .await
                .expect("failed to create torrent files");

            let mut previous_end_piece = 0 as PieceIndex;
            for file in files {
                let start_piece = file.pieces.start;
                let end_piece = file.pieces.end;

                // the file should either start at the previous and piece or the next one
                assert!(
                    start_piece == previous_end_piece.saturating_sub(1usize)
                        || start_piece == previous_end_piece,
                    "expected the start piece {} to continue from previous end piece {}",
                    start_piece,
                    previous_end_piece
                );
                previous_end_piece = end_piece;
            }

            // check if the piece range from the last file ends at the last piece of the torrent
            assert_eq!(
                pieces[pieces.len() - 1].index,
                previous_end_piece.saturating_sub(1usize),
                "expected the last file to end on the last piece of the torrent"
            );
        }

        #[tokio::test]
        async fn test_create_file() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let temp_path = temp_dir.path().to_str().unwrap();
            let (context, _) = torrent_context!(
                "multifile.torrent",
                temp_path,
                TorrentFlags::none(),
                TorrentConfig::builder().build(),
                vec![]
            );
            let metadata_info = context
                .metadata()
                .info
                .as_ref()
                .expect("expected the metadata info to be present");
            let metadata_files = metadata_info.files();

            let result = CreatePiecesAndFilesOperation::create_file(
                metadata_files.get(1).unwrap().clone(),
                &metadata_info,
                1,
                3364128518,
            );

            assert_eq!(
                401, result.pieces.start,
                "expected the starting piece to match"
            );
            assert_eq!(725, result.pieces.end, "expected the ending piece to match");
        }
    }
}