/
js-compute-builtins.cpp
7314 lines (5967 loc) · 245 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 <strings.h>
#include <arpa/inet.h>
#include "../xqd.h"
#include "js-compute-builtins.h"
#include "rust-url/rust-url.h"
#include "js/Array.h"
#include "js/ArrayBuffer.h"
#include "js/Conversions.h"
// TODO: remove these once the warnings are fixed
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#include "js/experimental/TypedData.h"
#pragma clang diagnostic pop
#include "js/friend/DumpFunctions.h"
#include "js/JSON.h"
#include "js/shadow/Object.h"
#include "js/Stream.h"
#include "js/experimental/TypedData.h"
#include "js/StructuredClone.h"
#include "js/Value.h"
using JS::CallArgs;
using JS::CallArgsFromVp;
using JS::UniqueChars;
using JS::Value;
using JS::ObjectValue;
using JS::ObjectOrNullValue;
using JS::PrivateValue;
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;
typedef bool InternalMethod(JSContext* cx, HandleObject receiver, HandleValue extra,
CallArgs args);
template<InternalMethod fun>
bool internal_method(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
RootedObject self(cx, &js::GetFunctionNativeReserved(&args.callee(), 0).toObject());
RootedValue extra(cx, js::GetFunctionNativeReserved(&args.callee(), 1));
return fun(cx, self, extra, args);
}
template<InternalMethod fun>
JSObject* create_internal_method(JSContext* cx, HandleObject receiver,
HandleValue extra = JS::UndefinedHandleValue,
unsigned int nargs = 0, const char* name = "")
{
JSFunction* method = js::NewFunctionWithReserved(cx, internal_method<fun>, 1, 0, name);
if (!method) return nullptr;
RootedObject method_obj(cx, JS_GetFunctionObject(method));
js::SetFunctionNativeReserved(method_obj, 0, JS::ObjectValue(*receiver));
js::SetFunctionNativeReserved(method_obj, 1, extra);
return method_obj;
}
template<InternalMethod fun>
bool enqueue_internal_method(JSContext* cx, HandleObject receiver,
HandleValue extra = JS::UndefinedHandleValue,
unsigned int nargs = 0, const char* name = "")
{
RootedObject method(cx, create_internal_method<fun>(cx, receiver, extra, nargs, name));
if (!method) {
return false;
}
RootedObject promise(cx, JS::CallOriginalPromiseResolve(cx, JS::UndefinedHandleValue));
if (!promise) {
return false;
}
return JS::AddPromiseReactions(cx, promise, method, nullptr);
}
// Ensure that all the things we want to use the hostcall buffer for actually fit into the buffer.
#define HOSTCALL_BUFFER_LEN HEADER_MAX_LEN
static_assert(DICTIONARY_ENTRY_MAX_LEN < HOSTCALL_BUFFER_LEN);
static_assert(METHOD_MAX_LEN < HOSTCALL_BUFFER_LEN);
static_assert(URI_MAX_LEN < HOSTCALL_BUFFER_LEN);
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;
}
};
char* OwnedHostCallBuffer::hostcall_buffer;
using jsurl::SpecSlice, jsurl::SpecString, jsurl::JSUrl, jsurl::JSUrlSearchParams, jsurl::JSSearchParam;
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);
}
SpecString encode(JSContext* cx, HandleValue val) {
SpecString slice(nullptr, 0, 0);
auto chars = encode(cx, val, &slice.len);
if (!chars) return slice;
slice.data = (uint8_t*)chars.release();
slice.cap = slice.len;
return slice;
}
/* 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) {
switch(result)
{
case 0:
return true;
case 1:
JS_ReportErrorUTF8(cx, "%s: Generic error value. This means that some unexpected error occurred during a hostcall. - Fastly error code %d\n", func, result);
return false;
case 2:
JS_ReportErrorUTF8(cx, "%s: Invalid argument. - Fastly error code %d\n", func, result);
return false;
case 3:
JS_ReportErrorUTF8(cx, "%s: Invalid handle. Thrown when a request, response, dictionary, or body handle is not valid. - Fastly error code %d\n", func, result);
return false;
case 4:
JS_ReportErrorUTF8(cx, "%s: Buffer length error. Buffer is too long. - Fastly error code %d\n", func, result);
return false;
case 5:
JS_ReportErrorUTF8(cx, "%s: Unsupported operation error. This error is thrown when some operation cannot be performed, because it is not supported. - Fastly error code %d\n", func, result);
return false;
case 6:
JS_ReportErrorUTF8(cx, "%s: Alignment error. This is thrown when a pointer does not point to a properly aligned slice of memory. - Fastly error code %d\n", func, result);
return false;
case 7:
JS_ReportErrorUTF8(cx, "%s: HTTP parse error. This can be thrown when a method, URI, header, or status is not valid. This can also be thrown if a message head is too large. - Fastly error code %d\n", func, result);
return false;
case 8:
JS_ReportErrorUTF8(cx, "%s: HTTP user error. This is thrown in cases where user code caused an HTTP error. For example, attempt to send a 1xx response code, or a request with a non-absolute URI. This can also be caused by an unexpected header: both `content-length` and `transfer-encoding`, for example. - Fastly error code %d\n", func, result);
return false;
case 9:
JS_ReportErrorUTF8(cx, "%s: HTTP incomplete message error. A stream ended unexpectedly. - Fastly error code %d\n", func, result);
return false;
case 10:
JS_ReportErrorUTF8(cx, "%s: A `None` error. This status code is used to indicate when an optional value did not exist, as opposed to an empty value. - Fastly error code %d\n", func, result);
return false;
case 11:
JS_ReportErrorUTF8(cx, "%s: HTTP head too large error. This error will be thrown when the message head is too large. - Fastly error code %d\n", func, result);
return false;
case 12:
JS_ReportErrorUTF8(cx, "%s: HTTP invalid status error. This error will be thrown when the HTTP message contains an invalid status code. - Fastly error code %d\n", func, result);
return false;
default:
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);
bool RejectPromiseWithPendingError(JSContext* cx, HandleObject promise) {
RootedValue exn(cx);
if (!JS_IsExceptionPending(cx) || !JS_GetPendingException(cx, &exn)) {
return false;
}
JS_ClearPendingException(cx);
return JS::RejectPromise(cx, promise, exn);
}
JSObject* PromiseRejectedWithPendingError(JSContext* cx) {
RootedObject promise(cx, JS::NewPromiseObject(cx, nullptr));
if (!promise || !RejectPromiseWithPendingError(cx, promise)) {
return nullptr;
}
return promise;
}
inline bool ReturnPromiseRejectedWithPendingError(JSContext* cx, const JS::CallArgs& args) {
JSObject* promise = PromiseRejectedWithPendingError(cx);
if (!promise) {
return false;
}
args.rval().setObject(*promise);
return true;
}
#define HANDLE_READ_CHUNK_SIZE 8192
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) {
JS_ReportOutOfMemory(cx);
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);
JS_ReportOutOfMemory(cx);
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);
JS_ReportOutOfMemory(cx);
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 !!obj && JS::GetClass(obj) == &class_; \
} \
\
bool is_instance(JS::Value val) { \
return val.isObject() && is_instance(&val.toObject()); \
} \
\
bool check_receiver(JSContext* cx, HandleValue receiver, const char* method_name) { \
if (!is_instance(receiver)) { \
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 this to make most methods print their name to stderr when invoked.
// #define TRACE_METHOD_CALLS
#ifdef TRACE_METHOD_CALLS
#define TRACE_METHOD(name) \
DBG("%s\n", name)
#else
#define TRACE_METHOD(name)
#endif
#define METHOD_HEADER_WITH_NAME(required_argc, name) \
TRACE_METHOD(name) \
CallArgs args = CallArgsFromVp(argc, vp); \
if (!check_receiver(cx, args.thisv(), name)) return false; \
RootedObject self(cx, &args.thisv().toObject()); \
if (!args.requireAtLeast(cx, name, required_argc)) \
return false; \
#define METHOD_HEADER(required_argc) \
METHOD_HEADER_WITH_NAME(required_argc, __func__)
#define REQUEST_HANDLER_ONLY(name) \
if (!FetchEvent::instance()) { \
JS_ReportErrorUTF8(cx, "%s can only be used during request handling, " \
"not during initialization", name); \
return false; \
}
#define INIT_ONLY(name) \
if (FetchEvent::instance()) { \
JS_ReportErrorUTF8(cx, "%s can only be used during initialization, " \
"not during request handling", name); \
return false; \
}
namespace Logger {
namespace Slots { enum {
Endpoint,
Count
};};
const unsigned ctor_length = 1;
bool check_receiver(JSContext* cx, HandleValue receiver, 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;
}
}
namespace Env {
bool env_get(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!args.requireAtLeast(cx, "fastly.env.get", 1))
return false;
size_t var_name_len;
UniqueChars var_name_chars = encode(cx, args[0], &var_name_len);
if (!var_name_chars) {
return false;
}
RootedString env_var(cx, JS_NewStringCopyZ(cx, getenv(var_name_chars.get())));
if (!env_var) return false;
args.rval().setString(env_var);
return true;
}
const JSFunctionSpec methods[] = {
JS_FN("get", env_get, 1, JSPROP_ENUMERATE),
JS_FS_END};
JSObject* create(JSContext* cx) {
RootedObject env(cx, JS_NewPlainObject(cx));
if (!env || !JS_DefineFunctions(cx, env, methods)) return nullptr;
return env;
}
}
namespace URL {
bool is_instance(JS::Value);
JSObject* create(JSContext* cx, SpecString url_str, const JSUrl* base = nullptr);
JSObject* create(JSContext* cx, HandleValue url_val, HandleObject base_obj);
SpecString origin(JSContext* cx, HandleObject self);
}
static JSString* get_geo_info(JSContext* cx, HandleString address_str);
namespace Fastly {
static bool debug_logging_enabled = false;
static PersistentRooted<JSObject*> env;
static PersistentRooted<JSObject*> baseURL;
static PersistentRooted<JSString*> defaultBackend;
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);
REQUEST_HANDLER_ONLY("fastly.getGeolocationForIpAddress");
if (!args.requireAtLeast(cx, "fastly.getGeolocationForIpAddress", 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: consider allowing logger creation during initialization, but then throw when trying
// to log.
bool getLogger(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
REQUEST_HANDLER_ONLY("fastly.getLogger");
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;
}
bool includeBytes(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
INIT_ONLY("fastly.includeBytes");
RootedObject self(cx, &args.thisv().toObject());
if (!args.requireAtLeast(cx, "fastly.includeBytes", 1))
return false;
size_t path_len;
UniqueChars path = encode(cx, args[0], &path_len);
if (!path) return false;
FILE* fp = fopen(path.get(), "r");
if (!fp) {
JS_ReportErrorUTF8(cx, "Error opening file %s", path.get());
return false;
}
fseek(fp, 0L, SEEK_END);
size_t size = ftell(fp);
rewind(fp);
RootedObject typed_array(cx, JS_NewUint8Array(cx, size));
if (!typed_array) return false;
size_t read_bytes;
{
JS::AutoCheckCannotGC noGC(cx);
bool is_shared;
void* buffer = JS_GetArrayBufferViewData(typed_array, &is_shared, noGC);
read_bytes = fread(buffer, 1, size, fp);
}
if (read_bytes != size) {
JS_ReportErrorUTF8(cx, "Failed to read contents of file %s", path.get());
return false;
}
args.rval().setObject(*typed_array);
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_FN("includeBytes", includeBytes, 1, JSPROP_ENUMERATE),
JS_FS_END
};
bool env_get(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
args.rval().setObject(*env);
return true;
}
bool baseURL_get(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
args.rval().setObjectOrNull(baseURL);
return true;
}
bool baseURL_set(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (args.get(0).isNullOrUndefined()) {
baseURL.set(nullptr);
}
else if (!URL::is_instance(args.get(0))) {
JS_ReportErrorUTF8(cx,
"Invalid value assigned to fastly.baseURL, must be an instance of "
"URL, null, or undefined");
return false;
}
baseURL.set(&args.get(0).toObject());
args.rval().setObjectOrNull(baseURL);
return true;
}
bool defaultBackend_get(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
args.rval().setString(defaultBackend);
return true;
}
bool defaultBackend_set(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
RootedString backend(cx, JS::ToString(cx, args.get(0)));
if (!backend) return false;
defaultBackend = backend;
args.rval().setUndefined();
return true;
}
const JSPropertySpec properties[] = {
JS_PSG("env", env_get, JSPROP_ENUMERATE),
JS_PSGS("baseURL", baseURL_get, baseURL_set, JSPROP_ENUMERATE),
JS_PSGS("defaultBackend", defaultBackend_get, defaultBackend_set, JSPROP_ENUMERATE),
JS_PS_END};
static bool create(JSContext* cx, HandleObject global) {
RootedObject fastly(cx, JS_NewPlainObject(cx));
if (!fastly) return false;
env.init(cx, Env::create(cx));
if (!env) return false;
baseURL.init(cx);
defaultBackend.init(cx);
if (!JS_DefineProperty(cx, global, "fastly", fastly, 0)) return false;
return JS_DefineFunctions(cx, fastly, methods) &&
JS_DefineProperties(cx, fastly, properties);
}
}
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) ||
JS_IsBigInt64Array(obj) ||
JS_IsBigUint64Array(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::AutoCheckCannotGC 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 NativeStreamSource {
typedef bool PullAlgorithm(JSContext* cx, CallArgs args, HandleObject stream, HandleObject owner,
HandleObject controller);
typedef bool CancelAlgorithm(JSContext* cx, CallArgs args, HandleObject stream,
HandleObject owner, HandleValue reason);
JSObject* create(JSContext* cx, HandleObject owner, HandleValue startPromise,
PullAlgorithm* pull, CancelAlgorithm* cancel);
static JSObject* get_stream_source(JSContext* cx, HandleObject stream);
JSObject* owner(JSObject* self);
JSObject* stream(JSObject* self);
bool stream_has_native_source(JSContext* cx, HandleObject stream);
bool stream_is_body(JSContext* cx, HandleObject stream);
bool lock_stream(JSContext* cx, HandleObject stream);
JSObject* piped_to_transform_stream(JSObject* source);
}
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, HandleObject init_headers);
JSObject* create(JSContext* cx, Mode mode, HandleObject owner, HandleValue initv);
bool delazify(JSContext* cx, HandleObject headers);
bool maybe_add(JSContext* cx, HandleObject headers, const char* name, const char* value);
}
namespace Request {
bool is_instance(JSObject* obj);
}
namespace Response {
bool is_instance(JSObject* obj);
}
namespace TransformStream {
namespace Slots { enum {
Controller,
Readable,
Writable,
Backpressure,
BackpressureChangePromise,
Owner, // The target RequestOrResponse object if the stream's readable end is used as a body.
Count
};};
bool is_instance(JSObject* obj);
JSObject* owner(JSObject* self);
void set_owner(JSObject* self, JSObject* owner);
JSObject* readable(JSObject* self);
bool is_ts_readable(JSContext* cx, HandleObject readable);
bool readable_used_as_body(JSObject* self);
void set_readable_used_as_body(JSContext* cx, HandleObject readable, HandleObject target);
bool is_ts_writable(JSContext* cx, HandleObject writable);
JSObject* controller(JSObject* self);
bool backpressure(JSObject* self);
bool ErrorWritableAndUnblockWrite(JSContext* cx, HandleObject stream, HandleValue error);
bool SetBackpressure(JSContext* cx, HandleObject stream, bool backpressure);
bool Error(JSContext* cx, HandleObject stream, HandleValue error);
}
namespace URLSearchParams {
bool is_instance(JSObject* obj);
JSObject* create(JSContext* cx, jsurl::JSUrl* url);
JSUrlSearchParams* get_params(JSObject* self);
SpecSlice serialize(JSContext* cx, HandleObject self);
}
namespace RequestOrResponse {
namespace Slots { enum {
RequestOrResponse,
Body,
BodyStream,
BodyAllPromise,
HasBody,
BodyUsed,
Headers,
URL,
Count
};};
bool is_instance(JSObject* obj) {
return Request::is_instance(obj) || Response::is_instance(obj);
}
uint32_t handle(JSObject* obj) {
MOZ_ASSERT(is_instance(obj));
return static_cast<uint32_t>(JS::GetReservedSlot(obj, Slots::RequestOrResponse).toInt32());
}
bool has_body(JSObject* obj) {
MOZ_ASSERT(is_instance(obj));
return JS::GetReservedSlot(obj, Slots::HasBody).toBoolean();
}
BodyHandle body_handle(JSObject* obj) {
MOZ_ASSERT(is_instance(obj));
return BodyHandle { static_cast<uint32_t>(JS::GetReservedSlot(obj, Slots::Body).toInt32()) };
}
JSObject* body_stream(JSObject* obj) {
MOZ_ASSERT(is_instance(obj));
return JS::GetReservedSlot(obj, Slots::BodyStream).toObjectOrNull();
}
JSObject* body_source(JSContext* cx, HandleObject obj) {
MOZ_ASSERT(has_body(obj));
RootedObject stream(cx, body_stream(obj));
return NativeStreamSource::get_stream_source(cx, stream);
}
bool body_used(JSObject* obj) {
MOZ_ASSERT(is_instance(obj));
return JS::GetReservedSlot(obj, Slots::BodyUsed).toBoolean();
}
bool mark_body_used(JSContext* cx, HandleObject obj) {
MOZ_ASSERT(!body_used(obj));
JS::SetReservedSlot(obj, Slots::BodyUsed, JS::BooleanValue(true));
RootedObject stream(cx, body_stream(obj));
if (stream && NativeStreamSource::stream_is_body(cx, stream)) {
if (!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 move_body_handle(JSContext* cx, HandleObject from, 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.
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) {
MOZ_ASSERT(is_instance(obj));
Value val = JS::GetReservedSlot(obj, Slots::URL);
MOZ_ASSERT(val.isString());
return val;
}
void set_url(JSObject* obj, Value url) {
MOZ_ASSERT(is_instance(obj));
MOZ_ASSERT(url.isString());
JS::SetReservedSlot(obj, Slots::URL, url);
}
/**
* Implementation of the `body is unusable` concept at
* https://fetch.spec.whatwg.org/#body-unusable
*/
bool body_unusable(JSContext* cx, 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 extract_body(JSContext*cx, HandleObject self, HandleValue body_val) {
MOZ_ASSERT(is_instance(self));
MOZ_ASSERT(!has_body(self));