oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package release
2
3import (
4 "archive/tar"
5 "compress/gzip"
6 "crypto/sha256"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "io"
11 "io/fs"
12 "os"
13 "path"
14 "path/filepath"
15 "regexp"
16 "strings"
17 "syscall"
18 "unicode/utf8"
19
20 "amadan.net/oficina/equipo/internal/wire"
21)
22
23// RendererArchive is the renderer a release ships beside the Linux
24// runner (scripts/build-renderer-tree.py), and RendererArchiveMax bounds
25// it wherever it is read whole: served by the instance, fetched by the
26// installer. The real one is about 230 MB.
27const (
28 RendererArchive = "renderer.tar.gz"
29 RendererArchiveMax = 384 << 20
30)
31
32// Bounds on an unpacked archive: the real tree is about 560 MB in 2,316
33// entries. Tests lower them.
34var (
35 rendererUnpackedMax int64 = 2 << 30
36 rendererEntriesMax int64 = 50000
37)
38
39// RendererTree is where a runner whose executable is in runnerDir keeps
40// the tree pin names: <runnerDir>/renderer/<first 12 of pin>. It is ""
41// for a malformed pin.
42func RendererTree(runnerDir, pin string) string {
43 if !sha256Hex(pin) {
44 return ""
45 }
46 return filepath.Join(runnerDir, "renderer", pin[:12])
47}
48
49// oldTree is the name of a tree RendererTree would give another pin.
50var oldTree = regexp.MustCompile(`^[0-9a-f]{12}$`)
51
52// InstallRenderer installs the renderer archive (renderer.tar.gz) at
53// RendererTree(runnerDir, pin) and returns that path. A tree there that
54// already verifies is kept and the archive is not read. Otherwise the
55// archive is unpacked into a new directory beside the tree's place,
56// verified (VerifyRenderer) and renamed into place, replacing whatever
57// was there. Then every other tree in <runnerDir>/renderer/, a
58// directory named as another pin's first 12 hex digits, is removed;
59// nothing else there is touched.
60//
61// The archive must be what the build writes: MANIFEST first, its SHA-256
62// the pin (checked before anything else is written), then only
63// directories, regular files and symbolic links, each a clean relative
64// path whose directory came earlier in the archive, so nothing is
65// written through a link. Modes are the headers' exactly, never the
66// umask's: no group or world write, setuid, setgid or sticky bit. A hard
67// link, a device, a fifo, an absolute or climbing path or link target,
68// a repeated name, or more bytes or entries than any real tree has, is
69// refused. <runnerDir>/renderer/ is created 0755 and must be a directory
70// owned by this user or root that nobody else can write, as render.Launch
71// requires of a tree's parent.
72//
73// It returns a *RendererError (unpinned for a malformed pin, mismatch
74// for an archive or tree that is not the pinned one) or the error of the
75// disk.
76func InstallRenderer(runnerDir string, archive io.Reader, pin string) (string, error) {
77 return installTree(runnerDir, pin, func(tmp string) error { return unpackRenderer(tmp, archive, pin) })
78}
79
80// CopyRenderer installs, as InstallRenderer does, a copy of the tree at
81// from, which must verify for pin first: an earlier release's tree, so a
82// new release beside it needs nothing fetched. Files are copied, never
83// linked (VerifyRenderer refuses a file with more than one link), and the
84// copy is verified whole before it is renamed into place.
85func CopyRenderer(runnerDir, from, pin string) (string, error) {
86 if err := VerifyRenderer(from, pin); err != nil {
87 return "", err
88 }
89 return installTree(runnerDir, pin, func(tmp string) error { return copyTree(tmp, from) })
90}
91
92// installTree is InstallRenderer's and CopyRenderer's shared part: fill
93// writes a candidate tree into a new directory beside the tree's place,
94// which is verified and renamed into place; a tree there that already
95// verifies is kept and fill never runs. Then every other tree is removed.
96func installTree(runnerDir, pin string, fill func(tmp string) error) (string, error) {
97 if !sha256Hex(pin) {
98 return "", &RendererError{Health: wire.ToolUnpinned, Reason: "no renderer pin is linked into this runner"}
99 }
100 if !filepath.IsAbs(runnerDir) || filepath.Clean(runnerDir) != runnerDir {
101 return "", rendererMismatch("", "%q is not an absolute, clean path", runnerDir)
102 }
103 parent := filepath.Join(runnerDir, "renderer")
104 if err := rendererParent(parent); err != nil {
105 return "", err
106 }
107 final := RendererTree(runnerDir, pin)
108 if VerifyRenderer(final, pin) == nil {
109 removeOldTrees(parent, filepath.Base(final))
110 return final, nil
111 }
112 tmp, err := os.MkdirTemp(parent, ".install-")
113 if err != nil {
114 return "", err
115 }
116 defer func() {
117 if tmp != "" {
118 os.RemoveAll(tmp)
119 }
120 }()
121 if err = fill(tmp); err != nil {
122 return "", err
123 }
124 if err = os.Chmod(tmp, 0o755); err != nil {
125 return "", err
126 }
127 if err = VerifyRenderer(tmp, pin); err != nil {
128 return "", err
129 }
130 if err = os.RemoveAll(final); err != nil {
131 return "", err
132 }
133 if err = os.Rename(tmp, final); err != nil {
134 return "", err
135 }
136 tmp = ""
137 if d, err := os.Open(parent); err == nil {
138 d.Sync()
139 d.Close()
140 }
141 removeOldTrees(parent, filepath.Base(final))
142 return final, nil
143}
144
145// testCopyHook runs between copyTree's Lstat of a file and its open
146// (tests only).
147var testCopyHook func(path string)
148
149// copyTree copies the tree at from into the empty directory dir:
150// directories, regular files (their bytes, in new files) and symbolic
151// links, each with its mode; anything else, or more entries or bytes than
152// a tree may hold, is refused. VerifyRenderer then checks the copy.
153func copyTree(dir, from string) error {
154 root, err := os.OpenRoot(dir)
155 if err != nil {
156 return err
157 }
158 defer root.Close()
159 src, err := os.OpenRoot(from)
160 if err != nil {
161 return err
162 }
163 defer src.Close()
164 var total, count int64
165 return fs.WalkDir(src.FS(), ".", func(name string, d fs.DirEntry, err error) error {
166 if err != nil || name == "." {
167 return err
168 }
169 if count++; count > rendererEntriesMax {
170 return rendererMismatch("", "more than %d entries", rendererEntriesMax)
171 }
172 info, err := src.Lstat(name)
173 if err != nil {
174 return err
175 }
176 mode := info.Mode()
177 switch {
178 case mode.IsDir():
179 if err = root.Mkdir(name, 0o700); err != nil {
180 return err
181 }
182 return root.Chmod(name, mode.Perm())
183 case mode.IsRegular():
184 if total += info.Size(); total > rendererUnpackedMax {
185 return rendererMismatch(name, "more bytes than any renderer tree holds")
186 }
187 if testCopyHook != nil {
188 testCopyHook(filepath.Join(from, name))
189 }
190 // Opened without following a link or blocking (a FIFO swapped
191 // in after Lstat), and held to what Lstat saw: the same regular
192 // file, exactly its size, nothing beyond it.
193 in, err := src.OpenFile(name, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0)
194 if err != nil {
195 return err
196 }
197 defer in.Close()
198 opened, err := in.Stat()
199 if err != nil || !opened.Mode().IsRegular() || !os.SameFile(opened, info) || opened.Size() != info.Size() {
200 return rendererMismatch(name, "changed while it was copied")
201 }
202 out, err := root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
203 if err != nil {
204 return err
205 }
206 defer out.Close()
207 if n, err := io.CopyN(out, in, info.Size()); err != nil || n != info.Size() {
208 return rendererMismatch(name, "copied %d of %d bytes: %v", n, info.Size(), err)
209 }
210 if n, _ := in.Read(make([]byte, 1)); n != 0 {
211 return rendererMismatch(name, "grew while it was copied")
212 }
213 if err = out.Chmod(mode.Perm()); err != nil {
214 return err
215 }
216 return out.Close()
217 case mode&fs.ModeSymlink != 0:
218 target, err := src.Readlink(name)
219 if err != nil {
220 return err
221 }
222 return root.Symlink(target, name)
223 }
224 return rendererMismatch(name, "is not a directory, file or link")
225 })
226}
227
228// rendererParent makes <runner dir>/renderer/ (0755, whatever the umask)
229// unless it exists, and checks it is a directory, not a link, owned by
230// this user or root, that nobody else can write.
231func rendererParent(dir string) error {
232 if err := os.Mkdir(dir, 0o755); err == nil {
233 if err = os.Chmod(dir, 0o755); err != nil {
234 return err
235 }
236 } else if !errors.Is(err, fs.ErrExist) {
237 return err
238 }
239 info, err := os.Lstat(dir)
240 if err != nil {
241 return err
242 }
243 st, ok := info.Sys().(*syscall.Stat_t)
244 if !info.IsDir() || info.Mode().Perm()&0o022 != 0 || !ok || st.Uid != uint32(os.Geteuid()) && st.Uid != 0 {
245 return rendererMismatch("", "%s is not a directory only this user can write", dir)
246 }
247 return nil
248}
249
250// removeOldTrees removes, by exact name, every tree in dir but keep.
251func removeOldTrees(dir, keep string) {
252 entries, err := os.ReadDir(dir)
253 if err != nil {
254 return
255 }
256 for _, e := range entries {
257 if name := e.Name(); name != keep && oldTree.MatchString(name) {
258 os.RemoveAll(filepath.Join(dir, name))
259 }
260 }
261}
262
263// unpackRenderer writes the archive's members into dir, as
264// InstallRenderer says.
265func unpackRenderer(dir string, archive io.Reader, pin string) error {
266 gz, err := gzip.NewReader(archive)
267 if err != nil {
268 return rendererMismatch("", "not a gzip archive: %v", err)
269 }
270 defer gz.Close()
271 root, err := os.OpenRoot(dir)
272 if err != nil {
273 return err
274 }
275 defer root.Close()
276 tr := tar.NewReader(gz)
277 kinds := map[string]byte{}
278 var total, count int64
279 for first := true; ; first = false {
280 h, err := tr.Next()
281 if err == io.EOF && !first {
282 return nil
283 }
284 if err != nil {
285 return rendererMismatch("", "reading the archive: %v", err)
286 }
287 if count++; count > rendererEntriesMax {
288 return rendererMismatch("", "more than %d entries", rendererEntriesMax)
289 }
290 name, err := memberName(h, first)
291 if err != nil {
292 return err
293 }
294 if dir := path.Dir(name); dir != "." && kinds[dir] != 'd' {
295 return rendererMismatch(name, "its directory is not an earlier directory of the archive")
296 }
297 if _, ok := kinds[name]; ok {
298 return rendererMismatch(name, "is in the archive twice")
299 }
300 perm := h.Mode
301 switch h.Typeflag {
302 case tar.TypeDir:
303 if perm&^0o755 != 0 || perm&0o700 != 0o700 {
304 return rendererMismatch(name, "mode %04o is not one the tree may hold", perm)
305 }
306 if err = root.Mkdir(name, 0o700); err != nil {
307 return err
308 }
309 if err = root.Chmod(name, fs.FileMode(perm)); err != nil {
310 return err
311 }
312 kinds[name] = 'd'
313 case tar.TypeReg:
314 if perm&^0o755 != 0 || perm&0o400 == 0 {
315 return rendererMismatch(name, "mode %04o is not one the tree may hold", perm)
316 }
317 if total += h.Size; h.Size < 0 || total > rendererUnpackedMax || first && h.Size > rendererManifestMax {
318 return rendererMismatch(name, "more bytes than any renderer tree holds")
319 }
320 if err = unpackFile(root, name, tr, h.Size, fs.FileMode(perm), first, pin); err != nil {
321 return err
322 }
323 kinds[name] = 'f'
324 case tar.TypeSymlink:
325 target := h.Linkname
326 if to := path.Join(path.Dir(name), target); target == "" || strings.HasPrefix(target, "/") || to == ".." || strings.HasPrefix(to, "../") {
327 return rendererMismatch(name, "link target %q leaves the tree", target)
328 }
329 if err = root.Symlink(target, name); err != nil {
330 return err
331 }
332 kinds[name] = 'l'
333 default:
334 return rendererMismatch(name, "a member of type %q: the tree holds only directories, files and links", h.Typeflag)
335 }
336 }
337}
338
339// memberName is a member's path in the tree: MANIFEST first and only
340// first, then clean relative paths (a directory's trailing slash, as
341// tar writes it, dropped).
342func memberName(h *tar.Header, first bool) (string, error) {
343 name := h.Name
344 if h.Typeflag == tar.TypeDir {
345 name = strings.TrimSuffix(name, "/")
346 }
347 if first != (name == "MANIFEST") {
348 return "", rendererMismatch(name, "MANIFEST must be the archive's first member, and only it")
349 }
350 if !first && (!utf8.ValidString(name) || !rendererPath(name)) {
351 return "", rendererMismatch("", "%q is not a clean relative path", name)
352 }
353 return name, nil
354}
355
356// unpackFile writes one regular file, created new, its mode set on the
357// descriptor. MANIFEST must have the pin's hash before anything else is
358// written.
359func unpackFile(root *os.Root, name string, r io.Reader, size int64, mode fs.FileMode, manifest bool, pin string) error {
360 f, err := root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
361 if err != nil {
362 return err
363 }
364 defer f.Close()
365 h := sha256.New()
366 n, err := io.Copy(io.MultiWriter(f, h), r)
367 if err != nil || n != size {
368 return rendererMismatch(name, "reading the archive: %d of %d bytes: %v", n, size, err)
369 }
370 if manifest && hex.EncodeToString(h.Sum(nil)) != pin {
371 return rendererMismatch("MANIFEST", "its SHA-256 is %x, the pin is %s", h.Sum(nil), pin)
372 }
373 if err = f.Chmod(mode); err != nil {
374 return err
375 }
376 return f.Close()
377}
378
379// RendererArchivePin is the SHA-256 of a renderer archive's MANIFEST,
380// its first member, read without the rest: the pin the archive is for.
381func RendererArchivePin(archive io.Reader) (string, error) {
382 gz, err := gzip.NewReader(archive)
383 if err != nil {
384 return "", err
385 }
386 defer gz.Close()
387 tr := tar.NewReader(gz)
388 h, err := tr.Next()
389 if err != nil {
390 return "", err
391 }
392 if h.Name != "MANIFEST" || h.Typeflag != tar.TypeReg || h.Size < 0 || h.Size > rendererManifestMax {
393 return "", fmt.Errorf("the archive's first member is %q, not its MANIFEST", h.Name)
394 }
395 sum := sha256.New()
396 if n, err := io.Copy(sum, tr); err != nil || n != h.Size {
397 return "", fmt.Errorf("reading MANIFEST: %v", err)
398 }
399 return hex.EncodeToString(sum.Sum(nil)), nil
400}
401