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!(
14 /// The main authentication mechanism for components.
15 Handshake, "handshake", COMPONENT,
16 text: (
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);
26
27impl Handshake {
28 /// Creates a successful reply from a server.
29 pub fn new() -> Handshake {
30 Handshake {
31 data: None,
32 }
33 }
34
35 /// Creates an authentication request from the component.
36 pub fn from_password_and_stream_id(password: &str, stream_id: &str) -> Handshake {
37 let input = String::from(stream_id) + password;
38 let hash = Sha1::digest(input.as_bytes());
39 let content = format!("{:x}", hash);
40 Handshake {
41 data: Some(content),
42 }
43 }
44}
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49 use try_from::TryFrom;
50 use minidom::Element;
51
52 #[test]
53 fn test_simple() {
54 let elem: Element = "<handshake xmlns='jabber:component:accept'/>".parse().unwrap();
55 let handshake = Handshake::try_from(elem).unwrap();
56 assert_eq!(handshake.data, None);
57
58 let elem: Element = "<handshake xmlns='jabber:component:accept'>Coucou</handshake>".parse().unwrap();
59 let handshake = Handshake::try_from(elem).unwrap();
60 assert_eq!(handshake.data, Some(String::from("Coucou")));
61 }
62
63 #[test]
64 fn test_constructors() {
65 let handshake = Handshake::new();
66 assert_eq!(handshake.data, None);
67
68 let handshake = Handshake::from_password_and_stream_id("123456", "sid");
69 assert_eq!(handshake.data, Some(String::from("9accec263ab84a43c6037ccf7cd48cb1d3f6df8e")));
70 }
71}