jingle_ft.rs

  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    use base64;
331
332    #[cfg(target_pointer_width = "32")]
333    #[test]
334    fn test_size() {
335        assert_size!(Range, 40);
336        assert_size!(File, 128);
337        assert_size!(Description, 128);
338        assert_size!(Checksum, 144);
339        assert_size!(Received, 16);
340    }
341
342    #[cfg(target_pointer_width = "64")]
343    #[test]
344    fn test_size() {
345        assert_size!(Range, 48);
346        assert_size!(File, 184);
347        assert_size!(Description, 184);
348        assert_size!(Checksum, 216);
349        assert_size!(Received, 32);
350    }
351
352    #[test]
353    fn test_description() {
354        let elem: Element = r#"
355<description xmlns='urn:xmpp:jingle:apps:file-transfer:5'>
356  <file>
357    <media-type>text/plain</media-type>
358    <name>test.txt</name>
359    <date>2015-07-26T21:46:00+01:00</date>
360    <size>6144</size>
361    <hash xmlns='urn:xmpp:hashes:2'
362          algo='sha-1'>w0mcJylzCn+AfvuGdqkty2+KP48=</hash>
363  </file>
364</description>
365"#
366        .parse()
367        .unwrap();
368        let desc = Description::try_from(elem).unwrap();
369        assert_eq!(desc.file.media_type, Some(String::from("text/plain")));
370        assert_eq!(desc.file.name, Some(String::from("test.txt")));
371        assert_eq!(desc.file.descs, BTreeMap::new());
372        assert_eq!(
373            desc.file.date,
374            DateTime::from_str("2015-07-26T21:46:00+01:00").ok()
375        );
376        assert_eq!(desc.file.size, Some(6144u64));
377        assert_eq!(desc.file.range, None);
378        assert_eq!(desc.file.hashes[0].algo, Algo::Sha_1);
379        assert_eq!(
380            desc.file.hashes[0].hash,
381            base64::decode("w0mcJylzCn+AfvuGdqkty2+KP48=").unwrap()
382        );
383    }
384
385    #[test]
386    fn test_request() {
387        let elem: Element = r#"
388<description xmlns='urn:xmpp:jingle:apps:file-transfer:5'>
389  <file>
390    <hash xmlns='urn:xmpp:hashes:2'
391          algo='sha-1'>w0mcJylzCn+AfvuGdqkty2+KP48=</hash>
392  </file>
393</description>
394"#
395        .parse()
396        .unwrap();
397        let desc = Description::try_from(elem).unwrap();
398        assert_eq!(desc.file.media_type, None);
399        assert_eq!(desc.file.name, None);
400        assert_eq!(desc.file.descs, BTreeMap::new());
401        assert_eq!(desc.file.date, None);
402        assert_eq!(desc.file.size, None);
403        assert_eq!(desc.file.range, None);
404        assert_eq!(desc.file.hashes[0].algo, Algo::Sha_1);
405        assert_eq!(
406            desc.file.hashes[0].hash,
407            base64::decode("w0mcJylzCn+AfvuGdqkty2+KP48=").unwrap()
408        );
409    }
410
411    #[test]
412    fn test_descs() {
413        let elem: Element = r#"
414<description xmlns='urn:xmpp:jingle:apps:file-transfer:5'>
415  <file>
416    <media-type>text/plain</media-type>
417    <desc xml:lang='fr'>Fichier secret !</desc>
418    <desc xml:lang='en'>Secret file!</desc>
419    <hash xmlns='urn:xmpp:hashes:2'
420          algo='sha-1'>w0mcJylzCn+AfvuGdqkty2+KP48=</hash>
421  </file>
422</description>
423"#
424        .parse()
425        .unwrap();
426        let desc = Description::try_from(elem).unwrap();
427        assert_eq!(
428            desc.file.descs.keys().cloned().collect::<Vec<_>>(),
429            ["en", "fr"]
430        );
431        assert_eq!(desc.file.descs["en"], Desc(String::from("Secret file!")));
432        assert_eq!(
433            desc.file.descs["fr"],
434            Desc(String::from("Fichier secret !"))
435        );
436
437        let elem: Element = r#"
438<description xmlns='urn:xmpp:jingle:apps:file-transfer:5'>
439  <file>
440    <media-type>text/plain</media-type>
441    <desc xml:lang='fr'>Fichier secret !</desc>
442    <desc xml:lang='fr'>Secret file!</desc>
443    <hash xmlns='urn:xmpp:hashes:2'
444          algo='sha-1'>w0mcJylzCn+AfvuGdqkty2+KP48=</hash>
445  </file>
446</description>
447"#
448        .parse()
449        .unwrap();
450        let error = Description::try_from(elem).unwrap_err();
451        let message = match error {
452            Error::ParseError(string) => string,
453            _ => panic!(),
454        };
455        assert_eq!(message, "Desc element present twice for the same xml:lang.");
456    }
457
458    #[test]
459    fn test_received() {
460        let elem: Element = "<received xmlns='urn:xmpp:jingle:apps:file-transfer:5' name='coucou' creator='initiator'/>".parse().unwrap();
461        let received = Received::try_from(elem).unwrap();
462        assert_eq!(received.name, ContentId(String::from("coucou")));
463        assert_eq!(received.creator, Creator::Initiator);
464        let elem2 = Element::from(received.clone());
465        let received2 = Received::try_from(elem2).unwrap();
466        assert_eq!(received2.name, ContentId(String::from("coucou")));
467        assert_eq!(received2.creator, Creator::Initiator);
468
469        let elem: Element = "<received xmlns='urn:xmpp:jingle:apps:file-transfer:5' name='coucou' creator='initiator'><coucou/></received>".parse().unwrap();
470        let error = Received::try_from(elem).unwrap_err();
471        let message = match error {
472            Error::ParseError(string) => string,
473            _ => panic!(),
474        };
475        assert_eq!(message, "Unknown child in received element.");
476
477        let elem: Element =
478            "<received xmlns='urn:xmpp:jingle:apps:file-transfer:5' creator='initiator'/>"
479                .parse()
480                .unwrap();
481        let error = Received::try_from(elem).unwrap_err();
482        let message = match error {
483            Error::ParseError(string) => string,
484            _ => panic!(),
485        };
486        assert_eq!(message, "Required attribute 'name' missing.");
487
488        let elem: Element = "<received xmlns='urn:xmpp:jingle:apps:file-transfer:5' name='coucou' creator='coucou'/>".parse().unwrap();
489        let error = Received::try_from(elem).unwrap_err();
490        let message = match error {
491            Error::ParseError(string) => string,
492            _ => panic!(),
493        };
494        assert_eq!(message, "Unknown value for 'creator' attribute.");
495    }
496
497    #[cfg(not(feature = "disable-validation"))]
498    #[test]
499    fn test_invalid_received() {
500        let elem: Element = "<received xmlns='urn:xmpp:jingle:apps:file-transfer:5' name='coucou' creator='initiator' coucou=''/>".parse().unwrap();
501        let error = Received::try_from(elem).unwrap_err();
502        let message = match error {
503            Error::ParseError(string) => string,
504            _ => panic!(),
505        };
506        assert_eq!(message, "Unknown attribute in received element.");
507    }
508
509    #[test]
510    fn test_checksum() {
511        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();
512        let hash = vec![
513            195, 73, 156, 39, 41, 115, 10, 127, 128, 126, 251, 134, 118, 169, 45, 203, 111, 138,
514            63, 143,
515        ];
516        let checksum = Checksum::try_from(elem).unwrap();
517        assert_eq!(checksum.name, ContentId(String::from("coucou")));
518        assert_eq!(checksum.creator, Creator::Initiator);
519        assert_eq!(
520            checksum.file.hashes,
521            vec!(Hash {
522                algo: Algo::Sha_1,
523                hash: hash.clone()
524            })
525        );
526        let elem2 = Element::from(checksum);
527        let checksum2 = Checksum::try_from(elem2).unwrap();
528        assert_eq!(checksum2.name, ContentId(String::from("coucou")));
529        assert_eq!(checksum2.creator, Creator::Initiator);
530        assert_eq!(
531            checksum2.file.hashes,
532            vec!(Hash {
533                algo: Algo::Sha_1,
534                hash: hash.clone()
535            })
536        );
537
538        let elem: Element = "<checksum xmlns='urn:xmpp:jingle:apps:file-transfer:5' name='coucou' creator='initiator'><coucou/></checksum>".parse().unwrap();
539        let error = Checksum::try_from(elem).unwrap_err();
540        let message = match error {
541            Error::ParseError(string) => string,
542            _ => panic!(),
543        };
544        assert_eq!(message, "This is not a file element.");
545
546        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();
547        let error = Checksum::try_from(elem).unwrap_err();
548        let message = match error {
549            Error::ParseError(string) => string,
550            _ => panic!(),
551        };
552        assert_eq!(message, "Required attribute 'name' missing.");
553
554        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();
555        let error = Checksum::try_from(elem).unwrap_err();
556        let message = match error {
557            Error::ParseError(string) => string,
558            _ => panic!(),
559        };
560        assert_eq!(message, "Unknown value for 'creator' attribute.");
561    }
562
563    #[cfg(not(feature = "disable-validation"))]
564    #[test]
565    fn test_invalid_checksum() {
566        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();
567        let error = Checksum::try_from(elem).unwrap_err();
568        let message = match error {
569            Error::ParseError(string) => string,
570            _ => panic!(),
571        };
572        assert_eq!(message, "Unknown attribute in checksum element.");
573    }
574
575    #[test]
576    fn test_range() {
577        let elem: Element = "<range xmlns='urn:xmpp:jingle:apps:file-transfer:5'/>"
578            .parse()
579            .unwrap();
580        let range = Range::try_from(elem).unwrap();
581        assert_eq!(range.offset, 0);
582        assert_eq!(range.length, None);
583        assert_eq!(range.hashes, vec!());
584
585        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();
586        let hashes = vec![Hash {
587            algo: Algo::Sha_1,
588            hash: vec![
589                144, 122, 121, 69, 44, 214, 254, 30, 198, 155, 87, 173, 73, 255, 116, 50, 190, 79,
590                11, 249,
591            ],
592        }];
593        let range = Range::try_from(elem).unwrap();
594        assert_eq!(range.offset, 2048);
595        assert_eq!(range.length, Some(1024));
596        assert_eq!(range.hashes, hashes);
597        let elem2 = Element::from(range);
598        let range2 = Range::try_from(elem2).unwrap();
599        assert_eq!(range2.offset, 2048);
600        assert_eq!(range2.length, Some(1024));
601        assert_eq!(range2.hashes, hashes);
602    }
603
604    #[cfg(not(feature = "disable-validation"))]
605    #[test]
606    fn test_invalid_range() {
607        let elem: Element = "<range xmlns='urn:xmpp:jingle:apps:file-transfer:5' coucou=''/>"
608            .parse()
609            .unwrap();
610        let error = Range::try_from(elem).unwrap_err();
611        let message = match error {
612            Error::ParseError(string) => string,
613            _ => panic!(),
614        };
615        assert_eq!(message, "Unknown attribute in range element.");
616    }
617}