-
Notifications
You must be signed in to change notification settings - Fork 26
/
js-compute-builtins.cpp
3499 lines (2800 loc) · 109 KB
/
js-compute-builtins.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 <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include "../xqd.h"
#include "js-compute-builtins.h"
#include "js/ArrayBuffer.h"
#include "js/Conversions.h"
#include "js/experimental/TypedData.h"
#include "js/JSON.h"
#include "js/shadow/Object.h"
#include "js/Stream.h"
#include "js/Value.h"
using JS::CallArgs;
using JS::CallArgsFromVp;
using JS::UniqueChars;
using JS::Value;
using JS::RootedValue;
using JS::RootedObject;
using JS::RootedString;
using JS::HandleValue;
using JS::HandleValueArray;
using JS::HandleObject;
using JS::HandleString;
using JS::MutableHandleValue;
using JS::PersistentRooted;
// Ensure that all the things we want to use the hostcall buffer for actually fit into the buffer.
#define HOSTCALL_BUFFER_LEN DICTIONARY_ENTRY_MAX_LEN
static_assert(HEADER_MAX_LEN < HOSTCALL_BUFFER_LEN);
static_assert(METHOD_MAX_LEN < HOSTCALL_BUFFER_LEN);
static_assert(URI_MAX_LEN < HOSTCALL_BUFFER_LEN);
static bool response_sent;
class OwnedHostCallBuffer {
static char* hostcall_buffer;
char* borrowed_buffer;
public:
static bool initialize(JSContext* cx) {
// Ensure the buffer is all zeros so it doesn't add too much to the snapshot.
hostcall_buffer = (char*)js_calloc(HOSTCALL_BUFFER_LEN);
return !!hostcall_buffer;
}
OwnedHostCallBuffer() {
MOZ_RELEASE_ASSERT(hostcall_buffer != nullptr);
borrowed_buffer = hostcall_buffer;
hostcall_buffer = nullptr;
}
char* get() {
return borrowed_buffer;
}
~OwnedHostCallBuffer() {
// TODO: consider adding a build config that makes this zero the buffer.
hostcall_buffer = borrowed_buffer;
}
};
static JS::PersistentRootedObjectVector* pending_requests;
static JS::PersistentRootedObjectVector* pending_body_reads;
// TODO: introduce a version that writes into an existing buffer, and use that
// with the hostcall buffer where possible.
UniqueChars encode(JSContext* cx, HandleString str, size_t* encoded_len) {
UniqueChars text = JS_EncodeStringToUTF8(cx, str);
if (!text)
return nullptr;
// This shouldn't fail, since the encode operation ensured `str` is linear.
JSLinearString* linear = JS_EnsureLinearString(cx, str);
*encoded_len = JS::GetDeflatedUTF8StringLength(linear);
return text;
}
UniqueChars encode(JSContext* cx, HandleValue val, size_t* encoded_len) {
RootedString str(cx, JS::ToString(cx, val));
if (!str) return nullptr;
return encode(cx, str, encoded_len);
}
/* Returns false if an exception is set on `cx` and the caller should immediately
return to propagate the exception. */
static inline bool handle_fastly_result(JSContext* cx, int result, int line, const char* func) {
if (result == 0) {
return true;
} else {
fprintf(stdout, __FILE__":%d (%s) - Fastly error code %d\n", line, func, result);
JS_ReportErrorUTF8(cx, "Fastly error code %d", result);
return false;
}
}
#define HANDLE_RESULT(cx, result) \
handle_fastly_result(cx, result, __LINE__, __func__)
#define DBG(...) \
printf("%s#%d: ", __func__, __LINE__); printf(__VA_ARGS__); fflush(stdout);
static bool rejected_promise_with_current_exception(JSContext* cx, CallArgs* args = nullptr) {
RootedValue exn(cx);
if (!JS_GetPendingException(cx, &exn)) return false;
RootedObject promise(cx, JS::CallOriginalPromiseReject(cx, exn));
if (!promise) return false;
if (args) {
args->rval().setObject(*promise);
}
return true;
}
static bool resolved_promise_with_value(JSContext* cx, JS::HandleValue value,
CallArgs* args = nullptr)
{
RootedObject promise(cx, JS::CallOriginalPromiseResolve(cx, value));
if (!promise) return false;
if (args) {
args->rval().setObject(*promise);
}
return true;
}
#define HANDLE_READ_CHUNK_SIZE 1024
template<auto op, class HandleType>
static char* read_from_handle_all(JSContext* cx, HandleType handle,
size_t* nwritten, bool read_until_zero)
{
// TODO: investigate passing a size hint in situations where we might know
// the final size, e.g. via the `content-length` header.
size_t buf_size = HANDLE_READ_CHUNK_SIZE;
// TODO: make use of malloc slack.
char* buf = static_cast<char*>(JS_malloc(cx, buf_size));
if (!buf) {
return nullptr;
}
// For realloc below.
char* new_buf;
size_t offset = 0;
while (true) {
size_t num_written = 0;
int result = op(handle, buf + offset, HANDLE_READ_CHUNK_SIZE, &num_written);
if (!HANDLE_RESULT(cx, result)) {
JS_free(cx, buf);
return nullptr;
}
offset += num_written;
if (num_written == 0 ||
(!read_until_zero && num_written < HANDLE_READ_CHUNK_SIZE))
{
break;
}
// TODO: make use of malloc slack, and use a smarter buffer growth strategy.
size_t new_size = buf_size + HANDLE_READ_CHUNK_SIZE;
new_buf = static_cast<char*>(JS_realloc(cx, buf, buf_size, new_size));
if (!new_buf) {
JS_free(cx, buf);
return nullptr;
}
buf = new_buf;
buf_size += HANDLE_READ_CHUNK_SIZE;
}
new_buf = static_cast<char*>(JS_realloc(cx, buf, buf_size, offset + 1));
if (!buf) {
JS_free(cx, buf);
return nullptr;
}
buf = new_buf;
buf[offset] = '\0';
*nwritten = offset;
return buf;
}
#define MULTI_VALUE_HOSTCALL(op, accum) \
uint32_t cursor = 0; \
int64_t ending_cursor = 0; \
size_t nwritten; \
\
while (true) { \
op \
\
if (nwritten == 0) { \
break; \
} \
\
accum \
\
if (ending_cursor < 0) { \
break; \
} \
\
cursor = (uint32_t)ending_cursor; \
}
static constexpr const JSClassOps class_ops = {};
static const uint32_t class_flags = 0;
#define CLASS_BOILERPLATE_CUSTOM_INIT(cls) \
const JSClass class_ = { #cls, JSCLASS_HAS_RESERVED_SLOTS(Slots::Count) | class_flags, \
&class_ops }; \
static PersistentRooted<JSObject*> proto_obj; \
\
bool is_instance(JSObject* obj) { \
return JS::GetClass(obj) == &class_; \
} \
\
bool is_instance(JS::Value val) { \
return val.isObject() && is_instance(&val.toObject()); \
} \
\
bool check_receiver(JSContext* cx, HandleObject self, const char* method_name) { \
if (!is_instance(self)) { \
JS_ReportErrorUTF8(cx, "Method %s called on receiver that's not an instance of %s\n", \
method_name, class_.name); \
return false; \
} \
return true; \
}; \
\
bool init_class_impl(JSContext* cx, HandleObject global, \
HandleObject parent_proto = nullptr) \
{ \
proto_obj.init(cx, JS_InitClass(cx, global, parent_proto, &class_, constructor, ctor_length, \
properties, methods, nullptr, nullptr)); \
return proto_obj; \
}; \
#define CLASS_BOILERPLATE(cls) \
CLASS_BOILERPLATE_CUSTOM_INIT(cls) \
\
bool init_class(JSContext* cx, HandleObject global) { \
return init_class_impl(cx, global); \
} \
#define CLASS_BOILERPLATE_NO_CTOR(cls) \
bool constructor(JSContext* cx, unsigned argc, Value* vp) { \
JS_ReportErrorUTF8(cx, #cls " can't be instantiated directly"); \
return false; \
} \
\
CLASS_BOILERPLATE_CUSTOM_INIT(cls) \
\
bool init_class(JSContext* cx, HandleObject global) { \
/* Right now, deleting the ctor from the global object after class \
initialization seems to be the best we can do. Not ideal, but works. */ \
return init_class_impl(cx, global) && \
JS_DeleteProperty(cx, global, class_.name); \
} \
#define METHOD_HEADER(required_argc) \
/* \
// printf("method: %s\n", __func__); \
*/ \
CallArgs args = CallArgsFromVp(argc, vp); \
if (!args.requireAtLeast(cx, __func__, required_argc)) \
return false; \
RootedObject self(cx, &args.thisv().toObject()); \
if (!check_receiver(cx, self, __func__)) return false; \
namespace Logger {
namespace Slots { enum {
Endpoint,
Count
};};
const unsigned ctor_length = 1;
bool check_receiver(JSContext* cx, HandleObject self, const char* method_name);
static bool log(JSContext* cx, unsigned argc, Value* vp) {
METHOD_HEADER(1)
auto endpoint = LogEndpointHandle { (uint32_t)JS::GetReservedSlot(self, Slots::Endpoint).toInt32() };
size_t msg_len;
UniqueChars msg = encode(cx, args.get(0), &msg_len);
if (!msg) return false;
size_t nwritten;
if (!HANDLE_RESULT(cx, xqd_log_write(endpoint, msg.get(), msg_len, &nwritten)))
return false;
args.rval().setUndefined();
return true;
}
const JSFunctionSpec methods[] = {
JS_FN("log", log, 1, JSPROP_ENUMERATE),
JS_FS_END
};
const JSPropertySpec properties[] = {JS_PS_END};
CLASS_BOILERPLATE_NO_CTOR(Logger)
JSObject* create(JSContext* cx, const char* name) {
RootedObject logger(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj));
if (!logger) return nullptr;
auto handle = LogEndpointHandle { INVALID_HANDLE };
if (!HANDLE_RESULT(cx, xqd_log_endpoint_get(name, strlen(name), &handle)))
return nullptr;
JS::SetReservedSlot(logger, Slots::Endpoint, JS::Int32Value(handle.handle));
return logger;
}
}
static JSString* get_geo_info(JSContext* cx, HandleString address_str);
namespace Fastly {
static bool debug_logging_enabled = false;
bool dump(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!args.requireAtLeast(cx, __func__, 1))
return false;
dump_value(cx, args[0], stdout);
args.rval().setUndefined();
return true;
}
bool enableDebugLogging(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!args.requireAtLeast(cx, __func__, 1))
return false;
debug_logging_enabled = JS::ToBoolean(args[0]);
args.rval().setUndefined();
return true;
}
bool getGeolocationForIpAddress(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!args.requireAtLeast(cx, __func__, 1))
return false;
RootedString address_str(cx, JS::ToString(cx, args[0]));
if (!address_str)
return false;
RootedString geo_info_str(cx, get_geo_info(cx, address_str));
if (!geo_info_str) return false;
return JS_ParseJSON(cx, geo_info_str, args.rval());
}
// TODO: throw a proper error when trying to create a logger during the init phase.
// Alternatively, allow doing so to reduce per-request work, but then throw when trying
// to log.
bool getLogger(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
RootedObject self(cx, &args.thisv().toObject());
if (!args.requireAtLeast(cx, "fastly.getLogger", 1))
return false;
size_t name_len;
UniqueChars name = encode(cx, args[0], &name_len);
if (!name) return false;
RootedObject logger(cx, Logger::create(cx, name.get()));
if (!logger) return false;
args.rval().setObject(*logger);
return true;
}
const JSFunctionSpec methods[] = {
JS_FN("dump", dump, 1, 0),
JS_FN("enableDebugLogging", enableDebugLogging, 1, JSPROP_ENUMERATE),
JS_FN("getGeolocationForIpAddress", getGeolocationForIpAddress, 1, JSPROP_ENUMERATE),
JS_FN("getLogger", getLogger, 1, JSPROP_ENUMERATE),
JS_FS_END
};
static bool create(JSContext* cx, HandleObject global) {
RootedObject fastly(cx, JS_NewPlainObject(cx));
if (!fastly) return false;
if (!JS_DefineProperty(cx, global, "fastly", fastly, 0)) return false;
return JS_DefineFunctions(cx, fastly, methods);
}
}
namespace Console {
template<const char* prefix, uint8_t prefix_len>
static bool console_out(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
size_t msg_len;
UniqueChars msg = encode(cx, args.get(0), &msg_len);
if (!msg) return false;
printf("%s: %s\n", prefix, msg.get());
fflush(stdout);
args.rval().setUndefined();
return true;
}
static constexpr char PREFIX_LOG[] = "Log";
static constexpr char PREFIX_TRACE[] = "Trace";
static constexpr char PREFIX_INFO[] = "Info";
static constexpr char PREFIX_WARN[] = "Warn";
static constexpr char PREFIX_ERROR[] = "Error";
const JSFunctionSpec methods[] = {
JS_FN("log", (console_out<PREFIX_LOG, 3>), 1, JSPROP_ENUMERATE),
JS_FN("trace", (console_out<PREFIX_TRACE, 5>), 1, JSPROP_ENUMERATE),
JS_FN("info", (console_out<PREFIX_INFO, 4>), 1, JSPROP_ENUMERATE),
JS_FN("warn", (console_out<PREFIX_WARN, 4>), 1, JSPROP_ENUMERATE),
JS_FN("error", (console_out<PREFIX_ERROR, 5>), 1, JSPROP_ENUMERATE),
JS_FS_END
};
static bool create(JSContext* cx, HandleObject global) {
RootedObject console(cx, JS_NewPlainObject(cx));
if (!console) return false;
if (!JS_DefineProperty(cx, global, "console", console, JSPROP_ENUMERATE)) return false;
return JS_DefineFunctions(cx, console, methods);
}
}
bool is_int_typed_array(JSObject* obj) {
return JS_IsInt8Array(obj) ||
JS_IsUint8Array(obj) ||
JS_IsInt16Array(obj) ||
JS_IsUint16Array(obj) ||
JS_IsInt32Array(obj) ||
JS_IsUint32Array(obj) ||
JS_IsUint8ClampedArray(obj);
}
namespace Crypto {
#define MAX_BYTE_LENGTH 65536
/**
* Implementation of https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues
* TODO: investigate ways to automatically wipe the buffer passed in here when it is
* GC'd. Content can roughly approximate that using finalizers for views of the buffer,
* but it's far from ideal.
*/
bool get_random_values(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!args.requireAtLeast(cx, "crypto.getRandomValues", 1))
return false;
if (!args[0].isObject() || !is_int_typed_array(&args[0].toObject())) {
JS_ReportErrorUTF8(cx, "crypto.getRandomValues: input must be an integer-typed TypedArray");
return false;
}
RootedObject typed_array(cx, &args[0].toObject());
size_t byte_length = JS_GetArrayBufferViewByteLength(typed_array);
if (byte_length > MAX_BYTE_LENGTH) {
JS_ReportErrorUTF8(cx, "crypto.getRandomValues: input byteLength must be at most %u, "
"but is %zu", MAX_BYTE_LENGTH, byte_length);
return false;
}
JS::AutoAssertNoGC noGC(cx);
bool is_shared;
void* buffer = JS_GetArrayBufferViewData(typed_array, &is_shared, noGC);
arc4random_buf(buffer, byte_length);
args.rval().setObject(*typed_array);
return true;
}
const JSFunctionSpec methods[] = {
JS_FN("getRandomValues", get_random_values, 1, JSPROP_ENUMERATE),
JS_FS_END
};
static bool create(JSContext* cx, HandleObject global) {
RootedObject crypto(cx, JS_NewPlainObject(cx));
if (!crypto) return false;
if (!JS_DefineProperty(cx, global, "crypto", crypto, JSPROP_ENUMERATE)) return false;
return JS_DefineFunctions(cx, crypto, methods);
}
}
namespace BodyStreamSource {
JSObject* create(JSContext* cx, HandleObject owner);
static JSObject* get_stream_source(JSObject* stream);
bool stream_has_native_source(JSObject* stream);
bool lock_stream(JSContext* cx, HandleObject stream);
}
enum class BodyReadResult {
ArrayBuffer,
JSON,
Text,
};
namespace Headers {
enum class Mode : int32_t {
Standalone,
ProxyToRequest,
ProxyToResponse
};
JSObject* create(JSContext* cx, Mode mode, HandleObject owner);
JSObject* create(JSContext* cx, Mode mode, HandleObject owner, HandleValue initv);
bool delazify(JSContext* cx, HandleObject headers);
}
namespace Request {
bool is_instance(JSObject* obj);
}
namespace Response {
bool is_instance(JSObject* obj);
}
namespace RequestOrResponse {
namespace Slots { enum {
RequestOrResponse,
Body,
BodyStream,
HasBody,
BodyUsed,
Headers,
URL,
Count
};};
bool is_instance(JSObject* obj) {
return Request::is_instance(obj) || Response::is_instance(obj);
}
uint32_t handle(JSObject* obj) {
return static_cast<uint32_t>(JS::GetReservedSlot(obj, Slots::RequestOrResponse).toInt32());
}
bool has_body(JSObject* obj) {
return JS::GetReservedSlot(obj, Slots::HasBody).toBoolean();
}
BodyHandle body_handle(JSObject* obj) {
return BodyHandle { static_cast<uint32_t>(JS::GetReservedSlot(obj, Slots::Body).toInt32()) };
}
JSObject* body_stream(JSObject* obj) {
// Can't use toObjectOrNull here because the Value might be `undefined`.
Value val = JS::GetReservedSlot(obj, Slots::BodyStream);
return val.isNullOrUndefined() ? nullptr : &val.toObject();
}
JSObject* body_source(JSObject* obj) {
MOZ_RELEASE_ASSERT(has_body(obj));
return BodyStreamSource::get_stream_source(body_stream(obj));
}
bool mark_body_used(JSContext* cx, HandleObject obj) {
JS::SetReservedSlot(obj, Slots::BodyUsed, JS::BooleanValue(true));
RootedObject stream(cx, body_stream(obj));
if (stream)
return BodyStreamSource::lock_stream(cx, stream);
return true;
}
/**
* Moves an underlying body handle from one Request/Response object to another.
*
* Also marks the source object's body as consumed.
*/
bool move_body_handle(JSContext* cx, HandleObject from, HandleObject to) {
MOZ_RELEASE_ASSERT(is_instance(from));
MOZ_RELEASE_ASSERT(is_instance(to));
// 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.
BodyHandle body = body_handle(from);
JS::SetReservedSlot(to, Slots::Body, JS::Int32Value(body.handle));
// 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);
}
Value url(JSObject* obj) {
Value val = JS::GetReservedSlot(obj, Slots::URL);
MOZ_RELEASE_ASSERT(val.isString());
return val;
}
void set_url(JSObject* obj, Value url) {
MOZ_RELEASE_ASSERT(url.isString());
JS::SetReservedSlot(obj, Slots::URL, url);
}
bool body_used(JSObject* obj) {
return JS::GetReservedSlot(obj, Slots::BodyUsed).toBoolean();
}
bool set_body(JSContext*cx, HandleObject obj, HandleValue body_val) {
if (body_val.isNullOrUndefined()) {
JS::SetReservedSlot(obj, Slots::HasBody, JS::BooleanValue(false));
return true;
}
// TODO: throw if method is GET or HEAD.
// TODO: properly implement the spec steps for extracting the body and setting the content-type.
// (https://fetch.spec.whatwg.org/#dom-response)
if (body_val.isObject() && JS::IsReadableStream(&body_val.toObject())) {
JS_SetReservedSlot(obj, RequestOrResponse::Slots::BodyStream, body_val);
} else {
// TODO: Support BufferSource and the other possible inputs to Body.
BodyHandle body_handle = RequestOrResponse::body_handle(obj);
size_t utf8Length;
UniqueChars text = encode(cx, body_val, &utf8Length);
if (!text) return false;
size_t num_written = 0;
int result = xqd_body_write(body_handle, text.get(), utf8Length, BodyWriteEndBack,
&num_written);
if (!HANDLE_RESULT(cx, result))
return false;
}
JS::SetReservedSlot(obj, Slots::HasBody, JS::BooleanValue(true));
return true;
}
template<auto mode>
JSObject* headers(JSContext*cx, HandleObject obj) {
Value val = JS::GetReservedSlot(obj, Slots::Headers);
if (val.isNullOrUndefined()) {
JSObject* headers = Headers::create(cx, mode, obj);
if (!headers) return nullptr;
val = JS::ObjectValue(*headers);
JS_SetReservedSlot(obj, Slots::Headers, val);
}
return &val.toObject();
}
template<BodyReadResult result_type>
bool bodyAll(JSContext* cx, CallArgs args, 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 rejected_promise_with_current_exception(cx, &args);
}
BodyHandle body = body_handle(self);
// TODO: check if this should be lazified. JS code might expect to be able to trigger
// multiple requests for response body contents in parallel instead of blocking
// on them sequentially.
size_t bytes_read;
UniqueChars buf(read_from_handle_all<xqd_body_read, BodyHandle>(cx, body, &bytes_read, true));
if (!buf) {
return rejected_promise_with_current_exception(cx, &args);
}
if (!mark_body_used(cx, self))
return false;
RootedValue result(cx);
if (result_type == BodyReadResult::ArrayBuffer) {
auto* rawBuf = buf.release();
RootedObject array_buffer(cx, JS::NewArrayBufferWithContents(cx, bytes_read, rawBuf));
if (!array_buffer) {
JS_free(cx, rawBuf);
return rejected_promise_with_current_exception(cx, &args);
}
result.setObject(*array_buffer);
} else {
RootedString text(cx, JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(buf.get(), bytes_read)));
if (!text) {
return rejected_promise_with_current_exception(cx, &args);
}
if (result_type == BodyReadResult::Text) {
result.setString(text);
} else if (result_type == BodyReadResult::JSON) {
if (!JS_ParseJSON(cx, text, &result)) {
return rejected_promise_with_current_exception(cx, &args);
}
} else {
MOZ_ASSERT_UNREACHABLE("Unsupported body read result type");
}
}
return resolved_promise_with_value(cx, result, &args);
}
JSObject* create_body_stream(JSContext* cx, HandleObject owner) {
RootedObject source(cx, BodyStreamSource::create(cx, owner));
if (!source) return nullptr;
// Create a readable stream with a highwater mark of 0.0 to prevent an eager pull.
// With the default HWM of 1.0, the streams implementation causes a pull, which means
// we enqueue a read from the host handle, which we quite often have no interest in
// at all.
RootedObject body_stream(cx, JS::NewReadableDefaultStreamObject(cx, source, nullptr, 0.0));
if (!body_stream) return nullptr;
// This assert guarantees that we fail early in case SpiderMonkey ever changes how
// the underlying source for streams is stored, instead of operating on invalid
// values.
MOZ_RELEASE_ASSERT(BodyStreamSource::get_stream_source(body_stream) == source);
JS_SetReservedSlot(owner, RequestOrResponse::Slots::BodyStream, JS::ObjectValue(*body_stream));
return body_stream;
}
bool body_get(JSContext* cx, CallArgs args, HandleObject self, bool create_if_undefined) {
if (!has_body(self)) {
args.rval().setNull();
return true;
}
RootedObject body_stream(cx, ::RequestOrResponse::body_stream(self));
if (!body_stream && create_if_undefined) {
body_stream = create_body_stream(cx, self);
if (!body_stream) return false;
}
if (body_stream) {
args.rval().setObject(*body_stream);
}
return true;
}
}
static JS::Value get_fixed_slot(JSObject* obj, size_t slot) {
const auto* nobj = reinterpret_cast<const JS::shadow::Object*>(obj);
return nobj->fixedSlots()[slot];
}
// A JS class to use as the underlying source for native body streams.
// In principle, SpiderMonkey has the concept of a native ReadableStreamUnderlyingSource
// for just that, but in practice making that work turned out to be extremely difficult,
// because it involves GC tracing through a non-GC object (because our underlying source
// needs access to the Request/Response object), which is ... non-trivial.
//
// This is a bit unfortunate, because SpiderMonkey doesn't provide an embedding API for
// retrieving a JS object as the underlying source, so we have to resort to retrieving
// it from a fixed slot directly, which isn't API exposed and could change.
// To ensure we don't accidentally do unsafe things, we use various release asserts
// verifying that we operate on the objects we expect. SpiderMonkey might change how
// it stores the source, but at least we'd fail early.
namespace BodyStreamSource {
namespace Slots { enum {
Owner, // Request or Response object.
Controller, // The ReadableStreamDefaultController.
InternalReader, // Only used to lock the stream if it's consumed internally.
Count
};};
bool is_instance(JSObject* obj);
// Fixed slot SpiderMonkey stores the controller in on ReadableStream objects.
#define STREAM_SLOT_CONTROLLER 1
// Fixed slot SpiderMonkey stores the underlying source in on ReadableStream
// controller objects.
#define CONTROLLER_SLOT_SOURCE 3
JSObject* owner(JSObject* self) {
return &JS::GetReservedSlot(self, Slots::Owner).toObject();
}
JSObject* controller(JSObject* self) {
return &JS::GetReservedSlot(self, Slots::Controller).toObject();
}
static JSObject* get_controller_source(JSObject* controller) {
return &get_fixed_slot(controller, CONTROLLER_SLOT_SOURCE).toObject();
}
static JSObject* get_stream_source(JSObject* stream) {
JSObject* controller = &get_fixed_slot(stream, STREAM_SLOT_CONTROLLER).toObject();
return get_controller_source(controller);
}
bool stream_has_native_source(JSObject* stream) {
MOZ_RELEASE_ASSERT(JS::IsReadableStream(stream));
JSObject* source = get_stream_source(stream);
return is_instance(source);
}
bool lock_stream(JSContext* cx, HandleObject stream) {
MOZ_RELEASE_ASSERT(JS::IsReadableStream(stream));
bool locked;
JS::ReadableStreamIsLocked(cx, stream, &locked);
MOZ_RELEASE_ASSERT(!locked);
RootedObject self(cx, get_stream_source(stream));
MOZ_RELEASE_ASSERT(is_instance(self));
auto mode = JS::ReadableStreamReaderMode::Default;
RootedObject reader(cx, JS::ReadableStreamGetReader(cx, stream, mode));
if (!reader)
return false;
JS::SetReservedSlot(self, Slots::InternalReader, JS::ObjectValue(*reader));
return true;
}
const unsigned ctor_length = 0;
bool start(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
RootedObject self(cx, &args.thisv().toObject());
MOZ_RELEASE_ASSERT(args[0].isObject());
RootedObject controller(cx, &args[0].toObject());
MOZ_RELEASE_ASSERT(get_controller_source(controller) == self);
JS::SetReservedSlot(self, Slots::Controller, args[0]);
args.rval().setUndefined();
return true;
}
bool pull(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
RootedObject self(cx, &args.thisv().toObject());
RootedObject controller(cx, &args[0].toObject());
MOZ_RELEASE_ASSERT(controller == BodyStreamSource::controller(self));
MOZ_RELEASE_ASSERT(get_controller_source(controller) == self.get());
// 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_body_reads->append(self))
return false;
args.rval().setUndefined();
return true;
}
const JSFunctionSpec methods[] = {
JS_FN("start", start, 1, 0),
JS_FN("pull", pull, 1, 0),
JS_FS_END};
const JSPropertySpec properties[] = {JS_PS_END};
CLASS_BOILERPLATE_NO_CTOR(BodyStreamSource)
JSObject* create(JSContext* cx, HandleObject owner) {
RootedObject source(cx, JS_NewObjectWithGivenProto(cx, &class_, proto_obj));
if (!source) return nullptr;
JS::SetReservedSlot(source, Slots::Owner, JS::ObjectValue(*owner));
return source;
}
}
namespace CacheOverride {
// The values stored in these slots are ultimately passed to the host
// via the xqd_req_cache_override_v2_set hostcall.
//
// If `Mode` is not `Override`, all other values are ignored.
//
// If `Mode` is `Override`, the values are interpreted in the following way:
//
// If `TTL`, `SWR`, or `SurrogateKey` are `undefined`, they're ignored.
// For each of them, if the value isn't `undefined`, a flag gets set in the
// hostcall's `tag` parameter, and the value itself is encoded as a uint32
// parameter.
//
// `PCI` is interpreted as a boolean, and a flag gets set in the hostcall's
// `tag` parameter if `PCI` is true.
namespace Slots { enum {
Mode,
TTL,
SWR,
SurrogateKey,
PCI,
Count
};};
enum class Mode {
None,
Pass,
Override
};
// These values are defined by the Fastly ABI:
// https://docs.rs/fastly-shared/0.6.1/src/fastly_shared/lib.rs.html#407-412
enum class CacheOverrideTag {
None = 0,
Pass = 1 << 0,
TTL = 1 << 1,
SWR = 1 << 2,
PCI = 1 << 3,
};
Mode mode(JSObject* self) {
return (Mode)JS::GetReservedSlot(self, Slots::Mode).toInt32();
}
void set_mode(JSObject* self, Mode mode) {
JS::SetReservedSlot(self, Slots::Mode, JS::Int32Value((int32_t)mode));
}
JS::Value ttl(JSObject* self) {
if (mode(self) != Mode::Override)
return JS::UndefinedValue();
return JS::GetReservedSlot(self, Slots::TTL);
}
void set_ttl(JSObject* self, uint32_t ttl) {
MOZ_RELEASE_ASSERT(mode(self) == Mode::Override);
JS::SetReservedSlot(self, Slots::TTL, JS::Int32Value((int32_t)ttl));
}
JS::Value swr(JSObject* self) {
if (mode(self) != Mode::Override)
return JS::UndefinedValue();
return JS::GetReservedSlot(self, Slots::SWR);
}
void set_swr(JSObject* self, uint32_t swr) {
MOZ_RELEASE_ASSERT(mode(self) == Mode::Override);
JS::SetReservedSlot(self, Slots::SWR, JS::Int32Value((int32_t)swr));
}
JS::Value surrogate_key(JSObject* self) {
if (mode(self) != Mode::Override)
return JS::UndefinedValue();
return JS::GetReservedSlot(self, Slots::SurrogateKey);
}
void set_surrogate_key(JSObject* self, JSString* key) {
MOZ_RELEASE_ASSERT(mode(self) == Mode::Override);
JS::SetReservedSlot(self, Slots::SurrogateKey, JS::StringValue(key));
}
JS::Value pci(JSObject* self) {
if (mode(self) != Mode::Override)
return JS::UndefinedValue();
return JS::GetReservedSlot(self, Slots::PCI);
}
void set_pci(JSObject* self, bool pci) {
MOZ_RELEASE_ASSERT(mode(self) == Mode::Override);
JS::SetReservedSlot(self, Slots::PCI, JS::BooleanValue(pci));
}
uint32_t abi_tag(JSObject* self) {
switch (mode(self)) {
case Mode::None: return (uint32_t)CacheOverrideTag::None;
case Mode::Pass: return (uint32_t)CacheOverrideTag::Pass;
default:;
}
uint32_t tag = 0;
if (!ttl(self).isUndefined())
tag |= (uint32_t)CacheOverrideTag::TTL;
if (!swr(self).isUndefined())