vendor/github.com/go-rod/rod/lib/launcher/launcher.go
556 lines · 15038 bytes
1// Package launcher for launching browser utils.
2package launcher
3
4import (
5 "context"
6 "crypto"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "sort"
14 "strings"
15 "sync/atomic"
16
17 "github.com/go-rod/rod/lib/defaults"
18 "github.com/go-rod/rod/lib/launcher/flags"
19 "github.com/go-rod/rod/lib/utils"
20 "github.com/ysmood/leakless"
21)
22
23// DefaultUserDataDirPrefix ...
24var DefaultUserDataDirPrefix = filepath.Join(os.TempDir(), "rod", "user-data")
25
26// Launcher is a helper to launch browser binary smartly.
27type Launcher struct {
28 Flags map[flags.Flag][]string `json:"flags"`
29
30 ctx context.Context
31 ctxCancel func()
32
33 logger io.Writer
34
35 browser *Browser
36 parser *URLParser
37 pid int
38 exit chan struct{}
39
40 managed bool
41 serviceURL string
42
43 isLaunched int32 // zero means not launched
44}
45
46// New returns the default arguments to start browser.
47// Headless will be enabled by default.
48// Leakless will be enabled by default.
49// UserDataDir will use OS tmp dir by default, this folder will usually be cleaned up by the OS after reboot.
50// It will auto download the browser binary according to the current platform,
51// check [Launcher.Bin] and [Launcher.Revision] for more info.
52func New() *Launcher {
53 dir := defaults.Dir
54 if dir == "" {
55 dir = filepath.Join(DefaultUserDataDirPrefix, utils.RandString(8))
56 }
57
58 defaultFlags := map[flags.Flag][]string{
59 flags.Bin: {defaults.Bin},
60 flags.Leakless: nil,
61
62 flags.UserDataDir: {dir},
63
64 // use random port by default
65 flags.RemoteDebuggingPort: {defaults.Port},
66
67 // enable headless by default
68 flags.Headless: nil,
69
70 // to disable the init blank window
71 "no-first-run": nil,
72 "no-startup-window": nil,
73
74 // TODO: about the "site-per-process" see https://github.com/puppeteer/puppeteer/issues/2548
75 "disable-features": {"site-per-process", "TranslateUI"},
76
77 "disable-dev-shm-usage": nil,
78 "disable-background-networking": nil,
79 "disable-background-timer-throttling": nil,
80 "disable-backgrounding-occluded-windows": nil,
81 "disable-breakpad": nil,
82 "disable-client-side-phishing-detection": nil,
83 "disable-component-extensions-with-background-pages": nil,
84 "disable-default-apps": nil,
85 "disable-hang-monitor": nil,
86 "disable-ipc-flooding-protection": nil,
87 "disable-popup-blocking": nil,
88 "disable-prompt-on-repost": nil,
89 "disable-renderer-backgrounding": nil,
90 "disable-sync": nil,
91 "disable-site-isolation-trials": nil,
92 "enable-automation": nil,
93 "enable-features": {"NetworkService", "NetworkServiceInProcess"},
94 "force-color-profile": {"srgb"},
95 "metrics-recording-only": nil,
96 "use-mock-keychain": nil,
97 }
98
99 if defaults.Show {
100 delete(defaultFlags, flags.Headless)
101 }
102 if defaults.Devtools {
103 defaultFlags["auto-open-devtools-for-tabs"] = nil
104 }
105 if inContainer {
106 defaultFlags[flags.NoSandbox] = nil
107 }
108 if defaults.Proxy != "" {
109 defaultFlags[flags.ProxyServer] = []string{defaults.Proxy}
110 }
111
112 ctx, cancel := context.WithCancel(context.Background())
113 return &Launcher{
114 ctx: ctx,
115 ctxCancel: cancel,
116 Flags: defaultFlags,
117 exit: make(chan struct{}),
118 browser: NewBrowser(),
119 parser: NewURLParser(),
120 logger: io.Discard,
121 }
122}
123
124// NewUserMode is a preset to enable reusing current user data. Useful for automation of personal browser.
125// If you see any error, it may because you can't launch debug port for existing browser, the solution is to
126// completely close the running browser. Unfortunately, there's no API for rod to tell it automatically yet.
127func NewUserMode() *Launcher {
128 ctx, cancel := context.WithCancel(context.Background())
129 bin, _ := LookPath()
130
131 return &Launcher{
132 ctx: ctx,
133 ctxCancel: cancel,
134 Flags: map[flags.Flag][]string{
135 flags.RemoteDebuggingPort: {"37712"},
136 "no-startup-window": nil,
137 flags.Bin: {bin},
138 },
139 browser: NewBrowser(),
140 exit: make(chan struct{}),
141 parser: NewURLParser(),
142 logger: io.Discard,
143 }
144}
145
146// NewAppMode is a preset to run the browser like a native application.
147// The u should be a URL.
148func NewAppMode(u string) *Launcher {
149 l := New()
150 l.Set(flags.App, u).
151 Set(flags.Env, "GOOGLE_API_KEY=no").
152 Headless(false).
153 Delete("no-startup-window").
154 Delete("enable-automation")
155 return l
156}
157
158// Context sets the context.
159func (l *Launcher) Context(ctx context.Context) *Launcher {
160 ctx, cancel := context.WithCancel(ctx)
161 l.ctx = ctx
162 l.parser.Context(ctx)
163 l.ctxCancel = cancel
164 return l
165}
166
167// Set a command line argument when launching the browser.
168// Be careful the first argument is a flag name, it shouldn't contain values. The values the will be joined with comma.
169// A flag can have multiple values. If no values are provided the flag will be a boolean flag.
170// You can use the [Launcher.FormatArgs] to debug the final CLI arguments.
171// List of available flags: https://peter.sh/experiments/chromium-command-line-switches
172func (l *Launcher) Set(name flags.Flag, values ...string) *Launcher {
173 name.Check()
174 l.Flags[name.NormalizeFlag()] = values
175 return l
176}
177
178// Get flag's first value.
179func (l *Launcher) Get(name flags.Flag) string {
180 if list, has := l.GetFlags(name); has {
181 return list[0]
182 }
183 return ""
184}
185
186// Has flag or not.
187func (l *Launcher) Has(name flags.Flag) bool {
188 _, has := l.GetFlags(name)
189 return has
190}
191
192// GetFlags from settings.
193func (l *Launcher) GetFlags(name flags.Flag) ([]string, bool) {
194 flag, has := l.Flags[name.NormalizeFlag()]
195 return flag, has
196}
197
198// Append values to the flag.
199func (l *Launcher) Append(name flags.Flag, values ...string) *Launcher {
200 flags, has := l.GetFlags(name)
201 if !has {
202 flags = []string{}
203 }
204 return l.Set(name, append(flags, values...)...)
205}
206
207// Delete a flag.
208func (l *Launcher) Delete(name flags.Flag) *Launcher {
209 delete(l.Flags, name.NormalizeFlag())
210 return l
211}
212
213// Bin of the browser binary path to launch, if the path is not empty the auto download will be disabled.
214func (l *Launcher) Bin(path string) *Launcher {
215 return l.Set(flags.Bin, path)
216}
217
218// Revision of the browser to auto download.
219func (l *Launcher) Revision(rev int) *Launcher {
220 l.browser.Revision = rev
221 return l
222}
223
224// Headless switch. Whether to run browser in headless mode. A mode without visible UI.
225func (l *Launcher) Headless(enable bool) *Launcher {
226 if enable {
227 return l.Set(flags.Headless)
228 }
229 return l.Delete(flags.Headless)
230}
231
232// HeadlessNew switch is the "--headless=new" switch: https://developer.chrome.com/docs/chromium/new-headless
233func (l *Launcher) HeadlessNew(enable bool) *Launcher {
234 if enable {
235 return l.Set(flags.Headless, "new")
236 }
237 return l.Delete(flags.Headless)
238}
239
240// NoSandbox switch. Whether to run browser in no-sandbox mode.
241// Linux users may face "running as root without --no-sandbox is not supported" in some Linux/Chrome combinations.
242// This function helps switch mode easily.
243// Be aware disabling sandbox is not trivial. Use at your own risk.
244// Related doc: https://bugs.chromium.org/p/chromium/issues/detail?id=638180
245func (l *Launcher) NoSandbox(enable bool) *Launcher {
246 if enable {
247 return l.Set(flags.NoSandbox)
248 }
249 return l.Delete(flags.NoSandbox)
250}
251
252// XVFB enables to run browser in by XVFB. Useful when you want to run headful mode on linux.
253func (l *Launcher) XVFB(args ...string) *Launcher {
254 return l.Set(flags.XVFB, args...)
255}
256
257// Preferences set chromium user preferences, such as set the default search engine or disable the pdf viewer.
258// The pref is a json string, the doc is here
259// https://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/pref_names.cc
260func (l *Launcher) Preferences(pref string) *Launcher {
261 return l.Set(flags.Preferences, pref)
262}
263
264// AlwaysOpenPDFExternally switch.
265// It will set chromium user preferences to enable the always_open_pdf_externally option.
266func (l *Launcher) AlwaysOpenPDFExternally() *Launcher {
267 return l.Set(flags.Preferences, `{"plugins":{"always_open_pdf_externally": true}}`)
268}
269
270// Leakless switch. If enabled, the browser will be force killed after the Go process exits.
271// The doc of leakless: https://github.com/ysmood/leakless.
272func (l *Launcher) Leakless(enable bool) *Launcher {
273 if enable {
274 return l.Set(flags.Leakless)
275 }
276 return l.Delete(flags.Leakless)
277}
278
279// Devtools switch to auto open devtools for each tab.
280func (l *Launcher) Devtools(autoOpenForTabs bool) *Launcher {
281 if autoOpenForTabs {
282 return l.Set("auto-open-devtools-for-tabs")
283 }
284 return l.Delete("auto-open-devtools-for-tabs")
285}
286
287// IgnoreCerts configure the Chrome's ignore-certificate-errors-spki-list argument with the public keys.
288func (l *Launcher) IgnoreCerts(pks []crypto.PublicKey) error {
289 spkis := make([]string, 0, len(pks))
290
291 for _, pk := range pks {
292 spki, err := certSPKI(pk)
293 if err != nil {
294 return fmt.Errorf("certSPKI: %w", err)
295 }
296 spkis = append(spkis, string(spki))
297 }
298
299 l.Set("ignore-certificate-errors-spki-list", spkis...)
300
301 return nil
302}
303
304// UserDataDir is where the browser will look for all of its state, such as cookie and cache.
305// When set to empty, browser will use current OS home dir.
306// Related doc: https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md
307func (l *Launcher) UserDataDir(dir string) *Launcher {
308 if dir == "" {
309 l.Delete(flags.UserDataDir)
310 } else {
311 l.Set(flags.UserDataDir, dir)
312 }
313 return l
314}
315
316// ProfileDir is the browser profile the browser will use.
317// When set to empty, the profile 'Default' is used.
318// Related article: https://superuser.com/a/377195
319func (l *Launcher) ProfileDir(dir string) *Launcher {
320 if dir == "" {
321 l.Delete(flags.ProfileDir)
322 } else {
323 l.Set(flags.ProfileDir, dir)
324 }
325 return l
326}
327
328// RemoteDebuggingPort to launch the browser. Zero for a random port. Zero is the default value.
329// If it's not zero and the Launcher.Leakless is disabled, the launcher will try to reconnect to it first,
330// if the reconnection fails it will launch a new browser.
331func (l *Launcher) RemoteDebuggingPort(port int) *Launcher {
332 return l.Set(flags.RemoteDebuggingPort, fmt.Sprintf("%d", port))
333}
334
335// Proxy for the browser.
336func (l *Launcher) Proxy(host string) *Launcher {
337 return l.Set(flags.ProxyServer, host)
338}
339
340// WorkingDir to launch the browser process.
341func (l *Launcher) WorkingDir(path string) *Launcher {
342 return l.Set(flags.WorkingDir, path)
343}
344
345// Env to launch the browser process. The default value is [os.Environ]().
346// Usually you use it to set the timezone env. Such as:
347//
348// Env(append(os.Environ(), "TZ=Asia/Tokyo")...)
349func (l *Launcher) Env(env ...string) *Launcher {
350 return l.Set(flags.Env, env...)
351}
352
353// StartURL to launch.
354func (l *Launcher) StartURL(u string) *Launcher {
355 return l.Set("", u)
356}
357
358// FormatArgs returns the formatted arg list for cli.
359func (l *Launcher) FormatArgs() []string {
360 execArgs := []string{}
361 for k, v := range l.Flags {
362 if k == flags.Arguments {
363 continue
364 }
365
366 if strings.HasPrefix(string(k), "rod-") {
367 continue
368 }
369
370 // fix a bug of chrome, if path is not absolute chrome will hang
371 if k == flags.UserDataDir {
372 abs, err := filepath.Abs(v[0])
373 utils.E(err)
374 v[0] = abs
375 }
376
377 str := "--" + string(k)
378 if v != nil {
379 str += "=" + strings.Join(v, ",")
380 }
381 execArgs = append(execArgs, str)
382 }
383
384 execArgs = append(execArgs, l.Flags[flags.Arguments]...)
385 sort.Strings(execArgs)
386 return execArgs
387}
388
389// Logger to handle stdout and stderr from browser.
390// For example, pipe all browser output to stdout:
391//
392// launcher.New().Logger(os.Stdout)
393func (l *Launcher) Logger(w io.Writer) *Launcher {
394 l.logger = w
395 return l
396}
397
398// MustLaunch is similar to Launch.
399func (l *Launcher) MustLaunch() string {
400 u, err := l.Launch()
401 utils.E(err)
402 return u
403}
404
405// Launch a standalone temp browser instance and returns the debug url.
406// bin and profileDir are optional, set them to empty to use the default values.
407// If you want to reuse sessions, such as cookies, set the [Launcher.UserDataDir] to the same location.
408//
409// Please note launcher can only be used once.
410func (l *Launcher) Launch() (string, error) {
411 if l.hasLaunched() {
412 return "", ErrAlreadyLaunched
413 }
414
415 defer l.ctxCancel()
416
417 bin, err := l.getBin()
418 if err != nil {
419 return "", err
420 }
421
422 l.setupUserPreferences()
423
424 var ll *leakless.Launcher
425 var cmd *exec.Cmd
426
427 args := l.FormatArgs()
428
429 if l.Has(flags.Leakless) && leakless.Support() {
430 ll = leakless.New()
431 cmd = ll.Command(bin, args...)
432 } else {
433 port := l.Get(flags.RemoteDebuggingPort)
434 u, err := ResolveURL(port)
435 if err == nil {
436 return u, nil
437 }
438 cmd = exec.Command(bin, args...)
439 }
440
441 l.setupCmd(cmd)
442
443 err = cmd.Start()
444 if err != nil {
445 return "", err
446 }
447
448 if ll == nil {
449 l.pid = cmd.Process.Pid
450 } else {
451 l.pid = <-ll.Pid()
452 if ll.Err() != "" {
453 return "", errors.New(ll.Err())
454 }
455 }
456
457 go func() {
458 _ = cmd.Wait()
459 close(l.exit)
460 }()
461
462 u, err := l.getURL()
463 if err != nil {
464 l.Kill()
465 return "", err
466 }
467
468 return ResolveURL(u)
469}
470
471func (l *Launcher) hasLaunched() bool {
472 return !atomic.CompareAndSwapInt32(&l.isLaunched, 0, 1)
473}
474
475func (l *Launcher) setupUserPreferences() {
476 userDir := l.Get(flags.UserDataDir)
477 pref := l.Get(flags.Preferences)
478
479 if userDir == "" || pref == "" {
480 return
481 }
482
483 userDir, err := filepath.Abs(userDir)
484 utils.E(err)
485
486 profile := l.Get(flags.ProfileDir)
487 if profile == "" {
488 profile = "Default"
489 }
490
491 path := filepath.Join(userDir, profile, "Preferences")
492
493 utils.E(utils.OutputFile(path, pref))
494}
495
496func (l *Launcher) setupCmd(cmd *exec.Cmd) {
497 l.osSetupCmd(cmd)
498
499 dir := l.Get(flags.WorkingDir)
500 env, _ := l.GetFlags(flags.Env)
501 cmd.Dir = dir
502 cmd.Env = env
503
504 cmd.Stdout = io.MultiWriter(l.logger, l.parser)
505 cmd.Stderr = io.MultiWriter(l.logger, l.parser)
506}
507
508func (l *Launcher) getBin() (string, error) {
509 bin := l.Get(flags.Bin)
510 if bin == "" {
511 l.browser.Context = l.ctx
512 return l.browser.Get()
513 }
514 return bin, nil
515}
516
517func (l *Launcher) getURL() (u string, err error) {
518 select {
519 case <-l.ctx.Done():
520 err = l.ctx.Err()
521 case u = <-l.parser.URL:
522 case <-l.exit:
523 err = l.parser.Err()
524 }
525 return
526}
527
528// PID returns the browser process pid.
529func (l *Launcher) PID() int {
530 return l.pid
531}
532
533// Kill the browser process.
534func (l *Launcher) Kill() {
535 // TODO: If kill too fast, the browser's children processes may not be ready.
536 // Browser don't have an API to tell if the children processes are ready.
537 utils.Sleep(1)
538
539 if l.PID() == 0 { // avoid killing the current process
540 return
541 }
542
543 killGroup(l.PID())
544 p, err := os.FindProcess(l.PID())
545 if err == nil {
546 _ = p.Kill()
547 }
548}
549
550// Cleanup wait until the Browser exits and remove [flags.UserDataDir].
551func (l *Launcher) Cleanup() {
552 <-l.exit
553
554 dir := l.Get(flags.UserDataDir)
555 _ = os.RemoveAll(dir)
556}