Debian Codegraph @

examples/decode_torrent.rs

raw symbols SCIP
1 //! A decoder for torrent files.
2 //!
3 //! This example will ...
4 //!
5 //! - read a torrent file,
6 //! - deserialize the bencode formatted information
7 //! - and print the result into stdout.
8 //!
9 //! *Attention*: Please consider to pipe the output into a file of your choice.
10 //!
11 //! # Run the Example
12 //!
13 //! ```
14 //! cargo run --example decode_torrent > parsing_output.txt
15 //! ```
16
17 use bendy::{
18 decoding::{Error, FromBencode, Object, ResultExt},
19 encoding::AsString,
20 };
21
22 static EXAMPLE_TORRENT: &[u8] =
23 include_bytes!("torrent_files/debian-9.4.0-amd64-netinst.iso.torrent");
24
25 /// Main struct containing all required information.
26 ///
27 /// Based on: [http://fileformats.wikia.com/wiki/Torrent_file].
28 ///
29 /// # Design Decision
30 ///
31 /// To keep the example simple we won't parse the integers fields
32 /// into a concrete number type as the bencode integer definition
33 /// is actually a `BigNum` and the content may not fit.
34 #[allow(dead_code)]
35 #[derive(Debug)]
36 struct MetaInfo {
37 pub announce: String,
38 pub info: Info,
39 pub comment: Option<String>, // not official element
40 pub creation_date: Option<u64>, // not official element
41 pub http_seeds: Option<Vec<String>>, // not official element
42 }
43
44 /// File related information (Single-file format)
45 #[allow(dead_code)]
46 #[derive(Debug)]
47 struct Info {
48 pub piece_length: String,
49 pub pieces: Vec<u8>,
50 pub name: String,
51 pub file_length: String,
52 }
53
54 impl FromBencode for MetaInfo {
55 // Try to parse with a `max_depth` of two.
56 //
57 // The required max depth of a data structure is calculated as follows:
58 //
59 // - Every potential nesting level encoded as bencode dictionary or list count as +1,
60 // - everything else is ignored.
61 //
62 // This typically means that we only need to count the amount of nested structs and container
63 // types. (Potentially ignoring lists of bytes as they are normally encoded as strings.)
64 //
65 // struct MetaInfo { // encoded as dictionary (+1)
66 // announce: String,
67 // info: Info { // encoded as dictionary (+1)
68 // piece_length: String,
69 // pieces: Vec<u8>, // encoded as string and therefore ignored
70 // name: String,
71 // file_length: String,
72 // },
73 // comment: Option<String>,
74 // creation_date: Option<u64>,
75 // http_seeds: Option<Vec<String>> // if available encoded as list but even then doesn't
76 // increase the limit over the deepest chain including
77 // info
78 // }
79 const EXPECTED_RECURSION_DEPTH: usize = Info::EXPECTED_RECURSION_DEPTH + 1;
80
81 /// Entry point for decoding a torrent. The dictionary is parsed for all
82 /// non-optional and optional fields. Missing optional fields are ignored
83 /// but any other missing fields result in stopping the decoding and in
84 /// spawning [`DecodingError::MissingField`].
85 fn decode_bencode_object(object: Object) -> Result<Self, Error>
86 where
87 Self: Sized,
88 {
89 let mut announce = None;
90 let mut comment = None;
91 let mut creation_date = None;
92 let mut http_seeds = None;
93 let mut info = None;
94
95 let mut dict_dec = object.try_into_dictionary()?;
96 while let Some(pair) = dict_dec.next_pair()? {
97 match pair {
98 (b"announce", value) => {
99 announce = String::decode_bencode_object(value)
100 .context("announce")
101 .map(Some)?;
102 },
103 (b"comment", value) => {
104 comment = String::decode_bencode_object(value)
105 .context("comment")
106 .map(Some)?;
107 },
108 (b"creation date", value) => {
109 creation_date = u64::decode_bencode_object(value)
110 .context("creation_date")
111 .map(Some)?;
112 },
113 (b"httpseeds", value) => {
114 http_seeds = Vec::decode_bencode_object(value)
115 .context("http_seeds")
116 .map(Some)?;
117 },
118 (b"info", value) => {
119 info = Info::decode_bencode_object(value)
120 .context("info")
121 .map(Some)?;
122 },
123 (unknown_field, _) => {
124 return Err(Error::unexpected_field(String::from_utf8_lossy(
125 unknown_field,
126 )));
127 },
128 }
129 }
130
131 let announce = announce.ok_or_else(|| Error::missing_field("announce"))?;
132 let info = info.ok_or_else(|| Error::missing_field("info"))?;
133
134 Ok(MetaInfo {
135 announce,
136 info,
137 comment,
138 creation_date,
139 http_seeds,
140 })
141 }
142 }
143
144 impl FromBencode for Info {
145 const EXPECTED_RECURSION_DEPTH: usize = 1;
146
147 /// Treats object as dictionary containing all fields for the info struct.
148 /// On success the dictionary is parsed for the fields of info which are
149 /// necessary for torrent. Any missing field will result in a missing field
150 /// error which will stop the decoding.
151 fn decode_bencode_object(object: Object) -> Result<Self, Error>
152 where
153 Self: Sized,
154 {
155 let mut file_length = None;
156 let mut name = None;
157 let mut piece_length = None;
158 let mut pieces = None;
159
160 let mut dict_dec = object.try_into_dictionary()?;
161 while let Some(pair) = dict_dec.next_pair()? {
162 match pair {
163 (b"length", value) => {
164 file_length = value
165 .try_into_integer()
166 .context("file.length")
167 .map(ToString::to_string)
168 .map(Some)?;
169 },
170 (b"name", value) => {
171 name = String::decode_bencode_object(value)
172 .context("name")
173 .map(Some)?;
174 },
175 (b"piece length", value) => {
176 piece_length = value
177 .try_into_integer()
178 .context("length")
179 .map(ToString::to_string)
180 .map(Some)?;
181 },
182 (b"pieces", value) => {
183 pieces = AsString::decode_bencode_object(value)
184 .context("pieces")
185 .map(|bytes| Some(bytes.0))?;
186 },
187 (unknown_field, _) => {
188 return Err(Error::unexpected_field(String::from_utf8_lossy(
189 unknown_field,
190 )));
191 },
192 }
193 }
194
195 let file_length = file_length.ok_or_else(|| Error::missing_field("file_length"))?;
196 let name = name.ok_or_else(|| Error::missing_field("name"))?;
197 let piece_length = piece_length.ok_or_else(|| Error::missing_field("piece_length"))?;
198 let pieces = pieces.ok_or_else(|| Error::missing_field("pieces"))?;
199
200 // Check that we discovered all necessary fields
201 Ok(Info {
202 file_length,
203 name,
204 piece_length,
205 pieces,
206 })
207 }
208 }
209
210 fn main() -> Result<(), Error> {
211 let torrent = MetaInfo::from_bencode(EXAMPLE_TORRENT)?;
212 println!("{:#?}", torrent);
213 Ok(())
214 }