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 TryFrom<Element> for Hash {
 70    type Error = Error;
 71
 72    fn try_from(elem: 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 = get_attr!(elem, "algo", required);
 80        let hash = match elem.text().as_ref() {
 81            "" => return Err(Error::ParseError("Hash element shouldn’t be empty.")),
 82            text => text.to_owned(),
 83        };
 84        Ok(Hash {
 85            algo: algo,
 86            hash: hash,
 87        })
 88    }
 89}
 90
 91impl Into<Element> for Hash {
 92    fn into(self) -> Element {
 93        Element::builder("hash")
 94                .ns(ns::HASHES)
 95                .attr("algo", self.algo)
 96                .append(self.hash.clone())
 97                .build()
 98    }
 99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    #[test]
106    fn test_simple() {
107        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=</hash>".parse().unwrap();
108        let hash = Hash::try_from(elem).unwrap();
109        assert_eq!(hash.algo, Algo::Sha_256);
110        assert_eq!(hash.hash, "2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=");
111    }
112
113    #[test]
114    fn test_unknown() {
115        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>".parse().unwrap();
116        let error = Hash::try_from(elem).unwrap_err();
117        let message = match error {
118            Error::ParseError(string) => string,
119            _ => panic!(),
120        };
121        assert_eq!(message, "This is not a hash element.");
122    }
123
124    #[test]
125    fn test_invalid_child() {
126        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2'><coucou/></hash>".parse().unwrap();
127        let error = Hash::try_from(elem).unwrap_err();
128        let message = match error {
129            Error::ParseError(string) => string,
130            _ => panic!(),
131        };
132        assert_eq!(message, "Unknown child in hash element.");
133    }
134}