oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package render runs the page renderer: the pinned headless browser and
2// a server for one exported site, inside a bubblewrap sandbox with no
3// network but its own loopback (spec section 3, "Sandbox").
4//
5// The runner calls Launch. Bubblewrap starts the runner's own binary as
6// the sandbox's first process, its render-sandbox subcommand
7// (SandboxMain), which serves /site on 127.0.0.1 and starts the browser
8// with --remote-debugging-pipe on descriptors 3 and 4. The runner holds
9// the other ends of that pipe and drives the browser over it.
10package render
11
12import (
13 "bytes"
14 "errors"
15 "io"
16 "os"
17 "os/exec"
18 "sync"
19 "time"
20)
21
22// Subcommand is the runner's subcommand that is the sandbox's first
23// process.
24const Subcommand = "render-sandbox"
25
26// ExecSubcommand is the runner's subcommand that the launcher starts: it
27// closes every descriptor it should not have and executes bubblewrap.
28const ExecSubcommand = "render-exec"
29
30// ErrNotEnded is a sandbox whose processes could not be shown to have
31// ended: its init was never identified (no PID, no pidfd, no way to tell
32// the process at that PID is the init), or it did not end within
33// endBound of being killed, twice. Some of its processes may still run.
34// The runner needs attention: it is never a reason to try again.
35var ErrNotEnded = errors.New("render: the sandbox's processes did not end")
36
37// Paths inside the sandbox.
38const (
39 // BrowserPath is the pinned tree's program (renderer.json "program"),
40 // seen through the tree bound at /usr.
41 BrowserPath = "/usr/lib/chromium/chromium-headless-shell"
42 // SiteDir holds the exported site, read only.
43 SiteDir = "/site"
44 // binaryPath is where the runner's own executable is bound, read only.
45 binaryPath = "/runner"
46 // browserHome is the browser's HOME and the parent of its profile:
47 // the sandbox's tmpfs.
48 browserHome = "/tmp"
49)
50
51// HostResolverRules is the browser's --host-resolver-rules: every host
52// name is not found except the site server's own address. Direct IP
53// addresses never reach the resolver; the sandbox has no route for them.
54const HostResolverRules = "MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"
55
56// Descriptors the sandbox's first process inherits, and nothing else
57// beyond 0, 1 and 2.
58const (
59 // fdBrowserIn and fdBrowserOut are the browser's
60 // --remote-debugging-pipe: it reads CDP messages on 3 and writes on 4.
61 fdBrowserIn = 3
62 fdBrowserOut = 4
63 // fdStatus is render-sandbox's status pipe (status lines, JSON).
64 fdStatus = 5
65)
66
67// browserArgs is the browser's command line. Chromium's own sandbox stays
68// on: nothing here turns it off, and a host that cannot nest it fails to
69// start the browser rather than run it unsandboxed.
70func browserArgs() []string {
71 return []string{
72 "--remote-debugging-pipe",
73 "--host-resolver-rules=" + HostResolverRules,
74 "--user-data-dir=" + browserHome + "/profile",
75 "--disable-crash-reporter",
76 "--no-first-run",
77 "--enable-logging=stderr",
78 "about:blank",
79 }
80}
81
82// TmpSize bounds the sandbox's /tmp, a tmpfs (the browser's profile and
83// caches): a write past it fails with ENOSPC. tmpfs pages are memory no
84// process's resident set shows, so MemoryLimit does not cover them.
85const TmpSize = 512 << 20
86
87// StartTimeout bounds how long Launch waits for the sandbox to report
88// ready when LaunchConfig.StartTimeout is zero.
89const StartTimeout = 30 * time.Second
90
91// LaunchConfig is how the runner starts a render sandbox.
92type LaunchConfig struct {
93 // Bwrap is the pinned bubblewrap, an absolute path.
94 Bwrap string
95 // Binary is the runner's own executable, which carries the
96 // render-sandbox subcommand. Symlinks are resolved on the host and
97 // the file they name is bound.
98 Binary string
99 // Tree is the installed renderer tree and Pin the SHA-256 of its
100 // MANIFEST that this runner links (release.RendererPin). Launch
101 // verifies the tree against the pin before it mounts anything.
102 Tree, Pin string
103 // Site is the exported site, bound read only at /site. It must be a
104 // directory this user owns that nobody else can write, reached
105 // through no symlink.
106 Site string
107 // StartTimeout bounds the wait for the sandbox to report ready; zero
108 // means StartTimeout.
109 StartTimeout time.Duration
110 // Stderr receives the sandbox's diagnostics (bubblewrap's, the
111 // subcommand's and the browser's), bounded; nil discards them.
112 Stderr io.Writer
113}
114
115// Sandbox is a running render sandbox.
116type Sandbox struct {
117 // Site is the site server's address inside the sandbox, as
118 // http://127.0.0.1:<port>/. Only the browser can reach it.
119 Site string
120 // ToBrowser and FromBrowser are this side of the browser's
121 // --remote-debugging-pipe: CDP messages, each ended by a NUL byte.
122 ToBrowser *os.File
123 FromBrowser *os.File
124
125 done chan struct{}
126 stop func()
127 ready chan status
128 stderr *bounded
129 cmd *exec.Cmd
130
131 mu sync.Mutex
132 // pidfd is the sandbox's PID namespace init while state is
133 // initHeld, or -1.
134 pidfd int
135 state initState
136 exit BrowserExit
137 // err is bubblewrap's; ended is ErrNotEnded or nil.
138 err error
139 ended error
140}
141
142// BrowserExit is how the browser ended, as render-sandbox saw it. Known
143// is false when the sandbox ended without reporting it.
144type BrowserExit struct {
145 Known bool
146 Code int
147 Signal string
148}
149
150// status is one line render-sandbox writes on its status pipe.
151type status struct {
152 // Event is "ready" (the site is served and the browser started),
153 // "exit" (the browser ended) or "failed" (render-sandbox could not
154 // go on; Reason says where).
155 Event string `json:"event"`
156 Site string `json:"site,omitempty"`
157 Code int `json:"code,omitempty"`
158 Signal string `json:"signal,omitempty"`
159 Reason string `json:"reason,omitempty"`
160}
161
162// Reasons in a "failed" status.
163const (
164 reasonSite = "site"
165 reasonBrowser = "browser"
166)
167
168// Wait waits until every process of the sandbox has ended and returns
169// how the browser ended. The error is bubblewrap's (killed, or a
170// non-zero exit), joined with ErrNotEnded when the end of the sandbox's
171// processes could not be established; then some may still run.
172func (s *Sandbox) Wait() (BrowserExit, error) {
173 <-s.done
174 s.mu.Lock()
175 defer s.mu.Unlock()
176 return s.exit, errors.Join(s.err, s.ended)
177}
178
179// Close kills the sandbox and everything in it, waits until every one of
180// its processes has ended and closes this side of the browser's pipe. It
181// returns ErrNotEnded when that end could not be established.
182func (s *Sandbox) Close() error {
183 s.stop()
184 <-s.done
185 s.ToBrowser.Close()
186 s.FromBrowser.Close()
187 s.mu.Lock()
188 defer s.mu.Unlock()
189 return s.ended
190}
191
192// bounded keeps the first max bytes written to it.
193type bounded struct {
194 mu sync.Mutex
195 buf bytes.Buffer
196 max int
197}
198
199func (b *bounded) Write(p []byte) (int, error) {
200 b.mu.Lock()
201 defer b.mu.Unlock()
202 if room := b.max - b.buf.Len(); room > 0 {
203 b.buf.Write(p[:min(len(p), room)])
204 }
205 return len(p), nil
206}
207
208func (b *bounded) Bytes() []byte {
209 b.mu.Lock()
210 defer b.mu.Unlock()
211 return bytes.Clone(b.buf.Bytes())
212}
213
214// What is known of a sandbox's PID namespace init.
215type initState int
216
217const (
218 // initUnknown: not identified; nothing shows the sandbox ended.
219 initUnknown initState = iota
220 // initHeld: the Sandbox's pidfd is the init.
221 initHeld
222 // initGone: the init had ended (so had its whole namespace) before
223 // it could be held.
224 initGone
225)
226