1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
// Copyright (c) 2018 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use crate::util::error::Error;
use crate::iq::{IqResultPayload, IqSetPayload};
use crate::ns;
use jid::FullJid;
use minidom::Element;
use std::str::FromStr;
use std::convert::TryFrom;

/// The request for resource binding, which is the process by which a client
/// can obtain a full JID and start exchanging on the XMPP network.
///
/// See https://xmpp.org/rfcs/rfc6120.html#bind
#[derive(Debug, Clone, PartialEq)]
pub enum Bind {
    /// Requests no particular resource, a random one will be affected by the
    /// server.
    None,

    /// Requests this resource, the server may associate another one though.
    Resource(String),

    /// The full JID returned by the server for this client.
    Jid(FullJid),
}

impl Bind {
    /// Creates a resource binding request.
    pub fn new(resource: Option<String>) -> Bind {
        match resource {
            None => Bind::None,
            Some(resource) => Bind::Resource(resource),
        }
    }
}

impl IqSetPayload for Bind {}
impl IqResultPayload for Bind {}

impl TryFrom<Element> for Bind {
    type Error = Error;

    fn try_from(elem: Element) -> Result<Bind, Error> {
        check_self!(elem, "bind", BIND);
        check_no_attributes!(elem, "bind");

        let mut bind = Bind::None;
        for child in elem.children() {
            if bind != Bind::None {
                return Err(Error::ParseError("Bind can only have one child."));
            }
            if child.is("resource", ns::BIND) {
                check_no_attributes!(child, "resource");
                check_no_children!(child, "resource");
                bind = Bind::Resource(child.text());
            } else if child.is("jid", ns::BIND) {
                check_no_attributes!(child, "jid");
                check_no_children!(child, "jid");
                bind = Bind::Jid(FullJid::from_str(&child.text())?);
            } else {
                return Err(Error::ParseError("Unknown element in bind."));
            }
        }

        Ok(bind)
    }
}

impl From<Bind> for Element {
    fn from(bind: Bind) -> Element {
        Element::builder("bind")
            .ns(ns::BIND)
            .append(match bind {
                Bind::None => vec![],
                Bind::Resource(resource) => vec![Element::builder("resource")
                    .ns(ns::BIND)
                    .append(resource)
                    .build()],
                Bind::Jid(jid) => vec![Element::builder("jid").ns(ns::BIND).append(jid).build()],
            })
            .build()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(target_pointer_width = "32")]
    #[test]
    fn test_size() {
        assert_size!(Bind, 40);
    }

    #[cfg(target_pointer_width = "64")]
    #[test]
    fn test_size() {
        assert_size!(Bind, 80);
    }

    #[test]
    fn test_simple() {
        let elem: Element = "<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/>"
            .parse()
            .unwrap();
        let bind = Bind::try_from(elem).unwrap();
        assert_eq!(bind, Bind::None);
    }

    #[cfg(not(feature = "disable-validation"))]
    #[test]
    fn test_invalid_resource() {
        let elem: Element = "<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource attr='coucou'>resource</resource></bind>"
            .parse()
            .unwrap();
        let error = Bind::try_from(elem).unwrap_err();
        let message = match error {
            Error::ParseError(string) => string,
            _ => panic!(),
        };
        assert_eq!(message, "Unknown attribute in resource element.");

        let elem: Element = "<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource><hello-world/>resource</resource></bind>"
            .parse()
            .unwrap();
        let error = Bind::try_from(elem).unwrap_err();
        let message = match error {
            Error::ParseError(string) => string,
            _ => panic!(),
        };
        assert_eq!(message, "Unknown child in resource element.");
    }
}