Skip to main content

rocket/serde/
xml.rs

1//! Automatic XML (de)serialization support.
2//!
3//! See [`Xml`] for details.
4//!
5//! # Enabling
6//!
7//! This module is only available when the `xml` feature is enabled. Enable it
8//! in `Cargo.toml` as follows:
9//!
10//! ```toml
11//! [dependencies.rocket]
12//! version = "=0.6.0-rc.1"
13//! features = ["xml"]
14//! ```
15//!
16//! # Testing
17//!
18//! The [`LocalRequest`] and [`LocalResponse`] types provide [`xml()`] and
19//! [`into_xml()`] methods to create a request with serialized XML and
20//! deserialize a response as XML, respectively.
21//!
22//! [`LocalRequest`]: crate::local::blocking::LocalRequest
23//! [`LocalResponse`]: crate::local::blocking::LocalResponse
24//! [`xml()`]: crate::local::blocking::LocalRequest::xml()
25//! [`into_xml()`]: crate::local::blocking::LocalResponse::into_xml()
26
27use std::{io, fmt, error};
28use std::ops::{Deref, DerefMut};
29
30use crate::request::{Request, local_cache};
31use crate::data::{Limits, Data, FromData, Outcome};
32use crate::response::{self, Responder, content};
33use crate::form::prelude as form;
34use crate::http::uri::fmt::{UriDisplay, FromUriParam, Query, Formatter as UriFormatter};
35use crate::http::Status;
36
37use serde::{Serialize, Deserialize};
38
39#[doc(hidden)]
40pub use quick_xml;
41
42/// The XML guard: easily consume and return XML.
43///
44/// ## Sending XML
45///
46/// To respond with serialized XML data, return a `Xml<T>` type, where `T`
47/// implements [`Serialize`] from [`serde`]. The content type of the response is
48/// set to `text/xml; charset=utf-8` automatically.
49///
50/// ```rust
51/// # #[macro_use] extern crate rocket;
52/// use rocket::serde::{Serialize, xml::Xml};
53///
54/// #[derive(Serialize)]
55/// #[serde(crate = "rocket::serde")]
56/// struct User {
57///     id: usize,
58/// }
59///
60/// #[get("/users/<id>")]
61/// fn user(id: usize) -> Xml<User> {
62///     let user_from_id = User { id };
63///     /* ... */
64///     Xml(user_from_id)
65/// }
66/// ```
67///
68/// XML requires a root element, so `T` must serialize as a named element, such
69/// as a struct or enum. Values without a name, like integers, strings,
70/// sequences, and tuples, fail to serialize, resulting in a `500` response.
71///
72/// ## Receiving XML
73///
74/// `Xml` is both a data guard and a form guard.
75///
76/// ### Data Guard
77///
78/// To deserialize request body data as XML , add a `data` route argument with
79/// a target type of `Xml<T>`, where `T` is some type you'd like to parse from
80/// XML. `T` must implement [`serde::Deserialize`].
81///
82/// ```rust
83/// # #[macro_use] extern crate rocket;
84/// # use rocket::serde::Deserialize;
85/// # #[derive(Deserialize)]
86/// # #[serde(crate = "rocket::serde")]
87/// # struct User { id: usize }
88/// use rocket::serde::xml::Xml;
89///
90/// #[post("/user", format = "xml", data = "<user>")]
91/// fn new_user(user: Xml<User>) {
92///     /* ... */
93/// }
94/// ```
95///
96/// The name of the root element is not checked: `<Other>...</Other>`
97/// deserializes into a `User` just as `<User>...</User>` does.
98///
99/// You don't _need_ to use `format = "xml"`, but it _may_ be what you want.
100/// Using `format = xml` means that any request that doesn't specify
101/// "text/xml" as its `Content-Type` header value will not be routed to
102/// the handler. Use `format = "*/xml"` to accept both `text/xml` and
103/// `application/xml`.
104///
105/// ### Form Guard
106///
107/// `Xml<T>`, as a form guard, accepts value and data fields and parses the
108/// data as a `T`. Simple use `Xml<T>`:
109///
110/// ```rust
111/// # #[macro_use] extern crate rocket;
112/// # use rocket::serde::Deserialize;
113/// # #[derive(Deserialize)]
114/// # #[serde(crate = "rocket::serde")]
115/// # struct Metadata { version: usize }
116/// use rocket::form::{Form, FromForm};
117/// use rocket::serde::xml::Xml;
118///
119/// #[derive(FromForm)]
120/// struct User<'r> {
121///     name: &'r str,
122///     metadata: Xml<Metadata>
123/// }
124///
125/// #[post("/user", data = "<form>")]
126/// fn new_user(form: Form<User<'_>>) {
127///     /* ... */
128/// }
129/// ```
130///
131/// ### Incoming Data Limits
132///
133/// The default size limit for incoming XML data is 1MiB. Setting a limit
134/// protects your application from denial of service (DoS) attacks and from
135/// resource exhaustion through high memory consumption. The limit can be
136/// increased by setting the `limits.xml` configuration parameter. For
137/// instance, to increase the XML limit to 5MiB for all environments, you may
138/// add the following to your `Rocket.toml`:
139///
140/// ```toml
141/// [global.limits]
142/// xml = 5242880
143/// ```
144#[repr(transparent)]
145#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
146pub struct Xml<T>(pub T);
147
148/// Error returned by the [`Xml`] guard when XML deserialization fails.
149#[derive(Debug)]
150pub enum Error<'a> {
151    /// An I/O error occurred while reading the incoming request data.
152    Io(io::Error),
153
154    /// The client's data was received successfully but failed to parse as valid
155    /// XML or as the requested type. The `&str` value in `.0` is the raw data
156    /// received from the user, while the `Error` in `.1` is the deserialization
157    /// error from `quick_xml`.
158    Parse(&'a str, quick_xml::DeError),
159}
160
161impl<'a> fmt::Display for Error<'a> {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        match self {
164            Self::Io(err) => write!(f, "i/o error: {}", err),
165            Self::Parse(_, err) => write!(f, "parse error: {}", err),
166        }
167    }
168}
169
170impl<'a> error::Error for Error<'a> {
171    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
172        match self {
173            Self::Io(err) => Some(err),
174            Self::Parse(_, err) => Some(err),
175        }
176    }
177}
178
179impl<T> Xml<T> {
180    /// Consumes the XML wrapper and returns the wrapped item.
181    ///
182    /// # Example
183    /// ```rust
184    /// # use rocket::serde::xml::Xml;
185    /// let string = "Hello".to_string();
186    /// let my_xml = Xml(string);
187    /// assert_eq!(my_xml.into_inner(), "Hello".to_string());
188    /// ```
189    #[inline(always)]
190    pub fn into_inner(self) -> T {
191        self.0
192    }
193}
194
195impl<'r, T: Deserialize<'r>> Xml<T> {
196    fn from_str(s: &'r str) -> Result<Self, Error<'r>> {
197        from_str(s).map(Xml).map_err(|e| Error::Parse(s, e))
198    }
199
200    async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> Result<Self, Error<'r>> {
201        let limit = req.limits().get("xml").unwrap_or(Limits::XML);
202        let string = match data.open(limit).into_string().await {
203            Ok(s) if s.is_complete() => s.into_inner(),
204            Ok(_) => {
205                let eof = io::ErrorKind::UnexpectedEof;
206                return Err(Error::Io(io::Error::new(eof, "data limit exceeded")));
207            },
208            Err(e) => return Err(Error::Io(e)),
209        };
210
211        Self::from_str(local_cache!(req, string))
212    }
213}
214
215#[crate::async_trait]
216impl<'r, T: Deserialize<'r>> FromData<'r> for Xml<T> {
217    type Error = Error<'r>;
218
219    async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> Outcome<'r, Self> {
220        match Self::from_data(req, data).await {
221            Ok(value) => Outcome::Success(value),
222            Err(Error::Io(e)) if e.kind() == io::ErrorKind::UnexpectedEof => {
223                Outcome::Error((Status::PayloadTooLarge, Error::Io(e)))
224            },
225            Err(e) => Outcome::Error((Status::BadRequest, e)),
226        }
227    }
228}
229
230/// Serializes the wrapped value into XML. Returns a response with Content-Type
231/// XML and a fixed-size body with the serialized value. If serialization
232/// fails, an `Err` of `Status::InternalServerError` is returned.
233impl<'r, T: Serialize> Responder<'r, 'static> for Xml<T> {
234    fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static> {
235        let string = quick_xml::se::to_string(&self.0)
236            .map_err(|e| {
237                error!("XML serialize failure: {}", e);
238                Status::InternalServerError
239            })?;
240
241        content::RawXml(string).respond_to(req)
242    }
243}
244
245impl<T: Serialize> UriDisplay<Query> for Xml<T> {
246    fn fmt(&self, f: &mut UriFormatter<'_, Query>) -> fmt::Result {
247        let string = to_string(&self.0).map_err(|_| fmt::Error)?;
248        f.write_value(&string)
249    }
250}
251
252macro_rules! impl_from_uri_param_from_inner_type {
253    ($($lt:lifetime)?, $T:ty) => (
254        impl<$($lt,)? T: Serialize> FromUriParam<Query, $T> for Xml<T> {
255            type Target = Xml<$T>;
256
257            #[inline(always)]
258            fn from_uri_param(param: $T) -> Self::Target {
259                Xml(param)
260            }
261        }
262    )
263}
264
265impl_from_uri_param_from_inner_type!(, T);
266impl_from_uri_param_from_inner_type!('a, &'a T);
267impl_from_uri_param_from_inner_type!('a, &'a mut T);
268
269crate::http::impl_from_uri_param_identity!([Query] (T: Serialize) Xml<T>);
270
271impl<T> From<T> for Xml<T> {
272    fn from(value: T) -> Self {
273        Xml(value)
274    }
275}
276
277impl<T> Deref for Xml<T> {
278    type Target = T;
279
280    #[inline(always)]
281    fn deref(&self) -> &T {
282        &self.0
283    }
284}
285
286impl<T> DerefMut for Xml<T> {
287    #[inline(always)]
288    fn deref_mut(&mut self) -> &mut T {
289        &mut self.0
290    }
291}
292
293impl From<Error<'_>> for form::Error<'_> {
294    fn from(e: Error<'_>) -> Self {
295        match e {
296            Error::Io(e) => e.into(),
297            Error::Parse(_, e) => form::Error::custom(e)
298        }
299    }
300}
301
302#[crate::async_trait]
303impl<'v, T: Deserialize<'v> + Send> form::FromFormField<'v> for Xml<T> {
304    fn from_value(field: form::ValueField<'v>) -> Result<Self, form::Errors<'v>> {
305        Ok(Self::from_str(field.value)?)
306    }
307
308    async fn from_data(f: form::DataField<'v, '_>) -> Result<Self, form::Errors<'v>> {
309        Ok(Self::from_data(f.request, f.data).await?)
310    }
311}
312
313/// Deserialize an instance of type `T` from a string of XML text.
314///
315/// Elements or non-whitespace text that follow the value in `string` are an
316/// error.
317///
318/// **_Always_ use [`Xml`] to deserialize XML request data.**
319///
320/// # Example
321///
322/// ```
323/// use rocket::serde::{Deserialize, xml};
324///
325/// #[derive(Debug, PartialEq, Deserialize)]
326/// #[serde(crate = "rocket::serde")]
327/// struct Data<'r> {
328///     framework: &'r str,
329///     stars: usize,
330/// }
331///
332/// let string = r#"
333///     <Data>
334///         <framework>Rocket</framework>
335///         <stars>5</stars>
336///     </Data>
337/// "#;
338///
339/// let data: Data = xml::from_str(string).unwrap();
340/// assert_eq!(data, Data { framework: "Rocket", stars: 5, });
341/// ```
342///
343/// # Errors
344///
345/// This conversion can fail if the structure of the input does not match the
346/// structure expected by `T`, for example if `T` is a struct type but the input
347/// contains something other than a XML element. It can also fail if the structure
348/// is correct but `T`'s implementation of `Deserialize` decides that something
349/// is wrong with the data, for example required struct fields are missing from
350/// the XML element or some number is too big to fit in the expected primitive
351/// type.
352pub fn from_str<'a, T>(string: &'a str) -> Result<T, quick_xml::DeError>
353    where T: Deserialize<'a>,
354{
355    // `T` may not read all of the input, so check that the rest is blank. This
356    // sees what `quick_xml` deserializes: it can't tell if whitespace was
357    // written as `CDATA` or a character reference, and `quick_xml` skips an XML
358    // declaration that follows the value. Neither carries any data.
359    let mut de = quick_xml::de::Deserializer::from_str(string);
360    let value = T::deserialize(&mut de)?;
361    while !de.is_empty() {
362        Blank::deserialize(&mut de)?;
363    }
364
365    Ok(value)
366}
367
368/// XML whitespace, the only content allowed after a value. Comments and
369/// processing instructions are skipped by `quick_xml`.
370struct Blank;
371
372impl<'de> Deserialize<'de> for Blank {
373    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
374        use serde::de::{self, Visitor, Unexpected};
375
376        struct BlankVisitor;
377
378        impl<'de> Visitor<'de> for BlankVisitor {
379            type Value = Blank;
380
381            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382                f.write_str("end of input")
383            }
384
385            fn visit_str<E: de::Error>(self, v: &str) -> Result<Blank, E> {
386                match v.bytes().all(|b| matches!(b, b' ' | b'\t' | b'\r' | b'\n')) {
387                    true => Ok(Blank),
388                    false => Err(E::invalid_value(Unexpected::Str(v), &self)),
389                }
390            }
391        }
392
393        de.deserialize_any(BlankVisitor)
394    }
395}
396
397/// Serialize a `T` into a XML string with compact representation.
398///
399/// **_Always_ use [`Xml`] to serialize XML response data.**
400///
401/// # Example
402///
403/// ```
404/// use rocket::serde::{Deserialize, Serialize, xml};
405///
406/// #[derive(Debug, PartialEq, Deserialize, Serialize)]
407/// #[serde(crate = "rocket::serde")]
408/// struct Data<'r> {
409///     framework: &'r str,
410///     stars: usize,
411/// }
412///
413/// let data = Data {
414///     framework: "Rocket",
415///     stars: 5,
416/// };
417///
418/// let string = xml::to_string(&data).unwrap();
419/// let data: Data = xml::from_str(&string).unwrap();
420/// assert_eq!(data, Data { framework: "Rocket", stars: 5, });
421/// ```
422///
423/// # Errors
424///
425/// Serialization fails if `T`'s `Serialize` implementation fails.
426#[inline(always)]
427pub fn to_string<T>(value: &T) -> Result<String, quick_xml::SeError>
428    where T: Serialize
429{
430    quick_xml::se::to_string(value)
431}