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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
// Copyright (c) 2017 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
// Copyright (c) 2017 Maxime “pep” Buquet <pep@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;
use jid::Jid;
use minidom::Element;
use minidom::IntoAttributeValue;
use std::convert::TryFrom;

/// 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> {}

/// Represents one of the four possible iq types.
#[derive(Debug, Clone)]
pub enum IqType {
    /// This is a request for accessing some data.
    Get(Element),

    /// This is a request for modifying some data.
    Set(Element),

    /// This is a result containing some data.
    Result(Option<Element>),

    /// A get or set request failed.
    Error(StanzaError),
}

impl<'a> IntoAttributeValue for &'a IqType {
    fn into_attribute_value(self) -> Option<String> {
        Some(
            match *self {
                IqType::Get(_) => "get",
                IqType::Set(_) => "set",
                IqType::Result(_) => "result",
                IqType::Error(_) => "error",
            }
            .to_owned(),
        )
    }
}

/// The main structure representing the `<iq/>` stanza.
#[derive(Debug, Clone)]
pub struct Iq {
    /// The JID emitting this stanza.
    pub from: Option<Jid>,

    /// The recipient of this stanza.
    pub to: Option<Jid>,

    /// The @id attribute of this stanza, which is required in order to match a
    /// request with its result/error.
    pub id: String,

    /// The payload content of this stanza.
    pub payload: IqType,
}

impl Iq {
    /// Creates an `<iq/>` stanza containing a get request.
    pub fn from_get<S: Into<String>>(id: S, payload: impl IqGetPayload) -> Iq {
        Iq {
            from: None,
            to: None,
            id: id.into(),
            payload: IqType::Get(payload.into()),
        }
    }

    /// Creates an `<iq/>` stanza containing a set request.
    pub fn from_set<S: Into<String>>(id: S, payload: impl IqSetPayload) -> Iq {
        Iq {
            from: None,
            to: None,
            id: id.into(),
            payload: IqType::Set(payload.into()),
        }
    }

    /// Creates an `<iq/>` stanza containing a result.
    pub fn from_result<S: Into<String>>(id: S, payload: Option<impl IqResultPayload>) -> Iq {
        Iq {
            from: None,
            to: None,
            id: id.into(),
            payload: IqType::Result(payload.map(Into::into)),
        }
    }

    /// Creates an `<iq/>` stanza containing an error.
    pub fn from_error<S: Into<String>>(id: S, payload: StanzaError) -> Iq {
        Iq {
            from: None,
            to: None,
            id: id.into(),
            payload: IqType::Error(payload),
        }
    }

    /// Sets the recipient of this stanza.
    pub fn with_to(mut self, to: Jid) -> Iq {
        self.to = Some(to);
        self
    }

    /// Sets the emitter of this stanza.
    pub fn with_from(mut self, from: Jid) -> Iq {
        self.from = Some(from);
        self
    }

    /// Sets the id of this stanza, in order to later match its response.
    pub fn with_id(mut self, id: String) -> Iq {
        self.id = id;
        self
    }
}

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

    fn try_from(root: Element) -> Result<Iq, Error> {
        check_self!(root, "iq", DEFAULT_NS);
        let from = get_attr!(root, "from", Option);
        let to = get_attr!(root, "to", Option);
        let id = get_attr!(root, "id", Required);
        let type_: String = get_attr!(root, "type", Required);

        let mut payload = None;
        let mut error_payload = None;
        for elem in root.children() {
            if payload.is_some() {
                return Err(Error::ParseError("Wrong number of children in iq element."));
            }
            if type_ == "error" {
                if elem.is("error", ns::DEFAULT_NS) {
                    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 {
                    return Err(Error::ParseError("Wrong number of children in iq element."));
                }
            } else {
                payload = Some(elem.clone());
            }
        }

        let type_ = if type_ == "get" {
            if let Some(payload) = payload {
                IqType::Get(payload)
            } else {
                return Err(Error::ParseError("Wrong number of children in iq element."));
            }
        } else if type_ == "set" {
            if let Some(payload) = payload {
                IqType::Set(payload)
            } else {
                return Err(Error::ParseError("Wrong number of children in iq element."));
            }
        } else if type_ == "result" {
            if let Some(payload) = payload {
                IqType::Result(Some(payload))
            } else {
                IqType::Result(None)
            }
        } else if type_ == "error" {
            if let Some(payload) = error_payload {
                IqType::Error(payload)
            } else {
                return Err(Error::ParseError("Wrong number of children in iq element."));
            }
        } else {
            return Err(Error::ParseError("Unknown iq type."));
        };

        Ok(Iq {
            from,
            to,
            id,
            payload: type_,
        })
    }
}

impl From<Iq> for Element {
    fn from(iq: Iq) -> Element {
        let mut stanza = Element::builder("iq")
            .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 {
            IqType::Get(elem) | IqType::Set(elem) | IqType::Result(Some(elem)) => elem,
            IqType::Error(error) => error.into(),
            IqType::Result(None) => return stanza,
        };
        stanza.append_child(elem);
        stanza
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::util::compare_elements::NamespaceAwareCompare;
    use crate::disco::DiscoInfoQuery;
    use crate::stanza_error::{DefinedCondition, ErrorType};

    #[cfg(target_pointer_width = "32")]
    #[test]
    fn test_size() {
        assert_size!(IqType, 112);
        assert_size!(Iq, 204);
    }

    #[cfg(target_pointer_width = "64")]
    #[test]
    fn test_size() {
        assert_size!(IqType, 224);
        assert_size!(Iq, 408);
    }

    #[test]
    fn test_require_type() {
        #[cfg(not(feature = "component"))]
        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();
        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.");
    }

    #[test]
    fn test_get() {
        #[cfg(not(feature = "component"))]
        let elem: Element = "<iq xmlns='jabber:client' type='get' id='foo'>
            <foo xmlns='bar'/>
        </iq>"
            .parse()
            .unwrap();
        #[cfg(feature = "component")]
        let elem: Element = "<iq xmlns='jabber:component:accept' type='get' id='foo'>
            <foo xmlns='bar'/>
        </iq>"
            .parse()
            .unwrap();
        let iq = Iq::try_from(elem).unwrap();
        let query: Element = "<foo xmlns='bar'/>".parse().unwrap();
        assert_eq!(iq.from, None);
        assert_eq!(iq.to, None);
        assert_eq!(&iq.id, "foo");
        assert!(match iq.payload {
            IqType::Get(element) => element.compare_to(&query),
            _ => false,
        });
    }

    #[test]
    fn test_set() {
        #[cfg(not(feature = "component"))]
        let elem: Element = "<iq xmlns='jabber:client' type='set' id='vcard'>
            <vCard xmlns='vcard-temp'/>
        </iq>"
            .parse()
            .unwrap();
        #[cfg(feature = "component")]
        let elem: Element = "<iq xmlns='jabber:component:accept' type='set' id='vcard'>
            <vCard xmlns='vcard-temp'/>
        </iq>"
            .parse()
            .unwrap();
        let iq = Iq::try_from(elem).unwrap();
        let vcard: Element = "<vCard xmlns='vcard-temp'/>".parse().unwrap();
        assert_eq!(iq.from, None);
        assert_eq!(iq.to, None);
        assert_eq!(&iq.id, "vcard");
        assert!(match iq.payload {
            IqType::Set(element) => element.compare_to(&vcard),
            _ => false,
        });
    }

    #[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'/>"
            .parse()
            .unwrap();
        let iq = Iq::try_from(elem).unwrap();
        assert_eq!(iq.from, None);
        assert_eq!(iq.to, None);
        assert_eq!(&iq.id, "res");
        assert!(match iq.payload {
            IqType::Result(None) => true,
            _ => false,
        });
    }

    #[test]
    fn test_result() {
        #[cfg(not(feature = "component"))]
        let elem: Element = "<iq xmlns='jabber:client' type='result' id='res'>
            <query xmlns='http://jabber.org/protocol/disco#items'/>
        </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'/>
        </iq>"
            .parse()
            .unwrap();
        let iq = Iq::try_from(elem).unwrap();
        let query: Element = "<query xmlns='http://jabber.org/protocol/disco#items'/>"
            .parse()
            .unwrap();
        assert_eq!(iq.from, None);
        assert_eq!(iq.to, None);
        assert_eq!(&iq.id, "res");
        assert!(match iq.payload {
            IqType::Result(Some(element)) => element.compare_to(&query),
            _ => false,
        });
    }

    #[test]
    fn test_error() {
        #[cfg(not(feature = "component"))]
        let elem: Element = "<iq xmlns='jabber:client' type='error' id='err1'>
            <ping xmlns='urn:xmpp:ping'/>
            <error type='cancel'>
                <service-unavailable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
            </error>
        </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>
        </iq>"
            .parse()
            .unwrap();
        let iq = Iq::try_from(elem).unwrap();
        assert_eq!(iq.from, None);
        assert_eq!(iq.to, None);
        assert_eq!(iq.id, "err1");
        match iq.payload {
            IqType::Error(error) => {
                assert_eq!(error.type_, ErrorType::Cancel);
                assert_eq!(error.by, None);
                assert_eq!(
                    error.defined_condition,
                    DefinedCondition::ServiceUnavailable
                );
                assert_eq!(error.texts.len(), 0);
                assert_eq!(error.other, None);
            }
            _ => panic!(),
        }
    }

    #[test]
    fn test_children_invalid() {
        #[cfg(not(feature = "component"))]
        let elem: Element = "<iq xmlns='jabber:client' type='error' id='error'/>"
            .parse()
            .unwrap();
        #[cfg(feature = "component")]
        let elem: Element = "<iq xmlns='jabber:component:accept' type='error' id='error'/>"
            .parse()
            .unwrap();
        let error = Iq::try_from(elem).unwrap_err();
        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'/>"
            .parse()
            .unwrap();
        let iq2 = Iq {
            from: None,
            to: None,
            id: String::from("res"),
            payload: IqType::Result(None),
        };
        let elem2 = iq2.into();
        assert_eq!(elem, elem2);
    }

    #[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());
    }
}