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