Skip to main content

ntex/http/h2/
service.rs

1use std::{cell::Cell, cell::RefCell, future::poll_fn, io, mem, pin::Pin, rc::Rc};
2
3use ntex_h2::{self as h2, control::ExpectResult, frame::StreamId, server};
4use urly::Url;
5
6use crate::error::{Error, IntoFailure};
7use crate::http::body::{Body, BodySize, MessageBody, ResponseBody};
8use crate::http::config::{DispatcherConfig, HttpServiceConfig};
9use crate::http::error::{DispatchError, H2Error, ResponseError};
10use crate::http::header::{self, HeaderMap, HeaderName, HeaderValue};
11use crate::http::helpers::{TargetPolicy, process_request_target};
12use crate::http::message::{CurrentIo, ResponseHead};
13use crate::http::{DateService, Method, Request, Response, StatusCode, Version};
14use crate::io::{Filter, Io, IoBoxed, IoRef, types};
15use crate::service::cfg::Configuration;
16use crate::service::pipeline::{Pipeline, PipelineBinding, PipelineFactory};
17use crate::service::{BindCtx, Ctx, IntoServiceFactory, RequestState, Service, ServiceFactory};
18use crate::util::{ByteString, Bytes, HashMap};
19
20use super::{payload::Payload, payload::PayloadSender};
21
22/// An HTTP/2 transport service.
23///
24/// Construct this service with [`HttpService::h2`](crate::http::HttpService::h2).
25/// Request handling is delegated to the configured application service, while
26/// control events get their default action unless a control service is
27/// provided with [`control`](Self::control).
28///
29/// The application and control factories are instantiated for every accepted
30/// connection; see [factory scope](crate::http::HttpService#factory-scope).
31#[derive(derive_more::Debug)]
32#[debug("H2Service")]
33pub struct H2Service<F, Req: RequestState<Io<F>>, Err> {
34    sf: crate::http::HttpPipeline<Req::State, Err>,
35    /// Without a control service the default action is applied to every event.
36    ctl: Option<crate::http::Ctl2Pipeline<Req::State>>,
37    config: DispatcherConfig,
38}
39
40impl<F, Req, Err> H2Service<F, Req, Err>
41where
42    F: Filter,
43    Req: RequestState<Io<F>>,
44    Req::State: Clone,
45    Err: ResponseError + 'static,
46{
47    /// Create new `H2Service` instance.
48    pub(crate) fn new<Sf>(sf: impl IntoServiceFactory<Sf, Req::State, Request>) -> Self
49    where
50        Sf: ServiceFactory<Req::State, Request, Error = Err> + 'static,
51        Sf::Res: Into<Response>,
52        Sf::InitError: IntoFailure,
53    {
54        H2Service {
55            sf: PipelineFactory::new(
56                sf.into_factory()
57                    .map(Into::into)
58                    .map_init_err(|e| DispatchError::Control(e.fail())),
59            ),
60            ctl: None,
61            config: DispatcherConfig::default(),
62        }
63    }
64}
65
66impl<F, Req, Err> H2Service<F, Req, Err>
67where
68    F: Filter,
69    Req: RequestState<Io<F>>,
70    Req::State: Clone,
71    Err: ResponseError + 'static,
72{
73    #[must_use]
74    /// Provides the HTTP/2 control service.
75    ///
76    /// Unless this method is called, the default action is applied to each
77    /// control event without a service call.
78    pub fn control<I, Sf>(self, ctl: I) -> Self
79    where
80        I: IntoServiceFactory<Sf, Req::State, h2::Control<Error<H2Error>>>,
81        Sf: ServiceFactory<Req::State, h2::Control<Error<H2Error>>, Res = h2::ControlAck> + 'static,
82        Sf::Error: IntoFailure,
83        Sf::InitError: IntoFailure,
84    {
85        H2Service {
86            sf: self.sf,
87            ctl: Some(PipelineFactory::new(
88                ctl.into_factory()
89                    .map_err(|e| DispatchError::Service(e.fail()))
90                    .map_init_err(|e| DispatchError::Service(e.fail())),
91            )),
92            config: self.config,
93        }
94    }
95}
96
97impl<St, F, Req, Err> Service<St, Req> for H2Service<F, Req, Err>
98where
99    F: Filter,
100    Req: RequestState<Io<F>>,
101    Req::State: Clone,
102    Err: ResponseError + 'static,
103{
104    type Res = ();
105    type Error = DispatchError;
106
107    async fn call(&self, req: Req, _: Ctx<'_, Self, St>) -> Result<Self::Res, Self::Error> {
108        let (st, io) = req.unpack();
109
110        let svc = self.sf.create(st.clone()).await?;
111        let ctl = match &self.ctl {
112            Some(ctl) => Some(ctl.create(st).await?),
113            None => None,
114        };
115
116        let id = self.config.next_id();
117        let ioref = io.get_ref();
118        let (_guard, inflight) = self.config.insert_io(&ioref);
119        log::trace!(
120            "{}: New http2 connection {id}, peer address {:?}, inflight: {inflight}",
121            io.tag(),
122            io.query::<types::PeerAddr>().get()
123        );
124
125        handle(id, io.into(), svc, ctl).await
126    }
127
128    #[inline]
129    async fn ready(&self, _: Ctx<'_, Self, St>) -> Result<(), Self::Error> {
130        Ok(())
131    }
132
133    #[inline]
134    async fn shutdown(&self, _: Ctx<'_, Self, St>) {
135        // check inflight connections
136        let inflight = self.config.shutdown();
137        if inflight != 0 {
138            log::trace!("Shutting down service, in-flight connections: {inflight}");
139
140            self.config.wait_shutdown().await;
141            log::trace!("Shutting down is complected");
142        }
143    }
144}
145
146pub(in crate::http) async fn handle<Err>(
147    id: usize,
148    io: IoBoxed,
149    svc: Pipeline<Request, Response, Err>,
150    control: Option<Pipeline<h2::Control<Error<H2Error>>, h2::ControlAck, DispatchError>>,
151) -> Result<(), DispatchError>
152where
153    Err: ResponseError + 'static,
154{
155    let ioref = io.get_ref();
156    let control = Pipeline::new((), ControlService { inner: control });
157
158    let _ = server::handle_one(
159        io,
160        Pipeline::new((), PublishService::new(id, ioref, svc, control.bind())),
161        control,
162    )
163    .await;
164
165    Ok(())
166}
167
168/// Sets `GOAWAY` reason codes for connection level request errors.
169///
170/// Without a user control service the default action is applied to every event.
171struct ControlService {
172    inner: Option<Pipeline<h2::Control<Error<H2Error>>, h2::ControlAck, DispatchError>>,
173}
174
175impl Service<(), h2::Control<Error<H2Error>>> for ControlService {
176    type Res = h2::ControlAck;
177    type Error = DispatchError;
178
179    fn bind(&self, ctx: BindCtx<'_>) {
180        if let Some(inner) = &self.inner {
181            inner.bind_to(&ctx);
182        }
183    }
184
185    async fn ready(&self, _: Ctx<'_, Self, ()>) -> Result<(), Self::Error> {
186        if let Some(inner) = &self.inner {
187            inner.ready().await
188        } else {
189            Ok(())
190        }
191    }
192
193    async fn shutdown(&self, _: Ctx<'_, Self, ()>) {
194        if let Some(inner) = &self.inner {
195            inner.shutdown().await;
196        }
197    }
198
199    async fn call(
200        &self,
201        msg: h2::Control<Error<H2Error>>,
202        _: Ctx<'_, Self, ()>,
203    ) -> Result<Self::Res, Self::Error> {
204        let msg = match msg {
205            h2::Control::Disconnect(h2::control::Reason::Error(err))
206                if matches!(**err.get_ref(), H2Error::EmptyDataFrames) =>
207            {
208                h2::Control::Disconnect(h2::control::Reason::Error(
209                    err.reason(h2::frame::Reason::ENHANCE_YOUR_CALM),
210                ))
211            }
212            msg => msg,
213        };
214        if let Some(inner) = &self.inner {
215            inner.call(msg).await
216        } else {
217            log::trace!("HTTP/2 Control message: {msg:?}");
218            Ok(msg.ack())
219        }
220    }
221}
222
223struct PublishService<Err> {
224    id: usize,
225    target_policy: TargetPolicy,
226    /// `None` if the h2 decoder limit already enforces `HttpServiceConfig::max_headers`
227    max_headers: Option<usize>,
228    io: IoRef,
229    svc: Pipeline<Request, Response, Err>,
230    control: PipelineBinding<h2::Control<Error<H2Error>>, h2::ControlAck, DispatchError>,
231    streams: Rc<RefCell<HashMap<StreamId, StreamPayload>>>,
232    /// Consecutive empty non-final `DATA` frames
233    empty_data: Cell<u8>,
234}
235
236/// Maximum number of consecutive empty non-final `DATA` frames,
237/// such frames are not flow controlled
238const MAX_EMPTY_DATA_FRAMES: u8 = 10;
239
240/// Request payload of a stream.
241struct StreamPayload {
242    sender: PayloadSender,
243    /// The response is complete
244    complete: bool,
245}
246
247impl<Err> PublishService<Err>
248where
249    Err: ResponseError,
250{
251    fn new(
252        id: usize,
253        io: IoRef,
254        svc: Pipeline<Request, Response, Err>,
255        control: PipelineBinding<h2::Control<Error<H2Error>>, h2::ControlAck, DispatchError>,
256    ) -> Self {
257        let cfg = io.cfg().ctx().get::<HttpServiceConfig>();
258        let max_headers = usize::from(cfg.max_headers);
259        // the h2 decoder refuses header blocks over its own limit, it counts
260        // fields the same way, so an equal or larger limit is always met
261        let h2_max_headers = cfg.get_shared::<h2::ServiceConfig>().max_headers();
262        Self {
263            id,
264            target_policy: cfg.target_policy(),
265            max_headers: (max_headers < h2_max_headers).then_some(max_headers),
266            io,
267            svc,
268            control,
269            streams: Rc::new(RefCell::new(HashMap::default())),
270            empty_data: Cell::new(0),
271        }
272    }
273}
274
275impl<Err> PublishService<Err> {
276    /// Answers a rejected request with an empty response, the connection stays open.
277    fn reject(&self, stream: &h2::StreamRef, status: StatusCode, eof: bool) {
278        self.streams.borrow_mut().remove(&stream.id());
279
280        let mut res = Response::new(status).drop_body();
281        let head = res.head_mut();
282        prepare_response(head, &mut BodySize::Empty);
283        let _ = stream.send_response(status, &head.headers, true);
284        if !eof {
285            // the request body is not needed
286            stream.reset(h2::frame::Reason::NO_ERROR);
287        }
288    }
289
290    /// Starts a request: registers its payload, validates the request head and
291    /// builds the request.
292    ///
293    /// Runs before the publish future is created, so the pseudo headers and
294    /// the request target are not kept in it. Only `Expect: 100-continue`
295    /// waits for the control service.
296    fn request_head(
297        &self,
298        stream: h2::StreamRef,
299        pseudo: h2::frame::PseudoHeaders,
300        headers: HeaderMap,
301        eof: bool,
302    ) -> Start<'_> {
303        let payload = if eof {
304            None
305        } else {
306            #[cfg(feature = "trace")]
307            log::debug!(
308                "{}: Creating local payload stream for {:?}",
309                self.io.tag(),
310                stream.id()
311            );
312            let (sender, payload) = Payload::create(stream.empty_capacity());
313            self.streams.borrow_mut().insert(
314                stream.id(),
315                StreamPayload {
316                    sender,
317                    complete: false,
318                },
319            );
320            Some(payload)
321        };
322
323        // repeated header names count separately, like HTTP/1
324        if let Some(max) = self.max_headers
325            && headers.iter().nth(max).is_some()
326        {
327            log::debug!("{}: Too many headers on {:?}", self.io.tag(), stream.id());
328            self.reject(&stream, StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE, eof);
329            return Start::Done(Ok(()));
330        }
331
332        // a malformed request is a stream error, the connection stays open,
333        // see RFC 9113 section 8.1.1
334        let Some(target) = request_uri(&pseudo, self.target_policy) else {
335            log::debug!(
336                "{}: Malformed request on {:?}: {pseudo:?}",
337                self.io.tag(),
338                stream.id()
339            );
340            self.reject(&stream, StatusCode::BAD_REQUEST, eof);
341            return Start::Done(Ok(()));
342        };
343
344        // the client waits for `100 Continue` before sending the request body,
345        // see RFC 9110 section 10.1.1
346        if !eof && expect_continue(&headers) {
347            return Start::Expect(Box::pin(
348                self.expect_continue(stream, target, pseudo, headers, payload),
349            ));
350        }
351
352        log::trace!(
353            "{}: {:?} got request (eof: {eof}): {pseudo:#?}\nheaders: {headers:#?}",
354            self.io.tag(),
355            stream.id()
356        );
357        Start::Request(self.request(stream, target, headers, payload))
358    }
359
360    /// Answers `Expect: 100-continue` with the control service, then builds
361    /// the request.
362    async fn expect_continue(
363        &self,
364        stream: h2::StreamRef,
365        target: Target,
366        pseudo: h2::frame::PseudoHeaders,
367        headers: HeaderMap,
368        payload: Option<Payload>,
369    ) -> Option<NewRequest> {
370        let msg = h2::Control::expect(stream.clone(), pseudo, headers);
371        let (pseudo, headers) = match self
372            .control
373            .call(msg)
374            .await
375            .map(h2::ControlAck::into_expect)
376        {
377            Ok(Some(ExpectResult::Continue(expect))) => {
378                if stream
379                    .send_informational(StatusCode::CONTINUE, HeaderMap::new())
380                    .is_err()
381                {
382                    // the stream is closed
383                    self.streams.borrow_mut().remove(&stream.id());
384                    return None;
385                }
386                let (_, pseudo, headers) = expect.into_parts();
387                (pseudo, headers)
388            }
389            Ok(Some(ExpectResult::Failed(_, status, headers))) => {
390                self.streams.borrow_mut().remove(&stream.id());
391
392                let mut res = Response::new(status).drop_body();
393                let head = res.head_mut();
394                h2::release_header_map(mem::replace(&mut head.headers, headers));
395                prepare_response(head, &mut BodySize::Empty);
396                let _ = stream.send_response(status, &head.headers, true);
397
398                // the request body is not needed
399                stream.reset(h2::frame::Reason::NO_ERROR);
400                return None;
401            }
402            result => {
403                log::error!(
404                    "{}: Control service failed to handle expect for {:?}: {:?}",
405                    self.io.tag(),
406                    stream.id(),
407                    result.map(|_| ())
408                );
409                self.streams.borrow_mut().remove(&stream.id());
410                stream.reset(h2::frame::Reason::INTERNAL_ERROR);
411                return None;
412            }
413        };
414
415        log::trace!(
416            "{}: {:?} got request (eof: false): {pseudo:#?}\nheaders: {headers:#?}",
417            self.io.tag(),
418            stream.id()
419        );
420        Some(self.request(stream, target, headers, payload))
421    }
422
423    /// Builds the request for the application service.
424    fn request(
425        &self,
426        stream: h2::StreamRef,
427        target: Target,
428        headers: HeaderMap,
429        payload: Option<Payload>,
430    ) -> NewRequest {
431        let mut req = if let Some(pl) = payload {
432            Request::with_payload(crate::http::Payload::H2(pl))
433        } else {
434            Request::new()
435        };
436
437        let is_head_req = target.method == Method::HEAD;
438        let head = req.head_mut();
439        head.set_stream(stream.clone());
440        head.uri = target.uri;
441        head.scheme = target.scheme;
442        head.authority = target.authority;
443        head.version = Version::HTTP_2;
444        head.method = target.method;
445        // the pooled head map is empty, the h2 decoder reuses its allocation
446        h2::release_header_map(mem::replace(&mut head.headers, headers));
447        head.io = CurrentIo::Ref(self.io.clone());
448        head.id = self.id;
449
450        NewRequest {
451            stream,
452            req,
453            is_head_req,
454        }
455    }
456
457    /// Feeds a `DATA` frame to the request payload.
458    fn data(
459        &self,
460        stream: &h2::StreamRef,
461        data: Bytes,
462        cap: h2::Capacity,
463    ) -> Result<(), Error<H2Error>> {
464        #[cfg(feature = "trace")]
465        log::debug!(
466            "{}: Got data chunk for {:?}: {:?}",
467            self.io.tag(),
468            stream.id(),
469            data.len()
470        );
471        // the limit is sticky, frames buffered after it are not delivered
472        let count = if data.is_empty() {
473            self.empty_data.get().saturating_add(1)
474        } else if self.empty_data.get() >= MAX_EMPTY_DATA_FRAMES {
475            MAX_EMPTY_DATA_FRAMES
476        } else {
477            0
478        };
479        self.empty_data.set(count);
480        if count >= MAX_EMPTY_DATA_FRAMES {
481            log::debug!(
482                "{}: Too many consecutive empty DATA frames, closing connection",
483                self.io.tag()
484            );
485            return Err(H2Error::EmptyDataFrames.into());
486        }
487        let mut streams = self.streams.borrow_mut();
488        if let Some(pl) = streams.get(&stream.id()) {
489            if pl.complete && pl.sender.is_dropped() {
490                // the response is complete, the request body is dropped unread
491                streams.remove(&stream.id());
492                drop(streams);
493                stream.reset(h2::frame::Reason::NO_ERROR);
494            } else {
495                pl.sender.feed_data(data, cap);
496            }
497        } else {
498            log::error!(
499                "{}: Payload stream does not exists for {:?}",
500                self.io.tag(),
501                stream.id()
502            );
503        }
504        Ok(())
505    }
506
507    /// Completes the request payload.
508    fn eof(&self, stream: &h2::StreamRef, item: h2::StreamEof) -> Result<(), Error<H2Error>> {
509        log::debug!(
510            "{}: Got payload eof for {:?}: {item:?}",
511            self.io.tag(),
512            stream.id()
513        );
514        if self.empty_data.get() >= MAX_EMPTY_DATA_FRAMES {
515            return Err(H2Error::EmptyDataFrames.into());
516        }
517        if matches!(item, h2::StreamEof::Data(ref data, _) if !data.is_empty()) {
518            self.empty_data.set(0);
519        }
520        if let Some(StreamPayload { sender, .. }) = self.streams.borrow_mut().remove(&stream.id()) {
521            match item {
522                h2::StreamEof::Data(data, cap) => {
523                    sender.feed_eof(data, Some(cap));
524                }
525                h2::StreamEof::Trailers(hdrs) => {
526                    sender.feed_trailers(hdrs);
527                }
528                h2::StreamEof::Error(err) => {
529                    sender.set_error(err.into_error().into());
530                }
531            }
532        }
533        Ok(())
534    }
535}
536
537/// The synchronous part of handling an [`h2::Message`].
538enum Start<'a> {
539    /// The message is handled.
540    Done(Result<(), Error<H2Error>>),
541    /// The request is ready for the application service.
542    Request(NewRequest),
543    /// The client waits for `100 Continue`, `None` if the stream is answered.
544    Expect(Pin<Box<dyn Future<Output = Option<NewRequest>> + 'a>>),
545}
546
547/// A request ready for the application service.
548struct NewRequest {
549    stream: h2::StreamRef,
550    req: Request,
551    is_head_req: bool,
552}
553
554impl<Err> Service<(), h2::Message> for PublishService<Err>
555where
556    Err: ResponseError + 'static,
557{
558    type Res = ();
559    type Error = Error<H2Error>;
560
561    // Keep payload delivery independent of application capacity.
562    // New requests check readiness through `self.svc.call`.
563    fn bind(&self, ctx: BindCtx<'_>) {
564        self.svc.bind_to(&ctx);
565        self.control.bind_to(&ctx);
566    }
567
568    async fn shutdown(&self, _: Ctx<'_, Self, ()>) {
569        self.svc.shutdown().await;
570    }
571
572    // A plain fn keeps the message out of the publish future,
573    // an `async fn` would store it next to the service call.
574    fn call(
575        &self,
576        msg: h2::Message,
577        _: Ctx<'_, Self, ()>,
578    ) -> impl Future<Output = Result<Self::Res, Self::Error>> {
579        let h2::Message { stream, kind } = msg;
580        let start = match kind {
581            h2::MessageKind::Headers {
582                pseudo,
583                headers,
584                eof,
585            } => self.request_head(stream, pseudo, headers, eof),
586            h2::MessageKind::Data(data, cap) => Start::Done(self.data(&stream, data, cap)),
587            h2::MessageKind::Eof(item) => Start::Done(self.eof(&stream, item)),
588            h2::MessageKind::Disconnect(err) => {
589                log::debug!("{}: Connection is disconnected {err:?}", self.io.tag());
590                if let Some(pl) = self.streams.borrow_mut().remove(&stream.id()) {
591                    pl.sender
592                        .set_error(io::Error::new(io::ErrorKind::UnexpectedEof, err).into());
593                }
594                Start::Done(Ok(()))
595            }
596        };
597
598        async move {
599            let NewRequest {
600                stream,
601                req,
602                is_head_req,
603            } = match start {
604                Start::Done(result) => return result,
605                Start::Request(req) => req,
606                Start::Expect(fut) => match fut.await {
607                    Some(req) => req,
608                    None => return Ok(()),
609                },
610            };
611
612            let result = self.svc.call(req).await;
613            let (mut res, mut body) = Response::from(result).into_parts();
614
615            // an interim response cannot complete the request and `101` is not
616            // supported in HTTP/2, see RFC 9113 section 8.1 and 8.6
617            let status = res.status();
618            if status.is_informational() {
619                log::error!(
620                    "{}: Informational response {status} is not supported, sending 500",
621                    self.io.tag()
622                );
623                res = Response::new(StatusCode::INTERNAL_SERVER_ERROR).drop_body();
624                body = ResponseBody::Other(Body::Empty);
625            }
626
627            let head = res.head_mut();
628            let mut size = body.size();
629            prepare_response(head, &mut size);
630
631            #[cfg(feature = "trace")]
632            log::debug!(
633                "{}: Received service response: {head:?} payload: {size:?}",
634                self.io.tag()
635            );
636
637            // borrowed, the pooled response head keeps its header map capacity
638            let hdrs = &head.headers;
639            // `Err(Some(_))` is a body error, `Err(None)` is a closed stream
640            let sent = async {
641                if size.is_eof() || is_head_req {
642                    stream
643                        .send_response(head.status, hdrs, true)
644                        .map_err(|_| None)?;
645                    return Ok(());
646                }
647                stream
648                    .send_response(head.status, hdrs, false)
649                    .map_err(|_| None)?;
650
651                // the last chunk of a sized body ends the stream, no empty eof frame
652                let mut remaining = if let BodySize::Sized(len) = size {
653                    Some(len)
654                } else {
655                    None
656                };
657                loop {
658                    match poll_fn(|cx| body.poll_next_chunk(cx)).await {
659                        None => {
660                            #[cfg(feature = "trace")]
661                            log::debug!(
662                                "{}: {:?} closing payload stream",
663                                self.io.tag(),
664                                stream.id()
665                            );
666                            return stream
667                                .send_payload(Bytes::new(), true)
668                                .await
669                                .map_err(|_| None);
670                        }
671                        Some(Ok(chunk)) => {
672                            #[cfg(feature = "trace")]
673                            log::debug!(
674                                "{}: {:?} sending data chunk {:?} bytes",
675                                self.io.tag(),
676                                stream.id(),
677                                chunk.len()
678                            );
679                            if !chunk.is_empty() {
680                                let eof = remaining.as_mut().is_some_and(|rem| {
681                                    *rem = rem.saturating_sub(chunk.len() as u64);
682                                    *rem == 0
683                                });
684                                stream.send_payload(chunk, eof).await.map_err(|_| None)?;
685                                if eof {
686                                    return Ok(());
687                                }
688                            }
689                        }
690                        Some(Err(e)) => return Err(Some(e)),
691                    }
692                }
693            }
694            .await;
695
696            match sent {
697                Ok(()) => (),
698                Err(Some(e)) => {
699                    // only the stream fails, the connection stays open
700                    log::error!(
701                        "{}: Response payload stream error for {:?}: {e:?}",
702                        self.io.tag(),
703                        stream.id()
704                    );
705                    stream.reset(h2::frame::Reason::INTERNAL_ERROR);
706                    return Ok(());
707                }
708                Err(None) => {
709                    // the stream is reset or the connection is closed
710                    self.streams.borrow_mut().remove(&stream.id());
711                    return Ok(());
712                }
713            }
714
715            // the response is complete, an unread request body must not keep the stream
716            let id = stream.id();
717            let mut streams = self.streams.borrow_mut();
718            if let Some(pl) = streams.get_mut(&id) {
719                if pl.sender.is_dropped() {
720                    streams.remove(&id);
721                    drop(streams);
722                    stream.reset(h2::frame::Reason::NO_ERROR);
723                } else {
724                    // the app still holds the request body, release the stream once it is dropped
725                    pl.complete = true;
726                    let streams = Rc::downgrade(&self.streams);
727                    pl.sender.on_drop(move || {
728                        if let Some(streams) = streams.upgrade()
729                            && let Ok(mut streams) = streams.try_borrow_mut()
730                        {
731                            streams.remove(&id);
732                        }
733                        stream.reset(h2::frame::Reason::NO_ERROR);
734                    });
735                }
736            }
737            Ok(())
738        }
739    }
740}
741
742#[allow(clippy::declare_interior_mutable_const)]
743const ZERO_CONTENT_LENGTH: HeaderValue = HeaderValue::from_static("0");
744#[allow(clippy::declare_interior_mutable_const)]
745const KEEP_ALIVE: HeaderName = HeaderName::from_static("keep-alive");
746#[allow(clippy::declare_interior_mutable_const)]
747const PROXY_CONNECTION: HeaderName = HeaderName::from_static("proxy-connection");
748
749/// Request target built from HTTP/2 pseudo-headers.
750struct Target {
751    method: Method,
752    uri: Url,
753    /// `:scheme`, `None` for `CONNECT`.
754    scheme: Option<ByteString>,
755    /// `:authority`, `None` for `CONNECT`, whose `uri` holds it.
756    authority: Option<ByteString>,
757}
758
759/// Builds the request target from HTTP/2 pseudo-headers, validating and
760/// normalizing it according to `policy`.
761///
762/// A `CONNECT` request gets its authority-form target as the URI. Other
763/// requests get an origin-form URI from `:path`, while `:scheme` and
764/// `:authority` are kept separately, see RFC 9113 section 8.3.1.
765fn request_uri(pseudo: &h2::frame::PseudoHeaders, policy: TargetPolicy) -> Option<Target> {
766    let method = pseudo.method.clone()?;
767    // Mandatory pseudo-header presence and CONNECT combinations are checked by ntex-h2.
768    if method == Method::CONNECT {
769        let authority = pseudo.authority.as_ref()?;
770        let mut uri = Url::from_target_parts(None, Some(authority), "").ok()?;
771        process_request_target(policy, &method, Version::HTTP_2, &mut uri).ok()?;
772        return Some(Target {
773            method,
774            uri,
775            scheme: None,
776            authority: None,
777        });
778    }
779
780    let scheme = pseudo.scheme.as_ref()?;
781    let path = pseudo.path.as_ref()?;
782    // `parse_target_str` reads other targets as absolute- or authority-form,
783    // `:path` must not supply an authority
784    let mut uri = if path.starts_with('/') || path == "*" {
785        Url::parse_target_str(path.clone(), path.find('?'))
786    } else {
787        Url::from_target_parts(None, None, path)
788    }
789    .ok()?;
790    process_request_target(policy, &method, Version::HTTP_2, &mut uri).ok()?;
791
792    let authority = pseudo.authority.as_ref();
793    let normalize = policy == TargetPolicy::Normalize;
794    let (scheme, authority) = match policy {
795        TargetPolicy::Raw => (scheme.clone(), authority.cloned()),
796        _ if check_scheme_authority(scheme, authority.map(ByteString::as_str), normalize)? => {
797            (scheme.clone(), authority.cloned())
798        }
799        _ => {
800            let mut base =
801                Url::from_target_parts(Some(scheme), authority.map(ByteString::as_str), "/")
802                    .ok()?;
803            base.validate_target().ok()?;
804            if normalize {
805                base.normalize().ok()?;
806            }
807            (
808                same_or_copy(scheme, base.scheme_str()?),
809                authority
810                    .zip(base.authority())
811                    .map(|(orig, a)| same_or_copy(orig, a.as_str())),
812            )
813        }
814    };
815    Some(Target {
816        method,
817        uri,
818        scheme: Some(scheme),
819        authority,
820    })
821}
822
823/// Checks `:scheme` and `:authority` like `Url::validate_target`, without building a url.
824///
825/// Returns `None` if the target is invalid, `Some(true)` if it is valid and, when
826/// `normalize` is set, already normalized, and `Some(false)` if it needs the full check:
827/// an encoded host must also be valid after decoding, and a non-canonical scheme or
828/// authority must be normalized.
829fn check_scheme_authority(scheme: &str, authority: Option<&str>, normalize: bool) -> Option<bool> {
830    if authority.is_some_and(|a| a.contains('%')) {
831        return Some(false);
832    }
833    let scheme = urly::Scheme::new(scheme).ok()?;
834    let Some(authority) = authority else {
835        return Some(!normalize || !has_uppercase(scheme.as_str()));
836    };
837    let a = urly::Authority::new(authority).ok()?;
838    let host = a.host();
839    if a.userinfo().is_some() || host.is_empty() {
840        return None;
841    }
842    if !normalize {
843        return Some(true);
844    }
845    // normalization lowercases the scheme and host, canonicalizes IPv6, drops an
846    // empty or default port and strips leading zeros from the port, the authority
847    // starts with the host as it has no userinfo
848    let port = authority[host.len()..].strip_prefix(':');
849    Some(
850        !has_uppercase(scheme.as_str())
851            && !has_uppercase(host)
852            && !host.starts_with('[')
853            && port.is_none_or(|p| {
854                !p.is_empty()
855                    && (p.len() == 1 || !p.starts_with('0'))
856                    && p.parse::<u16>().ok() != scheme.default_port()
857            }),
858    )
859}
860
861fn has_uppercase(s: &str) -> bool {
862    s.bytes().any(|b| b.is_ascii_uppercase())
863}
864
865/// Returns `orig` if `value` equals it, so it keeps sharing the decode buffer.
866fn same_or_copy(orig: &ByteString, value: &str) -> ByteString {
867    if orig.as_str() == value {
868        orig.clone()
869    } else {
870        ByteString::from(value)
871    }
872}
873
874/// Checks the case-insensitive `100-continue` expectation, see RFC 9110 section 10.1.1
875fn expect_continue(headers: &HeaderMap) -> bool {
876    headers.get_all(header::EXPECT).any(|value| {
877        value
878            .as_bytes()
879            .split(|&b| b == b',')
880            .any(|e| e.trim_ascii().eq_ignore_ascii_case(b"100-continue"))
881    })
882}
883
884fn prepare_response(head: &mut ResponseHead, size: &mut BodySize) {
885    // Content length
886    // `204` and `304` responses never have a body, see RFC 9110 section 15.3.5 and 15.4.5
887    if head.status == StatusCode::NO_CONTENT || head.status == StatusCode::NOT_MODIFIED {
888        *size = BodySize::None;
889    }
890
891    // Find the headers to update in one pass, a lookup hashes the name even
892    // if the header is absent
893    let mut has_length = false;
894    let mut has_date = false;
895    let mut has_conn_specific = false;
896    for name in head.headers.keys() {
897        match *name {
898            header::CONTENT_LENGTH => has_length = true,
899            header::DATE => has_date = true,
900            header::CONNECTION | header::TRANSFER_ENCODING | header::UPGRADE => {
901                has_conn_specific = true;
902            }
903            _ => has_conn_specific |= *name == KEEP_ALIVE || *name == PROXY_CONNECTION,
904        }
905    }
906
907    match size {
908        BodySize::None | BodySize::Stream => {
909            if has_length {
910                head.headers.remove(header::CONTENT_LENGTH);
911            }
912        }
913        BodySize::Empty => head
914            .headers
915            .insert(header::CONTENT_LENGTH, ZERO_CONTENT_LENGTH),
916        BodySize::Sized(len) => {
917            head.headers
918                .insert(header::CONTENT_LENGTH, HeaderValue::from(*len));
919        }
920    }
921
922    // omit connection-specific headers, see RFC 9113 section 8.2.2
923    if has_conn_specific {
924        head.headers.remove(header::CONNECTION);
925        head.headers.remove(header::TRANSFER_ENCODING);
926        head.headers.remove(header::UPGRADE);
927        head.headers.remove(KEEP_ALIVE);
928        head.headers.remove(PROXY_CONNECTION);
929    }
930
931    // set date header
932    if !has_date {
933        head.headers
934            .insert(header::DATE, DateService::header_value());
935    }
936}
937
938#[cfg(test)]
939mod tests {
940    use super::*;
941
942    fn valid_target(pseudo: &h2::frame::PseudoHeaders) -> bool {
943        assert!(request_uri(pseudo, TargetPolicy::Raw).is_some());
944        let valid = request_uri(pseudo, TargetPolicy::Validate).is_some();
945        assert_eq!(
946            request_uri(pseudo, TargetPolicy::Normalize).is_some(),
947            valid
948        );
949        valid
950    }
951
952    /// STATEMENT: HTTP/2 targets keep `:path` as an origin-form uri with `:scheme` and
953    /// `:authority` stored beside it, and target validation and normalization are opt-in.
954    ///
955    /// HOW:
956    /// - Build targets from pseudo headers, including CONNECT, OPTIONS and double-slash paths.
957    /// - Check the uri, scheme and authority with processing disabled, and that malformed
958    ///   values are rejected and components are normalized when enabled.
959    /// - Check that a `:path` in absolute- or authority-form does not supply the uri
960    ///   scheme or authority, normalization length limits, preservation of OPTIONS
961    ///   asterisk-form and rejection of asterisk-form for other methods under every policy.
962    #[test]
963    fn test_request_uri() {
964        let mut pseudo = h2::frame::PseudoHeaders::default();
965        assert!(request_uri(&pseudo, TargetPolicy::Raw).is_none());
966
967        // CONNECT uses the authority form
968        pseudo.method = Some(Method::CONNECT);
969        pseudo.authority = Some("example.com:443".into());
970        let target = request_uri(&pseudo, TargetPolicy::Normalize).unwrap();
971        assert_eq!(target.method, Method::CONNECT);
972        assert_eq!(target.uri.authority().unwrap(), "example.com:443");
973        assert!(target.scheme.is_none());
974        assert!(target.authority.is_none());
975
976        for authority in ["bad authority", "[email protected]:443", ":443"] {
977            pseudo.authority = Some(authority.into());
978            assert!(!valid_target(&pseudo), "{authority}");
979        }
980
981        // inline and heap buffers
982        for authority in ["a.io:1", "very-long-host-name.example.com:8443"] {
983            pseudo.authority = Some(authority.into());
984            let uri = request_uri(&pseudo, TargetPolicy::Raw).unwrap().uri;
985            assert_eq!(uri.authority().unwrap(), authority);
986            assert_eq!(uri.to_string(), format!("//{authority}"));
987        }
988
989        // other methods require the scheme, the uri holds only the path
990        pseudo.method = Some(Method::GET);
991        pseudo.authority = Some("example.com".into());
992        pseudo.path = Some("/path".into());
993        assert!(request_uri(&pseudo, TargetPolicy::Raw).is_none());
994        pseudo.scheme = Some("https".into());
995        let target = request_uri(&pseudo, TargetPolicy::Normalize).unwrap();
996        assert_eq!(target.method, Method::GET);
997        assert_eq!(target.uri.as_str(), "/path");
998        assert!(target.uri.scheme_str().is_none());
999        assert!(target.uri.authority().is_none());
1000        assert_eq!(target.scheme.as_deref(), Some("https"));
1001        assert_eq!(target.authority.as_deref(), Some("example.com"));
1002        // userinfo and an empty host are kept raw but fail validation
1003        for authority in ["u:[email protected]", ""] {
1004            pseudo.authority = Some(authority.into());
1005            let target = request_uri(&pseudo, TargetPolicy::Raw).unwrap();
1006            assert_eq!(target.authority.as_deref(), Some(authority));
1007            assert!(!valid_target(&pseudo), "{authority}");
1008        }
1009        pseudo.authority = Some("example.com".into());
1010
1011        pseudo.path = Some("/api/v1/users/1?fields=name,email".into());
1012        let uri = request_uri(&pseudo, TargetPolicy::Raw).unwrap().uri;
1013        assert_eq!(uri.path(), "/api/v1/users/1");
1014        assert_eq!(uri.path_and_query(), "/api/v1/users/1?fields=name,email");
1015
1016        // target components are normalized only when enabled
1017        pseudo.scheme = Some("HTTPS".into());
1018        pseudo.authority = Some("Example.COM:00080".into());
1019        pseudo.path = Some("/a/./b/../c".into());
1020        for policy in [TargetPolicy::Raw, TargetPolicy::Validate] {
1021            let target = request_uri(&pseudo, policy).unwrap();
1022            assert_eq!(target.uri.as_str(), "/a/./b/../c");
1023            assert_eq!(target.scheme.as_deref(), Some("HTTPS"));
1024            assert_eq!(target.authority.as_deref(), Some("Example.COM:00080"));
1025        }
1026        let target = request_uri(&pseudo, TargetPolicy::Normalize).unwrap();
1027        assert_eq!(target.uri.as_str(), "/a/c");
1028        assert_eq!(target.scheme.as_deref(), Some("https"));
1029        assert_eq!(target.authority.as_deref(), Some("example.com:80"));
1030        pseudo.authority = Some("example.com".into());
1031        pseudo.path = Some("/path".into());
1032
1033        pseudo.scheme = Some("ht/tp".into());
1034        assert!(!valid_target(&pseudo));
1035        pseudo.scheme = Some("https".into());
1036        pseudo.authority = Some("example.com/x?".into());
1037        assert!(!valid_target(&pseudo));
1038        pseudo.authority = Some("example.com".into());
1039
1040        // a `:path` that is not origin-form never supplies the uri scheme or authority,
1041        // a colon in the first segment is guarded by `./`, see RFC 3986 section 4.2
1042        for (path, uri_path) in [
1043            ("x", "x"),
1044            ("http://evil.com/x", "./http://evil.com/x"),
1045            ("evil.com:80", "./evil.com:80"),
1046        ] {
1047            pseudo.path = Some(path.into());
1048            let target = request_uri(&pseudo, TargetPolicy::Raw).unwrap();
1049            assert_eq!(target.uri.path(), uri_path);
1050            assert!(target.uri.scheme_str().is_none(), "{path}");
1051            assert!(target.uri.authority().is_none(), "{path}");
1052            assert_eq!(target.authority.as_deref(), Some("example.com"));
1053            assert!(!valid_target(&pseudo), "{path}");
1054        }
1055
1056        pseudo.authority = None;
1057        pseudo.path = Some("/path".into());
1058        let target = request_uri(&pseudo, TargetPolicy::Normalize).unwrap();
1059        assert_eq!(target.uri.path(), "/path");
1060        assert!(target.authority.is_none());
1061        pseudo.path = Some("//example.com/path".into());
1062        let uri = request_uri(&pseudo, TargetPolicy::Normalize).unwrap().uri;
1063        assert_eq!(uri.path(), "//example.com/path");
1064        assert!(uri.authority().is_none());
1065        pseudo.path = Some("/a b".into());
1066        assert!(!valid_target(&pseudo));
1067        pseudo.path = Some("/a\x7f".into());
1068        assert!(!valid_target(&pseudo));
1069        for path in ["/a#f", "/a%zz", "/a\"", "/a%00"] {
1070            pseudo.path = Some(path.into());
1071            assert!(!valid_target(&pseudo), "{path}");
1072        }
1073        pseudo.path = Some("/a%3b/%2e%2e/b?%00".into());
1074        let uri = request_uri(&pseudo, TargetPolicy::Raw).unwrap().uri;
1075        assert_eq!(uri.path_and_query(), "/a%3b/%2e%2e/b?%00");
1076        let uri = request_uri(&pseudo, TargetPolicy::Normalize).unwrap().uri;
1077        assert_eq!(uri.path_and_query(), "/b?%00");
1078
1079        pseudo.path = Some(format!("/{}", "[".repeat(22000)).into());
1080        assert!(request_uri(&pseudo, TargetPolicy::Raw).is_some());
1081        assert!(request_uri(&pseudo, TargetPolicy::Normalize).is_none());
1082
1083        pseudo.path = Some("*".into());
1084        for policy in [
1085            TargetPolicy::Raw,
1086            TargetPolicy::Validate,
1087            TargetPolicy::Normalize,
1088        ] {
1089            assert!(request_uri(&pseudo, policy).is_none());
1090        }
1091        pseudo.method = Some(Method::OPTIONS);
1092        let uri = request_uri(&pseudo, TargetPolicy::Normalize).unwrap().uri;
1093        assert_eq!(uri.path(), "*");
1094        assert_eq!(uri.as_str(), "*");
1095    }
1096
1097    /// STATEMENT: HTTP/2 preserves authority boundaries for opt-in transport validation.
1098    ///
1099    /// HOW:
1100    /// - Preserve malformed authorities with processing disabled and reject them when enabled.
1101    /// - Accept valid authorities while preserving their case, escapes, port spelling and
1102    ///   boundaries, in the uri for CONNECT and beside the origin-form uri otherwise.
1103    #[test]
1104    fn test_request_uri_authority() {
1105        for (method, path) in [
1106            (Method::GET, Some("/path")),
1107            (Method::CONNECT, None),
1108            (Method::OPTIONS, Some("*")),
1109        ] {
1110            let mut pseudo = h2::frame::PseudoHeaders {
1111                method: Some(method),
1112                scheme: path.map(|_| "https".into()),
1113                path: path.map(Into::into),
1114                ..Default::default()
1115            };
1116            // returns the uri and the authority
1117            let target = |pseudo: &h2::frame::PseudoHeaders, policy| {
1118                let target = request_uri(pseudo, policy).unwrap();
1119                let authority = if path.is_some() {
1120                    assert!(target.uri.authority().is_none());
1121                    target.authority.unwrap().to_string()
1122                } else {
1123                    assert!(target.authority.is_none());
1124                    target.uri.authority().unwrap().as_str().to_owned()
1125                };
1126                (target.uri.to_string(), authority)
1127            };
1128            for authority in [
1129                "",
1130                ":",
1131                ":443",
1132                "@example.com",
1133                "u:[email protected]:443",
1134                "example.com@",
1135                "[email protected]",
1136                "bad authority",
1137                "exa\tmple.com",
1138                "m\u{fc}nchen.de",
1139                "example.com/path",
1140                "example.com?query",
1141                "example.com#fragment",
1142                "example.com%zz",
1143                "example.com:abc",
1144                "example.com:+443",
1145                "example.com:65536",
1146                "127.0.0.256",
1147                "::1",
1148                "[::1",
1149                "[::g]",
1150                "[::1]:65536",
1151            ] {
1152                pseudo.authority = Some(authority.into());
1153                assert_eq!(target(&pseudo, TargetPolicy::Raw).1, authority);
1154                assert!(!valid_target(&pseudo), "{pseudo:?}");
1155            }
1156            for authority in [
1157                "example.com",
1158                "Example.COM:00080",
1159                "example.com:",
1160                "example.com:0",
1161                "example.com:65535",
1162                "%45xample.com:443",
1163                "127.0.0.1:8443",
1164                "[::1]",
1165                "[0:0:0:0:0:0:0:1]:00443",
1166            ] {
1167                pseudo.authority = Some(authority.into());
1168                let expected = (
1169                    path.map_or_else(|| format!("//{authority}"), ToOwned::to_owned),
1170                    authority.to_owned(),
1171                );
1172                assert_eq!(target(&pseudo, TargetPolicy::Raw), expected, "{pseudo:?}");
1173                assert_eq!(
1174                    target(&pseudo, TargetPolicy::Validate),
1175                    expected,
1176                    "{pseudo:?}"
1177                );
1178                assert!(valid_target(&pseudo), "{pseudo:?}");
1179            }
1180        }
1181    }
1182
1183    /// STATEMENT: HTTP/2 `:scheme` and `:authority` checks agree with building a url from
1184    /// them and calling `Url::validate_target` and `Url::normalize`.
1185    ///
1186    /// HOW:
1187    /// - Combine valid, invalid, non-canonical, encoded, IPv4 and IPv6 values.
1188    /// - Compare the scheme and authority of `request_uri` under `Validate` and `Normalize`
1189    ///   with the url built, validated and optionally normalized from the same values.
1190    #[test]
1191    fn test_request_uri_scheme_authority() {
1192        let reference = |scheme: &str, authority: Option<&str>, normalize: bool| {
1193            let mut url = Url::from_target_parts(Some(scheme), authority, "/").ok()?;
1194            url.validate_target().ok()?;
1195            if normalize {
1196                url.normalize().ok()?;
1197            }
1198            let authority = url.authority().map(|a| a.as_str().to_owned());
1199            Some((url.scheme_str()?.to_owned(), authority))
1200        };
1201        for scheme in ["https", "HTTPS", "http", "h2+x.y-z", "1http", "ht/tp", ""] {
1202            for authority in [
1203                None,
1204                Some("example.com"),
1205                Some("Example.COM:00080"),
1206                Some("example.com:"),
1207                Some("example.com:0"),
1208                Some("example.com:0443"),
1209                Some("example.com:443"),
1210                Some("example.com:80"),
1211                Some("example.com:8443"),
1212                Some("example.com:65536"),
1213                Some("127.0.0.1:8080"),
1214                Some("127.0.0.256"),
1215                Some("[::1]:443"),
1216                Some("[0:0::1]"),
1217                Some("[::1"),
1218                Some("%65xample.com"),
1219                Some("%45xample.com:0080"),
1220                Some("example.com%zz"),
1221                Some("[email protected]"),
1222                Some(""),
1223                Some(":443"),
1224                Some("bad host"),
1225            ] {
1226                let pseudo = h2::frame::PseudoHeaders {
1227                    method: Some(Method::GET),
1228                    scheme: Some(scheme.into()),
1229                    authority: authority.map(Into::into),
1230                    path: Some("/".into()),
1231                    ..Default::default()
1232                };
1233                for policy in [TargetPolicy::Validate, TargetPolicy::Normalize] {
1234                    let target = request_uri(&pseudo, policy).map(|t| {
1235                        (
1236                            t.scheme.unwrap().to_string(),
1237                            t.authority.map(|a| a.to_string()),
1238                        )
1239                    });
1240                    let expected = reference(scheme, authority, policy == TargetPolicy::Normalize);
1241                    assert_eq!(target, expected, "{scheme:?} {authority:?} {policy:?}");
1242                }
1243            }
1244        }
1245    }
1246
1247    /// STATEMENT: HTTP/2 responses drop connection-specific headers, get a content-length
1248    /// that matches the body size, and keep or add a `date` header.
1249    ///
1250    /// HOW:
1251    /// - For each of the five connection-specific headers, prepare a response with only
1252    ///   that header plus a custom header, a stale `content-length` and a `date`; check
1253    ///   that only the custom header, the original `date` and the sized
1254    ///   `content-length` remain.
1255    /// - Prepare `Empty`, streaming and `204` sized responses without a `date`; check the
1256    ///   `content-length` is `0`, removed and removed, the size becomes `None` for `204`,
1257    ///   and a `date` is added.
1258    #[crate::rt_test]
1259    async fn test_prepare_response() {
1260        for name in [
1261            header::CONNECTION,
1262            header::TRANSFER_ENCODING,
1263            header::UPGRADE,
1264            KEEP_ALIVE,
1265            PROXY_CONNECTION,
1266        ] {
1267            let mut head = ResponseHead::new(StatusCode::OK, Version::HTTP_2);
1268            let hdrs = head.headers_mut();
1269            hdrs.insert(name.clone(), HeaderValue::from_static("value"));
1270            hdrs.insert(header::CONTENT_LENGTH, HeaderValue::from_static("100"));
1271            hdrs.insert(header::DATE, HeaderValue::from_static("custom"));
1272            hdrs.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/plain"));
1273
1274            let mut size = BodySize::Sized(5);
1275            prepare_response(&mut head, &mut size);
1276            assert_eq!(size, BodySize::Sized(5));
1277            assert!(!head.headers.contains_key(&name), "{name}");
1278            assert_eq!(head.headers.len(), 3, "{name}");
1279            assert_eq!(head.headers.get(header::CONTENT_LENGTH).unwrap(), "5");
1280            assert_eq!(head.headers.get(header::DATE).unwrap(), "custom");
1281            assert_eq!(
1282                head.headers.get(header::CONTENT_TYPE).unwrap(),
1283                "text/plain"
1284            );
1285        }
1286
1287        for (status, mut size, len) in [
1288            (StatusCode::OK, BodySize::Empty, Some("0")),
1289            (StatusCode::OK, BodySize::Stream, None),
1290            (StatusCode::NO_CONTENT, BodySize::Sized(5), None),
1291        ] {
1292            let mut head = ResponseHead::new(status, Version::HTTP_2);
1293            head.headers
1294                .insert(header::CONTENT_LENGTH, HeaderValue::from_static("100"));
1295            prepare_response(&mut head, &mut size);
1296            if status == StatusCode::NO_CONTENT {
1297                assert_eq!(size, BodySize::None);
1298            }
1299            assert_eq!(
1300                head.headers
1301                    .get(header::CONTENT_LENGTH)
1302                    .map(|v| v.to_str().unwrap()),
1303                len,
1304                "{status}"
1305            );
1306            assert!(head.headers.contains_key(header::DATE), "{status}");
1307        }
1308    }
1309}