1// Copyright (c) 2017 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use crate::date::DateTime;
8use crate::util::error::Error;
9use crate::hashes::Hash;
10use crate::jingle::{ContentId, Creator};
11use crate::ns;
12use minidom::{Element, Node};
13use std::collections::BTreeMap;
14use std::str::FromStr;
15use std::convert::TryFrom;
16
17generate_element!(
18 /// Represents a range in a file.
19 #[derive(PartialEq, Default)]
20 Range, "range", JINGLE_FT,
21 attributes: [
22 /// The offset in bytes from the beginning of the file.
23 offset: Default<u64> = "offset",
24
25 /// The length in bytes of the range, or None to be the entire
26 /// remaining of the file.
27 length: Option<u64> = "length"
28 ],
29 children: [
30 /// List of hashes for this range.
31 hashes: Vec<Hash> = ("hash", HASHES) => Hash
32 ]
33);
34
35impl Range {
36 /// Creates a new range.
37 pub fn new() -> Range {
38 Default::default()
39 }
40}
41
42type Lang = String;
43
44generate_id!(
45 /// Wrapper for a file description.
46 Desc
47);
48
49/// Represents a file to be transferred.
50#[derive(Debug, Clone, Default)]
51pub struct File {
52 /// The date of last modification of this file.
53 pub date: Option<DateTime>,
54
55 /// The MIME type of this file.
56 pub media_type: Option<String>,
57
58 /// The name of this file.
59 pub name: Option<String>,
60
61 /// The description of this file, possibly localised.
62 pub descs: BTreeMap<Lang, Desc>,
63
64 /// The size of this file, in bytes.
65 pub size: Option<u64>,
66
67 /// Used to request only a part of this file.
68 pub range: Option<Range>,
69
70 /// A list of hashes matching this entire file.
71 pub hashes: Vec<Hash>,
72}
73
74impl File {
75 /// Creates a new file descriptor.
76 pub fn new() -> File {
77 File::default()
78 }
79
80 /// Sets the date of last modification on this file.
81 pub fn with_date(mut self, date: DateTime) -> File {
82 self.date = Some(date);
83 self
84 }
85
86 /// Sets the date of last modification on this file from an ISO-8601
87 /// string.
88 pub fn with_date_str(mut self, date: &str) -> Result<File, Error> {
89 self.date = Some(DateTime::from_str(date)?);
90 Ok(self)
91 }
92
93 /// Sets the MIME type of this file.
94 pub fn with_media_type(mut self, media_type: String) -> File {
95 self.media_type = Some(media_type);
96 self
97 }
98
99 /// Sets the name of this file.
100 pub fn with_name(mut self, name: String) -> File {
101 self.name = Some(name);
102 self
103 }
104
105 /// Sets a description for this file.
106 pub fn add_desc(mut self, lang: &str, desc: Desc) -> File {
107 self.descs.insert(Lang::from(lang), desc);
108 self
109 }
110
111 /// Sets the file size of this file, in bytes.
112 pub fn with_size(mut self, size: u64) -> File {
113 self.size = Some(size);
114 self
115 }
116
117 /// Request only a range of this file.
118 pub fn with_range(mut self, range: Range) -> File {
119 self.range = Some(range);
120 self
121 }
122
123 /// Add a hash on this file.
124 pub fn add_hash(mut self, hash: Hash) -> File {
125 self.hashes.push(hash);
126 self
127 }
128}
129
130impl TryFrom<Element> for File {
131 type Error = Error;
132
133 fn try_from(elem: Element) -> Result<File, Error> {
134 check_self!(elem, "file", JINGLE_FT);
135 check_no_attributes!(elem, "file");
136
137 let mut file = File {
138 date: None,
139 media_type: None,
140 name: None,
141 descs: BTreeMap::new(),
142 size: None,
143 range: None,
144 hashes: vec![],
145 };
146
147 for child in elem.children() {
148 if child.is("date", ns::JINGLE_FT) {
149 if file.date.is_some() {
150 return Err(Error::ParseError("File must not have more than one date."));
151 }
152 file.date = Some(child.text().parse()?);
153 } else if child.is("media-type", ns::JINGLE_FT) {
154 if file.media_type.is_some() {
155 return Err(Error::ParseError(
156 "File must not have more than one media-type.",
157 ));
158 }
159 file.media_type = Some(child.text());
160 } else if child.is("name", ns::JINGLE_FT) {
161 if file.name.is_some() {
162 return Err(Error::ParseError("File must not have more than one name."));
163 }
164 file.name = Some(child.text());
165 } else if child.is("desc", ns::JINGLE_FT) {
166 let lang = get_attr!(child, "xml:lang", Default);
167 let desc = Desc(child.text());
168 if file.descs.insert(lang, desc).is_some() {
169 return Err(Error::ParseError(
170 "Desc element present twice for the same xml:lang.",
171 ));
172 }
173 } else if child.is("size", ns::JINGLE_FT) {
174 if file.size.is_some() {
175 return Err(Error::ParseError("File must not have more than one size."));
176 }
177 file.size = Some(child.text().parse()?);
178 } else if child.is("range", ns::JINGLE_FT) {
179 if file.range.is_some() {
180 return Err(Error::ParseError("File must not have more than one range."));
181 }
182 file.range = Some(Range::try_from(child.clone())?);
183 } else if child.is("hash", ns::HASHES) {
184 file.hashes.push(Hash::try_from(child.clone())?);
185 } else {
186 return Err(Error::ParseError("Unknown element in JingleFT file."));
187 }
188 }
189
190 Ok(file)
191 }
192}
193
194impl From<File> for Element {
195 fn from(file: File) -> Element {
196 Element::builder("file")
197 .ns(ns::JINGLE_FT)
198 .append_all(file.date.map(|date|
199 Element::builder("date")
200 .append(date)))
201 .append_all(file.media_type.map(|media_type|
202 Element::builder("media-type")
203 .append(media_type)))
204 .append_all(file.name.map(|name|
205 Element::builder("name")
206 .append(name)))
207 .append_all(file.descs.into_iter().map(|(lang, desc)|
208 Element::builder("desc")
209 .attr("xml:lang", lang)
210 .append(desc.0)))
211 .append_all(file.size.map(|size|
212 Element::builder("size")
213 .append(format!("{}", size))))
214 .append_all(file.range)
215 .append_all(file.hashes)
216 .build()
217 }
218}
219
220/// A wrapper element for a file.
221#[derive(Debug, Clone)]
222pub struct Description {
223 /// The actual file descriptor.
224 pub file: File,
225}
226
227impl TryFrom<Element> for Description {
228 type Error = Error;
229
230 fn try_from(elem: Element) -> Result<Description, Error> {
231 check_self!(elem, "description", JINGLE_FT, "JingleFT description");
232 check_no_attributes!(elem, "JingleFT description");
233 let mut file = None;
234 for child in elem.children() {
235 if file.is_some() {
236 return Err(Error::ParseError(
237 "JingleFT description element must have exactly one child.",
238 ));
239 }
240 file = Some(File::try_from(child.clone())?);
241 }
242 if file.is_none() {
243 return Err(Error::ParseError(
244 "JingleFT description element must have exactly one child.",
245 ));
246 }
247 Ok(Description {
248 file: file.unwrap(),
249 })
250 }
251}
252
253impl From<Description> for Element {
254 fn from(description: Description) -> Element {
255 Element::builder("description")
256 .ns(ns::JINGLE_FT)
257 .append(Node::Element(description.file.into()))
258 .build()
259 }
260}
261
262/// A checksum for checking that the file has been transferred correctly.
263#[derive(Debug, Clone)]
264pub struct Checksum {
265 /// The identifier of the file transfer content.
266 pub name: ContentId,
267
268 /// The creator of this file transfer.
269 pub creator: Creator,
270
271 /// The file being checksummed.
272 pub file: File,
273}
274
275impl TryFrom<Element> for Checksum {
276 type Error = Error;
277
278 fn try_from(elem: Element) -> Result<Checksum, Error> {
279 check_self!(elem, "checksum", JINGLE_FT);
280 check_no_unknown_attributes!(elem, "checksum", ["name", "creator"]);
281 let mut file = None;
282 for child in elem.children() {
283 if file.is_some() {
284 return Err(Error::ParseError(
285 "JingleFT checksum element must have exactly one child.",
286 ));
287 }
288 file = Some(File::try_from(child.clone())?);
289 }
290 if file.is_none() {
291 return Err(Error::ParseError(
292 "JingleFT checksum element must have exactly one child.",
293 ));
294 }
295 Ok(Checksum {
296 name: get_attr!(elem, "name", Required),
297 creator: get_attr!(elem, "creator", Required),
298 file: file.unwrap(),
299 })
300 }
301}
302
303impl From<Checksum> for Element {
304 fn from(checksum: Checksum) -> Element {
305 Element::builder("checksum")
306 .ns(ns::JINGLE_FT)
307 .attr("name", checksum.name)
308 .attr("creator", checksum.creator)
309 .append(Node::Element(checksum.file.into()))
310 .build()
311 }
312}
313
314generate_element!(
315 /// A notice that the file transfer has been completed.
316 Received, "received", JINGLE_FT,
317 attributes: [
318 /// The content identifier of this Jingle session.
319 name: Required<ContentId> = "name",
320
321 /// The creator of this file transfer.
322 creator: Required<Creator> = "creator",
323 ]
324);
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329 use crate::hashes::Algo;
330
331 #[cfg(target_pointer_width = "32")]
332 #[test]
333 fn test_size() {
334 assert_size!(Range, 40);
335 assert_size!(File, 128);
336 assert_size!(Description, 128);
337 assert_size!(Checksum, 144);
338 assert_size!(Received, 16);
339 }
340
341 #[cfg(target_pointer_width = "64")]
342 #[test]
343 fn test_size() {
344 assert_size!(Range, 48);
345 assert_size!(File, 184);
346 assert_size!(Description, 184);
347 assert_size!(Checksum, 216);
348 assert_size!(Received, 32);
349 }
350
351 #[test]
352 fn test_description() {
353 let elem: Element = r#"
354<description xmlns='urn:xmpp:jingle:apps:file-transfer:5'>
355 <file>
356 <media-type>text/plain</media-type>
357 <name>test.txt</name>
358 <date>2015-07-26T21:46:00+01:00</date>
359 <size>6144</size>
360 <hash xmlns='urn:xmpp:hashes:2'
361 algo='sha-1'>w0mcJylzCn+AfvuGdqkty2+KP48=</hash>
362 </file>
363</description>
364"#
365 .parse()
366 .unwrap();
367 let desc = Description::try_from(elem).unwrap();
368 assert_eq!(desc.file.media_type, Some(String::from("text/plain")));
369 assert_eq!(desc.file.name, Some(String::from("test.txt")));
370 assert_eq!(desc.file.descs, BTreeMap::new());
371 assert_eq!(
372 desc.file.date,
373 DateTime::from_str("2015-07-26T21:46:00+01:00").ok()
374 );
375 assert_eq!(desc.file.size, Some(6144u64));
376 assert_eq!(desc.file.range, None);
377 assert_eq!(desc.file.hashes[0].algo, Algo::Sha_1);
378 assert_eq!(
379 desc.file.hashes[0].hash,
380 base64::decode("w0mcJylzCn+AfvuGdqkty2+KP48=").unwrap()
381 );
382 }
383
384 #[test]
385 fn test_request() {
386 let elem: Element = r#"
387<description xmlns='urn:xmpp:jingle:apps:file-transfer:5'>
388 <file>
389 <hash xmlns='urn:xmpp:hashes:2'
390 algo='sha-1'>w0mcJylzCn+AfvuGdqkty2+KP48=</hash>
391 </file>
392</description>
393"#
394 .parse()
395 .unwrap();
396 let desc = Description::try_from(elem).unwrap();
397 assert_eq!(desc.file.media_type, None);
398 assert_eq!(desc.file.name, None);
399 assert_eq!(desc.file.descs, BTreeMap::new());
400 assert_eq!(desc.file.date, None);
401 assert_eq!(desc.file.size, None);
402 assert_eq!(desc.file.range, None);
403 assert_eq!(desc.file.hashes[0].algo, Algo::Sha_1);
404 assert_eq!(
405 desc.file.hashes[0].hash,
406 base64::decode("w0mcJylzCn+AfvuGdqkty2+KP48=").unwrap()
407 );
408 }
409
410 #[test]
411 fn test_descs() {
412 let elem: Element = r#"
413<description xmlns='urn:xmpp:jingle:apps:file-transfer:5'>
414 <file>
415 <media-type>text/plain</media-type>
416 <desc xml:lang='fr'>Fichier secret !</desc>
417 <desc xml:lang='en'>Secret file!</desc>
418 <hash xmlns='urn:xmpp:hashes:2'
419 algo='sha-1'>w0mcJylzCn+AfvuGdqkty2+KP48=</hash>
420 </file>
421</description>
422"#
423 .parse()
424 .unwrap();
425 let desc = Description::try_from(elem).unwrap();
426 assert_eq!(
427 desc.file.descs.keys().cloned().collect::<Vec<_>>(),
428 ["en", "fr"]
429 );
430 assert_eq!(desc.file.descs["en"], Desc(String::from("Secret file!")));
431 assert_eq!(
432 desc.file.descs["fr"],
433 Desc(String::from("Fichier secret !"))
434 );
435
436 let elem: Element = r#"
437<description xmlns='urn:xmpp:jingle:apps:file-transfer:5'>
438 <file>
439 <media-type>text/plain</media-type>
440 <desc xml:lang='fr'>Fichier secret !</desc>
441 <desc xml:lang='fr'>Secret file!</desc>
442 <hash xmlns='urn:xmpp:hashes:2'
443 algo='sha-1'>w0mcJylzCn+AfvuGdqkty2+KP48=</hash>
444 </file>
445</description>
446"#
447 .parse()
448 .unwrap();
449 let error = Description::try_from(elem).unwrap_err();
450 let message = match error {
451 Error::ParseError(string) => string,
452 _ => panic!(),
453 };
454 assert_eq!(message, "Desc element present twice for the same xml:lang.");
455 }
456
457 #[test]
458 fn test_received() {
459 let elem: Element = "<received xmlns='urn:xmpp:jingle:apps:file-transfer:5' name='coucou' creator='initiator'/>".parse().unwrap();
460 let received = Received::try_from(elem).unwrap();
461 assert_eq!(received.name, ContentId(String::from("coucou")));
462 assert_eq!(received.creator, Creator::Initiator);
463 let elem2 = Element::from(received.clone());
464 let received2 = Received::try_from(elem2).unwrap();
465 assert_eq!(received2.name, ContentId(String::from("coucou")));
466 assert_eq!(received2.creator, Creator::Initiator);
467
468 let elem: Element = "<received xmlns='urn:xmpp:jingle:apps:file-transfer:5' name='coucou' creator='initiator'><coucou/></received>".parse().unwrap();
469 let error = Received::try_from(elem).unwrap_err();
470 let message = match error {
471 Error::ParseError(string) => string,
472 _ => panic!(),
473 };
474 assert_eq!(message, "Unknown child in received element.");
475
476 let elem: Element =
477 "<received xmlns='urn:xmpp:jingle:apps:file-transfer:5' creator='initiator'/>"
478 .parse()
479 .unwrap();
480 let error = Received::try_from(elem).unwrap_err();
481 let message = match error {
482 Error::ParseError(string) => string,
483 _ => panic!(),
484 };
485 assert_eq!(message, "Required attribute 'name' missing.");
486
487 let elem: Element = "<received xmlns='urn:xmpp:jingle:apps:file-transfer:5' name='coucou' creator='coucou'/>".parse().unwrap();
488 let error = Received::try_from(elem).unwrap_err();
489 let message = match error {
490 Error::ParseError(string) => string,
491 _ => panic!(),
492 };
493 assert_eq!(message, "Unknown value for 'creator' attribute.");
494 }
495
496 #[cfg(not(feature = "disable-validation"))]
497 #[test]
498 fn test_invalid_received() {
499 let elem: Element = "<received xmlns='urn:xmpp:jingle:apps:file-transfer:5' name='coucou' creator='initiator' coucou=''/>".parse().unwrap();
500 let error = Received::try_from(elem).unwrap_err();
501 let message = match error {
502 Error::ParseError(string) => string,
503 _ => panic!(),
504 };
505 assert_eq!(message, "Unknown attribute in received element.");
506 }
507
508 #[test]
509 fn test_checksum() {
510 let elem: Element = "<checksum xmlns='urn:xmpp:jingle:apps:file-transfer:5' name='coucou' creator='initiator'><file><hash xmlns='urn:xmpp:hashes:2' algo='sha-1'>w0mcJylzCn+AfvuGdqkty2+KP48=</hash></file></checksum>".parse().unwrap();
511 let hash = vec![
512 195, 73, 156, 39, 41, 115, 10, 127, 128, 126, 251, 134, 118, 169, 45, 203, 111, 138,
513 63, 143,
514 ];
515 let checksum = Checksum::try_from(elem).unwrap();
516 assert_eq!(checksum.name, ContentId(String::from("coucou")));
517 assert_eq!(checksum.creator, Creator::Initiator);
518 assert_eq!(
519 checksum.file.hashes,
520 vec!(Hash {
521 algo: Algo::Sha_1,
522 hash: hash.clone()
523 })
524 );
525 let elem2 = Element::from(checksum);
526 let checksum2 = Checksum::try_from(elem2).unwrap();
527 assert_eq!(checksum2.name, ContentId(String::from("coucou")));
528 assert_eq!(checksum2.creator, Creator::Initiator);
529 assert_eq!(
530 checksum2.file.hashes,
531 vec!(Hash {
532 algo: Algo::Sha_1,
533 hash: hash.clone()
534 })
535 );
536
537 let elem: Element = "<checksum xmlns='urn:xmpp:jingle:apps:file-transfer:5' name='coucou' creator='initiator'><coucou/></checksum>".parse().unwrap();
538 let error = Checksum::try_from(elem).unwrap_err();
539 let message = match error {
540 Error::ParseError(string) => string,
541 _ => panic!(),
542 };
543 assert_eq!(message, "This is not a file element.");
544
545 let elem: Element = "<checksum xmlns='urn:xmpp:jingle:apps:file-transfer:5' creator='initiator'><file><hash xmlns='urn:xmpp:hashes:2' algo='sha-1'>w0mcJylzCn+AfvuGdqkty2+KP48=</hash></file></checksum>".parse().unwrap();
546 let error = Checksum::try_from(elem).unwrap_err();
547 let message = match error {
548 Error::ParseError(string) => string,
549 _ => panic!(),
550 };
551 assert_eq!(message, "Required attribute 'name' missing.");
552
553 let elem: Element = "<checksum xmlns='urn:xmpp:jingle:apps:file-transfer:5' name='coucou' creator='coucou'><file><hash xmlns='urn:xmpp:hashes:2' algo='sha-1'>w0mcJylzCn+AfvuGdqkty2+KP48=</hash></file></checksum>".parse().unwrap();
554 let error = Checksum::try_from(elem).unwrap_err();
555 let message = match error {
556 Error::ParseError(string) => string,
557 _ => panic!(),
558 };
559 assert_eq!(message, "Unknown value for 'creator' attribute.");
560 }
561
562 #[cfg(not(feature = "disable-validation"))]
563 #[test]
564 fn test_invalid_checksum() {
565 let elem: Element = "<checksum xmlns='urn:xmpp:jingle:apps:file-transfer:5' name='coucou' creator='initiator' coucou=''><file><hash xmlns='urn:xmpp:hashes:2' algo='sha-1'>w0mcJylzCn+AfvuGdqkty2+KP48=</hash></file></checksum>".parse().unwrap();
566 let error = Checksum::try_from(elem).unwrap_err();
567 let message = match error {
568 Error::ParseError(string) => string,
569 _ => panic!(),
570 };
571 assert_eq!(message, "Unknown attribute in checksum element.");
572 }
573
574 #[test]
575 fn test_range() {
576 let elem: Element = "<range xmlns='urn:xmpp:jingle:apps:file-transfer:5'/>"
577 .parse()
578 .unwrap();
579 let range = Range::try_from(elem).unwrap();
580 assert_eq!(range.offset, 0);
581 assert_eq!(range.length, None);
582 assert_eq!(range.hashes, vec!());
583
584 let elem: Element = "<range xmlns='urn:xmpp:jingle:apps:file-transfer:5' offset='2048' length='1024'><hash xmlns='urn:xmpp:hashes:2' algo='sha-1'>kHp5RSzW/h7Gm1etSf90Mr5PC/k=</hash></range>".parse().unwrap();
585 let hashes = vec![Hash {
586 algo: Algo::Sha_1,
587 hash: vec![
588 144, 122, 121, 69, 44, 214, 254, 30, 198, 155, 87, 173, 73, 255, 116, 50, 190, 79,
589 11, 249,
590 ],
591 }];
592 let range = Range::try_from(elem).unwrap();
593 assert_eq!(range.offset, 2048);
594 assert_eq!(range.length, Some(1024));
595 assert_eq!(range.hashes, hashes);
596 let elem2 = Element::from(range);
597 let range2 = Range::try_from(elem2).unwrap();
598 assert_eq!(range2.offset, 2048);
599 assert_eq!(range2.length, Some(1024));
600 assert_eq!(range2.hashes, hashes);
601 }
602
603 #[cfg(not(feature = "disable-validation"))]
604 #[test]
605 fn test_invalid_range() {
606 let elem: Element = "<range xmlns='urn:xmpp:jingle:apps:file-transfer:5' coucou=''/>"
607 .parse()
608 .unwrap();
609 let error = Range::try_from(elem).unwrap_err();
610 let message = match error {
611 Error::ParseError(string) => string,
612 _ => panic!(),
613 };
614 assert_eq!(message, "Unknown attribute in range element.");
615 }
616}