Skip to main content

net_traits/
request.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4use std::collections::HashSet;
5use std::sync::Arc;
6
7use content_security_policy::{self as csp};
8use http::header::{AUTHORIZATION, HeaderName};
9use http::{HeaderMap, Method};
10use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
11use ipc_channel::router::ROUTER;
12use log::error;
13use malloc_size_of_derive::MallocSizeOf;
14use mime::Mime;
15use parking_lot::Mutex;
16use rustc_hash::FxHashMap;
17use serde::{Deserialize, Serialize};
18use servo_base::generic_channel::GenericSharedMemory;
19use servo_base::id::{PipelineId, WebViewId};
20use servo_url::{ImmutableOrigin, ServoUrl};
21use tokio::sync::oneshot::Sender as TokioSender;
22use url::Position;
23use uuid::Uuid;
24
25use crate::ReferrerPolicy;
26use crate::blob_url_store::UrlWithBlobClaim;
27use crate::policy_container::{PolicyContainer, RequestPolicyContainer};
28use crate::pub_domains::{Site, is_same_site};
29use crate::resource_fetch_timing::ResourceTimingType;
30use crate::response::{RedirectTaint, Response};
31
32/// A [network partition key](https://fetch.spec.whatwg.org/#network-partition-keys).
33/// Currently consists of a top-level site, or null if unpartitioned.
34pub type NetworkPartitionKey = Option<Site>;
35
36#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
37/// An id to differentiate one network request from another.
38pub struct RequestId(pub Uuid);
39
40impl Default for RequestId {
41    fn default() -> Self {
42        Self(Uuid::new_v4())
43    }
44}
45
46/// An [initiator](https://fetch.spec.whatwg.org/#concept-request-initiator)
47#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
48pub enum Initiator {
49    None,
50    Download,
51    ImageSet,
52    Manifest,
53    XSLT,
54    Prefetch,
55    Link,
56}
57
58/// A request [destination](https://fetch.spec.whatwg.org/#concept-request-destination)
59pub use csp::Destination;
60
61/// A request [origin](https://fetch.spec.whatwg.org/#concept-request-origin)
62#[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
63pub enum Origin {
64    Client,
65    Origin(ImmutableOrigin),
66}
67
68impl Origin {
69    pub fn is_opaque(&self) -> bool {
70        matches!(self, Origin::Origin(ImmutableOrigin::Opaque(_)))
71    }
72}
73
74/// A [referer](https://fetch.spec.whatwg.org/#concept-request-referrer)
75#[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
76pub enum Referrer {
77    NoReferrer,
78    /// Contains the url that "client" would be resolved to. See
79    /// [https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer](https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer)
80    ///
81    /// If you are unsure you should probably use
82    /// [`GlobalScope::get_referrer`](https://doc.servo.org/script/dom/globalscope/struct.GlobalScope.html#method.get_referrer)
83    Client(ServoUrl),
84    ReferrerUrl(ServoUrl),
85}
86
87/// A [request mode](https://fetch.spec.whatwg.org/#concept-request-mode)
88#[derive(Clone, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
89pub enum RequestMode {
90    Navigate,
91    SameOrigin,
92    NoCors,
93    CorsMode,
94    WebSocket {
95        protocols: Vec<String>,
96        original_url: ServoUrl,
97    },
98}
99
100/// Request [credentials mode](https://fetch.spec.whatwg.org/#concept-request-credentials-mode)
101#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
102pub enum CredentialsMode {
103    Omit,
104    CredentialsSameOrigin,
105    Include,
106}
107
108/// [Cache mode](https://fetch.spec.whatwg.org/#concept-request-cache-mode)
109#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
110pub enum CacheMode {
111    Default,
112    NoStore,
113    Reload,
114    NoCache,
115    ForceCache,
116    OnlyIfCached,
117}
118
119/// [Service-workers mode](https://fetch.spec.whatwg.org/#request-service-workers-mode)
120#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
121pub enum ServiceWorkersMode {
122    All,
123    None,
124}
125
126/// [Redirect mode](https://fetch.spec.whatwg.org/#concept-request-redirect-mode)
127#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
128pub enum RedirectMode {
129    Follow,
130    Error,
131    Manual,
132}
133
134/// [Response tainting](https://fetch.spec.whatwg.org/#concept-request-response-tainting)
135#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
136pub enum ResponseTainting {
137    Basic,
138    CorsTainting,
139    Opaque,
140}
141
142/// Servo-internal to keep track of which requests originate from Servo internal implementation
143#[derive(Clone, Copy, Debug, Default, Deserialize, MallocSizeOf, PartialEq, Serialize)]
144pub enum InternalRequest {
145    Yes,
146    #[default]
147    No,
148}
149
150/// <https://html.spec.whatwg.org/multipage/#preload-key>
151#[derive(Clone, Debug, Eq, Hash, Deserialize, MallocSizeOf, Serialize, PartialEq)]
152pub struct PreloadKey {
153    /// <https://html.spec.whatwg.org/multipage/#preload-url>
154    pub url: ServoUrl,
155    /// <https://html.spec.whatwg.org/multipage/#preload-destination>
156    pub destination: Destination,
157    /// <https://html.spec.whatwg.org/multipage/#preload-mode>
158    pub mode: RequestMode,
159    /// <https://html.spec.whatwg.org/multipage/#preload-credentials-mode>
160    pub credentials_mode: CredentialsMode,
161}
162
163impl PreloadKey {
164    pub fn new(request: &RequestBuilder) -> Self {
165        Self {
166            url: request.url.url(),
167            destination: request.destination,
168            mode: request.mode.clone(),
169            credentials_mode: request.credentials_mode,
170        }
171    }
172}
173
174#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize, Hash, MallocSizeOf)]
175pub struct PreloadId(pub Uuid);
176
177impl Default for PreloadId {
178    fn default() -> Self {
179        Self(Uuid::new_v4())
180    }
181}
182
183/// <https://html.spec.whatwg.org/multipage/#preload-entry>
184#[derive(Debug, MallocSizeOf)]
185pub struct PreloadEntry {
186    /// <https://html.spec.whatwg.org/multipage/#preload-integrity-metadata>
187    pub integrity_metadata: String,
188    /// <https://html.spec.whatwg.org/multipage/#preload-response>
189    pub response: Option<Response>,
190    /// <https://html.spec.whatwg.org/multipage/#preload-on-response-available>
191    pub on_response_available: Option<TokioSender<Response>>,
192}
193
194impl PreloadEntry {
195    pub fn new(integrity_metadata: String) -> Self {
196        Self {
197            integrity_metadata,
198            response: None,
199            on_response_available: None,
200        }
201    }
202
203    /// Part of step 11.5 of <https://html.spec.whatwg.org/multipage/#preload>
204    pub fn with_response(&mut self, response: Response) {
205        // Step 11.5. If entry's on response available is null, then set entry's response to response;
206        // otherwise call entry's on response available given response.
207        if let Some(sender) = self.on_response_available.take() {
208            let _ = sender.send(response);
209        } else {
210            self.response = Some(response);
211        }
212    }
213}
214
215pub type PreloadedResources = FxHashMap<PreloadKey, PreloadId>;
216
217/// <https://fetch.spec.whatwg.org/#concept-request-client>
218#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
219pub struct RequestClient {
220    /// <https://html.spec.whatwg.org/multipage/#map-of-preloaded-resources>
221    pub preloaded_resources: PreloadedResources,
222    /// <https://html.spec.whatwg.org/multipage/#concept-settings-object-policy-container>
223    #[conditional_malloc_size_of]
224    pub policy_container: Arc<PolicyContainer>,
225    /// <https://html.spec.whatwg.org/multipage/#concept-settings-object-origin>
226    pub origin: Origin,
227    /// <https://html.spec.whatwg.org/multipage/#nested-browsing-context>
228    pub is_nested_browsing_context: bool,
229    /// <https://w3c.github.io/webappsec-upgrade-insecure-requests/#insecure-requests-policy>
230    pub insecure_requests_policy: InsecureRequestsPolicy,
231    /// <https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set>
232    pub upgrade_insecure_navigations_set: HashSet<UpgradeInsecureNavigations>,
233    /// <https://w3c.github.io/webappsec-secure-contexts/#potentially-trustworthy-origin>
234    pub has_trustworthy_ancestor_origin: bool,
235    /// <https://fetch.spec.whatwg.org/#determining-the-network-partition-key>
236    pub network_partition_key: NetworkPartitionKey,
237}
238
239/// <https://html.spec.whatwg.org/multipage/#system-visibility-state>
240#[derive(Clone, Copy, Default, MallocSizeOf, PartialEq)]
241pub enum SystemVisibilityState {
242    #[default]
243    Hidden,
244    Visible,
245}
246
247/// <https://html.spec.whatwg.org/multipage/#traversable-navigable>
248#[derive(Clone, Copy, Default, MallocSizeOf, PartialEq)]
249pub struct TraversableNavigable {
250    /// <https://html.spec.whatwg.org/multipage/#tn-current-session-history-step>
251    current_session_history_step: u8,
252    // TODO: https://html.spec.whatwg.org/multipage/#tn-session-history-entries
253    // TODO: https://html.spec.whatwg.org/multipage/#tn-session-history-traversal-queue
254    /// <https://html.spec.whatwg.org/multipage/#tn-running-nested-apply-history-step>
255    running_nested_apply_history_step: bool,
256    /// <https://html.spec.whatwg.org/multipage/#system-visibility-state>
257    system_visibility_state: SystemVisibilityState,
258    /// <https://html.spec.whatwg.org/multipage/#is-created-by-web-content>
259    is_created_by_web_content: bool,
260}
261
262/// <https://fetch.spec.whatwg.org/#concept-request-window>
263#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
264pub enum TraversableForUserPrompts {
265    NoTraversable,
266    Client,
267    TraversableNavigable(TraversableNavigable),
268}
269
270/// [CORS settings attribute](https://html.spec.whatwg.org/multipage/#attr-crossorigin-anonymous)
271#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
272pub enum CorsSettings {
273    Anonymous,
274    UseCredentials,
275}
276
277impl CorsSettings {
278    /// <https://html.spec.whatwg.org/multipage/#cors-settings-attribute>
279    pub fn from_enumerated_attribute(value: &str) -> CorsSettings {
280        if value.eq_ignore_ascii_case("use-credentials") {
281            CorsSettings::UseCredentials
282        } else {
283            CorsSettings::Anonymous
284        }
285    }
286}
287
288/// [Parser Metadata](https://fetch.spec.whatwg.org/#concept-request-parser-metadata)
289#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
290pub enum ParserMetadata {
291    Default,
292    ParserInserted,
293    NotParserInserted,
294}
295
296/// <https://fetch.spec.whatwg.org/#concept-body-source>
297#[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
298pub enum BodySource {
299    Null,
300    Object,
301}
302
303/// Messages used to implement <https://fetch.spec.whatwg.org/#concept-request-transmit-body>
304/// which are sent from script to net.
305#[derive(Debug, Deserialize, Serialize)]
306pub enum BodyChunkResponse {
307    /// A chunk of bytes.
308    Chunk(GenericSharedMemory),
309    /// The body is done.
310    Done,
311    /// There was an error streaming the body,
312    /// terminate fetch.
313    Error,
314}
315
316/// Messages used to implement [request body transmission] which are sent from
317/// net to script.
318///
319/// [request body transmission]: <https://fetch.spec.whatwg.org/#concept-request-transmit-body>
320#[derive(Debug, Deserialize, Serialize)]
321pub enum BodyChunkRequest {
322    /// Connect a fetch in `net`, with a stream of bytes from `script`.
323    Connect(IpcSender<BodyChunkResponse>),
324    /// Re-extract a new stream from the source, following a redirect.
325    Extract(IpcReceiver<BodyChunkRequest>),
326    /// Ask for another chunk.
327    Chunk,
328}
329
330/// A process local view into <https://fetch.spec.whatwg.org/#bodies>.
331/// After IPC serialization, each process gets its own shared sender state for the same body
332/// stream. the net side fetch entry points own clearing their local copy once that fetch invocation
333/// reaches its terminal state. Redirect replay can later deserialize a fresh "RequestBody", so
334/// lower level fetch steps cannot always clean up immediately.
335#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
336pub struct RequestBody {
337    /// Net's channel to communicate with script re this body.
338    #[conditional_malloc_size_of]
339    body_chunk_request_channel: Arc<Mutex<Option<IpcSender<BodyChunkRequest>>>>,
340    /// <https://fetch.spec.whatwg.org/#concept-body-source>
341    source: BodySource,
342    /// <https://fetch.spec.whatwg.org/#concept-body-total-bytes>
343    total_bytes: Option<usize>,
344}
345
346impl RequestBody {
347    pub fn new(
348        body_chunk_request_channel: IpcSender<BodyChunkRequest>,
349        source: BodySource,
350        total_bytes: Option<usize>,
351    ) -> Self {
352        RequestBody {
353            body_chunk_request_channel: Arc::new(Mutex::new(Some(body_chunk_request_channel))),
354            source,
355            total_bytes,
356        }
357    }
358
359    /// Step 12 of <https://fetch.spec.whatwg.org/#concept-http-redirect-fetch>
360    pub fn extract_source(&mut self) {
361        match self.source {
362            BodySource::Null => panic!("Null sources should never be re-directed."),
363            BodySource::Object => {
364                let (chan, port) = ipc::channel().unwrap();
365                let mut lock = self.body_chunk_request_channel.lock();
366                let Some(selfchan) = lock.as_mut() else {
367                    error!(
368                        "Could not re-extract the request body source because the body stream has already been closed."
369                    );
370                    return;
371                };
372                if let Err(error) = selfchan.send(BodyChunkRequest::Extract(port)) {
373                    error!(
374                        "Could not re-extract the request body source because the body stream has already been closed: {error}"
375                    );
376                    return;
377                }
378                *selfchan = chan;
379            },
380        }
381    }
382
383    /// This is the current process shared optional sender for requesting body chunks.
384    pub fn clone_stream(&self) -> Arc<Mutex<Option<IpcSender<BodyChunkRequest>>>> {
385        self.body_chunk_request_channel.clone()
386    }
387
388    /// Clears the current process shared sender state for this "RequestBody" copy.
389    ///
390    /// This does not notify or mutate other deserialized "RequestBody" values in other processes.
391    /// Can be called multiple times.
392    pub fn close_stream(&self) {
393        self.body_chunk_request_channel.lock().take();
394    }
395
396    pub fn source_is_null(&self) -> bool {
397        self.source == BodySource::Null
398    }
399
400    #[expect(clippy::len_without_is_empty)]
401    pub fn len(&self) -> Option<usize> {
402        self.total_bytes
403    }
404}
405
406trait RequestBodySize {
407    fn body_length(&self) -> usize;
408}
409
410impl RequestBodySize for Option<RequestBody> {
411    fn body_length(&self) -> usize {
412        self.as_ref()
413            .and_then(|body| body.len())
414            .unwrap_or_default()
415    }
416}
417
418#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
419pub enum InsecureRequestsPolicy {
420    DoNotUpgrade,
421    Upgrade,
422}
423
424#[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Eq, Hash, Serialize)]
425pub struct UpgradeInsecureNavigations {
426    pub host: String,
427    pub port: u16,
428}
429
430pub trait RequestHeadersSize {
431    fn total_size(&self) -> usize;
432}
433
434impl RequestHeadersSize for HeaderMap {
435    fn total_size(&self) -> usize {
436        self.iter()
437            .map(|(name, value)| name.as_str().len() + value.len())
438            .sum()
439    }
440}
441
442#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
443pub struct RequestBuilder {
444    pub id: RequestId,
445
446    pub preload_id: Option<PreloadId>,
447
448    /// <https://fetch.spec.whatwg.org/#concept-request-method>
449    #[serde(
450        deserialize_with = "::hyper_serde::deserialize",
451        serialize_with = "::hyper_serde::serialize"
452    )]
453    pub method: Method,
454
455    /// <https://fetch.spec.whatwg.org/#concept-request-url>
456    pub url: UrlWithBlobClaim,
457
458    /// <https://fetch.spec.whatwg.org/#concept-request-header-list>
459    #[serde(
460        deserialize_with = "::hyper_serde::deserialize",
461        serialize_with = "::hyper_serde::serialize"
462    )]
463    pub headers: HeaderMap,
464
465    /// <https://fetch.spec.whatwg.org/#unsafe-request-flag>
466    pub unsafe_request: bool,
467
468    /// <https://fetch.spec.whatwg.org/#concept-request-body>
469    pub body: Option<RequestBody>,
470    /// <https://fetch.spec.whatwg.org/#concept-request-reload-navigation-flag>
471    /// A request has an associated reload-navigation flag. Unless stated otherwise, it is unset.
472    pub reload_navigation: bool,
473    /// <https://fetch.spec.whatwg.org/#concept-request-history-navigation-flag>
474    /// A request has an associated history-navigation flag. Unless stated otherwise, it is unset.
475    pub history_navigation: bool,
476
477    /// <https://fetch.spec.whatwg.org/#request-service-workers-mode>
478    pub service_workers_mode: ServiceWorkersMode,
479    pub client: Option<RequestClient>,
480    /// <https://fetch.spec.whatwg.org/#concept-request-destination>
481    pub destination: Destination,
482    pub synchronous: bool,
483    pub mode: RequestMode,
484
485    /// <https://fetch.spec.whatwg.org/#concept-request-cache-mode>
486    pub cache_mode: CacheMode,
487
488    /// <https://fetch.spec.whatwg.org/#use-cors-preflight-flag>
489    pub use_cors_preflight: bool,
490
491    /// <https://fetch.spec.whatwg.org/#request-keepalive-flag>
492    pub keep_alive: bool,
493
494    /// <https://fetch.spec.whatwg.org/#concept-request-credentials-mode>
495    pub credentials_mode: CredentialsMode,
496    pub use_url_credentials: bool,
497
498    /// <https://fetch.spec.whatwg.org/#concept-request-origin>
499    pub origin: Origin,
500
501    /// <https://fetch.spec.whatwg.org/#concept-request-policy-container>
502    pub policy_container: RequestPolicyContainer,
503
504    /// <https://fetch.spec.whatwg.org/#request-user-activation>
505    pub user_activation: bool,
506
507    /// <https://fetch.spec.whatwg.org/#concept-request-referrer>
508    pub referrer: Referrer,
509
510    /// <https://fetch.spec.whatwg.org/#concept-request-referrer-policy>
511    pub referrer_policy: ReferrerPolicy,
512    pub pipeline_id: Option<PipelineId>,
513    pub target_webview_id: Option<WebViewId>,
514
515    /// <https://fetch.spec.whatwg.org/#concept-request-redirect-mode>
516    pub redirect_mode: RedirectMode,
517
518    /// <https://fetch.spec.whatwg.org/#concept-request-integrity-metadata>
519    pub integrity_metadata: String,
520
521    /// <https://fetch.spec.whatwg.org/#concept-request-nonce-metadata>
522    pub cryptographic_nonce_metadata: String,
523
524    /// <https://fetch.spec.whatwg.org/#concept-request-url-list>
525    pub url_list: Vec<UrlWithBlobClaim>,
526
527    /// <https://fetch.spec.whatwg.org/#concept-request-parser-metadata>
528    pub parser_metadata: ParserMetadata,
529
530    /// <https://fetch.spec.whatwg.org/#concept-request-initiator>
531    pub initiator: Initiator,
532    pub response_tainting: ResponseTainting,
533    /// Servo internal: if crash details are present, trigger a crash error page with these details.
534    pub crash: Option<String>,
535    /// Servo internal: whether this request originates from Servo internal implementation
536    pub is_internal_request: InternalRequest,
537}
538
539impl RequestBuilder {
540    pub fn new(
541        webview_id: Option<WebViewId>,
542        url: UrlWithBlobClaim,
543        referrer: Referrer,
544    ) -> RequestBuilder {
545        RequestBuilder {
546            id: RequestId::default(),
547            preload_id: None,
548            method: Method::GET,
549            url,
550            headers: HeaderMap::new(),
551            unsafe_request: false,
552            body: None,
553            reload_navigation: false,
554            history_navigation: false,
555            service_workers_mode: ServiceWorkersMode::All,
556            destination: Destination::None,
557            synchronous: false,
558            mode: RequestMode::NoCors,
559            cache_mode: CacheMode::Default,
560            use_cors_preflight: false,
561            keep_alive: false,
562            credentials_mode: CredentialsMode::CredentialsSameOrigin,
563            use_url_credentials: false,
564            user_activation: false,
565            origin: Origin::Client,
566            client: None,
567            policy_container: RequestPolicyContainer::default(),
568            referrer,
569            referrer_policy: ReferrerPolicy::EmptyString,
570            pipeline_id: None,
571            target_webview_id: webview_id,
572            redirect_mode: RedirectMode::Follow,
573            integrity_metadata: String::new(),
574            cryptographic_nonce_metadata: String::new(),
575            url_list: vec![],
576            parser_metadata: ParserMetadata::Default,
577            initiator: Initiator::None,
578            response_tainting: ResponseTainting::Basic,
579            is_internal_request: Default::default(),
580            crash: None,
581        }
582    }
583
584    pub fn preload_id(mut self, preload_id: PreloadId) -> RequestBuilder {
585        self.preload_id = Some(preload_id);
586        self
587    }
588
589    /// <https://fetch.spec.whatwg.org/#concept-request-initiator>
590    pub fn initiator(mut self, initiator: Initiator) -> RequestBuilder {
591        self.initiator = initiator;
592        self
593    }
594
595    /// <https://fetch.spec.whatwg.org/#concept-request-method>
596    pub fn method(mut self, method: Method) -> RequestBuilder {
597        self.method = method;
598        self
599    }
600
601    /// <https://fetch.spec.whatwg.org/#concept-request-header-list>
602    pub fn headers(mut self, headers: HeaderMap) -> RequestBuilder {
603        self.headers = headers;
604        self
605    }
606
607    /// <https://fetch.spec.whatwg.org/#unsafe-request-flag>
608    pub fn unsafe_request(mut self, unsafe_request: bool) -> RequestBuilder {
609        self.unsafe_request = unsafe_request;
610        self
611    }
612
613    /// <https://fetch.spec.whatwg.org/#concept-request-body>
614    pub fn body(mut self, body: Option<RequestBody>) -> RequestBuilder {
615        self.body = body;
616        self
617    }
618
619    /// <https://fetch.spec.whatwg.org/#concept-request-destination>
620    pub fn destination(mut self, destination: Destination) -> RequestBuilder {
621        self.destination = destination;
622        self
623    }
624
625    pub fn synchronous(mut self, synchronous: bool) -> RequestBuilder {
626        self.synchronous = synchronous;
627        self
628    }
629
630    pub fn mode(mut self, mode: RequestMode) -> RequestBuilder {
631        self.mode = mode;
632        self
633    }
634
635    /// <https://fetch.spec.whatwg.org/#use-cors-preflight-flag>
636    pub fn use_cors_preflight(mut self, use_cors_preflight: bool) -> RequestBuilder {
637        self.use_cors_preflight = use_cors_preflight;
638        self
639    }
640
641    /// <https://fetch.spec.whatwg.org/#request-keepalive-flag>
642    pub fn keep_alive(mut self, keep_alive: bool) -> RequestBuilder {
643        self.keep_alive = keep_alive;
644        self
645    }
646
647    /// <https://fetch.spec.whatwg.org/#request-user-activation>
648    pub fn user_activation(mut self, user_activation: bool) -> RequestBuilder {
649        self.user_activation = user_activation;
650        self
651    }
652
653    /// <https://fetch.spec.whatwg.org/#concept-request-credentials-mode>
654    pub fn credentials_mode(mut self, credentials_mode: CredentialsMode) -> RequestBuilder {
655        self.credentials_mode = credentials_mode;
656        self
657    }
658
659    pub fn use_url_credentials(mut self, use_url_credentials: bool) -> RequestBuilder {
660        self.use_url_credentials = use_url_credentials;
661        self
662    }
663
664    /// <https://fetch.spec.whatwg.org/#concept-request-origin>
665    pub fn origin(mut self, origin: ImmutableOrigin) -> RequestBuilder {
666        self.origin = Origin::Origin(origin);
667        self
668    }
669
670    /// <https://fetch.spec.whatwg.org/#concept-request-referrer-policy>
671    pub fn referrer_policy(mut self, referrer_policy: ReferrerPolicy) -> RequestBuilder {
672        self.referrer_policy = referrer_policy;
673        self
674    }
675
676    /// <https://fetch.spec.whatwg.org/#concept-request-url-list>
677    pub fn url_list(mut self, url_list: Vec<UrlWithBlobClaim>) -> RequestBuilder {
678        self.url_list = url_list;
679        self
680    }
681
682    pub fn pipeline_id(mut self, pipeline_id: Option<PipelineId>) -> RequestBuilder {
683        self.pipeline_id = pipeline_id;
684        self
685    }
686
687    /// <https://fetch.spec.whatwg.org/#concept-request-redirect-mode>
688    pub fn redirect_mode(mut self, redirect_mode: RedirectMode) -> RequestBuilder {
689        self.redirect_mode = redirect_mode;
690        self
691    }
692
693    /// <https://fetch.spec.whatwg.org/#concept-request-integrity-metadata>
694    pub fn integrity_metadata(mut self, integrity_metadata: String) -> RequestBuilder {
695        self.integrity_metadata = integrity_metadata;
696        self
697    }
698
699    /// <https://fetch.spec.whatwg.org/#concept-request-nonce-metadata>
700    pub fn cryptographic_nonce_metadata(mut self, nonce_metadata: String) -> RequestBuilder {
701        self.cryptographic_nonce_metadata = nonce_metadata;
702        self
703    }
704
705    /// <https://fetch.spec.whatwg.org/#concept-request-parser-metadata>
706    pub fn parser_metadata(mut self, parser_metadata: ParserMetadata) -> RequestBuilder {
707        self.parser_metadata = parser_metadata;
708        self
709    }
710
711    pub fn response_tainting(mut self, response_tainting: ResponseTainting) -> RequestBuilder {
712        self.response_tainting = response_tainting;
713        self
714    }
715
716    pub fn crash(mut self, crash: Option<String>) -> Self {
717        self.crash = crash;
718        self
719    }
720
721    /// <https://fetch.spec.whatwg.org/#concept-request-policy-container>
722    pub fn policy_container(mut self, policy_container: Arc<PolicyContainer>) -> RequestBuilder {
723        self.policy_container = RequestPolicyContainer::PolicyContainer(policy_container);
724        self
725    }
726
727    /// <https://fetch.spec.whatwg.org/#concept-request-client>
728    pub fn client(mut self, client: RequestClient) -> RequestBuilder {
729        self.client = Some(client);
730        self
731    }
732
733    /// <https://fetch.spec.whatwg.org/#request-service-workers-mode>
734    pub fn service_workers_mode(
735        mut self,
736        service_workers_mode: ServiceWorkersMode,
737    ) -> RequestBuilder {
738        self.service_workers_mode = service_workers_mode;
739        self
740    }
741
742    /// <https://fetch.spec.whatwg.org/#concept-request-cache-mode>
743    pub fn cache_mode(mut self, cache_mode: CacheMode) -> RequestBuilder {
744        self.cache_mode = cache_mode;
745        self
746    }
747
748    pub fn is_internal_request(mut self, is_internal_request: InternalRequest) -> RequestBuilder {
749        self.is_internal_request = is_internal_request;
750        self
751    }
752
753    pub fn build(self) -> Request {
754        let mut request = Request::new(
755            self.id,
756            self.url.clone(),
757            Some(self.origin),
758            self.referrer,
759            self.pipeline_id,
760            self.target_webview_id,
761        );
762        request.preload_id = self.preload_id;
763        request.initiator = self.initiator;
764        request.method = self.method;
765        request.headers = self.headers;
766        request.unsafe_request = self.unsafe_request;
767        request.body = self.body;
768        request.reload_navigation = self.reload_navigation;
769        request.history_navigation = self.history_navigation;
770        request.service_workers_mode = self.service_workers_mode;
771        request.destination = self.destination;
772        request.synchronous = self.synchronous;
773        request.mode = self.mode;
774        request.use_cors_preflight = self.use_cors_preflight;
775        request.keep_alive = self.keep_alive;
776        request.credentials_mode = self.credentials_mode;
777        request.use_url_credentials = self.use_url_credentials;
778        request.cache_mode = self.cache_mode;
779        request.referrer_policy = self.referrer_policy;
780        request.redirect_mode = self.redirect_mode;
781        let mut url_list = self.url_list;
782        if url_list.is_empty() {
783            url_list.push(self.url);
784        }
785        request.redirect_count = url_list.len() as u32 - 1;
786        request.url_list = url_list;
787        request.integrity_metadata = self.integrity_metadata;
788        request.cryptographic_nonce_metadata = self.cryptographic_nonce_metadata;
789        request.parser_metadata = self.parser_metadata;
790        request.response_tainting = self.response_tainting;
791        request.crash = self.crash;
792        request.client = self.client;
793        request.user_activation = self.user_activation;
794        request.policy_container = self.policy_container;
795        request.is_internal_request = self.is_internal_request;
796        request
797    }
798
799    /// The body length for a keep-alive request. Is 0 if this request is not keep-alive
800    pub fn keep_alive_body_length(&self) -> u64 {
801        assert!(self.keep_alive);
802        self.body.body_length() as u64
803    }
804}
805
806/// A [Request](https://fetch.spec.whatwg.org/#concept-request) as defined by
807/// the Fetch spec.
808#[derive(Clone, MallocSizeOf)]
809pub struct Request {
810    /// The unique id of this request so that the task that triggered it can route
811    /// messages to the correct listeners. This is a UUID that is generated when a request
812    /// is being built.
813    pub id: RequestId,
814    pub preload_id: Option<PreloadId>,
815    /// <https://fetch.spec.whatwg.org/#concept-request-method>
816    pub method: Method,
817    /// <https://fetch.spec.whatwg.org/#local-urls-only-flag>
818    pub local_urls_only: bool,
819    /// <https://fetch.spec.whatwg.org/#concept-request-header-list>
820    pub headers: HeaderMap,
821    /// <https://fetch.spec.whatwg.org/#unsafe-request-flag>
822    pub unsafe_request: bool,
823    /// <https://fetch.spec.whatwg.org/#concept-request-body>
824    pub body: Option<RequestBody>,
825    /// <https://fetch.spec.whatwg.org/#concept-request-reload-navigation-flag>
826    /// A request has an associated reload-navigation flag. Unless stated otherwise, it is unset.
827    pub reload_navigation: bool,
828    /// <https://fetch.spec.whatwg.org/#concept-request-history-navigation-flag>
829    /// A request has an associated history-navigation flag. Unless stated otherwise, it is unset.
830    pub history_navigation: bool,
831    /// <https://fetch.spec.whatwg.org/#concept-request-client>
832    pub client: Option<RequestClient>,
833    /// <https://fetch.spec.whatwg.org/#concept-request-window>
834    pub traversable_for_user_prompts: TraversableForUserPrompts,
835    pub target_webview_id: Option<WebViewId>,
836    /// <https://fetch.spec.whatwg.org/#request-keepalive-flag>
837    pub keep_alive: bool,
838    /// <https://fetch.spec.whatwg.org/#request-service-workers-mode>
839    pub service_workers_mode: ServiceWorkersMode,
840    /// <https://fetch.spec.whatwg.org/#concept-request-initiator>
841    pub initiator: Initiator,
842    /// <https://fetch.spec.whatwg.org/#concept-request-destination>
843    pub destination: Destination,
844    // TODO: priority object
845    /// <https://fetch.spec.whatwg.org/#concept-request-origin>
846    pub origin: Origin,
847    /// <https://fetch.spec.whatwg.org/#concept-request-referrer>
848    pub referrer: Referrer,
849    /// <https://fetch.spec.whatwg.org/#concept-request-referrer-policy>
850    pub referrer_policy: ReferrerPolicy,
851    pub pipeline_id: Option<PipelineId>,
852    /// <https://fetch.spec.whatwg.org/#synchronous-flag>
853    pub synchronous: bool,
854    /// <https://fetch.spec.whatwg.org/#concept-request-mode>
855    pub mode: RequestMode,
856    /// <https://fetch.spec.whatwg.org/#use-cors-preflight-flag>
857    pub use_cors_preflight: bool,
858    /// <https://fetch.spec.whatwg.org/#concept-request-credentials-mode>
859    pub credentials_mode: CredentialsMode,
860    /// <https://fetch.spec.whatwg.org/#concept-request-use-url-credentials-flag>
861    pub use_url_credentials: bool,
862    /// <https://fetch.spec.whatwg.org/#concept-request-cache-mode>
863    pub cache_mode: CacheMode,
864    /// <https://fetch.spec.whatwg.org/#concept-request-redirect-mode>
865    pub redirect_mode: RedirectMode,
866    /// <https://fetch.spec.whatwg.org/#concept-request-integrity-metadata>
867    pub integrity_metadata: String,
868    /// <https://fetch.spec.whatwg.org/#concept-request-nonce-metadata>
869    pub cryptographic_nonce_metadata: String,
870    /// <https://fetch.spec.whatwg.org/#concept-request-url-list>
871    pub url_list: Vec<UrlWithBlobClaim>,
872    /// <https://fetch.spec.whatwg.org/#concept-request-redirect-count>
873    pub redirect_count: u32,
874    /// <https://fetch.spec.whatwg.org/#concept-request-response-tainting>
875    pub response_tainting: ResponseTainting,
876    /// <https://fetch.spec.whatwg.org/#concept-request-parser-metadata>
877    pub parser_metadata: ParserMetadata,
878    /// <https://fetch.spec.whatwg.org/#concept-request-policy-container>
879    pub policy_container: RequestPolicyContainer,
880    /// <https://fetch.spec.whatwg.org/#request-user-activation>
881    pub user_activation: bool,
882    /// Servo internal: if crash details are present, trigger a crash error page with these details.
883    pub crash: Option<String>,
884    /// Servo internal: whether this request originates from Servo internal implementation
885    pub is_internal_request: InternalRequest,
886}
887
888impl Request {
889    pub fn new(
890        id: RequestId,
891        url: UrlWithBlobClaim,
892        origin: Option<Origin>,
893        referrer: Referrer,
894        pipeline_id: Option<PipelineId>,
895        webview_id: Option<WebViewId>,
896    ) -> Request {
897        Request {
898            id,
899            preload_id: None,
900            method: Method::GET,
901            local_urls_only: false,
902            headers: HeaderMap::new(),
903            unsafe_request: false,
904            body: None,
905            reload_navigation: false,
906            history_navigation: false,
907            client: None,
908            traversable_for_user_prompts: TraversableForUserPrompts::Client,
909            keep_alive: false,
910            service_workers_mode: ServiceWorkersMode::All,
911            initiator: Initiator::None,
912            destination: Destination::None,
913            origin: origin.unwrap_or(Origin::Client),
914            referrer,
915            referrer_policy: ReferrerPolicy::EmptyString,
916            pipeline_id,
917            target_webview_id: webview_id,
918            synchronous: false,
919            mode: RequestMode::NoCors,
920            use_cors_preflight: false,
921            credentials_mode: CredentialsMode::CredentialsSameOrigin,
922            use_url_credentials: false,
923            user_activation: false,
924            cache_mode: CacheMode::Default,
925            redirect_mode: RedirectMode::Follow,
926            integrity_metadata: String::new(),
927            cryptographic_nonce_metadata: String::new(),
928            url_list: vec![url],
929            parser_metadata: ParserMetadata::Default,
930            redirect_count: 0,
931            response_tainting: ResponseTainting::Basic,
932            policy_container: RequestPolicyContainer::Client,
933            is_internal_request: Default::default(),
934            crash: None,
935        }
936    }
937
938    /// <https://fetch.spec.whatwg.org/#concept-request-url>
939    pub fn url(&self) -> ServoUrl {
940        self.url_list.first().unwrap().url()
941    }
942
943    pub fn url_with_blob_claim(&self) -> UrlWithBlobClaim {
944        self.url_list.first().unwrap().clone()
945    }
946
947    pub fn original_url(&self) -> ServoUrl {
948        match self.mode {
949            RequestMode::WebSocket {
950                protocols: _,
951                ref original_url,
952            } => original_url.clone(),
953            _ => self.url(),
954        }
955    }
956
957    /// <https://fetch.spec.whatwg.org/#concept-request-current-url>
958    pub fn current_url(&self) -> ServoUrl {
959        self.current_url_with_blob_claim().url()
960    }
961
962    /// <https://fetch.spec.whatwg.org/#concept-request-current-url>
963    pub fn current_url_with_blob_claim(&self) -> UrlWithBlobClaim {
964        self.url_list.last().unwrap().clone()
965    }
966
967    /// <https://fetch.spec.whatwg.org/#concept-request-current-url>
968    pub fn current_url_mut(&mut self) -> &mut ServoUrl {
969        self.url_list.last_mut().unwrap()
970    }
971
972    /// <https://fetch.spec.whatwg.org/#navigation-request>
973    pub fn is_navigation_request(&self) -> bool {
974        matches!(
975            self.destination,
976            Destination::Document |
977                Destination::Embed |
978                Destination::Frame |
979                Destination::IFrame |
980                Destination::Object
981        )
982    }
983
984    /// <https://fetch.spec.whatwg.org/#subresource-request>
985    pub fn is_subresource_request(&self) -> bool {
986        matches!(
987            self.destination,
988            Destination::Audio |
989                Destination::AudioWorklet |
990                Destination::Font |
991                Destination::Image |
992                Destination::Json |
993                Destination::Manifest |
994                Destination::PaintWorklet |
995                Destination::Script |
996                Destination::Style |
997                Destination::Text |
998                Destination::Track |
999                Destination::Video |
1000                Destination::Xslt |
1001                Destination::None
1002        )
1003    }
1004
1005    pub fn timing_type(&self) -> ResourceTimingType {
1006        if self.is_navigation_request() {
1007            ResourceTimingType::Navigation
1008        } else {
1009            ResourceTimingType::Resource
1010        }
1011    }
1012
1013    /// <https://fetch.spec.whatwg.org/#populate-request-from-client>
1014    pub fn populate_request_from_client(&mut self) {
1015        // Step 1. If request’s traversable for user prompts is "client":
1016        if self.traversable_for_user_prompts == TraversableForUserPrompts::Client {
1017            // Step 1.1. Set request’s traversable for user prompts to "no-traversable".
1018            self.traversable_for_user_prompts = TraversableForUserPrompts::NoTraversable;
1019            // Step 1.2. If request’s client is non-null:
1020            if self.client.is_some() {
1021                // Step 1.2.1. Let global be request’s client’s global object.
1022                // TODO
1023                // Step 1.2.2. If global is a Window object and global’s navigable is not null,
1024                // then set request’s traversable for user prompts to global’s navigable’s traversable navigable.
1025                self.traversable_for_user_prompts =
1026                    TraversableForUserPrompts::TraversableNavigable(Default::default());
1027            }
1028        }
1029        // Step 2. If request’s origin is "client":
1030        if self.origin == Origin::Client {
1031            let Some(client) = self.client.as_ref() else {
1032                // Step 2.1. Assert: request’s client is non-null.
1033                unreachable!();
1034            };
1035            // Step 2.2. Set request’s origin to request’s client’s origin.
1036            self.origin = client.origin.clone();
1037        }
1038        // Step 3. If request’s policy container is "client":
1039        if matches!(self.policy_container, RequestPolicyContainer::Client) {
1040            // Step 3.1. If request’s client is non-null, then set request’s
1041            // policy container to a clone of request’s client’s policy container. [HTML]
1042            if let Some(client) = self.client.as_ref() {
1043                self.policy_container =
1044                    RequestPolicyContainer::PolicyContainer(client.policy_container.clone());
1045            } else {
1046                // Step 3.2. Otherwise, set request’s policy container to a new policy container.
1047                self.policy_container =
1048                    RequestPolicyContainer::PolicyContainer(Arc::new(PolicyContainer::default()));
1049            }
1050        }
1051    }
1052
1053    /// The body length for a keep-alive request. Is 0 if this request is not keep-alive
1054    pub fn keep_alive_body_length(&self) -> u64 {
1055        assert!(self.keep_alive);
1056        self.body.body_length() as u64
1057    }
1058
1059    /// <https://fetch.spec.whatwg.org/#total-request-length>
1060    pub fn total_request_length(&self) -> usize {
1061        // Step 1. Let totalRequestLength be the length of request’s URL, serialized with exclude fragment set to true.
1062        let mut total_request_length = self.url()[..Position::AfterQuery].len();
1063        // Step 2. Increment totalRequestLength by the length of request’s referrer, serialized.
1064        total_request_length += self
1065            .referrer
1066            .to_url()
1067            .map(|url| url.as_str().len())
1068            .unwrap_or_default();
1069        // Step 3. For each (name, value) of request’s header list, increment totalRequestLength
1070        // by name’s length + value’s length.
1071        total_request_length += self.headers.total_size();
1072        // Step 4. Increment totalRequestLength by request’s body’s length.
1073        total_request_length += self.body.body_length();
1074        // Step 5. Return totalRequestLength.
1075        total_request_length
1076    }
1077
1078    /// <https://fetch.spec.whatwg.org/#concept-request-tainted-origin>
1079    pub fn redirect_taint_for_request(&self) -> RedirectTaint {
1080        // Step 1. Assert: request’s origin is not "client".
1081        let Origin::Origin(request_origin) = &self.origin else {
1082            unreachable!("origin cannot be \"client\" at this point in time");
1083        };
1084
1085        // Step 2. Let lastURL be null.
1086        let mut last_url = None;
1087
1088        // Step 3. Let taint be "same-origin".
1089        let mut taint = RedirectTaint::SameOrigin;
1090
1091        // Step 4. For each url of request’s URL list:
1092        for url in &self.url_list {
1093            // Step 4.1 If lastURL is null, then set lastURL to url and continue.
1094            let Some(last_url) = &mut last_url else {
1095                last_url = Some(url);
1096                continue;
1097            };
1098
1099            // Step 4.2. If url’s origin is not same site with lastURL’s origin and
1100            // request’s origin is not same site with lastURL’s origin, then return "cross-site".
1101            if !is_same_site(&url.origin(), &last_url.origin()) &&
1102                !is_same_site(request_origin, &last_url.origin())
1103            {
1104                return RedirectTaint::CrossSite;
1105            }
1106
1107            // Step 4.3. If url’s origin is not same origin with lastURL’s origin
1108            // and request’s origin is not same origin with lastURL’s origin, then set taint to "same-site".
1109            if url.origin() != last_url.origin() && *request_origin != last_url.origin() {
1110                taint = RedirectTaint::SameSite;
1111            }
1112
1113            // Step 4.4 Set lastURL to url.
1114            *last_url = url;
1115        }
1116
1117        // Step 5. Return taint.
1118        taint
1119    }
1120}
1121
1122impl Referrer {
1123    pub fn to_url(&self) -> Option<&ServoUrl> {
1124        match *self {
1125            Referrer::NoReferrer => None,
1126            Referrer::Client(ref url) => Some(url),
1127            Referrer::ReferrerUrl(ref url) => Some(url),
1128        }
1129    }
1130}
1131
1132// https://fetch.spec.whatwg.org/#cors-unsafe-request-header-byte
1133// TODO: values in the control-code range are being quietly stripped out by
1134// HeaderMap and never reach this function to be loudly rejected!
1135fn is_cors_unsafe_request_header_byte(value: &u8) -> bool {
1136    matches!(value,
1137        0x00..=0x08 |
1138        0x10..=0x19 |
1139        0x22 |
1140        0x28 |
1141        0x29 |
1142        0x3A |
1143        0x3C |
1144        0x3E |
1145        0x3F |
1146        0x40 |
1147        0x5B |
1148        0x5C |
1149        0x5D |
1150        0x7B |
1151        0x7D |
1152        0x7F
1153    )
1154}
1155
1156// https://fetch.spec.whatwg.org/#cors-safelisted-request-header
1157// subclause `accept`
1158fn is_cors_safelisted_request_accept(value: &[u8]) -> bool {
1159    !(value.iter().any(is_cors_unsafe_request_header_byte))
1160}
1161
1162// https://fetch.spec.whatwg.org/#cors-safelisted-request-header
1163// subclauses `accept-language`, `content-language`
1164fn is_cors_safelisted_language(value: &[u8]) -> bool {
1165    value.iter().all(|&x| {
1166        matches!(x,
1167            0x30..=0x39 |
1168            0x41..=0x5A |
1169            0x61..=0x7A |
1170            0x20 |
1171            0x2A |
1172            0x2C |
1173            0x2D |
1174            0x2E |
1175            0x3B |
1176            0x3D
1177        )
1178    })
1179}
1180
1181// https://fetch.spec.whatwg.org/#cors-safelisted-request-header
1182// subclause `content-type`
1183pub fn is_cors_safelisted_request_content_type(value: &[u8]) -> bool {
1184    // step 1
1185    if value.iter().any(is_cors_unsafe_request_header_byte) {
1186        return false;
1187    }
1188    // step 2
1189    let value_string = if let Ok(s) = std::str::from_utf8(value) {
1190        s
1191    } else {
1192        return false;
1193    };
1194    let value_mime_result: Result<Mime, _> = value_string.parse();
1195    match value_mime_result {
1196        Err(_) => false, // step 3
1197        Ok(value_mime) => match (value_mime.type_(), value_mime.subtype()) {
1198            (mime::APPLICATION, mime::WWW_FORM_URLENCODED) |
1199            (mime::MULTIPART, mime::FORM_DATA) |
1200            (mime::TEXT, mime::PLAIN) => true,
1201            _ => false, // step 4
1202        },
1203    }
1204}
1205
1206// TODO: "DPR", "Downlink", "Save-Data", "Viewport-Width", "Width":
1207// ... once parsed, the value should not be failure.
1208// https://fetch.spec.whatwg.org/#cors-safelisted-request-header
1209pub fn is_cors_safelisted_request_header<N: AsRef<str>, V: AsRef<[u8]>>(
1210    name: &N,
1211    value: &V,
1212) -> bool {
1213    let name: &str = name.as_ref();
1214    let value: &[u8] = value.as_ref();
1215    if value.len() > 128 {
1216        return false;
1217    }
1218    match name {
1219        "accept" => is_cors_safelisted_request_accept(value),
1220        "accept-language" | "content-language" => is_cors_safelisted_language(value),
1221        "content-type" => is_cors_safelisted_request_content_type(value),
1222        "range" => is_cors_safelisted_request_range(value),
1223        _ => false,
1224    }
1225}
1226
1227pub fn is_cors_safelisted_request_range(value: &[u8]) -> bool {
1228    if let Ok(value_str) = std::str::from_utf8(value) {
1229        return validate_range_header(value_str);
1230    }
1231    false
1232}
1233
1234fn validate_range_header(value: &str) -> bool {
1235    let trimmed = value.trim();
1236    if !trimmed.starts_with("bytes=") {
1237        return false;
1238    }
1239
1240    if let Some(range) = trimmed.strip_prefix("bytes=") {
1241        let mut parts = range.split('-');
1242        let start = parts.next();
1243        let end = parts.next();
1244
1245        if let Some(start) = start &&
1246            let Ok(start_num) = start.parse::<u64>()
1247        {
1248            return match end {
1249                Some(e) if !e.is_empty() => {
1250                    e.parse::<u64>().is_ok_and(|end_num| start_num <= end_num)
1251                },
1252                _ => true,
1253            };
1254        }
1255    }
1256    false
1257}
1258
1259/// <https://fetch.spec.whatwg.org/#cors-safelisted-method>
1260pub fn is_cors_safelisted_method(method: &Method) -> bool {
1261    matches!(*method, Method::GET | Method::HEAD | Method::POST)
1262}
1263
1264/// <https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name>
1265pub fn is_cors_non_wildcard_request_header_name(name: &HeaderName) -> bool {
1266    name == AUTHORIZATION
1267}
1268
1269/// <https://fetch.spec.whatwg.org/#cors-unsafe-request-header-names>
1270pub fn get_cors_unsafe_header_names(headers: &HeaderMap) -> Vec<HeaderName> {
1271    // Step 1
1272    let mut unsafe_names: Vec<&HeaderName> = vec![];
1273    // Step 2
1274    let mut potentillay_unsafe_names: Vec<&HeaderName> = vec![];
1275    // Step 3
1276    let mut safelist_value_size = 0;
1277
1278    // Step 4
1279    for (name, value) in headers.iter() {
1280        if !is_cors_safelisted_request_header(&name, &value) {
1281            unsafe_names.push(name);
1282        } else {
1283            potentillay_unsafe_names.push(name);
1284            safelist_value_size += value.as_ref().len();
1285        }
1286    }
1287
1288    // Step 5
1289    if safelist_value_size > 1024 {
1290        unsafe_names.extend_from_slice(&potentillay_unsafe_names);
1291    }
1292
1293    // Step 6
1294    convert_header_names_to_sorted_lowercase_set(unsafe_names)
1295}
1296
1297/// <https://fetch.spec.whatwg.org/#ref-for-convert-header-names-to-a-sorted-lowercase-set>
1298pub fn convert_header_names_to_sorted_lowercase_set(
1299    mut header_names: Vec<&HeaderName>,
1300) -> Vec<HeaderName> {
1301    // HeaderName does not implement the needed traits to use a BTreeSet
1302    // So sort the Vec, then dedup
1303    header_names.sort_by(|a, b| a.as_str().partial_cmp(b.as_str()).unwrap());
1304    header_names.dedup();
1305    header_names.into_iter().cloned().collect()
1306}
1307
1308pub fn create_request_body_with_content(content: String) -> RequestBody {
1309    let content_bytes = GenericSharedMemory::from_vec(content.into_bytes());
1310    let content_len = content_bytes.len();
1311
1312    let (chunk_request_sender, chunk_request_receiver) = ipc::channel().unwrap();
1313    ROUTER.add_typed_route(
1314        chunk_request_receiver,
1315        Box::new(move |message| {
1316            let request = message.unwrap();
1317            if let BodyChunkRequest::Connect(sender) = request {
1318                let _ = sender.send(BodyChunkResponse::Chunk(content_bytes.clone()));
1319                let _ = sender.send(BodyChunkResponse::Done);
1320            }
1321        }),
1322    );
1323
1324    RequestBody::new(chunk_request_sender, BodySource::Object, Some(content_len))
1325}