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
use crate::{HttpOrWsIncoming, TcpIncoming, TcpStream};
use async_http_codec::internal::buffer_decode::BufferDecode;
use async_http_codec::{BodyDecodeWithContinue, BodyEncode, RequestHead, ResponseHead};
use futures::prelude::*;
use futures::stream::{FusedStream, FuturesUnordered};
use futures::StreamExt;
use http::header::{IntoHeaderName, HOST, LOCATION, TRANSFER_ENCODING};
use http::uri::{Authority, Parts, Scheme};
use http::{HeaderMap, HeaderValue, Method, Request, StatusCode, Uri, Version};
use log::debug;
use std::borrow::Cow;
use std::convert::TryFrom;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
pub struct HttpIncoming<IO: AsyncRead + AsyncWrite + Unpin, T: Stream<Item = IO> + Unpin> {
incoming: Option<T>,
decoding: FuturesUnordered<BufferDecode<IO, RequestHead<'static>>>,
}
impl<IO: AsyncRead + AsyncWrite + Unpin, T: Stream<Item = IO> + Unpin> HttpIncoming<IO, T> {
pub fn new(transport_incoming: T) -> Self {
HttpIncoming {
incoming: Some(transport_incoming),
decoding: FuturesUnordered::new(),
}
}
pub fn or_ws(self) -> HttpOrWsIncoming<IO, Self> {
HttpOrWsIncoming::new(self)
}
}
impl<IO: AsyncRead + AsyncWrite + Unpin, T: Stream<Item = IO> + Unpin> Stream
for HttpIncoming<IO, T>
{
type Item = HttpRequest<IO>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
loop {
match self.decoding.poll_next_unpin(cx) {
Poll::Ready(Some(Ok((transport, head)))) => {
match BodyDecodeWithContinue::from_head(&head, transport) {
Ok(body) => return Poll::Ready(Some(HttpRequest { head, body })),
Err(err) => log::debug!("http head error: {:?}", err),
};
}
Poll::Ready(Some(Err(err))) => log::debug!("http head decode error: {:?}", err),
Poll::Ready(None) | Poll::Pending => match &mut self.incoming {
Some(incoming) => match incoming.poll_next_unpin(cx) {
Poll::Ready(Some(transport)) => {
self.decoding.push(RequestHead::decode(transport))
}
Poll::Ready(None) => drop(self.incoming.take()),
Poll::Pending => return Poll::Pending,
},
None => match self.is_terminated() {
true => return Poll::Ready(None),
false => return Poll::Pending,
},
},
}
}
}
}
impl<IO: AsyncRead + AsyncWrite + Unpin, T: Stream<Item = IO> + Unpin> FusedStream
for HttpIncoming<IO, T>
{
fn is_terminated(&self) -> bool {
self.incoming.is_none() && self.decoding.is_terminated()
}
}
impl<IO: AsyncRead + AsyncWrite + Unpin, T: Stream<Item = IO> + Unpin> Unpin
for HttpIncoming<IO, T>
{
}
pub struct HttpRequest<IO: AsyncRead + AsyncWrite + Unpin> {
pub(crate) head: RequestHead<'static>,
pub(crate) body: BodyDecodeWithContinue<IO>,
}
impl<IO: AsyncRead + AsyncWrite + Unpin> HttpRequest<IO> {
pub fn into_inner(self) -> Request<BodyDecodeWithContinue<IO>> {
Request::from_parts(self.head.into(), self.body)
}
pub fn from_inner(request: Request<BodyDecodeWithContinue<IO>>) -> Self {
let (head, body) = request.into_parts();
let head = head.into();
Self { head, body }
}
pub async fn response(mut self) -> io::Result<HttpResponse<IO>> {
while 0 < self.body().read(&mut [0u8; 1 << 14]).await? {}
let Self { head, body } = self;
let request_head = http::request::Parts::from(head);
let request_headers = request_head.headers;
let request_method = request_head.method;
let request_uri = request_head.uri;
let transport = body.checkpoint().0;
let headers = Cow::Owned(HeaderMap::with_capacity(128));
Ok(HttpResponse {
request_headers,
request_uri,
request_method,
head: ResponseHead::new(StatusCode::OK, request_head.version, headers),
transport,
})
}
pub fn body(&mut self) -> &mut BodyDecodeWithContinue<IO> {
&mut self.body
}
pub async fn body_string(&mut self) -> io::Result<String> {
let mut body = String::new();
self.body().read_to_string(&mut body).await?;
Ok(body)
}
pub async fn body_vec(&mut self) -> io::Result<Vec<u8>> {
let mut body = Vec::new();
self.body().read_to_end(&mut body).await?;
Ok(body)
}
pub fn headers(&self) -> &HeaderMap {
self.head.headers()
}
pub fn uri(&self) -> &Uri {
&self.head.uri()
}
pub fn method(&self) -> Method {
self.head.method().clone()
}
pub fn version(&self) -> Version {
self.head.version()
}
}
pub struct HttpResponse<IO: AsyncRead + AsyncWrite + Unpin> {
request_uri: Uri,
request_headers: HeaderMap,
request_method: Method,
head: ResponseHead<'static>,
transport: IO,
}
impl<IO: AsyncRead + AsyncWrite + Unpin> HttpResponse<IO> {
pub fn request_headers(&self) -> &HeaderMap {
&self.request_headers
}
pub fn uri(&self) -> &Uri {
&self.request_uri
}
pub fn method(&self) -> Method {
self.request_method.clone()
}
pub fn version(&self) -> Version {
self.head.version()
}
pub fn headers(&self) -> &HeaderMap {
self.head.headers()
}
pub fn headers_mut(&mut self) -> &mut HeaderMap {
self.head.headers_mut()
}
pub fn insert_header(&mut self, key: impl IntoHeaderName, value: HeaderValue) -> &mut Self {
self.headers_mut().insert(key, value);
self
}
pub fn status(&self) -> StatusCode {
self.head.status()
}
pub fn status_mut(&mut self) -> &mut StatusCode {
self.head.status_mut()
}
pub fn set_status(&mut self, status: StatusCode) -> &mut Self {
*self.status_mut() = status;
self
}
pub async fn send(mut self, body: impl AsRef<[u8]>) -> io::Result<()> {
self.insert_header(TRANSFER_ENCODING, HeaderValue::from_static("chunked"));
self.head.encode(&mut self.transport).await?;
let mut encoder = BodyEncode::new(&mut self.transport, None);
encoder.write_all(body.as_ref()).await?;
encoder.close().await?;
Ok(())
}
}
impl HttpIncoming<TcpStream, TcpIncoming> {
pub fn redirect_https(self) -> RedirectHttps {
RedirectHttps {
incoming: self,
redirecting: FuturesUnordered::new(),
}
}
}
pub struct RedirectHttps {
incoming: HttpIncoming<TcpStream, TcpIncoming>,
redirecting: FuturesUnordered<Pin<Box<dyn Future<Output = ()> + Send + Sync>>>,
}
impl RedirectHttps {
fn set_location_header(resp: &mut HttpResponse<TcpStream>) -> http::Result<()> {
let authority = match resp.request_headers().get(HOST) {
Some(host) => Some(Authority::try_from(host.as_bytes())?),
None => None,
};
let mut parts: Parts = Default::default();
parts.scheme = Some(Scheme::HTTPS);
parts.authority = authority;
parts.path_and_query = resp.uri().path_and_query().cloned();
let header_value = HeaderValue::try_from(Uri::from_parts(parts)?.to_string())?;
resp.insert_header(LOCATION, header_value);
Ok(())
}
async fn send(req: HttpRequest<TcpStream>) {
match req.response().await {
Err(err) => debug!("error reading body of request to be redirected: {:?}", err),
Ok(mut resp) => match Self::set_location_header(&mut resp) {
Err(err) => debug!("error constructing redirect location header: {:?}", err),
Ok(()) => {
resp.set_status(StatusCode::TEMPORARY_REDIRECT);
dbg!();
if let Err(err) = resp.send(&[]).await {
debug!("error sending redirect response: {:?}", err)
}
}
},
}
}
}
impl Future for RedirectHttps {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
if let Poll::Ready(Some(())) = Pin::new(&mut self.redirecting).poll_next(cx) {
continue;
}
if !self.incoming.is_terminated() {
if let Poll::Ready(Some(req)) = Pin::new(&mut self.incoming).poll_next(cx) {
self.redirecting.push(Box::pin(Self::send(req)));
continue;
}
}
return match self.incoming.is_terminated() && self.redirecting.is_terminated() {
true => Poll::Ready(()),
false => Poll::Pending,
};
}
}
}