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
const std = @import("std");
const net = std.Io.net;
pub const SimIo = struct {
now_ns: i96,
prng: std.Random.DefaultPrng,
sleeps: u64 = 0,
cancel_sleep: bool = false,
network: ?*Network = null,
pub fn init(seed: u64, seconds: i64) SimIo {
return .{ .now_ns = @as(i96, seconds) * std.time.ns_per_s, .prng = .init(seed) };
}
pub fn io(self: *SimIo) std.Io {
return .{ .userdata = self, .vtable = &vtable };
}
const vtable = blk: {
var table = std.Io.failing.vtable.*;
table.now = now;
table.sleep = sleep;
table.random = random;
table.randomSecure = randomSecure;
table.netLookup = netLookup;
table.netConnectIp = netConnectIp;
table.netClose = netClose;
table.netShutdown = netShutdown;
table.operate = operate;
table.checkCancel = checkCancel;
break :blk table;
};
/// cases run on one thread and nothing cancels them, so a
/// cancellation point always continues
fn checkCancel(_: ?*anyopaque) std.Io.Cancelable!void {}
fn context(raw: ?*anyopaque) *SimIo {
return @ptrCast(@alignCast(raw.?));
}
fn now(raw: ?*anyopaque, _: std.Io.Clock) std.Io.Timestamp {
return .{ .nanoseconds = context(raw).now_ns };
}
fn sleep(raw: ?*anyopaque, timeout: std.Io.Timeout) std.Io.Cancelable!void {
const self = context(raw);
self.sleeps += 1;
if (self.cancel_sleep) return error.Canceled;
switch (timeout) {
.none => return error.Canceled,
.duration => |duration| self.now_ns += @max(duration.raw.nanoseconds, 0),
.deadline => |deadline| self.now_ns = @max(self.now_ns, deadline.raw.nanoseconds),
}
}
fn random(raw: ?*anyopaque, bytes: []u8) void {
context(raw).prng.random().bytes(bytes);
}
fn randomSecure(raw: ?*anyopaque, bytes: []u8) std.Io.RandomSecureError!void {
random(raw, bytes);
}
fn world(raw: ?*anyopaque) *Network {
return context(raw).network orelse @panic("SimIo has no network attached");
}
fn netLookup(raw: ?*anyopaque, host: net.HostName, results: *std.Io.Queue(net.HostName.LookupResult), options: net.HostName.LookupOptions) net.HostName.LookupError!void {
const self = context(raw);
defer results.close(self.io());
const network = world(raw);
network.lookups += 1;
// a literal address resolves to itself, as in std.Io.Threaded
if (net.IpAddress.parse(host.bytes, options.port)) |address| {
results.putOne(self.io(), .{ .address = address }) catch return error.Canceled;
return;
} else |_| {}
const index = network.hostIndex(host.bytes) orelse return error.UnknownHostName;
results.putOne(self.io(), .{ .address = .{ .ip4 = .{ .bytes = network.hosts.items[index].address, .port = options.port } } }) catch return error.Canceled;
results.putOne(self.io(), .{ .canonical_name = host }) catch return error.Canceled;
}
fn netConnectIp(raw: ?*anyopaque, address: *const net.IpAddress, _: net.IpAddress.ConnectOptions) net.IpAddress.ConnectError!net.Socket {
const network = world(raw);
network.connects += 1;
network.attempted = address.*;
const ip4 = switch (address.*) {
.ip4 => |ip4| ip4,
.ip6 => return error.NetworkUnreachable,
};
const host = network.hostByAddress(ip4.bytes) orelse return error.HostUnreachable;
if (network.refuse_connect) |refuse| {
if (refuse(network.handler_context)) {
network.faults_fired += 1;
return error.ConnectionRefused;
}
}
network.dialed.append(network.allocator, ip4.bytes) catch return error.SystemResources;
network.connections.append(network.allocator, .{ .host = host }) catch return error.SystemResources;
return .{ .handle = @intCast(first_handle + network.connections.items.len - 1), .address = address.* };
}
fn netClose(raw: ?*anyopaque, sockets: []const net.Socket) void {
const network = world(raw);
for (sockets) |socket| {
if (network.connection(socket.handle)) |conn| conn.closed = true;
}
}
fn netShutdown(_: ?*anyopaque, _: net.Socket.Handle, _: net.ShutdownHow) net.ShutdownError!void {}
fn operate(raw: ?*anyopaque, operation: std.Io.Operation) std.Io.Cancelable!std.Io.Operation.Result {
return switch (operation) {
.net_write => |write| .{ .net_write = world(raw).write(write) },
.net_read => |read| .{ .net_read = world(raw).read(context(raw), read) },
else => std.Io.failing.vtable.operate(null, operation),
};
}
};
const first_handle = 1 << 30;
pub const Request = struct {
host: []const u8,
method: []const u8,
target: []const u8,
head: []const u8,
body: []const u8,
pub fn header(self: Request, name: []const u8) ?[]const u8 {
var lines = std.mem.splitSequence(u8, self.head, "\r\n");
_ = lines.next();
while (lines.next()) |line| {
const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue;
if (std.ascii.eqlIgnoreCase(line[0..colon], name)) return std.mem.trim(u8, line[colon + 1 ..], " \t");
}
return null;
}
};
pub const Fault = enum { none, reset_before_response, truncate_body, close_after_response };
pub const Response = struct {
status: u16 = 200,
headers: []const u8 = "",
body: []const u8 = "",
fault: Fault = .none,
raw: ?[]const u8 = null,
};
pub const Handler = *const fn (context: *anyopaque, request: Request) Response;
pub const Network = struct {
allocator: std.mem.Allocator,
handler: Handler,
handler_context: *anyopaque,
hosts: std.ArrayList(Host) = .empty,
connections: std.ArrayList(Connection) = .empty,
dialed: std.ArrayList([4]u8) = .empty,
/// the last address a connect was attempted to, reachable or not
attempted: ?net.IpAddress = null,
max_read: usize = 4096,
/// websocket.zig v0.2.0 drops a handshake header whose CRLF is split
/// across reads. Until zat pins a release with the fix, reads inside an
/// upgrade response head are extended past such a \r, and counted.
split_upgrade_crlf: bool = true,
upgrade_crlf_splits_avoided: u64 = 0,
refuse_connect: ?*const fn (context: *anyopaque) bool = null,
lookups: u64 = 0,
connects: u64 = 0,
requests: u64 = 0,
faults_fired: u64 = 0,
const Host = struct { name: []const u8, address: [4]u8 };
const Connection = struct {
host: usize,
inbound: std.ArrayList(u8) = .empty,
outbound: std.ArrayList(u8) = .empty,
sent: usize = 0,
fault: Fault = .none,
upgraded: bool = false,
closed: bool = false,
peer_closed: bool = false,
};
pub fn init(allocator: std.mem.Allocator, handler_context: *anyopaque, handler: Handler) Network {
return .{ .allocator = allocator, .handler = handler, .handler_context = handler_context };
}
pub fn addHost(self: *Network, name: []const u8, address: [4]u8) !void {
try self.hosts.append(self.allocator, .{ .name = name, .address = address });
}
fn hostIndex(self: *Network, name: []const u8) ?usize {
for (self.hosts.items, 0..) |host, index| {
if (std.ascii.eqlIgnoreCase(host.name, name)) return index;
}
return null;
}
fn hostByAddress(self: *Network, address: [4]u8) ?usize {
for (self.hosts.items, 0..) |host, index| {
if (std.mem.eql(u8, &host.address, &address)) return index;
}
return null;
}
fn connection(self: *Network, handle: net.Socket.Handle) ?*Connection {
const index = std.math.sub(usize, @intCast(handle), first_handle) catch return null;
if (index >= self.connections.items.len) return null;
return &self.connections.items[index];
}
fn write(self: *Network, op: std.Io.Operation.NetWrite) std.Io.Operation.NetWrite.Result {
const conn = self.connection(op.socket_handle) orelse return error.SocketUnconnected;
if (conn.closed or conn.peer_closed) return error.ConnectionResetByPeer;
var written: usize = 0;
conn.inbound.appendSlice(self.allocator, op.header) catch return error.SystemResources;
written += op.header.len;
for (op.data, 0..) |chunk, index| {
const repeat = if (index == op.data.len - 1) op.splat else 1;
for (0..repeat) |_| conn.inbound.appendSlice(self.allocator, chunk) catch return error.SystemResources;
written += chunk.len * repeat;
}
return written;
}
fn read(self: *Network, sim: *SimIo, op: std.Io.Operation.NetRead) std.Io.Operation.NetRead.Result {
const conn = self.connection(op.socket_handle) orelse return error.SocketUnconnected;
if (conn.closed) return error.SocketUnconnected;
if (conn.sent == conn.outbound.items.len) {
if (conn.peer_closed) return .{ .data_len = 0 };
self.serve(conn) catch return error.SystemResources;
if (conn.fault == .reset_before_response) {
conn.peer_closed = true;
return error.ConnectionResetByPeer;
}
if (conn.sent == conn.outbound.items.len) return .{ .data_len = 0 };
}
const remaining = conn.outbound.items[conn.sent..];
const limit = 1 + sim.prng.random().uintLessThan(usize, @max(1, self.max_read));
var copied: usize = 0;
for (op.data) |buffer| {
const n = @min(buffer.len, remaining.len - copied, limit - copied);
@memcpy(buffer[0..n], remaining[copied..][0..n]);
copied += n;
if (copied == remaining.len or copied == limit) break;
}
if (!self.split_upgrade_crlf and conn.upgraded and op.data.len == 1 and copied > 0 and copied < @min(remaining.len, op.data[0].len) and
remaining[copied - 1] == '\r' and remaining[copied] == '\n')
{
const head_end = (std.mem.indexOf(u8, conn.outbound.items, "\r\n\r\n") orelse 0) + 4;
if (conn.sent + copied < head_end) {
op.data[0][copied] = '\n';
copied += 1;
self.upgrade_crlf_splits_avoided += 1;
}
}
conn.sent += copied;
if (conn.sent == conn.outbound.items.len and conn.fault != .none) conn.peer_closed = true;
return .{ .data_len = copied };
}
fn serve(self: *Network, conn: *Connection) !void {
if (conn.upgraded) return;
const head_end = (std.mem.indexOf(u8, conn.inbound.items, "\r\n\r\n") orelse return) + 4;
const head = conn.inbound.items[0..head_end];
var request: Request = .{ .host = self.hosts.items[conn.host].name, .method = "", .target = "", .head = head, .body = "" };
const content_length = if (request.header("content-length")) |value| std.fmt.parseInt(usize, value, 10) catch 0 else 0;
if (conn.inbound.items.len < head_end + content_length) return;
var first = std.mem.splitScalar(u8, head[0 .. std.mem.indexOf(u8, head, "\r\n") orelse head.len], ' ');
request.method = first.next() orelse "";
request.target = first.next() orelse "";
request.body = conn.inbound.items[head_end..][0..content_length];
self.requests += 1;
const response = self.handler(self.handler_context, request);
conn.fault = response.fault;
if (response.fault != .none) self.faults_fired += 1;
conn.outbound.clearRetainingCapacity();
conn.sent = 0;
if (response.raw) |raw| {
try conn.outbound.appendSlice(self.allocator, raw);
conn.upgraded = std.mem.startsWith(u8, raw, "HTTP/1.1 101 ");
if (conn.fault == .none) conn.fault = .close_after_response;
} else if (response.fault != .reset_before_response) {
const reason = (std.http.Status.phrase(@fromBackingInt(@intCast(response.status)))) orelse "Status";
try conn.outbound.print(self.allocator, "HTTP/1.1 {d} {s}\r\ncontent-length: {d}\r\n{s}{s}\r\n", .{
response.status,
reason,
response.body.len,
response.headers,
if (response.fault == .close_after_response) "connection: close\r\n" else "",
});
const body_len = if (response.fault == .truncate_body) response.body.len / 2 else response.body.len;
try conn.outbound.appendSlice(self.allocator, response.body[0..body_len]);
}
const consumed = head_end + content_length;
std.mem.copyForwards(u8, conn.inbound.items, conn.inbound.items[consumed..]);
conn.inbound.shrinkRetainingCapacity(conn.inbound.items.len - consumed);
}
};
pub fn websocketAccept(key: []const u8) [28]u8 {
var digest: [20]u8 = undefined;
var hasher = std.crypto.hash.Sha1.init(.{});
hasher.update(key);
hasher.update("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
hasher.final(&digest);
var encoded: [28]u8 = undefined;
_ = std.base64.standard.Encoder.encode(&encoded, &digest);
return encoded;
}
pub fn websocketFrame(out: *std.ArrayList(u8), allocator: std.mem.Allocator, opcode: u4, payload: []const u8) !void {
try out.append(allocator, 0x80 | @as(u8, opcode));
if (payload.len < 126) {
try out.append(allocator, @intCast(payload.len));
} else if (payload.len <= std.math.maxInt(u16)) {
try out.append(allocator, 126);
try out.appendSlice(allocator, &std.mem.toBytes(std.mem.nativeToBig(u16, @intCast(payload.len))));
} else {
try out.append(allocator, 127);
try out.appendSlice(allocator, &std.mem.toBytes(std.mem.nativeToBig(u64, payload.len)));
}
try out.appendSlice(allocator, payload);
}
/// Turn off zttp's head deadline and stall guards. zttp 0.3.0 runs each
/// configured guard with `Io.concurrent`, which SimIo does not provide, so a
/// guarded request fails with `ConcurrencyUnavailable` before it is sent.
/// Deadline and stall behavior stay untested until SimIo can run tasks
/// concurrently.
pub fn withoutGuards(transport: anytype) void {
transport.head_deadline_ns = 0;
transport.stall = .{ .idle_ns = 0, .min_bytes_per_s = 0, .grace_ns = 0, .window_ns = 0 };
}