xmpp-rs/src/iq.rs

448 lines
14 KiB
Rust
Raw Normal View History

2017-04-29 21:14:34 +00:00
// Copyright (c) 2017 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
// Copyright (c) 2017 Maxime “pep” Buquet <pep+code@bouah.net>
//
// 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::ns;
use crate::stanza_error::StanzaError;
2018-12-18 14:32:05 +00:00
use jid::Jid;
use minidom::Element;
use minidom::IntoAttributeValue;
use try_from::TryFrom;
2017-04-23 20:12:27 +00:00
/// Should be implemented on every known payload of an `<iq type='get'/>`.
pub trait IqGetPayload: TryFrom<Element> + Into<Element> {}
/// Should be implemented on every known payload of an `<iq type='set'/>`.
pub trait IqSetPayload: TryFrom<Element> + Into<Element> {}
/// Should be implemented on every known payload of an `<iq type='result'/>`.
pub trait IqResultPayload: TryFrom<Element> + Into<Element> {}
2018-08-08 17:52:37 +00:00
/// Represents one of the four possible iq types.
2017-04-23 19:38:13 +00:00
#[derive(Debug, Clone)]
pub enum IqType {
2018-08-08 17:52:37 +00:00
/// This is a request for accessing some data.
Get(Element),
2018-08-08 17:52:37 +00:00
/// This is a request for modifying some data.
Set(Element),
2018-08-08 17:52:37 +00:00
/// This is a result containing some data.
Result(Option<Element>),
2018-08-08 17:52:37 +00:00
/// A get or set request failed.
2017-05-06 20:13:53 +00:00
Error(StanzaError),
2017-04-23 19:38:13 +00:00
}
impl<'a> IntoAttributeValue for &'a IqType {
2017-04-23 19:38:13 +00:00
fn into_attribute_value(self) -> Option<String> {
2018-12-18 14:32:05 +00:00
Some(
match *self {
IqType::Get(_) => "get",
IqType::Set(_) => "set",
IqType::Result(_) => "result",
IqType::Error(_) => "error",
}
.to_owned(),
)
2017-04-23 19:38:13 +00:00
}
}
/// The main structure representing the `<iq/>` stanza.
2017-04-23 19:38:13 +00:00
#[derive(Debug, Clone)]
pub struct Iq {
2018-08-08 17:52:37 +00:00
/// The JID emitting this stanza.
2017-04-23 19:38:13 +00:00
pub from: Option<Jid>,
2018-08-08 17:52:37 +00:00
/// The recipient of this stanza.
2017-04-23 19:38:13 +00:00
pub to: Option<Jid>,
2018-08-08 17:52:37 +00:00
/// The @id attribute of this stanza, which is required in order to match a
/// request with its result/error.
pub id: String,
2018-08-08 17:52:37 +00:00
/// The payload content of this stanza.
2017-04-23 19:38:13 +00:00
pub payload: IqType,
}
2018-05-16 12:49:00 +00:00
impl Iq {
2018-08-08 17:52:37 +00:00
/// Creates an `<iq/>` stanza containing a get request.
pub fn from_get(id: String, payload: impl IqGetPayload) -> Iq {
2018-05-16 12:49:00 +00:00
Iq {
from: None,
to: None,
id,
2018-05-16 12:49:00 +00:00
payload: IqType::Get(payload.into()),
}
}
2018-08-08 17:52:37 +00:00
/// Creates an `<iq/>` stanza containing a set request.
pub fn from_set(id: String, payload: impl IqSetPayload) -> Iq {
2018-05-16 12:49:00 +00:00
Iq {
from: None,
to: None,
id,
2018-05-16 12:49:00 +00:00
payload: IqType::Set(payload.into()),
}
}
2018-08-08 17:52:37 +00:00
/// Creates an `<iq/>` stanza containing a result.
pub fn from_result(id: String, payload: Option<impl IqResultPayload>) -> Iq {
2018-05-16 12:49:00 +00:00
Iq {
from: None,
to: None,
id,
2019-02-21 20:00:58 +00:00
payload: IqType::Result(payload.map(Into::into)),
2018-05-16 12:49:00 +00:00
}
}
2018-08-08 17:52:37 +00:00
/// Creates an `<iq/>` stanza containing an error.
pub fn from_error(id: String, payload: StanzaError) -> Iq {
2018-05-16 12:49:00 +00:00
Iq {
from: None,
to: None,
id,
2018-05-16 12:49:00 +00:00
payload: IqType::Error(payload),
}
}
2018-08-08 17:52:37 +00:00
/// Sets the recipient of this stanza.
2018-05-16 12:49:00 +00:00
pub fn with_to(mut self, to: Jid) -> Iq {
self.to = Some(to);
self
}
2018-08-08 17:52:37 +00:00
/// Sets the emitter of this stanza.
2018-05-16 12:49:00 +00:00
pub fn with_from(mut self, from: Jid) -> Iq {
self.from = Some(from);
self
}
2018-08-08 17:52:37 +00:00
/// Sets the id of this stanza, in order to later match its response.
2018-05-16 12:49:00 +00:00
pub fn with_id(mut self, id: String) -> Iq {
self.id = id;
2018-05-16 12:49:00 +00:00
self
}
}
impl TryFrom<Element> for Iq {
type Err = Error;
2017-04-23 19:38:13 +00:00
fn try_from(root: Element) -> Result<Iq, Error> {
2018-05-14 14:30:28 +00:00
check_self!(root, "iq", DEFAULT_NS);
let from = get_attr!(root, "from", optional);
let to = get_attr!(root, "to", optional);
let id = get_attr!(root, "id", required);
let type_: String = get_attr!(root, "type", required);
2017-05-06 20:16:56 +00:00
let mut payload = None;
let mut error_payload = None;
for elem in root.children() {
if payload.is_some() {
2017-04-23 19:38:13 +00:00
return Err(Error::ParseError("Wrong number of children in iq element."));
}
2017-05-06 20:16:56 +00:00
if type_ == "error" {
if elem.is("error", ns::DEFAULT_NS) {
2017-05-06 20:16:56 +00:00
if error_payload.is_some() {
return Err(Error::ParseError("Wrong number of children in iq element."));
}
error_payload = Some(StanzaError::try_from(elem.clone())?);
} else if root.children().count() != 2 {
2017-05-06 20:16:56 +00:00
return Err(Error::ParseError("Wrong number of children in iq element."));
}
2017-04-23 20:12:27 +00:00
} else {
2017-05-18 23:07:51 +00:00
payload = Some(elem.clone());
2017-05-06 20:16:56 +00:00
}
2017-04-23 19:38:13 +00:00
}
2017-05-06 20:16:56 +00:00
let type_ = if type_ == "get" {
2017-05-18 23:07:51 +00:00
if let Some(payload) = payload {
IqType::Get(payload)
2017-05-06 20:16:56 +00:00
} else {
return Err(Error::ParseError("Wrong number of children in iq element."));
}
} else if type_ == "set" {
2017-05-18 23:07:51 +00:00
if let Some(payload) = payload {
IqType::Set(payload)
2017-05-06 20:16:56 +00:00
} else {
return Err(Error::ParseError("Wrong number of children in iq element."));
}
} else if type_ == "result" {
2017-05-18 23:07:51 +00:00
if let Some(payload) = payload {
IqType::Result(Some(payload))
2017-05-06 20:16:56 +00:00
} else {
IqType::Result(None)
}
} else if type_ == "error" {
if let Some(payload) = error_payload {
2017-05-18 23:07:51 +00:00
IqType::Error(payload)
2017-05-06 20:16:56 +00:00
} else {
return Err(Error::ParseError("Wrong number of children in iq element."));
}
2017-04-23 19:38:13 +00:00
} else {
2017-05-18 23:10:23 +00:00
return Err(Error::ParseError("Unknown iq type."));
2017-05-06 20:16:56 +00:00
};
2017-04-23 19:38:13 +00:00
2017-05-06 20:16:56 +00:00
Ok(Iq {
2019-02-21 20:00:58 +00:00
from,
to,
id,
2017-05-06 20:16:56 +00:00
payload: type_,
})
}
2017-04-23 19:38:13 +00:00
}
impl From<Iq> for Element {
fn from(iq: Iq) -> Element {
2017-05-06 20:16:56 +00:00
let mut stanza = Element::builder("iq")
2018-12-18 14:32:05 +00:00
.ns(ns::DEFAULT_NS)
.attr("from", iq.from)
.attr("to", iq.to)
.attr("id", iq.id)
.attr("type", &iq.payload)
.build();
let elem = match iq.payload {
2018-12-18 14:32:05 +00:00
IqType::Get(elem) | IqType::Set(elem) | IqType::Result(Some(elem)) => elem,
IqType::Error(error) => error.into(),
2017-05-06 20:16:56 +00:00
IqType::Result(None) => return stanza,
};
stanza.append_child(elem);
stanza
}
2017-04-23 19:38:13 +00:00
}
#[cfg(test)]
mod tests {
2017-05-06 20:13:53 +00:00
use super::*;
use crate::util::compare_elements::NamespaceAwareCompare;
use crate::disco::DiscoInfoQuery;
2018-12-18 14:32:05 +00:00
use crate::stanza_error::{DefinedCondition, ErrorType};
2017-04-23 19:38:13 +00:00
2018-10-28 12:10:48 +00:00
#[cfg(target_pointer_width = "32")]
#[test]
fn test_size() {
assert_size!(IqType, 108);
assert_size!(Iq, 192);
}
#[cfg(target_pointer_width = "64")]
#[test]
fn test_size() {
assert_size!(IqType, 216);
assert_size!(Iq, 384);
}
2017-04-23 19:38:13 +00:00
#[test]
fn test_require_type() {
#[cfg(not(feature = "component"))]
2017-04-23 19:38:13 +00:00
let elem: Element = "<iq xmlns='jabber:client'/>".parse().unwrap();
#[cfg(feature = "component")]
let elem: Element = "<iq xmlns='jabber:component:accept'/>".parse().unwrap();
let error = Iq::try_from(elem).unwrap_err();
2017-04-23 19:38:13 +00:00
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Required attribute 'id' missing.");
#[cfg(not(feature = "component"))]
let elem: Element = "<iq xmlns='jabber:client' id='coucou'/>".parse().unwrap();
#[cfg(feature = "component")]
let elem: Element = "<iq xmlns='jabber:component:accept' id='coucou'/>".parse().unwrap();
let error = Iq::try_from(elem).unwrap_err();
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Required attribute 'type' missing.");
2017-04-23 19:38:13 +00:00
}
#[test]
fn test_get() {
#[cfg(not(feature = "component"))]
let elem: Element = "<iq xmlns='jabber:client' type='get' id='foo'>
<foo xmlns='bar'/>
2018-12-18 14:32:05 +00:00
</iq>"
.parse()
.unwrap();
#[cfg(feature = "component")]
let elem: Element = "<iq xmlns='jabber:component:accept' type='get' id='foo'>
<foo xmlns='bar'/>
2018-12-18 14:32:05 +00:00
</iq>"
.parse()
.unwrap();
let iq = Iq::try_from(elem).unwrap();
let query: Element = "<foo xmlns='bar'/>".parse().unwrap();
2017-04-23 19:38:13 +00:00
assert_eq!(iq.from, None);
assert_eq!(iq.to, None);
assert_eq!(&iq.id, "foo");
2017-04-23 19:38:13 +00:00
assert!(match iq.payload {
IqType::Get(element) => element.compare_to(&query),
2018-12-18 14:32:05 +00:00
_ => false,
2017-04-23 19:38:13 +00:00
});
}
#[test]
fn test_set() {
#[cfg(not(feature = "component"))]
let elem: Element = "<iq xmlns='jabber:client' type='set' id='vcard'>
2017-04-23 19:38:13 +00:00
<vCard xmlns='vcard-temp'/>
2018-12-18 14:32:05 +00:00
</iq>"
.parse()
.unwrap();
#[cfg(feature = "component")]
let elem: Element = "<iq xmlns='jabber:component:accept' type='set' id='vcard'>
<vCard xmlns='vcard-temp'/>
2018-12-18 14:32:05 +00:00
</iq>"
.parse()
.unwrap();
let iq = Iq::try_from(elem).unwrap();
2017-04-23 19:38:13 +00:00
let vcard: Element = "<vCard xmlns='vcard-temp'/>".parse().unwrap();
assert_eq!(iq.from, None);
assert_eq!(iq.to, None);
assert_eq!(&iq.id, "vcard");
2017-04-23 19:38:13 +00:00
assert!(match iq.payload {
IqType::Set(element) => element.compare_to(&vcard),
2018-12-18 14:32:05 +00:00
_ => false,
2017-04-23 19:38:13 +00:00
});
}
#[test]
fn test_result_empty() {
#[cfg(not(feature = "component"))]
let elem: Element = "<iq xmlns='jabber:client' type='result' id='res'/>".parse().unwrap();
#[cfg(feature = "component")]
let elem: Element = "<iq xmlns='jabber:component:accept' type='result' id='res'/>"
2018-12-18 14:32:05 +00:00
.parse()
.unwrap();
let iq = Iq::try_from(elem).unwrap();
2017-04-23 19:38:13 +00:00
assert_eq!(iq.from, None);
assert_eq!(iq.to, None);
assert_eq!(&iq.id, "res");
2017-04-23 19:38:13 +00:00
assert!(match iq.payload {
2017-05-06 20:16:56 +00:00
IqType::Result(None) => true,
2017-04-23 19:38:13 +00:00
_ => false,
});
}
#[test]
fn test_result() {
#[cfg(not(feature = "component"))]
let elem: Element = "<iq xmlns='jabber:client' type='result' id='res'>
2017-04-23 19:38:13 +00:00
<query xmlns='http://jabber.org/protocol/disco#items'/>
2018-12-18 14:32:05 +00:00
</iq>"
.parse()
.unwrap();
#[cfg(feature = "component")]
let elem: Element = "<iq xmlns='jabber:component:accept' type='result' id='res'>
<query xmlns='http://jabber.org/protocol/disco#items'/>
2018-12-18 14:32:05 +00:00
</iq>"
.parse()
.unwrap();
let iq = Iq::try_from(elem).unwrap();
2018-12-18 14:32:05 +00:00
let query: Element = "<query xmlns='http://jabber.org/protocol/disco#items'/>"
.parse()
.unwrap();
2017-04-23 19:38:13 +00:00
assert_eq!(iq.from, None);
assert_eq!(iq.to, None);
assert_eq!(&iq.id, "res");
2017-04-23 19:38:13 +00:00
assert!(match iq.payload {
IqType::Result(Some(element)) => element.compare_to(&query),
2017-04-23 19:38:13 +00:00
_ => false,
});
}
#[test]
fn test_error() {
#[cfg(not(feature = "component"))]
let elem: Element = "<iq xmlns='jabber:client' type='error' id='err1'>
2017-04-23 19:38:13 +00:00
<ping xmlns='urn:xmpp:ping'/>
<error type='cancel'>
<service-unavailable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
</error>
2018-12-18 14:32:05 +00:00
</iq>"
.parse()
.unwrap();
#[cfg(feature = "component")]
let elem: Element = "<iq xmlns='jabber:component:accept' type='error' id='err1'>
<ping xmlns='urn:xmpp:ping'/>
<error type='cancel'>
<service-unavailable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
</error>
2018-12-18 14:32:05 +00:00
</iq>"
.parse()
.unwrap();
let iq = Iq::try_from(elem).unwrap();
2017-04-23 19:38:13 +00:00
assert_eq!(iq.from, None);
assert_eq!(iq.to, None);
assert_eq!(iq.id, "err1");
2017-05-01 00:23:56 +00:00
match iq.payload {
2017-05-06 20:16:56 +00:00
IqType::Error(error) => {
2017-05-06 20:13:53 +00:00
assert_eq!(error.type_, ErrorType::Cancel);
assert_eq!(error.by, None);
2018-12-18 14:32:05 +00:00
assert_eq!(
error.defined_condition,
DefinedCondition::ServiceUnavailable
);
assert_eq!(error.texts.len(), 0);
assert_eq!(error.other, None);
2018-12-18 14:32:05 +00:00
}
2017-05-01 00:23:56 +00:00
_ => panic!(),
}
2017-04-23 19:38:13 +00:00
}
#[test]
fn test_children_invalid() {
#[cfg(not(feature = "component"))]
let elem: Element = "<iq xmlns='jabber:client' type='error' id='error'/>"
2018-12-18 14:32:05 +00:00
.parse()
.unwrap();
#[cfg(feature = "component")]
let elem: Element = "<iq xmlns='jabber:component:accept' type='error' id='error'/>"
2018-12-18 14:32:05 +00:00
.parse()
.unwrap();
let error = Iq::try_from(elem).unwrap_err();
2017-04-23 19:38:13 +00:00
let message = match error {
Error::ParseError(string) => string,
_ => panic!(),
};
assert_eq!(message, "Wrong number of children in iq element.");
}
#[test]
fn test_serialise() {
#[cfg(not(feature = "component"))]
let elem: Element = "<iq xmlns='jabber:client' type='result' id='res'/>".parse().unwrap();
#[cfg(feature = "component")]
let elem: Element = "<iq xmlns='jabber:component:accept' type='result' id='res'/>"
2018-12-18 14:32:05 +00:00
.parse()
.unwrap();
2017-05-06 20:16:56 +00:00
let iq2 = Iq {
2017-04-23 19:38:13 +00:00
from: None,
to: None,
id: String::from("res"),
2017-05-06 20:16:56 +00:00
payload: IqType::Result(None),
2017-04-23 19:38:13 +00:00
};
let elem2 = iq2.into();
2017-04-23 19:38:13 +00:00
assert_eq!(elem, elem2);
}
2017-04-23 20:12:27 +00:00
#[test]
fn test_disco() {
#[cfg(not(feature = "component"))]
let elem: Element = "<iq xmlns='jabber:client' type='get' id='disco'><query xmlns='http://jabber.org/protocol/disco#info'/></iq>".parse().unwrap();
#[cfg(feature = "component")]
let elem: Element = "<iq xmlns='jabber:component:accept' type='get' id='disco'><query xmlns='http://jabber.org/protocol/disco#info'/></iq>".parse().unwrap();
let iq = Iq::try_from(elem).unwrap();
let disco_info = match iq.payload {
IqType::Get(payload) => DiscoInfoQuery::try_from(payload).unwrap(),
_ => panic!(),
};
assert!(disco_info.node.is_none());
2017-04-23 20:12:27 +00:00
}
2017-04-23 19:38:13 +00:00
}