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