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 xso::{text::FixedHex, AsXml, FromXml};
8
9use crate::ns;
10use digest::Digest;
11use sha1::Sha1;
12
13/// The main authentication mechanism for components.
14#[derive(FromXml, AsXml, PartialEq, Debug, Clone, Default)]
15#[xml(namespace = ns::COMPONENT, name = "handshake")]
16pub struct Handshake {
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 #[xml(text(codec = FixedHex<20>))]
24 pub data: Option<[u8; 20]>,
25}
26
27impl Handshake {
28 /// Creates a successful reply from a server.
29 pub fn new() -> Handshake {
30 Handshake::default()
31 }
32
33 /// Creates an authentication request from the component.
34 pub fn from_stream_id_and_password(stream_id: String, password: &str) -> Handshake {
35 let input = stream_id + password;
36 let hash = Sha1::digest(input.as_bytes());
37 Handshake {
38 data: Some(hash.into()),
39 }
40 }
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46 use minidom::Element;
47
48 #[test]
49 fn test_size() {
50 assert_size!(Handshake, 21);
51 }
52
53 #[test]
54 fn test_simple() {
55 let elem: Element = "<handshake xmlns='jabber:component:accept'/>"
56 .parse()
57 .unwrap();
58 let handshake = Handshake::try_from(elem).unwrap();
59 assert_eq!(handshake.data, None);
60
61 let elem: Element = "<handshake xmlns='jabber:component:accept'>9accec263ab84a43c6037ccf7cd48cb1d3f6df8e</handshake>"
62 .parse()
63 .unwrap();
64 let handshake = Handshake::try_from(elem).unwrap();
65 assert_eq!(
66 handshake.data,
67 Some([
68 0x9a, 0xcc, 0xec, 0x26, 0x3a, 0xb8, 0x4a, 0x43, 0xc6, 0x03, 0x7c, 0xcf, 0x7c, 0xd4,
69 0x8c, 0xb1, 0xd3, 0xf6, 0xdf, 0x8e
70 ])
71 );
72 }
73
74 #[test]
75 fn test_constructors() {
76 let handshake = Handshake::new();
77 assert_eq!(handshake.data, None);
78
79 let stream_id = String::from("sid");
80 let password = "123456";
81 let handshake = Handshake::from_stream_id_and_password(stream_id, password);
82 assert_eq!(
83 handshake.data,
84 Some([
85 0x9a, 0xcc, 0xec, 0x26, 0x3a, 0xb8, 0x4a, 0x43, 0xc6, 0x03, 0x7c, 0xcf, 0x7c, 0xd4,
86 0x8c, 0xb1, 0xd3, 0xf6, 0xdf, 0x8e
87 ])
88 );
89 }
90}