You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

498 lines
15 KiB

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