forked from wirepair/webdriver
/
firefoxdriver.go
420 lines (382 loc) · 11.9 KB
/
firefoxdriver.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// Copyright 2013 Federico Sogaro. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package webdriver
import (
"archive/zip"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"time"
)
const (
cpferr = "create profile failed: "
)
type FirefoxDriver struct {
WebDriverCore
// The port firefox webdriver listens on. This port - 1 will be used as a mutex to avoid starting multiple firefox instances listening to the same port. Default: 7055
Port int
// Start method fails if lock (see Port) is not acquired before LockPortTimeout. Default 60s
LockPortTimeout time.Duration
// Start method fails if Firefox doesn't start in less than StartTimeout. Default 20s.
StartTimeout time.Duration
// Log file to dump firefox stdout/stderr. If "" send to terminal. Default: ""
LogFile string
// Firefox preferences. Default: see method GetDefaultPrefs
Prefs map[string]interface{}
// If temporary profile has to be deleted when closing. Default: true
DeleteProfileOnClose bool
// extensions to add to the profile on start.
extensions []string
firefoxPath string
xpiPath string
profilePath string
env map[string]string
cmd *exec.Cmd
logFile *os.File
}
func NewFirefoxDriver(firefoxPath string, xpiPath string) *FirefoxDriver {
d := &FirefoxDriver{}
d.firefoxPath = firefoxPath
d.xpiPath = xpiPath
d.Port = 0
d.LockPortTimeout = 60 * time.Second
d.StartTimeout = 20 * time.Second
d.LogFile = ""
d.Prefs = GetDefaultPrefs()
d.DeleteProfileOnClose = true
d.extensions = make([]string, 0)
d.env = make(map[string]string)
return d
}
// Equivalent to setting the following firefox preferences to:
// "webdriver.log.file": path/jsconsole.log
// "webdriver.log.driver.file": path/driver.log
// "webdriver.log.profiler.file": path/profiler.log
// "webdriver.log.browser.file": path/browser.log
func (d *FirefoxDriver) SetLogPath(path string) {
d.Prefs["webdriver.log.file"] = filepath.Join(path, "jsconsole.log")
d.Prefs["webdriver.log.driver.file"] = filepath.Join(path, "driver.log")
d.Prefs["webdriver.log.profiler.file"] = filepath.Join(path, "profiler.log")
d.Prefs["webdriver.log.browser.file"] = filepath.Join(path, "browser.log")
}
func (d *FirefoxDriver) SetEnvironment(key, value string) {
d.env[key] = value
}
func (d *FirefoxDriver) AddExtension(extPath string) {
d.extensions = append(d.extensions, extPath)
}
func (d *FirefoxDriver) Start() error {
if d.Port == 0 { //otherwise try to use that port
d.Port = 7055
lockPortAddress := fmt.Sprintf("127.0.0.1:%d", d.Port-1)
now := time.Now()
//try to lock port d.Port - 1
for {
if ln, err := net.Listen("tcp", lockPortAddress); err == nil {
defer ln.Close()
break
}
if time.Since(now) > d.LockPortTimeout {
return errors.New("timeout expired trying to lock mutex port")
}
time.Sleep(1 * time.Second)
}
//find the first available port starting with d.Port
for i := d.Port; i < 65535; i++ {
address := fmt.Sprintf("127.0.0.1:%d", i)
if ln, err := net.Listen("tcp", address); err == nil {
if err = ln.Close(); err != nil {
return err
}
d.Port = i
break
}
}
}
//start firefox with custom profile
//TODO it should be possible to use an existing profile
d.Prefs["webdriver_firefox_port"] = d.Port
var err error
d.profilePath, err = createTempProfile(d.xpiPath, d.Prefs, d.extensions)
if err != nil {
return err
}
debugprint(d.profilePath)
switches := []string{"-no-remote", "-profile", d.profilePath}
d.cmd, d.logFile, err = runBrowser(d.firefoxPath, switches, d.env, d.LogFile)
if err != nil {
return errors.New("unable to start firefox: " + err.Error())
}
if err = probePort(d.Port, d.StartTimeout); err != nil {
return err
}
d.url = fmt.Sprintf("http://127.0.0.1:%d/hub", d.Port)
return nil
}
// Populate a map with default firefox preferences
func GetDefaultPrefs() map[string]interface{} {
prefs := map[string]interface{}{
// Disable cache
"browser.cache.disk.enable": false,
"browser.cache.disk.capacity": 0,
"browser.cache.memory.enable": true,
//Allow extensions to be installed into the profile and still work
"extensions.autoDisableScopes": 10,
//Disable "do you want to remember this password?"
"signon.rememberSignons": false,
//Disable re-asking for license agreement
"browser.EULA.3.accepted": true,
"browser.EULA.override": true,
//set blank homepage, no welcome page
"browser.startup.homepage": "about:blank",
"browser.startup.page": 0,
"browser.startup.homepage_override.mstone": "ignore",
//browser mode online
"browser.offline": false,
// Don't ask if we want to switch default browsers
"browser.shell.checkDefaultBrowser": false,
//TODO configure proxy if needed ("network.proxy.type", "network.proxy.autoconfig_url"
//enable pop-ups
"dom.disable_open_during_load": false,
//disable dialog for long username/password in url
"network.http.phishy-userpass-length": 255,
//Disable security warnings
"security.warn_entering_secure": false,
"security.warn_entering_secure.show_once": false,
"security.warn_entering_weak": false,
"security.warn_entering_weak.show_once": false,
"security.warn_leaving_secure": false,
"security.warn_leaving_secure.show_once": false,
"security.warn_submit_insecure": false,
"security.warn_submit_insecure.show_once": false,
"security.warn_viewing_mixed": false,
"security.warn_viewing_mixed.show_once": false,
//Do not use NetworkManager to detect offline/online status.
"toolkit.networkmanager.disable": true,
//TODO disable script timeout (should be same as server timeout)
//"dom.max_script_run_time"
//("dom.max_chrome_script_run_time")
// Disable various autostuff
"app.update.auto": false,
"app.update.enabled": false,
"extensions.update.enabled": false,
"browser.search.update": false,
"extensions.blocklist.enabled": false,
"browser.safebrowsing.enabled": false,
"browser.safebrowsing.malware.enabled": false,
"browser.download.manager.showWhenStarting": false,
"browser.sessionstore.resume_from_crash": false,
"browser.tabs.warnOnClose": false,
"browser.tabs.warnOnOpen": false,
"devtools.errorconsole.enabled": true,
"extensions.logging.enabled": true,
"extensions.update.notifyUser": false,
"network.manage-offline-status": false,
"offline-apps.allow_by_default": true,
"prompts.tab_modal.enabled": false,
"security.fileuri.origin_policy": 3,
"security.fileuri.strict_origin_policy": false,
"toolkit.telemetry.prompted": 2,
"toolkit.telemetry.enabled": false,
"toolkit.telemetry.rejected": true,
"browser.dom.window.dump.enabled": true,
"dom.report_all_js_exceptions": true,
"javascript.options.showInConsole": true,
"network.http.max-connections-per-server": 10,
// Webdriver settings
"webdriver_accept_untrusted_certs": true,
"webdriver_assume_untrusted_issuer": true,
"webdriver_enable_native_events": false,
"webdriver_unexpected_alert_behaviour": "dismiss",
}
return prefs
}
type InstallRDF struct {
Description InstallRDFDescription
}
type InstallRDFDescription struct {
Id string `xml:"id"`
}
func createTempProfile(xpiPath string, prefs map[string]interface{}, extensions []string) (string, error) {
profilePath, err := ioutil.TempDir(os.TempDir(), "webdriver")
if err != nil {
return "", errors.New(cpferr + err.Error())
}
extsPath := filepath.Join(profilePath, "extensions")
err = os.Mkdir(extsPath, 0770)
if err != nil {
return "", errors.New(cpferr + err.Error())
}
err = writeXpi(xpiPath, extsPath)
if err != nil {
return "", err
}
err = writeUserExtensions(extensions, extsPath)
if err != nil {
return "", err
}
err = writeUserPrefs(profilePath, prefs)
if err != nil {
return "", err
}
return profilePath, nil
}
func writeUserPrefs(profilePath string, prefs map[string]interface{}) error {
fuserName := filepath.Join(profilePath, "user.js")
fuser, err := os.OpenFile(fuserName, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return errors.New(cpferr + err.Error())
}
defer fuser.Close()
for k, i := range prefs {
fuser.WriteString("user_pref(\"" + k + "\", ")
switch x := i.(type) {
case bool:
if x {
fuser.WriteString("true")
} else {
fuser.WriteString("false")
}
case int:
fuser.WriteString(strconv.Itoa(x))
case string:
fuser.WriteString("\"" + x + "\"")
default:
return errors.New(cpferr + "unexpected preference type: " + k)
}
fuser.WriteString(");\n")
}
return nil
}
func writeXpi(xpiPath, extsPath string) error {
var err error
var zr *zip.ReadCloser
var extName string
zr, err = zip.OpenReader(xpiPath)
if err != nil {
return errors.New(cpferr + err.Error())
}
defer zr.Close()
extName, err = readIdFromInstallRdf(zr)
if err != nil {
return err
}
extPath := filepath.Join(extsPath, extName)
err = os.Mkdir(extPath, 0770)
if err != nil {
return errors.New(cpferr + err.Error())
}
for _, f := range zr.File {
if err = writeExtensionFile(f, extPath); err != nil {
return err
}
}
return nil
}
func writeUserExtensions(extensions []string, extsPath string) error {
for _, ext := range extensions {
err := writeXpi(ext, extsPath)
if err != nil {
return err
}
}
return nil
}
func readIdFromInstallRdf(zr *zip.ReadCloser) (string, error) {
for _, f := range zr.File {
if f.Name == "install.rdf" {
rc, err := f.Open()
if err != nil {
return "", errors.New(cpferr + err.Error())
}
buf, err := ioutil.ReadAll(rc)
if err != nil {
return "", errors.New(cpferr + err.Error())
}
rc.Close()
installRDF := InstallRDF{}
err = xml.Unmarshal(buf, &installRDF)
if err != nil {
return "", errors.New(cpferr + err.Error())
}
if installRDF.Description.Id == "" {
return "", errors.New(cpferr + "unable to find extension Id from install.rdf")
}
return installRDF.Description.Id, nil
}
}
return "", errors.New(cpferr + "unable to find install.rdf or extension Id from extension")
}
func writeExtensionFile(f *zip.File, extPath string) error {
weferr := "write extension failed: "
rc, err := f.Open()
if err != nil {
return errors.New(weferr + err.Error())
}
defer rc.Close()
filename := filepath.Join(extPath, f.Name)
// empty files will not create directories, do it manually.
if f.FileInfo().Size() == 0 {
os.MkdirAll(filepath.Dir(filename), 0770)
}
if f.FileInfo().IsDir() {
os.MkdirAll(filename, 0770)
} else {
dst, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return errors.New(weferr + err.Error())
}
defer dst.Close()
_, err = io.Copy(dst, rc)
if err != nil {
return errors.New(weferr + err.Error())
}
}
return nil
}
func (d *FirefoxDriver) Stop() error {
if d.cmd == nil {
return errors.New("stop failed: firefoxdriver not running")
}
defer func() {
d.cmd = nil
}()
d.cmd.Process.Signal(os.Interrupt)
if d.logFile != nil {
d.logFile.Close()
}
if d.DeleteProfileOnClose {
os.RemoveAll(d.profilePath)
}
return nil
}
func (d *FirefoxDriver) NewSession(desired, required Capabilities) (*Session, error) {
session, err := d.newSession(desired, required)
if err != nil {
return nil, err
}
session.wd = d
return session, nil
}
func (d *FirefoxDriver) Sessions() ([]Session, error) {
sessions, err := d.sessions()
if err != nil {
return nil, err
}
for i := range sessions {
sessions[i].wd = d
}
return sessions, nil
}
/*func (d *FirefoxDriver) NewSession(desired, required Capabilities) (*Session, error) {
id, capabs, err := d.newSession(desired, required)
return &Session{id, capabs, d}, err
}*/