libdav/
xmlutils.rs

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
// Copyright 2023-2024 Hugo Osvaldo Barrera
//
// SPDX-License-Identifier: EUPL-1.2

//! Utilities for handling XML data.
use std::borrow::Cow;
use std::str::FromStr;

use http::status::InvalidStatusCode;
use http::StatusCode;
use percent_encoding::percent_encode;
use percent_encoding::{percent_decode_str, AsciiSet, NON_ALPHANUMERIC};
use roxmltree::Node;

use crate::dav::{check_status, WebDavError};
use crate::names;
use crate::PropertyName;

/// Characters that are escaped for hrefs.
pub const DISALLOWED_FOR_HREF: &AsciiSet = &NON_ALPHANUMERIC.remove(b'/').remove(b'.');

/// Check all the statuses in a `multistatus` response.
///
/// # Errors
///
/// - If any of the `<DAV:status>` nodes is missing the status text, returns
///   [`WebDavError::InvalidResponse`].
///
/// - If the text inside a `<DAV:status>` node is not a valid status line, returns
///   [`WebDavError::InvalidStatusCode`].
///
/// - If any of the statuses are non-success, returns [`WebDavError::BadStatusCode`].
pub fn check_multistatus(root: Node) -> Result<(), WebDavError> {
    let statuses = root
        .descendants()
        .filter(|node| node.tag_name() == names::STATUS);
    for status in statuses {
        let status = status.text().ok_or(WebDavError::InvalidResponse(
            "missing text inside 'DAV:status'".into(),
        ))?;
        check_status(parse_statusline(status)?)?;
    }

    Ok(())
}

/// Parses a status line string into a [`StatusCode`].
///
/// Example input string: `HTTP/1.1 200 OK`.
///
/// # See also
///
/// - The [status element](https://www.rfc-editor.org/rfc/rfc2518#section-12.9.1.2)
/// - [Status-Line](https://www.rfc-editor.org/rfc/rfc2068#section-6.1)
///
/// # Errors
///
/// If the input string does not match a status line.
pub fn parse_statusline(status_line: impl AsRef<str>) -> Result<StatusCode, InvalidStatusCode> {
    let mut iter = status_line.as_ref().splitn(3, ' ');
    iter.next();
    let code = iter.next().unwrap_or("");
    StatusCode::from_str(code)
}

/// Render an empty XML node.
pub(crate) fn render_xml(name: &PropertyName) -> String {
    format!("<{0} xmlns=\"{1}\"/>", name.name(), name.namespace())
}

/// Render an XML node with optional text.
pub fn render_xml_with_text(name: &PropertyName, text: Option<impl AsRef<str>>) -> String {
    match text {
        None => format!("<{0} xmlns=\"{1}\"/>", name.name(), name.namespace()),
        Some(t) => format!(
            "<{0} xmlns=\"{1}\">{2}</{0}>",
            name.name(),
            name.namespace(),
            escape_text(t.as_ref())
        ),
    }
}

/// Replaces characters that need to be escaped in texts.
///
/// `<` --> `&lt;`
/// `>` --> `&gt;`
/// `&` --> `&amp;`
///
/// This IS NOT usable in other contexts of XML encoding.
#[must_use]
#[allow(clippy::missing_panics_doc)]
pub fn escape_text(raw: &str) -> Cow<str> {
    // This function is strongly based on `escape_partial` from `quick-xml`:
    {
        // The MIT License (MIT)
        //
        // Copyright (c) 2016 Johann Tuffe
        //
        // Permission is hereby granted, free of charge, to any person obtaining a copy
        // of this software and associated documentation files (the "Software"), to deal
        // in the Software without restriction, including without limitation the rights
        // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        // copies of the Software, and to permit persons to whom the Software is
        // furnished to do so, subject to the following conditions:
        //
        //
        // The above copyright notice and this permission notice shall be included in
        // all copies or substantial portions of the Software.
        //
        //
        // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
        // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        // THE SOFTWARE.
        let bytes = raw.as_bytes();
        let mut escaped = None;
        let mut iter = bytes.iter();
        let mut pos = 0;
        while let Some(i) = iter.position(|&b| matches!(b, b'<' | b'>' | b'&')) {
            let escaped = escaped.get_or_insert_with(|| Vec::with_capacity(raw.len()));
            let new_pos = pos + i;
            escaped.extend_from_slice(&bytes[pos..new_pos]);
            match bytes[new_pos] {
                b'<' => escaped.extend_from_slice(b"&lt;"),
                b'>' => escaped.extend_from_slice(b"&gt;"),
                b'&' => escaped.extend_from_slice(b"&amp;"),
                _ => unreachable!("Only '<', '>' and '&', are escaped"),
            }
            pos = new_pos + 1;
        }

        if let Some(mut escaped) = escaped {
            if let Some(raw) = bytes.get(pos..) {
                escaped.extend_from_slice(raw);
            }
            Cow::Owned(
                String::from_utf8(escaped).expect("manually escaped string must be valid utf-8"),
            )
            // The above is equivalent to the following:
            // SAFETY: we operate on UTF-8 input and search for an one byte chars only,
            // so all slices that were put into `escaped` are valid UTF-8 encoded strings.
            // Cow::Owned(unsafe { String::from_utf8_unchecked(escaped) })
        } else {
            Cow::Borrowed(raw)
        }
    }
    // End copied code.
}

/// Find an `href` node and return its unescaped text value.
pub(crate) fn get_unquoted_href<'a>(node: &'a Node) -> Result<Cow<'a, str>, WebDavError> {
    Ok(node
        .descendants()
        .find(|node| node.tag_name() == crate::names::HREF)
        .ok_or(WebDavError::InvalidResponse(
            "missing href in response".into(),
        ))?
        .text()
        .map(percent_decode_str)
        .ok_or(WebDavError::InvalidResponse("missing text in href".into()))?
        .decode_utf8()?)
}

// URL-encodes an href.
//
// Obviously the input parameter MUST NOT be url-encoded.
pub(crate) fn quote_href(href: &[u8]) -> Cow<'_, str> {
    Cow::from(percent_encode(href, DISALLOWED_FOR_HREF))
}

#[inline]
pub(crate) fn get_newline_corrected_text(
    node: &Node,
    property: &PropertyName<'_, '_>,
) -> Result<String, WebDavError> {
    node.descendants()
        .find(|node| node.tag_name() == *property)
        .ok_or(WebDavError::InvalidResponse(
            format!("missing {} in response", property.name()).into(),
        ))?
        .text()
        .ok_or(WebDavError::InvalidResponse(
            format!("missing text in property {property:?}").into(),
        ))
        // "\r\n" is usually converted into "\n" during parsing. This needs to be undone.
        //
        // See: https://github.com/RazrFalcon/roxmltree/issues/102
        // See: https://www.w3.org/TR/xml/#sec-line-ends
        // See: https://www.rfc-editor.org/rfc/rfc4791#section-9.6
        .map(normalise_newlines)
}

/// Normalise newlines by replacing any `\n` with `\r\n`.
///
/// # Examples
///
/// ```rust
/// # use libdav::xmlutils::normalise_newlines;
/// // These inputs return the same value unchanged:
/// assert_eq!(normalise_newlines("hello\r\nworld"), "hello\r\nworld");
/// assert_eq!(normalise_newlines("hello\r\r\nworld"),  "hello\r\r\nworld");
/// assert_eq!(normalise_newlines("hello\rworld"), "hello\rworld");
/// assert_eq!(normalise_newlines("hello\r\nworld\r\n"), "hello\r\nworld\r\n");
/// // These add a missing \r:
/// assert_eq!(normalise_newlines("hello\nworld"), "hello\r\nworld");
/// assert_eq!(normalise_newlines("hello\r\nworld\n"), "hello\r\nworld\r\n");
/// ```
#[must_use]
pub fn normalise_newlines(orig: &str) -> String {
    let mut result = String::new();
    let mut last_end = 0;
    for (start, part) in orig.match_indices('\n') {
        let line = &orig[last_end..start];
        result.push_str(line.strip_suffix('\r').unwrap_or(line));
        result.push_str("\r\n");
        last_end = start + part.len();
    }
    result.push_str(&orig[last_end..orig.len()]);
    result
}

#[cfg(test)]
mod test {
    use std::borrow::Cow;

    use crate::{
        names,
        xmlutils::{escape_text, get_newline_corrected_text},
    };

    #[test]
    fn test_escape_text() {
        match escape_text("HELLO THERE") {
            Cow::Borrowed(s) => assert_eq!(s, "HELLO THERE"),
            Cow::Owned(_) => panic!("expected Borrowed, got Owned"),
        }
        match escape_text("HELLO <") {
            Cow::Borrowed(_) => panic!("expected Owned, got Borrowed"),
            Cow::Owned(s) => assert_eq!(s, "HELLO &lt;"),
        }
        match escape_text("HELLO &lt;") {
            Cow::Borrowed(_) => panic!("expected Owned, got Borrowed"),
            Cow::Owned(s) => assert_eq!(s, "HELLO &amp;lt;"),
        }
        match escape_text("你吃过了吗?") {
            Cow::Borrowed(s) => assert_eq!(s, "你吃过了吗?"),
            Cow::Owned(_) => panic!("expected Borrowed, got Owned"),
        }
    }

    #[test]
    fn test_get_newline_corrected_text_without_returns() {
        let without_returns ="<ns0:multistatus xmlns:ns0=\"DAV:\" xmlns:ns1=\"urn:ietf:params:xml:ns:caldav\"><ns0:response><ns0:href>/user/calendars/qdBEnN9jwjQFLry4/1ehsci7nhH31.ics</ns0:href><ns0:propstat><ns0:status>HTTP/1.1 200 OK</ns0:status><ns0:prop><ns0:getetag>\"2d2c827debd802fb3844309b53254b90dd7fd900\"</ns0:getetag><ns1:calendar-data>BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//hacksw/handcal//NONSGML v1.0//EN\nBEGIN:VEVENT\nSUMMARY:hello\\, testing\nDTSTART:19970714T170000Z\nDTSTAMP:19970610T172345Z\nUID:92gDWceCowpO\nEND:VEVENT\nEND:VCALENDAR\n</ns1:calendar-data></ns0:prop></ns0:propstat></ns0:response></ns0:multistatus>";
        let expected = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//hacksw/handcal//NONSGML v1.0//EN\r\nBEGIN:VEVENT\r\nSUMMARY:hello\\, testing\r\nDTSTART:19970714T170000Z\r\nDTSTAMP:19970610T172345Z\r\nUID:92gDWceCowpO\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";

        let doc = roxmltree::Document::parse(without_returns).unwrap();
        let responses = doc
            .root_element()
            .descendants()
            .find(|node| node.tag_name() == names::RESPONSE)
            .unwrap();
        assert_eq!(
            get_newline_corrected_text(&responses, &names::CALENDAR_DATA).unwrap(),
            expected
        );
    }

    #[test]
    fn test_get_newline_corrected_text_with_returns() {
        let with_returns= "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<multistatus xmlns=\"DAV:\" xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n  <response>\n    <href>/dav/calendars/user/vdirsyncer@fastmail.com/UvrlExcG9Jp0gEzQ/2H8kQfNQj8GP.ics</href>\n    <propstat>\n      <prop>\n        <getetag>\"4d92fc1c8bdc18bbf83caf34eeab7e7167eb292e\"</getetag>\n        <C:calendar-data><![CDATA[BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//hacksw/handcal//NONSGML v1.0//EN\r\nBEGIN:VEVENT\r\nUID:jSayX7OSdp3V\r\nDTSTAMP:19970610T172345Z\r\nDTSTART:19970714T170000Z\r\nSUMMARY:hello\\, testing\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n]]></C:calendar-data>\n      </prop>\n      <status>HTTP/1.1 200 OK</status>\n    </propstat>\n  </response>\n</multistatus>\n";
        let expected = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//hacksw/handcal//NONSGML v1.0//EN\r\nBEGIN:VEVENT\r\nUID:jSayX7OSdp3V\r\nDTSTAMP:19970610T172345Z\r\nDTSTART:19970714T170000Z\r\nSUMMARY:hello\\, testing\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";

        let doc = roxmltree::Document::parse(with_returns).unwrap();
        let responses = doc
            .root_element()
            .descendants()
            .find(|node| node.tag_name() == names::RESPONSE)
            .unwrap();
        assert_eq!(
            get_newline_corrected_text(&responses, &names::CALENDAR_DATA).unwrap(),
            expected
        );
    }
}