//go:build linux package thin import ( "context" "errors" "fmt" "os" "os/signal" "path/filepath" "strconv" "sync/atomic" "testing" "time" "unsafe" "golang.org/x/sys/unix" ) // Adversaries a sandbox may run against the pause (Astra task 9 round 1, // F1 and F4). The pause does not stop them; the copy must then refuse with // busy, by its check that nothing it read changed while it was made. // // The helpers run as this test binary, started inside the test's sandbox // with EQUIPO_WORKSNAP_HELPER naming one; init runs them before any test. func init() { switch os.Getenv("EQUIPO_WORKSNAP_HELPER") { case "": return case "selfcont": helperSelfCont(os.Getenv("FILE"), filepath.SplitList(os.Getenv("WATCH"))) case "uring": helperURing(os.Getenv("FILE"), os.Getenv("READY")) } os.Exit(2) } // helperSelfCont resumes itself, two ways, while it overwrites FILE (same // size, a new count) about every 200 microseconds. A POSIX timer sends it // SIGCONT every millisecond; since Linux 6.13 that timer re-arms only when // its signal is delivered, so a SIGSTOP that flushes a pending SIGCONT // (as stop signals do) ends it, and the pause wins. So an inotify // descriptor on the watch directories also has the kernel send it // SIGCONT (O_ASYNC, F_SETSIG) whenever anything there is opened or read: // the copy itself. It handles SIGCONT, which is ignored by default and // parked. func helperSelfCont(file string, watch []string) { signal.Notify(make(chan os.Signal, 1), unix.SIGCONT) ino, err := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK) if err != nil { os.Exit(7) } for _, dir := range append(watch, filepath.Dir(file)) { if _, err := unix.InotifyAddWatch(ino, dir, unix.IN_OPEN|unix.IN_ACCESS); err != nil { os.Exit(7) } } if _, err := unix.FcntlInt(uintptr(ino), unix.F_SETOWN, os.Getpid()); err != nil { os.Exit(7) } if _, err := unix.FcntlInt(uintptr(ino), unix.F_SETSIG, int(unix.SIGCONT)); err != nil { os.Exit(7) } if _, err := unix.FcntlInt(uintptr(ino), unix.F_SETFL, unix.O_ASYNC|unix.O_NONBLOCK); err != nil { os.Exit(7) } var ev [64]byte // struct sigevent: value (8), signo (4), notify (4: SIGEV_SIGNAL = 0) *(*int32)(unsafe.Pointer(&ev[8])) = int32(unix.SIGCONT) var id int32 if _, _, e := unix.Syscall(unix.SYS_TIMER_CREATE, uintptr(unix.CLOCK_MONOTONIC), uintptr(unsafe.Pointer(&ev[0])), uintptr(unsafe.Pointer(&id))); e != 0 { os.Exit(3) } spec := [4]int64{0, 1_000_000, 0, 1_000_000} // interval, value if _, _, e := unix.Syscall6(unix.SYS_TIMER_SETTIME, uintptr(id), 0, uintptr(unsafe.Pointer(&spec[0])), 0, 0, 0); e != 0 { os.Exit(4) } f, err := os.OpenFile(file, os.O_WRONLY, 0) if err != nil { os.Exit(5) } events := make([]byte, 4096) for i := 0; ; i++ { f.WriteAt([]byte(fmt.Sprintf("%08d", i%100000000)), 0) // Drained, so the queue never overflows and each access queues // an event (and its signal) of its own. for { if n, err := unix.Read(ino, events); n <= 0 || err != nil { break } } time.Sleep(200 * time.Microsecond) } } // io_uring, by raw system calls (golang.org/x/sys has no ring types). type uringParams struct { sqEntries, cqEntries, flags, sqThreadCPU, sqThreadIdle, features, wqFd uint32 resv [3]uint32 sq struct { head, tail, ringMask, ringEntries, flags, dropped, array, resv1 uint32 userAddr uint64 } cq struct { head, tail, ringMask, ringEntries, overflow, cqes, flags, resv1 uint32 userAddr uint64 } } type uringSQE struct { opcode, flags uint8 ioprio uint16 fd int32 off, addr uint64 len, rwFlags uint32 userData uint64 bufIndex, personality uint16 spliceFdIn int32 addr3, pad uint64 } const ( uringOpWrite = 23 uringSQELink = 1 << 2 uringSQEAsync = 1 << 4 uringGetEvents = 1 uringChain = 128 uringBlock = 64 << 10 ) // helperURing writes READY ("ok" or "unavailable"), then keeps submitting // chains of linked asynchronous O_DSYNC overwrites of FILE's first 64 KiB // (its size never changes) and waiting for each: work the kernel's io-wq // workers carry on with after the submitting thread stops. func helperURing(file, ready string) { say := func(s string) { os.WriteFile(ready, []byte(s), 0o600) } var p uringParams ring, _, e := unix.Syscall(unix.SYS_IO_URING_SETUP, uringChain, uintptr(unsafe.Pointer(&p)), 0) if e != 0 { say("unavailable: io_uring_setup: " + e.Error()) select {} } fd := int(ring) sqRing, err1 := unix.Mmap(fd, 0, int(p.sq.array+p.sqEntries*4), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED|unix.MAP_POPULATE) cqRing, err2 := unix.Mmap(fd, 0x8000000, int(p.cq.cqes+p.cqEntries*16), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED|unix.MAP_POPULATE) sqes, err3 := unix.Mmap(fd, 0x10000000, int(p.sqEntries)*int(unsafe.Sizeof(uringSQE{})), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED|unix.MAP_POPULATE) target, err4 := unix.Open(file, unix.O_WRONLY|unix.O_DSYNC|unix.O_CLOEXEC, 0) if err := errors.Join(err1, err2, err3, err4); err != nil { say("unavailable: " + err.Error()) select {} } u32 := func(b []byte, off uint32) *uint32 { return (*uint32)(unsafe.Pointer(&b[off])) } sqTail, sqMask, sqArray := u32(sqRing, p.sq.tail), *u32(sqRing, p.sq.ringMask), p.sq.array cqHead, cqTail := u32(cqRing, p.cq.head), u32(cqRing, p.cq.tail) buf := make([]byte, uringBlock) for round := 0; ; round++ { for i := range buf { buf[i] = byte('a' + round%26) } tail := atomic.LoadUint32(sqTail) for i := uint32(0); i < uringChain; i++ { slot := (tail + i) & sqMask sqe := (*uringSQE)(unsafe.Pointer(&sqes[uintptr(slot)*unsafe.Sizeof(uringSQE{})])) *sqe = uringSQE{opcode: uringOpWrite, flags: uringSQEAsync, fd: int32(target), addr: uint64(uintptr(unsafe.Pointer(&buf[0]))), len: uringBlock} if i < uringChain-1 { sqe.flags |= uringSQELink } *u32(sqRing, sqArray+slot*4) = slot } atomic.StoreUint32(sqTail, tail+uringChain) if _, _, e := unix.Syscall6(unix.SYS_IO_URING_ENTER, uintptr(fd), uringChain, 0, 0, 0, 0); e != 0 { say("unavailable: io_uring_enter: " + e.Error()) select {} } if round == 0 { say("ok") } // Wait for the whole chain, then consume its completions. if _, _, e := unix.Syscall6(unix.SYS_IO_URING_ENTER, uintptr(fd), 0, uringChain, uringGetEvents, 0, 0); e != 0 && e != unix.EINTR { os.Exit(6) } atomic.StoreUint32(cqHead, atomic.LoadUint32(cqTail)) _ = runtimeKeep(buf) } } //go:noinline func runtimeKeep(b []byte) int { return len(b) } // adversarySnapshots runs snapshots while the adversary writes into // site/page.bin; each must be busy whenever the page changed while the // copy was made (seen from inside the pause by the workCopied seam). It // returns how many saw the page change inside the pause: there, or in a // window as the copy begins (the workParsed seam), since a copy that // catches the change itself refuses before it reaches workCopied. func adversarySnapshots(t *testing.T, h *sandboxHandle, ws string, rounds int) (changed, busy int) { t.Helper() page := filepath.Join(ws, "site/page.bin") var moved, active bool window := func() bool { before, _ := os.Stat(page) time.Sleep(150 * time.Millisecond) after, _ := os.Stat(page) return before == nil || after == nil || !before.ModTime().Equal(after.ModTime()) } workParsed = func() { active = window() } workCopied = func() { moved = window() } defer func() { workParsed, workCopied = nil, nil }() for i := range rounds { moved, active = false, false stage := filepath.Join(t.TempDir(), "stage"+strconv.Itoa(i)) _, err := h.snapshot(context.Background(), ws, stage, "") if moved || active { changed++ } if errors.Is(err, errWorkBusy) { busy++ continue } if err != nil { t.Fatalf("round %d: %v", i, err) } if moved { t.Fatalf("round %d: the page changed while the copy was made, and the copy was accepted", i) } } return changed, busy } func adversaryTree(t *testing.T) string { files := siteFiles() files["site/page.bin"] = string(make([]byte, uringBlock)) return workTree(t, files, nil) } func helperSandbox(t *testing.T, env ...string) *sandboxHandle { t.Helper() self, err := os.Executable() if err != nil { t.Fatal(err) } r := stepSandbox(t, append([]string{"BIN=" + self}, env...), `exec "$BIN" -test.run=NONE`) h := &sandboxHandle{} h.keep(r) return h } // waitMoving waits until file's mtime moves. func waitMoving(t *testing.T, file string) { t.Helper() first, _ := os.Stat(file) for deadline := time.Now().Add(10 * time.Second); ; { if now, err := os.Stat(file); err == nil && first != nil && !now.ModTime().Equal(first.ModTime()) { return } if time.Now().After(deadline) { t.Fatal("the adversary never wrote") } time.Sleep(5 * time.Millisecond) } } // F1: a process that resumes itself with a SIGCONT timer and overwrites // a page (same size) during the copy: every copy it changes is refused. func TestSnapshotRefusesASelfResumingWriter(t *testing.T) { ws := adversaryTree(t) page := filepath.Join(ws, "site/page.bin") watch := filepath.Join(ws, "release") + string(filepath.ListSeparator) + filepath.Join(ws, "site") h := helperSandbox(t, "EQUIPO_WORKSNAP_HELPER=selfcont", "FILE="+page, "WATCH="+watch) waitMoving(t, page) changed, busy := adversarySnapshots(t, h, ws, 5) t.Logf("%d of 5 copies saw the page change; %d refused busy", changed, busy) if changed == 0 { t.Fatal("the self-resuming writer never wrote during a copy: the test proves nothing") } } // F1: two processes that SIGCONT each other and stop themselves, one // overwriting the page each turn: every copy they change is refused, and // a copy they do not change is accepted. func TestSnapshotRefusesSIGCONTPeers(t *testing.T) { ws := adversaryTree(t) page := filepath.Join(ws, "site/page.bin") d := t.TempDir() peer := `echo $$ > "$D/$0.pid"; while [ ! -s "$D/$1.pid" ]; do :; done; read other < "$D/$1.pid"; i=0 while :; do kill -CONT $other; if [ "$0" = a ]; then i=$((i+1)); printf '%08d' $i 1<> "$PAGE"; fi; kill -STOP $$; done` r := stepSandbox(t, []string{"D=" + d, "PAGE=" + page, "P=" + peer}, `sh -c "$P" a b & sh -c "$P" b a & wait`) h := &sandboxHandle{} h.keep(r) waitMoving(t, page) changed, busy := adversarySnapshots(t, h, ws, 5) // Each copy is busy or saw no change (adversarySnapshots). Here the // pause's repeated SIGSTOPs usually catch both peers stopped at once, // after which neither can resume the other: then nothing changes. t.Logf("%d of 5 copies saw the page change; %d refused busy", changed, busy) } // F4: asynchronous writes (io_uring, linked O_DSYNC overwrites punted to // the kernel's workers) submitted before the pause and completing during // the copy: every copy they change is refused. Skipped where io_uring // is unavailable. (On 6.12 the chain does not advance while the // submitting process is stopped, so the copies see no change.) func TestSnapshotRefusesAsyncWrites(t *testing.T) { ws := adversaryTree(t) page := filepath.Join(ws, "site/page.bin") ready := filepath.Join(t.TempDir(), "ready") h := helperSandbox(t, "EQUIPO_WORKSNAP_HELPER=uring", "FILE="+page, "READY="+ready) for deadline := time.Now().Add(10 * time.Second); ; { raw, _ := os.ReadFile(ready) if string(raw) == "ok" { break } if len(raw) > 0 { t.Skipf("io_uring is unavailable here: %s", raw) } if time.Now().After(deadline) { t.Fatal("the io_uring helper never started") } time.Sleep(5 * time.Millisecond) } waitMoving(t, page) changed, busy := adversarySnapshots(t, h, ws, 5) t.Logf("%d of 5 copies saw the page change; %d refused busy", changed, busy) } // The copy's own check, driven from inside it (the workCopied seam runs // once every file is copied): any change to what it read refuses with // busy, a same-size overwrite whose mtime is put back (only ctime shows // it) included; and a deadline passing during the copy refuses too. func TestWorkSiteRefusesAChangeDuringTheCopy(t *testing.T) { restored := func(path string, write func()) func() { return func() { info, err := os.Stat(path) if err != nil { t.Fatal(err) } time.Sleep(20 * time.Millisecond) // past the timestamp granularity write() if err := os.Chtimes(path, info.ModTime(), info.ModTime()); err != nil { t.Fatal(err) } } } for name, change := range map[string]func(ws string) func(){ "a same-size overwrite, mtime put back": func(ws string) func() { p := filepath.Join(ws, "site/index.html") return restored(p, func() { os.WriteFile(p, []byte("