-
Notifications
You must be signed in to change notification settings - Fork 25
/
request-response.cpp
2616 lines (2283 loc) · 94.9 KB
/
request-response.cpp
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 "builtins/request-response.h"
#include "builtins/cache-override.h"
#include "builtins/client-info.h"
#include "builtins/fastly.h"
#include "builtins/fetch-event.h"
#include "builtins/native-stream-source.h"
#include "builtins/object-store.h"
#include "builtins/shared/url.h"
#include "builtins/transform-stream.h"
#include "host_interface/host_api.h"
#include "third_party/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 "js/experimental/TypedData.h"
#pragma clang diagnostic pop
namespace builtins {
namespace {
constexpr size_t HANDLE_READ_CHUNK_SIZE = 8192;
// 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 (size_t i = 0; i < 6; i++) {
auto name = names[i];
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 {
JS::UniqueChars buffer;
size_t length;
};
// Returns a UniqueChars and the length of that string. The UniqueChars value is not
// null-terminated.
ReadResult read_from_handle_all(JSContext *cx, uint32_t handle) {
std::vector<HostString> chunks;
size_t bytes_read = 0;
HttpBody body{handle};
while (true) {
auto res = body.read(HANDLE_READ_CHUNK_SIZE);
if (auto *err = res.to_err()) {
HANDLE_ERROR(cx, *err);
return {nullptr, 0};
}
auto &chunk = res.unwrap();
if (chunk.len == 0) {
break;
}
bytes_read += chunk.len;
chunks.emplace_back(std::move(chunk));
}
JS::UniqueChars buf;
if (chunks.size() == 1) {
// If there was only one chunk read, reuse that allocation.
auto &chunk = chunks.back();
buf = std::move(chunk.ptr);
} else {
// If there wasn't exactly one chunk read, we'll need to allocate a buffer to store the results.
buf.reset(static_cast<char *>(JS_string_malloc(cx, bytes_read)));
if (!buf) {
JS_ReportOutOfMemory(cx);
return {nullptr, 0};
}
char *end = buf.get();
for (auto &chunk : chunks) {
end = std::copy(chunk.ptr.get(), chunk.ptr.get() + chunk.len, end);
}
}
return {std::move(buf), bytes_read};
}
template <InternalMethod fun>
bool enqueue_internal_method(JSContext *cx, JS::HandleObject receiver,
JS::HandleValue extra = JS::UndefinedHandleValue,
unsigned int nargs = 0, const char *name = "") {
JS::RootedObject method(cx, create_internal_method<fun>(cx, receiver, extra, nargs, name));
if (!method) {
return false;
}
JS::RootedObject promise(cx, JS::CallOriginalPromiseResolve(cx, JS::UndefinedHandleValue));
if (!promise) {
return false;
}
return JS::AddPromiseReactions(cx, promise, method, nullptr);
}
} // namespace
bool RequestOrResponse::is_instance(JSObject *obj) {
return Request::is_instance(obj) || Response::is_instance(obj) ||
ObjectStoreEntry::is_instance(obj);
}
uint32_t RequestOrResponse::handle(JSObject *obj) {
MOZ_ASSERT(is_instance(obj));
return static_cast<uint32_t>(
JS::GetReservedSlot(obj, static_cast<uint32_t>(Slots::RequestOrResponse)).toInt32());
}
bool RequestOrResponse::has_body(JSObject *obj) {
MOZ_ASSERT(is_instance(obj));
return JS::GetReservedSlot(obj, static_cast<uint32_t>(Slots::HasBody)).toBoolean();
}
fastly_body_handle_t RequestOrResponse::body_handle(JSObject *obj) {
MOZ_ASSERT(is_instance(obj));
return JS::GetReservedSlot(obj, static_cast<uint32_t>(Slots::Body)).toInt32();
}
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 builtins::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 && builtins::NativeStreamSource::stream_is_body(cx, stream)) {
if (!builtins::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);
JS_ReportErrorLatin1(cx, "The ReadableStream body is already locked and can't be consumed");
return false;
}
}
return true;
}
/**
* Moves an underlying body handle from one Request/Response object to another.
*
* Also marks the source object's body as consumed.
*/
bool RequestOrResponse::move_body_handle(JSContext *cx, JS::HandleObject from,
JS::HandleObject to) {
MOZ_ASSERT(is_instance(from));
MOZ_ASSERT(is_instance(to));
MOZ_ASSERT(!body_used(from));
// Replace the receiving object's body handle with the body stream source's
// underlying handle.
// TODO: Let the host know we'll not use the old handle anymore, once C@E has
// a hostcall for that.
fastly_body_handle_t body = body_handle(from);
JS::SetReservedSlot(to, static_cast<uint32_t>(Slots::Body), JS::Int32Value(body));
// Mark the source's body as used, and the stream as locked to prevent any
// future attempts to use the underlying handle we just removed.
return mark_body_used(cx, from);
}
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: our implementation is somewhat different from what the spec describes
* in that we immediately write all non-streaming body types to the host instead
* of creating a stream for them. We don't have threads, so there's nothing "in
* parallel" to be had anyway.
*
* 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;
// 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)) {
JS_ReportErrorLatin1(cx, "Can't use a ReadableStream that's locked or has ever been "
"read from or canceled as a Request or Response body.");
return false;
}
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 (builtins::TransformStream::is_ts_readable(cx, body_obj)) {
// But only if the TransformStream isn't used as a mixin by other
// builtins.
if (!builtins::TransformStream::used_as_mixin(
builtins::TransformStream::ts_from_readable(cx, body_obj))) {
builtins::TransformStream::set_readable_used_as_body(cx, body_obj, self);
}
}
} else {
mozilla::Maybe<JS::AutoCheckCannotGC> maybeNoGC;
JS::UniqueChars text;
char *buf;
size_t length;
if (body_obj && JS_IsArrayBufferViewObject(body_obj)) {
// Short typed arrays have inline data which can move on GC, so assert
// that no GC happens. (Which it doesn't, because we're not allocating
// before `buf` goes out of scope.)
maybeNoGC.emplace(cx);
JS::AutoCheckCannotGC &noGC = maybeNoGC.ref();
bool is_shared;
length = JS_GetArrayBufferViewByteLength(body_obj);
buf = (char *)JS_GetArrayBufferViewData(body_obj, &is_shared, noGC);
} else if (body_obj && JS::IsArrayBufferObject(body_obj)) {
bool is_shared;
JS::GetArrayBufferLengthAndData(body_obj, &length, &is_shared, (uint8_t **)&buf);
} else if (body_obj && builtins::URLSearchParams::is_instance(body_obj)) {
auto slice = builtins::URLSearchParams::serialize(cx, body_obj);
buf = (char *)slice.data;
length = slice.len;
content_type = "application/x-www-form-urlencoded;charset=UTF-8";
} else {
text = encode(cx, body_val, &length);
if (!text)
return false;
buf = text.get();
content_type = "text/plain;charset=UTF-8";
}
HttpBody body{RequestOrResponse::body_handle(self)};
auto write_res = body.write_all(reinterpret_cast<uint8_t *>(buf), length);
// Ensure that the NoGC is reset, so throwing an error in HANDLE_ERROR
// succeeds.
if (maybeNoGC.isSome()) {
maybeNoGC.reset();
}
if (auto *err = write_res.to_err()) {
HANDLE_ERROR(cx, *err);
return false;
}
}
// Step 36.3 of Request constructor / 8.4 of Response constructor.
if (content_type) {
JS::RootedObject headers(
cx, &JS::GetReservedSlot(self, static_cast<uint32_t>(Slots::Headers)).toObject());
if (!builtins::Headers::maybe_add(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();
}
bool RequestOrResponse::append_body(JSContext *cx, JS::HandleObject self, JS::HandleObject source) {
MOZ_ASSERT(!body_used(source));
HttpBody source_body{body_handle(source)};
HttpBody dest_body{body_handle(self)};
auto res = dest_body.append(source_body);
if (auto *err = res.to_err()) {
HANDLE_ERROR(cx, *err);
return false;
}
return true;
}
template <Headers::Mode mode>
JSObject *RequestOrResponse::headers(JSContext *cx, JS::HandleObject obj) {
JSObject *headers = maybe_headers(obj);
if (!headers) {
JS::RootedObject headersInstance(cx, JS_NewObjectWithGivenProto(cx, &builtins::Headers::class_,
builtins::Headers::proto_obj));
if (!headersInstance) {
return nullptr;
}
headers = builtins::Headers::create(cx, headersInstance, mode, obj);
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) {
auto *rawBuf = buf.release();
JS::RootedObject array_buffer(cx, JS::NewArrayBufferWithContents(cx, len, rawBuf));
if (!array_buffer) {
JS_free(cx, rawBuf);
return RejectPromiseWithPendingError(cx, result_promise);
}
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;
}
// TODO(performance): investigate whether we can infer the size directly from `contents`
size_t buf_size = HANDLE_READ_CHUNK_SIZE;
// TODO(performance): make use of malloc slack.
// https://github.com/fastly/js-compute-runtime/issues/217
size_t offset = 0;
// In this loop we are finding the length of each entry in `contents` and resizing the `buf`
// until it is large enough to fit all the entries in `contents`
for (uint32_t index = 0; index < contentsLength; index++) {
JS::RootedValue val(cx);
if (!JS_GetElement(cx, contents, index, &val)) {
return false;
}
{
JS::AutoCheckCannotGC nogc;
MOZ_ASSERT(val.isObject());
JSObject *array = &val.toObject();
MOZ_ASSERT(JS_IsUint8Array(array));
size_t length = JS_GetTypedArrayByteLength(array);
if (length) {
offset += length;
// if buf is not big enough to fit the next uint8array's bytes then resize
if (offset > buf_size) {
buf_size =
buf_size + (HANDLE_READ_CHUNK_SIZE * ((length / HANDLE_READ_CHUNK_SIZE) + 1));
}
}
}
}
auto buf = static_cast<char *>(JS_malloc(cx, buf_size + 1));
if (!buf) {
JS_ReportOutOfMemory(cx);
return false;
}
// reset the offset for the next loop
offset = 0;
// In this loop we are inserting each entry in `contents` into `buf`
for (uint32_t index = 0; index < contentsLength; index++) {
JS::RootedValue val(cx);
if (!JS_GetElement(cx, contents, index, &val)) {
JS_free(cx, buf);
return false;
}
{
JS::AutoCheckCannotGC nogc;
MOZ_ASSERT(val.isObject());
JSObject *array = &val.toObject();
MOZ_ASSERT(JS_IsUint8Array(array));
bool is_shared;
size_t length = JS_GetTypedArrayByteLength(array);
if (length) {
static_assert(CHAR_BIT == 8, "Strange char");
auto bytes = reinterpret_cast<char *>(JS_GetUint8ArrayData(array, &is_shared, nogc));
memcpy(buf + offset, bytes, length);
offset += length;
}
}
}
buf[offset] = '\0';
#ifdef DEBUG
bool foundBodyParser;
if (!JS_HasElement(cx, catch_handler, 2, &foundBodyParser)) {
JS_free(cx, buf);
return false;
}
MOZ_ASSERT(foundBodyParser);
#endif
// Now we can call parse_body on the result
JS::RootedValue body_parser(cx);
if (!JS_GetElement(cx, catch_handler, 2, &body_parser)) {
JS_free(cx, buf);
return false;
}
auto parse_body = (ParseBodyCB *)body_parser.toPrivate();
JS::UniqueChars body(buf);
return parse_body(cx, self, std::move(body), 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())) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_RESPONSE_VALUE_NOT_UINT8ARRAY);
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)) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_RESPONSE_BODY_DISTURBED_OR_LOCKED);
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);
}
bool RequestOrResponse::consume_body_handle_for_bodyAll(JSContext *cx, JS::HandleObject self,
JS::HandleValue body_parser,
JS::CallArgs args) {
fastly_body_handle_t body = body_handle(self);
auto *parse_body = reinterpret_cast<ParseBodyCB *>(body_parser.toPrivate());
auto [buf, bytes_read] = read_from_handle_all(cx, body);
if (!buf) {
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);
}
return parse_body(cx, self, std::move(buf), bytes_read);
}
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)) {
JS_ReportErrorASCII(cx, "Body has already been consumed");
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;
}
if (!mark_body_used(cx, self)) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
JS::RootedValue body_parser(cx, JS::PrivateValue((void *)parse_body<result_type>));
// If the body is a ReadableStream that's not backed by a fastly_body_handle_t,
// we need to manually read all chunks from the stream.
// TODO(performance): ensure that we're properly shortcutting reads from TransformStream
// readables.
// https://github.com/fastly/js-compute-runtime/issues/218
JS::RootedObject stream(cx, body_stream(self));
if (stream && !builtins::NativeStreamSource::stream_is_body(cx, stream)) {
if (!JS_SetElement(cx, stream, 1, body_parser)) {
return false;
}
JS::RootedValue extra(cx, JS::ObjectValue(*stream));
if (!enqueue_internal_method<consume_content_stream_for_bodyAll>(cx, self, extra)) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
} else {
if (!enqueue_internal_method<consume_body_handle_for_bodyAll>(cx, self, body_parser)) {
return ReturnPromiseRejectedWithPendingError(cx, args);
}
}
args.rval().setObject(*bodyAll_promise);
return true;
}
bool RequestOrResponse::body_source_pull_algorithm(JSContext *cx, JS::CallArgs args,
JS::HandleObject source,
JS::HandleObject body_owner,
JS::HandleObject controller) {
// 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.
JS::RootedObject pipe_dest(cx, builtins::NativeStreamSource::piped_to_transform_stream(source));
if (pipe_dest) {
if (builtins::TransformStream::readable_used_as_body(pipe_dest)) {
JS::RootedObject dest_owner(cx, builtins::TransformStream::owner(pipe_dest));
if (!RequestOrResponse::append_body(cx, dest_owner, body_owner)) {
return false;
}
JS::RootedObject stream(cx, builtins::NativeStreamSource::stream(source));
bool success = JS::ReadableStreamClose(cx, stream);
MOZ_RELEASE_ASSERT(success);
args.rval().setUndefined();
return true;
}
}
// The actual read from the body needs to be delayed, because it'd otherwise
// be a blocking operation in case the backend didn't yet send any data.
// That would lead to situations where we block on I/O before processing
// all pending Promises, which in turn can result in operations happening in
// observably different behavior, up to and including causing deadlocks
// because a body read response is blocked on content making another request.
//
// (This deadlock happens in automated tests, but admittedly might not happen
// in real usage.)
if (!pending_async_tasks->append(source))
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) {
args.rval().setUndefined();
return true;
}
bool RequestOrResponse::body_reader_then_handler(JSContext *cx, JS::HandleObject body_owner,
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.
JS::RootedObject catch_handler(cx, &extra.toObject());
JS::RootedObject reader(cx, &js::GetFunctionNativeReserved(catch_handler, 1).toObject());
HttpBody body{RequestOrResponse::body_handle(body_owner)};
// 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()) {
// The only response we ever send is the one passed to
// `FetchEvent#respondWith` to send to the client. As such, we can be
// certain that if we have a response here, we can advance the FetchState to
// `responseDone`.
if (Response::is_instance(body_owner)) {
FetchEvent::set_state(FetchEvent::instance(), FetchEvent::State::responseDone);
}
auto res = body.close();
if (auto *err = res.to_err()) {
HANDLE_ERROR(cx, *err);
return false;
}
if (Request::is_instance(body_owner)) {
if (!pending_async_tasks->append(body_owner)) {
return false;
}
}
return true;
}
JS::RootedValue val(cx);
if (!JS_GetProperty(cx, chunk_obj, "value", &val))
return false;
// The read operation returned something that's not a Uint8Array
if (!val.isObject() || !JS_IsUint8Array(&val.toObject())) {
// reject the request promise
if (Request::is_instance(body_owner)) {
JS::RootedObject response_promise(cx, Request::response_promise(body_owner));
JS::RootedValue exn(cx);
// TODO: this should be a TypeError, but I'm not sure how to make that work
JS_ReportErrorUTF8(cx, "TypeError");
if (!JS_GetPendingException(cx, &exn)) {
return false;
}
JS_ClearPendingException(cx);
return JS::RejectPromise(cx, response_promise, exn);
}
// TODO: should we also create a rejected promise if a response reads something that's not a
// Uint8Array?
fprintf(stderr, "Error: read operation on body ReadableStream didn't respond with a "
"Uint8Array. Received value: ");
dump_value(cx, val, stderr);
return false;
}
Result<Void> res;
{
JS::AutoCheckCannotGC nogc;
JSObject *array = &val.toObject();
bool is_shared;
uint8_t *bytes = JS_GetUint8ArrayData(array, &is_shared, nogc);
size_t length = JS_GetTypedArrayByteLength(array);
res = body.write_all(bytes, length);
}
// Needs to be outside the nogc block in case we need to create an exception.
if (auto *err = res.to_err()) {
HANDLE_ERROR(cx, *err);
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::body_reader_catch_handler(JSContext *cx, JS::HandleObject body_owner,
JS::HandleValue extra, JS::CallArgs args) {
// TODO: check if this should create a rejected promise instead, so an
// in-content handler for unhandled rejections could deal with it. The body
// stream errored during the streaming send. Not much we can do, but at least
// close the stream, and warn.
fprintf(stderr, "Warning: body ReadableStream closed during body streaming. Exception: ");
dump_value(cx, args.get(0), stderr);
// The only response we ever send is the one passed to
// `FetchEvent#respondWith` to send to the client. As such, we can be certain
// that if we have a response here, we can advance the FetchState to
// `responseDone`. (Note that even though we encountered an error,
// `responseDone` is the right state: `responsedWithError` is for when sending
// a response at all failed.)
if (Response::is_instance(body_owner)) {
FetchEvent::set_state(FetchEvent::instance(), FetchEvent::State::responseDone);
}
return true;
}
bool RequestOrResponse::maybe_stream_body(JSContext *cx, JS::HandleObject body_owner,
bool *requires_streaming) {
JS::RootedObject stream(cx, RequestOrResponse::body_stream(body_owner));
if (!stream) {
return true;
}
if (RequestOrResponse::body_unusable(cx, stream)) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_RESPONSE_BODY_DISTURBED_OR_LOCKED);
return false;
}
// If the body stream is backed by a C@E body handle, we can directly pipe
// that handle into the body we're about to send.
if (builtins::NativeStreamSource::stream_is_body(cx, stream)) {
// First, move the source's body handle to the target and lock the stream.
JS::RootedObject stream_source(cx, builtins::NativeStreamSource::get_stream_source(cx, stream));
JS::RootedObject source_owner(cx, builtins::NativeStreamSource::owner(stream_source));
if (!RequestOrResponse::move_body_handle(cx, source_owner, body_owner)) {
return false;
}
// Then, send the request/response without streaming. We know that content
// won't append to this body handle, because we don't expose any means to do
// so, so it's ok for it to be closed immediately.
return true;
}
JS::RootedObject reader(
cx, JS::ReadableStreamGetReader(cx, stream, JS::ReadableStreamReaderMode::Default));
if (!reader)
return false;
bool is_closed;
if (!JS::ReadableStreamReaderIsClosed(cx, reader, &is_closed))
return false;
// It's ok for the stream to be closed, as its contents might
// already have fully been written to the body handle.
// In that case, we can do a blocking send instead.
if (is_closed) {
return true;
}
// 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);
JS::RootedValue extra(cx, JS::ObjectValue(*reader));
catch_handler = create_internal_method<body_reader_catch_handler>(cx, body_owner, extra);