forked from LadybirdBrowser/ladybird
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFetching.cpp
More file actions
2844 lines (2359 loc) · 164 KB
/
Copy pathFetching.cpp
File metadata and controls
2844 lines (2359 loc) · 164 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
* Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
* Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
* Copyright (c) 2024, Jamie Mansfield <jmansfield@cadixdev.org>
* Copyright (c) 2025, Shannon Booth <shannon@serenityos.org>
* Copyright (c) 2025, Kenneth Myhra <kennethmyhra@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Base64.h>
#include <AK/Debug.h>
#include <AK/ScopeGuard.h>
#include <LibJS/Runtime/Completion.h>
#include <LibRequests/RequestTimingInfo.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Bindings/PrincipalHostDefined.h>
#include <LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h>
#include <LibWeb/Cookie/Cookie.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOMURL/DOMURL.h>
#include <LibWeb/Fetch/BodyInit.h>
#include <LibWeb/Fetch/Fetching/Checks.h>
#include <LibWeb/Fetch/Fetching/FetchedDataReceiver.h>
#include <LibWeb/Fetch/Fetching/Fetching.h>
#include <LibWeb/Fetch/Fetching/PendingResponse.h>
#include <LibWeb/Fetch/Fetching/RefCountedFlag.h>
#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
#include <LibWeb/Fetch/Infrastructure/FetchParams.h>
#include <LibWeb/Fetch/Infrastructure/FetchRecord.h>
#include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Headers.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Methods.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Statuses.h>
#include <LibWeb/Fetch/Infrastructure/MimeTypeBlocking.h>
#include <LibWeb/Fetch/Infrastructure/NetworkPartitionKey.h>
#include <LibWeb/Fetch/Infrastructure/NoSniffBlocking.h>
#include <LibWeb/Fetch/Infrastructure/PortBlocking.h>
#include <LibWeb/Fetch/Infrastructure/Task.h>
#include <LibWeb/Fetch/Infrastructure/URL.h>
#include <LibWeb/FileAPI/Blob.h>
#include <LibWeb/FileAPI/BlobURLStore.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WorkerGlobalScope.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Loader/LoadRequest.h>
#include <LibWeb/Loader/ResourceLoader.h>
#include <LibWeb/MixedContent/AbstractOperations.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/ReferrerPolicy/AbstractOperations.h>
#include <LibWeb/ResourceTiming/PerformanceResourceTiming.h>
#include <LibWeb/SRI/SRI.h>
#include <LibWeb/SecureContexts/AbstractOperations.h>
#include <LibWeb/Streams/TransformStream.h>
#include <LibWeb/Streams/TransformStreamDefaultController.h>
#include <LibWeb/Streams/TransformStreamOperations.h>
#include <LibWeb/Streams/Transformer.h>
#include <LibWeb/WebIDL/DOMException.h>
namespace Web::Fetch::Fetching {
bool g_http_cache_enabled;
#define TRY_OR_IGNORE(expression) \
({ \
auto&& _temporary_result = (expression); \
if (_temporary_result.is_error()) \
return; \
static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
"Do not return a reference from a fallible expression"); \
_temporary_result.release_value(); \
})
// https://fetch.spec.whatwg.org/#concept-fetch
WebIDL::ExceptionOr<GC::Ref<Infrastructure::FetchController>> fetch(JS::Realm& realm, Infrastructure::Request& request, Infrastructure::FetchAlgorithms const& algorithms, UseParallelQueue use_parallel_queue)
{
dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'fetch' with: request @ {}", &request);
auto& vm = realm.vm();
// 1. Assert: request’s mode is "navigate" or processEarlyHintsResponse is null.
VERIFY(request.mode() == Infrastructure::Request::Mode::Navigate || !algorithms.process_early_hints_response());
// 2. Let taskDestination be null.
Infrastructure::TaskDestination task_destination;
// 3. Let crossOriginIsolatedCapability be false.
auto cross_origin_isolated_capability = HTML::CanUseCrossOriginIsolatedAPIs::No;
// 4. Populate request from client given request.
populate_request_from_client(realm, request);
// 5. If request’s client is non-null, then:
if (request.client() != nullptr) {
// 1. Set taskDestination to request’s client’s global object.
task_destination = GC::Ref { request.client()->global_object() };
// 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin isolated capability.
cross_origin_isolated_capability = request.client()->cross_origin_isolated_capability();
}
// 6. If useParallelQueue is true, then set taskDestination to the result of starting a new parallel queue.
if (use_parallel_queue == UseParallelQueue::Yes)
task_destination = HTML::ParallelQueue::create();
// 7. Let timingInfo be a new fetch timing info whose start time and post-redirect start time are the coarsened
// shared current time given crossOriginIsolatedCapability, and render-blocking is set to request’s
// render-blocking.
auto timing_info = Infrastructure::FetchTimingInfo::create(vm);
auto now = HighResolutionTime::coarsened_shared_current_time(cross_origin_isolated_capability == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
timing_info->set_start_time(now);
timing_info->set_post_redirect_start_time(now);
timing_info->set_render_blocking(request.render_blocking());
// 8. Let fetchParams be a new fetch params whose request is request, timing info is timingInfo, process request
// body chunk length is processRequestBodyChunkLength, process request end-of-body is processRequestEndOfBody,
// process early hints response is processEarlyHintsResponse, process response is processResponse, process
// response consume body is processResponseConsumeBody, process response end-of-body is processResponseEndOfBody,
// task destination is taskDestination, and cross-origin isolated capability is crossOriginIsolatedCapability.
auto fetch_params = Infrastructure::FetchParams::create(vm, request, timing_info);
fetch_params->set_algorithms(algorithms);
fetch_params->set_task_destination(task_destination);
fetch_params->set_cross_origin_isolated_capability(cross_origin_isolated_capability);
// 9. If request’s body is a byte sequence, then set request’s body to request’s body as a body.
if (auto const* buffer = request.body().get_pointer<ByteBuffer>())
request.set_body(Infrastructure::byte_sequence_as_body(realm, buffer->bytes()));
// 10. If all of the following conditions are true:
if (
// - request’s URL’s scheme is an HTTP(S) scheme
Infrastructure::is_http_or_https_scheme(request.url().scheme())
// - request’s mode is "same-origin", "cors", or "no-cors"
&& (request.mode() == Infrastructure::Request::Mode::SameOrigin || request.mode() == Infrastructure::Request::Mode::CORS || request.mode() == Infrastructure::Request::Mode::NoCORS)
// - request’s client is not null, and request’s client’s global object is a Window object
&& request.client() && is<HTML::Window>(request.client()->global_object())
// - request’s method is `GET`
&& StringView { request.method() }.equals_ignoring_ascii_case("GET"sv)
// - request’s unsafe-request flag is not set or request’s header list is empty
&& (!request.unsafe_request() || request.header_list()->is_empty())) {
// 1. Assert: request’s origin is same origin with request’s client’s origin.
VERIFY(request.origin().has<URL::Origin>() && request.origin().get<URL::Origin>().is_same_origin(request.client()->origin()));
// 2. Let onPreloadedResponseAvailable be an algorithm that runs the following step given a response
// response: set fetchParams’s preloaded response candidate to response.
auto on_preloaded_response_available = GC::create_function(realm.heap(), [fetch_params](GC::Ref<Infrastructure::Response> response) {
fetch_params->set_preloaded_response_candidate(response);
});
// FIXME: 3. Let foundPreloadedResource be the result of invoking consume a preloaded resource for request’s
// window, given request’s URL, request’s destination, request’s mode, request’s credentials mode,
// request’s integrity metadata, and onPreloadedResponseAvailable.
auto found_preloaded_resource = false;
(void)on_preloaded_response_available;
// 4. If foundPreloadedResource is true and fetchParams’s preloaded response candidate is null, then set
// fetchParams’s preloaded response candidate to "pending".
if (found_preloaded_resource && fetch_params->preloaded_response_candidate().has<Empty>())
fetch_params->set_preloaded_response_candidate(Infrastructure::FetchParams::PreloadedResponseCandidatePendingTag {});
}
// 11. If request’s header list does not contain `Accept`, then:
if (!request.header_list()->contains("Accept"sv.bytes())) {
// 1. Let value be `*/*`.
auto value = "*/*"sv;
// 2. If request’s initiator is "prefetch", then set value to the document `Accept` header value.
if (request.initiator() == Infrastructure::Request::Initiator::Prefetch) {
value = document_accept_header_value;
}
// 3. Otherwise, the user agent should set value to the first matching statement, if any, switching on request’s destination:
else if (request.destination().has_value()) {
switch (*request.destination()) {
// -> "document"
// -> "frame"
// -> "iframe"
case Infrastructure::Request::Destination::Document:
case Infrastructure::Request::Destination::Frame:
case Infrastructure::Request::Destination::IFrame:
// the document `Accept` header value
value = document_accept_header_value;
break;
// -> "image"
case Infrastructure::Request::Destination::Image:
// `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
value = "image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5"sv;
break;
// -> "json"
case Infrastructure::Request::Destination::JSON:
// `application/json,*/*;q=0.5`
value = "application/json,*/*;q=0.5"sv;
break;
// -> "style"
case Infrastructure::Request::Destination::Style:
// `text/css,*/*;q=0.1`
value = "text/css,*/*;q=0.1"sv;
break;
default:
break;
}
}
// 4. Append (`Accept`, value) to request’s header list.
auto header = Infrastructure::Header::from_string_pair("Accept"sv, value.bytes());
request.header_list()->append(move(header));
}
// 12. If request’s header list does not contain `Accept-Language`, then user agents should append
// (`Accept-Language, an appropriate header value) to request’s header list.
if (!request.header_list()->contains("Accept-Language"sv.bytes())) {
StringBuilder accept_language;
accept_language.join(","sv, ResourceLoader::the().preferred_languages());
auto header = Infrastructure::Header::from_string_pair("Accept-Language"sv, accept_language.string_view());
request.header_list()->append(move(header));
}
// 13. If request’s internal priority is null, then use request’s priority, initiator, destination, and
// render-blocking in an implementation-defined manner to set request’s internal priority to an
// implementation-defined object.
// NOTE: The user-agent-defined object could encompass stream weight and dependency for HTTP/2, and equivalent
// information used to prioritize dispatch and processing of HTTP/1 fetches.
// 14. If request is a subresource request, then:
if (request.is_subresource_request()) {
// 1. Let record be a new fetch record whose request is request and controller is fetchParams’s controller.
auto record = Infrastructure::FetchRecord::create(vm, request, fetch_params->controller());
// 2. Append record to request’s client’s fetch group’s fetch records.
request.client()->fetch_group().append(record);
}
// 15. Run main fetch given fetchParams.
(void)TRY(main_fetch(realm, fetch_params));
// 16. Return fetchParams’s controller.
return fetch_params->controller();
}
// https://fetch.spec.whatwg.org/#populate-request-from-client
void populate_request_from_client(JS::Realm const& realm, Infrastructure::Request& request)
{
auto& heap = realm.heap();
// 1. If request’s traversable for user prompts is "client":
auto const* traversable_for_user_prompts = request.traversable_for_user_prompts().get_pointer<Infrastructure::Request::TraversableForUserPrompts>();
if (traversable_for_user_prompts && *traversable_for_user_prompts == Infrastructure::Request::TraversableForUserPrompts::Client) {
// 1. Set request’s traversable for user prompts to "no-traversable".
request.set_traversable_for_user_prompts(Infrastructure::Request::TraversableForUserPrompts::NoTraversable);
// 2. If request’s client is non-null:
if (request.client()) {
// 1. Let global be request’s client’s global object.
auto& global = request.client()->global_object();
// 2. If global is a Window object and global’s navigable is not null, then set request’s traversable for
// user prompts to global’s navigable’s traversable navigable.
if (auto const* window = as_if<HTML::Window>(global)) {
if (window->navigable())
request.set_traversable_for_user_prompts(window->navigable()->traversable_navigable());
}
}
}
// 2. If request’s origin is "client":
auto const* origin = request.origin().get_pointer<Infrastructure::Request::Origin>();
if (origin && *origin == Infrastructure::Request::Origin::Client) {
// 1. Assert: request’s client is non-null.
VERIFY(request.client());
// 2. Set request’s origin to request’s client’s origin.
request.set_origin(request.client()->origin());
}
// 3. If request’s policy container is "client":
auto const* policy_container = request.policy_container().get_pointer<Infrastructure::Request::PolicyContainer>();
if (policy_container && *policy_container == Infrastructure::Request::PolicyContainer::Client) {
// 1. If request’s client is non-null, then set request’s policy container to a clone of request’s client’s
// policy container.
if (request.client())
request.set_policy_container(request.client()->policy_container()->clone(heap));
// 2. Otherwise, set request’s policy container to a new policy container.
else
request.set_policy_container(heap.allocate<HTML::PolicyContainer>(heap));
}
}
// https://fetch.spec.whatwg.org/#concept-main-fetch
WebIDL::ExceptionOr<GC::Ptr<PendingResponse>> main_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Recursive recursive)
{
dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' with: fetch_params @ {}", &fetch_params);
auto& vm = realm.vm();
// 1. Let request be fetchParams’s request.
auto request = fetch_params.request();
// 2. Let response be null.
GC::Ptr<Infrastructure::Response> response;
// 3. If request’s local-URLs-only flag is set and request’s current URL is not local, then set response to a
// network error.
if (request->local_urls_only() && !Infrastructure::is_local_url(request->current_url()))
response = Infrastructure::Response::network_error(vm, "Request with 'local-URLs-only' flag must have a local URL"_string);
// 4. Run report Content Security Policy violations for request.
ContentSecurityPolicy::report_content_security_policy_violations_for_request(realm, request);
// FIXME: 5. Upgrade request to a potentially trustworthy URL, if appropriate.
// 6. Upgrade a mixed content request to a potentially trustworthy URL, if appropriate.
MixedContent::upgrade_a_mixed_content_request_to_a_potentially_trustworthy_url_if_appropriate(request);
// 7. If should request be blocked due to a bad port, should fetching request be blocked as mixed content, should
// request be blocked by Content Security Policy, or should request be blocked by Integrity Policy Policy
// returns blocked, then set response to a network error.
if (Infrastructure::block_bad_port(request) == Infrastructure::RequestOrResponseBlocking::Blocked
|| MixedContent::should_fetching_request_be_blocked_as_mixed_content(request) == Infrastructure::RequestOrResponseBlocking::Blocked
|| ContentSecurityPolicy::should_request_be_blocked_by_content_security_policy(realm, request) == ContentSecurityPolicy::Directives::Directive::Result::Blocked
|| ContentSecurityPolicy::should_request_be_blocked_by_integrity_policy(request) == ContentSecurityPolicy::Directives::Directive::Result::Blocked) {
response = Infrastructure::Response::network_error(vm, "Request was blocked"_string);
}
// 8. If request’s referrer policy is the empty string, then set request’s referrer policy to request’s policy
// container’s referrer policy.
if (request->referrer_policy() == ReferrerPolicy::ReferrerPolicy::EmptyString) {
VERIFY(request->policy_container().has<GC::Ref<HTML::PolicyContainer>>());
request->set_referrer_policy(request->policy_container().get<GC::Ref<HTML::PolicyContainer>>()->referrer_policy);
}
// 9. If request’s referrer is not "no-referrer", then set request’s referrer to the result of invoking determine
// request’s referrer.
// NOTE: As stated in Referrer Policy, user agents can provide the end user with options to override request’s
// referrer to "no-referrer" or have it expose less sensitive information.
auto const* referrer = request->referrer().get_pointer<Infrastructure::Request::Referrer>();
if (!referrer || *referrer != Infrastructure::Request::Referrer::NoReferrer) {
auto determined_referrer = ReferrerPolicy::determine_requests_referrer(request);
if (determined_referrer.has_value())
request->set_referrer(*determined_referrer);
else
request->set_referrer(Infrastructure::Request::Referrer::NoReferrer);
}
// 10. Set request’s current URL’s scheme to "https" if all of the following conditions are true:
if (
// - request’s current URL’s scheme is "http"
request->current_url().scheme() == "http"sv
// - request’s current URL’s host is a domain
&& request->current_url().host().has_value() && request->current_url().host()->is_domain()
// FIXME: - Matching request’s current URL’s host per Known HSTS Host Domain Name Matching results in either a
// superdomain match with an asserted includeSubDomains directive or a congruent match (with or without an
// asserted includeSubDomains directive) [HSTS]; or DNS resolution for the request finds a matching HTTPS RR
// per section 9.5 of [SVCB].
&& false) {
request->current_url().set_scheme("https"_string);
}
auto get_response = GC::create_function(vm.heap(), [&realm, &vm, &fetch_params, request]() -> WebIDL::ExceptionOr<GC::Ref<PendingResponse>> {
dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' get_response() function");
auto const* origin = request->origin().get_pointer<URL::Origin>();
// -> fetchParams’s preloaded response candidate is not null
if (!fetch_params.preloaded_response_candidate().has<Empty>()) {
// 1. Wait until fetchParams’s preloaded response candidate is not "pending".
HTML::main_thread_event_loop().spin_until(GC::create_function(vm.heap(), [&] {
return !fetch_params.preloaded_response_candidate().has<Infrastructure::FetchParams::PreloadedResponseCandidatePendingTag>();
}));
// 2. Assert: fetchParams’s preloaded response candidate is a response.
VERIFY(fetch_params.preloaded_response_candidate().has<GC::Ref<Infrastructure::Response>>());
// 3. Return fetchParams’s preloaded response candidate.
return PendingResponse::create(vm, request, fetch_params.preloaded_response_candidate().get<GC::Ref<Infrastructure::Response>>());
}
// -> request’s current URL’s origin is same origin with request’s origin, and request’s response tainting is "basic"
// -> request’s current URL’s scheme is "data"
// -> request’s mode is "navigate" or "websocket"
if (
(origin && request->current_url().origin().is_same_origin(*origin) && request->response_tainting() == Infrastructure::Request::ResponseTainting::Basic)
|| request->current_url().scheme() == "data"sv
|| (request->mode() == Infrastructure::Request::Mode::Navigate || request->mode() == Infrastructure::Request::Mode::WebSocket)) {
// 1. Set request’s response tainting to "basic".
request->set_response_tainting(Infrastructure::Request::ResponseTainting::Basic);
// 2. Return the result of running scheme fetch given fetchParams.
return scheme_fetch(realm, fetch_params);
// NOTE: HTML assigns any documents and workers created from URLs whose scheme is "data" a unique
// opaque origin. Service workers can only be created from URLs whose scheme is an HTTP(S) scheme.
}
// -> request’s mode is "same-origin"
if (request->mode() == Infrastructure::Request::Mode::SameOrigin) {
// Return a network error.
return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'same-origin' mode must have same URL and request origin"_string));
}
// -> request’s mode is "no-cors"
if (request->mode() == Infrastructure::Request::Mode::NoCORS) {
// 1. If request’s redirect mode is not "follow", then return a network error.
if (request->redirect_mode() != Infrastructure::Request::RedirectMode::Follow)
return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'no-cors' mode must have redirect mode set to 'follow'"_string));
// 2. Set request’s response tainting to "opaque".
request->set_response_tainting(Infrastructure::Request::ResponseTainting::Opaque);
// 3. Return the result of running scheme fetch given fetchParams.
return scheme_fetch(realm, fetch_params);
}
// -> request’s current URL’s scheme is not an HTTP(S) scheme
// AD-HOC: We allow CORS requests for resource:// URLs from opaque origins to enable requesting JS modules from internal pages.
if (!Infrastructure::is_http_or_https_scheme(request->current_url().scheme())
&& !(origin && origin->is_opaque() && request->current_url().scheme() == "resource"sv)) {
// NOTE: At this point all other request modes have been handled. Ensure we're not lying in the error message :^)
VERIFY(request->mode() == Infrastructure::Request::Mode::CORS);
// Return a network error.
return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'cors' mode must have URL with HTTP or HTTPS scheme"_string));
}
// -> request’s use-CORS-preflight flag is set
// -> request’s unsafe-request flag is set and either request’s method is not a CORS-safelisted method or
// CORS-unsafe request-header names with request’s header list is not empty
if (
request->use_cors_preflight()
|| (request->unsafe_request()
&& (!Infrastructure::is_cors_safelisted_method(request->method())
|| !Infrastructure::get_cors_unsafe_header_names(request->header_list()).is_empty()))) {
// 1. Set request’s response tainting to "cors".
request->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);
auto returned_pending_response = PendingResponse::create(vm, request);
// 2. Let corsWithPreflightResponse be the result of running HTTP fetch given fetchParams and true.
auto cors_with_preflight_response = TRY(http_fetch(realm, fetch_params, MakeCORSPreflight::Yes));
cors_with_preflight_response->when_loaded([returned_pending_response](GC::Ref<Infrastructure::Response> cors_with_preflight_response) {
dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' cors_with_preflight_response load callback");
// 3. If corsWithPreflightResponse is a network error, then clear cache entries using request.
if (cors_with_preflight_response->is_network_error()) {
// FIXME: Clear cache entries
}
// 4. Return corsWithPreflightResponse.
returned_pending_response->resolve(cors_with_preflight_response);
});
return returned_pending_response;
}
// -> Otherwise
// 1. Set request’s response tainting to "cors".
request->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);
// 2. Return the result of running HTTP fetch given fetchParams.
return http_fetch(realm, fetch_params);
});
if (recursive == Recursive::Yes) {
// 12. If response is null, then set response to the result of running the steps corresponding to the first
// matching statement:
auto pending_response = !response
? TRY(get_response->function()())
: PendingResponse::create(vm, request, *response);
// 13. If recursive is true, then return response.
return pending_response;
}
// 11. If recursive is false, then run the remaining steps in parallel.
Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(realm.heap(), [&realm, &vm, &fetch_params, request, response, get_response] {
// 12. If response is null, then set response to the result of running the steps corresponding to the first
// matching statement:
auto pending_response = PendingResponse::create(vm, request, Infrastructure::Response::create(vm));
if (!response) {
auto pending_response_or_error = get_response->function()();
if (pending_response_or_error.is_error())
return;
pending_response = pending_response_or_error.release_value();
}
pending_response->when_loaded([&realm, &vm, &fetch_params, request, response, response_was_null = !response](GC::Ref<Infrastructure::Response> resolved_response) mutable {
dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' pending_response load callback");
if (response_was_null)
response = resolved_response;
// 14. If response is not a network error and response is not a filtered response, then:
if (!response->is_network_error() && !is<Infrastructure::FilteredResponse>(*response)) {
// 1. If request’s response tainting is "cors", then:
if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS) {
// 1. Let headerNames be the result of extracting header list values given
// `Access-Control-Expose-Headers` and response’s header list.
auto header_names_or_failure = Infrastructure::extract_header_list_values("Access-Control-Expose-Headers"sv.bytes(), response->header_list());
auto header_names = header_names_or_failure.has<Vector<ByteBuffer>>() ? header_names_or_failure.get<Vector<ByteBuffer>>() : Vector<ByteBuffer> {};
// 2. If request’s credentials mode is not "include" and headerNames contains `*`, then set
// response’s CORS-exposed header-name list to all unique header names in response’s header
// list.
if (request->credentials_mode() != Infrastructure::Request::CredentialsMode::Include && header_names.contains_slow("*"sv.bytes())) {
auto unique_header_names = response->header_list()->unique_names();
response->set_cors_exposed_header_name_list(move(unique_header_names));
}
// 3. Otherwise, if headerNames is not null or failure, then set response’s CORS-exposed
// header-name list to headerNames.
else if (!header_names.is_empty()) {
response->set_cors_exposed_header_name_list(move(header_names));
}
}
// 2. Set response to the following filtered response with response as its internal response, depending
// on request’s response tainting:
response = [&]() -> GC::Ref<Infrastructure::Response> {
switch (request->response_tainting()) {
// -> "basic"
case Infrastructure::Request::ResponseTainting::Basic:
// basic filtered response
return Infrastructure::BasicFilteredResponse::create(vm, *response);
// -> "cors"
case Infrastructure::Request::ResponseTainting::CORS:
// CORS filtered response
return Infrastructure::CORSFilteredResponse::create(vm, *response);
// -> "opaque"
case Infrastructure::Request::ResponseTainting::Opaque:
// opaque filtered response
return Infrastructure::OpaqueFilteredResponse::create(vm, *response);
default:
VERIFY_NOT_REACHED();
}
}();
}
// 15. Let internalResponse be response, if response is a network error, and response’s internal response
// otherwise.
auto internal_response = response->is_network_error()
? GC::Ref { *response }
: static_cast<Infrastructure::FilteredResponse&>(*response).internal_response();
// 16. If internalResponse’s URL list is empty, then set it to a clone of request’s URL list.
// NOTE: A response’s URL list can be empty (for example, when the response represents an about URL).
if (internal_response->url_list().is_empty())
internal_response->set_url_list(request->url_list());
// 17. Set internalResponse’s redirect taint to request’s redirect-taint.
internal_response->set_redirect_taint(request->redirect_taint());
// 18. If request’s timing allow failed flag is unset, then set internalResponse’s timing allow passed flag.
if (!request->timing_allow_failed())
internal_response->set_timing_allow_passed(true);
// 19. If response is not a network error and any of the following returns blocked
if (!response->is_network_error() && (
// - should internalResponse to request be blocked as mixed content
MixedContent::should_response_to_request_be_blocked_as_mixed_content(request, internal_response) == Infrastructure::RequestOrResponseBlocking::Blocked
// - should internalResponse to request be blocked by Content Security Policy
|| ContentSecurityPolicy::should_response_to_request_be_blocked_by_content_security_policy(realm, internal_response, request) == ContentSecurityPolicy::Directives::Directive::Result::Blocked
// - should internalResponse to request be blocked due to its MIME type
|| Infrastructure::should_response_to_request_be_blocked_due_to_its_mime_type(internal_response, request) == Infrastructure::RequestOrResponseBlocking::Blocked
// - should internalResponse to request be blocked due to nosniff
|| Infrastructure::should_response_to_request_be_blocked_due_to_nosniff(internal_response, request) == Infrastructure::RequestOrResponseBlocking::Blocked)) {
// then set response and internalResponse to a network error.
response = internal_response = Infrastructure::Response::network_error(vm, "Response was blocked"_string);
}
// 20. If response’s type is "opaque", internalResponse’s status is 206, internalResponse’s range-requested
// flag is set, and request’s header list does not contain `Range`, then set response and
// internalResponse to a network error.
// NOTE: Traditionally, APIs accept a ranged response even if a range was not requested. This prevents a
// partial response from an earlier ranged request being provided to an API that did not make a range
// request.
if (response->type() == Infrastructure::Response::Type::Opaque
&& internal_response->status() == 206
&& internal_response->range_requested()
&& !request->header_list()->contains("Range"sv.bytes())) {
response = internal_response = Infrastructure::Response::network_error(vm, "Response has status 206 and 'range-requested' flag set, but request has no 'Range' header"_string);
}
// 21. If response is not a network error and either request’s method is `HEAD` or `CONNECT`, or
// internalResponse’s status is a null body status, set internalResponse’s body to null and disregard
// any enqueuing toward it (if any).
// NOTE: This standardizes the error handling for servers that violate HTTP.
if (!response->is_network_error() && (StringView { request->method() }.is_one_of("HEAD"sv, "CONNECT"sv) || Infrastructure::is_null_body_status(internal_response->status())))
internal_response->set_body({});
// 22. If request’s integrity metadata is not the empty string, then:
if (!request->integrity_metadata().is_empty()) {
// 1. Let processBodyError be this step: run fetch response handover given fetchParams and a network
// error.
auto process_body_error = GC::create_function(vm.heap(), [&realm, &vm, &fetch_params](JS::Value) {
fetch_response_handover(realm, fetch_params, Infrastructure::Response::network_error(vm, "Response body could not be processed"_string));
});
// 2. If response’s body is null, then run processBodyError and abort these steps.
if (!response->body()) {
process_body_error->function()({});
return;
}
// 3. Let processBody given bytes be these steps:
auto process_body = GC::create_function(vm.heap(), [&realm, request, response, &fetch_params, process_body_error](ByteBuffer bytes) {
// 1. If bytes do not match request’s integrity metadata, then run processBodyError and abort these steps.
if (!TRY_OR_IGNORE(SRI::do_bytes_match_metadata_list(bytes, request->integrity_metadata()))) {
process_body_error->function()({});
return;
}
// 2. Set response’s body to bytes as a body.
response->set_body(Infrastructure::byte_sequence_as_body(realm, bytes));
// 3. Run fetch response handover given fetchParams and response.
fetch_response_handover(realm, fetch_params, *response);
});
// 4. Fully read response’s body given processBody and processBodyError.
response->body()->fully_read(realm, process_body, process_body_error, fetch_params.task_destination());
}
// 23. Otherwise, run fetch response handover given fetchParams and response.
else {
fetch_response_handover(realm, fetch_params, *response);
}
});
}));
return GC::Ptr<PendingResponse> {};
}
// https://fetch.spec.whatwg.org/#request-determine-the-environment
static GC::Ptr<HTML::Environment> determine_the_environment(GC::Ref<Infrastructure::Request> request)
{
// 1. If request’s reserved client is non-null, then return request’s reserved client.
if (request->reserved_client())
return request->reserved_client();
// 2. If request’s client is non-null, then return request’s client.
if (request->client())
return request->client();
// 3. Return null.
return {};
}
// https://fetch.spec.whatwg.org/#fetch-finale
void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Infrastructure::Response& response)
{
dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'fetch response handover' with: fetch_params @ {}, response @ {}", &fetch_params, &response);
auto& vm = realm.vm();
// 1. Let timingInfo be fetchParams’s timing info.
auto timing_info = fetch_params.timing_info();
// 2. If response is not a network error and fetchParams’s request’s client is a secure context, then set
// timingInfo’s server-timing headers to the result of getting, decoding, and splitting `Server-Timing` from
// response’s header list.
// The user agent may decide to expose `Server-Timing` headers to non-secure contexts requests as well.
auto client = fetch_params.request()->client();
if (!response.is_network_error() && client != nullptr && HTML::is_secure_context(*client)) {
auto server_timing_headers = response.header_list()->get_decode_and_split("Server-Timing"sv.bytes());
if (server_timing_headers.has_value())
timing_info->set_server_timing_headers(server_timing_headers.release_value());
}
// 3. Let processResponseEndOfBody be the following steps:
auto process_response_end_of_body = [&vm, &response, &fetch_params, timing_info] {
// 1. Let unsafeEndTime be the unsafe shared current time.
auto unsafe_end_time = HighResolutionTime::unsafe_shared_current_time();
// 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s full timing
// info to fetchParams’s timing info.
if (fetch_params.request()->destination() == Infrastructure::Request::Destination::Document)
fetch_params.controller()->set_full_timing_info(fetch_params.timing_info());
// 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:
fetch_params.controller()->set_report_timing_steps([&vm, &response, &fetch_params, timing_info, unsafe_end_time](JS::Object& global) mutable {
// 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return.
if (!Infrastructure::is_http_or_https_scheme(fetch_params.request()->url().scheme()))
return;
// 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global.
// Spec Issue: Using relative time here is incorrect, as end time is converted to relative time by Resource Timing,
// causing it to take a relative time of an already relative time, effectively make it always a negative
// value approximately the value of the time origin.
timing_info->set_end_time(unsafe_end_time);
// 3. Let cacheState be response’s cache state.
auto cache_state = response.cache_state();
// 4. Let bodyInfo be response’s body info.
auto body_info = response.body_info();
// 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an
// opaque timing info for timingInfo, set bodyInfo to a new response body info, and set cacheState to
// the empty string.
// NOTE: This covers the case of response being a network error.
if (!response.timing_allow_passed()) {
timing_info = Infrastructure::create_opaque_timing_info(vm, timing_info);
body_info = Infrastructure::Response::BodyInfo {};
cache_state = {};
}
// 6. Let responseStatus be 0.
auto response_status = 0;
// 7. If fetchParams’s request’s mode is not "navigate" or response’s redirect taint is "same-origin":
if (fetch_params.request()->mode() != Infrastructure::Request::Mode::Navigate || response.redirect_taint() == Infrastructure::RedirectTaint::SameOrigin) {
// 1. Set responseStatus to response’s status.
response_status = response.status();
// 2. Let mimeType be the result of extracting a MIME type from response’s header list.
auto mime_type = response.header_list()->extract_mime_type();
// 3. If mimeType is non-null, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType.
if (mime_type.has_value())
body_info.content_type = MimeSniff::minimise_a_supported_mime_type(mime_type.value());
}
// 8. If fetchParams’s request’s initiator type is not null, then mark resource timing given timingInfo,
// request’s URL, request’s initiator type, global, cacheState, bodyInfo, and responseStatus.
if (fetch_params.request()->initiator_type().has_value()) {
ResourceTiming::PerformanceResourceTiming::mark_resource_timing(timing_info, fetch_params.request()->url().to_string(), Infrastructure::initiator_type_to_string(fetch_params.request()->initiator_type().value()), global, cache_state, body_info, response_status);
}
});
// 4. Let processResponseEndOfBodyTask be the following steps:
auto process_response_end_of_body_task = GC::create_function(vm.heap(), [&fetch_params, &response] {
// 1. Set fetchParams’s request’s done flag.
fetch_params.request()->set_done(true);
// 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process response
// end-of-body given response.
if (fetch_params.algorithms()->process_response_end_of_body())
(fetch_params.algorithms()->process_response_end_of_body())(response);
// 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s global
// object is fetchParams’s task destination, then run fetchParams’s controller’s report timing steps
// given fetchParams’s request’s client’s global object.
auto client = fetch_params.request()->client();
auto const* task_destination_global_object = fetch_params.task_destination().get_pointer<GC::Ref<JS::Object>>();
if (client != nullptr && task_destination_global_object != nullptr) {
if (fetch_params.request()->initiator_type().has_value() && &client->global_object() == task_destination_global_object->ptr())
fetch_params.controller()->report_timing(client->global_object());
}
});
// 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination.
Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.task_destination(), move(process_response_end_of_body_task));
};
// 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s process response
// given response, with fetchParams’s task destination.
if (fetch_params.algorithms()->process_response()) {
Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.task_destination(), GC::create_function(vm.heap(), [&fetch_params, &response]() {
fetch_params.algorithms()->process_response()(response);
}));
}
// 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response.
auto internal_response = response.is_network_error() ? GC::Ref { response } : response.unsafe_response();
// 6. If internalResponse’s body is null, then run processResponseEndOfBody.
if (!internal_response->body()) {
process_response_end_of_body();
}
// 7. Otherwise:
else {
HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
// 1. Let transformStream be a new TransformStream.
auto transform_stream = realm.create<Streams::TransformStream>(realm);
// 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.
auto identity_transform_algorithm = GC::create_function(realm.heap(), [&realm, transform_stream](JS::Value chunk) -> GC::Ref<WebIDL::Promise> {
MUST(Streams::transform_stream_default_controller_enqueue(*transform_stream->controller(), chunk));
return WebIDL::create_resolved_promise(realm, JS::js_undefined());
});
// 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm set
// to processResponseEndOfBody.
auto flush_algorithm = GC::create_function(realm.heap(), [&realm, process_response_end_of_body]() -> GC::Ref<WebIDL::Promise> {
process_response_end_of_body();
return WebIDL::create_resolved_promise(realm, JS::js_undefined());
});
transform_stream->set_up(identity_transform_algorithm, flush_algorithm);
// 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream.
internal_response->body()->set_stream(internal_response->body()->stream()->piped_through(transform_stream));
}
// 8. If fetchParams’s process response consume body is non-null, then:
if (fetch_params.algorithms()->process_response_consume_body()) {
// 1. Let processBody given nullOrBytes be this step: run fetchParams’s process response consume body given
// response and nullOrBytes.
auto process_body = GC::create_function(vm.heap(), [&fetch_params, &response](ByteBuffer null_or_bytes) {
(fetch_params.algorithms()->process_response_consume_body())(response, null_or_bytes);
});
// 2. Let processBodyError be this step: run fetchParams’s process response consume body given response and
// failure.
auto process_body_error = GC::create_function(vm.heap(), [&fetch_params, &response](JS::Value) {
(fetch_params.algorithms()->process_response_consume_body())(response, Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag {});
});
// 3. If internalResponse's body is null, then queue a fetch task to run processBody given null, with
// fetchParams’s task destination.
if (!internal_response->body()) {
Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.task_destination(), GC::create_function(vm.heap(), [process_body]() {
process_body->function()({});
}));
}
// 4. Otherwise, fully read internalResponse body given processBody, processBodyError, and fetchParams’s task
// destination.
else {
internal_response->body()->fully_read(realm, process_body, process_body_error, fetch_params.task_destination());
}
}
}
// https://fetch.spec.whatwg.org/#concept-scheme-fetch
WebIDL::ExceptionOr<GC::Ref<PendingResponse>> scheme_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params)
{
dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'scheme fetch' with: fetch_params @ {}", &fetch_params);
auto& vm = realm.vm();
// 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
if (fetch_params.is_canceled())
return PendingResponse::create(vm, fetch_params.request(), Infrastructure::Response::appropriate_network_error(vm, fetch_params));
// 2. Let request be fetchParams’s request.
auto request = fetch_params.request();
// 3. Switch on request’s current URL’s scheme and run the associated steps:
// -> "about"
if (request->current_url().scheme() == "about"sv) {
// If request’s current URL’s path is the string "blank", then return a new response whose status message is
// `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », and body is the empty byte sequence as
// a body.
// NOTE: URLs such as "about:config" are handled during navigation and result in a network error in the context
// of fetching.
if (request->current_url().paths().size() == 1 && request->current_url().paths()[0] == "blank"sv) {
auto response = Infrastructure::Response::create(vm);
response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
auto header = Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html;charset=utf-8"sv);
response->header_list()->append(move(header));
response->set_body(Infrastructure::byte_sequence_as_body(realm, ""sv.bytes()));
return PendingResponse::create(vm, request, response);
}
// FIXME: This is actually wrong, see note above.
return TRY(nonstandard_resource_loader_file_or_http_network_fetch(realm, fetch_params));
}
// -> "blob"
else if (request->current_url().scheme() == "blob"sv) {
// 1. Let blobURLEntry be request’s current URL’s blob URL entry.
auto const& blob_url_entry = request->current_url().blob_url_entry();
// 2. If request’s method is not `GET` or blobURLEntry is null, then return a network error. [FILEAPI]
if (request->method() != "GET"sv.bytes() || !blob_url_entry.has_value()) {
// FIXME: Handle "blobURLEntry’s object is not a Blob object". It could be a MediaSource object, but we
// have not yet implemented the Media Source Extensions spec.
return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has an invalid 'blob:' URL"_string));
}
// 3. Let requestEnvironment be the result of determining the environment given request.
auto request_environment = determine_the_environment(request);
// 4. Let isTopLevelNavigation be true if request’s destination is "document"; otherwise, false.
bool is_top_level_navigation = request->destination() == Infrastructure::Request::Destination::Document;
// 5. If isTopLevelNavigation is false and requestEnvironment is null, then return a network error.
if (!is_top_level_navigation && !request_environment)
return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request is missing fetch client"_string));
// 6. Let navigationOrEnvironment be the string "navigation" if isTopLevelNavigation is true; otherwise, requestEnvironment.
auto navigation_or_environment = [&]() -> Variant<FileAPI::NavigationEnvironment, GC::Ref<HTML::Environment>> {
if (is_top_level_navigation)
return FileAPI::NavigationEnvironment {};
return GC::Ref { *request_environment };
}();
// 7. Let blob be the result of obtaining a blob object given blobURLEntry and navigationOrEnvironment.
auto blob_object = FileAPI::obtain_a_blob_object(blob_url_entry.value(), navigation_or_environment);
// 8. If blob is not a Blob object, then return a network error.
// FIXME: This should probably check for a MediaSource object as well, once we implement that.
if (!blob_object.has_value())
return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Failed to obtain a Blob object from 'blob:' URL"_string));
auto const blob = FileAPI::Blob::create(realm, blob_object->data, blob_object->type);
// 9. Let response be a new response.
auto response = Infrastructure::Response::create(vm);
// 10. Let fullLength be blob’s size.
auto full_length = blob->size();
// 11. Let serializedFullLength be fullLength, serialized and isomorphic encoded.
auto serialized_full_length = String::number(full_length);
// 12. Let type be blob’s type.
auto const& type = blob->type();
// 13. If request’s header list does not contain `Range`:
if (!request->header_list()->contains("Range"sv.bytes())) {
// 1. Let bodyWithType be the result of safely extracting blob.
auto body_with_type = safely_extract_body(realm, blob->raw_bytes());
// 2. Set response’s status message to `OK`.
response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
// 3. Set response’s body to bodyWithType’s body.
response->set_body(body_with_type.body);
// 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ».
auto content_length_header = Infrastructure::Header::from_string_pair("Content-Length"sv, serialized_full_length);
response->header_list()->append(move(content_length_header));
auto content_type_header = Infrastructure::Header::from_string_pair("Content-Type"sv, type);
response->header_list()->append(move(content_type_header));
}
// 14. Otherwise:
else {
// 1. Set response’s range-requested flag.
response->set_range_requested(true);
// 2. Let rangeHeader be the result of getting `Range` from request’s header list.
auto const range_header = request->header_list()->get("Range"sv.bytes()).value_or(ByteBuffer {});
// 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true.
auto maybe_range_value = Infrastructure::parse_single_range_header_value(range_header, true);
// 4. If rangeValue is failure, then return a network error.
if (!maybe_range_value.has_value())
return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Failed to parse single range header value"_string));
// 5. Let (rangeStart, rangeEnd) be rangeValue.
auto& [range_start, range_end] = maybe_range_value.value();
// 6. If rangeStart is null:
if (!range_start.has_value()) {
VERIFY(range_end.has_value());
// 1. Set rangeStart to fullLength − rangeEnd.
range_start = full_length - *range_end;
// 2. Set rangeEnd to rangeStart + rangeEnd − 1.
range_end = *range_start + *range_end - 1;
}
// 7. Otherwise:
else {
// 1. If rangeStart is greater than or equal to fullLength, then return a network error.
if (*range_start >= full_length)
return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "rangeStart is greater than or equal to fullLength"_string));
// 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set rangeEnd to fullLength − 1.
if (!range_end.has_value() || *range_end >= full_length)
range_end = full_length - 1;
}
// 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart, rangeEnd + 1, and type.
auto sliced_blob = TRY(blob->slice(*range_start, *range_end + 1, type));
// 9. Let slicedBodyWithType be the result of safely extracting slicedBlob.
auto sliced_body_with_type = safely_extract_body(realm, sliced_blob->raw_bytes());
// 10. Set response’s body to slicedBodyWithType’s body.
response->set_body(sliced_body_with_type.body);
// 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded.
auto serialized_sliced_length = String::number(sliced_blob->size());
// 12. Let contentRange be the result of invoking build a content range given rangeStart, rangeEnd, and fullLength.
auto content_range = Infrastructure::build_content_range(*range_start, *range_end, full_length);
// 13. Set response’s status to 206.
response->set_status(206);
// 14. Set response’s status message to `Partial Content`.
response->set_status_message(MUST(ByteBuffer::copy("Partial Content"sv.bytes())));
// 15. Set response’s header list to «
// (`Content-Length`, serializedSlicedLength),
auto content_length_header = Infrastructure::Header::from_string_pair("Content-Length"sv, serialized_sliced_length);
response->header_list()->append(move(content_length_header));
// (`Content-Type`, type),
auto content_type_header = Infrastructure::Header::from_string_pair("Content-Type"sv, type);
response->header_list()->append(move(content_type_header));
// (`Content-Range`, contentRange) ».
auto content_range_header = Infrastructure::Header::from_string_pair("Content-Range"sv, content_range);
response->header_list()->append(move(content_range_header));