Path: blob/trunk/javascript/selenium-webdriver/http/index.js
3220 views
// Licensed to the Software Freedom Conservancy (SFC) under one1// or more contributor license agreements. See the NOTICE file2// distributed with this work for additional information3// regarding copyright ownership. The SFC licenses this file4// to you under the Apache License, Version 2.0 (the5// "License"); you may not use this file except in compliance6// with the License. You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing,11// software distributed under the License is distributed on an12// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13// KIND, either express or implied. See the License for the14// specific language governing permissions and limitations15// under the License.1617/**18* @fileoverview Defines an {@linkplain cmd.Executor command executor} that19* communicates with a remote end using HTTP + JSON.20*/2122'use strict'2324const http = require('node:http')25const https = require('node:https')26const url = require('node:url')2728const httpLib = require('../lib/http')2930/**31* @typedef {{protocol: (?string|undefined),32* auth: (?string|undefined),33* hostname: (?string|undefined),34* host: (?string|undefined),35* port: (?string|undefined),36* path: (?string|undefined),37* pathname: (?string|undefined)}}38*/39let RequestOptions // eslint-disable-line4041/**42* @param {string} aUrl The request URL to parse.43* @return {RequestOptions} The request options.44* @throws {Error} if the URL does not include a hostname.45*/46function getRequestOptions(aUrl) {47// eslint-disable-next-line n/no-deprecated-api48let options = url.parse(aUrl)49if (!options.hostname) {50throw new Error('Invalid URL: ' + aUrl)51}52// Delete the search and has portions as they are not used.53options.search = null54options.hash = null55options.path = options.pathname56options.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.57return options58}5960/** @const {string} */61const USER_AGENT = (function () {62const version = require('../package.json').version63const platform = { darwin: 'mac', win32: 'windows' }[process.platform] || 'linux'64return `selenium/${version} (js ${platform})`65})()6667/**68* A basic HTTP client used to send messages to a remote end.69*70* @implements {httpLib.Client}71*/72class HttpClient {73/**74* @param {string} serverUrl URL for the WebDriver server to send commands to.75* @param {http.Agent=} opt_agent The agent to use for each request.76* Defaults to `http.globalAgent`.77* @param {?string=} opt_proxy The proxy to use for the connection to the78* server. Default is to use no proxy.79* @param {?Object.<string,Object>} client_options80*/81constructor(serverUrl, opt_agent, opt_proxy, client_options = {}) {82/** @private {http.Agent} */83this.agent_ = opt_agent || null8485/**86* Base options for each request.87* @private {RequestOptions}88*/89this.options_ = getRequestOptions(serverUrl)9091/**92* client options, header overrides93*/94this.client_options = client_options9596/**97* sets keep-alive for the agent98* see https://stackoverflow.com/a/5833291099*/100this.keepAlive = this.client_options['keep-alive']101102/** @private {?RequestOptions} */103this.proxyOptions_ = opt_proxy ? getRequestOptions(opt_proxy) : null104}105106get keepAlive() {107return this.agent_.keepAlive108}109110set keepAlive(value) {111if (value === 'true' || value === true) {112this.agent_.keepAlive = true113}114}115116/** @override */117send(httpRequest) {118let data119120let headers = {}121122if (httpRequest.headers) {123httpRequest.headers.forEach(function (value, name) {124headers[name] = value125})126}127128headers['User-Agent'] = this.client_options['user-agent'] || USER_AGENT129headers['Content-Length'] = 0130if (httpRequest.method == 'POST' || httpRequest.method == 'PUT') {131data = JSON.stringify(httpRequest.data)132headers['Content-Length'] = Buffer.byteLength(data, 'utf8')133headers['Content-Type'] = 'application/json;charset=UTF-8'134}135136let path = this.options_.path137if (path.endsWith('/') && httpRequest.path.startsWith('/')) {138path += httpRequest.path.substring(1)139} else {140path += httpRequest.path141}142// eslint-disable-next-line n/no-deprecated-api143let parsedPath = url.parse(path)144145let options = {146agent: this.agent_ || null,147method: httpRequest.method,148149auth: this.options_.auth,150hostname: this.options_.hostname,151port: this.options_.port,152protocol: this.options_.protocol,153154path: parsedPath.path,155pathname: parsedPath.pathname,156search: parsedPath.search,157hash: parsedPath.hash,158159headers,160}161162return new Promise((fulfill, reject) => {163sendRequest(options, fulfill, reject, data, this.proxyOptions_)164})165}166}167168/**169* Sends a single HTTP request.170* @param {!Object} options The request options.171* @param {function(!httpLib.Response)} onOk The function to call if the172* request succeeds.173* @param {function(!Error)} onError The function to call if the request fails.174* @param {?string=} opt_data The data to send with the request.175* @param {?RequestOptions=} opt_proxy The proxy server to use for the request.176* @param {number=} opt_retries The current number of retries.177*/178function sendRequest(options, onOk, onError, opt_data, opt_proxy, opt_retries) {179var hostname = options.hostname180var port = options.port181182if (opt_proxy) {183let proxy = /** @type {RequestOptions} */ (opt_proxy)184185// RFC 2616, section 5.1.2:186// The absoluteURI form is REQUIRED when the request is being made to a187// proxy.188let absoluteUri = url.format(options)189190// RFC 2616, section 14.23:191// An HTTP/1.1 proxy MUST ensure that any request message it forwards does192// contain an appropriate Host header field that identifies the service193// being requested by the proxy.194let targetHost = options.hostname195if (options.port) {196targetHost += ':' + options.port197}198199// Update the request options with our proxy info.200options.headers['Host'] = targetHost201options.path = absoluteUri202options.host = proxy.host203options.hostname = proxy.hostname204options.port = proxy.port205206// Update the protocol to avoid EPROTO errors when the webdriver proxy207// uses a different protocol from the remote selenium server.208options.protocol = opt_proxy.protocol209210if (proxy.auth) {211options.headers['Proxy-Authorization'] = 'Basic ' + Buffer.from(proxy.auth).toString('base64')212}213}214215let requestFn = options.protocol === 'https:' ? https.request : http.request216var request = requestFn(options, function onResponse(response) {217if (response.statusCode == 302 || response.statusCode == 303) {218let location219try {220// eslint-disable-next-line n/no-deprecated-api221location = url.parse(response.headers['location'])222} catch (ex) {223onError(224Error(225'Failed to parse "Location" header for server redirect: ' +226ex.message +227'\nResponse was: \n' +228new httpLib.Response(response.statusCode, response.headers, ''),229),230)231return232}233234if (!location.hostname) {235location.hostname = hostname236location.port = port237location.auth = options.auth238}239240request.destroy()241sendRequest(242{243method: 'GET',244protocol: location.protocol || options.protocol,245hostname: location.hostname,246port: location.port,247path: location.path,248auth: location.auth,249pathname: location.pathname,250search: location.search,251hash: location.hash,252headers: {253Accept: 'application/json; charset=utf-8',254'User-Agent': options.headers['User-Agent'] || USER_AGENT,255},256},257onOk,258onError,259undefined,260opt_proxy,261)262return263}264265const body = []266response.on('data', body.push.bind(body))267response.on('end', function () {268const resp = new httpLib.Response(269/** @type {number} */ (response.statusCode),270/** @type {!Object<string>} */ (response.headers),271Buffer.concat(body).toString('utf8').replace(/\0/g, ''),272)273onOk(resp)274})275})276277request.on('error', function (e) {278if (typeof opt_retries === 'undefined') {279opt_retries = 0280}281282if (shouldRetryRequest(opt_retries, e)) {283opt_retries += 1284setTimeout(function () {285sendRequest(options, onOk, onError, opt_data, opt_proxy, opt_retries)286}, 15)287} else {288let message = e.message289if (e.code) {290message = e.code + ' ' + message291}292onError(new Error(message))293}294})295296if (opt_data) {297request.write(opt_data)298}299300request.end()301}302303const MAX_RETRIES = 3304305/**306* A retry is sometimes needed on Windows where we may quickly run out of307* ephemeral ports. A more robust solution is bumping the MaxUserPort setting308* as described here: http://msdn.microsoft.com/en-us/library/aa560610%28v=bts.20%29.aspx309*310* @param {!number} retries311* @param {!Error} err312* @return {boolean}313*/314function shouldRetryRequest(retries, err) {315return retries < MAX_RETRIES && isRetryableNetworkError(err)316}317318/**319* @param {!Error} err320* @return {boolean}321*/322function isRetryableNetworkError(err) {323if (err && err.code) {324return (325err.code === 'ECONNABORTED' ||326err.code === 'ECONNRESET' ||327err.code === 'ECONNREFUSED' ||328err.code === 'EADDRINUSE' ||329err.code === 'EPIPE' ||330err.code === 'ETIMEDOUT'331)332}333334return false335}336337// PUBLIC API338339module.exports.Agent = http.Agent340module.exports.Executor = httpLib.Executor341module.exports.HttpClient = HttpClient342module.exports.Request = httpLib.Request343module.exports.Response = httpLib.Response344345346