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
//! Types for working directly with the bodies of requests and responses.
//!
//! This module includes types like `Json`, which can be used to automatically (de)serialize bodies
//! using `serde_json`.
//!
//! # Examples
//!
//! Read/Write `Strings` and `Bytes` from/to bodies:
//!
//! ```rust, no_run
//! # #![feature(async_await, futures_api)]
//! use tide::body;
//!
//! async fn echo_string(msg: body::Str) -> String {
//!     println!("String: {}", *msg);
//!     format!("{}", *msg)
//! }
//!
//! async fn echo_string_lossy(msg: body::StrLossy) -> String {
//!     println!("String: {}", *msg);
//!     format!("{}", *msg)
//! }
//!
//! async fn echo_bytes(msg: body::Bytes) -> body::Bytes {
//!     println!("Bytes: {:?}", *msg);
//!     msg
//! }
//!
//! # fn main() {
//! #    let mut app = tide::App::new(());
//! #
//! app.at("/echo/string").post(echo_string);
//! app.at("/echo/string_lossy").post(echo_string_lossy);
//! app.at("/echo/bytes").post(echo_bytes);
//!
//! #    app.serve();
//! # }
//!
//! ```
//!
//! Using `serde_json` to automatically (de)serialize bodies into/from structs:
//!
//! ```rust, no_run
//! # #![feature(async_await, futures_api)]
//! #[macro_use]
//! extern crate serde_derive;
//! use tide::body;
//!
//! #[derive(Serialize, Deserialize, Clone, Debug)]
//! struct Message {
//!     author: Option<String>,
//!     contents: String,
//! }
//!
//! async fn echo_json(msg: body::Json<Message>) -> body::Json<Message> {
//!     println!("JSON: {:?}", *msg);
//!     msg
//! }
//!
//! async fn echo_form(msg: body::Form<Message>) -> body::Form<Message> {
//!     println!("Form: {:?}", *msg);
//!     msg
//! }
//!
//! # fn main() {
//! #    let mut app = tide::App::new(());
//! #
//! app.at("/echo/json").post(echo_json);
//! app.at("/echo/form").post(echo_form);
//! #
//! #    app.serve();
//! # }
//!
//! ```
//!
use futures::{compat::Compat01As03, future::FutureObj, prelude::*, stream::StreamObj};
use http::status::StatusCode;
use multipart::server::Multipart;
use pin_utils::pin_mut;
use std::io::Cursor;
use std::ops::{Deref, DerefMut};

use crate::{configuration::Store, Extract, IntoResponse, Request, Response, RouteMatch};

/// The raw contents of an http request or response.
///
/// A body is a stream of `BodyChunk`s, which are essentially `Vec<u8>` values.
/// Both `Body` and `BodyChunk` values can be easily created from standard byte buffer types,
/// using the `From` trait.
#[derive(Debug)]
pub struct Body {
    inner: BodyInner,
}

type BodyStream = StreamObj<'static, Result<BodyChunk, Error>>;
type Error = Box<dyn std::error::Error + Send + Sync>;
pub struct BodyChunk(hyper::Chunk);

impl BodyChunk {
    pub fn as_bytes(&self) -> &[u8] {
        (*self.0).as_ref()
    }
}

impl From<Vec<u8>> for BodyChunk {
    fn from(v: Vec<u8>) -> Self {
        BodyChunk(v.into())
    }
}

impl From<String> for BodyChunk {
    fn from(v: String) -> Self {
        BodyChunk(v.into())
    }
}

#[derive(Debug)]
enum BodyInner {
    Streaming(BodyStream),
    Fixed(Vec<u8>),
}

impl Body {
    /// Create an empty body.
    pub fn empty() -> Self {
        Body {
            inner: BodyInner::Fixed(Vec::new()),
        }
    }

    /// Collect the full contents of the body into a vector.
    ///
    /// This method is asynchronous because, in general, it requires reading an async
    /// stream of `BodyChunk` values.
    pub async fn read_to_vec(&mut self) -> Result<Vec<u8>, Error> {
        match &mut self.inner {
            BodyInner::Streaming(s) => {
                let mut bytes = Vec::new();
                pin_mut!(s);
                while let Some(chunk) = await!(s.next()) {
                    // TODO: do something more robust than `unwrap`
                    bytes.extend(chunk?.as_bytes());
                }
                Ok(bytes)
            }
            BodyInner::Fixed(v) => Ok(v.clone()),
        }
    }
}

impl From<Vec<u8>> for Body {
    fn from(v: Vec<u8>) -> Self {
        Self {
            inner: BodyInner::Fixed(v),
        }
    }
}

impl From<hyper::Body> for Body {
    fn from(body: hyper::Body) -> Body {
        // TODO: handle chunk-level errors
        let stream = Compat01As03::new(body).map(|c| match c {
            Ok(chunk) => Ok(BodyChunk(chunk)),
            Err(e) => {
                let e: Error = Box::new(e);
                Err(e)
            }
        });
        Body {
            inner: BodyInner::Streaming(StreamObj::new(Box::new(stream))),
        }
    }
}

impl From<BodyChunk> for hyper::Chunk {
    fn from(chunk: BodyChunk) -> hyper::Chunk {
        chunk.0
    }
}

impl Into<hyper::Body> for Body {
    fn into(self) -> hyper::Body {
        match self.inner {
            BodyInner::Fixed(v) => v.into(),
            BodyInner::Streaming(s) => hyper::Body::wrap_stream(s.compat()),
        }
    }
}

// Small utility function to return a stamped error when we cannot parse a request body
fn mk_err<T>(_: T) -> Response {
    StatusCode::BAD_REQUEST.into_response()
}

/// A wrapper for multipart form
///
/// This type is useable as an extractor (argument to an endpoint) for getting
/// a Multipart type defined in the multipart crate
pub struct MultipartForm(pub Multipart<Cursor<Vec<u8>>>);

impl<S: 'static> Extract<S> for MultipartForm {
    // Note: cannot use `existential type` here due to ICE
    type Fut = FutureObj<'static, Result<Self, Response>>;

    fn extract(
        data: &mut S,
        req: &mut Request,
        params: &Option<RouteMatch<'_>>,
        store: &Store,
    ) -> Self::Fut {
        // https://stackoverflow.com/questions/43424982/how-to-parse-multipart-forms-using-abonander-multipart-with-rocket

        const BOUNDARY: &str = "boundary=";
        let boundary = req.headers().get("content-type").and_then(|ct| {
            let ct = ct.to_str().ok()?;
            let idx = ct.find(BOUNDARY)?;
            Some(ct[idx + BOUNDARY.len()..].to_string())
        });

        let mut body = std::mem::replace(req.body_mut(), Body::empty());

        FutureObj::new(Box::new(
            async move {
                let body = await!(body.read_to_vec()).map_err(mk_err)?;
                let boundary = boundary.ok_or(()).map_err(mk_err)?;
                let mp = Multipart::with_body(Cursor::new(body), boundary);
                Ok(MultipartForm(mp))
            },
        ))
    }
}

impl Deref for MultipartForm {
    type Target = Multipart<Cursor<Vec<u8>>>;
    fn deref(&self) -> &Multipart<Cursor<Vec<u8>>> {
        &self.0
    }
}

impl DerefMut for MultipartForm {
    fn deref_mut(&mut self) -> &mut Multipart<Cursor<Vec<u8>>> {
        &mut self.0
    }
}

/// A wrapper for json (de)serialization of bodies.
///
/// This type is usable both as an extractor (argument to an endpoint) and as a response
/// (return value from an endpoint).
pub struct Json<T>(pub T);

impl<T: Send + serde::de::DeserializeOwned + 'static, S: 'static> Extract<S> for Json<T> {
    // Note: cannot use `existential type` here due to ICE
    type Fut = FutureObj<'static, Result<Self, Response>>;

    fn extract(
        data: &mut S,
        req: &mut Request,
        params: &Option<RouteMatch<'_>>,
        store: &Store,
    ) -> Self::Fut {
        let mut body = std::mem::replace(req.body_mut(), Body::empty());
        FutureObj::new(Box::new(
            async move {
                let body = await!(body.read_to_vec()).map_err(mk_err)?;
                let json: T = serde_json::from_slice(&body).map_err(mk_err)?;
                Ok(Json(json))
            },
        ))
    }
}

impl<T: Send + serde::Serialize> IntoResponse for Json<T> {
    fn into_response(self) -> Response {
        // TODO: think about how to handle errors
        http::Response::builder()
            .status(http::status::StatusCode::OK)
            .header("Content-Type", "application/json")
            .body(Body::from(serde_json::to_vec(&self.0).unwrap()))
            .unwrap()
    }
}

impl<T> Deref for Json<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.0
    }
}

impl<T> DerefMut for Json<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.0
    }
}

/// A wrapper for form encoded (application/x-www-form-urlencoded) (de)serialization of bodies.
///
/// This type is usable both as an extractor (argument to an endpoint) and as a response
/// (return value from an endpoint), though returning a response with form data is uncommon
/// and probably not good practice.
pub struct Form<T>(pub T);

impl<T: Send + serde::de::DeserializeOwned + 'static, S: 'static> Extract<S> for Form<T> {
    // Note: cannot use `existential type` here due to ICE
    type Fut = FutureObj<'static, Result<Self, Response>>;

    fn extract(
        data: &mut S,
        req: &mut Request,
        params: &Option<RouteMatch<'_>>,
        store: &Store,
    ) -> Self::Fut {
        let mut body = std::mem::replace(req.body_mut(), Body::empty());
        FutureObj::new(Box::new(
            async move {
                let body = await!(body.read_to_vec()).map_err(mk_err)?;
                let data: T = serde_qs::from_bytes(&body).map_err(mk_err)?;
                Ok(Form(data))
            },
        ))
    }
}

impl<T: 'static + Send + serde::Serialize> IntoResponse for Form<T> {
    fn into_response(self) -> Response {
        // TODO: think about how to handle errors
        http::Response::builder()
            .status(http::status::StatusCode::OK)
            .header("Content-Type", "application/x-www-form-urlencoded")
            .body(Body::from(
                serde_qs::to_string(&self.0).unwrap().into_bytes(),
            ))
            .unwrap()
    }
}

impl<T> Deref for Form<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.0
    }
}

impl<T> DerefMut for Form<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.0
    }
}

pub struct Str(pub String);

impl<S: 'static> Extract<S> for Str {
    type Fut = FutureObj<'static, Result<Self, Response>>;

    fn extract(
        data: &mut S,
        req: &mut Request,
        params: &Option<RouteMatch<'_>>,
        store: &Store,
    ) -> Self::Fut {
        let mut body = std::mem::replace(req.body_mut(), Body::empty());

        FutureObj::new(Box::new(
            async move {
                let body = await!(body.read_to_vec().map_err(mk_err))?;
                let string = String::from_utf8(body).map_err(mk_err)?;
                Ok(Str(string))
            },
        ))
    }
}

impl Deref for Str {
    type Target = String;
    fn deref(&self) -> &String {
        &self.0
    }
}

impl DerefMut for Str {
    fn deref_mut(&mut self) -> &mut String {
        &mut self.0
    }
}

pub struct StrLossy(pub String);

impl<S: 'static> Extract<S> for StrLossy {
    type Fut = FutureObj<'static, Result<Self, Response>>;

    fn extract(
        data: &mut S,
        req: &mut Request,
        params: &Option<RouteMatch<'_>>,
        store: &Store,
    ) -> Self::Fut {
        let mut body = std::mem::replace(req.body_mut(), Body::empty());

        FutureObj::new(Box::new(
            async move {
                let body = await!(body.read_to_vec().map_err(mk_err))?;
                let string = String::from_utf8_lossy(&body).to_string();
                Ok(StrLossy(string))
            },
        ))
    }
}

impl Deref for StrLossy {
    type Target = String;
    fn deref(&self) -> &String {
        &self.0
    }
}

impl DerefMut for StrLossy {
    fn deref_mut(&mut self) -> &mut String {
        &mut self.0
    }
}

pub struct Bytes(pub Vec<u8>);

impl<S: 'static> Extract<S> for Bytes {
    type Fut = FutureObj<'static, Result<Self, Response>>;

    fn extract(
        data: &mut S,
        req: &mut Request,
        params: &Option<RouteMatch<'_>>,
        store: &Store,
    ) -> Self::Fut {
        let mut body = std::mem::replace(req.body_mut(), Body::empty());

        FutureObj::new(Box::new(
            async move {
                let body = await!(body.read_to_vec().map_err(mk_err))?;
                Ok(Bytes(body))
            },
        ))
    }
}

impl Deref for Bytes {
    type Target = Vec<u8>;
    fn deref(&self) -> &Vec<u8> {
        &self.0
    }
}

impl DerefMut for Bytes {
    fn deref_mut(&mut self) -> &mut Vec<u8> {
        &mut self.0
    }
}