vendor/github.com/go-rod/rod/lib/launcher/manager.go

211 lines · 6028 bytes

  1package launcher
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"net/http"
  7	"net/http/httputil"
  8	"net/url"
  9	"os"
 10	"strings"
 11
 12	"github.com/go-rod/rod/lib/cdp"
 13	"github.com/go-rod/rod/lib/launcher/flags"
 14	"github.com/go-rod/rod/lib/utils"
 15)
 16
 17const (
 18	// HeaderName for remote launch.
 19	HeaderName = "Rod-Launcher"
 20)
 21
 22// MustNewManaged is similar to NewManaged.
 23func MustNewManaged(serviceURL string) *Launcher {
 24	l, err := NewManaged(serviceURL)
 25	utils.E(err)
 26
 27	// TODO: remove this after we have a better way to handle this
 28	// The latest chromium in docker will crash pages that use http2
 29	l.Set("disable-http2")
 30
 31	return l
 32}
 33
 34// NewManaged creates a default Launcher instance from launcher.Manager.
 35// The serviceURL must point to a launcher.Manager. It will send a http request to the serviceURL
 36// to get the default settings of the Launcher instance. For example if the launcher.Manager running on a
 37// Linux machine will return different default settings from the one on Mac.
 38// If Launcher.Leakless is enabled, the remote browser will be killed after the websocket is closed.
 39func NewManaged(serviceURL string) (*Launcher, error) {
 40	if serviceURL == "" {
 41		serviceURL = "ws://127.0.0.1:7317"
 42	}
 43
 44	u, err := url.Parse(serviceURL)
 45	if err != nil {
 46		return nil, err
 47	}
 48
 49	l := New()
 50	l.managed = true
 51	l.serviceURL = toWS(*u).String()
 52	l.Flags = nil
 53
 54	res, err := http.Get(toHTTP(*u).String()) //nolint: noctx
 55	if err != nil {
 56		return nil, err
 57	}
 58	defer func() { _ = res.Body.Close() }()
 59
 60	return l, json.NewDecoder(res.Body).Decode(l)
 61}
 62
 63// KeepUserDataDir after remote browser is closed. By default launcher.FlagUserDataDir will be removed.
 64func (l *Launcher) KeepUserDataDir() *Launcher {
 65	l.mustManaged()
 66	l.Set(flags.KeepUserDataDir)
 67	return l
 68}
 69
 70// JSON serialization.
 71func (l *Launcher) JSON() []byte {
 72	return utils.MustToJSONBytes(l)
 73}
 74
 75// MustClient similar to Launcher.Client.
 76func (l *Launcher) MustClient() *cdp.Client {
 77	u, h := l.ClientHeader()
 78	return cdp.MustStartWithURL(l.ctx, u, h)
 79}
 80
 81// Client for launching browser remotely via the launcher.Manager.
 82func (l *Launcher) Client() (*cdp.Client, error) {
 83	u, h := l.ClientHeader()
 84	return cdp.StartWithURL(l.ctx, u, h)
 85}
 86
 87// ClientHeader for launching browser remotely via the launcher.Manager.
 88func (l *Launcher) ClientHeader() (string, http.Header) {
 89	l.mustManaged()
 90	header := http.Header{}
 91	header.Add(string(HeaderName), utils.MustToJSON(l))
 92	return l.serviceURL, header
 93}
 94
 95func (l *Launcher) mustManaged() {
 96	if !l.managed {
 97		panic("Must be used with launcher.NewManaged")
 98	}
 99}
100
101var _ http.Handler = &Manager{}
102
103// Manager is used to launch browsers via http server on another machine.
104// The reason why we have Manager is after we launcher a browser, we can't dynamically change its
105// CLI arguments, such as "--headless". The Manager allows us to decide what CLI arguments to
106// pass to the browser when launch it remotely.
107// The work flow looks like:
108//
109//	|      Machine X       |                             Machine Y                                    |
110//	| NewManaged("a.com") -|-> http.ListenAndServe("a.com", launcher.NewManager()) --> launch browser |
111//
112//	1. X send a http request to Y, Y respond default Launcher settings based the OS of Y.
113//	2. X start a websocket connect to Y with the Launcher settings
114//	3. Y launches a browser with the Launcher settings X
115//	4. Y transparently proxy the websocket connect between X and the launched browser
116type Manager struct {
117	// Logger for key events
118	Logger utils.Logger
119
120	// Defaults should return the default Launcher settings
121	Defaults func(http.ResponseWriter, *http.Request) *Launcher
122
123	// BeforeLaunch hook is called right before the launching with the Launcher instance that will be used
124	// to launch the browser.
125	// Such as use it to filter malicious values of Launcher.UserDataDir, Launcher.Bin, or Launcher.WorkingDir.
126	BeforeLaunch func(*Launcher, http.ResponseWriter, *http.Request)
127}
128
129// NewManager instance.
130func NewManager() *Manager {
131	allowedPath := map[flags.Flag]string{
132		flags.Bin: DefaultBrowserDir,
133		flags.WorkingDir: func() string {
134			p, _ := os.Getwd()
135			return p
136		}(),
137		flags.UserDataDir: DefaultUserDataDirPrefix,
138	}
139
140	return &Manager{
141		Logger:   utils.LoggerQuiet,
142		Defaults: func(_ http.ResponseWriter, _ *http.Request) *Launcher { return New() },
143		BeforeLaunch: func(l *Launcher, w http.ResponseWriter, _ *http.Request) {
144			for f, allowed := range allowedPath {
145				p := l.Get(f)
146				if p != "" && !strings.HasPrefix(p, allowed) {
147					b := []byte(fmt.Sprintf("[rod-manager] not allowed %s path: %s (use --allow-all to disable the protection)", f, p))
148					w.Header().Add("Content-Length", fmt.Sprintf("%d", len(b)))
149					w.WriteHeader(http.StatusBadRequest)
150					utils.E(w.Write(b))
151					w.(http.Flusher).Flush() //nolint: forcetypeassert
152					panic(http.ErrAbortHandler)
153				}
154			}
155		},
156	}
157}
158
159func (m *Manager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
160	if r.Header.Get("Upgrade") == "websocket" {
161		m.launch(w, r)
162		return
163	}
164
165	l := m.Defaults(w, r)
166	utils.E(w.Write(l.JSON()))
167}
168
169func (m *Manager) launch(w http.ResponseWriter, r *http.Request) {
170	l := New()
171
172	options := r.Header.Get(string(HeaderName))
173	if options != "" {
174		l.Flags = nil
175		utils.E(json.Unmarshal([]byte(options), l))
176	}
177
178	m.BeforeLaunch(l, w, r)
179
180	kill := l.Has(flags.Leakless)
181
182	// Always enable leakless so that if the Manager process crashes
183	// all the managed browsers will be killed.
184	u := l.Leakless(true).MustLaunch()
185	defer m.cleanup(l, kill)
186
187	parsedURL, err := url.Parse(u)
188	utils.E(err)
189
190	m.Logger.Println("Launch", u, options)
191	defer m.Logger.Println("Close", u)
192
193	parsedWS, err := url.Parse(u)
194	utils.E(err)
195	parsedURL.Path = parsedWS.Path
196
197	httputil.NewSingleHostReverseProxy(toHTTP(*parsedURL)).ServeHTTP(w, r)
198}
199
200func (m *Manager) cleanup(l *Launcher, kill bool) {
201	if kill {
202		l.Kill()
203		m.Logger.Println("Killed PID:", l.PID())
204	}
205
206	if !l.Has(flags.KeepUserDataDir) {
207		l.Cleanup()
208		dir := l.Get(flags.UserDataDir)
209		m.Logger.Println("Removed", dir)
210	}
211}