1// Copyright (c) 2019 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::hashes::{Hash, Algo};
8use crate::util::helpers::Base64;
9use crate::util::error::Error;
10use minidom::IntoAttributeValue;
11use std::str::FromStr;
12
13/// A Content-ID, as defined in RFC2111.
14///
15/// The text value SHOULD be of the form algo+hash@bob.xmpp.org, this struct
16/// enforces that format.
17#[derive(Clone, Debug)]
18pub struct ContentId {
19 hash: Hash,
20}
21
22impl FromStr for ContentId {
23 type Err = Error;
24
25 fn from_str(s: &str) -> Result<Self, Error> {
26 let temp: Vec<_> = s.splitn(2, '@').collect();
27 let temp: Vec<_> = match temp[..] {
28 [lhs, rhs] => {
29 if rhs != "bob.xmpp.org" {
30 return Err(Error::ParseError("Wrong domain for cid URI."))
31 }
32 lhs.splitn(2, '+').collect()
33 },
34 _ => return Err(Error::ParseError("Missing @ in cid URI."))
35 };
36 let (algo, hex) = match temp[..] {
37 [lhs, rhs] => {
38 let algo = match lhs {
39 "sha1" => Algo::Sha_1,
40 "sha256" => Algo::Sha_256,
41 _ => unimplemented!(),
42 };
43 (algo, rhs)
44 },
45 _ => return Err(Error::ParseError("Missing + in cid URI."))
46 };
47 let hash = Hash::from_hex(algo, hex)?;
48 Ok(ContentId { hash })
49 }
50}
51
52impl IntoAttributeValue for ContentId {
53 fn into_attribute_value(self) -> Option<String> {
54 let algo = match self.hash.algo {
55 Algo::Sha_1 => "sha1",
56 Algo::Sha_256 => "sha256",
57 _ => unimplemented!(),
58 };
59 Some(format!("{}+{}@bob.xmpp.org", algo, self.hash.to_hex()))
60 }
61}
62
63generate_element!(
64 /// Request for an uncached cid file.
65 Data, "data", BOB,
66 attributes: [
67 /// The cid in question.
68 cid: Required<ContentId> = "cid",
69
70 /// How long to cache it (in seconds).
71 max_age: Option<usize> = "max-age",
72
73 /// The MIME type of the data being transmitted.
74 ///
75 /// See the [IANA MIME Media Types Registry][1] for a list of
76 /// registered types, but unregistered or yet-to-be-registered are
77 /// accepted too.
78 ///
79 /// [1]: https://www.iana.org/assignments/media-types/media-types.xhtml
80 type_: Option<String> = "type"
81 ],
82 text: (
83 /// The actual data.
84 data: Base64<Vec<u8>>
85 )
86);
87
88#[cfg(test)]
89mod tests {
90 use super::*;
91 use minidom::Element;
92 use std::convert::TryFrom;
93 use std::error::Error as StdError;
94
95 #[cfg(target_pointer_width = "32")]
96 #[test]
97 fn test_size() {
98 assert_size!(ContentId, 24);
99 assert_size!(Data, 24);
100 }
101
102 #[cfg(target_pointer_width = "64")]
103 #[test]
104 fn test_size() {
105 assert_size!(ContentId, 56);
106 assert_size!(Data, 120);
107 }
108
109 #[test]
110 fn test_simple() {
111 let cid: ContentId = "sha1+8f35fef110ffc5df08d579a50083ff9308fb6242@bob.xmpp.org".parse().unwrap();
112 assert_eq!(cid.hash.algo, Algo::Sha_1);
113 assert_eq!(cid.hash.hash, b"\x8f\x35\xfe\xf1\x10\xff\xc5\xdf\x08\xd5\x79\xa5\x00\x83\xff\x93\x08\xfb\x62\x42");
114 assert_eq!(cid.into_attribute_value().unwrap(), "sha1+8f35fef110ffc5df08d579a50083ff9308fb6242@bob.xmpp.org");
115
116 let elem: Element = "<data xmlns='urn:xmpp:bob' cid='sha1+8f35fef110ffc5df08d579a50083ff9308fb6242@bob.xmpp.org'/>".parse().unwrap();
117 let data = Data::try_from(elem).unwrap();
118 assert_eq!(data.cid.hash.algo, Algo::Sha_1);
119 assert_eq!(data.cid.hash.hash, b"\x8f\x35\xfe\xf1\x10\xff\xc5\xdf\x08\xd5\x79\xa5\x00\x83\xff\x93\x08\xfb\x62\x42");
120 assert!(data.max_age.is_none());
121 assert!(data.type_.is_none());
122 assert!(data.data.is_empty());
123 }
124
125 #[test]
126 fn invalid_cid() {
127 let error = "Hello world!".parse::<ContentId>().unwrap_err();
128 let message = match error {
129 Error::ParseError(string) => string,
130 _ => panic!(),
131 };
132 assert_eq!(message, "Missing @ in cid URI.");
133
134 let error = "Hello world@bob.xmpp.org".parse::<ContentId>().unwrap_err();
135 let message = match error {
136 Error::ParseError(string) => string,
137 _ => panic!(),
138 };
139 assert_eq!(message, "Missing + in cid URI.");
140
141 let error = "sha1+1234@coucou.linkmauve.fr".parse::<ContentId>().unwrap_err();
142 let message = match error {
143 Error::ParseError(string) => string,
144 _ => panic!(),
145 };
146 assert_eq!(message, "Wrong domain for cid URI.");
147
148 let error = "sha1+invalid@bob.xmpp.org".parse::<ContentId>().unwrap_err();
149 let message = match error {
150 Error::ParseIntError(error) => error,
151 _ => panic!(),
152 };
153 assert_eq!(message.description(), "invalid digit found in string");
154 }
155
156 #[test]
157 fn unknown_child() {
158 let elem: Element = "<data xmlns='urn:xmpp:bob'><coucou/></data>"
159 .parse()
160 .unwrap();
161 let error = Data::try_from(elem).unwrap_err();
162 let message = match error {
163 Error::ParseError(string) => string,
164 _ => panic!(),
165 };
166 assert_eq!(message, "Unknown child in data element.");
167 }
168}