[57e58a3] | 1 | var url = require("url");
|
---|
| 2 | var URL = url.URL;
|
---|
| 3 | var http = require("http");
|
---|
| 4 | var https = require("https");
|
---|
| 5 | var Writable = require("stream").Writable;
|
---|
| 6 | var assert = require("assert");
|
---|
| 7 | var debug = require("./debug");
|
---|
| 8 |
|
---|
| 9 | // Preventive platform detection
|
---|
| 10 | // istanbul ignore next
|
---|
| 11 | (function detectUnsupportedEnvironment() {
|
---|
| 12 | var looksLikeNode = typeof process !== "undefined";
|
---|
| 13 | var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined";
|
---|
| 14 | var looksLikeV8 = isFunction(Error.captureStackTrace);
|
---|
| 15 | if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) {
|
---|
| 16 | console.warn("The follow-redirects package should be excluded from browser builds.");
|
---|
| 17 | }
|
---|
| 18 | }());
|
---|
| 19 |
|
---|
| 20 | // Whether to use the native URL object or the legacy url module
|
---|
| 21 | var useNativeURL = false;
|
---|
| 22 | try {
|
---|
| 23 | assert(new URL(""));
|
---|
| 24 | }
|
---|
| 25 | catch (error) {
|
---|
| 26 | useNativeURL = error.code === "ERR_INVALID_URL";
|
---|
| 27 | }
|
---|
| 28 |
|
---|
| 29 | // URL fields to preserve in copy operations
|
---|
| 30 | var preservedUrlFields = [
|
---|
| 31 | "auth",
|
---|
| 32 | "host",
|
---|
| 33 | "hostname",
|
---|
| 34 | "href",
|
---|
| 35 | "path",
|
---|
| 36 | "pathname",
|
---|
| 37 | "port",
|
---|
| 38 | "protocol",
|
---|
| 39 | "query",
|
---|
| 40 | "search",
|
---|
| 41 | "hash",
|
---|
| 42 | ];
|
---|
| 43 |
|
---|
| 44 | // Create handlers that pass events from native requests
|
---|
| 45 | var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
|
---|
| 46 | var eventHandlers = Object.create(null);
|
---|
| 47 | events.forEach(function (event) {
|
---|
| 48 | eventHandlers[event] = function (arg1, arg2, arg3) {
|
---|
| 49 | this._redirectable.emit(event, arg1, arg2, arg3);
|
---|
| 50 | };
|
---|
| 51 | });
|
---|
| 52 |
|
---|
| 53 | // Error types with codes
|
---|
| 54 | var InvalidUrlError = createErrorType(
|
---|
| 55 | "ERR_INVALID_URL",
|
---|
| 56 | "Invalid URL",
|
---|
| 57 | TypeError
|
---|
| 58 | );
|
---|
| 59 | var RedirectionError = createErrorType(
|
---|
| 60 | "ERR_FR_REDIRECTION_FAILURE",
|
---|
| 61 | "Redirected request failed"
|
---|
| 62 | );
|
---|
| 63 | var TooManyRedirectsError = createErrorType(
|
---|
| 64 | "ERR_FR_TOO_MANY_REDIRECTS",
|
---|
| 65 | "Maximum number of redirects exceeded",
|
---|
| 66 | RedirectionError
|
---|
| 67 | );
|
---|
| 68 | var MaxBodyLengthExceededError = createErrorType(
|
---|
| 69 | "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
|
---|
| 70 | "Request body larger than maxBodyLength limit"
|
---|
| 71 | );
|
---|
| 72 | var WriteAfterEndError = createErrorType(
|
---|
| 73 | "ERR_STREAM_WRITE_AFTER_END",
|
---|
| 74 | "write after end"
|
---|
| 75 | );
|
---|
| 76 |
|
---|
| 77 | // istanbul ignore next
|
---|
| 78 | var destroy = Writable.prototype.destroy || noop;
|
---|
| 79 |
|
---|
| 80 | // An HTTP(S) request that can be redirected
|
---|
| 81 | function RedirectableRequest(options, responseCallback) {
|
---|
| 82 | // Initialize the request
|
---|
| 83 | Writable.call(this);
|
---|
| 84 | this._sanitizeOptions(options);
|
---|
| 85 | this._options = options;
|
---|
| 86 | this._ended = false;
|
---|
| 87 | this._ending = false;
|
---|
| 88 | this._redirectCount = 0;
|
---|
| 89 | this._redirects = [];
|
---|
| 90 | this._requestBodyLength = 0;
|
---|
| 91 | this._requestBodyBuffers = [];
|
---|
| 92 |
|
---|
| 93 | // Attach a callback if passed
|
---|
| 94 | if (responseCallback) {
|
---|
| 95 | this.on("response", responseCallback);
|
---|
| 96 | }
|
---|
| 97 |
|
---|
| 98 | // React to responses of native requests
|
---|
| 99 | var self = this;
|
---|
| 100 | this._onNativeResponse = function (response) {
|
---|
| 101 | try {
|
---|
| 102 | self._processResponse(response);
|
---|
| 103 | }
|
---|
| 104 | catch (cause) {
|
---|
| 105 | self.emit("error", cause instanceof RedirectionError ?
|
---|
| 106 | cause : new RedirectionError({ cause: cause }));
|
---|
| 107 | }
|
---|
| 108 | };
|
---|
| 109 |
|
---|
| 110 | // Perform the first request
|
---|
| 111 | this._performRequest();
|
---|
| 112 | }
|
---|
| 113 | RedirectableRequest.prototype = Object.create(Writable.prototype);
|
---|
| 114 |
|
---|
| 115 | RedirectableRequest.prototype.abort = function () {
|
---|
| 116 | destroyRequest(this._currentRequest);
|
---|
| 117 | this._currentRequest.abort();
|
---|
| 118 | this.emit("abort");
|
---|
| 119 | };
|
---|
| 120 |
|
---|
| 121 | RedirectableRequest.prototype.destroy = function (error) {
|
---|
| 122 | destroyRequest(this._currentRequest, error);
|
---|
| 123 | destroy.call(this, error);
|
---|
| 124 | return this;
|
---|
| 125 | };
|
---|
| 126 |
|
---|
| 127 | // Writes buffered data to the current native request
|
---|
| 128 | RedirectableRequest.prototype.write = function (data, encoding, callback) {
|
---|
| 129 | // Writing is not allowed if end has been called
|
---|
| 130 | if (this._ending) {
|
---|
| 131 | throw new WriteAfterEndError();
|
---|
| 132 | }
|
---|
| 133 |
|
---|
| 134 | // Validate input and shift parameters if necessary
|
---|
| 135 | if (!isString(data) && !isBuffer(data)) {
|
---|
| 136 | throw new TypeError("data should be a string, Buffer or Uint8Array");
|
---|
| 137 | }
|
---|
| 138 | if (isFunction(encoding)) {
|
---|
| 139 | callback = encoding;
|
---|
| 140 | encoding = null;
|
---|
| 141 | }
|
---|
| 142 |
|
---|
| 143 | // Ignore empty buffers, since writing them doesn't invoke the callback
|
---|
| 144 | // https://github.com/nodejs/node/issues/22066
|
---|
| 145 | if (data.length === 0) {
|
---|
| 146 | if (callback) {
|
---|
| 147 | callback();
|
---|
| 148 | }
|
---|
| 149 | return;
|
---|
| 150 | }
|
---|
| 151 | // Only write when we don't exceed the maximum body length
|
---|
| 152 | if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
|
---|
| 153 | this._requestBodyLength += data.length;
|
---|
| 154 | this._requestBodyBuffers.push({ data: data, encoding: encoding });
|
---|
| 155 | this._currentRequest.write(data, encoding, callback);
|
---|
| 156 | }
|
---|
| 157 | // Error when we exceed the maximum body length
|
---|
| 158 | else {
|
---|
| 159 | this.emit("error", new MaxBodyLengthExceededError());
|
---|
| 160 | this.abort();
|
---|
| 161 | }
|
---|
| 162 | };
|
---|
| 163 |
|
---|
| 164 | // Ends the current native request
|
---|
| 165 | RedirectableRequest.prototype.end = function (data, encoding, callback) {
|
---|
| 166 | // Shift parameters if necessary
|
---|
| 167 | if (isFunction(data)) {
|
---|
| 168 | callback = data;
|
---|
| 169 | data = encoding = null;
|
---|
| 170 | }
|
---|
| 171 | else if (isFunction(encoding)) {
|
---|
| 172 | callback = encoding;
|
---|
| 173 | encoding = null;
|
---|
| 174 | }
|
---|
| 175 |
|
---|
| 176 | // Write data if needed and end
|
---|
| 177 | if (!data) {
|
---|
| 178 | this._ended = this._ending = true;
|
---|
| 179 | this._currentRequest.end(null, null, callback);
|
---|
| 180 | }
|
---|
| 181 | else {
|
---|
| 182 | var self = this;
|
---|
| 183 | var currentRequest = this._currentRequest;
|
---|
| 184 | this.write(data, encoding, function () {
|
---|
| 185 | self._ended = true;
|
---|
| 186 | currentRequest.end(null, null, callback);
|
---|
| 187 | });
|
---|
| 188 | this._ending = true;
|
---|
| 189 | }
|
---|
| 190 | };
|
---|
| 191 |
|
---|
| 192 | // Sets a header value on the current native request
|
---|
| 193 | RedirectableRequest.prototype.setHeader = function (name, value) {
|
---|
| 194 | this._options.headers[name] = value;
|
---|
| 195 | this._currentRequest.setHeader(name, value);
|
---|
| 196 | };
|
---|
| 197 |
|
---|
| 198 | // Clears a header value on the current native request
|
---|
| 199 | RedirectableRequest.prototype.removeHeader = function (name) {
|
---|
| 200 | delete this._options.headers[name];
|
---|
| 201 | this._currentRequest.removeHeader(name);
|
---|
| 202 | };
|
---|
| 203 |
|
---|
| 204 | // Global timeout for all underlying requests
|
---|
| 205 | RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
|
---|
| 206 | var self = this;
|
---|
| 207 |
|
---|
| 208 | // Destroys the socket on timeout
|
---|
| 209 | function destroyOnTimeout(socket) {
|
---|
| 210 | socket.setTimeout(msecs);
|
---|
| 211 | socket.removeListener("timeout", socket.destroy);
|
---|
| 212 | socket.addListener("timeout", socket.destroy);
|
---|
| 213 | }
|
---|
| 214 |
|
---|
| 215 | // Sets up a timer to trigger a timeout event
|
---|
| 216 | function startTimer(socket) {
|
---|
| 217 | if (self._timeout) {
|
---|
| 218 | clearTimeout(self._timeout);
|
---|
| 219 | }
|
---|
| 220 | self._timeout = setTimeout(function () {
|
---|
| 221 | self.emit("timeout");
|
---|
| 222 | clearTimer();
|
---|
| 223 | }, msecs);
|
---|
| 224 | destroyOnTimeout(socket);
|
---|
| 225 | }
|
---|
| 226 |
|
---|
| 227 | // Stops a timeout from triggering
|
---|
| 228 | function clearTimer() {
|
---|
| 229 | // Clear the timeout
|
---|
| 230 | if (self._timeout) {
|
---|
| 231 | clearTimeout(self._timeout);
|
---|
| 232 | self._timeout = null;
|
---|
| 233 | }
|
---|
| 234 |
|
---|
| 235 | // Clean up all attached listeners
|
---|
| 236 | self.removeListener("abort", clearTimer);
|
---|
| 237 | self.removeListener("error", clearTimer);
|
---|
| 238 | self.removeListener("response", clearTimer);
|
---|
| 239 | self.removeListener("close", clearTimer);
|
---|
| 240 | if (callback) {
|
---|
| 241 | self.removeListener("timeout", callback);
|
---|
| 242 | }
|
---|
| 243 | if (!self.socket) {
|
---|
| 244 | self._currentRequest.removeListener("socket", startTimer);
|
---|
| 245 | }
|
---|
| 246 | }
|
---|
| 247 |
|
---|
| 248 | // Attach callback if passed
|
---|
| 249 | if (callback) {
|
---|
| 250 | this.on("timeout", callback);
|
---|
| 251 | }
|
---|
| 252 |
|
---|
| 253 | // Start the timer if or when the socket is opened
|
---|
| 254 | if (this.socket) {
|
---|
| 255 | startTimer(this.socket);
|
---|
| 256 | }
|
---|
| 257 | else {
|
---|
| 258 | this._currentRequest.once("socket", startTimer);
|
---|
| 259 | }
|
---|
| 260 |
|
---|
| 261 | // Clean up on events
|
---|
| 262 | this.on("socket", destroyOnTimeout);
|
---|
| 263 | this.on("abort", clearTimer);
|
---|
| 264 | this.on("error", clearTimer);
|
---|
| 265 | this.on("response", clearTimer);
|
---|
| 266 | this.on("close", clearTimer);
|
---|
| 267 |
|
---|
| 268 | return this;
|
---|
| 269 | };
|
---|
| 270 |
|
---|
| 271 | // Proxy all other public ClientRequest methods
|
---|
| 272 | [
|
---|
| 273 | "flushHeaders", "getHeader",
|
---|
| 274 | "setNoDelay", "setSocketKeepAlive",
|
---|
| 275 | ].forEach(function (method) {
|
---|
| 276 | RedirectableRequest.prototype[method] = function (a, b) {
|
---|
| 277 | return this._currentRequest[method](a, b);
|
---|
| 278 | };
|
---|
| 279 | });
|
---|
| 280 |
|
---|
| 281 | // Proxy all public ClientRequest properties
|
---|
| 282 | ["aborted", "connection", "socket"].forEach(function (property) {
|
---|
| 283 | Object.defineProperty(RedirectableRequest.prototype, property, {
|
---|
| 284 | get: function () { return this._currentRequest[property]; },
|
---|
| 285 | });
|
---|
| 286 | });
|
---|
| 287 |
|
---|
| 288 | RedirectableRequest.prototype._sanitizeOptions = function (options) {
|
---|
| 289 | // Ensure headers are always present
|
---|
| 290 | if (!options.headers) {
|
---|
| 291 | options.headers = {};
|
---|
| 292 | }
|
---|
| 293 |
|
---|
| 294 | // Since http.request treats host as an alias of hostname,
|
---|
| 295 | // but the url module interprets host as hostname plus port,
|
---|
| 296 | // eliminate the host property to avoid confusion.
|
---|
| 297 | if (options.host) {
|
---|
| 298 | // Use hostname if set, because it has precedence
|
---|
| 299 | if (!options.hostname) {
|
---|
| 300 | options.hostname = options.host;
|
---|
| 301 | }
|
---|
| 302 | delete options.host;
|
---|
| 303 | }
|
---|
| 304 |
|
---|
| 305 | // Complete the URL object when necessary
|
---|
| 306 | if (!options.pathname && options.path) {
|
---|
| 307 | var searchPos = options.path.indexOf("?");
|
---|
| 308 | if (searchPos < 0) {
|
---|
| 309 | options.pathname = options.path;
|
---|
| 310 | }
|
---|
| 311 | else {
|
---|
| 312 | options.pathname = options.path.substring(0, searchPos);
|
---|
| 313 | options.search = options.path.substring(searchPos);
|
---|
| 314 | }
|
---|
| 315 | }
|
---|
| 316 | };
|
---|
| 317 |
|
---|
| 318 |
|
---|
| 319 | // Executes the next native request (initial or redirect)
|
---|
| 320 | RedirectableRequest.prototype._performRequest = function () {
|
---|
| 321 | // Load the native protocol
|
---|
| 322 | var protocol = this._options.protocol;
|
---|
| 323 | var nativeProtocol = this._options.nativeProtocols[protocol];
|
---|
| 324 | if (!nativeProtocol) {
|
---|
| 325 | throw new TypeError("Unsupported protocol " + protocol);
|
---|
| 326 | }
|
---|
| 327 |
|
---|
| 328 | // If specified, use the agent corresponding to the protocol
|
---|
| 329 | // (HTTP and HTTPS use different types of agents)
|
---|
| 330 | if (this._options.agents) {
|
---|
| 331 | var scheme = protocol.slice(0, -1);
|
---|
| 332 | this._options.agent = this._options.agents[scheme];
|
---|
| 333 | }
|
---|
| 334 |
|
---|
| 335 | // Create the native request and set up its event handlers
|
---|
| 336 | var request = this._currentRequest =
|
---|
| 337 | nativeProtocol.request(this._options, this._onNativeResponse);
|
---|
| 338 | request._redirectable = this;
|
---|
| 339 | for (var event of events) {
|
---|
| 340 | request.on(event, eventHandlers[event]);
|
---|
| 341 | }
|
---|
| 342 |
|
---|
| 343 | // RFC7230§5.3.1: When making a request directly to an origin server, […]
|
---|
| 344 | // a client MUST send only the absolute path […] as the request-target.
|
---|
| 345 | this._currentUrl = /^\//.test(this._options.path) ?
|
---|
| 346 | url.format(this._options) :
|
---|
| 347 | // When making a request to a proxy, […]
|
---|
| 348 | // a client MUST send the target URI in absolute-form […].
|
---|
| 349 | this._options.path;
|
---|
| 350 |
|
---|
| 351 | // End a redirected request
|
---|
| 352 | // (The first request must be ended explicitly with RedirectableRequest#end)
|
---|
| 353 | if (this._isRedirect) {
|
---|
| 354 | // Write the request entity and end
|
---|
| 355 | var i = 0;
|
---|
| 356 | var self = this;
|
---|
| 357 | var buffers = this._requestBodyBuffers;
|
---|
| 358 | (function writeNext(error) {
|
---|
| 359 | // Only write if this request has not been redirected yet
|
---|
| 360 | // istanbul ignore else
|
---|
| 361 | if (request === self._currentRequest) {
|
---|
| 362 | // Report any write errors
|
---|
| 363 | // istanbul ignore if
|
---|
| 364 | if (error) {
|
---|
| 365 | self.emit("error", error);
|
---|
| 366 | }
|
---|
| 367 | // Write the next buffer if there are still left
|
---|
| 368 | else if (i < buffers.length) {
|
---|
| 369 | var buffer = buffers[i++];
|
---|
| 370 | // istanbul ignore else
|
---|
| 371 | if (!request.finished) {
|
---|
| 372 | request.write(buffer.data, buffer.encoding, writeNext);
|
---|
| 373 | }
|
---|
| 374 | }
|
---|
| 375 | // End the request if `end` has been called on us
|
---|
| 376 | else if (self._ended) {
|
---|
| 377 | request.end();
|
---|
| 378 | }
|
---|
| 379 | }
|
---|
| 380 | }());
|
---|
| 381 | }
|
---|
| 382 | };
|
---|
| 383 |
|
---|
| 384 | // Processes a response from the current native request
|
---|
| 385 | RedirectableRequest.prototype._processResponse = function (response) {
|
---|
| 386 | // Store the redirected response
|
---|
| 387 | var statusCode = response.statusCode;
|
---|
| 388 | if (this._options.trackRedirects) {
|
---|
| 389 | this._redirects.push({
|
---|
| 390 | url: this._currentUrl,
|
---|
| 391 | headers: response.headers,
|
---|
| 392 | statusCode: statusCode,
|
---|
| 393 | });
|
---|
| 394 | }
|
---|
| 395 |
|
---|
| 396 | // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
|
---|
| 397 | // that further action needs to be taken by the user agent in order to
|
---|
| 398 | // fulfill the request. If a Location header field is provided,
|
---|
| 399 | // the user agent MAY automatically redirect its request to the URI
|
---|
| 400 | // referenced by the Location field value,
|
---|
| 401 | // even if the specific status code is not understood.
|
---|
| 402 |
|
---|
| 403 | // If the response is not a redirect; return it as-is
|
---|
| 404 | var location = response.headers.location;
|
---|
| 405 | if (!location || this._options.followRedirects === false ||
|
---|
| 406 | statusCode < 300 || statusCode >= 400) {
|
---|
| 407 | response.responseUrl = this._currentUrl;
|
---|
| 408 | response.redirects = this._redirects;
|
---|
| 409 | this.emit("response", response);
|
---|
| 410 |
|
---|
| 411 | // Clean up
|
---|
| 412 | this._requestBodyBuffers = [];
|
---|
| 413 | return;
|
---|
| 414 | }
|
---|
| 415 |
|
---|
| 416 | // The response is a redirect, so abort the current request
|
---|
| 417 | destroyRequest(this._currentRequest);
|
---|
| 418 | // Discard the remainder of the response to avoid waiting for data
|
---|
| 419 | response.destroy();
|
---|
| 420 |
|
---|
| 421 | // RFC7231§6.4: A client SHOULD detect and intervene
|
---|
| 422 | // in cyclical redirections (i.e., "infinite" redirection loops).
|
---|
| 423 | if (++this._redirectCount > this._options.maxRedirects) {
|
---|
| 424 | throw new TooManyRedirectsError();
|
---|
| 425 | }
|
---|
| 426 |
|
---|
| 427 | // Store the request headers if applicable
|
---|
| 428 | var requestHeaders;
|
---|
| 429 | var beforeRedirect = this._options.beforeRedirect;
|
---|
| 430 | if (beforeRedirect) {
|
---|
| 431 | requestHeaders = Object.assign({
|
---|
| 432 | // The Host header was set by nativeProtocol.request
|
---|
| 433 | Host: response.req.getHeader("host"),
|
---|
| 434 | }, this._options.headers);
|
---|
| 435 | }
|
---|
| 436 |
|
---|
| 437 | // RFC7231§6.4: Automatic redirection needs to done with
|
---|
| 438 | // care for methods not known to be safe, […]
|
---|
| 439 | // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
|
---|
| 440 | // the request method from POST to GET for the subsequent request.
|
---|
| 441 | var method = this._options.method;
|
---|
| 442 | if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
|
---|
| 443 | // RFC7231§6.4.4: The 303 (See Other) status code indicates that
|
---|
| 444 | // the server is redirecting the user agent to a different resource […]
|
---|
| 445 | // A user agent can perform a retrieval request targeting that URI
|
---|
| 446 | // (a GET or HEAD request if using HTTP) […]
|
---|
| 447 | (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
|
---|
| 448 | this._options.method = "GET";
|
---|
| 449 | // Drop a possible entity and headers related to it
|
---|
| 450 | this._requestBodyBuffers = [];
|
---|
| 451 | removeMatchingHeaders(/^content-/i, this._options.headers);
|
---|
| 452 | }
|
---|
| 453 |
|
---|
| 454 | // Drop the Host header, as the redirect might lead to a different host
|
---|
| 455 | var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
|
---|
| 456 |
|
---|
| 457 | // If the redirect is relative, carry over the host of the last request
|
---|
| 458 | var currentUrlParts = parseUrl(this._currentUrl);
|
---|
| 459 | var currentHost = currentHostHeader || currentUrlParts.host;
|
---|
| 460 | var currentUrl = /^\w+:/.test(location) ? this._currentUrl :
|
---|
| 461 | url.format(Object.assign(currentUrlParts, { host: currentHost }));
|
---|
| 462 |
|
---|
| 463 | // Create the redirected request
|
---|
| 464 | var redirectUrl = resolveUrl(location, currentUrl);
|
---|
| 465 | debug("redirecting to", redirectUrl.href);
|
---|
| 466 | this._isRedirect = true;
|
---|
| 467 | spreadUrlObject(redirectUrl, this._options);
|
---|
| 468 |
|
---|
| 469 | // Drop confidential headers when redirecting to a less secure protocol
|
---|
| 470 | // or to a different domain that is not a superdomain
|
---|
| 471 | if (redirectUrl.protocol !== currentUrlParts.protocol &&
|
---|
| 472 | redirectUrl.protocol !== "https:" ||
|
---|
| 473 | redirectUrl.host !== currentHost &&
|
---|
| 474 | !isSubdomain(redirectUrl.host, currentHost)) {
|
---|
| 475 | removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
|
---|
| 476 | }
|
---|
| 477 |
|
---|
| 478 | // Evaluate the beforeRedirect callback
|
---|
| 479 | if (isFunction(beforeRedirect)) {
|
---|
| 480 | var responseDetails = {
|
---|
| 481 | headers: response.headers,
|
---|
| 482 | statusCode: statusCode,
|
---|
| 483 | };
|
---|
| 484 | var requestDetails = {
|
---|
| 485 | url: currentUrl,
|
---|
| 486 | method: method,
|
---|
| 487 | headers: requestHeaders,
|
---|
| 488 | };
|
---|
| 489 | beforeRedirect(this._options, responseDetails, requestDetails);
|
---|
| 490 | this._sanitizeOptions(this._options);
|
---|
| 491 | }
|
---|
| 492 |
|
---|
| 493 | // Perform the redirected request
|
---|
| 494 | this._performRequest();
|
---|
| 495 | };
|
---|
| 496 |
|
---|
| 497 | // Wraps the key/value object of protocols with redirect functionality
|
---|
| 498 | function wrap(protocols) {
|
---|
| 499 | // Default settings
|
---|
| 500 | var exports = {
|
---|
| 501 | maxRedirects: 21,
|
---|
| 502 | maxBodyLength: 10 * 1024 * 1024,
|
---|
| 503 | };
|
---|
| 504 |
|
---|
| 505 | // Wrap each protocol
|
---|
| 506 | var nativeProtocols = {};
|
---|
| 507 | Object.keys(protocols).forEach(function (scheme) {
|
---|
| 508 | var protocol = scheme + ":";
|
---|
| 509 | var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
|
---|
| 510 | var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
|
---|
| 511 |
|
---|
| 512 | // Executes a request, following redirects
|
---|
| 513 | function request(input, options, callback) {
|
---|
| 514 | // Parse parameters, ensuring that input is an object
|
---|
| 515 | if (isURL(input)) {
|
---|
| 516 | input = spreadUrlObject(input);
|
---|
| 517 | }
|
---|
| 518 | else if (isString(input)) {
|
---|
| 519 | input = spreadUrlObject(parseUrl(input));
|
---|
| 520 | }
|
---|
| 521 | else {
|
---|
| 522 | callback = options;
|
---|
| 523 | options = validateUrl(input);
|
---|
| 524 | input = { protocol: protocol };
|
---|
| 525 | }
|
---|
| 526 | if (isFunction(options)) {
|
---|
| 527 | callback = options;
|
---|
| 528 | options = null;
|
---|
| 529 | }
|
---|
| 530 |
|
---|
| 531 | // Set defaults
|
---|
| 532 | options = Object.assign({
|
---|
| 533 | maxRedirects: exports.maxRedirects,
|
---|
| 534 | maxBodyLength: exports.maxBodyLength,
|
---|
| 535 | }, input, options);
|
---|
| 536 | options.nativeProtocols = nativeProtocols;
|
---|
| 537 | if (!isString(options.host) && !isString(options.hostname)) {
|
---|
| 538 | options.hostname = "::1";
|
---|
| 539 | }
|
---|
| 540 |
|
---|
| 541 | assert.equal(options.protocol, protocol, "protocol mismatch");
|
---|
| 542 | debug("options", options);
|
---|
| 543 | return new RedirectableRequest(options, callback);
|
---|
| 544 | }
|
---|
| 545 |
|
---|
| 546 | // Executes a GET request, following redirects
|
---|
| 547 | function get(input, options, callback) {
|
---|
| 548 | var wrappedRequest = wrappedProtocol.request(input, options, callback);
|
---|
| 549 | wrappedRequest.end();
|
---|
| 550 | return wrappedRequest;
|
---|
| 551 | }
|
---|
| 552 |
|
---|
| 553 | // Expose the properties on the wrapped protocol
|
---|
| 554 | Object.defineProperties(wrappedProtocol, {
|
---|
| 555 | request: { value: request, configurable: true, enumerable: true, writable: true },
|
---|
| 556 | get: { value: get, configurable: true, enumerable: true, writable: true },
|
---|
| 557 | });
|
---|
| 558 | });
|
---|
| 559 | return exports;
|
---|
| 560 | }
|
---|
| 561 |
|
---|
| 562 | function noop() { /* empty */ }
|
---|
| 563 |
|
---|
| 564 | function parseUrl(input) {
|
---|
| 565 | var parsed;
|
---|
| 566 | // istanbul ignore else
|
---|
| 567 | if (useNativeURL) {
|
---|
| 568 | parsed = new URL(input);
|
---|
| 569 | }
|
---|
| 570 | else {
|
---|
| 571 | // Ensure the URL is valid and absolute
|
---|
| 572 | parsed = validateUrl(url.parse(input));
|
---|
| 573 | if (!isString(parsed.protocol)) {
|
---|
| 574 | throw new InvalidUrlError({ input });
|
---|
| 575 | }
|
---|
| 576 | }
|
---|
| 577 | return parsed;
|
---|
| 578 | }
|
---|
| 579 |
|
---|
| 580 | function resolveUrl(relative, base) {
|
---|
| 581 | // istanbul ignore next
|
---|
| 582 | return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative));
|
---|
| 583 | }
|
---|
| 584 |
|
---|
| 585 | function validateUrl(input) {
|
---|
| 586 | if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
|
---|
| 587 | throw new InvalidUrlError({ input: input.href || input });
|
---|
| 588 | }
|
---|
| 589 | if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
|
---|
| 590 | throw new InvalidUrlError({ input: input.href || input });
|
---|
| 591 | }
|
---|
| 592 | return input;
|
---|
| 593 | }
|
---|
| 594 |
|
---|
| 595 | function spreadUrlObject(urlObject, target) {
|
---|
| 596 | var spread = target || {};
|
---|
| 597 | for (var key of preservedUrlFields) {
|
---|
| 598 | spread[key] = urlObject[key];
|
---|
| 599 | }
|
---|
| 600 |
|
---|
| 601 | // Fix IPv6 hostname
|
---|
| 602 | if (spread.hostname.startsWith("[")) {
|
---|
| 603 | spread.hostname = spread.hostname.slice(1, -1);
|
---|
| 604 | }
|
---|
| 605 | // Ensure port is a number
|
---|
| 606 | if (spread.port !== "") {
|
---|
| 607 | spread.port = Number(spread.port);
|
---|
| 608 | }
|
---|
| 609 | // Concatenate path
|
---|
| 610 | spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
|
---|
| 611 |
|
---|
| 612 | return spread;
|
---|
| 613 | }
|
---|
| 614 |
|
---|
| 615 | function removeMatchingHeaders(regex, headers) {
|
---|
| 616 | var lastValue;
|
---|
| 617 | for (var header in headers) {
|
---|
| 618 | if (regex.test(header)) {
|
---|
| 619 | lastValue = headers[header];
|
---|
| 620 | delete headers[header];
|
---|
| 621 | }
|
---|
| 622 | }
|
---|
| 623 | return (lastValue === null || typeof lastValue === "undefined") ?
|
---|
| 624 | undefined : String(lastValue).trim();
|
---|
| 625 | }
|
---|
| 626 |
|
---|
| 627 | function createErrorType(code, message, baseClass) {
|
---|
| 628 | // Create constructor
|
---|
| 629 | function CustomError(properties) {
|
---|
| 630 | // istanbul ignore else
|
---|
| 631 | if (isFunction(Error.captureStackTrace)) {
|
---|
| 632 | Error.captureStackTrace(this, this.constructor);
|
---|
| 633 | }
|
---|
| 634 | Object.assign(this, properties || {});
|
---|
| 635 | this.code = code;
|
---|
| 636 | this.message = this.cause ? message + ": " + this.cause.message : message;
|
---|
| 637 | }
|
---|
| 638 |
|
---|
| 639 | // Attach constructor and set default properties
|
---|
| 640 | CustomError.prototype = new (baseClass || Error)();
|
---|
| 641 | Object.defineProperties(CustomError.prototype, {
|
---|
| 642 | constructor: {
|
---|
| 643 | value: CustomError,
|
---|
| 644 | enumerable: false,
|
---|
| 645 | },
|
---|
| 646 | name: {
|
---|
| 647 | value: "Error [" + code + "]",
|
---|
| 648 | enumerable: false,
|
---|
| 649 | },
|
---|
| 650 | });
|
---|
| 651 | return CustomError;
|
---|
| 652 | }
|
---|
| 653 |
|
---|
| 654 | function destroyRequest(request, error) {
|
---|
| 655 | for (var event of events) {
|
---|
| 656 | request.removeListener(event, eventHandlers[event]);
|
---|
| 657 | }
|
---|
| 658 | request.on("error", noop);
|
---|
| 659 | request.destroy(error);
|
---|
| 660 | }
|
---|
| 661 |
|
---|
| 662 | function isSubdomain(subdomain, domain) {
|
---|
| 663 | assert(isString(subdomain) && isString(domain));
|
---|
| 664 | var dot = subdomain.length - domain.length - 1;
|
---|
| 665 | return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
|
---|
| 666 | }
|
---|
| 667 |
|
---|
| 668 | function isString(value) {
|
---|
| 669 | return typeof value === "string" || value instanceof String;
|
---|
| 670 | }
|
---|
| 671 |
|
---|
| 672 | function isFunction(value) {
|
---|
| 673 | return typeof value === "function";
|
---|
| 674 | }
|
---|
| 675 |
|
---|
| 676 | function isBuffer(value) {
|
---|
| 677 | return typeof value === "object" && ("length" in value);
|
---|
| 678 | }
|
---|
| 679 |
|
---|
| 680 | function isURL(value) {
|
---|
| 681 | return URL && value instanceof URL;
|
---|
| 682 | }
|
---|
| 683 |
|
---|
| 684 | // Exports
|
---|
| 685 | module.exports = wrap({ http: http, https: https });
|
---|
| 686 | module.exports.wrap = wrap;
|
---|