1use std::{
2 cmp,
3 error::Error as StdError,
4 future::Future,
5 marker::PhantomData,
6 net,
7 pin::{pin, Pin},
8 rc::Rc,
9 task::{Context, Poll},
10};
11
12use actix_codec::{AsyncRead, AsyncWrite};
13use actix_service::Service;
14use actix_utils::future::poll_fn;
15use bytes::{Bytes, BytesMut};
16use futures_core::ready;
17use h2::{
18 server::{Connection, SendResponse},
19 Ping, PingPong,
20};
21use pin_project_lite::pin_project;
22use tokio::time::{sleep, Sleep};
23
24use crate::{
25 body::{BodySize, BoxBody, MessageBody},
26 config::{GracefulShutdownFuture, ServiceConfig},
27 header::{
28 HeaderName, HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING, UPGRADE,
29 },
30 service::HttpFlow,
31 Extensions, Method, OnConnectData, Payload, Request, Response, ResponseHead,
32};
33
34const CHUNK_SIZE: usize = 16_384;
35
36pin_project! {
37 pub struct Dispatcher<T, S, B, X, U> {
39 flow: Rc<HttpFlow<S, X, U>>,
40 connection: Connection<T, Bytes>,
41 conn_data: Option<Rc<Extensions>>,
42 config: ServiceConfig,
43 peer_addr: Option<net::SocketAddr>,
44 first_head_timer: Option<Pin<Box<Sleep>>>,
45 ping_pong: Option<H2PingPong>,
46 graceful_shutdown: Option<GracefulShutdownFuture>,
47 _phantom: PhantomData<B>
48 }
49}
50
51impl<T, S, B, X, U> Dispatcher<T, S, B, X, U>
52where
53 T: AsyncRead + AsyncWrite + Unpin,
54{
55 pub(crate) fn new(
56 mut conn: Connection<T, Bytes>,
57 flow: Rc<HttpFlow<S, X, U>>,
58 config: ServiceConfig,
59 peer_addr: Option<net::SocketAddr>,
60 conn_data: OnConnectData,
61 first_head_timer: Option<Pin<Box<Sleep>>>,
62 ) -> Self {
63 let ping_pong = config.keep_alive().duration().map(|dur| H2PingPong {
64 timer: Box::pin(sleep(dur)),
65 in_flight: false,
66 ping_pong: conn.ping_pong().unwrap(),
67 });
68
69 let graceful_shutdown = config.graceful_shutdown();
70
71 Self {
72 flow,
73 config,
74 peer_addr,
75 connection: conn,
76 conn_data: conn_data.0.map(Rc::new),
77 first_head_timer,
78 ping_pong,
79 graceful_shutdown,
80 _phantom: PhantomData,
81 }
82 }
83
84 fn poll_shutdown(&mut self, cx: &mut Context<'_>) {
86 let shutdown = self
87 .graceful_shutdown
88 .as_mut()
89 .is_some_and(|signal| signal.as_mut().poll(cx).is_ready());
90
91 if shutdown {
92 self.graceful_shutdown = None;
93
94 self.connection.graceful_shutdown();
98 }
99 }
100}
101
102struct H2PingPong {
103 ping_pong: PingPong,
105
106 in_flight: bool,
108
109 timer: Pin<Box<Sleep>>,
111}
112
113impl<T, S, B, X, U> Future for Dispatcher<T, S, B, X, U>
114where
115 T: AsyncRead + AsyncWrite + Unpin,
116
117 S: Service<Request>,
118 S::Error: Into<Response<BoxBody>>,
119 S::Future: 'static,
120 S::Response: Into<Response<B>>,
121
122 B: MessageBody,
123{
124 type Output = Result<(), crate::error::DispatchError>;
125
126 #[inline]
127 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
128 let this = self.get_mut();
129
130 this.poll_shutdown(cx);
131
132 loop {
133 match Pin::new(&mut this.connection).poll_accept(cx)? {
134 Poll::Ready(Some((req, tx))) => {
135 this.first_head_timer = None;
136
137 let (parts, body) = req.into_parts();
138 let payload = crate::h2::Payload::new(body);
139 let pl = Payload::H2 { payload };
140 let mut req = Request::with_payload(pl);
141 let head_req = parts.method == Method::HEAD;
142
143 let head = req.head_mut();
144 head.uri = parts.uri;
145 head.method = parts.method;
146 head.version = parts.version;
147 head.headers = parts.headers.into();
148 head.peer_addr = this.peer_addr;
149
150 req.conn_data.clone_from(&this.conn_data);
151
152 let fut = this.flow.service.call(req);
153 let config = this.config.clone();
154
155 tokio::task::spawn_local(async move {
157 let res = match fut.await {
159 Ok(res) => handle_response(res.into(), tx, config, head_req).await,
160 Err(err) => {
161 let res: Response<BoxBody> = err.into();
162 handle_response(res, tx, config, head_req).await
163 }
164 };
165
166 if let Err(err) = res {
168 match err {
169 DispatchError::SendResponse(err) => {
170 tracing::trace!("Error sending response: {err:?}");
171 }
172 DispatchError::SendData(err) => {
173 tracing::warn!("Send data error: {err:?}");
174 }
175 DispatchError::ResponseBody(err) => {
176 tracing::error!("Response payload stream error: {err:?}");
177 }
178 }
179 }
180 });
181 }
182 Poll::Ready(None) => return Poll::Ready(Ok(())),
183
184 Poll::Pending => {
185 if let Some(timer) = &mut this.first_head_timer {
186 if timer.as_mut().poll(cx).is_ready() {
187 return Poll::Ready(Err(
188 crate::error::DispatchError::SlowRequestTimeout,
189 ));
190 }
191 }
192
193 match this.ping_pong.as_mut() {
194 Some(ping_pong) => loop {
195 if ping_pong.in_flight {
196 match ping_pong.ping_pong.poll_pong(cx)? {
200 Poll::Ready(_) => {
201 ping_pong.in_flight = false;
202
203 let dead_line = this.config.keep_alive_deadline().unwrap();
204 ping_pong.timer.as_mut().reset(dead_line.into());
205 }
206 Poll::Pending => {
207 return ping_pong.timer.as_mut().poll(cx).map(|_| Ok(()));
208 }
209 }
210 } else {
211 ready!(ping_pong.timer.as_mut().poll(cx));
215
216 ping_pong.ping_pong.send_ping(Ping::opaque())?;
217
218 let dead_line = this.config.keep_alive_deadline().unwrap();
219 ping_pong.timer.as_mut().reset(dead_line.into());
220
221 ping_pong.in_flight = true;
222 }
223 },
224 None => return Poll::Pending,
225 }
226 }
227 }
228 }
229 }
230}
231
232enum DispatchError {
233 SendResponse(h2::Error),
234 SendData(h2::Error),
235 ResponseBody(Box<dyn StdError>),
236}
237
238async fn handle_response<B>(
239 res: Response<B>,
240 mut tx: SendResponse<Bytes>,
241 config: ServiceConfig,
242 head_req: bool,
243) -> Result<(), DispatchError>
244where
245 B: MessageBody,
246{
247 let (res, body) = res.replace_body(());
248
249 let mut size = body.size();
251 let res = prepare_response(config, res.head(), &mut size);
252 let eof_or_head = size.is_eof() || head_req;
253
254 let mut stream = tx
256 .send_response(res, eof_or_head)
257 .map_err(DispatchError::SendResponse)?;
258
259 if eof_or_head {
260 return Ok(());
261 }
262
263 let mut body = pin!(body);
264
265 while let Some(res) = poll_fn(|cx| body.as_mut().poll_next(cx)).await {
267 let mut chunk = res.map_err(|err| DispatchError::ResponseBody(err.into()))?;
268
269 'send: loop {
270 let chunk_size = cmp::min(chunk.len(), CHUNK_SIZE);
271
272 stream.reserve_capacity(chunk_size);
274
275 match poll_fn(|cx| stream.poll_capacity(cx)).await {
276 None => return Ok(()),
278
279 Some(Err(err)) => return Err(DispatchError::SendData(err)),
280
281 Some(Ok(cap)) => {
282 let len = chunk.len();
284 let bytes = chunk.split_to(cmp::min(len, cap));
285
286 stream
287 .send_data(bytes, false)
288 .map_err(DispatchError::SendData)?;
289
290 if chunk.is_empty() {
292 break 'send;
293 }
294 }
295 }
296 }
297 }
298
299 stream
301 .send_data(Bytes::new(), true)
302 .map_err(DispatchError::SendData)?;
303
304 Ok(())
305}
306
307fn prepare_response(
308 config: ServiceConfig,
309 head: &ResponseHead,
310 size: &mut BodySize,
311) -> http::Response<()> {
312 let mut has_date = false;
313 let mut skip_len = size != &BodySize::Stream;
314
315 let mut res = http::Response::new(());
316 *res.status_mut() = head.status;
317 *res.version_mut() = http::Version::HTTP_2;
318
319 match head.status {
321 http::StatusCode::NO_CONTENT
322 | http::StatusCode::CONTINUE
323 | http::StatusCode::PROCESSING => *size = BodySize::None,
324 http::StatusCode::SWITCHING_PROTOCOLS => {
325 skip_len = true;
326 *size = BodySize::Stream;
327 }
328 _ => {}
329 }
330
331 match size {
332 BodySize::None | BodySize::Stream => {}
333
334 BodySize::Sized(0) => {
335 #[allow(clippy::declare_interior_mutable_const)]
336 const HV_ZERO: HeaderValue = HeaderValue::from_static("0");
337 res.headers_mut().insert(CONTENT_LENGTH, HV_ZERO);
338 }
339
340 BodySize::Sized(len) => {
341 let mut buf = itoa::Buffer::new();
342
343 res.headers_mut().insert(
344 CONTENT_LENGTH,
345 HeaderValue::from_str(buf.format(*len)).unwrap(),
346 );
347 }
348 };
349
350 for (key, value) in head.headers.iter() {
352 match key {
353 &CONNECTION | &TRANSFER_ENCODING | &UPGRADE => continue,
356
357 &CONTENT_LENGTH if skip_len => continue,
358 &DATE => has_date = true,
359
360 hdr if hdr == HeaderName::from_static("keep-alive")
363 || hdr == HeaderName::from_static("proxy-connection") =>
364 {
365 continue
366 }
367
368 _ => {}
369 }
370
371 res.headers_mut().append(key, value.clone());
372 }
373
374 if !has_date {
376 let mut bytes = BytesMut::with_capacity(29);
377 config.write_date_header_value(&mut bytes);
378 res.headers_mut().insert(
379 DATE,
380 unsafe { HeaderValue::from_maybe_shared_unchecked(bytes.freeze()) },
382 );
383 }
384
385 res
386}