rama/cli/service/
echo.rs

1//! Echo '[`Service`] that echos the [`http`] [`Request`] and [`tls`] client config.
2//!
3//! [`Service`]: crate::Service
4//! [`http`]: crate::http
5//! [`Request`]: crate::http::Request
6//! [`tls`]: crate::tls
7
8use crate::{
9    Layer, Service,
10    cli::ForwardKind,
11    combinators::{Either, Either3, Either7},
12    error::{BoxError, ErrorContext, OpaqueError},
13    extensions::ExtensionsRef,
14    http::{
15        Request, Response, Version,
16        body::util::BodyExt,
17        convert::curl,
18        core::h2::frame::EarlyFrameCapture,
19        header::USER_AGENT,
20        headers::exotic::XClacksOverhead,
21        headers::forwarded::{CFConnectingIp, ClientIp, TrueClientIp, XClientIp, XRealIp},
22        layer::set_header::SetResponseHeaderLayer,
23        layer::{
24            forwarded::GetForwardedHeaderLayer, required_header::AddRequiredResponseHeadersLayer,
25            trace::TraceLayer,
26        },
27        proto::h1::Http1HeaderMap,
28        proto::h2::PseudoHeaderOrder,
29        server::{HttpServer, layer::upgrade::UpgradeLayer},
30        service::web::{extract::Json, response::IntoResponse},
31        ws::handshake::server::{WebSocketAcceptor, WebSocketEchoService, WebSocketMatcher},
32    },
33    layer::limit::policy::UnlimitedPolicy,
34    layer::{ConsumeErrLayer, LimitLayer, TimeoutLayer, limit::policy::ConcurrentPolicy},
35    net::fingerprint::{AkamaiH2, Ja4H},
36    net::forwarded::Forwarded,
37    net::http::RequestContext,
38    net::stream::{SocketInfo, layer::http::BodyLimitLayer},
39    proxy::haproxy::server::HaProxyLayer,
40    rt::Executor,
41    tcp::TcpStream,
42    telemetry::tracing,
43    ua::{UserAgent, layer::classifier::UserAgentClassifierLayer, profile::UserAgentDatabase},
44};
45
46use serde::Serialize;
47use serde_json::json;
48use std::{convert::Infallible, time::Duration};
49
50#[cfg(all(feature = "rustls", not(feature = "boring")))]
51use crate::tls::rustls::server::{TlsAcceptorData, TlsAcceptorLayer};
52
53#[cfg(any(feature = "rustls", feature = "boring"))]
54use crate::{
55    net::fingerprint::{Ja3, Ja4, PeetPrint},
56    net::tls::{
57        SecureTransport,
58        client::ClientHelloExtension,
59        client::{ECHClientHello, NegotiatedTlsParameters},
60    },
61};
62#[cfg(feature = "boring")]
63use crate::{
64    net::tls::server::ServerConfig,
65    tls::boring::server::{TlsAcceptorData, TlsAcceptorLayer},
66};
67
68#[cfg(feature = "boring")]
69type TlsConfig = ServerConfig;
70
71#[cfg(all(feature = "rustls", not(feature = "boring")))]
72type TlsConfig = TlsAcceptorData;
73
74#[derive(Debug, Clone)]
75/// Builder that can be used to run your own echo [`Service`],
76/// echo'ing back information about that request and its underlying transport / presentation layers.
77pub struct EchoServiceBuilder<H> {
78    concurrent_limit: usize,
79    body_limit: usize,
80    timeout: Duration,
81    forward: Option<ForwardKind>,
82
83    #[cfg(any(feature = "rustls", feature = "boring"))]
84    tls_server_config: Option<TlsConfig>,
85
86    http_version: Option<Version>,
87
88    ws_support: bool,
89
90    http_service_builder: H,
91
92    uadb: Option<std::sync::Arc<UserAgentDatabase>>,
93}
94
95impl Default for EchoServiceBuilder<()> {
96    fn default() -> Self {
97        Self {
98            concurrent_limit: 0,
99            body_limit: 1024 * 1024,
100            timeout: Duration::ZERO,
101            forward: None,
102
103            #[cfg(any(feature = "rustls", feature = "boring"))]
104            tls_server_config: None,
105
106            http_version: None,
107
108            ws_support: false,
109
110            http_service_builder: (),
111
112            uadb: None,
113        }
114    }
115}
116
117impl EchoServiceBuilder<()> {
118    /// Create a new [`EchoServiceBuilder`].
119    #[must_use]
120    pub fn new() -> Self {
121        Self::default()
122    }
123}
124
125impl<H> EchoServiceBuilder<H> {
126    crate::utils::macros::generate_set_and_with! {
127        /// set the number of concurrent connections to allow
128        ///
129        /// (0 = no limit)
130        pub fn concurrent(mut self, limit: usize) -> Self {
131            self.concurrent_limit = limit;
132            self
133        }
134    }
135
136    crate::utils::macros::generate_set_and_with! {
137        /// set the body limit in bytes for each request
138        pub fn body_limit(mut self, limit: usize) -> Self {
139            self.body_limit = limit;
140            self
141        }
142    }
143
144    crate::utils::macros::generate_set_and_with! {
145        /// set the timeout in seconds for each connection
146        ///
147        /// (0 = no timeout)
148        pub fn timeout(mut self, timeout: Duration) -> Self {
149            self.timeout = timeout;
150            self
151        }
152    }
153
154    crate::utils::macros::generate_set_and_with! {
155        /// enable support for one of the following "forward" headers or protocols
156        ///
157        /// Supported headers:
158        ///
159        /// Forwarded ("for="), X-Forwarded-For
160        ///
161        /// X-Client-IP Client-IP, X-Real-IP
162        ///
163        /// CF-Connecting-IP, True-Client-IP
164        ///
165        /// Or using HaProxy protocol.
166        pub fn forward(mut self, kind: Option<ForwardKind>) -> Self {
167            self.forward = kind;
168            self
169        }
170    }
171
172    crate::utils::macros::generate_set_and_with! {
173        #[cfg(any(feature = "rustls", feature = "boring"))]
174        /// define a tls server cert config to be used for tls terminaton
175        /// by the echo service.
176        pub fn tls_server_config(mut self, cfg: Option<TlsConfig>) -> Self {
177            self.tls_server_config = cfg;
178            self
179        }
180    }
181
182    crate::utils::macros::generate_set_and_with! {
183        /// set the http version to use for the http server (auto by default)
184        pub fn http_version(mut self, version: Option<Version>) -> Self {
185            self.http_version = version;
186            self
187        }
188    }
189
190    /// add a custom http layer which will be applied to the existing http layers
191    pub fn with_http_layer<H2>(self, layer: H2) -> EchoServiceBuilder<(H, H2)> {
192        EchoServiceBuilder {
193            concurrent_limit: self.concurrent_limit,
194            body_limit: self.body_limit,
195            timeout: self.timeout,
196            forward: self.forward,
197
198            #[cfg(any(feature = "rustls", feature = "boring"))]
199            tls_server_config: self.tls_server_config,
200
201            http_version: self.http_version,
202
203            ws_support: self.ws_support,
204
205            http_service_builder: (self.http_service_builder, layer),
206
207            uadb: self.uadb,
208        }
209    }
210
211    crate::utils::macros::generate_set_and_with! {
212        /// maybe set the user agent datasbase that if set would be used to look up
213        /// a user agent (by ua header string) to see if we have a ja3/ja4 hash.
214        pub fn user_agent_database(
215            mut self,
216            db: Option<std::sync::Arc<UserAgentDatabase>>,
217        ) -> Self {
218            self.uadb = db;
219            self
220        }
221    }
222
223    crate::utils::macros::generate_set_and_with! {
224        /// define whether or not WS support is enabled
225        pub fn ws_support(
226            mut self,
227            support: bool,
228        ) -> Self {
229            self.ws_support = support;
230            self
231        }
232    }
233}
234
235impl<H> EchoServiceBuilder<H>
236where
237    H: Layer<EchoService, Service: Service<Request, Response = Response, Error = BoxError>>,
238{
239    #[allow(unused_mut)]
240    /// build a tcp service ready to echo http traffic back
241    pub fn build(
242        mut self,
243        executor: Executor,
244    ) -> Result<impl Service<TcpStream, Response = (), Error = Infallible>, BoxError> {
245        let tcp_forwarded_layer = match &self.forward {
246            Some(ForwardKind::HaProxy) => Some(HaProxyLayer::default()),
247            _ => None,
248        };
249
250        let http_service = self.build_http();
251
252        #[cfg(all(feature = "rustls", not(feature = "boring")))]
253        let tls_cfg = self.tls_server_config;
254
255        #[cfg(feature = "boring")]
256        let tls_cfg: Option<TlsAcceptorData> = match self.tls_server_config {
257            Some(cfg) => Some(cfg.try_into()?),
258            None => None,
259        };
260
261        let tcp_service_builder = (
262            ConsumeErrLayer::trace(tracing::Level::DEBUG),
263            LimitLayer::new(if self.concurrent_limit > 0 {
264                Either::A(ConcurrentPolicy::max(self.concurrent_limit))
265            } else {
266                Either::B(UnlimitedPolicy::new())
267            }),
268            if !self.timeout.is_zero() {
269                TimeoutLayer::new(self.timeout)
270            } else {
271                TimeoutLayer::never()
272            },
273            tcp_forwarded_layer,
274            BodyLimitLayer::request_only(self.body_limit),
275            #[cfg(any(feature = "rustls", feature = "boring"))]
276            tls_cfg.map(|cfg| TlsAcceptorLayer::new(cfg).with_store_client_hello(true)),
277        );
278
279        let http_transport_service = match self.http_version {
280            Some(Version::HTTP_2) => Either3::A({
281                let mut http = HttpServer::h2(executor);
282                if self.ws_support {
283                    http.h2_mut().set_enable_connect_protocol();
284                }
285                http.service(http_service)
286            }),
287            Some(Version::HTTP_11 | Version::HTTP_10 | Version::HTTP_09) => {
288                Either3::B(HttpServer::http1().service(http_service))
289            }
290            Some(_) => {
291                return Err(OpaqueError::from_display("unsupported http version").into_boxed());
292            }
293            None => Either3::C({
294                let mut http = HttpServer::auto(executor);
295                if self.ws_support {
296                    http.h2_mut().set_enable_connect_protocol();
297                }
298                http.service(http_service)
299            }),
300        };
301
302        Ok(tcp_service_builder.into_layer(http_transport_service))
303    }
304
305    /// build an http service ready to echo http traffic back
306    pub fn build_http(
307        &self,
308    ) -> impl Service<Request, Response: IntoResponse, Error = Infallible> + use<H> {
309        let http_forwarded_layer = match &self.forward {
310            None | Some(ForwardKind::HaProxy) => None,
311            Some(ForwardKind::Forwarded) => Some(Either7::A(GetForwardedHeaderLayer::forwarded())),
312            Some(ForwardKind::XForwardedFor) => {
313                Some(Either7::B(GetForwardedHeaderLayer::x_forwarded_for()))
314            }
315            Some(ForwardKind::XClientIp) => {
316                Some(Either7::C(GetForwardedHeaderLayer::<XClientIp>::new()))
317            }
318            Some(ForwardKind::ClientIp) => {
319                Some(Either7::D(GetForwardedHeaderLayer::<ClientIp>::new()))
320            }
321            Some(ForwardKind::XRealIp) => {
322                Some(Either7::E(GetForwardedHeaderLayer::<XRealIp>::new()))
323            }
324            Some(ForwardKind::CFConnectingIp) => {
325                Some(Either7::F(GetForwardedHeaderLayer::<CFConnectingIp>::new()))
326            }
327            Some(ForwardKind::TrueClientIp) => {
328                Some(Either7::G(GetForwardedHeaderLayer::<TrueClientIp>::new()))
329            }
330        };
331
332        (
333            TraceLayer::new_for_http(),
334            SetResponseHeaderLayer::<XClacksOverhead>::if_not_present_default_typed(),
335            AddRequiredResponseHeadersLayer::default(),
336            UserAgentClassifierLayer::new(),
337            ConsumeErrLayer::default(),
338            http_forwarded_layer,
339            self.ws_support.then(|| {
340                UpgradeLayer::new(
341                    WebSocketMatcher::default(),
342                    {
343                        let acceptor = WebSocketAcceptor::default()
344                            .with_protocols_flex(true)
345                            .with_echo_protocols();
346
347                        #[cfg(feature = "compression")]
348                        {
349                            acceptor.with_per_message_deflate_overwrite_extensions()
350                        }
351                        #[cfg(not(feature = "compression"))]
352                        {
353                            acceptor
354                        }
355                    },
356                    ConsumeErrLayer::trace(tracing::Level::DEBUG)
357                        .into_layer(WebSocketEchoService::default()),
358                )
359            }),
360        )
361            .into_layer(self.http_service_builder.layer(EchoService {
362                uadb: self.uadb.clone(),
363            }))
364    }
365}
366
367#[derive(Debug, Clone)]
368#[non_exhaustive]
369/// The inner echo-service used by the [`EchoServiceBuilder`].
370pub struct EchoService {
371    uadb: Option<std::sync::Arc<UserAgentDatabase>>,
372}
373
374impl Service<Request> for EchoService {
375    type Response = Response;
376    type Error = BoxError;
377
378    async fn serve(&self, req: Request) -> Result<Self::Response, Self::Error> {
379        let user_agent_info = req
380            .extensions()
381            .get()
382            .map(|ua: &UserAgent| {
383                json!({
384                    "user_agent": ua.header_str().to_owned(),
385                    "kind": ua.info().map(|info| info.kind.to_string()),
386                    "version": ua.info().and_then(|info| info.version),
387                    "platform": ua.platform().map(|v| v.to_string()),
388                })
389            })
390            .unwrap_or_default();
391
392        let request_context = RequestContext::try_from(&req)?;
393
394        let authority = request_context.authority.to_string();
395        let scheme = request_context.protocol.to_string();
396
397        let ua_str = req
398            .headers()
399            .get(USER_AGENT)
400            .and_then(|h| h.to_str().ok())
401            .map(ToOwned::to_owned);
402        tracing::debug!(
403            user_agent.original = ua_str,
404            "echo request received from ua with ua header",
405        );
406
407        #[derive(Debug, Serialize)]
408        struct FingerprintProfileData {
409            hash: String,
410            verbose: String,
411            matched: bool,
412        }
413
414        let ja4h = Ja4H::compute(&req)
415            .inspect_err(|err| tracing::error!("ja4h compute failure: {err:?}"))
416            .ok()
417            .map(|ja4h| {
418                let mut profile_ja4h: Option<FingerprintProfileData> = None;
419
420                if let Some(uadb) = self.uadb.as_deref()
421                    && let Some(profile) =
422                        ua_str.as_deref().and_then(|s| uadb.get_exact_header_str(s))
423                    {
424                        let matched_ja4h = match req.version() {
425                            Version::HTTP_10 | Version::HTTP_11 => profile
426                                .http
427                                .ja4h_h1_navigate(Some(req.method().clone()))
428                                .inspect_err(|err| {
429                                    tracing::trace!(
430                                        "ja4h computation of matched profile for incoming h1 req: {err:?}"
431                                    )
432                                })
433                                .ok(),
434                            Version::HTTP_2 => profile
435                                .http
436                                .ja4h_h2_navigate(Some(req.method().clone()))
437                                .inspect_err(|err| {
438                                    tracing::trace!(
439                                        "ja4h computation of matched profile for incoming h2 req: {err:?}"
440                                    )
441                                })
442                                .ok(),
443                            _ => None,
444                        };
445                        if let Some(tgt) = matched_ja4h {
446                            let hash = format!("{tgt}");
447                            let matched = format!("{ja4h}") == hash;
448                            profile_ja4h = Some(FingerprintProfileData {
449                                hash,
450                                verbose: format!("{tgt:?}"),
451                                matched,
452                            });
453                        }
454                    }
455
456                json!({
457                    "hash": format!("{ja4h}"),
458                    "verbose": format!("{ja4h:?}"),
459                    "profile": profile_ja4h,
460                })
461            });
462
463        let (parts, body) = req.into_parts();
464
465        let body = body
466            .collect()
467            .await
468            .context("collect request body for echo purposes")?
469            .to_bytes();
470
471        let curl_request = curl::cmd_string_for_request_parts_and_payload(&parts, &body);
472
473        let headers: Vec<_> = Http1HeaderMap::new(parts.headers, Some(&parts.extensions))
474            .into_iter()
475            .map(|(name, value)| {
476                (
477                    name,
478                    std::str::from_utf8(value.as_bytes())
479                        .map(|s| s.to_owned())
480                        .unwrap_or_else(|_| format!("0x{:x?}", value.as_bytes())),
481                )
482            })
483            .collect();
484
485        let body = hex::encode(body.as_ref());
486
487        #[cfg(any(feature = "rustls", feature = "boring"))]
488        let tls_info = parts
489            .extensions
490            .get::<SecureTransport>()
491            .and_then(|st| st.client_hello())
492            .map(|hello| {
493                let ja4 = Ja4::compute(parts.extensions.extensions())
494                    .inspect_err(|err| tracing::trace!("ja4 computation: {err:?}"))
495                    .ok();
496
497                let mut profile_ja4: Option<FingerprintProfileData> = None;
498
499                if let Some(uadb) = self.uadb.as_deref()
500                    && let Some(profile) =
501                        ua_str.as_deref().and_then(|s| uadb.get_exact_header_str(s))
502                {
503                    let matched_ja4 = profile
504                        .tls
505                        .compute_ja4(
506                            parts
507                                .extensions
508                                .get::<NegotiatedTlsParameters>()
509                                .map(|param| param.protocol_version),
510                        )
511                        .inspect_err(|err| {
512                            tracing::trace!("ja4 computation of matched profile: {err:?}")
513                        })
514                        .ok();
515                    if let (Some(src), Some(tgt)) = (ja4.as_ref(), matched_ja4) {
516                        let hash = format!("{tgt}");
517                        let matched = format!("{src}") == hash;
518                        profile_ja4 = Some(FingerprintProfileData {
519                            hash,
520                            verbose: format!("{tgt:?}"),
521                            matched,
522                        });
523                    }
524                }
525
526                let ja4 = ja4.map(|ja4| {
527                    json!({
528                        "hash": format!("{ja4}"),
529                        "verbose": format!("{ja4:?}"),
530                        "profile": profile_ja4,
531                    })
532                });
533
534                let ja3 = Ja3::compute(parts.extensions.extensions())
535                    .inspect_err(|err| tracing::trace!("ja3 computation: {err:?}"))
536                    .ok();
537
538                let mut profile_ja3: Option<FingerprintProfileData> = None;
539
540                if let Some(uadb) = self.uadb.as_deref()
541                    && let Some(profile) =
542                        ua_str.as_deref().and_then(|s| uadb.get_exact_header_str(s))
543                {
544                    let matched_ja3 = profile
545                        .tls
546                        .compute_ja3(
547                            parts
548                                .extensions
549                                .get::<NegotiatedTlsParameters>()
550                                .map(|param| param.protocol_version),
551                        )
552                        .inspect_err(|err| {
553                            tracing::trace!("ja3 computation of matched profile: {err:?}")
554                        })
555                        .ok();
556                    if let (Some(src), Some(tgt)) = (ja3.as_ref(), matched_ja3) {
557                        let hash = format!("{tgt:x}");
558                        let matched = format!("{src:x}") == hash;
559                        profile_ja3 = Some(FingerprintProfileData {
560                            hash,
561                            verbose: format!("{tgt}"),
562                            matched,
563                        });
564                    }
565                }
566
567                let ja3 = ja3.map(|ja3| {
568                    json!({
569                        "hash": format!("{ja3:x}"),
570                        "verbose": format!("{ja3}"),
571                        "profile": profile_ja3,
572                    })
573                });
574
575                let peet = PeetPrint::compute(parts.extensions.extensions())
576                    .inspect_err(|err| tracing::trace!("peet computation: {err:?}"))
577                    .ok();
578
579                let mut profile_peet: Option<FingerprintProfileData> = None;
580
581                if let Some(uadb) = self.uadb.as_deref()
582                    && let Some(profile) =
583                        ua_str.as_deref().and_then(|s| uadb.get_exact_header_str(s))
584                {
585                    let matched_peet = profile
586                        .tls
587                        .compute_peet()
588                        .inspect_err(|err| {
589                            tracing::trace!("peetprint computation of matched profile: {err:?}")
590                        })
591                        .ok();
592                    if let (Some(src), Some(tgt)) = (peet.as_ref(), matched_peet) {
593                        let hash = format!("{tgt}");
594                        let matched = format!("{src}") == hash;
595                        profile_peet = Some(FingerprintProfileData {
596                            hash,
597                            verbose: format!("{tgt:?}"),
598                            matched,
599                        });
600                    }
601                }
602
603                let peet = peet.map(|peet| {
604                    json!({
605                        "hash": format!("{peet}"),
606                        "verbose": format!("{peet:?}"),
607                        "profile": profile_peet,
608                    })
609                });
610
611                json!({
612                    "header": {
613                        "version": hello.protocol_version().to_string(),
614                        "cipher_suites": hello
615                        .cipher_suites().iter().map(|s| s.to_string()).collect::<Vec<_>>(),
616                        "compression_algorithms": hello
617                        .compression_algorithms().iter().map(|s| s.to_string()).collect::<Vec<_>>(),
618                    },
619                    "extensions": hello.extensions().iter().map(|extension| match extension {
620                        ClientHelloExtension::ServerName(domain) => json!({
621                            "id": extension.id().to_string(),
622                            "data": domain,
623                        }),
624                        ClientHelloExtension::SignatureAlgorithms(v) => json!({
625                            "id": extension.id().to_string(),
626                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
627                        }),
628                        ClientHelloExtension::SupportedVersions(v) => json!({
629                            "id": extension.id().to_string(),
630                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
631                        }),
632                        ClientHelloExtension::ApplicationLayerProtocolNegotiation(v) => json!({
633                            "id": extension.id().to_string(),
634                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
635                        }),
636                        ClientHelloExtension::ApplicationSettings(v) => json!({
637                            "id": extension.id().to_string(),
638                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
639                        }),
640                        ClientHelloExtension::SupportedGroups(v) => json!({
641                            "id": extension.id().to_string(),
642                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
643                        }),
644                        ClientHelloExtension::ECPointFormats(v) => json!({
645                            "id": extension.id().to_string(),
646                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
647                        }),
648                        ClientHelloExtension::CertificateCompression(v) => json!({
649                            "id": extension.id().to_string(),
650                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
651                        }),
652                        ClientHelloExtension::DelegatedCredentials(v) => json!({
653                            "id": extension.id().to_string(),
654                            "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
655                        }),
656                        ClientHelloExtension::RecordSizeLimit(v) => json!({
657                            "id": extension.id().to_string(),
658                            "data": v.to_string(),
659                        }),
660                        ClientHelloExtension::EncryptedClientHello(ech) => match ech {
661                            ECHClientHello::Outer(ech) => json!({
662                                "id": extension.id().to_string(),
663                                "data": {
664                                    "type": "outer",
665                                    "cipher_suite": {
666                                        "aead_id": ech.cipher_suite.aead_id.to_string(),
667                                        "kdf_id": ech.cipher_suite.kdf_id.to_string(),
668                                    },
669                                    "config_id": ech.config_id,
670                                    "enc":  format!("0x{}", hex::encode(&ech.enc)),
671                                    "payload": format!("0x{}", hex::encode(&ech.payload)),
672                                },
673                            }),
674                            ECHClientHello::Inner => json!({
675                                "id": extension.id().to_string(),
676                                "data": {
677                                    "type": "inner",
678                                },
679                            })
680
681                        }
682                        ClientHelloExtension::Opaque { id, data } => if data.is_empty() {
683                            json!({
684                                "id": id.to_string()
685                            })
686                        } else {
687                            json!({
688                                "id": id.to_string(),
689                                "data": format!("0x{}", hex::encode(data))
690                            })
691                        },
692                    }).collect::<Vec<_>>(),
693                    "ja3": ja3,
694                    "ja4": ja4,
695                    "peet": peet
696                })
697            });
698
699        #[cfg(not(any(feature = "rustls", feature = "boring")))]
700        let tls_info: Option<()> = None;
701
702        let mut h2 = None;
703        if parts.version == Version::HTTP_2 {
704            let early_frames = parts.extensions.get::<EarlyFrameCapture>();
705            let pseudo_headers = parts.extensions.get::<PseudoHeaderOrder>();
706            let akamai_h2 = AkamaiH2::compute(&parts.extensions)
707                .inspect_err(|err| tracing::trace!("akamai h2 compute failure: {err:?}"))
708                .ok()
709                .map(|akamai| {
710                    json!({
711                        "hash": format!("{akamai}"),
712                        "verbose": format!("{akamai:?}"),
713                    })
714                });
715
716            h2 = Some(json!({
717                "early_frames": early_frames,
718                "pseudo_headers": pseudo_headers,
719                "akamai_h2": akamai_h2,
720            }));
721        }
722
723        Ok(Json(json!({
724            "ua": user_agent_info,
725            "http": {
726                "version": format!("{:?}", parts.version),
727                "scheme": scheme,
728                "method": format!("{:?}", parts.method),
729                "authority": authority,
730                "path": parts.uri.path().to_owned(),
731                "query": parts.uri.query().map(str::to_owned),
732                "h2": h2,
733                "headers": headers,
734                "payload": body,
735                "ja4h": ja4h,
736                "curl": curl_request,
737            },
738            "tls": tls_info,
739            "socket_addr": parts.extensions.get::<Forwarded>()
740                .and_then(|f|
741                        f.client_socket_addr().map(|addr| addr.to_string())
742                            .or_else(|| f.client_ip().map(|ip| ip.to_string()))
743                ).or_else(|| parts.extensions.get::<SocketInfo>().map(|v| v.peer_addr().to_string())),
744        }))
745        .into_response())
746    }
747}