index.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. var url = require("url");
  2. var http = require("http");
  3. var https = require("https");
  4. var assert = require("assert");
  5. var Writable = require("stream").Writable;
  6. var debug = require("debug")("follow-redirects");
  7. // RFC7231§4.2.1: Of the request methods defined by this specification,
  8. // the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe.
  9. var SAFE_METHODS = { GET: true, HEAD: true, OPTIONS: true, TRACE: true };
  10. // Create handlers that pass events from native requests
  11. var eventHandlers = Object.create(null);
  12. ["abort", "aborted", "error", "socket", "timeout"].forEach(function (event) {
  13. eventHandlers[event] = function (arg) {
  14. this._redirectable.emit(event, arg);
  15. };
  16. });
  17. // An HTTP(S) request that can be redirected
  18. function RedirectableRequest(options, responseCallback) {
  19. // Initialize the request
  20. Writable.call(this);
  21. options.headers = options.headers || {};
  22. this._options = options;
  23. this._redirectCount = 0;
  24. this._redirects = [];
  25. this._requestBodyLength = 0;
  26. this._requestBodyBuffers = [];
  27. // Attach a callback if passed
  28. if (responseCallback) {
  29. this.on("response", responseCallback);
  30. }
  31. // React to responses of native requests
  32. var self = this;
  33. this._onNativeResponse = function (response) {
  34. self._processResponse(response);
  35. };
  36. // Complete the URL object when necessary
  37. if (!options.pathname && options.path) {
  38. var searchPos = options.path.indexOf("?");
  39. if (searchPos < 0) {
  40. options.pathname = options.path;
  41. }
  42. else {
  43. options.pathname = options.path.substring(0, searchPos);
  44. options.search = options.path.substring(searchPos);
  45. }
  46. }
  47. // Perform the first request
  48. this._performRequest();
  49. }
  50. RedirectableRequest.prototype = Object.create(Writable.prototype);
  51. // Writes buffered data to the current native request
  52. RedirectableRequest.prototype.write = function (data, encoding, callback) {
  53. if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
  54. throw new Error("data should be a string, Buffer or Uint8Array");
  55. }
  56. if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
  57. this._requestBodyLength += data.length;
  58. this._requestBodyBuffers.push({ data: data, encoding: encoding });
  59. this._currentRequest.write(data, encoding, callback);
  60. }
  61. else {
  62. this.emit("error", new Error("Request body larger than maxBodyLength limit"));
  63. this.abort();
  64. }
  65. };
  66. // Ends the current native request
  67. RedirectableRequest.prototype.end = function (data, encoding, callback) {
  68. var currentRequest = this._currentRequest;
  69. if (!data) {
  70. currentRequest.end(null, null, callback);
  71. }
  72. else {
  73. this.write(data, encoding, function () {
  74. currentRequest.end(null, null, callback);
  75. });
  76. }
  77. };
  78. // Sets a header value on the current native request
  79. RedirectableRequest.prototype.setHeader = function (name, value) {
  80. this._options.headers[name] = value;
  81. this._currentRequest.setHeader(name, value);
  82. };
  83. // Clears a header value on the current native request
  84. RedirectableRequest.prototype.removeHeader = function (name) {
  85. delete this._options.headers[name];
  86. this._currentRequest.removeHeader(name);
  87. };
  88. // Proxy all other public ClientRequest methods
  89. [
  90. "abort", "flushHeaders", "getHeader",
  91. "setNoDelay", "setSocketKeepAlive", "setTimeout",
  92. ].forEach(function (method) {
  93. RedirectableRequest.prototype[method] = function (a, b) {
  94. return this._currentRequest[method](a, b);
  95. };
  96. });
  97. // Proxy all public ClientRequest properties
  98. ["aborted", "connection", "socket"].forEach(function (property) {
  99. Object.defineProperty(RedirectableRequest.prototype, property, {
  100. get: function () { return this._currentRequest[property]; },
  101. });
  102. });
  103. // Executes the next native request (initial or redirect)
  104. RedirectableRequest.prototype._performRequest = function () {
  105. // Load the native protocol
  106. var protocol = this._options.protocol;
  107. var nativeProtocol = this._options.nativeProtocols[protocol];
  108. // If specified, use the agent corresponding to the protocol
  109. // (HTTP and HTTPS use different types of agents)
  110. if (this._options.agents) {
  111. var scheme = protocol.substr(0, protocol.length - 1);
  112. this._options.agent = this._options.agents[scheme];
  113. }
  114. // Create the native request
  115. var request = this._currentRequest =
  116. nativeProtocol.request(this._options, this._onNativeResponse);
  117. this._currentUrl = url.format(this._options);
  118. // Set up event handlers
  119. request._redirectable = this;
  120. for (var event in eventHandlers) {
  121. /* istanbul ignore else */
  122. if (event) {
  123. request.on(event, eventHandlers[event]);
  124. }
  125. }
  126. // End a redirected request
  127. // (The first request must be ended explicitly with RedirectableRequest#end)
  128. if (this._isRedirect) {
  129. // Write the request entity and end.
  130. var requestBodyBuffers = this._requestBodyBuffers;
  131. (function writeNext() {
  132. if (requestBodyBuffers.length !== 0) {
  133. var buffer = requestBodyBuffers.pop();
  134. request.write(buffer.data, buffer.encoding, writeNext);
  135. }
  136. else {
  137. request.end();
  138. }
  139. }());
  140. }
  141. };
  142. // Processes a response from the current native request
  143. RedirectableRequest.prototype._processResponse = function (response) {
  144. // Store the redirected response
  145. if (this._options.trackRedirects) {
  146. this._redirects.push({
  147. url: this._currentUrl,
  148. headers: response.headers,
  149. statusCode: response.statusCode,
  150. });
  151. }
  152. // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
  153. // that further action needs to be taken by the user agent in order to
  154. // fulfill the request. If a Location header field is provided,
  155. // the user agent MAY automatically redirect its request to the URI
  156. // referenced by the Location field value,
  157. // even if the specific status code is not understood.
  158. var location = response.headers.location;
  159. if (location && this._options.followRedirects !== false &&
  160. response.statusCode >= 300 && response.statusCode < 400) {
  161. // RFC7231§6.4: A client SHOULD detect and intervene
  162. // in cyclical redirections (i.e., "infinite" redirection loops).
  163. if (++this._redirectCount > this._options.maxRedirects) {
  164. this.emit("error", new Error("Max redirects exceeded."));
  165. return;
  166. }
  167. // RFC7231§6.4: Automatic redirection needs to done with
  168. // care for methods not known to be safe […],
  169. // since the user might not wish to redirect an unsafe request.
  170. // RFC7231§6.4.7: The 307 (Temporary Redirect) status code indicates
  171. // that the target resource resides temporarily under a different URI
  172. // and the user agent MUST NOT change the request method
  173. // if it performs an automatic redirection to that URI.
  174. var header;
  175. var headers = this._options.headers;
  176. if (response.statusCode !== 307 && !(this._options.method in SAFE_METHODS)) {
  177. this._options.method = "GET";
  178. // Drop a possible entity and headers related to it
  179. this._requestBodyBuffers = [];
  180. for (header in headers) {
  181. if (/^content-/i.test(header)) {
  182. delete headers[header];
  183. }
  184. }
  185. }
  186. // Drop the Host header, as the redirect might lead to a different host
  187. if (!this._isRedirect) {
  188. for (header in headers) {
  189. if (/^host$/i.test(header)) {
  190. delete headers[header];
  191. }
  192. }
  193. }
  194. // Perform the redirected request
  195. var redirectUrl = url.resolve(this._currentUrl, location);
  196. debug("redirecting to", redirectUrl);
  197. Object.assign(this._options, url.parse(redirectUrl));
  198. this._isRedirect = true;
  199. this._performRequest();
  200. // Discard the remainder of the response to avoid waiting for data
  201. response.destroy();
  202. }
  203. else {
  204. // The response is not a redirect; return it as-is
  205. response.responseUrl = this._currentUrl;
  206. response.redirects = this._redirects;
  207. this.emit("response", response);
  208. // Clean up
  209. this._requestBodyBuffers = [];
  210. }
  211. };
  212. // Wraps the key/value object of protocols with redirect functionality
  213. function wrap(protocols) {
  214. // Default settings
  215. var exports = {
  216. maxRedirects: 21,
  217. maxBodyLength: 10 * 1024 * 1024,
  218. };
  219. // Wrap each protocol
  220. var nativeProtocols = {};
  221. Object.keys(protocols).forEach(function (scheme) {
  222. var protocol = scheme + ":";
  223. var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
  224. var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
  225. // Executes a request, following redirects
  226. wrappedProtocol.request = function (options, callback) {
  227. if (typeof options === "string") {
  228. options = url.parse(options);
  229. options.maxRedirects = exports.maxRedirects;
  230. }
  231. else {
  232. options = Object.assign({
  233. protocol: protocol,
  234. maxRedirects: exports.maxRedirects,
  235. maxBodyLength: exports.maxBodyLength,
  236. }, options);
  237. }
  238. options.nativeProtocols = nativeProtocols;
  239. assert.equal(options.protocol, protocol, "protocol mismatch");
  240. debug("options", options);
  241. return new RedirectableRequest(options, callback);
  242. };
  243. // Executes a GET request, following redirects
  244. wrappedProtocol.get = function (options, callback) {
  245. var request = wrappedProtocol.request(options, callback);
  246. request.end();
  247. return request;
  248. };
  249. });
  250. return exports;
  251. }
  252. // Exports
  253. module.exports = wrap({ http: http, https: https });
  254. module.exports.wrap = wrap;