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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
|
//! The per-user daemon (docs/next-daemon.md, "Phase 3 notes"): one
//! `pardes --daemon` per user per machine, on `pardes-daemon.sock` in the
//! runtime directory (ninep_io.socketDir), its `.lock` flocked for its life
//! so two never run. The first session that finds none starts it (a double
//! fork and an exec), and it exits once it holds nothing: no session
//! connected, no pty master kept.
//!
//! It spawns nothing and is nobody's parent. A session registers on one
//! connection and tells it, over that connection:
//! - a dup of every pty master it forks (`pty`), so a session killed
//! outright never hangs its shells up, and which ones it closed;
//! - whether a terminal or a window shows it (`state`).
//! It hands a terminal (`pardes --attach`) or a window request
//! (`pardes-gui --attach`) to a detached session, and a crashed session's
//! masters to the one that asks for them (Adopt).
//!
//! Messages are SOCK_SEQPACKET datagrams: a line of words, and the fds it
//! carries (SCM_RIGHTS).
//!
//! A replica (docs/next-daemon.md, phase 5) comes in on a stream socket of
//! its own, `pardes-replica.sock`, which `ssh -L` can forward: its hello
//! (wire.zig) names a session, and once its build is the session's
//! the connection is handed to that session, which it talks to from then on.
const std = @import("std");
const builtin = @import("builtin");
const libc = std.c;
const posix = std.posix;
const ninep_io = @import("9p_io.zig");
const wire = @import("wire.zig");
const upgrade = @import("upgrade.zig");
const log = std.log.scoped(.replica);
pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd;
/// 2: a session's hello carries its semantics hash (wire.semantics).
const version = 2;
pub const max_fds = 64;
const msg_max = 4096;
/// Idle this long, it exits: long enough for the session that started it to
/// say hello, short enough that nothing lingers.
const linger_ms = 1000;
const max_conns = 64;
const max_held = 256;
/// Replicas whose hello is still on its way. ponytail: one that never sends
/// it holds its slot until it hangs up; past 16 a new one is closed at once.
const max_replicas = 16;
const sun_path_len = ninep_io.sun_path_len;
const nosignal: u32 = if (builtin.os.tag == .linux) libc.MSG.NOSIGNAL else 0;
pub const Kind = enum { tty, gui };
/// Off for a harness that kills what it starts by its pid and closes its
/// terminal (`PARDES_DAEMON=off`, the snapshot harness's): a session there
/// is the process it started, and a hung-up terminal ends it, as before
/// the daemon. A GUI test window (PARDES_TEST) has none unless asked
/// (`PARDES_DAEMON=on`).
pub fn wanted() bool {
if (comptime !supported) return false;
const v = std.mem.span(libc.getenv("PARDES_DAEMON") orelse return libc.getenv("PARDES_TEST") == null);
return !std.mem.eql(u8, v, "off");
}
fn place(buf: *[sun_path_len:0]u8, comptime leaf: []const u8) ?[:0]const u8 {
var dir_buf: [sun_path_len:0]u8 = undefined;
const dir = ninep_io.socketDir(&dir_buf) orelse return null;
_ = libc.mkdir(dir, 0o700);
return std.fmt.bufPrintSentinel(buf, "{s}/" ++ leaf, .{dir}, 0) catch null;
}
// ---- one message: words and fds ----
const data_off = std.mem.alignForward(usize, @sizeOf(libc.cmsghdr), @sizeOf(usize));
fn cmsgSpace(n: usize) usize {
return data_off + std.mem.alignForward(usize, n * @sizeOf(c_int), @sizeOf(usize));
}
fn send(fd: c_int, words: []const u8, fds: []const c_int) bool {
std.debug.assert(words.len > 0 and fds.len <= max_fds);
var iov = [_]posix.iovec_const{.{ .base = words.ptr, .len = words.len }};
var cbuf: [cmsgSpace(max_fds)]u8 align(@alignOf(libc.cmsghdr)) = undefined;
var msg: libc.msghdr_const = .{ .name = null, .namelen = 0, .iov = &iov, .iovlen = 1, .control = null, .controllen = 0, .flags = 0 };
if (fds.len > 0) {
const hdr: *libc.cmsghdr = @ptrCast(&cbuf);
hdr.* = .{ .len = @intCast(data_off + fds.len * @sizeOf(c_int)), .level = libc.SOL.SOCKET, .type = libc.SCM.RIGHTS };
@memcpy(cbuf[data_off..][0 .. fds.len * @sizeOf(c_int)], std.mem.sliceAsBytes(fds));
msg.control = &cbuf;
msg.controllen = @intCast(cmsgSpace(fds.len));
}
while (true) {
// Never blocks: a peer that does not read loses its link instead.
const n = libc.sendmsg(fd, &msg, nosignal | libc.MSG.DONTWAIT);
if (n >= 0) return true;
if (libc.errno(n) != .INTR) return false;
}
}
const Got = struct { words: []const u8, fds: [max_fds]c_int = undefined, nfds: usize = 0 };
/// The next message, its fds close-on-exec; null at the end of the link.
fn recv(fd: c_int, buf: []u8) ?Got {
var iov = [_]posix.iovec{.{ .base = buf.ptr, .len = buf.len }};
var cbuf: [cmsgSpace(max_fds)]u8 align(@alignOf(libc.cmsghdr)) = undefined;
var msg: libc.msghdr = .{ .name = null, .namelen = 0, .iov = &iov, .iovlen = 1, .control = &cbuf, .controllen = cbuf.len, .flags = 0 };
const n = while (true) {
const r = libc.recvmsg(fd, &msg, libc.MSG.CMSG_CLOEXEC);
if (r >= 0) break r;
if (libc.errno(r) != .INTR) return null;
};
var got: Got = .{ .words = buf[0..@intCast(n)] };
if (msg.controllen >= data_off) {
const hdr: *const libc.cmsghdr = @ptrCast(&cbuf);
if (hdr.level == libc.SOL.SOCKET and hdr.type == libc.SCM.RIGHTS and hdr.len >= data_off) {
got.nfds = @min((hdr.len - data_off) / @sizeOf(c_int), max_fds);
@memcpy(std.mem.sliceAsBytes(got.fds[0..got.nfds]), cbuf[data_off..][0 .. got.nfds * @sizeOf(c_int)]);
}
}
// A zero-length datagram is never sent: it is the peer's end.
if (n == 0) {
for (got.fds[0..got.nfds]) |f| _ = libc.close(f);
return null;
}
return got;
}
fn socket() c_int {
return libc.socket(libc.AF.UNIX, libc.SOCK.SEQPACKET | libc.SOCK.CLOEXEC, 0);
}
fn address(path: [:0]const u8) libc.sockaddr.un {
var addr: libc.sockaddr.un = .{ .path = @splat(0) };
@memcpy(addr.path[0..path.len], path);
return addr;
}
/// Connected without ever waiting on a daemon that does not accept (a full
/// backlog parks a blocking connect for good), then blocking again.
fn dial(path: [:0]const u8) ?c_int {
const fd = socket();
if (fd < 0) return null;
const addr = address(path);
const flags = libc.fcntl(fd, libc.F.GETFL, @as(c_int, 0));
const nonblock: c_int = @bitCast(@as(u32, @bitCast(libc.O{ .NONBLOCK = true })));
_ = libc.fcntl(fd, libc.F.SETFL, flags | nonblock);
if (libc.connect(fd, @ptrCast(&addr), @sizeOf(libc.sockaddr.un)) != 0) {
_ = libc.close(fd);
return null;
}
_ = libc.fcntl(fd, libc.F.SETFL, flags);
return fd;
}
/// Waits `ms` for `fd` to be readable.
fn readable(fd: c_int, ms: c_int) bool {
var fds = [_]libc.pollfd{.{ .fd = fd, .events = libc.POLL.IN, .revents = 0 }};
while (true) {
const n = libc.poll(&fds, 1, ms);
if (n >= 0) return n > 0;
if (libc.errno(n) != .INTR) return false;
}
}
fn sleepMs(ms: u32) void {
const ts: libc.timespec = .{ .sec = 0, .nsec = @as(c_long, ms) * std.time.ns_per_ms };
_ = libc.nanosleep(&ts, null);
}
// ---- a client's half ----
/// A connection to the daemon. When none answers and `start`, the
/// connection is queued on a socket this process binds, and the daemon is
/// still to be started on it (`startPending`): a terminal's stub does that
/// after its fork, off the session's way; every other caller at once.
pub fn connect(start: bool) ?c_int {
if (comptime !supported) return null;
var sock_buf: [sun_path_len:0]u8 = undefined;
const sock = place(&sock_buf, "pardes-daemon.sock") orelse return null;
if (dial(sock)) |fd| return fd;
if (!start) return null;
var lock_buf: [sun_path_len:0]u8 = undefined;
const lock_path = place(&lock_buf, "pardes-daemon.lock") orelse return null;
// Another starter, or a daemon on its way out, holds the lock: it is
// asked again until the lock is free or the socket answers.
var waited: u32 = 0;
while (waited < 500) : (waited += 2) {
if (begin(sock, lock_path)) |fd| return fd;
sleepMs(2);
if (dial(sock)) |fd| return fd;
}
return null;
}
/// The listener and lock a daemon is still to be started on (`begin`).
var pending: ?struct { listener: c_int, lock: c_int } = null;
/// With the lock taken: the socket bound and listening here and this
/// process's connection queued on it, so it is answered as soon as the
/// daemon runs; the daemon itself is `startPending`'s.
fn begin(sock: [:0]const u8, lock_path: [:0]const u8) ?c_int {
const lock = libc.open(lock_path, .{ .ACCMODE = .RDWR, .CREAT = true, .CLOEXEC = true }, @as(libc.mode_t, 0o600));
if (lock < 0) return null;
if (libc.flock(lock, posix.LOCK.EX | posix.LOCK.NB) != 0) {
_ = libc.close(lock);
return null;
}
// Ours to replace: whatever is at the path was a daemon that died.
_ = libc.unlink(sock);
const listener = socket();
const addr = address(sock);
const conn = if (listener >= 0 and libc.bind(listener, @ptrCast(&addr), @sizeOf(libc.sockaddr.un)) == 0 and
libc.chmod(sock, 0o600) == 0 and libc.listen(listener, max_conns) == 0) dial(sock) else null;
if (conn == null) {
if (listener >= 0) _ = libc.close(listener);
_ = libc.close(lock);
return null;
}
pending = .{ .listener = listener, .lock = lock };
return conn;
}
/// The daemon `connect` left to start, started (or, `start` false, let go
/// of: a forked session's copies).
pub fn startPending(start: bool) void {
const p = pending orelse return;
pending = null;
if (start and !spawn(p.listener, p.lock)) {
var sock_buf: [sun_path_len:0]u8 = undefined;
if (place(&sock_buf, "pardes-daemon.sock")) |sock| _ = libc.unlink(sock);
}
_ = libc.close(p.listener);
_ = libc.close(p.lock);
}
extern "c" fn close_range(first: c_uint, last: c_uint, flags: c_int) c_int;
/// `pardes --daemon`, in a session of its own and nobody's child (forked
/// twice), on the listener and the lock as fds 3 and 4.
fn spawn(listener: c_int, lock: c_int) bool {
var exe_buf: [4096:0]u8 = undefined;
const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), &exe_buf) catch return false;
exe_buf[n] = 0;
const argv = [_:null]?[*:0]const u8{ &exe_buf, "--daemon", null };
const first = libc.fork();
if (first < 0) return false;
if (first == 0) {
// Only async-signal-safe calls between fork and exec.
_ = libc.setsid();
if (libc.fork() != 0) libc._exit(0);
const l = libc.fcntl(listener, libc.F.DUPFD, @as(c_int, 10));
const k = libc.fcntl(lock, libc.F.DUPFD, @as(c_int, 10));
if (l < 0 or k < 0 or libc.dup2(l, 3) < 0 or libc.dup2(k, 4) < 0) libc._exit(127);
if (close_range(5, std.math.maxInt(c_uint), 0) != 0) {
var fd: c_int = 5;
while (fd < 1024) : (fd += 1) _ = libc.close(fd);
}
const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR }, @as(libc.mode_t, 0));
if (null_fd >= 0) for (0..3) |i| {
_ = libc.dup2(null_fd, @intCast(i));
};
if (null_fd > 4) _ = libc.close(null_fd);
_ = libc.chdir("/");
_ = libc.execve(&exe_buf, &argv, @ptrCast(libc.environ));
libc._exit(127);
}
var status: c_int = 0;
while (libc.waitpid(first, &status, 0) < 0 and libc.errno(-1) == .INTR) {}
return true;
}
/// Says who this session is. Its answer is not waited for: a daemon just
/// started is still being exec'd, and no startup waits on it. The reader
/// (`watch`) takes the `ok`, and only then is the session kept (`kept`).
fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool) bool {
var buf: [256]u8 = undefined;
const words = std.fmt.bufPrint(&buf, "hello {d} {t} {d} {s} {x} {s}", .{ version, k, pid, if (detached) "detached" else "attached", wire.semantics, named }) catch return false;
return send(fd, words, &.{});
}
// ---- the session's link, process-wide ----
/// This session's registration (`register`), which forkShell and the hosts
/// tell of their ptys; -1 with none (no daemon, or PARDES_DAEMON=off).
pub var link: c_int = -1;
/// The daemon said `ok` to the hello, and the link has not ended since;
/// `gone` once it has ended.
var up = std.atomic.Value(bool).init(false);
var gone = std.atomic.Value(bool).init(false);
/// What it is called (its 9P name).
var name_buf: [128]u8 = undefined;
var name_len: usize = 0;
var reader: ?std.Thread = null;
pub fn name() []const u8 {
return name_buf[0..name_len];
}
/// Whether a daemon keeps this session: what Detach, and a terminal's end,
/// need, or the session would be left where nothing can attach to it. A
/// daemon just started answers the hello once it runs, so this waits for
/// that answer (up to 2 s): never on a startup's path, only on those two.
pub fn kept() bool {
if (link < 0) return false;
var waited: u32 = 0;
while (!up.load(.acquire) and !gone.load(.acquire) and waited < 2000) : (waited += 1) sleepMs(1);
return up.load(.acquire);
}
/// The name a session goes by: its 9P socket's (`--9p=`, `--detach=`), else
/// its pid, as ninep_io.start names it.
fn setName(named: []const u8) void {
const n = if (named.len != 0)
std.fmt.bufPrint(&name_buf, "{s}", .{named[0..@min(named.len, name_buf.len)]}) catch unreachable
else
std.fmt.bufPrint(&name_buf, "{d}", .{@as(u32, @intCast(libc.getpid()))}) catch unreachable;
name_len = n.len;
}
/// Registers this session on `fd` (connected already, as a terminal's
/// stub does before it forks), or on a new connection when `fd` is null.
pub fn register(fd: ?c_int, k: Kind, named: []const u8, detached: bool) bool {
if (comptime !supported) return false;
setName(named);
const c = fd orelse connect(true) orelse return false;
startPending(true);
if (!hello(c, k, libc.getpid(), name(), detached)) {
_ = libc.close(c);
return false;
}
link = c;
return true;
}
fn tell(words: []const u8, fds: []const c_int) void {
if (link < 0) return;
_ = send(link, words, fds);
}
/// A shell forked on `master` (host_io.forkShell): the daemon keeps a dup.
pub fn pty(pid: libc.pid_t, master: c_int) void {
var buf: [32]u8 = undefined;
tell(std.fmt.bufPrint(&buf, "pty {d}", .{pid}) catch return, &.{master});
}
/// The pty of `pid` closed here: the daemon lets its dup go too.
pub fn closed(pid: libc.pid_t) void {
if (pid <= 0) return;
var buf: [32]u8 = undefined;
tell(std.fmt.bufPrint(&buf, "close {d}", .{pid}) catch return, &.{});
}
pub fn setState(detached: bool) void {
tell(if (detached) "state detached" else "state attached", &.{});
}
/// Asks for the masters of sessions that died holding them; they come back
/// as an `adopted` note.
pub fn adopt() void {
tell("adopt", &.{});
}
/// This session is about to exec another build (upgrade.zig): the daemon
/// is asked to move too. Its replica clients were told why they are let go
/// (replica.zig `Peers.refuseAll`).
pub fn upgraded() void {
tell("upgrade", &.{});
}
/// An upgraded session's link and stub as its old process left them: its
/// build's hello said again on the link (the daemon keeps its masters as
/// they were), and the stub's death a HUP again.
pub fn resumeLink(fd: c_int, stub_fd: c_int, k: Kind, named: []const u8, detached: bool) void {
if (comptime !supported) return;
stub = stub_fd;
if (stub >= 0) hupOnStubDeath(true);
setName(named);
if (fd >= 0 and hello(fd, k, libc.getpid(), name(), detached)) link = fd else if (fd >= 0) _ = libc.close(fd);
}
pub const Note = union(enum) {
/// A terminal for a detached tui session (`pardes --attach`), and the
/// stub's pipe; for a window session, both -1: open a window.
attach: struct { tty: c_int, stub: c_int },
adopted: struct { pids: [max_fds]libc.pid_t, fds: [max_fds]c_int, n: usize },
/// A replica's connection, its hello taken (src/replica.zig `Peers`),
/// and the view it joins again for, if it does.
replica: Joining,
};
pub const Joining = struct { fd: c_int, view: ?u8 = null };
/// Hands every note the daemon sends on to `deliver`, on a thread of its
/// own, until the link ends (`quit`). Called each loop: started once.
pub fn watch(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
if (link < 0 or reader != null) return;
reader = std.Thread.spawn(.{}, readNotes, .{ link, ctx, deliver }) catch null;
}
fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void {
var buf: [msg_max]u8 = undefined;
// The end of the link (a daemon gone, a hello refused): not kept.
defer {
up.store(false, .release);
gone.store(true, .release);
}
while (recv(fd, &buf)) |got| {
var words = std.mem.tokenizeScalar(u8, got.words, ' ');
const verb = words.next() orelse "";
if (std.mem.eql(u8, verb, "ok")) {
up.store(true, .release);
} else if (std.mem.eql(u8, verb, "attach")) {
deliver(ctx, .{ .attach = .{
.tty = if (got.nfds >= 2) got.fds[0] else -1,
.stub = if (got.nfds >= 2) got.fds[1] else -1,
} });
for (got.fds[@min(got.nfds, 2)..got.nfds]) |f| _ = libc.close(f);
} else if (std.mem.eql(u8, verb, "replica")) {
const view = std.fmt.parseInt(u8, words.next() orelse "", 10) catch null;
if (got.nfds >= 1) deliver(ctx, .{ .replica = .{ .fd = got.fds[0], .view = view } });
for (got.fds[@min(got.nfds, 1)..got.nfds]) |f| _ = libc.close(f);
} else if (std.mem.eql(u8, verb, "adopted")) {
var note: Note = .{ .adopted = .{ .pids = undefined, .fds = undefined, .n = 0 } };
const a = ¬e.adopted;
for (got.fds[0..got.nfds]) |f| {
const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch {
_ = libc.close(f);
continue;
};
a.pids[a.n] = pid;
a.fds[a.n] = f;
a.n += 1;
}
deliver(ctx, note);
} else for (got.fds[0..got.nfds]) |f| {
_ = libc.close(f);
}
}
}
/// `bytes` sent whole on a socket, never raising SIGPIPE: false when the
/// peer is gone.
pub fn writeAll(fd: c_int, bytes: []const u8) bool {
var at: usize = 0;
while (at < bytes.len) {
const n = libc.send(fd, bytes[at..].ptr, bytes.len - at, nosignal);
if (n < 0 and libc.errno(n) == .INTR) continue;
if (n <= 0) return false;
at += @intCast(n);
}
return true;
}
/// A replica's connection refused in words, and closed: by the daemon at
/// its hello, or by its session. A fresh connection's buffer is empty, so
/// this never blocks.
pub fn refuseReplica(fd: c_int, why: []const u8) void {
var out: [600]u8 = undefined;
if (wire.encodeServer(&out, .{ .refused = why[0..@min(why.len, 512)] })) |bytes| _ = writeAll(fd, bytes) else |_| {}
_ = libc.close(fd);
}
/// A session ended by a signal (TERM, HUP, INT): its shells go with it, as
/// at a quit. Async-signal-safe: one send. One killed outright (KILL) or
/// crashed says nothing, and its shells live on for an Adopt.
pub fn hangUp() void {
if (link >= 0) _ = send(link, "quit", &.{});
}
/// The session's end: its masters are let go (its shells hang up), the
/// link closed, the reader joined.
pub fn quit() void {
if (link < 0) return;
tell("quit", &.{});
_ = libc.shutdown(link, 2);
if (reader) |r| r.join();
reader = null;
_ = libc.close(link);
link = -1;
}
// ---- `pardes --attach`: a terminal, or a window, for a detached session ----
/// `other`: the session is the other kind (a window's for a terminal, or a
/// terminal's for a window), named so: joined as a replica client instead
/// (`replicaSocket`).
pub const Answer = union(enum) { ok: libc.pid_t, no: []const u8, other: []const u8 };
/// This machine's replica socket, which joins a session of either kind.
pub fn replicaSocket(buf: *[sun_path_len:0]u8) ?[:0]const u8 {
return place(buf, "pardes-replica.sock");
}
/// Asks the daemon to hand `fds` (a terminal and a stub's pipe, or none for
/// a window) to the detached session `named` (any one, when empty), and
/// answers how it went; the words are `buf`'s.
pub fn attach(k: Kind, named: []const u8, fds: []const c_int, buf: []u8) Answer {
const fd = connect(false) orelse return .{ .no = "no detached session is running" };
defer _ = libc.close(fd);
var line: [256]u8 = undefined;
const words = std.fmt.bufPrint(&line, "attach {t} {s}", .{ k, named }) catch return .{ .no = "that name is too long" };
if (!send(fd, words, fds) or !readable(fd, 2000)) return .{ .no = "the daemon does not answer" };
const got = recv(fd, buf) orelse return .{ .no = "the daemon hung up" };
for (got.fds[0..got.nfds]) |f| _ = libc.close(f);
if (std.mem.startsWith(u8, got.words, "ok ")) {
const pid = std.fmt.parseInt(libc.pid_t, got.words[3..], 10) catch return .{ .no = "the daemon answered nonsense" };
return .{ .ok = pid };
}
if (std.mem.startsWith(u8, got.words, "other ")) return .{ .other = got.words["other ".len..] };
return .{ .no = if (std.mem.startsWith(u8, got.words, "no ")) got.words[3..] else got.words };
}
/// The daemon's answer to `words` (`list`, `kill <name>`, `killall`), in
/// `buf`; null with no daemon running, or none answering.
pub fn ask(words: []const u8, buf: []u8) ?[]const u8 {
const fd = connect(false) orelse return null;
defer _ = libc.close(fd);
if (!send(fd, words, &.{}) or !readable(fd, 2000)) return null;
const got = recv(fd, buf) orelse return null;
for (got.fds[0..got.nfds]) |f| _ = libc.close(f);
return got.words;
}
// ---- a terminal's stub ----
var stub_child: libc.pid_t = 0;
fn forward(sig: posix.SIG) callconv(.c) void {
if (stub_child > 0) _ = libc.kill(stub_child, sig);
// The terminal's hangup: the session, told, carries on detached, and
// this job ends as a hung-up one does.
if (sig == .HUP) {
const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 };
posix.sigaction(.HUP, &default, null);
_ = libc.raise(.HUP);
}
}
/// The job the shell waits on, for a session that is not its child any
/// more (`pardes --attach`) or that it forked (`child`, reaped here): what
/// a terminal sends the job goes on to the session (its size, an end
/// asked for), and it ends when the session is gone from the terminal --
/// detached (`d<name>`), exited (`x<code>`, or the pipe's end and the
/// child's status), or refused (`r<why>`).
pub fn stubWait(session: libc.pid_t, child: bool, pipe: c_int) noreturn {
stub_child = session;
const on: posix.Sigaction = .{ .handler = .{ .handler = forward }, .mask = posix.sigemptyset(), .flags = posix.SA.RESTART };
for ([_]posix.SIG{ .WINCH, .TERM, .INT, .QUIT, .HUP }) |sig| posix.sigaction(sig, &on, null);
// Ctrl-Z is a key in the raw terminal (the pane's), as before; a TSTP
// sent here would stop the job under a session still drawing, so it is
// not taken.
const ignore: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.IGN }, .mask = posix.sigemptyset(), .flags = 0 };
posix.sigaction(.TSTP, &ignore, null);
var buf: [512]u8 = undefined;
var len: usize = 0;
while (len < buf.len) {
const n = libc.read(pipe, buf[len..].ptr, buf.len - len);
if (n < 0 and libc.errno(n) == .INTR) continue;
if (n <= 0) break;
len += @intCast(n);
}
const said = buf[0..len];
const out = std.Io.File.stderr();
const io = std.Io.Threaded.global_single_threaded.io();
if (said.len > 0 and said[0] == 'd') {
var text: [700]u8 = undefined;
const who = said[1..];
out.writeStreamingAll(io, std.fmt.bufPrint(&text, "pardes: detached from '{s}', which is still running; come back with `pardes --attach={s}`\n", .{ who, who }) catch "pardes: detached\n") catch {};
libc._exit(0);
}
if (said.len > 0 and said[0] == 'r') {
var text: [700]u8 = undefined;
out.writeStreamingAll(io, std.fmt.bufPrint(&text, "pardes: --attach: {s}\n", .{said[1..]}) catch "pardes: --attach refused\n") catch {};
libc._exit(1);
}
if (child) {
var status: c_int = 0;
while (libc.waitpid(session, &status, 0) < 0) {
if (libc.errno(-1) != .INTR) libc._exit(1);
}
const s: u32 = @bitCast(status);
if (libc.W.IFEXITED(s)) libc._exit(@intCast(libc.W.EXITSTATUS(s)));
if (libc.W.IFSIGNALED(s)) {
const sig = libc.W.TERMSIG(s);
const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 };
posix.sigaction(sig, &default, null);
_ = libc.raise(sig);
}
libc._exit(1);
}
if (said.len > 0 and said[0] == 'x') libc._exit(std.fmt.parseInt(u8, said[1..], 10) catch 1);
out.writeStreamingAll(io, "pardes: the session ended without a word\n") catch {};
libc._exit(1);
}
/// The session's half of its stub: what `stubWait` reads.
pub var stub: c_int = -1;
extern "c" fn procctl(idtype: c_int, id: i64, cmd: c_int, data: ?*anyopaque) c_int;
/// A HUP when this process's parent dies (a forked session's stub, an
/// --attach client's ssh), or no longer. Linux keeps it per thread: set and
/// cleared on the main one.
pub fn hupOnStubDeath(on: bool) void {
var sig: c_int = if (on) @backingInt(posix.SIG.HUP) else 0;
switch (builtin.os.tag) {
.linux => _ = std.os.linux.prctl(@backingInt(std.os.linux.PR.SET_PDEATHSIG), @intCast(sig), 0, 0, 0),
// procctl(P_PID, 0, PROC_PDEATHSIG_CTL, &sig)
.freebsd => _ = procctl(0, 0, 11, &sig),
else => {},
}
}
/// Detached: the stub is told (and goes), and the pipe let go. Its end is
/// no hangup now (hupOnStubDeath).
pub fn tellStubDetached() void {
if (stub < 0) return;
hupOnStubDeath(false);
tellStub(stub, "d{s}", .{name()});
stub = -1;
}
/// The session's end, `code` its exit status: the stub is told (and goes).
pub fn tellStubExit(code: u8) void {
tellStub(stub, "x{d}", .{code});
stub = -1;
}
/// The stub on `fd` told how its terminal's session went, what stubWait
/// reads, and its pipe let go: `d<name>` detached (one of a session's
/// several terminals, views.zig), `x<code>` exited, `r<why>` refused (an
/// attach that came too late).
pub fn tellStub(fd: c_int, comptime fmt: []const u8, args: anytype) void {
if (fd < 0) return;
var buf: [256]u8 = undefined;
const said = std.fmt.bufPrint(&buf, fmt, args) catch fmt[0..1];
_ = libc.write(fd, said.ptr, said.len);
_ = libc.close(fd);
}
/// `pardes` in a terminal: the session forked off as a process of its own,
/// in a session of its own (setsid), which is what lets it outlive the
/// terminal's job, and this process left as its stub (`stubWait`). Returns
/// in the session; null (nothing forked) when it cannot be done, and the
/// session then runs here, as before the daemon.
pub fn forkSession(conn: c_int) ?void {
var pipe: [2]c_int = undefined;
if (libc.pipe(&pipe) != 0) return null;
ninep_io.setCloexec(pipe[0]);
ninep_io.setCloexec(pipe[1]);
const parent = libc.getpid();
const pid = libc.fork();
if (pid < 0) {
_ = libc.close(pipe[0]);
_ = libc.close(pipe[1]);
return null;
}
if (pid == 0) {
_ = libc.close(pipe[0]);
_ = libc.setsid();
// The stub's death, however it comes (a SIGKILL too), is a HUP:
// the terminal's end, which the session's signal thread takes and
// detaches on. One already dead hangs up at once.
hupOnStubDeath(true);
if (libc.getppid() != parent) _ = libc.raise(.HUP);
stub = pipe[1];
// The listener and lock are the daemon's, which the stub starts.
startPending(false);
return {};
}
_ = libc.close(pipe[1]);
_ = libc.close(conn);
// Off the session's way: it is drawing already, its hello queued.
startPending(true);
stubWait(pid, true, pipe[0]);
}
// ---- the daemon ----
const Conn = struct {
fd: c_int = -1,
kind: ?Kind = null,
pid: libc.pid_t = 0,
detached: bool = false,
/// Its build's wire.semantics: a replica's must be the same.
semantics: u64 = 0,
/// `pardes --kill` asked its end: its shells go with it, not kept.
killed: bool = false,
name: [128]u8 = undefined,
name_len: usize = 0,
fn named(c: *const Conn) []const u8 {
return c.name[0..c.name_len];
}
};
const Held = struct {
fd: c_int = -1,
pid: libc.pid_t = 0,
/// The conn whose session holds it; null: that session died with it.
owner: ?u8 = null,
};
fn drop(h: *Held) void {
_ = libc.close(h.fd);
h.* = .{};
}
/// A replica's connection until its hello is whole: read no further than
/// the hello, so what follows it is the session's to read.
const Replica = struct {
fd: c_int = -1,
buf: [wire.hello_max]u8 = undefined,
len: usize = 0,
};
const Daemon = struct {
conns: [max_conns]Conn = @splat(.{}),
held: [max_held]Held = @splat(.{}),
replicas: [max_replicas]Replica = @splat(.{}),
/// A session asked it to move onto the build installed since (`reexec`).
upgrade_asked: bool = false,
fn idle(d: *const Daemon) bool {
for (d.conns) |c| if (c.fd >= 0) return false;
for (d.held) |h| if (h.fd >= 0) return false;
return true;
}
fn hangUp(d: *Daemon, i: u8) void {
const c = &d.conns[i];
const killed = c.killed;
_ = libc.close(c.fd);
c.* = .{};
// Whatever it still held, it died holding: kept for an Adopt, unless
// it was killed on purpose, when its shells hang up with it.
for (&d.held) |*h| if (h.fd >= 0 and h.owner == i) {
if (killed) drop(h) else h.owner = null;
};
}
/// `pardes --kill`: each session named (every one, for null) sent a
/// TERM and marked, its pids answered; the shells of none kept, for
/// all of them.
fn kill(d: *Daemon, i: u8, named: ?[]const u8) void {
var line: [msg_max]u8 = undefined;
var w: std.Io.Writer = .fixed(&line);
w.writeAll("ok") catch {};
var n: usize = 0;
for (&d.conns) |*s| if (s.fd >= 0 and s.kind != null) {
if (named) |want| if (!std.mem.eql(u8, s.named(), want)) continue;
s.killed = true;
_ = libc.kill(s.pid, .TERM);
w.print(" {d}", .{s.pid}) catch {};
n += 1;
};
if (named == null) {
for (&d.held) |*h| if (h.fd >= 0 and h.owner == null) drop(h);
} else if (n == 0) {
var why: [256]u8 = undefined;
return d.reply(i, std.fmt.bufPrint(&why, "no no session called '{s}'", .{named.?}) catch "no no such session", &.{});
}
d.reply(i, w.buffered(), &.{});
}
/// `pardes --ps`: a line a session (pid, kind, state, name), a line
/// for each shell it holds after it, then the shells nobody holds.
/// ponytail: one message, so a registry past msg_max is cut short.
fn list(d: *Daemon, i: u8) void {
var line: [msg_max]u8 = undefined;
var w: std.Io.Writer = .fixed(&line);
w.print("daemon {d}\n", .{libc.getpid()}) catch {};
for (&d.conns, 0..) |*s, k| if (s.fd >= 0 and s.kind != null) {
w.print("session {d} {t} {s} {s}\n", .{ s.pid, s.kind.?, if (s.detached) "detached" else "attached", s.named() }) catch break;
for (d.held) |h| if (h.fd >= 0 and h.owner == @as(u8, @intCast(k))) w.print("shell {d}\n", .{h.pid}) catch break;
};
for (d.held) |h| if (h.fd >= 0 and h.owner == null) w.print("orphan {d}\n", .{h.pid}) catch break;
d.reply(i, w.buffered(), &.{});
}
fn reply(d: *Daemon, i: u8, words: []const u8, fds: []const c_int) void {
if (!send(d.conns[i].fd, words, fds)) d.hangUp(i);
}
fn take(d: *Daemon, i: u8, got: Got) void {
var fds_used: usize = 0;
defer for (got.fds[fds_used..got.nfds]) |f| {
_ = libc.close(f);
};
const c = &d.conns[i];
var words = std.mem.tokenizeScalar(u8, got.words, ' ');
const verb = words.next() orelse return;
if (std.mem.eql(u8, verb, "hello")) {
const v = std.fmt.parseInt(u32, words.next() orelse "", 10) catch 0;
const k = std.meta.stringToEnum(Kind, words.next() orelse "");
const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch 0;
const state = words.next() orelse "";
const semantics = std.fmt.parseInt(u64, words.next() orelse "", 16) catch 0;
const rest = std.mem.trim(u8, words.rest(), " ");
if (v != version or k == null or pid <= 0) {
// Another build's: it runs without a daemon.
d.reply(i, "version " ++ std.fmt.comptimePrint("{d}", .{version}), &.{});
return if (d.conns[i].fd >= 0) d.hangUp(i);
}
c.kind = k;
c.pid = pid;
c.detached = std.mem.eql(u8, state, "detached");
c.semantics = semantics;
c.name_len = @min(rest.len, c.name.len);
@memcpy(c.name[0..c.name_len], rest[0..c.name_len]);
return d.reply(i, "ok", &.{});
}
if (std.mem.eql(u8, verb, "state")) {
c.detached = std.mem.eql(u8, words.next() orelse "", "detached");
return;
}
if (std.mem.eql(u8, verb, "pty")) {
const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch return;
if (got.nfds < 1) return;
for (&d.held) |*h| if (h.fd < 0) {
h.* = .{ .fd = got.fds[0], .pid = pid, .owner = i };
fds_used = 1;
return;
};
return;
}
if (std.mem.eql(u8, verb, "close")) {
const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch return;
for (&d.held) |*h| if (h.fd >= 0 and h.pid == pid and h.owner == i) drop(h);
return;
}
if (std.mem.eql(u8, verb, "quit")) {
for (&d.held) |*h| if (h.fd >= 0 and h.owner == i) drop(h);
return;
}
if (std.mem.eql(u8, verb, "upgrade")) {
d.upgrade_asked = true;
return;
}
if (std.mem.eql(u8, verb, "list")) return d.list(i);
if (std.mem.eql(u8, verb, "kill")) return d.kill(i, std.mem.trim(u8, words.rest(), " "));
if (std.mem.eql(u8, verb, "killall")) return d.kill(i, null);
if (std.mem.eql(u8, verb, "adopt")) {
var line: [msg_max]u8 = undefined;
var w: std.Io.Writer = .fixed(&line);
w.writeAll("adopted") catch {};
var fds: [max_fds]c_int = undefined;
var given: [max_fds]*Held = undefined;
var n: usize = 0;
for (&d.held) |*h| if (h.fd >= 0 and h.owner == null and n < max_fds) {
w.print(" {d}", .{h.pid}) catch break;
fds[n] = h.fd;
given[n] = h;
n += 1;
};
if (!send(c.fd, w.buffered(), fds[0..n])) return d.hangUp(i);
for (given[0..n]) |h| h.owner = i;
return;
}
if (std.mem.eql(u8, verb, "attach")) {
const k = std.meta.stringToEnum(Kind, words.next() orelse "") orelse return d.reply(i, "no bad attach", &.{});
const wanted_name = std.mem.trim(u8, words.rest(), " ");
var why: [512]u8 = undefined;
// "other <name>": the client joins it through the replica socket.
const target = d.find(k, wanted_name, &why) orelse return d.reply(i, std.mem.sliceTo(&why, 0), &.{});
const t = &d.conns[target];
if (!send(t.fd, "attach", got.fds[0..got.nfds])) {
d.hangUp(target);
return d.reply(i, "no that session does not answer", &.{});
}
t.detached = false;
var line: [32]u8 = undefined;
return d.reply(i, std.fmt.bufPrint(&line, "ok {d}", .{t.pid}) catch "ok 0", &.{});
}
}
/// The detached session of kind `k` called `wanted_name`, or the one
/// there is when it is empty; else null, and why not in `why`
/// (0-terminated): "other <its name>" for one of the other kind.
fn find(d: *Daemon, k: Kind, wanted_name: []const u8, why: *[512]u8) ?u8 {
@memset(why, 0);
const other: []const u8 = switch (k) {
.tty => "a window: attach it with `pardes-gui --attach",
.gui => "a terminal session: attach it with `pardes --attach",
};
if (wanted_name.len != 0) {
for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.kind != null and std.mem.eql(u8, s.named(), wanted_name)) {
if (s.kind.? != k) {
_ = std.fmt.bufPrint(why, "other {s}", .{wanted_name}) catch {};
return null;
}
// Attached already: the session takes another view.
return @as(u8, @intCast(i));
};
_ = std.fmt.bufPrint(why, "no no session called '{s}'", .{wanted_name}) catch {};
return null;
}
var found: ?u8 = null;
var count: usize = 0;
var others: usize = 0;
var w: std.Io.Writer = .fixed(why[0 .. why.len - 1]);
for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.detached and s.kind != null) {
if (s.kind.? != k) {
others += 1;
continue;
}
count += 1;
found = @intCast(i);
};
if (count == 1) return found.?;
// None detached: the one session there is, as another view of it.
if (count == 0) {
for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.kind == k) {
count += 1;
found = @intCast(i);
};
if (count == 1) return found.?;
count = 0;
// None of this kind at all: the one session there is, the other kind's.
var only: ?*Conn = null;
var sessions: usize = 0;
for (&d.conns) |*s| if (s.fd >= 0 and s.kind != null) {
sessions += 1;
only = s;
};
if (found == null and sessions == 1) {
_ = std.fmt.bufPrint(why, "other {s}", .{only.?.named()}) catch {};
return null;
}
}
if (count == 0 and others == 0) {
w.writeAll("no no detached session is running") catch {};
return null;
}
if (count == 0) {
w.print("no the detached session{s} running {s} {s}=<name>`", .{ if (others == 1) " is" else "s are", if (others == 1) "is" else "are each", other }) catch {};
return null;
}
w.print("no {d} detached sessions are running; say which with --attach=<name>:", .{count}) catch {};
for (&d.conns) |*s| if (s.fd >= 0 and s.detached and s.kind == k) {
w.print(" {s}", .{s.named()}) catch {};
};
return null;
}
/// More of a replica's hello; once it is whole, the connection refused
/// in words or handed to its session.
fn hear(d: *Daemon, r: *Replica) void {
const want = if (r.len < wire.header_len) wire.header_len else wire.header_len + @as(usize, std.mem.readInt(u32, r.buf[1..5], .little));
if (want > r.buf.len) return refuse(r, "the first message is not a hello");
const n = libc.read(r.fd, r.buf[r.len..want].ptr, want - r.len);
if (n < 0 and libc.errno(n) == .INTR) return;
if (n <= 0) {
_ = libc.close(r.fd);
r.* = .{};
return;
}
r.len += @intCast(n);
if (r.len < wire.header_len or r.len < wire.header_len + std.mem.readInt(u32, r.buf[1..5], .little)) return;
const f = (wire.framed(r.buf[0..r.len]) catch null) orelse return refuse(r, "the first message is not a hello");
if (f.tag != @backingInt(wire.ClientTag.hello)) return refuse(r, "the first message is not a hello");
var why: [512]u8 = undefined;
const v = wire.helloVersion(f.payload) catch 0;
if (v != wire.version) return refuse(r, std.fmt.bufPrint(&why, "this client speaks replica protocol {d}, and this daemon {d}: run the same pardes at both ends", .{ v, wire.version }) catch "another protocol");
const h = (wire.decodeClient(f.tag, f.payload) catch return refuse(r, "a malformed hello")).hello;
const target = for (&d.conns, 0..) |*c, i| {
if (c.fd >= 0 and c.kind != null and std.mem.eql(u8, c.named(), h.session)) break i;
} else return refuse(r, std.fmt.bufPrint(&why, "no session called '{s}'", .{h.session}) catch "no such session");
const t = &d.conns[target];
if (t.semantics != h.semantics) return refuse(r, std.fmt.bufPrint(&why, "session '{s}' runs another build of pardes (semantics {x:0>16}, this client's {x:0>16}): a replica needs the same build at both ends, as `pardes --version` shows", .{ h.session, t.semantics, h.semantics }) catch "another build");
var words: [16]u8 = undefined;
const note = if (h.view) |k| std.fmt.bufPrint(&words, "replica {d}", .{k}) catch unreachable else "replica";
if (!send(t.fd, note, &.{r.fd})) {
d.hangUp(@intCast(target));
return refuse(r, "that session does not answer");
}
log.info("a replica handed to '{s}'", .{h.session});
_ = libc.close(r.fd);
r.* = .{};
}
fn refuse(r: *Replica, why: []const u8) void {
refuseReplica(r.fd, why);
r.* = .{};
}
fn acceptReplica(d: *Daemon, listener: c_int) void {
const fd = libc.accept4(listener, null, null, libc.SOCK.CLOEXEC);
if (fd < 0) return;
for (&d.replicas) |*r| if (r.fd < 0) {
r.* = .{ .fd = fd };
return;
};
_ = libc.close(fd);
}
/// Upgrade: this daemon exec'd as the pardes now at the path it was
/// started from, on the same listeners and lock, every session's link
/// and every master kept open, its registry on the new command line
/// (`restore`). A replica whose hello is still on its way is let go: it
/// dials again. Returns when it cannot be done, as it was.
fn reexec(d: *Daemon, replicas: c_int) void {
const path = upgrade.exe() orelse return;
var why: [700]u8 = undefined;
switch (upgrade.check(path, &why)) {
.no => |w| return log.warn("{s}", .{w}),
.ok => {},
}
var text: [flag_room]u8 = undefined;
var w: std.Io.Writer = .fixed(&text);
w.print("{s}replicas {d}\n", .{ upgrade.flag, replicas }) catch return;
for (&d.conns, 0..) |*c, i| if (c.fd >= 0) {
const k: []const u8 = if (c.kind) |k| @tagName(k) else "-";
w.print("c {d} {d} {s} {d} {d} {x} {s}\n", .{ i, c.fd, k, c.pid, @intFromBool(c.detached), c.semantics, c.named() }) catch return;
};
for (&d.held) |*h| if (h.fd >= 0) {
w.print("h {d} {d} {d}\n", .{ h.fd, h.pid, h.owner orelse 255 }) catch return;
};
w.writeByte(0) catch return;
for (&d.replicas) |*r| if (r.fd >= 0) {
_ = libc.close(r.fd);
r.* = .{};
};
const keep = struct {
fn all(dd: *Daemon, rep: c_int, on: bool) void {
const v: c_int = if (on) 0 else 1;
for ([_]c_int{ 3, 4, rep }) |fd| if (fd >= 0) {
_ = libc.fcntl(fd, libc.F.SETFD, v);
};
for (&dd.conns) |*c| if (c.fd >= 0) {
_ = libc.fcntl(c.fd, libc.F.SETFD, v);
};
for (&dd.held) |*h| if (h.fd >= 0) {
_ = libc.fcntl(h.fd, libc.F.SETFD, v);
};
}
}.all;
const argv = [_:null]?[*:0]const u8{ path, "--daemon", @ptrCast(&text), null };
keep(d, replicas, true);
_ = libc.execve(path, &argv, @ptrCast(libc.environ));
keep(d, replicas, false);
log.warn("upgrade: {s} would not start", .{path});
}
/// The registry an upgraded daemon was exec'd with (`reexec`); the
/// replicas' listener, its fd, or -1.
fn restore(d: *Daemon, text: []const u8) c_int {
var replicas: c_int = -1;
var lines = std.mem.splitScalar(u8, text, '\n');
while (lines.next()) |line| {
var words = std.mem.tokenizeScalar(u8, line, ' ');
const what = words.next() orelse continue;
if (std.mem.eql(u8, what, "replicas")) {
replicas = std.fmt.parseInt(c_int, words.next() orelse "", 10) catch -1;
if (replicas >= 0) ninep_io.setCloexec(replicas);
} else if (std.mem.eql(u8, what, "c")) {
const i = std.fmt.parseInt(u8, words.next() orelse "", 10) catch continue;
const fd = std.fmt.parseInt(c_int, words.next() orelse "", 10) catch continue;
if (i >= max_conns) continue;
const k = std.meta.stringToEnum(Kind, words.next() orelse "");
const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch 0;
const detached = std.mem.eql(u8, words.next() orelse "", "1");
const semantics = std.fmt.parseInt(u64, words.next() orelse "", 16) catch 0;
const rest = std.mem.trim(u8, words.rest(), " ");
ninep_io.setCloexec(fd);
const c = &d.conns[i];
c.* = .{ .fd = fd, .kind = k, .pid = pid, .detached = detached, .semantics = semantics };
c.name_len = @min(rest.len, c.name.len);
@memcpy(c.name[0..c.name_len], rest[0..c.name_len]);
} else if (std.mem.eql(u8, what, "h")) {
const fd = std.fmt.parseInt(c_int, words.next() orelse "", 10) catch continue;
const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch 0;
const owner = std.fmt.parseInt(u8, words.next() orelse "", 10) catch 255;
ninep_io.setCloexec(fd);
for (&d.held) |*h| if (h.fd < 0) {
h.* = .{ .fd = fd, .pid = pid, .owner = if (owner < max_conns) owner else null };
break;
};
}
}
return replicas;
}
fn accept(d: *Daemon, listener: c_int) void {
const fd = libc.accept4(listener, null, null, libc.SOCK.CLOEXEC);
if (fd < 0) return;
for (&d.conns) |*c| if (c.fd < 0) {
c.* = .{ .fd = fd };
return;
};
_ = libc.close(fd);
}
};
/// The replicas' stream socket, bound and listening; -1 when it cannot be
/// (a runtime directory too long for a socket's path: 104 bytes on FreeBSD).
/// Ours to replace: the daemon's lock is held.
fn listenReplicas() c_int {
var sock_buf: [sun_path_len:0]u8 = undefined;
const sock = place(&sock_buf, "pardes-replica.sock") orelse return -1;
_ = libc.unlink(sock);
const fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0);
if (fd < 0) return -1;
const addr = address(sock);
if (libc.bind(fd, @ptrCast(&addr), @sizeOf(libc.sockaddr.un)) == 0 and libc.chmod(sock, 0o600) == 0 and libc.listen(fd, max_replicas) == 0) return fd;
_ = libc.close(fd);
return -1;
}
/// Room for an upgrade's registry on a command line (`reexec`): every
/// connection and master, each a line.
const flag_room = 64 * 1024;
/// `pardes --daemon`: what `spawn` started, on the listener (fd 3) and the
/// lock (fd 4), or (`state`) an upgrade of one, its registry. Returns only
/// to exit, idle.
pub fn serve(state: ?[]const u8) noreturn {
const listener: c_int = 3;
ninep_io.setCloexec(3);
ninep_io.setCloexec(4);
const ignore: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.IGN }, .mask = posix.sigemptyset(), .flags = 0 };
for ([_]posix.SIG{ .PIPE, .HUP, .INT }) |sig| posix.sigaction(sig, &ignore, null);
upgrade.locate();
var d: Daemon = .{};
const given = if (state) |text| d.restore(text) else -1;
const replicas = if (given >= 0) given else listenReplicas();
// Every slot in its own place, an empty one's fd -1: poll passes over
// a negative fd.
var fds: [2 + max_conns + max_replicas + max_held]libc.pollfd = undefined;
const conns = fds[2..][0..max_conns];
const held = fds[2 + max_conns ..][0..max_held];
const reps = fds[2 + max_conns + max_held ..][0..max_replicas];
var buf: [msg_max]u8 = undefined;
while (true) {
fds[0] = .{ .fd = listener, .events = libc.POLL.IN, .revents = 0 };
fds[1] = .{ .fd = replicas, .events = libc.POLL.IN, .revents = 0 };
for (conns, &d.conns) |*pfd, *c| pfd.* = .{ .fd = c.fd, .events = libc.POLL.IN, .revents = 0 };
for (reps, &d.replicas) |*pfd, *r| pfd.* = .{ .fd = r.fd, .events = libc.POLL.IN, .revents = 0 };
// No events asked of a master: its hangup (every slave closed, the
// shell and all it ran gone) is reported anyway, and its output is
// the session's to read, never this one's.
for (held, &d.held) |*pfd, *h| pfd.* = .{ .fd = h.fd, .events = 0, .revents = 0 };
const idle = d.idle();
const ready = libc.poll(&fds, fds.len, if (idle) linger_ms else -1);
if (ready < 0) {
if (libc.errno(ready) == .INTR) continue;
break;
}
if (ready == 0) {
if (!idle) continue;
// Idle for the whole linger: one last look for a connection
// just made, then the socket goes, then this process (and its
// lock with it).
if (readable(listener, 0)) {
d.accept(listener);
continue;
}
break;
}
if (fds[0].revents & libc.POLL.IN != 0) d.accept(listener);
if (fds[1].revents & libc.POLL.IN != 0) d.acceptReplica(replicas);
// A slot an earlier handler emptied or filled again is passed over.
for (reps, &d.replicas) |pfd, *r| if (pfd.revents != 0 and r.fd == pfd.fd) d.hear(r);
for (conns, 0..) |pfd, i| {
if (pfd.revents == 0 or d.conns[i].fd != pfd.fd) continue;
const got = recv(pfd.fd, &buf) orelse {
d.hangUp(@intCast(i));
continue;
};
d.take(@intCast(i), got);
}
for (held, &d.held) |pfd, *h| if (pfd.revents != 0 and h.fd == pfd.fd) drop(h);
if (d.upgrade_asked) {
d.upgrade_asked = false;
d.reexec(replicas);
}
}
var sock_buf: [sun_path_len:0]u8 = undefined;
_ = libc.close(listener);
if (place(&sock_buf, "pardes-daemon.sock")) |sock| _ = libc.unlink(sock);
if (replicas >= 0) {
if (place(&sock_buf, "pardes-replica.sock")) |sock| _ = libc.unlink(sock);
}
libc._exit(0);
}
test "a message carries its words and its fds, and the peer's end is null" {
if (comptime !supported) return error.SkipZigTest;
var pair: [2]c_int = undefined;
try std.testing.expectEqual(@as(c_int, 0), libc.socketpair(libc.AF.UNIX, libc.SOCK.SEQPACKET | libc.SOCK.CLOEXEC, 0, &pair));
defer _ = libc.close(pair[0]);
var pipe: [2]c_int = undefined;
try std.testing.expectEqual(@as(c_int, 0), libc.pipe(&pipe));
defer _ = libc.close(pipe[0]);
try std.testing.expect(send(pair[1], "pty 42", &.{pipe[1]}));
_ = libc.close(pipe[1]);
var buf: [64]u8 = undefined;
const got = recv(pair[0], &buf).?;
try std.testing.expectEqualStrings("pty 42", got.words);
try std.testing.expectEqual(@as(usize, 1), got.nfds);
// The fd that came is the pipe's write end: what goes in comes out.
try std.testing.expectEqual(@as(isize, 1), libc.write(got.fds[0], "z", 1));
_ = libc.close(got.fds[0]);
var one: [1]u8 = undefined;
try std.testing.expectEqual(@as(isize, 1), libc.read(pipe[0], &one, 1));
_ = libc.close(pair[1]);
try std.testing.expect(recv(pair[0], &buf) == null);
}
|