-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathrare_data.zig
More file actions
801 lines (687 loc) · 26.7 KB
/
rare_data.zig
File metadata and controls
801 lines (687 loc) · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
const RareData = @This();
websocket_deflate: ?*WebSocketDeflate.RareData = null,
boring_ssl_engine: ?*BoringSSL.ENGINE = null,
editor_context: EditorContext = EditorContext{},
stderr_store: ?*Blob.Store = null,
stdin_store: ?*Blob.Store = null,
stdout_store: ?*Blob.Store = null,
mysql_context: bun.api.MySQL.MySQLContext = .{},
postgresql_context: bun.api.Postgres.PostgresSQLContext = .{},
entropy_cache: ?*EntropyCache = null,
hot_map: ?HotMap = null,
cron_jobs: std.ArrayListUnmanaged(*bun.api.cron.CronJob) = .{},
// TODO: make this per JSGlobalObject instead of global
// This does not handle ShadowRealm correctly!
cleanup_hooks: std.ArrayListUnmanaged(CleanupHook) = .{},
file_polls_: ?*Async.FilePoll.Store = null,
global_dns_data: ?*bun.api.dns.GlobalData = null,
spawn_ipc_usockets_context: ?*uws.SocketContext = null,
mime_types: ?bun.http.MimeType.Map = null,
node_fs_stat_watcher_scheduler: ?bun.ptr.RefPtr(StatWatcherScheduler) = null,
listening_sockets_for_watch_mode: std.ArrayListUnmanaged(bun.FD) = .{},
listening_sockets_for_watch_mode_lock: bun.Mutex = .{},
temp_pipe_read_buffer: ?*PipeReadBuffer = null,
aws_signature_cache: AWSSignatureCache = .{},
s3_default_client: jsc.Strong.Optional = .empty,
default_csrf_secret: []const u8 = "",
valkey_context: ValkeyContext = .{},
tls_default_ciphers: ?[:0]const u8 = null,
// proxy_env_storage moved to VirtualMachine — see comment there on why
// lazy RareData creation raced with worker spawn.
#spawn_sync_event_loop: bun.ptr.Owned(?*SpawnSyncEventLoop) = .initNull(),
path_buf: PathBuf = .{},
/// Reusable heap buffer for path.resolve, path.relative, and path.toNamespacedPath.
/// Three fixed-size tiers, lazily allocated on first use. Safe because JS is single-threaded.
/// The buffer is used via a FixedBufferAllocator as the backing for a stackFallback.
pub const PathBuf = struct {
const S = bun.MAX_PATH_BYTES;
const SmallBuf = [2 * S]u8;
const MediumBuf = [8 * S]u8;
const LargeBuf = [32 * S]u8;
small: ?*SmallBuf = null,
medium: ?*MediumBuf = null,
large: ?*LargeBuf = null,
/// Returns a StackFallbackAllocator backed by the smallest tier that
/// fits `min_len`, falling back to `fallback` when the buffer is exhausted.
pub fn get(self: *PathBuf, min_len: usize, fallback: std.mem.Allocator) bun.StackFallbackAllocator {
const buf: []u8 = if (min_len <= 2 * S)
(self.small orelse blk: {
self.small = bun.handleOom(bun.default_allocator.create(SmallBuf));
break :blk self.small.?;
})
else if (min_len <= 8 * S)
(self.medium orelse blk: {
self.medium = bun.handleOom(bun.default_allocator.create(MediumBuf));
break :blk self.medium.?;
})
else
(self.large orelse blk: {
self.large = bun.handleOom(bun.default_allocator.create(LargeBuf));
break :blk self.large.?;
});
return bun.StackFallbackAllocator.init(buf, fallback);
}
pub fn deinit(self: *PathBuf) void {
if (self.small) |p| {
bun.default_allocator.destroy(p);
self.small = null;
}
if (self.medium) |p| {
bun.default_allocator.destroy(p);
self.medium = null;
}
if (self.large) |p| {
bun.default_allocator.destroy(p);
self.large = null;
}
}
};
const PipeReadBuffer = [256 * 1024]u8;
const DIGESTED_HMAC_256_LEN = 32;
pub const ProxyEnvStorage = struct {
HTTP_PROXY: ?*RefCountedEnvValue = null,
http_proxy: ?*RefCountedEnvValue = null,
HTTPS_PROXY: ?*RefCountedEnvValue = null,
https_proxy: ?*RefCountedEnvValue = null,
NO_PROXY: ?*RefCountedEnvValue = null,
no_proxy: ?*RefCountedEnvValue = null,
/// Held by Bun__setEnvValue around the slot swap + env.map.put, and by
/// the worker around cloneFrom + env.map.cloneWithAllocator. This closes
/// two races: (1) worker's cloneFrom reading a slot pointer concurrently
/// with the parent's deref → free on the same pointer; (2) the env.map's
/// backing ArrayHashMap being iterated during clone while the parent's
/// put() rehashes it.
lock: bun.Mutex = .{},
pub const Slot = struct {
/// Static-lifetime field name (e.g. "NO_PROXY") — safe to use as
/// the env map key without duping.
key: []const u8,
ptr: *?*RefCountedEnvValue,
};
pub fn slot(self: *ProxyEnvStorage, name: []const u8) ?Slot {
// On Windows the env.map is case-insensitive (CaseInsensitiveASCII-
// StringArrayHashMap) — map.put("HTTP_PROXY", ...) and
// map.put("http_proxy", ...) write the same entry. If we tracked
// refs in separate case-variant slots, one slot's value would leak
// and syncInto would replay the stale one into the worker's map.
// Canonicalize both cases to the uppercase slot on Windows; the
// lowercase slots stay null. Posix keeps both — its map and its
// getHttpProxy lookup are case-sensitive.
const eql = if (comptime bun.Environment.isWindows)
bun.strings.eqlCaseInsensitiveASCIIICheckLength
else
bun.strings.eql;
inline for (@typeInfo(ProxyEnvStorage).@"struct".fields) |f| {
if (comptime f.type == ?*RefCountedEnvValue) {
// Uppercase fields are declared first. On Windows the
// case-insensitive eql matches the uppercase field for
// either input case and returns before reaching lowercase.
if (eql(name, f.name)) {
return .{ .key = f.name, .ptr = &@field(self, f.name) };
}
}
}
return null;
}
/// Bump refcounts on all non-null values so a worker can share the
/// parent's strings. Caller must hold parent.lock — the pointer load
/// and ref() are not atomic with respect to Bun__setEnvValue's deref().
pub fn cloneFrom(self: *ProxyEnvStorage, parent: *const ProxyEnvStorage) void {
inline for (@typeInfo(ProxyEnvStorage).@"struct".fields) |f| {
if (comptime f.type == ?*RefCountedEnvValue) {
if (@field(parent, f.name)) |val| {
val.ref();
@field(self, f.name) = val;
}
}
}
}
/// Overwrite proxy-var entries in an env map with this storage's reffed
/// bytes. Used after map.cloneWithAllocator in the worker so the cloned
/// map and the reffed storage agree — defense-in-depth in case the map
/// clone captured a snapshot the storage doesn't hold a ref on (e.g. an
/// initial-environ value later overwritten by the setter).
pub fn syncInto(self: *const ProxyEnvStorage, map: *bun.DotEnv.Map) void {
inline for (@typeInfo(ProxyEnvStorage).@"struct".fields) |f| {
if (comptime f.type == ?*RefCountedEnvValue) {
if (@field(self, f.name)) |val| {
bun.handleOom(map.put(f.name, val.bytes));
}
}
}
}
pub fn deinit(self: *ProxyEnvStorage) void {
inline for (@typeInfo(ProxyEnvStorage).@"struct".fields) |f| {
if (comptime f.type == ?*RefCountedEnvValue) {
if (@field(self, f.name)) |val| {
val.deref();
@field(self, f.name) = null;
}
}
}
}
};
/// A ref-counted heap-allocated byte slice. The env map stores borrowed
/// `.bytes` slices; as long as any VM holds a ref, the bytes stay valid.
pub const RefCountedEnvValue = struct {
const RefCount = bun.ptr.ThreadSafeRefCount(@This(), "ref_count", RefCountedEnvValue.destroy, .{});
pub const ref = RefCount.ref;
pub const deref = RefCount.deref;
ref_count: RefCount,
bytes: []const u8,
pub fn create(value: []const u8) *RefCountedEnvValue {
return bun.new(RefCountedEnvValue, .{
.ref_count = .init(),
.bytes = bun.handleOom(bun.default_allocator.dupe(u8, value)),
});
}
fn destroy(this: *RefCountedEnvValue) void {
bun.default_allocator.free(this.bytes);
bun.destroy(this);
}
};
pub const AWSSignatureCache = struct {
cache: bun.StringArrayHashMap([DIGESTED_HMAC_256_LEN]u8) = bun.StringArrayHashMap([DIGESTED_HMAC_256_LEN]u8).init(bun.default_allocator),
date: u64 = 0,
lock: bun.Mutex = .{},
pub fn clean(this: *@This()) void {
for (this.cache.keys()) |cached_key| {
bun.default_allocator.free(cached_key);
}
this.cache.clearRetainingCapacity();
}
pub fn get(this: *@This(), numeric_day: u64, key: []const u8) ?[]const u8 {
this.lock.lock();
defer this.lock.unlock();
if (this.date == 0) {
return null;
}
if (this.date == numeric_day) {
if (this.cache.getKey(key)) |cached| {
return cached;
}
}
return null;
}
pub fn set(this: *@This(), numeric_day: u64, key: []const u8, value: [DIGESTED_HMAC_256_LEN]u8) void {
this.lock.lock();
defer this.lock.unlock();
if (this.date == 0) {
this.cache = bun.StringArrayHashMap([DIGESTED_HMAC_256_LEN]u8).init(bun.default_allocator);
} else if (this.date != numeric_day) {
// day changed so we clean the old cache
this.clean();
}
this.date = numeric_day;
bun.handleOom(this.cache.put(bun.handleOom(bun.default_allocator.dupe(u8, key)), value));
}
pub fn deinit(this: *@This()) void {
this.date = 0;
this.clean();
this.cache.deinit();
}
};
pub fn awsCache(this: *RareData) *AWSSignatureCache {
return &this.aws_signature_cache;
}
pub fn pipeReadBuffer(this: *RareData) *PipeReadBuffer {
return this.temp_pipe_read_buffer orelse {
this.temp_pipe_read_buffer = bun.handleOom(default_allocator.create(PipeReadBuffer));
return this.temp_pipe_read_buffer.?;
};
}
pub fn addListeningSocketForWatchMode(this: *RareData, socket: bun.FD) void {
this.listening_sockets_for_watch_mode_lock.lock();
defer this.listening_sockets_for_watch_mode_lock.unlock();
this.listening_sockets_for_watch_mode.append(bun.default_allocator, socket) catch {};
}
pub fn removeListeningSocketForWatchMode(this: *RareData, socket: bun.FD) void {
this.listening_sockets_for_watch_mode_lock.lock();
defer this.listening_sockets_for_watch_mode_lock.unlock();
if (std.mem.indexOfScalar(bun.FD, this.listening_sockets_for_watch_mode.items, socket)) |i| {
_ = this.listening_sockets_for_watch_mode.swapRemove(i);
}
}
pub fn closeAllListenSocketsForWatchMode(this: *RareData) void {
this.listening_sockets_for_watch_mode_lock.lock();
defer this.listening_sockets_for_watch_mode_lock.unlock();
for (this.listening_sockets_for_watch_mode.items) |socket| {
// Prevent TIME_WAIT state
Syscall.disableLinger(socket);
socket.close();
}
this.listening_sockets_for_watch_mode = .{};
}
pub fn hotMap(this: *RareData, allocator: std.mem.Allocator) *HotMap {
if (this.hot_map == null) {
this.hot_map = HotMap.init(allocator);
}
return &this.hot_map.?;
}
pub fn mimeTypeFromString(this: *RareData, allocator: std.mem.Allocator, str: []const u8) ?bun.http.MimeType {
if (this.mime_types == null) {
this.mime_types = bun.http.MimeType.createHashTable(
allocator,
) catch |err| bun.handleOom(err);
}
if (this.mime_types.?.get(str)) |entry| {
return bun.http.MimeType.Compact.from(entry).toMimeType();
}
return null;
}
/// Look up a MIME type string in the interned table and return its raw
/// (uncanonicalized) static-string slice, if it exists.
///
/// Unlike `mimeTypeFromString`, this does NOT substitute canonical
/// charset-appended forms (e.g. `text/plain` is returned as-is, not as
/// `text/plain;charset=utf-8`). Use this where the WHATWG File/Blob API
/// requires preserving the user-supplied MIME type verbatim.
///
/// Returns a slice into a static `_bytes` blob — safe to store without
/// allocation tracking.
pub fn mimeTypeInternedValue(this: *RareData, allocator: std.mem.Allocator, str: []const u8) ?[]const u8 {
if (this.mime_types == null) {
this.mime_types = bun.http.MimeType.createHashTable(
allocator,
) catch |err| bun.handleOom(err);
}
if (this.mime_types.?.get(str)) |entry| {
return entry.slice();
}
return null;
}
pub const HotMap = struct {
_map: bun.StringArrayHashMap(Entry),
const HTTPServer = jsc.API.HTTPServer;
const HTTPSServer = jsc.API.HTTPSServer;
const DebugHTTPServer = jsc.API.DebugHTTPServer;
const DebugHTTPSServer = jsc.API.DebugHTTPSServer;
const TCPSocket = jsc.API.TCPSocket;
const TLSSocket = jsc.API.TLSSocket;
const Listener = jsc.API.Listener;
const Entry = bun.TaggedPointerUnion(.{
HTTPServer,
HTTPSServer,
DebugHTTPServer,
DebugHTTPSServer,
TCPSocket,
TLSSocket,
Listener,
});
pub fn init(allocator: std.mem.Allocator) HotMap {
return .{
._map = bun.StringArrayHashMap(Entry).init(allocator),
};
}
pub fn get(this: *HotMap, key: []const u8, comptime Type: type) ?*Type {
var entry = this._map.get(key) orelse return null;
return entry.get(Type);
}
pub fn getEntry(this: *HotMap, key: []const u8) ?Entry {
return this._map.get(key) orelse return null;
}
pub fn insert(this: *HotMap, key: []const u8, ptr: anytype) void {
const entry = bun.handleOom(this._map.getOrPut(key));
if (entry.found_existing) {
@panic("HotMap already contains key");
}
entry.key_ptr.* = bun.handleOom(this._map.allocator.dupe(u8, key));
entry.value_ptr.* = Entry.init(ptr);
}
pub fn remove(this: *HotMap, key: []const u8) void {
const entry = this._map.getEntry(key) orelse return;
const key_to_free = entry.key_ptr.*;
const is_same_slice = key_to_free.ptr == key.ptr and key_to_free.len == key.len;
_ = this._map.orderedRemove(key);
bun.debugAssert(!is_same_slice);
bun.default_allocator.free(key_to_free);
}
};
pub fn filePolls(this: *RareData, vm: *jsc.VirtualMachine) *Async.FilePoll.Store {
return this.file_polls_ orelse {
this.file_polls_ = vm.allocator.create(Async.FilePoll.Store) catch unreachable;
this.file_polls_.?.* = Async.FilePoll.Store.init();
return this.file_polls_.?;
};
}
pub fn nextUUID(this: *RareData) UUID {
if (this.entropy_cache == null) {
this.entropy_cache = default_allocator.create(EntropyCache) catch unreachable;
this.entropy_cache.?.init();
}
const bytes = this.entropy_cache.?.get();
return UUID.initWith(&bytes);
}
pub fn entropySlice(this: *RareData, len: usize) []u8 {
if (this.entropy_cache == null) {
this.entropy_cache = default_allocator.create(EntropyCache) catch unreachable;
this.entropy_cache.?.init();
}
return this.entropy_cache.?.slice(len);
}
pub const EntropyCache = struct {
pub const buffered_uuids_count = 16;
pub const size = buffered_uuids_count * 128;
cache: [size]u8 = undefined,
index: usize = 0,
pub fn init(instance: *EntropyCache) void {
instance.fill();
}
pub fn fill(this: *EntropyCache) void {
bun.csprng(&this.cache);
this.index = 0;
}
pub fn slice(this: *EntropyCache, len: usize) []u8 {
if (len > this.cache.len) {
return &[_]u8{};
}
if (this.index + len > this.cache.len) {
this.fill();
}
const result = this.cache[this.index..][0..len];
this.index += len;
return result;
}
pub fn get(this: *EntropyCache) [16]u8 {
if (this.index + 16 > this.cache.len) {
this.fill();
}
const result = this.cache[this.index..][0..16].*;
this.index += 16;
return result;
}
};
pub const CleanupHook = struct {
ctx: ?*anyopaque,
func: Function,
globalThis: *jsc.JSGlobalObject,
pub fn eql(self: CleanupHook, other: CleanupHook) bool {
return self.ctx == other.ctx and self.func == other.func and self.globalThis == other.globalThis;
}
pub fn execute(self: CleanupHook) void {
self.func(self.ctx);
}
pub fn init(
globalThis: *jsc.JSGlobalObject,
ctx: ?*anyopaque,
func: CleanupHook.Function,
) CleanupHook {
return .{
.ctx = ctx,
.func = func,
.globalThis = globalThis,
};
}
pub const Function = *const fn (?*anyopaque) callconv(.c) void;
};
pub fn pushCleanupHook(
this: *RareData,
globalThis: *jsc.JSGlobalObject,
ctx: ?*anyopaque,
func: CleanupHook.Function,
) void {
bun.handleOom(this.cleanup_hooks.append(bun.default_allocator, CleanupHook.init(globalThis, ctx, func)));
}
pub fn boringEngine(rare: *RareData) *BoringSSL.ENGINE {
return rare.boring_ssl_engine orelse brk: {
rare.boring_ssl_engine = BoringSSL.ENGINE_new();
break :brk rare.boring_ssl_engine.?;
};
}
pub fn stderr(rare: *RareData) *Blob.Store {
bun.analytics.Features.@"Bun.stderr" += 1;
return rare.stderr_store orelse brk: {
var mode: bun.Mode = 0;
const fd = bun.FD.fromUV(2);
switch (Syscall.fstat(fd)) {
.result => |stat| {
mode = @intCast(stat.mode);
},
.err => {},
}
const store = Blob.Store.new(.{
.ref_count = std.atomic.Value(u32).init(2),
.allocator = default_allocator,
.data = .{
.file = .{
.pathlike = .{
.fd = fd,
},
.is_atty = Output.stderr_descriptor_type == .terminal,
.mode = mode,
},
},
});
rare.stderr_store = store;
break :brk store;
};
}
pub fn stdout(rare: *RareData) *Blob.Store {
bun.analytics.Features.@"Bun.stdout" += 1;
return rare.stdout_store orelse brk: {
var mode: bun.Mode = 0;
const fd = bun.FD.fromUV(1);
switch (Syscall.fstat(fd)) {
.result => |stat| {
mode = @intCast(stat.mode);
},
.err => {},
}
const store = Blob.Store.new(.{
.ref_count = std.atomic.Value(u32).init(2),
.allocator = default_allocator,
.data = .{
.file = .{
.pathlike = .{
.fd = fd,
},
.is_atty = Output.stdout_descriptor_type == .terminal,
.mode = mode,
},
},
});
rare.stdout_store = store;
break :brk store;
};
}
pub fn stdin(rare: *RareData) *Blob.Store {
bun.analytics.Features.@"Bun.stdin" += 1;
return rare.stdin_store orelse brk: {
var mode: bun.Mode = 0;
const fd = bun.FD.fromUV(0);
switch (Syscall.fstat(fd)) {
.result => |stat| {
mode = @intCast(stat.mode);
},
.err => {},
}
const store = Blob.Store.new(.{
.allocator = default_allocator,
.ref_count = std.atomic.Value(u32).init(2),
.data = .{
.file = .{
.pathlike = .{ .fd = fd },
.is_atty = if (fd.unwrapValid()) |valid| std.posix.isatty(valid.native()) else false,
.mode = mode,
},
},
});
rare.stdin_store = store;
break :brk store;
};
}
const StdinFdType = enum(i32) {
file = 0,
pipe = 1,
socket = 2,
};
pub export fn Bun__Process__getStdinFdType(vm: *jsc.VirtualMachine, fd: i32) StdinFdType {
const mode = switch (fd) {
0 => vm.rareData().stdin().data.file.mode,
1 => vm.rareData().stdout().data.file.mode,
2 => vm.rareData().stderr().data.file.mode,
else => unreachable,
};
if (bun.S.ISFIFO(mode)) {
return .pipe;
} else if (bun.S.ISSOCK(mode)) {
return .socket;
} else {
return .file;
}
}
fn setTLSDefaultCiphersFromJS(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue {
const vm = globalThis.bunVM();
const args = callframe.arguments();
const ciphers = if (args.len > 0) args[0] else .js_undefined;
if (!ciphers.isString()) return globalThis.throwInvalidArgumentTypeValue("ciphers", "string", ciphers);
var sliced = try ciphers.toSlice(globalThis, bun.default_allocator);
defer sliced.deinit();
vm.rareData().setTLSDefaultCiphers(sliced.slice());
return .js_undefined;
}
fn getTLSDefaultCiphersFromJS(globalThis: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue {
const vm = globalThis.bunVM();
const ciphers = vm.rareData().tlsDefaultCiphers() orelse return try bun.String.createUTF8ForJS(globalThis, bun.uws.get_default_ciphers());
return try bun.String.createUTF8ForJS(globalThis, ciphers);
}
comptime {
const js_setTLSDefaultCiphers = jsc.toJSHostFn(setTLSDefaultCiphersFromJS);
@export(&js_setTLSDefaultCiphers, .{ .name = "Bun__setTLSDefaultCiphers" });
const js_getTLSDefaultCiphers = jsc.toJSHostFn(getTLSDefaultCiphersFromJS);
@export(&js_getTLSDefaultCiphers, .{ .name = "Bun__getTLSDefaultCiphers" });
}
pub fn spawnIPCContext(rare: *RareData, vm: *jsc.VirtualMachine) *uws.SocketContext {
if (rare.spawn_ipc_usockets_context) |ctx| {
return ctx;
}
const ctx = uws.SocketContext.createNoSSLContext(vm.event_loop_handle.?, @sizeOf(usize)).?;
IPC.Socket.configure(ctx, true, *IPC.SendQueue, IPC.IPCHandlers.PosixSocket);
rare.spawn_ipc_usockets_context = ctx;
return ctx;
}
pub fn globalDNSResolver(rare: *RareData, vm: *jsc.VirtualMachine) *api.dns.Resolver {
if (rare.global_dns_data == null) {
rare.global_dns_data = api.dns.GlobalData.init(vm.allocator, vm);
rare.global_dns_data.?.resolver.ref(); // live forever
}
return &rare.global_dns_data.?.resolver;
}
pub fn nodeFSStatWatcherScheduler(rare: *RareData, vm: *jsc.VirtualMachine) bun.ptr.RefPtr(StatWatcherScheduler) {
return (rare.node_fs_stat_watcher_scheduler orelse init: {
rare.node_fs_stat_watcher_scheduler = StatWatcherScheduler.init(vm);
break :init rare.node_fs_stat_watcher_scheduler.?;
}).dupeRef();
}
pub fn s3DefaultClient(rare: *RareData, globalThis: *jsc.JSGlobalObject) jsc.JSValue {
return rare.s3_default_client.get() orelse {
const vm = globalThis.bunVM();
var aws_options = bun.S3.S3Credentials.getCredentialsWithOptions(
vm.transpiler.env.getS3Credentials(),
.{},
null,
null,
null,
false,
globalThis,
) catch |err| switch (err) {
error.OutOfMemory => bun.outOfMemory(),
error.JSError => {
globalThis.reportActiveExceptionAsUnhandled(err);
return .js_undefined;
},
error.JSTerminated => {
globalThis.reportActiveExceptionAsUnhandled(err);
return .js_undefined;
},
};
defer aws_options.deinit();
const client = jsc.WebCore.S3Client.new(.{
.credentials = aws_options.credentials.dupe(),
.options = aws_options.options,
.acl = aws_options.acl,
.storage_class = aws_options.storage_class,
});
const js_client = client.toJS(globalThis);
js_client.ensureStillAlive();
rare.s3_default_client = .create(js_client, globalThis);
return js_client;
};
}
pub fn tlsDefaultCiphers(this: *RareData) ?[:0]const u8 {
return this.tls_default_ciphers orelse null;
}
pub fn setTLSDefaultCiphers(this: *RareData, ciphers: []const u8) void {
if (this.tls_default_ciphers) |old_ciphers| {
bun.default_allocator.free(old_ciphers);
}
this.tls_default_ciphers = bun.handleOom(bun.default_allocator.dupeZ(u8, ciphers));
}
pub fn defaultCSRFSecret(this: *RareData) []const u8 {
if (this.default_csrf_secret.len == 0) {
const secret = bun.handleOom(bun.default_allocator.alloc(u8, 16));
bun.csprng(secret);
this.default_csrf_secret = secret;
}
return this.default_csrf_secret;
}
pub fn deinit(this: *RareData) void {
if (this.temp_pipe_read_buffer) |pipe| {
this.temp_pipe_read_buffer = null;
bun.default_allocator.destroy(pipe);
}
this.#spawn_sync_event_loop.deinit();
this.aws_signature_cache.deinit();
this.s3_default_client.deinit();
if (this.boring_ssl_engine) |engine| {
_ = bun.BoringSSL.c.ENGINE_free(engine);
}
if (this.default_csrf_secret.len > 0) {
bun.default_allocator.free(this.default_csrf_secret);
}
this.cleanup_hooks.clearAndFree(bun.default_allocator);
bun.debugAssert(this.cron_jobs.items.len == 0);
this.cron_jobs.deinit(bun.default_allocator);
this.path_buf.deinit();
if (this.websocket_deflate) |deflate| {
this.websocket_deflate = null;
deflate.deinit();
}
if (this.tls_default_ciphers) |ciphers| {
this.tls_default_ciphers = null;
bun.default_allocator.free(ciphers);
}
this.valkey_context.deinit();
}
pub fn websocketDeflate(this: *RareData) *WebSocketDeflate.RareData {
return this.websocket_deflate orelse brk: {
this.websocket_deflate = bun.new(WebSocketDeflate.RareData, .{});
break :brk this.websocket_deflate.?;
};
}
pub const SpawnSyncEventLoop = @import("./event_loop/SpawnSyncEventLoop.zig");
pub fn spawnSyncEventLoop(this: *RareData, vm: *jsc.VirtualMachine) *SpawnSyncEventLoop {
return this.#spawn_sync_event_loop.get() orelse brk: {
this.#spawn_sync_event_loop = .new(undefined);
const ptr: *SpawnSyncEventLoop = this.#spawn_sync_event_loop.get().?;
ptr.init(vm);
break :brk ptr;
};
}
const IPC = @import("./ipc.zig");
const UUID = @import("./uuid.zig");
const WebSocketDeflate = @import("../http/websocket_client/WebSocketDeflate.zig");
const std = @import("std");
const EditorContext = @import("../open.zig").EditorContext;
const StatWatcherScheduler = @import("./node/node_fs_stat_watcher.zig").StatWatcherScheduler;
const ValkeyContext = @import("../valkey/valkey.zig").ValkeyContext;
const bun = @import("bun");
const Async = bun.Async;
const Output = bun.Output;
const Syscall = bun.sys;
const api = bun.api;
const default_allocator = bun.default_allocator;
const jsc = bun.jsc;
const uws = bun.uws;
const BoringSSL = bun.BoringSSL.c;
const Blob = jsc.WebCore.Blob;