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
|
//! The boundaries' fuzzes: bytes the core did not make, garbage and
//! mutated-valid, into the reader that takes them, on a fixed list of
//! seeds and a bound of seconds. Each holds one rule: an error, never a
//! panic, never a hang, memory bounded (`Capped`, and the testing
//! allocator's leak check at the end). A seed that fails is a run of its
//! own again: `-Dtest-filter` and the seed alone in `seeds`.
const std = @import("std");
const pardes = @import("root.zig");
const ninep = @import("runtime").ninep;
const th = @import("ninep/harness.zig");
const Pardes = pardes.Pardes;
const Random = std.Random;
const testing = std.testing;
const seeds = [_]u64{ 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597 };
/// An allocator over `child` that refuses one allocation past `one` and a
/// total past `all`, and counts what it refused: a reader that sizes an
/// allocation by a count the outside gave shows here, not as a machine
/// out of memory.
const Capped = struct {
child: std.mem.Allocator,
one: usize,
all: usize,
live: usize = 0,
refused: usize = 0,
fn allocator(c: *Capped) std.mem.Allocator {
return .{ .ptr = c, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } };
}
fn room(c: *Capped, more: usize) bool {
if (more <= c.one and c.live + more <= c.all) return true;
c.refused += 1;
return false;
}
fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ret: usize) ?[*]u8 {
const c: *Capped = @ptrCast(@alignCast(ctx));
if (!c.room(len)) return null;
const got = c.child.rawAlloc(len, a, ret) orelse return null;
c.live += len;
return got;
}
fn resize(ctx: *anyopaque, m: []u8, a: std.mem.Alignment, len: usize, ret: usize) bool {
const c: *Capped = @ptrCast(@alignCast(ctx));
if (len > m.len and !c.room(len - m.len)) return false;
if (!c.child.rawResize(m, a, len, ret)) return false;
c.live = c.live - m.len + len;
return true;
}
fn remap(ctx: *anyopaque, m: []u8, a: std.mem.Alignment, len: usize, ret: usize) ?[*]u8 {
const c: *Capped = @ptrCast(@alignCast(ctx));
if (len > m.len and !c.room(len - m.len)) return null;
const got = c.child.rawRemap(m, a, len, ret) orelse return null;
c.live = c.live - m.len + len;
return got;
}
fn free(ctx: *anyopaque, m: []u8, a: std.mem.Alignment, ret: usize) void {
const c: *Capped = @ptrCast(@alignCast(ctx));
c.child.rawFree(m, a, ret);
c.live -= m.len;
}
};
fn chance(r: Random, p: f32) bool {
return r.float(f32) < p;
}
fn pick(r: Random, xs: anytype) @TypeOf(xs[0]) {
return xs[r.uintLessThan(usize, xs.len)];
}
/// Random bytes with no byte that starts a shell or a prompt (`!|<>;&$` and
/// the backquote, `:`) and no capital (a builtin's first letter): what the
/// fuzz writes may be run (an exec file, a click, a key) and the core's
/// effects are dropped here, but a word that does its own I/O must never be
/// spelled by chance.
fn tame(r: Random, out: []u8) []u8 {
for (out) |*b| b.* = while (true) {
const c = r.int(u8);
if (std.mem.indexOfScalar(u8, "!|<>;&$`:", c) == null and !(c >= 'A' and c <= 'Z')) break c;
};
return out;
}
// ---------------------------------------------------------------------------
// (ii) 9P: frames through the engine pardes runs into its tree.
const Engine = ninep.Server(pardes.ctlfs, ninep.editor);
const msize = ninep.msize;
/// The names a walk takes: the tree's own, and the odd ones. Never `os` (the
/// host's files: read and WRITTEN through the tree) nor `n` (other servers).
const odd_names = [_][]const u8{ "", ".", "..", "...", "\x00", "a\x00b", "body\x00", "/", "a/b", "\xff\xfe", "na\xc3\xafve", "0", "1", "2", "3", "4", "9", "64", "99", "-1", "4294967295", "18446744073709551616", "pty", "ctl", "status", "data", "run", "new", "event" };
const forbidden = [_][]const u8{ "os", "n" };
fn walkName(r: Random, buf: []u8) []const u8 {
const top = std.meta.fieldNames(pardes.ctlfs.TopFile);
const pane = std.meta.fieldNames(pardes.ctlfs.PaneFile);
return switch (r.uintLessThan(u8, 10)) {
0...3 => pick(r, top),
4...6 => pick(r, pane),
7, 8 => pick(r, &odd_names),
else => tame(r, buf[0..r.uintAtMost(usize, @min(buf.len, @as(usize, if (chance(r, 0.5)) 300 else 8)))]),
};
}
const offsets = [_]u64{ 0, 0, 0, 1, 3, 7, 100, 4095, 4096, 65536, 1 << 31, 1 << 32, (1 << 63) - 1, 1 << 63, std.math.maxInt(u64) };
const counts = [_]u32{ 0, 1, 7, 64, 4096, 8192, msize - 11, msize, msize + 1, 1 << 31, std.math.maxInt(u32) };
const words = [_][]const u8{ "", "\n", "\x00", "\xff", "\xc0\x80", "\xe6\x97", "clean\n", "dirty\n", "show\n", "addr=dot\n", "dot=addr\n", "mark\n", "nomark\n", "limit=addr\n", "0\n", "1\n", "#3\n", ",\n", "/alpha/\n", "$\n", "0,$\n", "+\n", "-\n", "m 5 5 0\n", "m 99999 99999 7\n", "m -1 -1 1\n", "m a b c\n", "follow\n", "follow new\n", "lock\n", "unlock\n", "c 2 0\n", "99999999999\n", "-1\n", "\t\t\n",
// A pane's rows (core/locations.zig formatRows): kind, seven numbers, styles, path.
"m 1 0 0 0 0 0 0 5:0+5=7 a.txt\n", "c 3 0 0 0 0 0 0 3:1+2=15 y\n", "m 1 0 0 0 0 9999 9999 4:0+4=keyword.add x\n", "p 18446744073709551615 0 0 0 0 0 0 - x\n", "m 1 4294967296 1 1 1 1 1 2:0+2=string a.txt\nc 2 0 0 0 0 0 0 - b\n" };
fn data(r: Random, buf: []u8) []const u8 {
if (chance(r, 0.5)) return pick(r, &words);
const n = switch (r.uintLessThan(u8, 4)) {
0 => r.uintAtMost(usize, 16),
1 => r.uintAtMost(usize, 512),
2 => r.uintAtMost(usize, 8192),
else => r.uintAtMost(usize, msize - 23),
};
return tame(r, buf[0..@min(n, buf.len)]);
}
/// The fids a connection walked last: most requests are about them.
const Fids = struct {
recent: [4]u32 = @splat(0),
at: usize = 0,
fn any(f: *const Fids, r: Random) u32 {
if (chance(r, 0.6)) return pick(r, &f.recent);
return if (chance(r, 0.9)) r.uintLessThan(u32, 12) else pick(r, &[_]u32{ 255, 256, 4096, ninep.nofid, std.math.maxInt(u32) - 1 });
}
fn fresh(f: *Fids, r: Random) u32 {
const n = if (chance(r, 0.9)) 1 + r.uintLessThan(u32, 11) else f.any(r);
f.recent[f.at % f.recent.len] = n;
f.at += 1;
return n;
}
};
/// A path of the tree from its root, mostly; its names in `out`.
fn realPath(r: Random, out: *[16][]const u8) u16 {
const top = std.meta.fieldNames(pardes.ctlfs.TopFile);
const pane = std.meta.fieldNames(pardes.ctlfs.PaneFile);
if (chance(r, 0.4)) {
out[0] = pick(r, top);
return 1;
}
out[0] = "pane";
out[1] = pick(r, &[_][]const u8{ "1", "2", "3", "4", "new" });
if (std.mem.eql(u8, out[1], "new")) return 2;
if (chance(r, 0.15)) {
out[2] = "pty";
out[3] = pick(r, &[_][]const u8{ "ctl", "status", "data", "run" });
return 4;
}
out[2] = if (chance(r, 0.3)) pick(r, &[_][]const u8{ "rows", "body", "addr", "data", "ctl", "event", "tag" }) else pick(r, pane);
return 3;
}
/// One request, valid in its encoding, hostile in its values.
fn request(r: Random, f: *Fids, names: *[16][300]u8, buf: []u8) ninep.Msg {
return switch (r.uintLessThan(u8, 22)) {
0 => .{ .tversion = .{ .msize = pick(r, &[_]u32{ msize, msize, 0, 1, 7, 24, 4096, msize + 24, std.math.maxInt(u32) }), .version = pick(r, &[_][]const u8{ "9P2000", "9P2000", "9P2000.u", "", "9P", "\x00" }) } },
1 => .{ .tattach = .{ .fid = f.any(r), .afid = if (chance(r, 0.9)) ninep.nofid else f.any(r), .uname = pick(r, &[_][]const u8{ "user", "", "\x00" }), .aname = pick(r, &[_][]const u8{ "", "pardes", "x" }) } },
2 => .{ .tauth = .{ .afid = f.any(r), .uname = "u", .aname = "" } },
3 => .{ .tflush = .{ .oldtag = r.int(u16) } },
4...7 => walk: {
var m: ninep.Msg = .{ .twalk = .{ .fid = 0, .newfid = 0, .nwname = 0 } };
if (chance(r, 0.7)) {
m.twalk.nwname = realPath(r, &m.twalk.wname);
// One name of it odd, now and then.
if (chance(r, 0.15)) m.twalk.wname[r.uintLessThan(u16, m.twalk.nwname)] = walkName(r, &names[0]);
} else {
m.twalk.fid = f.any(r);
m.twalk.nwname = if (chance(r, 0.95)) r.uintAtMost(u16, 4) else r.uintAtMost(u16, 16);
for (m.twalk.wname[0..m.twalk.nwname], names[0..m.twalk.nwname]) |*w, *nb| w.* = walkName(r, nb);
}
m.twalk.newfid = f.fresh(r);
break :walk m;
},
8, 9 => .{ .topen = .{ .fid = f.any(r), .mode = if (chance(r, 0.7)) pick(r, &[_]u8{ 0, 1, 2, 3, 0x10, 0x11, 0x40, 0x12 }) else r.int(u8) } },
10 => .{ .tcreate = .{ .fid = f.any(r), .name = walkName(r, &names[0]), .perm = if (chance(r, 0.5)) pick(r, &[_]u32{ 0o644, 0x80000755, 0 }) else r.int(u32), .mode = r.int(u8) } },
11...13 => .{ .tread = .{ .fid = f.any(r), .offset = pick(r, &offsets), .count = pick(r, &counts) } },
14...17 => .{ .twrite = .{ .fid = f.any(r), .offset = pick(r, &offsets), .data = data(r, buf) } },
18 => .{ .tclunk = .{ .fid = f.any(r) } },
19 => .{ .tremove = .{ .fid = f.any(r) } },
20 => .{ .tstat = .{ .fid = f.any(r) } },
else => .{ .twstat = .{ .fid = f.any(r), .stat = .{
.type = if (chance(r, 0.8)) 0xffff else r.int(u16),
.dev = if (chance(r, 0.8)) 0xffffffff else r.int(u32),
.qid = .{ .type = 0xff, .version = 0xffffffff, .path = if (chance(r, 0.8)) std.math.maxInt(u64) else r.int(u64) },
.mode = if (chance(r, 0.7)) 0xffffffff else r.int(u32),
.atime = 0xffffffff,
.mtime = if (chance(r, 0.8)) 0xffffffff else r.int(u32),
.length = if (chance(r, 0.5)) std.math.maxInt(u64) else pick(r, &offsets),
.name = if (chance(r, 0.7)) "" else walkName(r, &names[1]),
.uid = "",
.gid = "",
.muid = "",
} } },
};
}
/// A frame the engine will take as one: whether it may be pushed. The
/// stream is framed here as the engine frames it (cloud9 Server.receive), so
/// a mutation that moves a frame's length cannot glue a walk into /os.
fn allowed(frame: []const u8) bool {
const got = ninep.decode(frame) catch return true; // the engine refuses it
switch (got.msg) {
.twalk => |w| for (w.wname[0..@min(w.nwname, w.wname.len)]) |name| {
for (forbidden) |f| if (std.mem.eql(u8, name, f)) return false;
},
.tattach => |a| for ([_][]const u8{ "", "pardes", "x" }) |ok| {
if (std.mem.eql(u8, a.aname, ok)) break;
} else return false,
else => {},
}
return true;
}
fn mutate(r: Random, frame: []u8, len: usize) usize {
switch (r.uintLessThan(u8, 6)) {
0 => frame[r.uintLessThan(usize, len)] ^= @as(u8, 1) << r.int(u3),
1 => frame[r.uintLessThan(usize, len)] = r.int(u8),
2 => return r.uintLessThan(usize, len), // cut, its length left saying more
3 => {
const n = @min(r.uintAtMost(usize, 64), frame.len - len);
r.bytes(frame[len..][0..n]);
return len + n; // more than it says
},
4 => std.mem.writeInt(u32, frame[0..4], pick(r, &[_]u32{ 0, 6, 7, @intCast(len + 1), msize + 1, std.math.maxInt(u32), r.int(u32) }), .little),
else => frame[4] = r.int(u8), // another type
}
return len;
}
/// Serves what the engine has whole, as runtime/9p_io.zig's `onServe` does
/// with the turn its own: the core's effects are dropped (no save, no
/// shell, no file).
fn serve(p: *Pardes, e: *Engine) void {
while (true) {
const req = e.next() orelse e.retry() orelse break;
const reply = pardes.filesystem.EditHold.retried(&p.fs, req) orelse p.serveFs(req);
p.fs.edit_started = false;
e.reply(&reply, p.fsPayload(reply));
if (req.op == .release) pardes.ctlfs.runClosedLines(p);
while (p.nextEffect()) |_| {}
e.wrote(e.output().len);
}
// What the pump does between requests (Core.settle), its effects dropped.
pardes.ctlfs.pane.flushPausedBatch(p);
pardes.ctlfs.ctl.fillClosedPagers(p);
pardes.ctlfs.runClosedLines(p);
while (p.nextEffect()) |_| {}
e.wrote(e.output().len);
}
fn connect(e: *Engine, in: []u8, out: []u8, seed: u64) void {
e.initIn(.{ .in = in, .out = out, .root = pardes.ctlfs.root, .seed = @truncate(seed) });
}
fn hangUp(p: *Pardes, e: *Engine) void {
e.hangup();
serve(p, e);
}
/// One seed: a connection or more, each greeted (mostly), then requests,
/// some mutated, some garbage.
fn ninepSeed(seed: u64, steps: usize) !void {
var prng: Random.DefaultPrng = .init(seed);
const r = prng.random();
var cap: Capped = .{ .child = testing.allocator, .one = 64 << 20, .all = 512 << 20 };
const gpa = cap.allocator();
const p = try th.withFile(gpa, "alpha beta\ngamma\n\tdelta \xe6\x97\xa5\n");
defer p.deinit();
p.fs.write_room = msize - 24;
const e = try testing.allocator.create(Engine);
defer testing.allocator.destroy(e);
e.seq = 0;
const in = try testing.allocator.alloc(u8, msize);
defer testing.allocator.free(in);
const out = try testing.allocator.alloc(u8, 2 * msize);
defer testing.allocator.free(out);
const buf = try testing.allocator.alloc(u8, msize + 128);
defer testing.allocator.free(buf);
const scratch = try testing.allocator.alloc(u8, msize);
defer testing.allocator.free(scratch);
var names: [16][300]u8 = undefined;
var fids: Fids = .{};
var c: Conn = .{ .p = p, .e = e, .buf = buf };
connect(e, in, out, seed);
var greet = true;
// A dirty connection's frames are mutated and garbage comes on it (the
// decoder's); a clean one's are whole, and go deep (the tree's).
var dirty = false;
for (0..steps) |_| {
if (e.protocol.dead or chance(r, 0.004)) {
hangUp(p, e);
connect(e, in, out, r.int(u64));
greet = true;
dirty = chance(r, 0.25);
fids = .{};
}
if (greet) {
greet = false;
try c.send(.{ .tversion = .{ .msize = msize, .version = "9P2000" } }, ninep.notag);
try c.send(.{ .tattach = .{ .fid = 0, .afid = ninep.nofid, .uname = "user", .aname = "" } }, c.next());
} else if (dirty and chance(r, 0.05)) {
const len = r.uintAtMost(usize, 96);
r.bytes(buf[0..len]); // garbage
try push(p, e, buf[0..len]);
} else if (!dirty and chance(r, 0.4)) {
// A file's round: walked, opened, read and written at hostile
// offsets and counts, clunked (or left open).
var w: ninep.Msg = .{ .twalk = .{ .fid = 0, .newfid = fids.fresh(r), .nwname = 0 } };
w.twalk.nwname = realPath(r, &w.twalk.wname);
const k = w.twalk.newfid;
try c.send(w, c.next());
try c.send(.{ .topen = .{ .fid = k, .mode = pick(r, &[_]u8{ 0, 1, 2, 2, 0x11, 0x12, 0x40 }) } }, c.next());
for (0..1 + r.uintLessThan(usize, 4)) |_| try c.send(if (chance(r, 0.6))
.{ .twrite = .{ .fid = k, .offset = pick(r, &offsets), .data = data(r, scratch) } }
else
.{ .tread = .{ .fid = k, .offset = pick(r, &offsets), .count = pick(r, &counts) } }, c.next());
if (chance(r, 0.7)) try c.send(.{ .tclunk = .{ .fid = k } }, c.next());
} else {
const msg = request(r, &fids, &names, scratch);
if (!dirty and (msg == .tversion or msg == .tauth)) continue;
const t: u16 = if (msg == .tversion) ninep.notag else if (!dirty or chance(r, 0.97)) c.next() else pick(r, &[_]u16{ 0, c.tag, ninep.notag });
const f = ninep.encode(msg, t, buf) catch continue;
const len = if (dirty and chance(r, 0.1)) mutate(r, buf, f.len) else f.len;
try push(p, e, buf[0..len]);
}
// Drawn, as the session draws after a request (and every client).
_ = p.frame_arena.reset(.retain_capacity);
_ = p.render(p.frame_arena.allocator()) catch {};
}
hangUp(p, e);
try testing.expectEqual(@as(usize, 0), cap.refused);
}
/// One connection's sending side: each request encoded whole and pushed.
const Conn = struct {
p: *Pardes,
e: *Engine,
buf: []u8,
tag: u16 = 0,
fn next(c: *Conn) u16 {
c.tag +%= 1;
if (c.tag == ninep.notag) c.tag = 1;
return c.tag;
}
fn send(c: *Conn, msg: ninep.Msg, tag: u16) !void {
const f = ninep.encode(msg, tag, c.buf) catch return;
try push(c.p, c.e, f);
}
};
/// Pushes `bytes` a frame at a time, as the engine will frame them, each
/// checked by `allowed`; one that is not ends the connection there.
fn push(p: *Pardes, e: *Engine, bytes: []const u8) !void {
var at: usize = 0;
while (at < bytes.len and !e.protocol.dead) {
const held = e.protocol.in_len;
// The length the engine will read: its own first bytes, or these.
var head: [4]u8 = undefined;
const have = @min(held, 4);
@memcpy(head[0..have], e.protocol.in[0..have]);
const more = @min(4 - have, bytes.len - at);
@memcpy(head[have..][0..more], bytes[at..][0..more]);
if (have + more < 4) {
at += e.push(bytes[at..]);
break;
}
const len = std.mem.readInt(u32, &head, .little);
if (held >= len) break; // a whole frame the engine has not taken yet: the rest goes
if (len < ninep.header_len or len > msize) {
_ = e.push(bytes[at..]); // the engine refuses it and ends the link
serve(p, e);
break;
}
const want = len - held;
if (bytes.len - at < want) {
at += e.push(bytes[at..]);
break;
}
var frame: [msize]u8 = undefined;
@memcpy(frame[0..held], e.protocol.in[0..held]);
@memcpy(frame[held..len], bytes[at..][0..want]);
if (!allowed(frame[0..len])) {
hangUp(p, e);
break;
}
const n = e.push(bytes[at..][0..want]);
at += n;
serve(p, e);
if (n < want) break;
}
serve(p, e);
}
test "9P: hostile and mutated frames through the engine into the tree: a refusal, never a panic" {
for (seeds) |seed| try ninepSeed(seed, 400);
}
// ---------------------------------------------------------------------------
// (iii) the wire: a client's messages into the session's reader and core;
// the session's units into a client's.
const wire = @import("wire");
const replica = pardes.replica;
/// Bytes laid out as abi/wire.zig's decoders read them.
const Out = struct {
buf: []u8,
n: usize = 0,
fn byte(o: *Out, v: u8) void {
if (o.n == o.buf.len) return;
o.buf[o.n] = v;
o.n += 1;
}
fn int(o: *Out, comptime T: type, v: T) void {
var b: [@sizeOf(T)]u8 = undefined;
std.mem.writeInt(T, &b, v, .little);
for (b) |x| o.byte(x);
}
fn bytes(o: *Out, v: []const u8) void {
for (v) |x| o.byte(x);
}
};
fn flag(r: Random) u8 {
return if (chance(r, 0.97)) @intFromBool(r.boolean()) else r.int(u8);
}
fn small(r: Random) u16 {
return if (chance(r, 0.8)) pick(r, &[_]u16{ 0, 1, 2, 5, 23, 24, 79, 80, 81, 127, 128, 511, 512, 513, 4096, 65535 }) else r.int(u16);
}
fn real(r: Random) u32 {
return if (chance(r, 0.9)) @bitCast(pick(r, &[_]f32{ 0, 1, -1, 0.5, 7.5, -0.0, 1e30, -1e30, 3.4e38, 1e-40, 65535.5 })) else r.int(u32);
}
fn metrics(o: *Out, r: Random) void {
const some = chance(r, 0.5);
o.byte(if (some) 1 else flag(r));
if (some) for (0..4) |_| o.int(u16, if (chance(r, 0.9)) 1 + r.uintLessThan(u16, 40) else small(r));
}
fn place(o: *Out, r: Random) void {
const rows = small(r);
for ([_]u16{ small(r), small(r), small(r), small(r), small(r), rows, if (chance(r, 0.9)) r.uintAtMost(u16, rows) else small(r) }) |n| o.int(u16, n);
}
/// A key's code: letters, digits, the specials' plane, and the odd ones.
fn codepoint(r: Random) u32 {
return switch (r.uintLessThan(u8, 6)) {
0, 1 => pick(r, "abcdefghijklmnopqrstuvwxyz0123456789 .,-_/\t\r"),
2 => pick(r, &[_]u32{ 0, 0x08, 0x1b, 0x7f, 0x0d, 0xD800, 0xDFFF, 0xFFFD, 0x10FFFF, 0x110000, 0xFFFFFFFF }),
3 => 0xE000 + r.uintLessThan(u32, 0x1900),
4 => 0xF0000 + r.uintLessThan(u32, 0x20000),
else => r.uintAtMost(u32, 0x10FFFF),
};
}
/// One client message: a frame (tag, length, payload) as the decoder reads
/// it, its shape mostly whole and its values hostile.
fn clientFrame(r: Random, out: []u8, text: []u8) []u8 {
const tags = std.enums.values(wire.ClientTag);
const tag: u8 = if (chance(r, 0.98)) @backingInt(pick(r, tags)) else r.int(u8);
var o: Out = .{ .buf = out };
o.byte(tag);
o.int(u32, 0);
switch (std.enums.fromInt(wire.ClientTag, tag) orelse .ping) {
.key => {
o.int(u32, codepoint(r));
const t = tame(r, text[0..if (chance(r, 0.9)) r.uintAtMost(usize, 8) else r.uintAtMost(usize, 300)]);
o.int(u16, @intCast(t.len));
o.bytes(t);
for (0..3) |_| o.byte(if (chance(r, 0.8)) 0 else flag(r));
},
.mouse => {
o.byte(if (chance(r, 0.95)) r.uintLessThan(u8, 10) else r.int(u8));
o.byte(if (chance(r, 0.95)) r.uintLessThan(u8, 4) else r.int(u8));
o.int(u16, small(r));
o.int(u16, small(r));
for (0..3) |_| o.byte(if (chance(r, 0.8)) 0 else flag(r));
o.int(u32, real(r));
// A body hit, then a tag hit.
for (0..2) |which| {
const some = chance(r, 0.4);
o.byte(if (some) 1 else flag(r));
if (!some) continue;
if (which == 1) {
o.byte(r.uintLessThan(u8, 8));
o.int(u16, small(r));
}
o.int(u32, if (chance(r, 0.8)) r.uintLessThan(u32, 6) else r.int(u32));
o.int(u16, small(r));
o.int(u16, small(r));
o.int(u32, real(r));
o.int(u32, real(r));
metrics(&o, r);
place(&o, r);
}
},
.resize => {
o.int(u16, if (chance(r, 0.9)) 1 + r.uintLessThan(u16, wire.max_cols) else small(r));
o.int(u16, if (chance(r, 0.9)) 1 + r.uintLessThan(u16, wire.max_rows) else small(r));
o.int(u16, small(r));
o.int(u16, small(r));
metrics(&o, r);
},
.paste => {
const t = tame(r, text[0..r.uintAtMost(usize, 300)]);
o.int(u32, @intCast(t.len));
o.bytes(t);
},
.command => {
const t = tame(r, text[0..r.uintAtMost(usize, 64)]);
o.int(u16, @intCast(t.len));
o.bytes(t);
},
.focus => o.byte(flag(r)),
.frontend => for (0..3) |_| o.byte(flag(r)),
.pointer_leave => {},
else => {
const n = r.uintAtMost(usize, 40);
r.bytes(text[0..n]);
o.bytes(text[0..n]);
},
}
std.mem.writeInt(u32, out[1..5], @intCast(o.n - wire.header_len), .little);
return out[0..o.n];
}
/// A client's input as the session's reader takes it (`Peer.take`): its
/// head, a stamp now and then, its event's frame; mutated, or garbage.
fn clientInput(r: Random, out: []u8, text: []u8) []u8 {
if (chance(r, 0.02)) {
const n = r.uintAtMost(usize, 64);
r.bytes(out[0..n]);
return out[0..n];
}
var o: Out = .{ .buf = out };
o.int(u16, r.uintLessThan(u16, 4));
o.int(u32, r.int(u32));
if (chance(r, 0.1)) {
o.byte(@backingInt(wire.ClientTag.stamp));
o.int(u32, 16);
o.int(i64, r.int(i64));
o.int(i64, r.int(i64));
}
const f = clientFrame(r, out[o.n..], text);
var n = o.n + f.len;
if (chance(r, 0.05)) n = mutate(r, out, n);
return out[0..n];
}
fn wireSessionSeed(seed: u64, steps: usize) !void {
var prng: Random.DefaultPrng = .init(seed);
const r = prng.random();
var cap: Capped = .{ .child = testing.allocator, .one = 64 << 20, .all = 512 << 20 };
const p = try th.withFile(cap.allocator(), "alpha beta\ngamma\n\tdelta \xe6\x97\xa5\n");
defer p.deinit();
const out = try testing.allocator.alloc(u8, 1 << 16);
defer testing.allocator.free(out);
const text = try testing.allocator.alloc(u8, 1 << 15);
defer testing.allocator.free(text);
for (0..steps) |_| {
const msg = clientInput(r, out, text);
// Every tag's decoder, as `Peer.take` and the daemon's hello read them.
if (msg.len > 6) if (wire.framed(msg[6..]) catch null) |f| {
_ = wire.decodeClient(f.tag, f.payload) catch {};
};
const in = replica.parseInput(msg) orelse continue;
p.update(in.event);
while (p.nextEffect()) |_| {}
_ = p.frame_arena.reset(.retain_capacity);
_ = p.render(p.frame_arena.allocator()) catch {};
}
try testing.expectEqual(@as(usize, 0), cap.refused);
}
test "the wire, a session's side: a client's hostile and mutated inputs are refused or applied, never a panic" {
for (seeds) |seed| try wireSessionSeed(seed, 300);
}
fn never(_: ?*anyopaque) bool {
return false;
}
const quiet_host: pardes.Host.VTable = .{ .watched = never };
/// A session's units from its boot, of inputs a client could send (typing,
/// a paste, sizes, focus, a pointer's motion: nothing that saves or runs).
fn recordedUnits(gpa: std.mem.Allocator, units: *std.ArrayList([]u8)) !void {
const a = try replica.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{ .vtable = &quiet_host });
defer a.deinit();
try units.append(gpa, try gpa.dupe(u8, try a.unit(0, 0)));
var buf: [256]u8 = undefined;
// Each a tag and its payload, as abi/wire.zig's decodeClient reads it.
const script = [_]struct { wire.ClientTag, []const u8 }{
.{ .key, "i\x00\x00\x00\x01\x00i\x00\x00\x00" },
.{ .key, "h\x00\x00\x00\x01\x00h\x00\x00\x00" },
.{ .paste, "\x0f\x00\x00\x00hello\nworld\n\xe6\x97\xa5" },
.{ .resize, "\x64\x00\x1e\x00\x0a\x00\x14\x00\x00" }, // 100x30
.{ .focus, "\x00" },
.{ .focus, "\x01" },
.{ .mouse, "\x07\x02\x0a\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" }, // motion at 10,5
.{ .key, "\x1b\x00\x00\x00\x00\x00\x00\x00\x00" }, // escape
.{ .resize, "\x3c\x00\x14\x00\x0a\x00\x14\x00\x00" }, // 60x20
.{ .key, "x\x00\x00\x00\x01\x00x\x00\x00\x00" },
};
for (0..3) |_| for (script) |s| {
var o: Out = .{ .buf = &buf };
o.bytes(&@as([6]u8, @splat(0)));
o.byte(@backingInt(s[0]));
o.int(u32, @intCast(s[1].len));
o.bytes(s[1]);
const in = replica.parseInput(buf[0..o.n]) orelse return error.BadScript;
a.apply(in.event);
a.seq += 1;
try units.append(gpa, try gpa.dupe(u8, try a.unit(0, a.seq)));
};
}
fn wireClientSeed(gpa: std.mem.Allocator, units: []const []const u8, seed: u64) !void {
var prng: Random.DefaultPrng = .init(seed);
const r = prng.random();
var cap: Capped = .{ .child = gpa, .one = 64 << 20, .all = 512 << 20 };
const copies = try gpa.alloc([]u8, units.len);
defer gpa.free(copies);
for (copies, units) |*c, u| c.* = try gpa.alloc(u8, u.len + 64);
defer for (copies) |c| gpa.free(c);
var lens = try gpa.alloc(usize, units.len);
defer gpa.free(lens);
for (copies, units, lens) |c, u, *n| {
@memcpy(c[0..u.len], u);
n.* = u.len;
// Seed 0 is the units as sent: a replica of them is the session.
if (seed != 0 and chance(r, 0.3)) n.* = switch (r.uintLessThan(u8, 4)) {
0 => flips: {
for (0..1 + r.uintLessThan(usize, 4)) |_| c[r.uintLessThan(usize, u.len)] ^= @as(u8, 1) << r.int(u3);
break :flips u.len;
},
1 => cut: {
break :cut r.uintLessThan(usize, u.len);
},
2 => grown: {
r.bytes(c[u.len..][0..64]);
break :grown u.len + r.uintAtMost(usize, 64);
},
else => set: {
c[r.uintLessThan(usize, u.len)] = r.int(u8);
break :set u.len;
},
};
}
const rep = replica.Replica.init(cap.allocator(), 1, copies[0][0..lens[0]]) catch return;
defer rep.deinit();
for (copies[1..], lens[1..]) |c, n| rep.confirm(c[0..n]);
rep.settle();
if (seed == 0) try testing.expect(rep.diverged == null);
try testing.expectEqual(@as(usize, 0), cap.refused);
}
test "the wire, a client's side: a session's units cut, flipped and grown diverge the client, never a panic" {
const gpa = testing.allocator;
var units: std.ArrayList([]u8) = .empty;
defer {
for (units.items) |u| gpa.free(u);
units.deinit(gpa);
}
try recordedUnits(gpa, &units);
try wireClientSeed(gpa, units.items, 0);
for (seeds) |seed| for (0..8) |k| try wireClientSeed(gpa, units.items, seed *% 31 +% k);
}
// ---------------------------------------------------------------------------
// (iv) a dump and an image read back: a join's (a client loads it before its
// digest is checked: replica.made), a Restore's and an Upgrade's (Db.zig's
// image, the state file's).
/// `n` bytes of `b` changed as a disk or a peer could: bits flipped, a
/// byte set, a run zeroed, cut, grown (`b` has room past `n`).
fn damage(r: Random, b: []u8, n: usize) usize {
if (n == 0) return n;
switch (r.uintLessThan(u8, 6)) {
0 => for (0..1 + r.uintLessThan(usize, 4)) |_| {
b[r.uintLessThan(usize, n)] ^= @as(u8, 1) << r.int(u3);
},
1 => b[r.uintLessThan(usize, n)] = r.int(u8),
2 => {
const at = r.uintLessThan(usize, n);
@memset(b[at..][0..@min(n - at, 1 + r.uintLessThan(usize, 16))], 0);
},
3 => return r.uintLessThan(usize, n),
4 => {
const more = @min(b.len - n, r.uintAtMost(usize, 64));
r.bytes(b[n..][0..more]);
return n + more;
},
else => {
const at = r.uintLessThan(usize, n);
@memset(b[at..][0..@min(n - at, 8)], 0xff);
},
}
return n;
}
fn loadSeed(whole: []const u8, seed: u64) !void {
var prng: Random.DefaultPrng = .init(seed);
const r = prng.random();
var cap: Capped = .{ .child = testing.allocator, .one = 64 << 20, .all = 512 << 20 };
const gpa = cap.allocator();
const b = try testing.allocator.alloc(u8, whole.len + 64);
defer testing.allocator.free(b);
@memcpy(b[0..whole.len], whole);
var n = whole.len;
if (seed != 0) for (0..1 + r.uintLessThan(usize, 3)) |_| {
n = damage(r, b, n);
};
var why: [256]u8 = undefined;
pardes.dump.check(gpa, b[0..n], &why) catch {};
var notes: std.ArrayList(u8) = .empty;
defer notes.deinit(gpa);
if (pardes.dump.load(gpa, .{ .cols = 80, .rows = 24 }, b[0..n], ¬es)) |q| {
_ = q.frame_arena.reset(.retain_capacity);
_ = q.render(q.frame_arena.allocator()) catch {};
q.deinit();
} else |err| if (seed == 0) return err;
try testing.expectEqual(@as(usize, 0), cap.refused);
}
test "a dump and an image cut, flipped and grown: refused or loaded, never a panic" {
const gpa = testing.allocator;
const p = try th.withFile(gpa, "alpha beta\ngamma\n\tdelta \xe6\x97\xa5\n");
defer p.deinit();
const bytes = try pardes.dump.dumpBytes(p);
defer gpa.free(bytes);
const image = try pardes.dump.image(p, "fuzz");
defer gpa.free(image);
for ([_][]const u8{ bytes, image }) |whole| {
try loadSeed(whole, 0);
for (seeds) |seed| for (0..8) |k| try loadSeed(whole, seed *% 31 +% k);
}
}
test "9P: a rows style past the syntax's kinds is refused, never drawn" {
const p = try th.withFile(testing.allocator, "x\n");
defer p.deinit();
// A results pane: its rows' styles are what it is painted with.
try pardes.panes.Output.fillResults(p, 0, "/tmp", .search, "foo", try p.gpa.dupe(u8, "a.txt:1:1 foo\nb.txt:2:3 foo\n"), null);
const serial = for (p.panes) |slot| {
const pane = slot orelse continue;
const f = pane.file orelse continue;
if (f.output != null and f.location_rows.len > 0) break pane.serial;
} else return error.NoSearch;
const rows = pardes.ctlfs.Node.of(serial, .rows);
// 1..4 are Syn's kinds (keyword, string, number, comment); 5..15 none.
for ([_][]const u8{ "7", "5", "15", "4" }) |n| {
_ = th.call(p, .{ .tag = 1, .op = .setattr, .node = rows, .truncate = true });
var line: [64]u8 = undefined;
const text = try std.fmt.bufPrint(&line, "m 1 1 0 0 0 0 0 3:0+3={s} a.txt\n", .{n});
const want: pardes.ctlfs.Status = if (std.mem.eql(u8, n, "4")) .ok else .err;
try testing.expectEqual(want, th.wr(p, rows, text).reply.status);
_ = p.frame_arena.reset(.retain_capacity);
_ = try p.render(p.frame_arena.allocator());
}
}
|