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