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
|
const uws = @import("../deps/uws.zig");
const bun = @import("root").bun;
const Environment = bun.Environment;
const Global = bun.Global;
const strings = bun.strings;
const string = bun.string;
const Output = @import("root").bun.Output;
const MutableString = @import("root").bun.MutableString;
const std = @import("std");
const Allocator = std.mem.Allocator;
const JSC = @import("root").bun.JSC;
const JSValue = JSC.JSValue;
const JSGlobalObject = JSC.JSGlobalObject;
pub const log = Output.scoped(.IPC, false);
pub const ipcHeaderLength = @sizeOf(u8) + @sizeOf(u32);
pub const ipcVersion = 1;
pub const DecodedIPCMessage = union(enum) {
version: u32,
data: JSValue,
};
pub const DecodeIPCMessageResult = struct {
bytes_consumed: u32,
message: DecodedIPCMessage,
};
pub const IPCDecodeError = error{ NotEnoughBytes, InvalidFormat };
pub const IPCMessageType = enum(u8) {
Version = 1,
SerializedMessage = 2,
_,
};
/// Given potentially unfinished buffer `data`, attempt to decode and process a message from it.
/// Returns `NotEnoughBytes` if there werent enough bytes
/// Returns `InvalidFormat` if the message was invalid, probably close the socket in this case
/// otherwise returns the number of bytes consumed.
pub fn decodeIPCMessage(
data: []const u8,
globalThis: *JSC.JSGlobalObject,
) IPCDecodeError!DecodeIPCMessageResult {
JSC.markBinding(@src());
if (data.len < ipcHeaderLength) {
return IPCDecodeError.NotEnoughBytes;
}
const message_type: IPCMessageType = @enumFromInt(data[0]);
const message_len: u32 = @as(*align(1) const u32, @ptrCast(data[1 .. @sizeOf(u32) + 1])).*;
log("Received IPC message type {d} ({s}) len {d}", .{
@intFromEnum(message_type),
std.enums.tagName(IPCMessageType, message_type) orelse "unknown",
message_len,
});
switch (message_type) {
.Version => {
return .{
.bytes_consumed = ipcHeaderLength,
.message = .{ .version = message_len },
};
},
.SerializedMessage => {
if (data.len < (ipcHeaderLength + message_len)) {
return IPCDecodeError.NotEnoughBytes;
}
const message = data[ipcHeaderLength .. ipcHeaderLength + message_len];
const deserialized = JSValue.deserialize(message, globalThis);
if (deserialized == .zero) {
return IPCDecodeError.InvalidFormat;
}
return .{
.bytes_consumed = ipcHeaderLength + message_len,
.message = .{ .data = deserialized },
};
},
else => {
return IPCDecodeError.InvalidFormat;
},
}
}
pub const Socket = uws.NewSocketHandler(false);
/// This type is shared between VirtualMachine and Subprocess for their respective IPC handlers
///
/// `Context` must be a struct that implements this interface:
/// struct {
/// globalThis: ?*JSGlobalObject,
/// ipc_buffer: bun.ByteList,
///
/// fn handleIPCMessage(*Context, DecodedIPCMessage) void
/// fn handleIPCClose(*Context, Socket) void
/// }
pub fn NewIPCHandler(comptime Context: type) type {
return struct {
pub fn onOpen(
_: *Context,
socket: Socket,
) void {
// Write the version message
const Data = extern struct {
type: IPCMessageType align(1) = .Version,
version: u32 align(1) = ipcVersion,
};
const data: []const u8 = comptime @as([@sizeOf(Data)]u8, @bitCast(Data{}))[0..];
_ = socket.write(data, false);
socket.flush();
}
pub fn onClose(
this: *Context,
socket: Socket,
_: c_int,
_: ?*anyopaque,
) void {
// ?! does uSockets .close call onClose?
log("onClose\n", .{});
this.handleIPCClose(socket);
}
// extern fn getpid() i32;
pub fn onData(
this: *Context,
socket: Socket,
data_: []const u8,
) void {
var data = data_;
log("onData {}", .{std.fmt.fmtSliceHexLower(data)});
// if (comptime Context == bun.JSC.VirtualMachine.IPCInstance) {
// logDataOnly("{d} -> '{}'", .{ getpid(), std.fmt.fmtSliceHexLower(data) });
// }
// In the VirtualMachine case, `globalThis` is an optional, in case
// the vm is freed before the socket closes.
var globalThis = switch (@typeInfo(@TypeOf(this.globalThis))) {
.Pointer => this.globalThis,
.Optional => brk: {
if (this.globalThis) |global| {
break :brk global;
}
this.handleIPCClose(socket);
socket.close(0, null);
return;
},
else => @panic("Unexpected globalThis type: " ++ @typeName(@TypeOf(this.globalThis))),
};
// Decode the message with just the temporary buffer, and if that
// fails (not enough bytes) then we allocate to .ipc_buffer
if (this.ipc_buffer.len == 0) {
while (true) {
const result = decodeIPCMessage(data, globalThis) catch |e| switch (e) {
error.NotEnoughBytes => {
_ = this.ipc_buffer.write(bun.default_allocator, data) catch @panic("OOM");
log("hit NotEnoughBytes", .{});
return;
},
error.InvalidFormat => {
Output.printErrorln("InvalidFormatError during IPC message handling", .{});
this.handleIPCClose(socket);
socket.close(0, null);
return;
},
};
this.handleIPCMessage(result.message);
if (result.bytes_consumed < data.len) {
data = data[result.bytes_consumed..];
} else {
return;
}
}
}
_ = this.ipc_buffer.write(bun.default_allocator, data) catch @panic("OOM");
var slice = this.ipc_buffer.slice();
while (true) {
const result = decodeIPCMessage(slice, globalThis) catch |e| switch (e) {
error.NotEnoughBytes => {
// copy the remaining bytes to the start of the buffer
std.mem.copyForwards(u8, this.ipc_buffer.ptr[0..slice.len], slice);
this.ipc_buffer.len = @truncate(slice.len);
log("hit NotEnoughBytes2", .{});
return;
},
error.InvalidFormat => {
Output.printErrorln("InvalidFormatError during IPC message handling", .{});
this.handleIPCClose(socket);
socket.close(0, null);
return;
},
};
this.handleIPCMessage(result.message);
if (result.bytes_consumed < slice.len) {
slice = slice[result.bytes_consumed..];
} else {
// clear the buffer
this.ipc_buffer.len = 0;
return;
}
}
}
pub fn onWritable(
_: *Context,
_: Socket,
) void {}
pub fn onTimeout(
_: *Context,
_: Socket,
) void {}
pub fn onConnectError(
_: *Context,
_: Socket,
_: c_int,
) void {}
pub fn onEnd(
_: *Context,
_: Socket,
) void {}
};
}
/// This is used for Bun.spawn() IPC because otherwise we would have to copy the data once to get it to zig, then write it.
/// Returns `true` on success, `false` on failure + throws a JS error.
extern fn Bun__serializeJSValueForSubprocess(global: *JSC.JSGlobalObject, value: JSValue, fd: bun.FileDescriptor) bool;
pub const serializeJSValueForSubprocess = Bun__serializeJSValueForSubprocess;
|