summaryrefslogtreecommitdiff
path: root/src/daemon.zig
blob: ac9e6eb4a04479d84248375d93ff7b202368945b (plain) (blame)
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
//! 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).
const std = @import("std");
const builtin = @import("builtin");
const libc = std.c;
const posix = std.posix;
const ninep_io = @import("9p_io.zig");

pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd;
const version = 1;
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;
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));
}

pub 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;
    }
}

pub 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.
pub 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} {s}", .{ version, k, pid, if (detached) "detached" else "attached", 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.
pub 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", &.{});
}

pub const Note = union(enum) {
    /// A terminal for a detached tty 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 },
};

/// 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, "adopted")) {
            var note: Note = .{ .adopted = .{ .pids = undefined, .fds = undefined, .n = 0 } };
            const a = &note.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);
        }
    }
}

/// 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 ----

pub const Answer = union(enum) { ok: libc.pid_t, no: []const u8 };

/// 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 };
    }
    return .{ .no = if (std.mem.startsWith(u8, got.words, "no ")) got.words[3..] else 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), or no
/// longer. Linux keeps it per thread: set and cleared on the main one.
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);
    tellDetached(stub);
    stub = -1;
}

/// The stub on `fd` told its terminal is detached (one of a session's
/// several, views.zig), and the pipe let go.
pub fn tellDetached(fd: c_int) void {
    if (fd < 0) return;
    var buf: [160]u8 = undefined;
    const said = std.fmt.bufPrint(&buf, "d{s}", .{name()}) catch "d";
    _ = libc.write(fd, said.ptr, said.len);
    _ = libc.close(fd);
}

/// The session's end, `code` its exit status: the stub is told (and goes).
pub fn tellStubExit(code: u8) void {
    tellExit(stub, code);
    stub = -1;
}

pub fn tellExit(fd: c_int, code: u8) void {
    if (fd < 0) return;
    var buf: [8]u8 = undefined;
    const said = std.fmt.bufPrint(&buf, "x{d}", .{code}) catch "x1";
    _ = libc.write(fd, said.ptr, said.len);
    _ = libc.close(fd);
}

/// A terminal refused (an attach that came too late): its stub is told why.
pub fn refuseStub(fd: c_int, why: []const u8) void {
    var buf: [256]u8 = undefined;
    const said = std.fmt.bufPrint(&buf, "r{s}", .{why}) catch "r";
    _ = 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,
    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,
};

const Daemon = struct {
    conns: [max_conns]Conn = @splat(.{}),
    held: [max_held]Held = @splat(.{}),

    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 drop(d: *Daemon, h: *Held) void {
        _ = d;
        _ = libc.close(h.fd);
        h.* = .{};
    }

    fn hangUp(d: *Daemon, i: u8) void {
        const c = &d.conns[i];
        _ = libc.close(c.fd);
        c.* = .{};
        // Whatever it still held, it died holding: kept for an Adopt.
        for (&d.held) |*h| if (h.fd >= 0 and h.owner == i) {
            h.owner = null;
        };
    }

    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 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.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) d.drop(h);
            return;
        }
        if (std.mem.eql(u8, verb, "quit")) {
            for (&d.held) |*h| if (h.fd >= 0 and h.owner == i) d.drop(h);
            return;
        }
        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;
            const target = d.find(k, wanted_name, &why) catch |err| return d.reply(i, switch (err) {
                error.Said => 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 why not, in `why` (0-terminated).
    fn find(d: *Daemon, k: Kind, wanted_name: []const u8, why: *[512]u8) error{Said}!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, "no '{s}' is {s}={s}`", .{ wanted_name, other, wanted_name }) catch {};
                    return error.Said;
                }
                // Attached already: the session takes another view.
                return @intCast(i);
            };
            _ = std.fmt.bufPrint(why, "no no session called '{s}'", .{wanted_name}) catch {};
            return error.Said;
        }
        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;
        }
        if (count == 0 and others == 0) {
            w.writeAll("no no detached session is running") catch {};
            return error.Said;
        }
        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 error.Said;
        }
        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 error.Said;
    }

    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);
    }
};

/// `pardes --daemon`: what `spawn` started, on the listener (fd 3) and the
/// lock (fd 4). Returns only to exit, idle.
pub fn serve() 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);
    var d: Daemon = .{};
    const slots = 1 + max_conns + max_held;
    var fds: [slots]libc.pollfd = undefined;
    var conn_of: [slots]u8 = undefined;
    var held_of: [slots]u16 = undefined;
    var buf: [msg_max]u8 = undefined;
    while (true) {
        var n: usize = 0;
        fds[n] = .{ .fd = listener, .events = libc.POLL.IN, .revents = 0 };
        n += 1;
        const conns_at = n;
        for (&d.conns, 0..) |*c, i| if (c.fd >= 0) {
            fds[n] = .{ .fd = c.fd, .events = libc.POLL.IN, .revents = 0 };
            conn_of[n] = @intCast(i);
            n += 1;
        };
        const held_at = n;
        // 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 (&d.held, 0..) |*h, i| if (h.fd >= 0) {
            fds[n] = .{ .fd = h.fd, .events = 0, .revents = 0 };
            held_of[n] = @intCast(i);
            n += 1;
        };
        const idle = d.idle();
        const ready = libc.poll(&fds, @intCast(n), 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);
        for (fds[conns_at..held_at], conn_of[conns_at..held_at]) |pfd, i| {
            if (pfd.revents == 0 or d.conns[i].fd != pfd.fd) continue;
            const got = recv(pfd.fd, &buf) orelse {
                d.hangUp(i);
                continue;
            };
            d.take(i, got);
        }
        for (fds[held_at..n], held_of[held_at..n]) |pfd, i| {
            if (pfd.revents == 0 or d.held[i].fd != pfd.fd) continue;
            d.drop(&d.held[i]);
        }
    }
    var sock_buf: [sun_path_len:0]u8 = undefined;
    _ = libc.close(listener);
    if (place(&sock_buf, "pardes-daemon.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);
}