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
|
//! docs/typ/guide.typ, Terminals <terminals>, through a real session's
//! socket: its shells run.
const std = @import("std");
const libc = std.c;
const process = @import("../process.zig");
const eh = @import("../e2e_harness.zig");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
extern "c" fn system(cmd: [*:0]const u8) c_int;
pub const cases = .{
.{ "terminals: pty/run takes a line and answers how it ended, then what it printed, on the same open; busy while a job holds the tty, gone with its shell", runFile },
.{ "terminals: a terminal started outside the session's directory is named by it from its new on, and a shell that cannot start leaves no pane", namedOnce },
.{ "terminals: a program's prompt shows and holds still, input sent unsubmitted shows, and ^U takes the screen back to what it was", prompt },
.{ "terminals: what a program prints past a screenful stays in the terminal's body, and its prompt after it shows", history },
.{ "terminals: a control byte through pty/data reaches a program in raw mode, which then carries on", rawKey },
};
fn has(hay: []const u8, needle: []const u8) bool {
return std.mem.indexOf(u8, hay, needle) != null;
}
fn refusedSaying(c: *process.Conn, path: []const u8, data: []const u8, why: []const u8) !void {
try std.testing.expectError(error.Refused, c.write(path, data));
if (!has(c.said, why)) {
std.debug.print("{s} refused saying {s}, not {s}\n", .{ path, c.said, why });
return error.WrongWords;
}
}
/// A line written to a terminal's pty/run and the answer read on the same open.
fn run(a: std.mem.Allocator, c: *process.Conn, serial: u32, line: []const u8) ![]const u8 {
var buf: [64]u8 = undefined;
const fid = try c.hold(try std.fmt.bufPrint(&buf, "/pane/{d}/pty/run", .{serial}), 2);
defer c.clunk(fid);
_ = try c.writeFid(fid, 0, line);
return a.dupe(u8, try c.readFid(fid, 0, 1 << 16));
}
/// The serials of /index's rows whose fourth word, the path, is `path`.
fn panesAt(a: std.mem.Allocator, c: *process.Conn, path: []const u8) ![]const []const u8 {
var out: std.ArrayList([]const u8) = .empty;
var rows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n');
while (rows.next()) |row| {
var w = std.mem.tokenizeScalar(u8, row, ' ');
const serial = w.next().?;
_ = w.next();
_ = w.next();
if (std.mem.eql(u8, w.next() orelse "", path)) try out.append(a, serial);
}
return out.items;
}
/// The serials /index lists.
fn serials(a: std.mem.Allocator, c: *process.Conn) ![]const u32 {
var out: std.ArrayList(u32) = .empty;
var rows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n');
while (rows.next()) |row| try out.append(a, try std.fmt.parseInt(u32, row[0..std.mem.indexOfScalar(u8, row, ' ').?], 10));
return out.items;
}
fn shell(a: std.mem.Allocator, comptime fmt: []const u8, args: anytype) c_int {
return system(std.fmt.allocPrintSentinel(a, fmt, args, 0) catch @panic("out of memory"));
}
/// A run on another connection, as another client's, in a thread.
const Other = struct {
a: std.mem.Allocator,
conn: *process.Conn,
serial: u32,
line: []const u8,
got: []const u8 = "",
fn go(o: *Other) void {
o.got = run(o.a, o.conn, o.serial, o.line) catch "";
}
};
fn runFile(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
var d = try process.Detached.start(gpa, exe, "run", .{});
defer d.deinit();
const f = &d.files;
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit();
const a = arena.allocator();
const c = try process.Conn.dial(gpa, d.socket());
defer c.deinit(gpa);
const root = d.root();
// From a pane on a peer's path no command or terminal starts: refused
// before any pane is made, no `exit 127` pane left.
const peer = try c.newPane();
try c.write(f.at("/pane/{d}/name", .{peer}), "/n/nosuchpeer/d/f.txt\n");
const count = std.mem.count(u8, try c.read(a, "/index"), "\n");
try refusedSaying(c, f.at("/pane/{d}/exec", .{peer}), "ls\n", "no such directory");
try refusedSaying(c, f.at("/pane/{d}/exec", .{peer}), "Term\n", "no such directory");
try expectEqual(count, std.mem.count(u8, try c.read(a, "/index"), "\n"));
try expect(!has(try c.read(a, "/log"), "exit 127"));
try c.remove(f.at("/pane/{d}", .{peer}));
try c.write("/exec", "Shell bash\n");
try c.write("/exec", "Term\n");
var term: u32 = 0;
var rows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n');
while (rows.next()) |r| {
var w = std.mem.tokenizeScalar(u8, r, ' ');
const serial = try std.fmt.parseInt(u32, w.next().?, 10);
if (std.mem.eql(u8, w.next().?, "term")) term = @max(term, serial);
}
const deadline = eh.nowMs() + 10_000;
while (std.mem.eql(u8, try run(a, c, term, "true\n"), "busy\n")) { // deadline its first prompt
if (eh.nowMs() > deadline) return error.NoPrompt;
process.sleep(50);
}
try expectEqualStrings("exit 1\n", try run(a, c, term, "false\n"));
try expectEqualStrings("exit 0\none\ntwo\n", try run(a, c, term, "printf \"one\\ntwo\\n\"\n")); // then what it printed
try expectEqualStrings("exit 7\n", try run(a, c, term, "sh -c \"exit 7\"\n"));
try expectEqualStrings("error not run\n", try run(a, c, term, "fi\n")); // a syntax error runs nothing
try expectEqualStrings("error not run\n", try run(a, c, term, "echo 'open\n")); // nor does an open quote
try expectEqualStrings("exit 0\n", try run(a, c, term, "true\n")); // ...and the shell is clear after
// The pty's size is in pixels too: with no frontend attached at a
// nominal 8x16 cell, in a window at its font's cell. A program sizes
// its kitty graphics by it.
const said = try run(a, c, term, "python3 -c 'import fcntl,termios,struct;print(*struct.unpack(\"4H\",fcntl.ioctl(0,termios.TIOCGWINSZ,bytes(8))))'\n");
var lines = std.mem.splitScalar(u8, said, '\n');
_ = lines.next();
var size = std.mem.tokenizeScalar(u8, lines.next() orelse "", ' ');
var n: [4]u32 = undefined;
for (&n) |*v| v.* = try std.fmt.parseInt(u32, size.next() orelse return error.NoSize, 10);
if (process.backend == .gui)
try expect(n[2] > 0 and n[3] > 0 and n[2] % n[1] == 0 and n[3] % n[0] == 0)
else
try expect(n[2] == n[1] * 8 and n[3] == n[0] * 16 and n[2] > 0);
// A paging command run through pty/run does not wait in less: the
// terminal's PAGER is `pardes -`, and its text is a +Pager pane.
if (shell(a, "command -v git >/dev/null", .{}) == 0) {
const git = f.at("HOME='{s}' git -C '{s}/pagedrepo' -c user.name=p -c user.email=p@x", .{ root, root });
try expectEqual(@as(c_int, 0), shell(a, "mkdir '{s}/pagedrepo' && {s} init -q && echo x > '{s}/pagedrepo/f' && {s} add f && {s} commit -qm paged-commit-subject", .{ root, git, root, git, git }));
try expect(std.mem.startsWith(u8, try run(a, c, term, "git -C pagedrepo log\n"), "exit 0\n"));
const pager = try panesAt(a, c, f.at("{s}/pagedrepo/+Pager", .{root})); // git -C runs it in the repo
try expectEqual(@as(usize, 1), pager.len);
const body = try c.read(a, f.at("/pane/{s}/body", .{pager[0]}));
try expect(has(body, "paged-commit-subject") and !has(body, "\x1b"));
try c.remove(f.at("/pane/{s}", .{pager[0]}));
}
// systemd's tools page through their own variable: set too, its secure
// mode off, the path unquoted where it needs none. Read by the shell:
// coreutils 9.12's printenv quotes a value with a blank on a terminal.
const systemd = try run(a, c, term, "printf \"%s\\n\" \"$SYSTEMD_PAGER\" \"$SYSTEMD_PAGERSECURE\"\n");
try expect(std.mem.startsWith(u8, systemd, "exit 0\n") and std.mem.endsWith(u8, std.mem.trimEnd(u8, systemd, " \n"), " -\n0"));
if (shell(a, "command -v journalctl >/dev/null", .{}) == 0) {
try expect(std.mem.startsWith(u8, try run(a, c, term, "journalctl -n 3 --no-hostname\n"), "exit "));
for (try panesAt(a, c, f.at("{s}/+Pager", .{root}))) |p| try c.remove(f.at("/pane/{s}", .{p}));
}
// A pty is not given one row (it loses the prompt's input mark, and the
// shell would read busy for ever): refused, and said.
const ptyctl = f.at("/pane/{d}/pty/ctl", .{term});
try refusedSaying(c, ptyctl, "winsize 20 1\n", "at least 2 rows");
try c.write(ptyctl, "winsize 20 2\n");
process.sleep(500);
try expectEqualStrings("exit 0\n", try run(a, c, term, "true\n"));
var words = std.mem.tokenizeAny(u8, try c.read(a, ptyctl), " \n");
_ = words.next();
_ = words.next();
try expectEqualStrings("2", words.next() orelse ""); // not `.?`: a panic leaves the session running
try c.write(ptyctl, "winsize 80 24\n");
// A shell started again that cannot start (its directory is there but
// cannot be entered) fails the write and leaves the running shell be:
// runs still work.
const locked = try std.fmt.allocPrintSentinel(a, "{s}/locked", .{root}, 0);
try expectEqual(@as(c_int, 0), libc.mkdir(locked, 0o755));
try expectEqualStrings("exit 0\n", try run(a, c, term, f.at("cd {s}\n", .{locked})));
const moved_by = eh.nowMs() + 5_000;
while (!has(try c.read(a, "/index"), locked)) {
if (eh.nowMs() > moved_by) return error.NeverMoved;
process.sleep(50);
}
_ = libc.chmod(locked, 0o600);
const refused = if (libc.geteuid() != 0) refusedSaying(c, ptyctl, "exec\n", "shell") else {}; // root enters any directory
_ = libc.chmod(locked, 0o755);
try refused;
try expectEqualStrings("exit 0\n", try run(a, c, term, "true\n"));
try expectEqualStrings("exit 0\n", try run(a, c, term, f.at("cd {s}\n", .{root})));
const other = try process.Conn.dial(gpa, d.socket());
defer other.deinit(gpa);
const tv: libc.timeval = .{ .sec = 10, .usec = 0 };
_ = libc.setsockopt(other.fd, libc.SOL.SOCKET, libc.SO.RCVTIMEO, &tv, @sizeOf(libc.timeval));
var slow: Other = .{ .a = a, .conn = other, .serial = term, .line = "sleep 1\n" };
var waiter = try std.Thread.spawn(.{}, Other.go, .{&slow});
process.sleep(300);
// The job the other client ran holds the tty, and says so.
const busy = run(a, c, term, "true\n");
waiter.join();
try expectEqualStrings("busy: sleep is running\n", try busy);
try expectEqualStrings("exit 0\n", slow.got);
var closing: Other = .{ .a = a, .conn = other, .serial = term, .line = "sleep 30\n" };
waiter = try std.Thread.spawn(.{}, Other.go, .{&closing});
process.sleep(300);
const del = c.write(f.at("/pane/{d}/exec", .{term}), "Del\n");
waiter.join();
try del;
try expectEqualStrings("error shell gone\n", closing.got);
}
fn namedOnce(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
var d = try process.Detached.start(gpa, exe, "names", .{});
defer d.deinit();
const f = &d.files;
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit();
const a = arena.allocator();
const c = try process.Conn.dial(gpa, d.socket());
defer c.deinit(gpa);
const root = d.root();
try expectEqual(@as(c_int, 0), libc.mkdir(try std.fmt.allocPrintSentinel(a, "{s}/sub", .{root}, 0), 0o755));
// A look at a directory starts a terminal there (DirLook terminal);
// DirLook pane, the default, lists it in a pane.
try c.write("/ctl", "DirLook terminal\n");
var made: std.ArrayList(u32) = .empty;
try made.append(a, try c.look(a, f.at("{s}/sub", .{root}), null));
const before = try serials(a, c);
try c.write("/pane/1/ctl", "Term\n");
if (shell(a, "command -v fish >/dev/null", .{}) == 0) try c.write("/pane/1/ctl", "Term fish\n");
for (try serials(a, c)) |s| if (std.mem.indexOfScalar(u32, before, s) == null) try made.append(a, s);
try expect(made.items.len >= 2);
process.sleep(1500); // their shells start and say where they are
// A shell started again by pty/ctl exec: named as it was.
try c.write(f.at("/pane/{d}/pty/ctl", .{made.items[0]}), "exec\n");
process.sleep(1500);
const log = f.at("\n{s}", .{try c.read(a, "/log")});
for (made.items) |s| {
try expect(!has(log, f.at("\nrename {d} ", .{s})));
try expect(has(log, f.at("\nnew {d} {s}", .{ s, root })));
}
// A shell that cannot start (its interpreter is not there): Term fails
// the write with why and leaves no pane; pty/ctl exec fails with why
// and keeps its terminal.
try d.put("badsh", "#!/nonexistent/interp\n");
const bad = f.at("{s}/badsh", .{root});
_ = libc.chmod(try std.fmt.allocPrintSentinel(a, "{s}", .{bad}, 0), 0o755);
const panes = std.mem.count(u8, try c.read(a, "/index"), "\n");
try refusedSaying(c, "/pane/1/ctl", f.at("Term {s}\n", .{bad}), "interpreter /nonexistent/interp not found");
try refusedSaying(c, "/ctl", f.at("Shell {s}\n", .{bad}), "interpreter /nonexistent/interp not found");
process.sleep(300);
try expectEqual(panes, std.mem.count(u8, try c.read(a, "/index"), "\n"));
try expect(!has(try c.read(a, "/log"), "shell: shell not found"));
try expect(std.mem.indexOfScalar(u32, try serials(a, c), made.items[0]) != null);
}
const ready = "AGENT_READY> ";
fn prompt(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
try drive(gpa, exe, "printf \"AGENT_READY> \"; read answer", null, 0);
}
fn history(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
try drive(gpa, exe, "printf \"AGENT_READY> \"; sleep .3; seq 1 3000; printf \"AGENT_READY> \"; read answer", null, 1000);
}
fn rawKey(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
try drive(gpa, exe, "stty raw -echo; printf \"AGENT_READY> \"; dd bs=1 count=1 of=/dev/null 2>/dev/null; stty sane; seq 1 3000; printf \"AGENT_READY> \"; read answer", 0x0f, 1000);
}
/// The script run in a new terminal's shell, as `/bin/sh command.sh`: its
/// prompt waited for, `key` sent and the prompt waited for again, the body
/// holding at least `rows` lines (and, with none asked, fewer than a
/// thousand: nothing printed is nothing kept), then a probe typed and
/// taken back with ^U.
fn drive(gpa: std.mem.Allocator, exe: [:0]const u8, script: []const u8, key: ?u8, rows: usize) !void {
var d = try process.Detached.start(gpa, exe, "agent", .{});
defer d.deinit();
const f = &d.files;
try d.put("command.sh", f.at("exec /bin/sh -c '{s}'\n", .{script}));
try f.write("/ctl", "Shell /bin/sh\n");
try f.write("/exec", "Term\n");
const term = try f.focused();
const body = f.at("/pane/{d}/body", .{term});
const data = f.at("/pane/{d}/pty/data", .{term});
try until(f, body, struct {
fn ok(text: []const u8) bool {
return std.mem.trim(u8, text, " \n").len > 0;
}
}.ok);
try f.write(data, f.at("/bin/sh {s}/command.sh\r", .{d.root()}));
_ = try settled(f);
if (key) |k| {
try f.write(data, &.{k});
_ = try settled(f);
}
const deadline = eh.nowMs() + 10_000;
while (lineCount(try f.read(body)) < rows) {
if (eh.nowMs() > deadline) return error.ShortHistory;
sleepMs(50);
}
if (rows == 0) try std.testing.expect(lineCount(try f.read(body)) < 1000);
const before = try settled(f);
const probe = "pq7c0ffee2b9d";
try std.testing.expect(std.mem.indexOf(u8, before, probe) == null);
try f.write(data, probe);
const shown_by = eh.nowMs() + 10_000;
while (std.mem.indexOf(u8, try unwrapped(f), probe) == null) {
if (eh.nowMs() > shown_by) return error.ProbeNotShown;
sleepMs(10);
}
try f.write(data, "\x15");
const back_by = eh.nowMs() + 10_000;
while (!std.mem.eql(u8, try f.screen(), before)) {
if (eh.nowMs() > back_by) return error.ScreenNotRestored;
sleepMs(10);
}
}
/// The screen once it shows the prompt and holds still between two reads.
fn settled(f: *process.Files) ![]const u8 {
const deadline = eh.nowMs() + 10_000;
var previous: []const u8 = "";
while (true) {
const text = try f.screen();
if (std.mem.indexOf(u8, text, ready) != null and std.mem.eql(u8, text, previous)) return text;
if (eh.nowMs() > deadline) {
std.debug.print("no settled prompt on the screen:\n{s}\n", .{text});
return error.NotReady;
}
previous = text;
sleepMs(50);
}
}
fn until(f: *process.Files, path: []const u8, ok: fn ([]const u8) bool) !void {
const deadline = eh.nowMs() + 10_000;
while (!ok(try f.read(path))) {
if (eh.nowMs() > deadline) return error.Timeout;
sleepMs(10);
}
}
/// The screen's text with its rows run together, as a long line wraps.
fn unwrapped(f: *process.Files) ![]const u8 {
const text = try f.screen();
const out = try f.arena.allocator().alloc(u8, text.len);
var n: usize = 0;
for (text) |c| if (c != '\n') {
out[n] = c;
n += 1;
};
return out[0..n];
}
fn lineCount(text: []const u8) usize {
return std.mem.count(u8, text, "\n") + @intFromBool(text.len > 0 and text[text.len - 1] != '\n');
}
fn sleepMs(ms: u32) void {
var ts: std.c.timespec = .{ .sec = 0, .nsec = @as(isize, ms) * std.time.ns_per_ms };
_ = std.c.nanosleep(&ts, null);
}
|