| 1 | //go:build linux |
| 2 | |
| 3 | package thin |
| 4 | |
| 5 | import ( |
| 6 | "errors" |
| 7 | "io" |
| 8 | "os" |
| 9 | "path" |
| 10 | "slices" |
| 11 | "sort" |
| 12 | "strings" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/runner/pause" |
| 16 | "golang.org/x/sys/unix" |
| 17 | ) |
| 18 | |
| 19 | // snapshotWork pauses the sandbox whose first process is p and, inside |
| 20 | // the pause, copies workspace's site into stage (emptied and made 0700 |
| 21 | // first, outside the pause). Any failure to pause in time, or a copy that |
| 22 | // runs past the bound, is errWorkBusy; the site's own refusals are |
| 23 | // exportStatic's (errPreviewConfig, errPreviewTooLarge). On any error the |
| 24 | // stage is removed, so a partial or unpaused copy is never left to use. |
| 25 | // bound is the pause's (snapshotWithin: at most snapshotBound). |
| 26 | func snapshotWork(p pause.Process, workspace, stage, headers string, bound time.Duration) (_ previewExport, err error) { |
| 27 | st, err := openSiteStage(stage) |
| 28 | if err != nil { |
| 29 | return previewExport{}, err |
| 30 | } |
| 31 | defer func() { |
| 32 | st.close() |
| 33 | if err != nil { |
| 34 | os.RemoveAll(stage) |
| 35 | } |
| 36 | }() |
| 37 | var ex previewExport |
| 38 | err = pause.Hold(p, bound, func(deadline time.Time) error { |
| 39 | var err error |
| 40 | ex, err = copyWorkSite(workspace, st, headers, deadline) |
| 41 | return err |
| 42 | }) |
| 43 | if errors.Is(err, pause.ErrBusy) || errors.Is(err, pause.ErrGone) || errors.Is(err, pause.ErrUnsupported) { |
| 44 | return previewExport{}, errWorkBusy |
| 45 | } |
| 46 | if err != nil { |
| 47 | return previewExport{}, err |
| 48 | } |
| 49 | return ex, nil |
| 50 | } |
| 51 | |
| 52 | // workResolve is how every path below the workspace root is resolved: never |
| 53 | // above the root, through no symlink (and so no magic link), and on the |
| 54 | // root's own mount. |
| 55 | const workResolve = unix.RESOLVE_BENEATH | unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS | unix.RESOLVE_NO_XDEV |
| 56 | |
| 57 | // workRoot is the workspace opened once; every path is opened from it. |
| 58 | type workRoot struct{ fd int } |
| 59 | |
| 60 | func openWorkRoot(workspace string) (workRoot, error) { |
| 61 | fd, err := unix.Open(workspace, unix.O_PATH|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| 62 | if err != nil { |
| 63 | return workRoot{}, errPreviewConfig |
| 64 | } |
| 65 | return workRoot{fd}, nil |
| 66 | } |
| 67 | |
| 68 | func (w workRoot) close() { unix.Close(w.fd) } |
| 69 | |
| 70 | // open opens rel from the root by workResolve. A link as rel's last part |
| 71 | // is refused too (O_NOFOLLOW), so no link is followed at any depth. |
| 72 | func (w workRoot) open(rel string, flags uint64) (int, error) { |
| 73 | for try := 0; ; try++ { |
| 74 | fd, err := unix.Openat2(w.fd, rel, &unix.OpenHow{Flags: flags | unix.O_NOFOLLOW | unix.O_CLOEXEC, Resolve: workResolve}) |
| 75 | if (err == unix.EINTR || err == unix.EAGAIN) && try < 16 { |
| 76 | // EAGAIN: a rename raced the resolution (RESOLVE_BENEATH). |
| 77 | continue |
| 78 | } |
| 79 | return fd, err |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | // stat is rel's own type and identity, read through an O_PATH descriptor: |
| 84 | // nothing of a device or FIFO is opened to learn what it is. A link as the |
| 85 | // last part comes back as the link itself. |
| 86 | func (w workRoot) stat(rel string) (unix.Stat_t, error) { |
| 87 | var st unix.Stat_t |
| 88 | fd, err := w.open(rel, unix.O_PATH) |
| 89 | if err != nil { |
| 90 | return st, errPreviewConfig |
| 91 | } |
| 92 | defer unix.Close(fd) |
| 93 | if err := unix.Fstat(fd, &st); err != nil { |
| 94 | return st, errPreviewConfig |
| 95 | } |
| 96 | return st, nil |
| 97 | } |
| 98 | |
| 99 | // readFile reads rel, a regular file the walk saw as want (same device and |
| 100 | // inode), whole: at most limit bytes, exactly its size. |
| 101 | func (w workRoot) readFile(rel string, want unix.Stat_t, limit int64) ([]byte, error) { |
| 102 | fd, err := w.open(rel, unix.O_RDONLY|unix.O_NONBLOCK|unix.O_NOCTTY) |
| 103 | if err != nil { |
| 104 | return nil, errPreviewConfig |
| 105 | } |
| 106 | defer unix.Close(fd) |
| 107 | var st unix.Stat_t |
| 108 | if err := unix.Fstat(fd, &st); err != nil || st.Mode&unix.S_IFMT != unix.S_IFREG || st.Dev != want.Dev || st.Ino != want.Ino { |
| 109 | return nil, errPreviewConfig |
| 110 | } |
| 111 | if st.Size < 0 || st.Size > limit { |
| 112 | return nil, errPreviewTooLarge |
| 113 | } |
| 114 | if !sameFile(st, want) { |
| 115 | // Changed since the walk saw it, while the step is paused. |
| 116 | return nil, errWorkBusy |
| 117 | } |
| 118 | buf := make([]byte, st.Size+1) |
| 119 | n, err := io.ReadFull(fdReader(fd), buf) |
| 120 | if err != io.ErrUnexpectedEOF && err != io.EOF || int64(n) != st.Size { |
| 121 | // A file that is not the size it said, while the step is paused. |
| 122 | return nil, errWorkBusy |
| 123 | } |
| 124 | return buf[:n], nil |
| 125 | } |
| 126 | |
| 127 | // sameFile: the same inode, unchanged: device, inode, type and mode, |
| 128 | // size, mtime and ctime (ctime moves on any write or change, a same-size |
| 129 | // overwrite included, to the file system's timestamp granularity). |
| 130 | func sameFile(a, b unix.Stat_t) bool { |
| 131 | return a.Dev == b.Dev && a.Ino == b.Ino && a.Mode == b.Mode && a.Size == b.Size && |
| 132 | a.Mtim == b.Mtim && a.Ctim == b.Ctim |
| 133 | } |
| 134 | |
| 135 | // workParsed and workCopied are called inside the pause once the config |
| 136 | // is parsed and once every file is copied (seams for the tests; nil in |
| 137 | // production). |
| 138 | var workParsed, workCopied func() |
| 139 | |
| 140 | // unchanged stats every path the copy read again, still inside the pause, |
| 141 | // and lists every directory again, and refuses with errWorkBusy if |
| 142 | // anything differs from what the walk saw: the defence against what the |
| 143 | // pause cannot stop (see pause.Hold). Times move by the file system's |
| 144 | // tick (coarse, a few milliseconds), so a change within the same tick as |
| 145 | // the inode's last one shows only in a directory's names, not in a file's |
| 146 | // times. |
| 147 | func (w workRoot) unchanged(seen map[string]unix.Stat_t, listed map[string][]string) error { |
| 148 | for rel, want := range seen { |
| 149 | got, err := w.stat(rel) |
| 150 | if err != nil || !sameFile(got, want) { |
| 151 | return errWorkBusy |
| 152 | } |
| 153 | } |
| 154 | for dir, want := range listed { |
| 155 | budget := len(want) |
| 156 | got, err := w.names(dir, &budget) |
| 157 | if err != nil || !slices.Equal(slices.Sorted(slices.Values(got)), slices.Sorted(slices.Values(want))) { |
| 158 | return errWorkBusy |
| 159 | } |
| 160 | } |
| 161 | return nil |
| 162 | } |
| 163 | |
| 164 | type fdReader int |
| 165 | |
| 166 | func (f fdReader) Read(p []byte) (int, error) { |
| 167 | for { |
| 168 | n, err := unix.Read(int(f), p) |
| 169 | if err == unix.EINTR { |
| 170 | continue |
| 171 | } |
| 172 | if err != nil { |
| 173 | return 0, err |
| 174 | } |
| 175 | if n == 0 { |
| 176 | return 0, io.EOF |
| 177 | } |
| 178 | return n, nil |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | // names lists the directory rel (opened by workResolve, O_DIRECTORY), at |
| 183 | // most budget names in all. |
| 184 | func (w workRoot) names(rel string, budget *int) ([]string, error) { |
| 185 | fd, err := w.open(rel, unix.O_RDONLY|unix.O_DIRECTORY) |
| 186 | if err != nil { |
| 187 | return nil, errPreviewConfig |
| 188 | } |
| 189 | defer unix.Close(fd) |
| 190 | var out []string |
| 191 | buf := make([]byte, 32<<10) |
| 192 | for { |
| 193 | n, err := unix.Getdents(fd, buf) |
| 194 | if err == unix.EINTR { |
| 195 | continue |
| 196 | } |
| 197 | if err != nil { |
| 198 | return nil, errPreviewConfig |
| 199 | } |
| 200 | if n <= 0 { |
| 201 | return out, nil |
| 202 | } |
| 203 | before := len(out) |
| 204 | _, _, out = unix.ParseDirent(buf[:n], -1, out) |
| 205 | if *budget -= len(out) - before; *budget < 0 { |
| 206 | return nil, errPreviewTooLarge |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | // copyWorkSite reads the workspace's release/preview.json by |
| 212 | // readPreviewConfig's rules and copies its output directory into st by |
| 213 | // exportStatic's: every path clean (no part starting with a dot, no |
| 214 | // marker's name), regular files and directories only, never a link, the |
| 215 | // caps checked against the whole listing before any file is read and |
| 216 | // again while copying, the files put in sorted order so the digest is the |
| 217 | // one exportStatic gives the same tree. Every path is opened from the |
| 218 | // workspace root by workResolve. It reads only; past deadline it stops |
| 219 | // with errWorkBusy. |
| 220 | func copyWorkSite(workspace string, st *siteStage, headers string, deadline time.Time) (previewExport, error) { |
| 221 | late := func() bool { return !time.Now().Before(deadline) } |
| 222 | if late() { |
| 223 | return previewExport{}, errWorkBusy |
| 224 | } |
| 225 | w, err := openWorkRoot(workspace) |
| 226 | if err != nil { |
| 227 | return previewExport{}, err |
| 228 | } |
| 229 | defer w.close() |
| 230 | |
| 231 | cst, err := w.stat(previewConfigPath) |
| 232 | if err != nil || cst.Mode&unix.S_IFMT != unix.S_IFREG { |
| 233 | return previewExport{}, errPreviewConfig |
| 234 | } |
| 235 | // seen is every path read (the config, each directory listed, each |
| 236 | // file copied), checked again once the copy is made. |
| 237 | seen := map[string]unix.Stat_t{previewConfigPath: cst} |
| 238 | // observe records what rel was seen as; a path seen again (the config, |
| 239 | // when the output holds release/) must be seen the same, or the copy |
| 240 | // is refused: no observation replaces an earlier one. |
| 241 | observe := func(rel string, st unix.Stat_t) error { |
| 242 | if was, ok := seen[rel]; ok && !sameFile(was, st) { |
| 243 | return errWorkBusy |
| 244 | } |
| 245 | seen[rel] = st |
| 246 | return nil |
| 247 | } |
| 248 | raw, err := w.readFile(previewConfigPath, cst, previewMaxConfig) |
| 249 | if errors.Is(err, errWorkBusy) { |
| 250 | return previewExport{}, err |
| 251 | } |
| 252 | if err != nil { |
| 253 | return previewExport{}, errPreviewConfig |
| 254 | } |
| 255 | cfg, err := parsePreviewConfig(raw) |
| 256 | if err != nil { |
| 257 | return previewExport{}, err |
| 258 | } |
| 259 | if workParsed != nil { |
| 260 | workParsed() |
| 261 | } |
| 262 | output := cfg.Output |
| 263 | |
| 264 | type entry struct { |
| 265 | rel string |
| 266 | st unix.Stat_t |
| 267 | } |
| 268 | var entries []entry |
| 269 | budget := newSiteBudget(headers) |
| 270 | // Every name is a file, a directory or a refusal. (The tree's own |
| 271 | // _headers, skipped, takes the name of the file slot the runner's |
| 272 | // takes.) This bounds what one listing holds in memory. |
| 273 | names := previewMaxFiles + previewMaxDirs |
| 274 | dirs := 0 |
| 275 | ost, err := w.stat(output) |
| 276 | if err != nil || ost.Mode&unix.S_IFMT != unix.S_IFDIR { |
| 277 | return previewExport{}, errPreviewConfig |
| 278 | } |
| 279 | if err := observe(output, ost); err != nil { |
| 280 | return previewExport{}, err |
| 281 | } |
| 282 | listed := map[string][]string{} |
| 283 | pending := []string{""} |
| 284 | for len(pending) > 0 { |
| 285 | if late() { |
| 286 | return previewExport{}, errWorkBusy |
| 287 | } |
| 288 | dir := pending[len(pending)-1] |
| 289 | pending = pending[:len(pending)-1] |
| 290 | list, err := w.names(path.Join(output, dir), &names) |
| 291 | if err != nil { |
| 292 | return previewExport{}, err |
| 293 | } |
| 294 | listed[path.Join(output, dir)] = list |
| 295 | for _, name := range list { |
| 296 | rel := path.Join(dir, name) |
| 297 | if strings.Count(rel, "/")+1 > previewMaxDepth { |
| 298 | return previewExport{}, errPreviewTooLarge |
| 299 | } |
| 300 | skip, err := siteEntry(rel, headers) |
| 301 | if err != nil { |
| 302 | return previewExport{}, err |
| 303 | } |
| 304 | est, err := w.stat(output + "/" + rel) |
| 305 | if err != nil { |
| 306 | return previewExport{}, err |
| 307 | } |
| 308 | switch est.Mode & unix.S_IFMT { |
| 309 | case unix.S_IFDIR: |
| 310 | if dirs++; dirs > previewMaxDirs { |
| 311 | return previewExport{}, errPreviewTooLarge |
| 312 | } |
| 313 | if err := observe(output+"/"+rel, est); err != nil { |
| 314 | return previewExport{}, err |
| 315 | } |
| 316 | pending = append(pending, rel) |
| 317 | case unix.S_IFREG: |
| 318 | if skip { |
| 319 | continue |
| 320 | } |
| 321 | if err := budget.add(est.Size); err != nil { |
| 322 | return previewExport{}, err |
| 323 | } |
| 324 | if err := observe(output+"/"+rel, est); err != nil { |
| 325 | return previewExport{}, err |
| 326 | } |
| 327 | entries = append(entries, entry{rel, est}) |
| 328 | default: |
| 329 | // A link, a FIFO, a socket, a device: never followed. |
| 330 | return previewExport{}, errPreviewConfig |
| 331 | } |
| 332 | } |
| 333 | } |
| 334 | if len(entries) == 0 { |
| 335 | return previewExport{}, errPreviewConfig |
| 336 | } |
| 337 | if headers != "" { |
| 338 | entries = append(entries, entry{rel: "_headers"}) |
| 339 | } |
| 340 | sort.Slice(entries, func(i, j int) bool { return entries[i].rel < entries[j].rel }) |
| 341 | for _, e := range entries { |
| 342 | if late() { |
| 343 | return previewExport{}, errWorkBusy |
| 344 | } |
| 345 | var blob []byte |
| 346 | if headers != "" && e.rel == "_headers" { |
| 347 | blob = []byte(headers) |
| 348 | } else if blob, err = w.readFile(output+"/"+e.rel, e.st, previewMaxFile); err != nil { |
| 349 | return previewExport{}, err |
| 350 | } |
| 351 | if err := st.put(e.rel, blob); err != nil { |
| 352 | return previewExport{}, err |
| 353 | } |
| 354 | } |
| 355 | if workCopied != nil { |
| 356 | workCopied() |
| 357 | } |
| 358 | if err := w.unchanged(seen, listed); err != nil { |
| 359 | return previewExport{}, err |
| 360 | } |
| 361 | if late() { |
| 362 | return previewExport{}, errWorkBusy |
| 363 | } |
| 364 | return previewExport{Digest: st.digest(), Files: len(entries), Bytes: budget.bytes}, nil |
| 365 | } |
| 366 | |