//go:build linux package thin import ( "errors" "io" "os" "path" "slices" "sort" "strings" "time" "amadan.net/oficina/equipo/internal/runner/pause" "golang.org/x/sys/unix" ) // snapshotWork pauses the sandbox whose first process is p and, inside // the pause, copies workspace's site into stage (emptied and made 0700 // first, outside the pause). Any failure to pause in time, or a copy that // runs past the bound, is errWorkBusy; the site's own refusals are // exportStatic's (errPreviewConfig, errPreviewTooLarge). On any error the // stage is removed, so a partial or unpaused copy is never left to use. // bound is the pause's (snapshotWithin: at most snapshotBound). func snapshotWork(p pause.Process, workspace, stage, headers string, bound time.Duration) (_ previewExport, err error) { st, err := openSiteStage(stage) if err != nil { return previewExport{}, err } defer func() { st.close() if err != nil { os.RemoveAll(stage) } }() var ex previewExport err = pause.Hold(p, bound, func(deadline time.Time) error { var err error ex, err = copyWorkSite(workspace, st, headers, deadline) return err }) if errors.Is(err, pause.ErrBusy) || errors.Is(err, pause.ErrGone) || errors.Is(err, pause.ErrUnsupported) { return previewExport{}, errWorkBusy } if err != nil { return previewExport{}, err } return ex, nil } // workResolve is how every path below the workspace root is resolved: never // above the root, through no symlink (and so no magic link), and on the // root's own mount. const workResolve = unix.RESOLVE_BENEATH | unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS | unix.RESOLVE_NO_XDEV // workRoot is the workspace opened once; every path is opened from it. type workRoot struct{ fd int } func openWorkRoot(workspace string) (workRoot, error) { fd, err := unix.Open(workspace, unix.O_PATH|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) if err != nil { return workRoot{}, errPreviewConfig } return workRoot{fd}, nil } func (w workRoot) close() { unix.Close(w.fd) } // open opens rel from the root by workResolve. A link as rel's last part // is refused too (O_NOFOLLOW), so no link is followed at any depth. func (w workRoot) open(rel string, flags uint64) (int, error) { for try := 0; ; try++ { fd, err := unix.Openat2(w.fd, rel, &unix.OpenHow{Flags: flags | unix.O_NOFOLLOW | unix.O_CLOEXEC, Resolve: workResolve}) if (err == unix.EINTR || err == unix.EAGAIN) && try < 16 { // EAGAIN: a rename raced the resolution (RESOLVE_BENEATH). continue } return fd, err } } // stat is rel's own type and identity, read through an O_PATH descriptor: // nothing of a device or FIFO is opened to learn what it is. A link as the // last part comes back as the link itself. func (w workRoot) stat(rel string) (unix.Stat_t, error) { var st unix.Stat_t fd, err := w.open(rel, unix.O_PATH) if err != nil { return st, errPreviewConfig } defer unix.Close(fd) if err := unix.Fstat(fd, &st); err != nil { return st, errPreviewConfig } return st, nil } // readFile reads rel, a regular file the walk saw as want (same device and // inode), whole: at most limit bytes, exactly its size. func (w workRoot) readFile(rel string, want unix.Stat_t, limit int64) ([]byte, error) { fd, err := w.open(rel, unix.O_RDONLY|unix.O_NONBLOCK|unix.O_NOCTTY) if err != nil { return nil, errPreviewConfig } defer unix.Close(fd) var st unix.Stat_t if err := unix.Fstat(fd, &st); err != nil || st.Mode&unix.S_IFMT != unix.S_IFREG || st.Dev != want.Dev || st.Ino != want.Ino { return nil, errPreviewConfig } if st.Size < 0 || st.Size > limit { return nil, errPreviewTooLarge } if !sameFile(st, want) { // Changed since the walk saw it, while the step is paused. return nil, errWorkBusy } buf := make([]byte, st.Size+1) n, err := io.ReadFull(fdReader(fd), buf) if err != io.ErrUnexpectedEOF && err != io.EOF || int64(n) != st.Size { // A file that is not the size it said, while the step is paused. return nil, errWorkBusy } return buf[:n], nil } // sameFile: the same inode, unchanged: device, inode, type and mode, // size, mtime and ctime (ctime moves on any write or change, a same-size // overwrite included, to the file system's timestamp granularity). func sameFile(a, b unix.Stat_t) bool { return a.Dev == b.Dev && a.Ino == b.Ino && a.Mode == b.Mode && a.Size == b.Size && a.Mtim == b.Mtim && a.Ctim == b.Ctim } // workParsed and workCopied are called inside the pause once the config // is parsed and once every file is copied (seams for the tests; nil in // production). var workParsed, workCopied func() // unchanged stats every path the copy read again, still inside the pause, // and lists every directory again, and refuses with errWorkBusy if // anything differs from what the walk saw: the defence against what the // pause cannot stop (see pause.Hold). Times move by the file system's // tick (coarse, a few milliseconds), so a change within the same tick as // the inode's last one shows only in a directory's names, not in a file's // times. func (w workRoot) unchanged(seen map[string]unix.Stat_t, listed map[string][]string) error { for rel, want := range seen { got, err := w.stat(rel) if err != nil || !sameFile(got, want) { return errWorkBusy } } for dir, want := range listed { budget := len(want) got, err := w.names(dir, &budget) if err != nil || !slices.Equal(slices.Sorted(slices.Values(got)), slices.Sorted(slices.Values(want))) { return errWorkBusy } } return nil } type fdReader int func (f fdReader) Read(p []byte) (int, error) { for { n, err := unix.Read(int(f), p) if err == unix.EINTR { continue } if err != nil { return 0, err } if n == 0 { return 0, io.EOF } return n, nil } } // names lists the directory rel (opened by workResolve, O_DIRECTORY), at // most budget names in all. func (w workRoot) names(rel string, budget *int) ([]string, error) { fd, err := w.open(rel, unix.O_RDONLY|unix.O_DIRECTORY) if err != nil { return nil, errPreviewConfig } defer unix.Close(fd) var out []string buf := make([]byte, 32<<10) for { n, err := unix.Getdents(fd, buf) if err == unix.EINTR { continue } if err != nil { return nil, errPreviewConfig } if n <= 0 { return out, nil } before := len(out) _, _, out = unix.ParseDirent(buf[:n], -1, out) if *budget -= len(out) - before; *budget < 0 { return nil, errPreviewTooLarge } } } // copyWorkSite reads the workspace's release/preview.json by // readPreviewConfig's rules and copies its output directory into st by // exportStatic's: every path clean (no part starting with a dot, no // marker's name), regular files and directories only, never a link, the // caps checked against the whole listing before any file is read and // again while copying, the files put in sorted order so the digest is the // one exportStatic gives the same tree. Every path is opened from the // workspace root by workResolve. It reads only; past deadline it stops // with errWorkBusy. func copyWorkSite(workspace string, st *siteStage, headers string, deadline time.Time) (previewExport, error) { late := func() bool { return !time.Now().Before(deadline) } if late() { return previewExport{}, errWorkBusy } w, err := openWorkRoot(workspace) if err != nil { return previewExport{}, err } defer w.close() cst, err := w.stat(previewConfigPath) if err != nil || cst.Mode&unix.S_IFMT != unix.S_IFREG { return previewExport{}, errPreviewConfig } // seen is every path read (the config, each directory listed, each // file copied), checked again once the copy is made. seen := map[string]unix.Stat_t{previewConfigPath: cst} // observe records what rel was seen as; a path seen again (the config, // when the output holds release/) must be seen the same, or the copy // is refused: no observation replaces an earlier one. observe := func(rel string, st unix.Stat_t) error { if was, ok := seen[rel]; ok && !sameFile(was, st) { return errWorkBusy } seen[rel] = st return nil } raw, err := w.readFile(previewConfigPath, cst, previewMaxConfig) if errors.Is(err, errWorkBusy) { return previewExport{}, err } if err != nil { return previewExport{}, errPreviewConfig } cfg, err := parsePreviewConfig(raw) if err != nil { return previewExport{}, err } if workParsed != nil { workParsed() } output := cfg.Output type entry struct { rel string st unix.Stat_t } var entries []entry budget := newSiteBudget(headers) // Every name is a file, a directory or a refusal. (The tree's own // _headers, skipped, takes the name of the file slot the runner's // takes.) This bounds what one listing holds in memory. names := previewMaxFiles + previewMaxDirs dirs := 0 ost, err := w.stat(output) if err != nil || ost.Mode&unix.S_IFMT != unix.S_IFDIR { return previewExport{}, errPreviewConfig } if err := observe(output, ost); err != nil { return previewExport{}, err } listed := map[string][]string{} pending := []string{""} for len(pending) > 0 { if late() { return previewExport{}, errWorkBusy } dir := pending[len(pending)-1] pending = pending[:len(pending)-1] list, err := w.names(path.Join(output, dir), &names) if err != nil { return previewExport{}, err } listed[path.Join(output, dir)] = list for _, name := range list { rel := path.Join(dir, name) if strings.Count(rel, "/")+1 > previewMaxDepth { return previewExport{}, errPreviewTooLarge } skip, err := siteEntry(rel, headers) if err != nil { return previewExport{}, err } est, err := w.stat(output + "/" + rel) if err != nil { return previewExport{}, err } switch est.Mode & unix.S_IFMT { case unix.S_IFDIR: if dirs++; dirs > previewMaxDirs { return previewExport{}, errPreviewTooLarge } if err := observe(output+"/"+rel, est); err != nil { return previewExport{}, err } pending = append(pending, rel) case unix.S_IFREG: if skip { continue } if err := budget.add(est.Size); err != nil { return previewExport{}, err } if err := observe(output+"/"+rel, est); err != nil { return previewExport{}, err } entries = append(entries, entry{rel, est}) default: // A link, a FIFO, a socket, a device: never followed. return previewExport{}, errPreviewConfig } } } if len(entries) == 0 { return previewExport{}, errPreviewConfig } if headers != "" { entries = append(entries, entry{rel: "_headers"}) } sort.Slice(entries, func(i, j int) bool { return entries[i].rel < entries[j].rel }) for _, e := range entries { if late() { return previewExport{}, errWorkBusy } var blob []byte if headers != "" && e.rel == "_headers" { blob = []byte(headers) } else if blob, err = w.readFile(output+"/"+e.rel, e.st, previewMaxFile); err != nil { return previewExport{}, err } if err := st.put(e.rel, blob); err != nil { return previewExport{}, err } } if workCopied != nil { workCopied() } if err := w.unchanged(seen, listed); err != nil { return previewExport{}, err } if late() { return previewExport{}, errWorkBusy } return previewExport{Digest: st.digest(), Files: len(entries), Bytes: budget.bytes}, nil }