-
-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathindex.js
344 lines (299 loc) · 9.99 KB
/
index.js
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
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
/**
* @fileoverview Defines an {@linkplain cmd.Executor command executor} that
* communicates with a remote end using HTTP + JSON.
*/
'use strict'
const http = require('node:http')
const https = require('node:https')
const url = require('node:url')
const httpLib = require('../lib/http')
/**
* @typedef {{protocol: (?string|undefined),
* auth: (?string|undefined),
* hostname: (?string|undefined),
* host: (?string|undefined),
* port: (?string|undefined),
* path: (?string|undefined),
* pathname: (?string|undefined)}}
*/
let RequestOptions // eslint-disable-line
/**
* @param {string} aUrl The request URL to parse.
* @return {RequestOptions} The request options.
* @throws {Error} if the URL does not include a hostname.
*/
function getRequestOptions(aUrl) {
// eslint-disable-next-line n/no-deprecated-api
let options = url.parse(aUrl)
if (!options.hostname) {
throw new Error('Invalid URL: ' + aUrl)
}
// Delete the search and has portions as they are not used.
options.search = null
options.hash = null
options.path = options.pathname
options.hostname = options.hostname === 'localhost' ? '127.0.0.1' : options.hostname // To support Node 17 and above. Refer https://github.com/nodejs/node/issues/40702 for details.
return options
}
/** @const {string} */
const USER_AGENT = (function () {
const version = require('../package.json').version
const platform = { darwin: 'mac', win32: 'windows' }[process.platform] || 'linux'
return `selenium/${version} (js ${platform})`
})()
/**
* A basic HTTP client used to send messages to a remote end.
*
* @implements {httpLib.Client}
*/
class HttpClient {
/**
* @param {string} serverUrl URL for the WebDriver server to send commands to.
* @param {http.Agent=} opt_agent The agent to use for each request.
* Defaults to `http.globalAgent`.
* @param {?string=} opt_proxy The proxy to use for the connection to the
* server. Default is to use no proxy.
* @param {?Object.<string,Object>} client_options
*/
constructor(serverUrl, opt_agent, opt_proxy, client_options = {}) {
/** @private {http.Agent} */
this.agent_ = opt_agent || null
/**
* Base options for each request.
* @private {RequestOptions}
*/
this.options_ = getRequestOptions(serverUrl)
/**
* client options, header overrides
*/
this.client_options = client_options
/**
* sets keep-alive for the agent
* see https://stackoverflow.com/a/58332910
*/
this.keepAlive = this.client_options['keep-alive']
/** @private {?RequestOptions} */
this.proxyOptions_ = opt_proxy ? getRequestOptions(opt_proxy) : null
}
get keepAlive() {
return this.agent_.keepAlive
}
set keepAlive(value) {
if (value === 'true' || value === true) {
this.agent_.keepAlive = true
}
}
/** @override */
send(httpRequest) {
let data
let headers = {}
if (httpRequest.headers) {
httpRequest.headers.forEach(function (value, name) {
headers[name] = value
})
}
headers['User-Agent'] = this.client_options['user-agent'] || USER_AGENT
headers['Content-Length'] = 0
if (httpRequest.method == 'POST' || httpRequest.method == 'PUT') {
data = JSON.stringify(httpRequest.data)
headers['Content-Length'] = Buffer.byteLength(data, 'utf8')
headers['Content-Type'] = 'application/json;charset=UTF-8'
}
let path = this.options_.path
if (path.endsWith('/') && httpRequest.path.startsWith('/')) {
path += httpRequest.path.substring(1)
} else {
path += httpRequest.path
}
// eslint-disable-next-line n/no-deprecated-api
let parsedPath = url.parse(path)
let options = {
agent: this.agent_ || null,
method: httpRequest.method,
auth: this.options_.auth,
hostname: this.options_.hostname,
port: this.options_.port,
protocol: this.options_.protocol,
path: parsedPath.path,
pathname: parsedPath.pathname,
search: parsedPath.search,
hash: parsedPath.hash,
headers,
}
return new Promise((fulfill, reject) => {
sendRequest(options, fulfill, reject, data, this.proxyOptions_)
})
}
}
/**
* Sends a single HTTP request.
* @param {!Object} options The request options.
* @param {function(!httpLib.Response)} onOk The function to call if the
* request succeeds.
* @param {function(!Error)} onError The function to call if the request fails.
* @param {?string=} opt_data The data to send with the request.
* @param {?RequestOptions=} opt_proxy The proxy server to use for the request.
* @param {number=} opt_retries The current number of retries.
*/
function sendRequest(options, onOk, onError, opt_data, opt_proxy, opt_retries) {
var hostname = options.hostname
var port = options.port
if (opt_proxy) {
let proxy = /** @type {RequestOptions} */ (opt_proxy)
// RFC 2616, section 5.1.2:
// The absoluteURI form is REQUIRED when the request is being made to a
// proxy.
let absoluteUri = url.format(options)
// RFC 2616, section 14.23:
// An HTTP/1.1 proxy MUST ensure that any request message it forwards does
// contain an appropriate Host header field that identifies the service
// being requested by the proxy.
let targetHost = options.hostname
if (options.port) {
targetHost += ':' + options.port
}
// Update the request options with our proxy info.
options.headers['Host'] = targetHost
options.path = absoluteUri
options.host = proxy.host
options.hostname = proxy.hostname
options.port = proxy.port
// Update the protocol to avoid EPROTO errors when the webdriver proxy
// uses a different protocol from the remote selenium server.
options.protocol = opt_proxy.protocol
if (proxy.auth) {
options.headers['Proxy-Authorization'] = 'Basic ' + Buffer.from(proxy.auth).toString('base64')
}
}
let requestFn = options.protocol === 'https:' ? https.request : http.request
var request = requestFn(options, function onResponse(response) {
if (response.statusCode == 302 || response.statusCode == 303) {
let location
try {
// eslint-disable-next-line n/no-deprecated-api
location = url.parse(response.headers['location'])
} catch (ex) {
onError(
Error(
'Failed to parse "Location" header for server redirect: ' +
ex.message +
'\nResponse was: \n' +
new httpLib.Response(response.statusCode, response.headers, ''),
),
)
return
}
if (!location.hostname) {
location.hostname = hostname
location.port = port
location.auth = options.auth
}
request.destroy()
sendRequest(
{
method: 'GET',
protocol: location.protocol || options.protocol,
hostname: location.hostname,
port: location.port,
path: location.path,
auth: location.auth,
pathname: location.pathname,
search: location.search,
hash: location.hash,
headers: {
Accept: 'application/json; charset=utf-8',
'User-Agent': options.headers['User-Agent'] || USER_AGENT,
},
},
onOk,
onError,
undefined,
opt_proxy,
)
return
}
const body = []
response.on('data', body.push.bind(body))
response.on('end', function () {
const resp = new httpLib.Response(
/** @type {number} */ (response.statusCode),
/** @type {!Object<string>} */ (response.headers),
Buffer.concat(body).toString('utf8').replace(/\0/g, ''),
)
onOk(resp)
})
})
request.on('error', function (e) {
if (typeof opt_retries === 'undefined') {
opt_retries = 0
}
if (shouldRetryRequest(opt_retries, e)) {
opt_retries += 1
setTimeout(function () {
sendRequest(options, onOk, onError, opt_data, opt_proxy, opt_retries)
}, 15)
} else {
let message = e.message
if (e.code) {
message = e.code + ' ' + message
}
onError(new Error(message))
}
})
if (opt_data) {
request.write(opt_data)
}
request.end()
}
const MAX_RETRIES = 3
/**
* A retry is sometimes needed on Windows where we may quickly run out of
* ephemeral ports. A more robust solution is bumping the MaxUserPort setting
* as described here: http://msdn.microsoft.com/en-us/library/aa560610%28v=bts.20%29.aspx
*
* @param {!number} retries
* @param {!Error} err
* @return {boolean}
*/
function shouldRetryRequest(retries, err) {
return retries < MAX_RETRIES && isRetryableNetworkError(err)
}
/**
* @param {!Error} err
* @return {boolean}
*/
function isRetryableNetworkError(err) {
if (err && err.code) {
return (
err.code === 'ECONNABORTED' ||
err.code === 'ECONNRESET' ||
err.code === 'ECONNREFUSED' ||
err.code === 'EADDRINUSE' ||
err.code === 'EPIPE' ||
err.code === 'ETIMEDOUT'
)
}
return false
}
// PUBLIC API
module.exports.Agent = http.Agent
module.exports.Executor = httpLib.Executor
module.exports.HttpClient = HttpClient
module.exports.Request = httpLib.Request
module.exports.Response = httpLib.Response