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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// Copyright 2017-2019 `multipart-async` Crate Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

use futures::{Stream, TryStream};
use std::pin::Pin;
use std::task::{Context, Poll};
use std::{fmt, mem};

use self::State::*;
use super::helpers::*;
use crate::http::errors::ReadError;
use crate::http::BodyChunk;

/// A struct implementing `Read` and `BufRead` that will yield bytes until it sees a given sequence.
pub struct BoundaryFinder<S: TryStream>
where
    S::Error: Into<ReadError>,
{
    stream: S,
    state: State<S::Ok>,
    boundary: Box<[u8]>,
}

impl<S: TryStream> BoundaryFinder<S>
where
    S::Error: Into<ReadError>,
{
    pub fn new<B: Into<Vec<u8>>>(stream: S, boundary: B) -> Self {
        BoundaryFinder {
            stream,
            state: State::Watching,
            boundary: boundary.into().into_boxed_slice(),
        }
    }
}

macro_rules! set_state {
    ($self:ident = $state:expr) => {
        *$self.as_mut().state() = $state;
    };
}

impl<S> BoundaryFinder<S>
where
    S: TryStream,
    S::Ok: BodyChunk,
    S::Error: Into<ReadError>,
{
    unsafe_pinned!(stream: S);
    unsafe_unpinned!(state: State<S::Ok>);

    pub fn body_chunk(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Result<S::Ok, ReadError>>> {
        macro_rules! try_ready_opt (
            ($try:expr) => (
                match $try {
                    Poll::Ready(Some(Ok(val))) => val,
                    Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e.into()))),
                    Poll::Ready(None) => {
                        set_state!(self = End);
                        return Poll::Ready(None);
                    }
                    Poll::Pending => return Poll::Pending,
                }
            );
            ($try:expr; $restore:expr) => (
                match $try {
                    Poll::Ready(Some(Ok(val))) => val,
                    Poll::Ready(Some(Err(e))) => {
                        set_state!(self = $restore);
                        return Poll::Ready(Some(Err(e.into())));
                    },
                    Poll::Ready(None) => {
                        set_state!(self = End);
                        return Poll::Ready(None);
                    },
                    Poll::Pending => {
                        set_state!(self = $restore);
                        return Poll::Pending;
                    }
                }
            )
        );

        loop {
            // tracing::debug!("body_chunk() loop state: {:?}", self.state);
            match self.state {
                Found(_) | Split(_, _) | End => return Poll::Ready(None),
                _ => (),
            }

            match mem::replace(self.as_mut().state(), Watching) {
                Watching => {
                    let chunk = try_ready_opt!(self.as_mut().stream().try_poll_next(cx));

                    // For sanity
                    if chunk.is_empty() {
                        return ready_ok(chunk);
                    }

                    if let Some(chunk) = self.as_mut().check_chunk(chunk) {
                        return ready_ok(chunk);
                    }
                }
                Remainder(rem) => {
                    if let Some(chunk) = self.as_mut().check_chunk(rem) {
                        return ready_ok(chunk);
                    }
                }
                Partial(partial, res) => {
                    let chunk = match self.as_mut().stream().try_poll_next(cx) {
                        Poll::Ready(Some(chunk)) => match chunk {
                            Ok(chunk) => chunk,
                            Err(e) => return Poll::Ready(Some(Err(e.into()))),
                        },
                        Poll::Ready(None) => {
                            set_state!(self = End);
                            return Poll::Ready(Some(fmt_err!(
                                "unable to verify multipart boundary; expected: \"{}\" found: \"{}\"",
                                show_bytes(&self.boundary),
                                show_bytes(partial.as_slice())
                            )));
                        }
                        Poll::Pending => {
                            set_state!(self = Partial(partial, res));
                            return Poll::Pending;
                        }
                    };

                    // tracing::debug!("Partial got second chunk: {}", show_bytes(chunk.as_slice()));
                    if !self.is_boundary_prefix(partial.as_slice(), chunk.as_slice(), res) {
                        // tracing::debug!("partial + chunk don't make a boundary prefix");
                        set_state!(self = Remainder(chunk));
                        return ready_ok(partial);
                    }

                    let needed_len = (self.boundary_size(res.incl_crlf)).saturating_sub(partial.len());

                    if needed_len > chunk.len() {
                        // hopefully rare; must be dealing with a poorly behaved stream impl
                        return Poll::Ready(Some(fmt_err!(
                            "needed {} more bytes to verify boundary, got {}",
                            needed_len,
                            chunk.len()
                        )));
                    }

                    let bnd_start = res.boundary_start();

                    let is_boundary = (bnd_start > partial.len()
                        // `partial` ended with a `<CR>` and `chunk` starts with `<LF>--<boundary>`
                        && self.check_boundary(&chunk.as_slice()[bnd_start - partial.len()..]))
                        || self.check_boundary_split(&partial.as_slice()[bnd_start..], chunk.as_slice());

                    if !is_boundary {
                        // tracing::debug!("partial + chunk don't make a whole boundary");
                        *self.as_mut().state() = Remainder(chunk);
                        return ready_ok(partial);
                    }

                    let ret = if res.incl_crlf {
                        if partial.len() < bnd_start {
                            // `partial` ended with a `<CR>` and `chunk` starts with `<LF>--<boundary>`
                            *self.as_mut().state() = Found(chunk.split_into(bnd_start - partial.len()).1);
                            partial.split_into(res.idx).0
                        } else {
                            let (ret, rem) = partial.split_into(res.idx);
                            let (_, first) = rem.split_into(2);
                            *self.as_mut().state() = Split(first, chunk);
                            ret
                        }
                    } else {
                        let (ret, first) = partial.split_into(res.idx);
                        *self.as_mut().state() = Split(first, chunk);
                        ret
                    };

                    if !ret.is_empty() {
                        return ready_ok(ret);
                    } else {
                        // Don't return an empty chunk at the end
                        return Poll::Ready(None);
                    }
                }
                state => unreachable!("invalid state: {:?}", state),
            }
        }
    }

    fn check_chunk(mut self: Pin<&mut Self>, chunk: S::Ok) -> Option<S::Ok> {
        // tracing::debug!("check chunk: '{}'", show_bytes(chunk.as_slice()));
        if chunk.is_empty() {
            return None;
        }

        if let Some(res) = self.find_boundary(&chunk) {
            // debug!("boundary found: {:?}", res);
            let len = self.boundary_size(res.incl_crlf);
            if chunk.len() < res.idx + len {
                // Either partial boundary, or boundary but not the two bytes after it
                set_state!(self = Partial(chunk, res));
                // tracing::debug!("partial boundary: {:?}", self.state);
                None
            } else {
                let (ret, bnd) = chunk.split_into(res.idx);
                let bnd = if res.incl_crlf {
                    // cut off the preceding CRLF
                    bnd.split_into(2).1
                } else {
                    bnd
                };
                set_state!(self = Found(bnd));
                // tracing::debug!(
                //     "boundary located: {:?} returning chunk: {}",
                //     self.state,
                //     show_bytes(ret.as_slice())
                // );
                if !ret.is_empty() {
                    Some(ret)
                } else {
                    None
                }
            }
        } else {
            Some(chunk)
        }
    }

    fn find_boundary(&self, chunk: &S::Ok) -> Option<SearchResult> {
        twoway::find_bytes(chunk.as_slice(), &self.boundary)
            .map(|idx| check_crlf(chunk.as_slice(), idx))
            .or_else(|| self.partial_find_boundary(chunk))
    }

    fn is_boundary_prefix(&self, first: &[u8], second: &[u8], res: SearchResult) -> bool {
        let maybe_prefix = first.iter().chain(second);

        if res.incl_crlf {
            maybe_prefix
                .zip(b"\r\n".iter().chain(&*self.boundary))
                .all(|(l, r)| l == r)
        } else {
            maybe_prefix.zip(&*self.boundary).all(|(l, r)| l == r)
        }
    }

    fn partial_find_boundary(&self, chunk: &S::Ok) -> Option<SearchResult> {
        let chunk = chunk.as_slice();
        let len = chunk.len();

        partial_rmatch(chunk, &self.boundary)
            .map(|idx| check_crlf(chunk, idx))
            .or_else(||
                // EDGE CASE: the bytes of the newline before the boundary are at the end of the chunk
                if len >= 2 && chunk[len - 2..] == *b"\r\n" {
                    Some(SearchResult {
                        idx: len - 2,
                        incl_crlf: true,
                    })
                } else if len >= 1 && chunk[len - 1] == b'\r' {
                    Some(SearchResult {
                        idx: len - 1,
                        incl_crlf: true,
                    })
                } else {
                    None
                }
            )
    }

    fn check_boundary(&self, bytes: &[u8]) -> bool {
        (bytes.len() >= 2 && bytes[2..].starts_with(&self.boundary)) || bytes.starts_with(&self.boundary)
    }

    fn check_boundary_split(&self, first: &[u8], second: &[u8]) -> bool {
        let check_len = self.boundary.len().saturating_sub(first.len());

        second.len() >= check_len
            && first
                .iter()
                .chain(&second[..check_len])
                .zip(self.boundary.iter())
                .all(|(l, r)| l == r)
    }

    /// Returns `true` if another field should follow this boundary, `false` if the stream is at a logical end
    pub fn consume_boundary(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<bool, ReadError>> {
        // debug!("consuming boundary");

        while ready!(self.as_mut().body_chunk(cx)?).is_some() {
            // tracing::debug!("body chunk loop!");
        }
        // tracing::debug!("consume_boundary() after-loop state: {:?}", self.state,);
        match mem::replace(self.as_mut().state(), Watching) {
            Found(bnd) => self.confirm_boundary(bnd),
            Split(first, second) => self.confirm_boundary_split(first, second),
            End => {
                *self.state() = End;
                ready_ok(false)
            }
            state => unreachable!("invalid state: {:?}", state),
        }
    }

    fn confirm_boundary(mut self: Pin<&mut Self>, boundary: S::Ok) -> Poll<Result<bool, ReadError>> {
        if boundary.len() < self.boundary_size(false) {
            ret_err!("boundary sequence too short: {}", show_bytes(boundary.as_slice()));
        }

        let (boundary, rem) = boundary.split_into(self.boundary_size(false));
        let boundary = boundary.as_slice();
        // tracing::debug!("confirming boundary: {}", show_bytes(boundary));
        debug_assert!(
            !boundary.starts_with(b"\r\n"),
            "leading CRLF should have been trimmed from boundary: {}",
            show_bytes(boundary)
        );
        debug_assert!(
            self.check_boundary(boundary),
            "invalid boundary previous confirmed as valid: {}",
            show_bytes(boundary)
        );

        set_state!(self = if !rem.is_empty() { Remainder(rem) } else { Watching });
        // tracing::debug!("boundary found: {}", show_bytes(boundary));
        let is_end = check_last_two(boundary);
        // debug!("is_end: {:?}", is_end);
        if is_end {
            set_state!(self = End);
        }

        ready_ok(!is_end)
    }

    fn confirm_boundary_split(mut self: Pin<&mut Self>, first: S::Ok, second: S::Ok) -> Poll<Result<bool, ReadError>> {
        let first = first.as_slice();
        let check_len = self.boundary_size(false) - first.len();

        if second.len() < check_len {
            ret_err!(
                "split boundary sequence too short: ({}, {})",
                show_bytes(first),
                show_bytes(second.as_slice())
            );
        }

        let (second, rem) = second.split_into(check_len);
        let second = second.as_slice();

        set_state!(self = Remainder(rem));
        debug_assert!(
            !first.starts_with(b"\r\n"),
            "leading CRLF should have been trimmed from first boundary section: {}",
            show_bytes(first)
        );
        debug_assert!(
            self.check_boundary_split(first, second),
            "invalid split boundary previous confirmed as valid: ({}, {})",
            show_bytes(first),
            show_bytes(second)
        );

        let is_end = check_last_two(second);
        if is_end {
            set_state!(self = End);
        }

        ready_ok(!is_end)
    }

    /// The necessary size to verify a boundary, including the potential CRLF before, and the
    /// CRLF / "--" afterward
    fn boundary_size(&self, incl_crlf: bool) -> usize {
        self.boundary.len() + if incl_crlf { 4 } else { 2 }
    }
}

impl<S> Stream for BoundaryFinder<S>
where
    S: TryStream,
    S::Ok: BodyChunk,
    S::Error: Into<ReadError>,
{
    type Item = Result<S::Ok, ReadError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        self.body_chunk(cx)
    }
}

impl<S: TryStream + fmt::Debug> fmt::Debug for BoundaryFinder<S>
where
    S::Ok: BodyChunk + fmt::Debug,
    S::Error: Into<ReadError>,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("BoundaryFinder")
            .field("stream", &self.stream)
            .field("state", &self.state)
            .field("boundary", &self.boundary)
            .finish()
    }
}

enum State<B> {
    /// Watching for next boundary
    Watching,
    /// Partial boundary
    Partial(B, SearchResult),
    Found(B),
    Split(B, B),
    /// The remains of a chunk after processing
    Remainder(B),
    End,
}

impl<B: BodyChunk> fmt::Debug for State<B> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::State::*;

        match *self {
            Watching => f.write_str("State::Watching"),
            Partial(ref bnd, res) => write!(f, "State::Partial({}, {:?})", show_bytes(bnd.as_slice()), res),
            Found(ref bnd) => write!(f, "State::Found({})", show_bytes(bnd.as_slice())),
            Split(ref first, ref second) => write!(
                f,
                "State::Split(\"{}\", \"{}\")",
                show_bytes(first.as_slice()),
                show_bytes(second.as_slice())
            ),
            Remainder(ref rem) => write!(f, "State::Remainder({})", show_bytes(rem.as_slice())),
            End => f.write_str("State::End"),
        }
    }
}

#[derive(Copy, Clone, Debug)]
struct SearchResult {
    idx: usize,
    incl_crlf: bool,
}

impl SearchResult {
    fn boundary_start(&self) -> usize {
        if self.incl_crlf {
            self.idx + 2
        } else {
            self.idx
        }
    }
}

/// If there's a CRLF before the boundary, we want to back up to make sure we don't yield a newline
/// that the client doesn't expect
fn check_crlf(chunk: &[u8], mut idx: usize) -> SearchResult {
    let mut incl_crlf = false;
    if idx >= 2 && chunk[idx - 2..idx] == *b"\r\n" {
        incl_crlf = true;
        idx -= 2;
    }

    SearchResult { idx, incl_crlf }
}

fn check_last_two(boundary: &[u8]) -> bool {
    let is_end = boundary.ends_with(b"--");

    if !is_end && !boundary.ends_with(b"\r\n") && boundary.len() > 2 {
        tracing::warn!("unexpected bytes after boundary");
    }

    is_end
}

/// Check if `needle` is cut off at the end of `haystack`, and if so, its index
fn partial_rmatch(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    if haystack.is_empty() || needle.is_empty() {
        return None;
    }

    // If the haystack is smaller than the needle, we still need to test it
    let trim_start = haystack.len().saturating_sub(needle.len() - 1);
    let idx = try_opt!(twoway::find_bytes(&haystack[trim_start..], &needle[..1])) + trim_start;
    // tracing::debug!("partial_rmatch found start: {:?}", idx);
    // If the rest of `haystack` matches `needle`, then we have our partial match
    if haystack[idx..].iter().zip(needle).all(|(l, r)| l == r) {
        Some(idx)
    } else {
        None
    }
}

#[cfg(test)]
mod test {
    use super::BoundaryFinder;
    use crate::http::multipart::test_util::*;

    #[test]
    fn test_empty_stream() {
        let finder = BoundaryFinder::new(mock_stream(&[]), BOUNDARY);
        pin_mut!(finder);
        ready_assert_ok_eq!(|cx| finder.as_mut().consume_boundary(cx), false);
    }

    #[test]
    fn test_one_boundary() {
        let finder = BoundaryFinder::new(mock_stream(&[b"--boundary\r\n"]), BOUNDARY);
        pin_mut!(finder);
        ready_assert_ok_eq!(|cx| finder.as_mut().consume_boundary(cx), true);
        ready_assert_ok_eq!(|cx| finder.as_mut().consume_boundary(cx), false);
    }

    #[test]
    fn test_one_incomplete_boundary() {
        let finder = BoundaryFinder::new(mock_stream(&[b"--bound"]), BOUNDARY);
        pin_mut!(finder);
        let result = until_ready!(|cx| finder.as_mut().consume_boundary(cx));
        assert_eq!(result.is_err(), true);
    }

    #[test]
    fn test_one_empty_field() {
        let finder = BoundaryFinder::new(
            mock_stream(&[b"--boundary", b"\r\n", b"\r\n", b"--boundary--"]),
            BOUNDARY,
        );
        pin_mut!(finder);
        ready_assert_ok_eq!(|cx| finder.as_mut().consume_boundary(cx), true);
        ready_assert_eq_none!(|cx| finder.as_mut().body_chunk(cx));
        ready_assert_ok_eq!(|cx| finder.as_mut().consume_boundary(cx), false);
    }

    #[test]
    fn test_one_nonempty_field() {
        let finder = BoundaryFinder::new(
            mock_stream(&[b"--boundary", b"\r\n", b"field data", b"\r\n", b"--boundary--"]),
            BOUNDARY,
        );
        pin_mut!(finder);

        ready_assert_ok_eq!(|cx| finder.as_mut().consume_boundary(cx), true);
        ready_assert_some_ok_eq!(|cx| finder.as_mut().body_chunk(cx), &b"field data"[..]);
        ready_assert_eq_none!(|cx| finder.as_mut().body_chunk(cx));
        ready_assert_ok_eq!(|cx| finder.as_mut().consume_boundary(cx), false);
    }

    #[test]
    fn test_two_empty_fields() {
        let finder = BoundaryFinder::new(
            mock_stream(&[b"--boundary", b"\r\n", b"\r\n--boundary\r\n", b"\r\n", b"--boundary--"]),
            BOUNDARY,
        );
        pin_mut!(finder);
        ready_assert_ok_eq!(|cx| finder.as_mut().consume_boundary(cx), true);
        ready_assert_eq_none!(|cx| finder.as_mut().body_chunk(cx));
        ready_assert_ok_eq!(|cx| finder.as_mut().consume_boundary(cx), true);
        ready_assert_eq_none!(|cx| finder.as_mut().body_chunk(cx));
        ready_assert_ok_eq!(|cx| finder.as_mut().consume_boundary(cx), false);
    }
}