bind.rs

  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 crate::util::error::Error;
  8use crate::iq::{IqResultPayload, IqSetPayload};
  9use crate::ns;
 10use jid::{FullJid, Jid};
 11use minidom::Element;
 12use std::str::FromStr;
 13use std::convert::TryFrom;
 14
 15/// The request for resource binding, which is the process by which a client
 16/// can obtain a full JID and start exchanging on the XMPP network.
 17///
 18/// See https://xmpp.org/rfcs/rfc6120.html#bind
 19#[derive(Debug, Clone, PartialEq)]
 20pub struct BindQuery {
 21    /// Requests this resource, the server may associate another one though.
 22    ///
 23    /// If this is None, we request no particular resource, and a random one
 24    /// will be affected by the server.
 25    resource: Option<String>,
 26}
 27
 28impl BindQuery {
 29    /// Creates a resource binding request.
 30    pub fn new(resource: Option<String>) -> BindQuery {
 31        BindQuery { resource }
 32    }
 33}
 34
 35impl IqSetPayload for BindQuery {}
 36
 37impl TryFrom<Element> for BindQuery {
 38    type Error = Error;
 39
 40    fn try_from(elem: Element) -> Result<BindQuery, Error> {
 41        check_self!(elem, "bind", BIND);
 42        check_no_attributes!(elem, "bind");
 43
 44        let mut resource = None;
 45        for child in elem.children() {
 46            if resource.is_some() {
 47                return Err(Error::ParseError("Bind can only have one child."));
 48            }
 49            if child.is("resource", ns::BIND) {
 50                check_no_attributes!(child, "resource");
 51                check_no_children!(child, "resource");
 52                resource = Some(child.text());
 53            } else {
 54                return Err(Error::ParseError("Unknown element in bind request."));
 55            }
 56        }
 57
 58        Ok(BindQuery { resource })
 59    }
 60}
 61
 62impl From<BindQuery> for Element {
 63    fn from(bind: BindQuery) -> Element {
 64        Element::builder("bind")
 65            .ns(ns::BIND)
 66            .append_all(bind.resource.map(|resource|
 67                Element::builder("resource")
 68                    .ns(ns::BIND)
 69                    .append(resource)))
 70            .build()
 71    }
 72}
 73
 74/// The response for resource binding, containing the client’s full JID.
 75///
 76/// See https://xmpp.org/rfcs/rfc6120.html#bind
 77#[derive(Debug, Clone, PartialEq)]
 78pub struct BindResponse {
 79    /// The full JID returned by the server for this client.
 80    jid: FullJid,
 81}
 82
 83impl IqResultPayload for BindResponse {}
 84
 85impl From<BindResponse> for FullJid {
 86    fn from(bind: BindResponse) -> FullJid {
 87        bind.jid
 88    }
 89}
 90
 91impl From<BindResponse> for Jid {
 92    fn from(bind: BindResponse) -> Jid {
 93        Jid::Full(bind.jid)
 94    }
 95}
 96
 97impl TryFrom<Element> for BindResponse {
 98    type Error = Error;
 99
100    fn try_from(elem: Element) -> Result<BindResponse, Error> {
101        check_self!(elem, "bind", BIND);
102        check_no_attributes!(elem, "bind");
103
104        let mut jid = None;
105        for child in elem.children() {
106            if jid.is_some() {
107                return Err(Error::ParseError("Bind can only have one child."));
108            }
109            if child.is("jid", ns::BIND) {
110                check_no_attributes!(child, "jid");
111                check_no_children!(child, "jid");
112                jid = Some(FullJid::from_str(&child.text())?);
113            } else {
114                return Err(Error::ParseError("Unknown element in bind response."));
115            }
116        }
117
118        Ok(BindResponse { jid: match jid {
119            None => return Err(Error::ParseError("Bind response must contain a jid element.")),
120            Some(jid) => jid,
121        } })
122    }
123}
124
125impl From<BindResponse> for Element {
126    fn from(bind: BindResponse) -> Element {
127        Element::builder("bind")
128            .ns(ns::BIND)
129            .append(Element::builder("jid").ns(ns::BIND).append(bind.jid))
130            .build()
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[cfg(target_pointer_width = "32")]
139    #[test]
140    fn test_size() {
141        assert_size!(BindQuery, 12);
142        assert_size!(BindResponse, 36);
143    }
144
145    #[cfg(target_pointer_width = "64")]
146    #[test]
147    fn test_size() {
148        assert_size!(BindQuery, 24);
149        assert_size!(BindResponse, 72);
150    }
151
152    #[test]
153    fn test_simple() {
154        let elem: Element = "<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/>"
155            .parse()
156            .unwrap();
157        let bind = BindQuery::try_from(elem).unwrap();
158        assert_eq!(bind.resource, None);
159
160        let elem: Element = "<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource>Hello™</resource></bind>"
161            .parse()
162            .unwrap();
163        let bind = BindQuery::try_from(elem).unwrap();
164        // FIXME: “™” should be resourceprep’d into “TM” here…
165        //assert_eq!(bind.resource.unwrap(), "HelloTM");
166        assert_eq!(bind.resource.unwrap(), "Hello™");
167
168        let elem: Element = "<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><jid>coucou@linkmauve.fr/HelloTM</jid></bind>"
169            .parse()
170            .unwrap();
171        let bind = BindResponse::try_from(elem).unwrap();
172        assert_eq!(bind.jid, FullJid::new("coucou", "linkmauve.fr", "HelloTM"));
173    }
174
175    #[cfg(not(feature = "disable-validation"))]
176    #[test]
177    fn test_invalid_resource() {
178        let elem: Element = "<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource attr='coucou'>resource</resource></bind>"
179            .parse()
180            .unwrap();
181        let error = BindQuery::try_from(elem).unwrap_err();
182        let message = match error {
183            Error::ParseError(string) => string,
184            _ => panic!(),
185        };
186        assert_eq!(message, "Unknown attribute in resource element.");
187
188        let elem: Element = "<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource><hello-world/>resource</resource></bind>"
189            .parse()
190            .unwrap();
191        let error = BindQuery::try_from(elem).unwrap_err();
192        let message = match error {
193            Error::ParseError(string) => string,
194            _ => panic!(),
195        };
196        assert_eq!(message, "Unknown child in resource element.");
197    }
198}