component.rs

 1// Copyright (c) 2018 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
 7#![deny(missing_docs)]
 8
 9use helpers::PlainText;
10use sha1::Sha1;
11use digest::Digest;
12
13generate_element_with_text!(
14    /// The main authentication mechanism for components.
15    Handshake, "handshake", COMPONENT,
16
17    /// If Some, contains the hex-encoded SHA-1 of the concatenation of the
18    /// stream id and the password, and is used to authenticate against the
19    /// server.
20    ///
21    /// If None, it is the successful reply from the server, the stream is now
22    /// fully established and both sides can now exchange stanzas.
23    data: PlainText<Option<String>>
24);
25
26impl Handshake {
27    /// Creates a successful reply from a server.
28    pub fn new() -> Handshake {
29        Handshake {
30            data: None,
31        }
32    }
33
34    /// Creates an authentication request from the component.
35    pub fn from_password_and_stream_id(password: &str, stream_id: &str) -> Handshake {
36        let input = String::from(stream_id) + password;
37        let hash = Sha1::digest(input.as_bytes());
38        let content = format!("{:x}", hash);
39        Handshake {
40            data: Some(content),
41        }
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48    use try_from::TryFrom;
49    use minidom::Element;
50
51    #[test]
52    fn test_simple() {
53        let elem: Element = "<handshake xmlns='jabber:component:accept'/>".parse().unwrap();
54        let handshake = Handshake::try_from(elem).unwrap();
55        assert_eq!(handshake.data, None);
56
57        let elem: Element = "<handshake xmlns='jabber:component:accept'>Coucou</handshake>".parse().unwrap();
58        let handshake = Handshake::try_from(elem).unwrap();
59        assert_eq!(handshake.data, Some(String::from("Coucou")));
60    }
61
62    #[test]
63    fn test_constructors() {
64        let handshake = Handshake::new();
65        assert_eq!(handshake.data, None);
66
67        let handshake = Handshake::from_password_and_stream_id("123456", "sid");
68        assert_eq!(handshake.data, Some(String::from("9accec263ab84a43c6037ccf7cd48cb1d3f6df8e")));
69    }
70}