-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathrequest-response.cpp
More file actions
2579 lines (2211 loc) · 93.7 KB
/
request-response.cpp
File metadata and controls
2579 lines (2211 loc) · 93.7 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
#include "request-response.h"
#include "../streams/native-stream-source.h"
#include "../streams/transform-stream.h"
#include "../url.h"
#include "encode.h"
#include "event_loop.h"
#include "extension-api.h"
#include "fetch_event.h"
#include "host_api.h"
#include "picosha2.h"
#include "js/Array.h"
#include "js/ArrayBuffer.h"
#include "js/Conversions.h"
#include "js/JSON.h"
#include "js/Stream.h"
#include <algorithm>
#include <iostream>
#include <vector>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#include "../worker-location.h"
#include "js/experimental/TypedData.h"
#pragma clang diagnostic pop
namespace builtins::web::streams {
JSObject *NativeStreamSource::stream(JSObject *self) {
return web::fetch::RequestOrResponse::body_stream(owner(self));
}
bool NativeStreamSource::stream_is_body(JSContext *cx, JS::HandleObject stream) {
JSObject *stream_source = get_stream_source(cx, stream);
return NativeStreamSource::is_instance(stream_source) &&
web::fetch::RequestOrResponse::is_instance(owner(stream_source));
}
} // namespace builtins::web::streams
namespace builtins::web::fetch {
static api::Engine *ENGINE;
bool error_stream_controller_with_pending_exception(JSContext *cx, HandleObject controller) {
RootedValue exn(cx);
if (!JS_GetPendingException(cx, &exn))
return false;
JS_ClearPendingException(cx);
RootedValueArray<1> args(cx);
args[0].set(exn);
RootedValue r(cx);
return JS::Call(cx, controller, "error", args, &r);
}
constexpr size_t HANDLE_READ_CHUNK_SIZE = 8192;
class BodyFutureTask final : public api::AsyncTask {
Heap<JSObject *> body_source_;
host_api::HttpIncomingBody *incoming_body_;
public:
explicit BodyFutureTask(const HandleObject body_source) : body_source_(body_source) {
auto owner = streams::NativeStreamSource::owner(body_source_);
incoming_body_ = RequestOrResponse::incoming_body_handle(owner);
auto res = incoming_body_->subscribe();
MOZ_ASSERT(!res.is_err(), "Subscribing to a future should never fail");
handle_ = res.unwrap();
}
[[nodiscard]] bool run(api::Engine *engine) override {
// MOZ_ASSERT(ready());
JSContext *cx = engine->cx();
RootedObject owner(cx, streams::NativeStreamSource::owner(body_source_));
RootedObject controller(cx, streams::NativeStreamSource::controller(body_source_));
auto body = RequestOrResponse::incoming_body_handle(owner);
auto read_res = body->read(HANDLE_READ_CHUNK_SIZE);
if (auto *err = read_res.to_err()) {
HANDLE_ERROR(cx, *err);
return error_stream_controller_with_pending_exception(cx, controller);
}
auto &chunk = read_res.unwrap();
if (chunk.done) {
RootedValue r(cx);
return Call(cx, controller, "close", HandleValueArray::empty(), &r);
}
// We don't release control of chunk's data until after we've checked that
// the array buffer allocation has been successful, as that ensures that the
// return path frees chunk automatically when necessary.
auto &bytes = chunk.bytes;
RootedObject buffer(
cx, JS::NewArrayBufferWithContents(cx, bytes.len, bytes.ptr.get(),
JS::NewArrayBufferOutOfMemory::CallerMustFreeMemory));
if (!buffer) {
return error_stream_controller_with_pending_exception(cx, controller);
}
// At this point `buffer` has taken full ownership of the chunk's data.
std::ignore = bytes.ptr.release();
RootedObject byte_array(cx, JS_NewUint8ArrayWithBuffer(cx, buffer, 0, bytes.len));
if (!byte_array) {
return false;
}
RootedValueArray<1> enqueue_args(cx);
enqueue_args[0].setObject(*byte_array);
RootedValue r(cx);
if (!JS::Call(cx, controller, "enqueue", enqueue_args, &r)) {
return error_stream_controller_with_pending_exception(cx, controller);
}
return cancel(engine);
}
[[nodiscard]] bool cancel(api::Engine *engine) override {
// TODO(TS): implement
handle_ = -1;
return true;
}
void trace(JSTracer *trc) override { TraceEdge(trc, &body_source_, "body source for future"); }
};
namespace {
// https://fetch.spec.whatwg.org/#concept-method-normalize
// Returns `true` if the method name was normalized, `false` otherwise.
bool normalize_http_method(char *method) {
static const char *names[6] = {"DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"};
for (const auto name : names) {
if (strcasecmp(method, name) == 0) {
if (strcmp(method, name) == 0) {
return false;
}
// Note: Safe because `strcasecmp` returning 0 above guarantees
// same-length strings.
strcpy(method, name);
return true;
}
}
return false;
}
struct ReadResult {
UniqueChars buffer;
size_t length;
};
} // namespace
host_api::HttpRequestResponseBase *RequestOrResponse::maybe_handle(JSObject *obj) {
MOZ_ASSERT(is_instance(obj));
auto slot = JS::GetReservedSlot(obj, static_cast<uint32_t>(Slots::RequestOrResponse));
return static_cast<host_api::HttpRequestResponseBase *>(slot.toPrivate());
}
host_api::HttpRequestResponseBase *RequestOrResponse::handle(JSObject *obj) {
auto handle = maybe_handle(obj);
MOZ_ASSERT(handle);
return handle;
}
bool RequestOrResponse::is_instance(JSObject *obj) {
return Request::is_instance(obj) || Response::is_instance(obj);
}
bool RequestOrResponse::is_incoming(JSObject *obj) {
auto handle = RequestOrResponse::maybe_handle(obj);
return handle && handle->is_incoming();
}
host_api::HttpHeadersReadOnly *RequestOrResponse::maybe_headers_handle(JSObject *obj) {
auto handle = maybe_handle(obj);
if (!handle) {
return nullptr;
}
auto res = handle->headers();
MOZ_ASSERT(!res.is_err(), "TODO: proper error handling");
return res.unwrap();
}
bool RequestOrResponse::has_body(JSObject *obj) {
MOZ_ASSERT(is_instance(obj));
return JS::GetReservedSlot(obj, static_cast<uint32_t>(Slots::HasBody)).toBoolean();
}
host_api::HttpIncomingBody *RequestOrResponse::incoming_body_handle(JSObject *obj) {
MOZ_ASSERT(is_incoming(obj));
auto handle = RequestOrResponse::handle(obj);
if (handle->is_request()) {
return reinterpret_cast<host_api::HttpIncomingRequest *>(handle)->body().unwrap();
} else {
return reinterpret_cast<host_api::HttpIncomingResponse *>(handle)->body().unwrap();
}
}
host_api::HttpOutgoingBody *RequestOrResponse::outgoing_body_handle(JSObject *obj) {
MOZ_ASSERT(!is_incoming(obj));
auto handle = RequestOrResponse::handle(obj);
if (handle->is_request()) {
return reinterpret_cast<host_api::HttpOutgoingRequest *>(handle)->body().unwrap();
} else {
return reinterpret_cast<host_api::HttpOutgoingResponse *>(handle)->body().unwrap();
}
}
JSObject *RequestOrResponse::body_stream(JSObject *obj) {
MOZ_ASSERT(is_instance(obj));
return JS::GetReservedSlot(obj, static_cast<uint32_t>(Slots::BodyStream)).toObjectOrNull();
}
JSObject *RequestOrResponse::body_source(JSContext *cx, JS::HandleObject obj) {
MOZ_ASSERT(has_body(obj));
JS::RootedObject stream(cx, body_stream(obj));
return streams::NativeStreamSource::get_stream_source(cx, stream);
}
bool RequestOrResponse::body_used(JSObject *obj) {
MOZ_ASSERT(is_instance(obj));
return JS::GetReservedSlot(obj, static_cast<uint32_t>(Slots::BodyUsed)).toBoolean();
}
bool RequestOrResponse::mark_body_used(JSContext *cx, JS::HandleObject obj) {
MOZ_ASSERT(!body_used(obj));
JS::SetReservedSlot(obj, static_cast<uint32_t>(Slots::BodyUsed), JS::BooleanValue(true));
JS::RootedObject stream(cx, body_stream(obj));
if (stream && streams::NativeStreamSource::stream_is_body(cx, stream)) {
RootedObject source(cx, streams::NativeStreamSource::get_stream_source(cx, stream));
if (streams::NativeStreamSource::piped_to_transform_stream(source)) {
return true;
}
if (!streams::NativeStreamSource::lock_stream(cx, stream)) {
// The only reason why marking the body as used could fail here is that
// it's a disturbed ReadableStream. To improve error reporting, we clear
// the current exception and throw a better one.
JS_ClearPendingException(cx);
return api::throw_error(cx, FetchErrors::BodyStreamUnusable);
}
}
return true;
}
JS::Value RequestOrResponse::url(JSObject *obj) {
MOZ_ASSERT(is_instance(obj));
JS::Value val = JS::GetReservedSlot(obj, static_cast<uint32_t>(RequestOrResponse::Slots::URL));
MOZ_ASSERT(val.isString());
return val;
}
void RequestOrResponse::set_url(JSObject *obj, JS::Value url) {
MOZ_ASSERT(is_instance(obj));
MOZ_ASSERT(url.isString());
JS::SetReservedSlot(obj, static_cast<uint32_t>(RequestOrResponse::Slots::URL), url);
}
/**
* Implementation of the `body is unusable` concept at
* https://fetch.spec.whatwg.org/#body-unusable
*/
bool RequestOrResponse::body_unusable(JSContext *cx, JS::HandleObject body) {
MOZ_ASSERT(JS::IsReadableStream(body));
bool disturbed;
bool locked;
MOZ_RELEASE_ASSERT(JS::ReadableStreamIsDisturbed(cx, body, &disturbed) &&
JS::ReadableStreamIsLocked(cx, body, &locked));
return disturbed || locked;
}
/**
* Implementation of the `extract a body` algorithm at
* https://fetch.spec.whatwg.org/#concept-bodyinit-extract
*
* Note: also includes the steps applying the `Content-Type` header from the
* Request and Response constructors in step 36 and 8 of those, respectively.
*/
bool RequestOrResponse::extract_body(JSContext *cx, JS::HandleObject self,
JS::HandleValue body_val) {
MOZ_ASSERT(is_instance(self));
MOZ_ASSERT(!has_body(self));
MOZ_ASSERT(!body_val.isNullOrUndefined());
const char *content_type = nullptr;
mozilla::Maybe<size_t> content_length;
// We currently support five types of body inputs:
// - byte sequence
// - buffer source
// - USV strings
// - URLSearchParams
// - ReadableStream
// After the other other options are checked explicitly, all other inputs are
// encoded to a UTF8 string to be treated as a USV string.
// TODO: Support the other possible inputs to Body.
JS::RootedObject body_obj(cx, body_val.isObject() ? &body_val.toObject() : nullptr);
if (body_obj && JS::IsReadableStream(body_obj)) {
if (RequestOrResponse::body_unusable(cx, body_obj)) {
return api::throw_error(cx, FetchErrors::BodyStreamUnusable);
}
JS_SetReservedSlot(self, static_cast<uint32_t>(RequestOrResponse::Slots::BodyStream), body_val);
// Ensure that we take the right steps for shortcutting operations on
// TransformStreams later on.
if (streams::TransformStream::is_ts_readable(cx, body_obj)) {
// But only if the TransformStream isn't used as a mixin by other
// builtins.
if (!streams::TransformStream::used_as_mixin(
streams::TransformStream::ts_from_readable(cx, body_obj))) {
streams::TransformStream::set_readable_used_as_body(cx, body_obj, self);
}
}
} else {
RootedValue chunk(cx);
RootedObject buffer(cx);
char *buf = nullptr;
size_t length = 0;
if (body_obj && JS_IsArrayBufferViewObject(body_obj)) {
length = JS_GetArrayBufferViewByteLength(body_obj);
buf = static_cast<char *>(js_malloc(length));
if (!buf) {
return false;
}
bool is_shared;
JS::AutoCheckCannotGC noGC(cx);
auto temp_buf = JS_GetArrayBufferViewData(body_obj, &is_shared, noGC);
memcpy(buf, temp_buf, length);
} else if (body_obj && IsArrayBufferObject(body_obj)) {
buffer = CopyArrayBuffer(cx, body_obj);
if (!buffer) {
return false;
}
length = GetArrayBufferByteLength(buffer);
} else if (body_obj && url::URLSearchParams::is_instance(body_obj)) {
auto slice = url::URLSearchParams::serialize(cx, body_obj);
buf = (char *)slice.data;
length = slice.len;
content_type = "application/x-www-form-urlencoded;charset=UTF-8";
} else {
auto text = core::encode(cx, body_val);
if (!text.ptr) {
return false;
}
buf = text.ptr.release();
length = text.len;
content_type = "text/plain;charset=UTF-8";
}
if (!buffer) {
MOZ_ASSERT_IF(length, buf);
buffer = NewArrayBufferWithContents(cx, length, buf,
JS::NewArrayBufferOutOfMemory::CallerMustFreeMemory);
if (!buffer) {
js_free(buf);
return false;
}
}
RootedObject array(cx, JS_NewUint8ArrayWithBuffer(cx, buffer, 0, length));
if (!array) {
return false;
}
chunk.setObject(*array);
// Set a __proto__-less source so modifying Object.prototype doesn't change the behavior.
RootedObject source(cx, JS_NewObjectWithGivenProto(cx, nullptr, nullptr));
if (!source) {
return false;
}
RootedObject body_stream(cx, JS::NewReadableDefaultStreamObject(cx, source, nullptr, 0.0));
if (!body_stream) {
return false;
}
mozilla::DebugOnly<bool> disturbed;
MOZ_ASSERT(ReadableStreamIsDisturbed(cx, body_stream, &disturbed));
MOZ_ASSERT(!disturbed);
if (!ReadableStreamEnqueue(cx, body_stream, chunk) || !ReadableStreamClose(cx, body_stream)) {
return false;
}
JS_SetReservedSlot(self, static_cast<uint32_t>(Slots::BodyStream), ObjectValue(*body_stream));
content_length.emplace(length);
}
if (content_type || content_length.isSome()) {
JS::RootedObject headers(cx, RequestOrResponse::headers(cx, self));
if (!headers) {
return false;
}
if (content_length.isSome()) {
auto length_str = std::to_string(content_length.value());
if (!Headers::set_valid_if_undefined(cx, headers, "content-length", length_str)) {
return false;
}
}
// Step 36.3 of Request constructor / 8.4 of Response constructor.
if (content_type &&
!Headers::set_valid_if_undefined(cx, headers, "content-type", content_type)) {
return false;
}
}
JS::SetReservedSlot(self, static_cast<uint32_t>(Slots::HasBody), JS::BooleanValue(true));
return true;
}
JSObject *RequestOrResponse::maybe_headers(JSObject *obj) {
MOZ_ASSERT(is_instance(obj));
return JS::GetReservedSlot(obj, static_cast<uint32_t>(Slots::Headers)).toObjectOrNull();
}
unique_ptr<host_api::HttpHeaders> RequestOrResponse::headers_handle_clone(JSContext *cx,
HandleObject self) {
MOZ_ASSERT(is_instance(self));
RootedObject headers(cx, maybe_headers(self));
if (headers) {
return Headers::handle_clone(cx, headers);
}
auto handle = RequestOrResponse::maybe_handle(self);
if (!handle) {
return std::make_unique<host_api::HttpHeaders>();
}
auto res = handle->headers();
if (auto *err = res.to_err()) {
HANDLE_ERROR(cx, *err);
return nullptr;
}
return unique_ptr<host_api::HttpHeaders>(res.unwrap()->clone());
}
bool finish_outgoing_body_streaming(JSContext *cx, HandleObject body_owner) {
// If no `body_owner` was passed, that means we sent a response: those aren't always
// reified during `respondWith` processing, and we don't need the instance here.
// That means, if we don't have the `body_owner`, we can advance the FetchState to
// `responseDone`.
// (Note that even if we encountered an error while streaming, `responseDone` is the
// right state: `respondedWithError` is for when sending a response at all failed.)
// TODO(TS): factor this out to remove dependency on fetch-event.h
if (!body_owner || Response::is_instance(body_owner)) {
fetch_event::FetchEvent::set_state(fetch_event::FetchEvent::instance(),
fetch_event::FetchEvent::State::responseDone);
return true;
}
auto body = RequestOrResponse::outgoing_body_handle(body_owner);
auto res = body->close();
if (auto *err = res.to_err()) {
HANDLE_ERROR(cx, *err);
return false;
}
if (Request::is_instance(body_owner)) {
auto pending_handle = static_cast<host_api::FutureHttpIncomingResponse *>(
GetReservedSlot(body_owner, static_cast<uint32_t>(Request::Slots::PendingResponseHandle))
.toPrivate());
SetReservedSlot(body_owner, static_cast<uint32_t>(Request::Slots::PendingResponseHandle),
PrivateValue(nullptr));
ENGINE->queue_async_task(new ResponseFutureTask(body_owner, pending_handle));
}
return true;
}
bool RequestOrResponse::append_body(JSContext *cx, JS::HandleObject self, JS::HandleObject source,
api::TaskCompletionCallback callback, HandleObject callback_receiver) {
MOZ_ASSERT(!body_used(source));
MOZ_ASSERT(self != source);
host_api::HttpIncomingBody *source_body = incoming_body_handle(source);
host_api::HttpOutgoingBody *dest_body = outgoing_body_handle(self);
auto res = dest_body->append(ENGINE, source_body, callback, callback_receiver);
if (auto *err = res.to_err()) {
HANDLE_ERROR(cx, *err);
return false;
}
mozilla::DebugOnly<bool> success = mark_body_used(cx, source);
MOZ_ASSERT(success);
// append_body can be called multiple times, but we only want to mark the body as used the first
// time it happens.
if (body_stream(source) != body_stream(self) && !body_used(self)) {
success = mark_body_used(cx, self);
MOZ_ASSERT(success);
}
return true;
}
JSObject *RequestOrResponse::headers(JSContext *cx, JS::HandleObject obj) {
JSObject *headers = maybe_headers(obj);
if (!headers) {
// Incoming request and incoming response headers are immutable per service worker
// and fetch specs respectively.
Headers::HeadersGuard guard = is_incoming(obj) ? Headers::HeadersGuard::Immutable
: Request::is_instance(obj) ? Headers::HeadersGuard::Request
: Headers::HeadersGuard::Response;
host_api::HttpHeadersReadOnly *handle;
if (is_incoming(obj) && (handle = maybe_headers_handle(obj))) {
headers = Headers::create(cx, handle, guard);
} else {
headers = Headers::create(cx, guard);
}
if (!headers) {
return nullptr;
}
JS_SetReservedSlot(obj, static_cast<uint32_t>(Slots::Headers), JS::ObjectValue(*headers));
}
return headers;
}
template <RequestOrResponse::BodyReadResult result_type>
bool RequestOrResponse::parse_body(JSContext *cx, JS::HandleObject self, JS::UniqueChars buf,
size_t len) {
JS::RootedObject result_promise(
cx, &JS::GetReservedSlot(self, static_cast<uint32_t>(Slots::BodyAllPromise)).toObject());
JS::SetReservedSlot(self, static_cast<uint32_t>(Slots::BodyAllPromise), JS::UndefinedValue());
JS::RootedValue result(cx);
if constexpr (result_type == RequestOrResponse::BodyReadResult::ArrayBuffer) {
JS::RootedObject array_buffer(
cx, JS::NewArrayBufferWithContents(cx, len, buf.get(),
JS::NewArrayBufferOutOfMemory::CallerMustFreeMemory));
if (!array_buffer) {
return RejectPromiseWithPendingError(cx, result_promise);
}
static_cast<void>(buf.release());
result.setObject(*array_buffer);
} else {
JS::RootedString text(cx, JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(buf.get(), len)));
if (!text) {
return RejectPromiseWithPendingError(cx, result_promise);
}
if constexpr (result_type == RequestOrResponse::BodyReadResult::Text) {
result.setString(text);
} else {
MOZ_ASSERT(result_type == RequestOrResponse::BodyReadResult::JSON);
if (!JS_ParseJSON(cx, text, &result)) {
return RejectPromiseWithPendingError(cx, result_promise);
}
}
}
return JS::ResolvePromise(cx, result_promise, result);
}
bool RequestOrResponse::content_stream_read_then_handler(JSContext *cx, JS::HandleObject self,
JS::HandleValue extra, JS::CallArgs args) {
JS::RootedObject then_handler(cx, &args.callee());
// The reader is stored in the catch handler, which we need here as well.
// So we get that first, then the reader.
MOZ_ASSERT(extra.isObject());
JS::RootedObject catch_handler(cx, &extra.toObject());
#ifdef DEBUG
bool foundContents;
if (!JS_HasElement(cx, catch_handler, 1, &foundContents)) {
return false;
}
MOZ_ASSERT(foundContents);
#endif
JS::RootedValue contents_val(cx);
if (!JS_GetElement(cx, catch_handler, 1, &contents_val)) {
return false;
}
MOZ_ASSERT(contents_val.isObject());
JS::RootedObject contents(cx, &contents_val.toObject());
if (!contents) {
return false;
}
#ifdef DEBUG
bool contentsIsArray;
if (!JS::IsArrayObject(cx, contents, &contentsIsArray)) {
return false;
}
MOZ_ASSERT(contentsIsArray);
#endif
auto reader_val = js::GetFunctionNativeReserved(catch_handler, 1);
MOZ_ASSERT(reader_val.isObject());
JS::RootedObject reader(cx, &reader_val.toObject());
// We're guaranteed to work with a native ReadableStreamDefaultReader here as we used
// `JS::ReadableStreamDefaultReaderRead(cx, reader)`, which in turn is guaranteed to return {done:
// bool, value: any} objects to read promise then callbacks.
MOZ_ASSERT(args[0].isObject());
JS::RootedObject chunk_obj(cx, &args[0].toObject());
JS::RootedValue done_val(cx);
JS::RootedValue value(cx);
#ifdef DEBUG
bool hasValue;
if (!JS_HasProperty(cx, chunk_obj, "value", &hasValue)) {
return false;
}
MOZ_ASSERT(hasValue);
#endif
if (!JS_GetProperty(cx, chunk_obj, "value", &value)) {
return false;
}
#ifdef DEBUG
bool hasDone;
if (!JS_HasProperty(cx, chunk_obj, "done", &hasDone)) {
return false;
}
MOZ_ASSERT(hasDone);
#endif
if (!JS_GetProperty(cx, chunk_obj, "done", &done_val)) {
return false;
}
MOZ_ASSERT(done_val.isBoolean());
if (done_val.toBoolean()) {
// We finished reading the stream
// Now we need to iterate/reduce `contents` JS Array into UniqueChars
uint32_t contentsLength;
if (!JS::GetArrayLength(cx, contents, &contentsLength)) {
return false;
}
size_t total_length = 0;
RootedValue val(cx);
for (size_t index = 0; index < contentsLength; index++) {
if (!JS_GetElement(cx, contents, index, &val)) {
return false;
}
JSObject *array = &val.toObject();
size_t length = JS_GetTypedArrayByteLength(array);
total_length += length;
}
JS::UniqueChars buf{static_cast<char *>(JS_malloc(cx, total_length))};
if (!buf) {
JS_ReportOutOfMemory(cx);
return false;
}
size_t offset = 0;
// In this loop we are inserting each entry in `contents` into `buf`
for (uint32_t index = 0; index < contentsLength; index++) {
if (!JS_GetElement(cx, contents, index, &val)) {
return false;
}
JSObject *array = &val.toObject();
bool is_shared;
size_t length = JS_GetTypedArrayByteLength(array);
JS::AutoCheckCannotGC nogc(cx);
auto bytes = reinterpret_cast<char *>(JS_GetUint8ArrayData(array, &is_shared, nogc));
memcpy(buf.get() + offset, bytes, length);
offset += length;
}
mozilla::DebugOnly foundBodyParser = false;
MOZ_ASSERT(JS_HasElement(cx, catch_handler, 2, &foundBodyParser));
MOZ_ASSERT(foundBodyParser);
// Now we can call parse_body on the result
JS::RootedValue body_parser(cx);
if (!JS_GetElement(cx, catch_handler, 2, &body_parser)) {
return false;
}
auto parse_body = (ParseBodyCB *)body_parser.toPrivate();
return parse_body(cx, self, std::move(buf), offset);
}
JS::RootedValue val(cx);
if (!JS_GetProperty(cx, chunk_obj, "value", &val)) {
return false;
}
// The read operation can return anything since this stream comes from the guest
// If it is not a UInt8Array -- reject with a TypeError
if (!val.isObject() || !JS_IsUint8Array(&val.toObject())) {
api::throw_error(cx, FetchErrors::InvalidStreamChunk);
JS::RootedObject result_promise(cx);
result_promise =
&JS::GetReservedSlot(self, static_cast<uint32_t>(Slots::BodyAllPromise)).toObject();
JS::SetReservedSlot(self, static_cast<uint32_t>(Slots::BodyAllPromise), JS::UndefinedValue());
return RejectPromiseWithPendingError(cx, result_promise);
}
{
uint32_t contentsLength;
if (!JS::GetArrayLength(cx, contents, &contentsLength)) {
return false;
}
if (!JS_SetElement(cx, contents, contentsLength, val)) {
return false;
}
}
// Read the next chunk.
JS::RootedObject promise(cx, JS::ReadableStreamDefaultReaderRead(cx, reader));
if (!promise)
return false;
return JS::AddPromiseReactions(cx, promise, then_handler, catch_handler);
}
bool RequestOrResponse::content_stream_read_catch_handler(JSContext *cx, JS::HandleObject self,
JS::HandleValue extra,
JS::CallArgs args) {
// The stream errored when being consumed
// we need to propagate the stream error
MOZ_ASSERT(extra.isObject());
JS::RootedObject reader(cx, &extra.toObject());
JS::RootedValue stream_val(cx);
if (!JS_GetElement(cx, reader, 1, &stream_val)) {
return false;
}
MOZ_ASSERT(stream_val.isObject());
JS::RootedObject stream(cx, &stream_val.toObject());
if (!stream) {
return false;
}
MOZ_ASSERT(JS::IsReadableStream(stream));
#ifdef DEBUG
bool isError;
if (!JS::ReadableStreamIsErrored(cx, stream, &isError)) {
return false;
}
MOZ_ASSERT(isError);
#endif
JS::RootedValue error(cx, JS::ReadableStreamGetStoredError(cx, stream));
JS_ClearPendingException(cx);
JS_SetPendingException(cx, error, JS::ExceptionStackBehavior::DoNotCapture);
JS::RootedObject result_promise(cx);
result_promise =
&JS::GetReservedSlot(self, static_cast<uint32_t>(Slots::BodyAllPromise)).toObject();
JS::SetReservedSlot(self, static_cast<uint32_t>(Slots::BodyAllPromise), JS::UndefinedValue());
return RejectPromiseWithPendingError(cx, result_promise);
}
bool RequestOrResponse::consume_content_stream_for_bodyAll(JSContext *cx, JS::HandleObject self,
JS::HandleValue stream_val,
JS::CallArgs args) {
// The body_parser is stored in the stream object, which we need here as well.
JS::RootedObject stream(cx, &stream_val.toObject());
JS::RootedValue body_parser(cx);
if (!JS_GetElement(cx, stream, 1, &body_parser)) {
return false;
}
MOZ_ASSERT(JS::IsReadableStream(stream));
if (RequestOrResponse::body_unusable(cx, stream)) {
api::throw_error(cx, FetchErrors::BodyStreamUnusable);
JS::RootedObject result_promise(cx);
result_promise =
&JS::GetReservedSlot(self, static_cast<uint32_t>(Slots::BodyAllPromise)).toObject();
JS::SetReservedSlot(self, static_cast<uint32_t>(Slots::BodyAllPromise), JS::UndefinedValue());
return RejectPromiseWithPendingError(cx, result_promise);
}
JS::Rooted<JSObject *> unwrappedReader(
cx, JS::ReadableStreamGetReader(cx, stream, JS::ReadableStreamReaderMode::Default));
if (!unwrappedReader) {
return false;
}
// contents is the JS Array we store the stream chunks within, to later convert to
// arrayBuffer/json/text
JS::Rooted<JSObject *> contents(cx, JS::NewArrayObject(cx, 0));
if (!contents) {
return false;
}
JS::RootedValue extra(cx, JS::ObjectValue(*unwrappedReader));
// TODO: confirm whether this is observable to the JS application
if (!JS_SetElement(cx, unwrappedReader, 1, stream)) {
return false;
}
// Create handlers for both `then` and `catch`.
// These are functions with two reserved slots, in which we store all
// information required to perform the reactions. We store the actually
// required information on the catch handler, and a reference to that on the
// then handler. This allows us to reuse these functions for the next read
// operation in the then handler. The catch handler won't ever have a need to
// perform another operation in this way.
JS::RootedObject catch_handler(
cx, create_internal_method<content_stream_read_catch_handler>(cx, self, extra));
if (!catch_handler) {
return false;
}
extra.setObject(*catch_handler);
if (!JS_SetElement(cx, catch_handler, 1, contents)) {
return false;
}
if (!JS_SetElement(cx, catch_handler, 2, body_parser)) {
return false;
}
JS::RootedObject then_handler(
cx, create_internal_method<content_stream_read_then_handler>(cx, self, extra));
if (!then_handler) {
return false;
}
// Read the next chunk.
JS::RootedObject promise(cx, JS::ReadableStreamDefaultReaderRead(cx, unwrappedReader));
if (!promise) {
return false;
}
return JS::AddPromiseReactions(cx, promise, then_handler, catch_handler);
}
template <RequestOrResponse::BodyReadResult result_type>
bool RequestOrResponse::bodyAll(JSContext *cx, JS::CallArgs args, JS::HandleObject self) {
// TODO: mark body as consumed when operating on stream, too.
if (body_used(self)) {
api::throw_error(cx, FetchErrors::BodyStreamUnusable);
return ReturnPromiseRejectedWithPendingError(cx, args);
}
JS::RootedObject bodyAll_promise(cx, JS::NewPromiseObject(cx, nullptr));
if (!bodyAll_promise) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
JS::SetReservedSlot(self, static_cast<uint32_t>(Slots::BodyAllPromise),
JS::ObjectValue(*bodyAll_promise));
// If the Request/Response doesn't have a body, empty default results need to
// be returned.
if (!has_body(self)) {
JS::UniqueChars chars;
if (!parse_body<result_type>(cx, self, std::move(chars), 0)) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
args.rval().setObject(*bodyAll_promise);
return true;
}
JS::RootedValue body_parser(cx, JS::PrivateValue((void *)parse_body<result_type>));
// TODO(performance): don't reify a ReadableStream for body handles—use an AsyncTask instead
JS::RootedObject stream(cx, body_stream(self));
if (!stream) {
stream = create_body_stream(cx, self);
if (!stream)
return false;
}
if (!JS_SetElement(cx, stream, 1, body_parser)) {
return false;
}
SetReservedSlot(self, static_cast<uint32_t>(Slots::BodyUsed), JS::BooleanValue(true));
JS::RootedValue extra(cx, JS::ObjectValue(*stream));
if (!enqueue_internal_method<consume_content_stream_for_bodyAll>(cx, self, extra)) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
args.rval().setObject(*bodyAll_promise);
return true;
}
/**
* Closes the ReadableStream representing a body after it's been appended to an outgoing body.
*
* The append operation is performed using the host API, not via the JS Streams API, so this
* explicit closing operation is needed to close the loop on the latter.
*/
bool close_appended_body(JSContext *cx, HandleObject body_owner) {
RootedObject body(cx, RequestOrResponse::body_stream(body_owner));
return ReadableStreamClose(cx, body);
}
bool do_body_source_pull(JSContext *cx, HandleObject source, HandleObject body_owner) {
// If the stream has been piped to a TransformStream whose readable end was
// then passed to a Request or Response as the body, we can just append the
// entire source body to the destination using a single native hostcall, and
// then close the source stream, instead of reading and writing it in
// individual chunks.
// Note that even in situations where multiple streams are piped to the same
// destination this is guaranteed to happen in the right order:
// ReadableStream#pipeTo locks the destination WritableStream until the
// source ReadableStream is closed/canceled, so only one stream can ever be
// piped in at the same time.
RootedObject pipe_dest(cx, streams::NativeStreamSource::piped_to_transform_stream(source));
if (pipe_dest && streams::TransformStream::readable_used_as_body(pipe_dest)) {
MOZ_ASSERT(!streams::TransformStream::backpressure(pipe_dest));
RootedObject dest_owner(cx, streams::TransformStream::owner(pipe_dest));
MOZ_ASSERT(!JS_IsExceptionPending(cx));
if (!RequestOrResponse::append_body(cx, dest_owner, body_owner, close_appended_body, body_owner)) {
return false;
}
MOZ_ASSERT(!JS_IsExceptionPending(cx));
return true;
}
ENGINE->queue_async_task(new BodyFutureTask(source));
return true;
}
bool bp_change_then_handler(JSContext *cx, HandleObject source, HandleValue extra, CallArgs args) {
MOZ_ASSERT(extra.isObject());
RootedObject body_owner(cx, &extra.toObject());
MOZ_ASSERT(RequestOrResponse::is_instance(body_owner));
if (!do_body_source_pull(cx, source, body_owner)) {
return false;
}
args.rval().setUndefined();
return true;
}
bool RequestOrResponse::body_source_pull_algorithm(JSContext *cx, CallArgs args,
HandleObject source, HandleObject body_owner,
HandleObject _controller) {
// If the stream has been piped to a TransformStream whose readable end has backpressure applied,
// we wait for the backpressure to be removed before actually reading from the body.
// That way, we can avoid reading any chunks from the body for now, and might be able to append
// it in full to an outgoing stream later.
RootedObject pipe_dest(cx, streams::NativeStreamSource::piped_to_transform_stream(source));
if (pipe_dest && streams::TransformStream::backpressure(pipe_dest)) {
RootedObject bp_change_promise(cx,
streams::TransformStream::backpressureChangePromise(pipe_dest));
JS::RootedObject then_handler(cx);
RootedValue extra(cx, ObjectValue(*body_owner));
then_handler = create_internal_method<bp_change_then_handler>(cx, source, extra);
if (!then_handler) {
return false;
}
return AddPromiseReactionsIgnoringUnhandledRejection(cx, bp_change_promise, then_handler,
nullptr);
}
if (!do_body_source_pull(cx, source, body_owner)) {
return false;
}
args.rval().setUndefined();
return true;
}
bool RequestOrResponse::body_source_cancel_algorithm(JSContext *cx, JS::CallArgs args,
JS::HandleObject stream,
JS::HandleObject owner,
JS::HandleValue reason) {
// TODO: implement or add a comment explaining why no implementation is required.
args.rval().setUndefined();
return true;
}
bool write_all_finish_callback(JSContext *cx, HandleObject then_handler) {
// The reader is stored in the catch handler, which we need here as well.
// So we get that first, then the reader.
JS::RootedObject catch_handler(cx, &GetFunctionNativeReserved(then_handler, 1).toObject());
JS::RootedObject reader(cx, &GetFunctionNativeReserved(catch_handler, 1).toObject());
// Read the next chunk.
JS::RootedObject promise(cx, ReadableStreamDefaultReaderRead(cx, reader));
if (!promise) {
return false;
}
return AddPromiseReactions(cx, promise, then_handler, catch_handler);
}
bool reader_for_outgoing_body_then_handler(JSContext *cx, JS::HandleObject body_owner,
JS::HandleValue extra, JS::CallArgs args) {
JS::RootedObject then_handler(cx, &args.callee());
// We're guaranteed to work with a native ReadableStreamDefaultReader here,
// which in turn is guaranteed to vend {done: bool, value: any} objects to
// read promise then callbacks.
JS::RootedObject chunk_obj(cx, &args[0].toObject());
JS::RootedValue done_val(cx);
if (!JS_GetProperty(cx, chunk_obj, "done", &done_val))
return false;
if (done_val.toBoolean()) {
return finish_outgoing_body_streaming(cx, body_owner);
}
JS::RootedValue val(cx);
if (!JS_GetProperty(cx, chunk_obj, "value", &val))
return false;