curlite 0.2.1

Small blocking HTTP client on top of libcurl: forms, multipart and raw bodies without an async runtime
Documentation
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use bytes::Bytes;
use http::StatusCode;
use http::header::{CONTENT_DISPOSITION, CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue};
use mime::{BOUNDARY, Mime};

use crate::error::{Error, Result};

/// A response, read completely into memory (or, for [`Request::send_to`],
/// with the body already written out).
///
/// [`Request::send_to`]: crate::Request::send_to
#[derive(Debug, Clone)]
pub struct Response {
    pub(crate) url: String,
    pub(crate) status: StatusCode,
    pub(crate) headers: HeaderMap,
    pub(crate) body: Bytes,
}

/// One part of a `multipart/*` response body, see [`Response::parts`].
#[derive(Debug, Clone)]
pub struct ResponsePart {
    /// The `name` of the part's `Content-Disposition`, empty if absent.
    pub name: String,
    /// The `filename` of the part's `Content-Disposition`.
    pub filename: Option<String>,
    /// The part's `Content-Type`, if it has one.
    pub content_type: Option<Mime>,
    /// The part's body, sharing the response buffer.
    pub body: Bytes,
}

impl Response {
    /// The URL the response came from: the request's, or the last
    /// redirect's when redirects were followed.
    pub fn url(&self) -> &str {
        &self.url
    }

    pub fn status(&self) -> StatusCode {
        self.status
    }

    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    /// The body. Cloning the returned `Bytes` shares the buffer.
    pub fn body(&self) -> &Bytes {
        &self.body
    }

    pub fn into_body(self) -> Bytes {
        self.body
    }

    /// The body as a string, if it is valid UTF-8.
    pub fn text(&self) -> Result<&str> {
        Ok(std::str::from_utf8(&self.body)?)
    }

    /// The parsed `Content-Type` header, if present and valid.
    pub fn content_type(&self) -> Result<Option<Mime>> {
        parse_content_type(&self.headers)
    }

    /// Splits a `multipart/*` body into its parts.
    ///
    /// Part bodies are slices of [`Response::body`]; nothing is copied.
    /// Nested multipart parts are not expanded.
    pub fn parts(&self) -> Result<Vec<ResponsePart>> {
        split_parts(self.content_type()?.as_ref(), &self.body)
    }

    /// Turns a 4xx or 5xx status into [`Error::Status`], which keeps the
    /// response.
    pub fn error_for_status(self) -> Result<Self> {
        if self.status.is_client_error() || self.status.is_server_error() {
            Err(Error::Status(Box::new(self)))
        } else {
            Ok(self)
        }
    }

    /// Parses the body as JSON.
    #[cfg(feature = "json")]
    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
        Ok(serde_json::from_slice(&self.body)?)
    }

    /// Parses an `application/x-www-form-urlencoded` body into pairs.
    pub fn form(&self) -> Vec<(String, String)> {
        form_urlencoded::parse(&self.body)
            .map(|(k, v)| (k.into_owned(), v.into_owned()))
            .collect()
    }
}

impl ResponsePart {
    /// Splits a part that is itself `multipart/*` into its parts, which share
    /// the same buffer. Fails if the part has no multipart `Content-Type`.
    pub fn parts(&self) -> Result<Vec<ResponsePart>> {
        split_parts(self.content_type.as_ref(), &self.body)
    }
}

fn split_parts(content_type: Option<&Mime>, body: &Bytes) -> Result<Vec<ResponsePart>> {
    let content_type = content_type
        .ok_or_else(|| Error::HeaderParse("multipart body without Content-Type".to_owned()))?;
    if content_type.type_() != mime::MULTIPART {
        return Err(Error::HeaderParse(format!(
            "expected a multipart Content-Type, got {content_type}"
        )));
    }
    let boundary = content_type
        .get_param(BOUNDARY)
        .ok_or_else(|| Error::HeaderParse("multipart Content-Type without boundary".to_owned()))?;
    parse_multipart(body, boundary.as_str())
}

pub(crate) fn parse_content_type(headers: &HeaderMap) -> Result<Option<Mime>> {
    headers
        .get(CONTENT_TYPE)
        .map(|value| Ok(value.to_str()?.trim().parse::<Mime>()?))
        .transpose()
}

/// Splits a multipart body (RFC 2046) into parts that share `body`'s buffer.
///
/// Line breaks are accepted as `\r\n` or bare `\n`. A preamble before the
/// first delimiter and an epilogue after the closing one are skipped.
pub(crate) fn parse_multipart(body: &Bytes, boundary: &str) -> Result<Vec<ResponsePart>> {
    let delimiter = format!("--{boundary}").into_bytes();
    let truncated = || Error::Multipart("body ends inside a part".to_owned());
    let malformed = |what: &dyn std::fmt::Display| Error::Multipart(what.to_string());
    let mut parts = Vec::new();
    // the first delimiter needs no preceding line break, but has to start a
    // line
    let mut pos = find_delimiter(body, 0, &delimiter, |i| i == 0 || body[i - 1] == b'\n')
        .ok_or_else(|| Error::Multipart(format!("boundary {boundary:?} not found")))?;
    loop {
        pos += delimiter.len();
        if body[pos..].starts_with(b"--") {
            return Ok(parts);
        }
        // the rest of the delimiter line is transport padding
        pos = find(body, pos, b"\n").ok_or_else(truncated)? + 1;

        let mut headers = HeaderMap::new();
        loop {
            let line_end = find(body, pos, b"\n").ok_or_else(truncated)?;
            let line = &body[pos..line_end];
            let line = line.strip_suffix(b"\r").unwrap_or(line);
            pos = line_end + 1;
            if line.is_empty() {
                break;
            }
            let Some(colon) = line.iter().position(|&b| b == b':') else {
                return Err(Error::Multipart(format!(
                    "malformed part header {:?}",
                    String::from_utf8_lossy(line)
                )));
            };
            headers.append(
                HeaderName::from_bytes(line[..colon].trim_ascii()).map_err(|e| malformed(&e))?,
                HeaderValue::from_bytes(line[colon + 1..].trim_ascii())
                    .map_err(|e| malformed(&e))?,
            );
        }

        // the part body runs to the next delimiter line; the line break
        // before it belongs to the delimiter, so search from the blank
        // line's own `\n` to allow empty bodies
        let next = find_delimiter(body, pos - 1, &delimiter, |i| i > 0 && body[i - 1] == b'\n')
            .ok_or_else(truncated)?
            - 1;
        let mut end = next;
        if end > pos && body[end - 1] == b'\r' {
            end -= 1;
        }
        let end = end.max(pos);

        // `to_str` would reject the non-ASCII names browsers send; bytes that
        // are not UTF-8 (Latin-1 from an old server) become U+FFFD
        let disposition = headers
            .get(CONTENT_DISPOSITION)
            .map(|v| String::from_utf8_lossy(v.as_bytes()));
        parts.push(ResponsePart {
            name: disposition
                .as_deref()
                .and_then(|d| disposition_param(d, "name"))
                .unwrap_or_default(),
            filename: disposition
                .as_deref()
                .and_then(|d| disposition_param(d, "filename")),
            content_type: parse_content_type(&headers).map_err(|e| malformed(&e))?,
            body: body.slice(pos..end),
        });
        pos = next + 1;
    }
}

fn find(haystack: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
    haystack
        .get(from..)?
        .windows(needle.len())
        .position(|window| window == needle)
        .map(|i| i + from)
}

/// The first delimiter at or after `from` that `at_line_start` accepts and
/// that is followed by `--`, transport padding, a line break or the end, so
/// that a boundary which is a prefix of a longer token does not match.
fn find_delimiter(
    body: &[u8],
    from: usize,
    delimiter: &[u8],
    at_line_start: impl Fn(usize) -> bool,
) -> Option<usize> {
    let mut from = from;
    loop {
        let i = find(body, from, delimiter)?;
        let after = body.get(i + delimiter.len());
        if at_line_start(i) && matches!(after, None | Some(b'-' | b' ' | b'\t' | b'\r' | b'\n')) {
            return Some(i);
        }
        from = i + 1;
    }
}

/// The value of `key` in a `Content-Disposition` style parameter list.
/// Quoted values may contain `;` and backslash escapes, which are resolved.
fn disposition_param(value: &str, key: &str) -> Option<String> {
    let mut rest = value.split_once(';')?.1;
    loop {
        let (k, after_eq) = rest.split_once('=')?;
        // a parameter without a value, `; flag;`, is skipped
        if let Some(i) = k.find(';') {
            rest = &rest[i + 1..];
            continue;
        }
        let k = k.trim();
        let (v, next) = match after_eq.trim_start().strip_prefix('"') {
            Some(quoted) => {
                let mut v = String::new();
                let mut chars = quoted.char_indices();
                let mut close = None;
                while let Some((i, c)) = chars.next() {
                    match c {
                        '\\' => {
                            if let Some((_, escaped)) = chars.next() {
                                v.push(escaped);
                            }
                        }
                        '"' => {
                            close = Some(i);
                            break;
                        }
                        c => v.push(c),
                    }
                }
                // an unterminated quote takes the rest of the value
                let next = close.and_then(|i| quoted[i + 1..].split_once(';').map(|(_, n)| n));
                (v, next)
            }
            None => match after_eq.split_once(';') {
                Some((v, next)) => (v.trim().to_owned(), Some(next)),
                None => (after_eq.trim().to_owned(), None),
            },
        };
        if k.eq_ignore_ascii_case(key) {
            return Some(v);
        }
        rest = next?;
    }
}

/// Processes one header line from libcurl's header callback.
///
/// A new `HTTP/` status line clears `headers` and records the status, so
/// that headers of earlier phases (`100 Continue`) do not bleed into the
/// final response. Values are kept as bytes, so Latin-1 from an old server
/// is fine; a line that is no header at all is skipped, as curl and
/// browsers do. Only a malformed status line is an error.
pub(crate) fn process_header_line(
    line: &[u8],
    headers: &mut HeaderMap,
    status: &mut Option<StatusCode>,
) -> Result<()> {
    let line = line.trim_ascii_end();
    if line.is_empty() {
        return Ok(());
    }
    if let Some(rest) = line.strip_prefix(b"HTTP/") {
        headers.clear();
        let code = std::str::from_utf8(rest)
            .ok()
            .and_then(|rest| rest.split_whitespace().nth(1)?.parse::<u16>().ok())
            .ok_or_else(|| {
                Error::HeaderParse(format!(
                    "malformed status line {:?}",
                    String::from_utf8_lossy(line)
                ))
            })?;
        *status = Some(StatusCode::from_u16(code)?);
        return Ok(());
    }
    if let Some(colon) = line.iter().position(|&b| b == b':')
        && let Ok(name) = HeaderName::from_bytes(line[..colon].trim_ascii())
        && let Ok(value) = HeaderValue::from_bytes(line[colon + 1..].trim_ascii())
    {
        headers.append(name, value);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn header_lines() {
        let mut headers = HeaderMap::new();
        let mut status = None;
        let mut line = |l: &[u8]| process_header_line(l, &mut headers, &mut status);
        line(b"HTTP/1.1 100 Continue\r\n").unwrap();
        line(b"X-Early: 1\r\n").unwrap();
        line(b"\r\n").unwrap();
        assert!(line(b"HTTP/1.1 abc\r\n").is_err());
        line(b"HTTP/2 200\r\n").unwrap();
        line(b"Content-Type: text/plain\r\n").unwrap();
        line(b"X-Empty:\r\n").unwrap();
        // skipped, not fatal: no header, bad name, control character
        line(b"garbage line\r\n").unwrap();
        line(b"Bad Name: x\r\n").unwrap();
        line(b"X-Ctl: a\x01b\r\n").unwrap();
        // Latin-1 is obs-text, kept as bytes
        line(b"X-Latin1: M\xfcller\r\n").unwrap();
        assert_eq!(status, Some(StatusCode::OK));
        assert!(!headers.contains_key("x-early"));
        assert_eq!(headers[CONTENT_TYPE], "text/plain");
        assert_eq!(headers["x-empty"], "");
        assert_eq!(headers["x-latin1"].as_bytes(), b"M\xfcller");
        assert_eq!(headers.len(), 3);
    }

    #[test]
    fn multipart_parsing() {
        let body = Bytes::from_static(
            b"preamble\r\n--B\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\n1\r\n\
              --B  \r\nContent-Disposition: form-data; name=\"f\"; filename=\"x \\\"y\\\".bin\"\r\n\
              Content-Type: application/octet-stream\r\n\r\n\x00--B\x01\r\n\
              --B\r\n\r\n\r\n\
              --B\r\nContent-Type: text/plain\r\n\r\n\r\n\
              --B--\r\nepilogue",
        );
        let parts = parse_multipart(&body, "B").unwrap();
        assert_eq!(parts.len(), 4);
        assert_eq!(parts[0].name, "a");
        assert_eq!(parts[0].body, "1");
        assert_eq!(parts[0].content_type, None);
        assert_eq!(parts[1].name, "f");
        assert_eq!(parts[1].filename.as_deref(), Some("x \"y\".bin"));
        assert_eq!(parts[1].content_type, Some(mime::APPLICATION_OCTET_STREAM));
        assert_eq!(parts[1].body, &b"\x00--B\x01"[..]);
        assert_eq!(parts[2].name, "");
        assert_eq!(parts[2].body, "");
        assert_eq!(parts[3].content_type, Some(mime::TEXT_PLAIN));
        assert_eq!(parts[3].body, "");
        // slices, not copies
        assert_eq!(
            parts[0].body.as_ptr(),
            body[body.len() - body.len()..]
                .as_ptr()
                .wrapping_add(find(&body, 0, b"1\r\n").unwrap())
        );
    }

    #[test]
    fn nested_parts() {
        let body = Bytes::from_static(
            b"--outer\r\nContent-Type: multipart/mixed; boundary=inner\r\n\r\n\
              --inner\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\n1\r\n\
              --inner--\r\n\r\n\
              --outer\r\nContent-Type: text/plain\r\n\r\nflat\r\n\
              --outer--\r\n",
        );
        let parts = parse_multipart(&body, "outer").unwrap();
        assert_eq!(parts.len(), 2);
        let inner = parts[0].parts().unwrap();
        assert_eq!(inner.len(), 1);
        assert_eq!(inner[0].name, "a");
        assert_eq!(inner[0].body, "1");
        // a slice of the outer buffer, not a copy
        assert!(body.as_ptr_range().contains(&inner[0].body.as_ptr()));
        assert!(matches!(
            parts[1].parts().unwrap_err(),
            Error::HeaderParse(_)
        ));
    }

    #[test]
    fn disposition_params() {
        let d = r#"form-data; name="a;b"; filename="x \"y\" \\ z;.txt"; token=plain ; last=1"#;
        assert_eq!(disposition_param(d, "name").as_deref(), Some("a;b"));
        assert_eq!(
            disposition_param(d, "FILENAME").as_deref(),
            Some("x \"y\" \\ z;.txt")
        );
        assert_eq!(disposition_param(d, "token").as_deref(), Some("plain"));
        assert_eq!(disposition_param(d, "last").as_deref(), Some("1"));
        assert_eq!(disposition_param(d, "missing"), None);
        assert_eq!(disposition_param("form-data", "name"), None);
        assert_eq!(
            disposition_param(r#"form-data; name="a"; flag; filename="x""#, "filename").as_deref(),
            Some("x")
        );
        assert_eq!(
            disposition_param("form-data; name=\"open", "name").as_deref(),
            Some("open")
        );
        assert_eq!(
            disposition_param("form-data; name=grüße", "name").as_deref(),
            Some("grüße")
        );
    }

    #[test]
    fn encoder_output_round_trips_through_the_parser() {
        let segments = crate::Multipart::new()
            .text("grüße", "ä;ö")
            .file(
                "f;g",
                "ré;sumé \"1\".pdf",
                mime::APPLICATION_PDF,
                &b"%PDF"[..],
            )
            .into_segments("xyz");
        let body = Bytes::from(segments.concat());
        let parts = parse_multipart(&body, "xyz").unwrap();
        assert_eq!(parts.len(), 2);
        assert_eq!(parts[0].name, "grüße");
        assert_eq!(parts[0].body, "ä;ö");
        assert_eq!(parts[1].name, "f;g");
        assert_eq!(parts[1].filename.as_deref(), Some("ré;sumé %221%22.pdf"));
        assert_eq!(parts[1].body, "%PDF");
    }

    #[test]
    fn boundary_prefix_is_not_a_delimiter() {
        let body = Bytes::from_static(
            b"--B\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nline\r\n--Bnot\r\n\r\nmore\r\n--B--\r\n",
        );
        let parts = parse_multipart(&body, "B").unwrap();
        assert_eq!(parts.len(), 1);
        assert_eq!(parts[0].body, &b"line\r\n--Bnot\r\n\r\nmore"[..]);
        // the first delimiter must start a line
        let body = Bytes::from_static(b"x--B\r\n\r\n1\r\n--B\r\n\r\n2\r\n--B--");
        let parts = parse_multipart(&body, "B").unwrap();
        assert_eq!(parts.len(), 1);
        assert_eq!(parts[0].body, "2");
        // malformed part headers are multipart errors
        let body = Bytes::from_static(b"--B\r\nBad Name: x\r\n\r\n\r\n--B--");
        assert!(matches!(
            parse_multipart(&body, "B").unwrap_err(),
            Error::Multipart(_)
        ));
    }

    #[test]
    fn multipart_bare_newlines_and_errors() {
        let body = Bytes::from_static(b"--B\nContent-Disposition: form-data; name=a\n\nx\n--B--\n");
        let parts = parse_multipart(&body, "B").unwrap();
        assert_eq!(parts.len(), 1);
        assert_eq!(parts[0].name, "a");
        assert_eq!(parts[0].body, "x");

        let truncated = Bytes::from_static(b"--B\r\nContent-Type: text/plain\r\n\r\nx\r\n");
        assert!(matches!(
            parse_multipart(&truncated, "B").unwrap_err(),
            Error::Multipart(_)
        ));
        assert!(matches!(
            parse_multipart(&Bytes::from_static(b"nothing"), "B").unwrap_err(),
            Error::Multipart(_)
        ));
        assert!(
            parse_multipart(&Bytes::from_static(b"--B--"), "B")
                .unwrap()
                .is_empty()
        );
    }
}