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