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 try_from::TryFrom;
8
9use minidom::Element;
10use error::Error;
11use helpers::PlainText;
12use ns;
13
14use sha1::Sha1;
15use digest::Digest;
16
17generate_element_with_text!(Handshake, "handshake", ns::COMPONENT,
18 data: PlainText<Option<String>>
19);
20
21impl Handshake {
22 pub fn new() -> Handshake {
23 Handshake {
24 data: None,
25 }
26 }
27
28 pub fn from_password_and_stream_id(password: &str, stream_id: &str) -> Handshake {
29 let input = String::from(stream_id) + password;
30 let hash = Sha1::digest(input.as_bytes());
31 let content = format!("{:x}", hash);
32 Handshake {
33 data: Some(content),
34 }
35 }
36}
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41
42 #[test]
43 fn test_simple() {
44 let elem: Element = "<handshake xmlns='jabber:component:accept'/>".parse().unwrap();
45 let handshake = Handshake::try_from(elem).unwrap();
46 assert_eq!(handshake.data, None);
47
48 let elem: Element = "<handshake xmlns='jabber:component:accept'>Coucou</handshake>".parse().unwrap();
49 let handshake = Handshake::try_from(elem).unwrap();
50 assert_eq!(handshake.data, Some(String::from("Coucou")));
51 }
52
53 #[test]
54 fn test_constructors() {
55 let handshake = Handshake::new();
56 assert_eq!(handshake.data, None);
57
58 let handshake = Handshake::from_password_and_stream_id("123456", "sid");
59 assert_eq!(handshake.data, Some(String::from("9accec263ab84a43c6037ccf7cd48cb1d3f6df8e")));
60 }
61}