// Package render runs the page renderer: the pinned headless browser and // a server for one exported site, inside a bubblewrap sandbox with no // network but its own loopback (spec section 3, "Sandbox"). // // The runner calls Launch. Bubblewrap starts the runner's own binary as // the sandbox's first process, its render-sandbox subcommand // (SandboxMain), which serves /site on 127.0.0.1 and starts the browser // with --remote-debugging-pipe on descriptors 3 and 4. The runner holds // the other ends of that pipe and drives the browser over it. package render import ( "bytes" "errors" "io" "os" "os/exec" "sync" "time" ) // Subcommand is the runner's subcommand that is the sandbox's first // process. const Subcommand = "render-sandbox" // ExecSubcommand is the runner's subcommand that the launcher starts: it // closes every descriptor it should not have and executes bubblewrap. const ExecSubcommand = "render-exec" // ErrNotEnded is a sandbox whose processes could not be shown to have // ended: its init was never identified (no PID, no pidfd, no way to tell // the process at that PID is the init), or it did not end within // endBound of being killed, twice. Some of its processes may still run. // The runner needs attention: it is never a reason to try again. var ErrNotEnded = errors.New("render: the sandbox's processes did not end") // Paths inside the sandbox. const ( // BrowserPath is the pinned tree's program (renderer.json "program"), // seen through the tree bound at /usr. BrowserPath = "/usr/lib/chromium/chromium-headless-shell" // SiteDir holds the exported site, read only. SiteDir = "/site" // binaryPath is where the runner's own executable is bound, read only. binaryPath = "/runner" // browserHome is the browser's HOME and the parent of its profile: // the sandbox's tmpfs. browserHome = "/tmp" ) // HostResolverRules is the browser's --host-resolver-rules: every host // name is not found except the site server's own address. Direct IP // addresses never reach the resolver; the sandbox has no route for them. const HostResolverRules = "MAP * ~NOTFOUND, EXCLUDE 127.0.0.1" // Descriptors the sandbox's first process inherits, and nothing else // beyond 0, 1 and 2. const ( // fdBrowserIn and fdBrowserOut are the browser's // --remote-debugging-pipe: it reads CDP messages on 3 and writes on 4. fdBrowserIn = 3 fdBrowserOut = 4 // fdStatus is render-sandbox's status pipe (status lines, JSON). fdStatus = 5 ) // browserArgs is the browser's command line. Chromium's own sandbox stays // on: nothing here turns it off, and a host that cannot nest it fails to // start the browser rather than run it unsandboxed. func browserArgs() []string { return []string{ "--remote-debugging-pipe", "--host-resolver-rules=" + HostResolverRules, "--user-data-dir=" + browserHome + "/profile", "--disable-crash-reporter", "--no-first-run", "--enable-logging=stderr", "about:blank", } } // TmpSize bounds the sandbox's /tmp, a tmpfs (the browser's profile and // caches): a write past it fails with ENOSPC. tmpfs pages are memory no // process's resident set shows, so MemoryLimit does not cover them. const TmpSize = 512 << 20 // StartTimeout bounds how long Launch waits for the sandbox to report // ready when LaunchConfig.StartTimeout is zero. const StartTimeout = 30 * time.Second // LaunchConfig is how the runner starts a render sandbox. type LaunchConfig struct { // Bwrap is the pinned bubblewrap, an absolute path. Bwrap string // Binary is the runner's own executable, which carries the // render-sandbox subcommand. Symlinks are resolved on the host and // the file they name is bound. Binary string // Tree is the installed renderer tree and Pin the SHA-256 of its // MANIFEST that this runner links (release.RendererPin). Launch // verifies the tree against the pin before it mounts anything. Tree, Pin string // Site is the exported site, bound read only at /site. It must be a // directory this user owns that nobody else can write, reached // through no symlink. Site string // StartTimeout bounds the wait for the sandbox to report ready; zero // means StartTimeout. StartTimeout time.Duration // Stderr receives the sandbox's diagnostics (bubblewrap's, the // subcommand's and the browser's), bounded; nil discards them. Stderr io.Writer } // Sandbox is a running render sandbox. type Sandbox struct { // Site is the site server's address inside the sandbox, as // http://127.0.0.1:/. Only the browser can reach it. Site string // ToBrowser and FromBrowser are this side of the browser's // --remote-debugging-pipe: CDP messages, each ended by a NUL byte. ToBrowser *os.File FromBrowser *os.File done chan struct{} stop func() ready chan status stderr *bounded cmd *exec.Cmd mu sync.Mutex // pidfd is the sandbox's PID namespace init while state is // initHeld, or -1. pidfd int state initState exit BrowserExit // err is bubblewrap's; ended is ErrNotEnded or nil. err error ended error } // BrowserExit is how the browser ended, as render-sandbox saw it. Known // is false when the sandbox ended without reporting it. type BrowserExit struct { Known bool Code int Signal string } // status is one line render-sandbox writes on its status pipe. type status struct { // Event is "ready" (the site is served and the browser started), // "exit" (the browser ended) or "failed" (render-sandbox could not // go on; Reason says where). Event string `json:"event"` Site string `json:"site,omitempty"` Code int `json:"code,omitempty"` Signal string `json:"signal,omitempty"` Reason string `json:"reason,omitempty"` } // Reasons in a "failed" status. const ( reasonSite = "site" reasonBrowser = "browser" ) // Wait waits until every process of the sandbox has ended and returns // how the browser ended. The error is bubblewrap's (killed, or a // non-zero exit), joined with ErrNotEnded when the end of the sandbox's // processes could not be established; then some may still run. func (s *Sandbox) Wait() (BrowserExit, error) { <-s.done s.mu.Lock() defer s.mu.Unlock() return s.exit, errors.Join(s.err, s.ended) } // Close kills the sandbox and everything in it, waits until every one of // its processes has ended and closes this side of the browser's pipe. It // returns ErrNotEnded when that end could not be established. func (s *Sandbox) Close() error { s.stop() <-s.done s.ToBrowser.Close() s.FromBrowser.Close() s.mu.Lock() defer s.mu.Unlock() return s.ended } // bounded keeps the first max bytes written to it. type bounded struct { mu sync.Mutex buf bytes.Buffer max int } func (b *bounded) Write(p []byte) (int, error) { b.mu.Lock() defer b.mu.Unlock() if room := b.max - b.buf.Len(); room > 0 { b.buf.Write(p[:min(len(p), room)]) } return len(p), nil } func (b *bounded) Bytes() []byte { b.mu.Lock() defer b.mu.Unlock() return bytes.Clone(b.buf.Bytes()) } // What is known of a sandbox's PID namespace init. type initState int const ( // initUnknown: not identified; nothing shows the sandbox ended. initUnknown initState = iota // initHeld: the Sandbox's pidfd is the init. initHeld // initGone: the init had ended (so had its whole namespace) before // it could be held. initGone )