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#[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 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 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 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 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
168struct 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 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 empty_data: Cell<u8>,
234}
235
236const MAX_EMPTY_DATA_FRAMES: u8 = 10;
239
240struct StreamPayload {
242 sender: PayloadSender,
243 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 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 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 stream.reset(h2::frame::Reason::NO_ERROR);
287 }
288 }
289
290 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 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 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 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 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 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 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 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 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 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 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 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 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
537enum Start<'a> {
539 Done(Result<(), Error<H2Error>>),
541 Request(NewRequest),
543 Expect(Pin<Box<dyn Future<Output = Option<NewRequest>> + 'a>>),
545}
546
547struct 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 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 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 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 let hdrs = &head.headers;
639 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 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 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 self.streams.borrow_mut().remove(&stream.id());
711 return Ok(());
712 }
713 }
714
715 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 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
749struct Target {
751 method: Method,
752 uri: Url,
753 scheme: Option<ByteString>,
755 authority: Option<ByteString>,
757}
758
759fn request_uri(pseudo: &h2::frame::PseudoHeaders, policy: TargetPolicy) -> Option<Target> {
766 let method = pseudo.method.clone()?;
767 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 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
823fn 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 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
865fn 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
874fn 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 if head.status == StatusCode::NO_CONTENT || head.status == StatusCode::NOT_MODIFIED {
888 *size = BodySize::None;
889 }
890
891 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 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 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 #[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 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 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 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 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 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 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 #[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 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 #[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 #[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}