| var url = require("url"); |
| var URL = url.URL; |
| var http = require("http"); |
| var https = require("https"); |
| var Writable = require("stream").Writable; |
| var assert = require("assert"); |
| var debug = require("./debug"); |
|
|
| |
| var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; |
| var eventHandlers = Object.create(null); |
| events.forEach(function (event) { |
| eventHandlers[event] = function (arg1, arg2, arg3) { |
| this._redirectable.emit(event, arg1, arg2, arg3); |
| }; |
| }); |
|
|
| |
| var RedirectionError = createErrorType( |
| "ERR_FR_REDIRECTION_FAILURE", |
| "Redirected request failed" |
| ); |
| var TooManyRedirectsError = createErrorType( |
| "ERR_FR_TOO_MANY_REDIRECTS", |
| "Maximum number of redirects exceeded" |
| ); |
| var MaxBodyLengthExceededError = createErrorType( |
| "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", |
| "Request body larger than maxBodyLength limit" |
| ); |
| var WriteAfterEndError = createErrorType( |
| "ERR_STREAM_WRITE_AFTER_END", |
| "write after end" |
| ); |
|
|
| |
| function RedirectableRequest(options, responseCallback) { |
| |
| Writable.call(this); |
| this._sanitizeOptions(options); |
| this._options = options; |
| this._ended = false; |
| this._ending = false; |
| this._redirectCount = 0; |
| this._redirects = []; |
| this._requestBodyLength = 0; |
| this._requestBodyBuffers = []; |
|
|
| |
| if (responseCallback) { |
| this.on("response", responseCallback); |
| } |
|
|
| |
| var self = this; |
| this._onNativeResponse = function (response) { |
| self._processResponse(response); |
| }; |
|
|
| |
| this._performRequest(); |
| } |
| RedirectableRequest.prototype = Object.create(Writable.prototype); |
|
|
| RedirectableRequest.prototype.abort = function () { |
| abortRequest(this._currentRequest); |
| this.emit("abort"); |
| }; |
|
|
| |
| RedirectableRequest.prototype.write = function (data, encoding, callback) { |
| |
| if (this._ending) { |
| throw new WriteAfterEndError(); |
| } |
|
|
| |
| if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { |
| throw new TypeError("data should be a string, Buffer or Uint8Array"); |
| } |
| if (typeof encoding === "function") { |
| callback = encoding; |
| encoding = null; |
| } |
|
|
| |
| |
| if (data.length === 0) { |
| if (callback) { |
| callback(); |
| } |
| return; |
| } |
| |
| if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { |
| this._requestBodyLength += data.length; |
| this._requestBodyBuffers.push({ data: data, encoding: encoding }); |
| this._currentRequest.write(data, encoding, callback); |
| } |
| |
| else { |
| this.emit("error", new MaxBodyLengthExceededError()); |
| this.abort(); |
| } |
| }; |
|
|
| |
| RedirectableRequest.prototype.end = function (data, encoding, callback) { |
| |
| if (typeof data === "function") { |
| callback = data; |
| data = encoding = null; |
| } |
| else if (typeof encoding === "function") { |
| callback = encoding; |
| encoding = null; |
| } |
|
|
| |
| if (!data) { |
| this._ended = this._ending = true; |
| this._currentRequest.end(null, null, callback); |
| } |
| else { |
| var self = this; |
| var currentRequest = this._currentRequest; |
| this.write(data, encoding, function () { |
| self._ended = true; |
| currentRequest.end(null, null, callback); |
| }); |
| this._ending = true; |
| } |
| }; |
|
|
| |
| RedirectableRequest.prototype.setHeader = function (name, value) { |
| this._options.headers[name] = value; |
| this._currentRequest.setHeader(name, value); |
| }; |
|
|
| |
| RedirectableRequest.prototype.removeHeader = function (name) { |
| delete this._options.headers[name]; |
| this._currentRequest.removeHeader(name); |
| }; |
|
|
| |
| RedirectableRequest.prototype.setTimeout = function (msecs, callback) { |
| var self = this; |
|
|
| |
| function destroyOnTimeout(socket) { |
| socket.setTimeout(msecs); |
| socket.removeListener("timeout", socket.destroy); |
| socket.addListener("timeout", socket.destroy); |
| } |
|
|
| |
| function startTimer(socket) { |
| if (self._timeout) { |
| clearTimeout(self._timeout); |
| } |
| self._timeout = setTimeout(function () { |
| self.emit("timeout"); |
| clearTimer(); |
| }, msecs); |
| destroyOnTimeout(socket); |
| } |
|
|
| |
| function clearTimer() { |
| |
| if (self._timeout) { |
| clearTimeout(self._timeout); |
| self._timeout = null; |
| } |
|
|
| |
| self.removeListener("abort", clearTimer); |
| self.removeListener("error", clearTimer); |
| self.removeListener("response", clearTimer); |
| if (callback) { |
| self.removeListener("timeout", callback); |
| } |
| if (!self.socket) { |
| self._currentRequest.removeListener("socket", startTimer); |
| } |
| } |
|
|
| |
| if (callback) { |
| this.on("timeout", callback); |
| } |
|
|
| |
| if (this.socket) { |
| startTimer(this.socket); |
| } |
| else { |
| this._currentRequest.once("socket", startTimer); |
| } |
|
|
| |
| this.on("socket", destroyOnTimeout); |
| this.on("abort", clearTimer); |
| this.on("error", clearTimer); |
| this.on("response", clearTimer); |
|
|
| return this; |
| }; |
|
|
| |
| [ |
| "flushHeaders", "getHeader", |
| "setNoDelay", "setSocketKeepAlive", |
| ].forEach(function (method) { |
| RedirectableRequest.prototype[method] = function (a, b) { |
| return this._currentRequest[method](a, b); |
| }; |
| }); |
|
|
| |
| ["aborted", "connection", "socket"].forEach(function (property) { |
| Object.defineProperty(RedirectableRequest.prototype, property, { |
| get: function () { return this._currentRequest[property]; }, |
| }); |
| }); |
|
|
| RedirectableRequest.prototype._sanitizeOptions = function (options) { |
| |
| if (!options.headers) { |
| options.headers = {}; |
| } |
|
|
| |
| |
| |
| if (options.host) { |
| |
| if (!options.hostname) { |
| options.hostname = options.host; |
| } |
| delete options.host; |
| } |
|
|
| |
| if (!options.pathname && options.path) { |
| var searchPos = options.path.indexOf("?"); |
| if (searchPos < 0) { |
| options.pathname = options.path; |
| } |
| else { |
| options.pathname = options.path.substring(0, searchPos); |
| options.search = options.path.substring(searchPos); |
| } |
| } |
| }; |
|
|
|
|
| |
| RedirectableRequest.prototype._performRequest = function () { |
| |
| var protocol = this._options.protocol; |
| var nativeProtocol = this._options.nativeProtocols[protocol]; |
| if (!nativeProtocol) { |
| this.emit("error", new TypeError("Unsupported protocol " + protocol)); |
| return; |
| } |
|
|
| |
| |
| if (this._options.agents) { |
| var scheme = protocol.substr(0, protocol.length - 1); |
| this._options.agent = this._options.agents[scheme]; |
| } |
|
|
| |
| var request = this._currentRequest = |
| nativeProtocol.request(this._options, this._onNativeResponse); |
| this._currentUrl = url.format(this._options); |
|
|
| |
| request._redirectable = this; |
| for (var e = 0; e < events.length; e++) { |
| request.on(events[e], eventHandlers[events[e]]); |
| } |
|
|
| |
| |
| if (this._isRedirect) { |
| |
| var i = 0; |
| var self = this; |
| var buffers = this._requestBodyBuffers; |
| (function writeNext(error) { |
| |
| |
| if (request === self._currentRequest) { |
| |
| |
| if (error) { |
| self.emit("error", error); |
| } |
| |
| else if (i < buffers.length) { |
| var buffer = buffers[i++]; |
| |
| if (!request.finished) { |
| request.write(buffer.data, buffer.encoding, writeNext); |
| } |
| } |
| |
| else if (self._ended) { |
| request.end(); |
| } |
| } |
| }()); |
| } |
| }; |
|
|
| |
| RedirectableRequest.prototype._processResponse = function (response) { |
| |
| var statusCode = response.statusCode; |
| if (this._options.trackRedirects) { |
| this._redirects.push({ |
| url: this._currentUrl, |
| headers: response.headers, |
| statusCode: statusCode, |
| }); |
| } |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| var location = response.headers.location; |
| if (!location || this._options.followRedirects === false || |
| statusCode < 300 || statusCode >= 400) { |
| response.responseUrl = this._currentUrl; |
| response.redirects = this._redirects; |
| this.emit("response", response); |
|
|
| |
| this._requestBodyBuffers = []; |
| return; |
| } |
|
|
| |
| abortRequest(this._currentRequest); |
| |
| response.destroy(); |
|
|
| |
| |
| if (++this._redirectCount > this._options.maxRedirects) { |
| this.emit("error", new TooManyRedirectsError()); |
| return; |
| } |
|
|
| |
| |
| |
| |
| if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || |
| |
| |
| |
| |
| (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { |
| this._options.method = "GET"; |
| |
| this._requestBodyBuffers = []; |
| removeMatchingHeaders(/^content-/i, this._options.headers); |
| } |
|
|
| |
| var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); |
|
|
| |
| var currentUrlParts = url.parse(this._currentUrl); |
| var currentHost = currentHostHeader || currentUrlParts.host; |
| var currentUrl = /^\w+:/.test(location) ? this._currentUrl : |
| url.format(Object.assign(currentUrlParts, { host: currentHost })); |
|
|
| |
| var redirectUrl; |
| try { |
| redirectUrl = url.resolve(currentUrl, location); |
| } |
| catch (cause) { |
| this.emit("error", new RedirectionError(cause)); |
| return; |
| } |
|
|
| |
| debug("redirecting to", redirectUrl); |
| this._isRedirect = true; |
| var redirectUrlParts = url.parse(redirectUrl); |
| Object.assign(this._options, redirectUrlParts); |
|
|
| |
| |
| if (redirectUrlParts.protocol !== currentUrlParts.protocol && |
| redirectUrlParts.protocol !== "https:" || |
| redirectUrlParts.host !== currentHost && |
| !isSubdomain(redirectUrlParts.host, currentHost)) { |
| removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers); |
| } |
|
|
| |
| if (typeof this._options.beforeRedirect === "function") { |
| var responseDetails = { headers: response.headers }; |
| try { |
| this._options.beforeRedirect.call(null, this._options, responseDetails); |
| } |
| catch (err) { |
| this.emit("error", err); |
| return; |
| } |
| this._sanitizeOptions(this._options); |
| } |
|
|
| |
| try { |
| this._performRequest(); |
| } |
| catch (cause) { |
| this.emit("error", new RedirectionError(cause)); |
| } |
| }; |
|
|
| |
| function wrap(protocols) { |
| |
| var exports = { |
| maxRedirects: 21, |
| maxBodyLength: 10 * 1024 * 1024, |
| }; |
|
|
| |
| var nativeProtocols = {}; |
| Object.keys(protocols).forEach(function (scheme) { |
| var protocol = scheme + ":"; |
| var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; |
| var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); |
|
|
| |
| function request(input, options, callback) { |
| |
| if (typeof input === "string") { |
| var urlStr = input; |
| try { |
| input = urlToOptions(new URL(urlStr)); |
| } |
| catch (err) { |
| |
| input = url.parse(urlStr); |
| } |
| } |
| else if (URL && (input instanceof URL)) { |
| input = urlToOptions(input); |
| } |
| else { |
| callback = options; |
| options = input; |
| input = { protocol: protocol }; |
| } |
| if (typeof options === "function") { |
| callback = options; |
| options = null; |
| } |
|
|
| |
| options = Object.assign({ |
| maxRedirects: exports.maxRedirects, |
| maxBodyLength: exports.maxBodyLength, |
| }, input, options); |
| options.nativeProtocols = nativeProtocols; |
|
|
| assert.equal(options.protocol, protocol, "protocol mismatch"); |
| debug("options", options); |
| return new RedirectableRequest(options, callback); |
| } |
|
|
| |
| function get(input, options, callback) { |
| var wrappedRequest = wrappedProtocol.request(input, options, callback); |
| wrappedRequest.end(); |
| return wrappedRequest; |
| } |
|
|
| |
| Object.defineProperties(wrappedProtocol, { |
| request: { value: request, configurable: true, enumerable: true, writable: true }, |
| get: { value: get, configurable: true, enumerable: true, writable: true }, |
| }); |
| }); |
| return exports; |
| } |
|
|
| |
| function noop() { } |
|
|
| |
| function urlToOptions(urlObject) { |
| var options = { |
| protocol: urlObject.protocol, |
| hostname: urlObject.hostname.startsWith("[") ? |
| |
| urlObject.hostname.slice(1, -1) : |
| urlObject.hostname, |
| hash: urlObject.hash, |
| search: urlObject.search, |
| pathname: urlObject.pathname, |
| path: urlObject.pathname + urlObject.search, |
| href: urlObject.href, |
| }; |
| if (urlObject.port !== "") { |
| options.port = Number(urlObject.port); |
| } |
| return options; |
| } |
|
|
| function removeMatchingHeaders(regex, headers) { |
| var lastValue; |
| for (var header in headers) { |
| if (regex.test(header)) { |
| lastValue = headers[header]; |
| delete headers[header]; |
| } |
| } |
| return (lastValue === null || typeof lastValue === "undefined") ? |
| undefined : String(lastValue).trim(); |
| } |
|
|
| function createErrorType(code, defaultMessage) { |
| function CustomError(cause) { |
| Error.captureStackTrace(this, this.constructor); |
| if (!cause) { |
| this.message = defaultMessage; |
| } |
| else { |
| this.message = defaultMessage + ": " + cause.message; |
| this.cause = cause; |
| } |
| } |
| CustomError.prototype = new Error(); |
| CustomError.prototype.constructor = CustomError; |
| CustomError.prototype.name = "Error [" + code + "]"; |
| CustomError.prototype.code = code; |
| return CustomError; |
| } |
|
|
| function abortRequest(request) { |
| for (var e = 0; e < events.length; e++) { |
| request.removeListener(events[e], eventHandlers[events[e]]); |
| } |
| request.on("error", noop); |
| request.abort(); |
| } |
|
|
| function isSubdomain(subdomain, domain) { |
| const dot = subdomain.length - domain.length - 1; |
| return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); |
| } |
|
|
| |
| module.exports = wrap({ http: http, https: https }); |
| module.exports.wrap = wrap; |
|
|