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