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
use std::marker::PhantomData;
use bytes::{Buf, Bytes, BytesMut};
use viz_utils::{
futures::stream::{Stream, StreamExt},
thiserror::Error as ThisError,
tracing,
};
use crate::{http, Response, Result};
#[derive(ThisError, Debug, PartialEq)]
pub enum PayloadError {
#[error("failed to read payload")]
Read,
#[error("failed to parse payload")]
Parse,
#[error("content-length is required")]
LengthRequired,
#[error("payload is too large")]
TooLarge,
#[error("unsupported media type")]
UnsupportedMediaType,
}
impl From<PayloadError> for Response {
fn from(e: PayloadError) -> Response {
(
match e {
PayloadError::Read | PayloadError::Parse => http::StatusCode::BAD_REQUEST,
PayloadError::LengthRequired => http::StatusCode::LENGTH_REQUIRED,
PayloadError::TooLarge => http::StatusCode::PAYLOAD_TOO_LARGE,
PayloadError::UnsupportedMediaType => http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
},
e.to_string(),
)
.into()
}
}
pub trait PayloadDetect {
fn detect(_: &mime::Mime) -> bool {
true
}
}
#[derive(Debug, Default)]
pub struct Payload<T = ()> {
limit: Option<u64>,
_t: PhantomData<T>,
}
impl Payload {
pub const PAYLOAD_LIMIT: u64 = 1024 * 1024;
pub const PAYLOAD_BUFFER_SIZE: usize = 8 * 1024;
}
impl<T> Payload<T>
where
T: PayloadDetect,
{
pub fn new() -> Self {
Self { limit: None, _t: PhantomData }
}
pub fn set_limit(&mut self, limit: u64) -> &mut Self {
self.limit.replace(limit);
self
}
pub fn limit(&self) -> u64 {
self.limit.unwrap_or(Payload::PAYLOAD_LIMIT)
}
pub fn check_header(
&self,
m: Option<mime::Mime>,
l: Option<u64>,
) -> Result<mime::Mime, PayloadError> {
let m = m.ok_or(PayloadError::UnsupportedMediaType)?;
if !T::detect(&m) {
return Err(PayloadError::UnsupportedMediaType);
}
if l.is_none() {
return Err(PayloadError::LengthRequired);
}
if l.unwrap() > self.limit() {
return Err(PayloadError::TooLarge);
}
Ok(m)
}
pub async fn check_real_length<S>(&self, mut stream: S) -> Result<impl Buf, PayloadError>
where
S: Stream<Item = Result<Bytes, hyper::Error>> + Unpin,
{
let mut body = BytesMut::with_capacity(Payload::PAYLOAD_BUFFER_SIZE);
let limit = self.limit();
while let Some(item) = stream.next().await {
let chunk = item.map_err(|e| {
tracing::error!("{}", e);
PayloadError::Read
})?;
if ((body.len() + chunk.len()) as u64) > limit {
return Err(PayloadError::TooLarge);
} else {
body.extend_from_slice(&chunk);
}
}
Ok(body.freeze())
}
}