index.js 19 KB

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