// Copyright (c) Tailscale Inc & contributors // SPDX-License-Identifier: BSD-3-Clause //go:build (darwin && !ios) || freebsd package tailssh import ( "golang.org/x/sys/unix" ) // exitWatcher learns session children's wait statuses without reaping // them, so a terminated session's exit can be reported while its leader // stays unreaped until group SIGKILL. // // It registers an EVFILT_PROC NOTE_EXIT filter per child on a kqueue, // which the kernel triggers at exit with the wait status in the event // data. The monitor loop wakes on the child's SIGCHLD, posted after the // NOTE_EXIT event, and drains the kqueue without blocking from // [monitor.sweep], so no goroutine reads it. // // The zero value is ready to use. The kqueue is created on first use. type exitWatcher struct { kq int // kqueue descriptor, valid if open open bool // kq is open failed bool // kqueue creation failed; watch nothing } // watch registers for pid's exit. Failure leaves pid to be reported // when it is reaped. func (w *exitWatcher) watch(pid int) { if !w.open { if w.failed { return } kq, err := unix.Kqueue() if err != nil { w.failed = true return } unix.CloseOnExec(kq) w.kq, w.open = kq, true } ev := unix.Kevent_t{ Ident: uint64(pid), Filter: unix.EVFILT_PROC, Flags: unix.EV_ADD | unix.EV_ONESHOT, Fflags: noteExitFflags, } // ESRCH means pid is already gone, so it is reaped and reported // by the next sweep. unix.Kevent(w.kq, []unix.Kevent_t{ev}, nil, nil) } // drain records the wait status of each exited child in children // without blocking. Events for pids not in children, already reaped, // are discarded. func (w *exitWatcher) drain(children map[int]*monChild) { if !w.open { return } var evs [16]unix.Kevent_t var zero unix.Timespec for { n, err := unix.Kevent(w.kq, nil, evs[:], &zero) if err != nil || n <= 0 { return } for _, ev := range evs[:n] { // On macOS, Data holds the wait status only if the event // reports NOTE_EXITSTATUS. if ev.Filter != unix.EVFILT_PROC || ev.Fflags¬eExitFflags != noteExitFflags || ev.Flags&unix.EV_ERROR != 0 { continue } if c, ok := children[int(ev.Ident)]; ok { c.exitWS, c.exited = unix.WaitStatus(ev.Data), true } } if n < len(evs) { return } } } // close releases the kqueue. func (w *exitWatcher) close() { if w.open { unix.Close(w.kq) w.open = false } } // zombieWaitStatus reports false. These platforms learn exit statuses // from [exitWatcher] instead. func zombieWaitStatus(pid int) (ws unix.WaitStatus, ok bool) { return 0, false }