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 std::convert::TryFrom;
8use std::str::FromStr;
9
10use minidom::{Element, IntoAttributeValue};
11
12use error::Error;
13
14use ns;
15
16use base64;
17
18#[allow(non_camel_case_types)]
19#[derive(Debug, Clone, PartialEq)]
20pub enum Algo {
21 Sha_1,
22 Sha_256,
23 Sha_512,
24 Sha3_256,
25 Sha3_512,
26 Blake2b_256,
27 Blake2b_512,
28 Unknown(String),
29}
30
31impl FromStr for Algo {
32 type Err = Error;
33
34 fn from_str(s: &str) -> Result<Algo, Error> {
35 Ok(match s {
36 "" => return Err(Error::ParseError("'algo' argument can’t be empty.")),
37
38 "sha-1" => Algo::Sha_1,
39 "sha-256" => Algo::Sha_256,
40 "sha-512" => Algo::Sha_512,
41 "sha3-256" => Algo::Sha3_256,
42 "sha3-512" => Algo::Sha3_512,
43 "blake2b-256" => Algo::Blake2b_256,
44 "blake2b-512" => Algo::Blake2b_512,
45 value => Algo::Unknown(value.to_owned()),
46 })
47 }
48}
49
50impl IntoAttributeValue for Algo {
51 fn into_attribute_value(self) -> Option<String> {
52 Some(String::from(match self {
53 Algo::Sha_1 => "sha-1",
54 Algo::Sha_256 => "sha-256",
55 Algo::Sha_512 => "sha-512",
56 Algo::Sha3_256 => "sha3-256",
57 Algo::Sha3_512 => "sha3-512",
58 Algo::Blake2b_256 => "blake2b-256",
59 Algo::Blake2b_512 => "blake2b-512",
60 Algo::Unknown(text) => return Some(text),
61 }))
62 }
63}
64
65#[derive(Debug, Clone, PartialEq)]
66pub struct Hash {
67 pub algo: Algo,
68 pub hash: Vec<u8>,
69}
70
71impl TryFrom<Element> for Hash {
72 type Error = Error;
73
74 fn try_from(elem: Element) -> Result<Hash, Error> {
75 if !elem.is("hash", ns::HASHES) {
76 return Err(Error::ParseError("This is not a hash element."));
77 }
78 for _ in elem.children() {
79 return Err(Error::ParseError("Unknown child in hash element."));
80 }
81 let algo = get_attr!(elem, "algo", required);
82 let hash = match elem.text().as_ref() {
83 "" => return Err(Error::ParseError("Hash element shouldn’t be empty.")),
84 text => base64::decode(text)?,
85 };
86 Ok(Hash {
87 algo: algo,
88 hash: hash,
89 })
90 }
91}
92
93impl Into<Element> for Hash {
94 fn into(self) -> Element {
95 Element::builder("hash")
96 .ns(ns::HASHES)
97 .attr("algo", self.algo)
98 .append(base64::encode(&self.hash))
99 .build()
100 }
101}
102
103#[cfg(test)]
104mod tests {
105 use super::*;
106
107 #[test]
108 fn test_simple() {
109 let elem: Element = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=</hash>".parse().unwrap();
110 let hash = Hash::try_from(elem).unwrap();
111 assert_eq!(hash.algo, Algo::Sha_256);
112 assert_eq!(hash.hash, base64::decode("2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=").unwrap());
113 }
114
115 #[test]
116 fn test_unknown() {
117 let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>".parse().unwrap();
118 let error = Hash::try_from(elem).unwrap_err();
119 let message = match error {
120 Error::ParseError(string) => string,
121 _ => panic!(),
122 };
123 assert_eq!(message, "This is not a hash element.");
124 }
125
126 #[test]
127 fn test_invalid_child() {
128 let elem: Element = "<hash xmlns='urn:xmpp:hashes:2'><coucou/></hash>".parse().unwrap();
129 let error = Hash::try_from(elem).unwrap_err();
130 let message = match error {
131 Error::ParseError(string) => string,
132 _ => panic!(),
133 };
134 assert_eq!(message, "Unknown child in hash element.");
135 }
136}