Files
2026-12-04 13:02:12 +01:00

293 lines
9.2 KiB
Go

package remotebrowser
import (
"archive/zip"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
)
// pinnedBrowserVersion is the Chrome for Testing build that is downloaded
// when the server has no browser of its own. It is a build of the stable
// channel. scripts/bump-browser.sh writes this version and the checksums
// below when a release is prepared.
const pinnedBrowserVersion = "158.0.8127.107"
// browserBuild is the download of one platform
type browserBuild struct {
// platform is the name of the platform in the download address
platform string
// sha256 is the checksum of the zip file, in hex
sha256 string
// size is the size of the zip file in bytes
size int64
}
// pinnedBrowserBuilds are the downloads of pinnedBrowserVersion by GOARCH.
// Only Linux has a download.
var pinnedBrowserBuilds = map[string]browserBuild{
"amd64": {platform: "linux64", sha256: "6cd5523dce2a8fe69e1578f36602afcee2ddda3d89ca8030abe25d60929353f7", size: 208053173},
"arm64": {platform: "linux-arm64", sha256: "18368baabebfa6cef247752a0c2778f431ed03c3940f64befea8b8fe2cee6d10", size: 205800827},
}
// pinnedBrowserHost is where the browser is downloaded from. It is the
// storage of Google that Chrome for Testing is published on.
var pinnedBrowserHost = "https://storage.googleapis.com/chrome-for-testing-public"
// maxBrowserUnpacked is the most bytes a browser zip may unpack to
const maxBrowserUnpacked = 2 << 30
// browserDownloadTimeout is how long one download may take
const browserDownloadTimeout = 20 * time.Minute
// browserDownloadMu lets one download run at a time, so two sessions that
// start together do not both fetch the browser
var browserDownloadMu sync.Mutex
var browserDownloadLog = log.New(os.Stdout, "[browser download] ", log.LstdFlags)
// pinnedBrowserDir is the folder under rootDir the pinned browser is kept in
func pinnedBrowserDir(rootDir string) string {
return filepath.Join(rootDir, "chrome-"+pinnedBrowserVersion)
}
// pinnedBrowserBin is the path of the binary of the pinned browser
func pinnedBrowserBin(rootDir string) string {
return filepath.Join(pinnedBrowserDir(rootDir), "chrome")
}
// ensurePinnedBrowser returns the binary of the pinned browser under rootDir
// and downloads the browser first when it is not there.
func ensurePinnedBrowser(rootDir string) (string, error) {
bin := pinnedBrowserBin(rootDir)
if _, err := os.Stat(bin); err == nil {
return bin, nil
}
browserDownloadMu.Lock()
defer browserDownloadMu.Unlock()
// another session may have downloaded it while this one waited
if _, err := os.Stat(bin); err == nil {
return bin, nil
}
build, ok := pinnedBrowserBuilds[runtime.GOARCH]
if runtime.GOOS != "linux" || !ok {
return "", fmt.Errorf(
"no browser download for %s/%s: install Chrome or Chromium, or set remote_browser.exec_path",
runtime.GOOS, runtime.GOARCH,
)
}
ctx, cancel := context.WithTimeout(context.Background(), browserDownloadTimeout)
defer cancel()
if err := downloadBrowser(ctx, rootDir, build); err != nil {
return "", err
}
return bin, nil
}
// downloadBrowser fetches the zip of build, checks its size and checksum,
// unpacks it and moves it in place under rootDir. Nothing is left in place
// when a step fails. Browsers of other versions are removed at the end.
func downloadBrowser(ctx context.Context, rootDir string, build browserBuild) error {
if err := os.MkdirAll(rootDir, 0o755); err != nil {
return err
}
removeDownloadLeftovers(rootDir)
address := fmt.Sprintf("%s/%s/%s/chrome-%s.zip", pinnedBrowserHost, pinnedBrowserVersion, build.platform, build.platform)
browserDownloadLog.Printf("downloading Chrome for Testing %s from %s", pinnedBrowserVersion, address)
zipFile, err := os.CreateTemp(rootDir, browserZipPrefix+"*.zip")
if err != nil {
return err
}
defer os.Remove(zipFile.Name())
defer zipFile.Close()
if err := fetchBrowserZip(ctx, address, build, zipFile); err != nil {
return fmt.Errorf("browser download: %w", err)
}
unpacked, err := os.MkdirTemp(rootDir, browserUnpackPrefix+"*")
if err != nil {
return err
}
defer os.RemoveAll(unpacked)
if err := unpackBrowserZip(zipFile, build.size, unpacked); err != nil {
return fmt.Errorf("browser unpack: %w", err)
}
if _, err := os.Stat(filepath.Join(unpacked, "chrome")); err != nil {
return errors.New("browser unpack: the download holds no chrome binary")
}
// the temp folder is made private, the browser folder is not
if err := os.Chmod(unpacked, 0o755); err != nil {
return err
}
final := pinnedBrowserDir(rootDir)
if err := os.RemoveAll(final); err != nil {
return err
}
if err := os.Rename(unpacked, final); err != nil {
return err
}
removeOtherBrowsers(rootDir)
browserDownloadLog.Printf("Chrome for Testing %s is ready", pinnedBrowserVersion)
return nil
}
// fetchBrowserZip writes the zip at address to out and fails unless it has
// the size and the checksum of build. A redirect is not followed.
func fetchBrowserZip(ctx context.Context, address string, build browserBuild, out *os.File) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil)
if err != nil {
return err
}
client := &http.Client{
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("the server answered %s", resp.Status)
}
sum := sha256.New()
// one byte over the size shows a file that is too long
n, err := io.Copy(io.MultiWriter(out, sum), io.LimitReader(resp.Body, build.size+1))
if err != nil {
return err
}
if n != build.size {
return fmt.Errorf("the file is not %d bytes long", build.size)
}
if got := hex.EncodeToString(sum.Sum(nil)); got != build.sha256 {
return fmt.Errorf("the checksum %s is not the expected %s, the file is not used", got, build.sha256)
}
return nil
}
// unpackBrowserZip unpacks the browser zip into dir without the one top
// folder all its files are in. Only folders and plain files are written, and
// a path that would land outside dir fails the unpack.
func unpackBrowserZip(zipFile *os.File, size int64, dir string) error {
reader, err := zip.NewReader(zipFile, size)
if err != nil {
return err
}
var written int64
for _, entry := range reader.File {
// leave out the top folder: chrome-linux64/chrome becomes chrome
_, name, found := strings.Cut(filepath.ToSlash(entry.Name), "/")
if !found || name == "" {
continue
}
if !filepath.IsLocal(name) {
return fmt.Errorf("the path %q leaves the browser folder", entry.Name)
}
target := filepath.Join(dir, filepath.FromSlash(name))
mode := entry.Mode()
switch {
case mode.IsDir():
if err := os.MkdirAll(target, 0o755); err != nil {
return err
}
continue
case !mode.IsRegular():
return fmt.Errorf("%q is not a plain file", entry.Name)
}
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
// a file is 0755 when the zip marks it as a program, else 0644
perm := os.FileMode(0o644)
if mode.Perm()&0o111 != 0 {
perm = 0o755
}
n, err := unpackBrowserFile(entry, target, perm, maxBrowserUnpacked-written)
if err != nil {
return err
}
written += n
}
return nil
}
// unpackBrowserFile writes one file of the zip and fails when it holds more
// than left bytes
func unpackBrowserFile(entry *zip.File, target string, perm os.FileMode, left int64) (int64, error) {
in, err := entry.Open()
if err != nil {
return 0, err
}
defer in.Close()
out, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
if err != nil {
return 0, err
}
n, err := io.Copy(out, io.LimitReader(in, left+1))
if closeErr := out.Close(); err == nil {
err = closeErr
}
if err != nil {
return n, err
}
if n > left {
return n, errors.New("the download unpacks to more than the limit")
}
return n, nil
}
// names of the files a download works in under rootDir
const (
browserZipPrefix = "download-"
browserUnpackPrefix = "unpack-"
)
// removeDownloadLeftovers deletes what a download left under rootDir when
// the server was stopped in the middle of it. Only one download runs at a
// time, so nothing it finds is in use.
func removeDownloadLeftovers(rootDir string) {
entries, err := os.ReadDir(rootDir)
if err != nil {
return
}
for _, entry := range entries {
name := entry.Name()
if strings.HasPrefix(name, browserZipPrefix) || strings.HasPrefix(name, browserUnpackPrefix) {
os.RemoveAll(filepath.Join(rootDir, name)) //nolint:errcheck
}
}
}
// removeOtherBrowsers deletes the browsers of other versions under rootDir,
// which a download of an earlier release left there. The other folders in
// rootDir, such as the cache and the profile config, are kept.
func removeOtherBrowsers(rootDir string) {
entries, err := os.ReadDir(rootDir)
if err != nil {
return
}
current := filepath.Base(pinnedBrowserDir(rootDir))
for _, entry := range entries {
name := entry.Name()
if !entry.IsDir() || name == current {
continue
}
if strings.HasPrefix(name, "chromium-") || strings.HasPrefix(name, "chrome-") {
if err := os.RemoveAll(filepath.Join(rootDir, name)); err != nil {
browserDownloadLog.Printf("could not remove the old browser %s: %v", name, err)
}
}
}
}