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.

http.js 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. /**
  2. * Module dependencies.
  3. */
  4. var url = require('url');
  5. var http = require('http');
  6. var https = require('https');
  7. var extend = require('extend');
  8. var NotFoundError = require('./notfound');
  9. var NotModifiedError = require('./notmodified');
  10. var debug = require('debug')('get-uri:http');
  11. /**
  12. * Module exports.
  13. */
  14. module.exports = get;
  15. /**
  16. * Returns a Readable stream from an "http:" URI.
  17. *
  18. * @api protected
  19. */
  20. function get (parsed, opts, fn) {
  21. debug('GET %o', parsed.href);
  22. var cache = getCache(parsed, opts.cache);
  23. // 5 redirects allowed by default
  24. var maxRedirects = opts.hasOwnProperty('maxRedirects') ? opts.maxRedirects : 5;
  25. debug('allowing %o max redirects', maxRedirects);
  26. // first check the previous Expires and/or Cache-Control headers
  27. // of a previous response if a `cache` was provided
  28. if (cache && isFresh(cache)) {
  29. // check for a 3xx "redirect" status code on the previous cache
  30. var location = cache.headers.location;
  31. var type = (cache.statusCode / 100 | 0);
  32. if (3 == type && location) {
  33. debug('cached redirect');
  34. fn(new Error('TODO: implement cached redirects!'));
  35. } else {
  36. // otherwise we assume that it's the destination endpoint,
  37. // since there's nowhere else to redirect to
  38. fn(new NotModifiedError());
  39. }
  40. return;
  41. }
  42. var mod;
  43. if (opts.http) {
  44. // the `https` module passed in from the "http.js" file
  45. mod = opts.http;
  46. debug('using secure `https` core module');
  47. } else {
  48. mod = http;
  49. debug('using `http` core module');
  50. }
  51. var options = extend({}, opts, parsed);
  52. // add "cache validation" headers if a `cache` was provided
  53. if (cache) {
  54. if (!options.headers) options.headers = {};
  55. var lastModified = cache.headers['last-modified'];
  56. if (lastModified != null) {
  57. options.headers['If-Modified-Since'] = lastModified;
  58. debug('added "If-Modified-Since" request header: %o', lastModified);
  59. }
  60. var etag = cache.headers.etag;
  61. if (etag != null) {
  62. options.headers['If-None-Match'] = etag;
  63. debug('added "If-None-Match" request header: %o', etag);
  64. }
  65. }
  66. var req = mod.get(options);
  67. req.once('error', onerror);
  68. req.once('response', onresponse);
  69. // http.ClientRequest "error" event handler
  70. function onerror (err) {
  71. debug('http.ClientRequest "error" event: %o', err.stack || err);
  72. fn(err);
  73. }
  74. // http.ClientRequest "response" event handler
  75. function onresponse (res) {
  76. var code = res.statusCode;
  77. // assign a Date to this response for the "Cache-Control" delta calculation
  78. res.date = new Date();
  79. res.parsed = parsed;
  80. debug('got %o response status code', code);
  81. // any 2xx response is a "success" code
  82. var type = (code / 100 | 0);
  83. // check for a 3xx "redirect" status code
  84. var location = res.headers.location;
  85. if (3 == type && location) {
  86. if (!opts.redirects) opts.redirects = [];
  87. var redirects = opts.redirects;
  88. if (redirects.length < maxRedirects) {
  89. debug('got a "redirect" status code with Location: %o', location);
  90. // flush this response - we're not going to use it
  91. res.resume();
  92. // hang on to this Response object for the "redirects" Array
  93. redirects.push(res);
  94. var newUri = url.resolve(parsed, location);
  95. debug('resolved redirect URL: %o', newUri);
  96. var left = maxRedirects - redirects.length;
  97. debug('%o more redirects allowed after this one', left);
  98. // check if redirecting to a different protocol
  99. var parsedUrl = url.parse(newUri);
  100. if (parsedUrl.protocol !== parsed.protocol) {
  101. opts.http = parsedUrl.protocol === 'https:' ? https : undefined;
  102. }
  103. return get(parsedUrl, opts, fn);
  104. }
  105. }
  106. // if we didn't get a 2xx "success" status code, then create an Error object
  107. if (2 != type) {
  108. var err;
  109. if (304 == code) {
  110. err = new NotModifiedError();
  111. } else if (404 == code) {
  112. err = new NotFoundError();
  113. } else {
  114. // other HTTP-level error
  115. var message = http.STATUS_CODES[code];
  116. err = new Error(message);
  117. err.statusCode = code;
  118. err.code = code;
  119. }
  120. res.resume();
  121. return fn(err);
  122. }
  123. if (opts.redirects) {
  124. // store a reference to the "redirects" Array on the Response object so that
  125. // they can be inspected during a subsequent call to GET the same URI
  126. res.redirects = opts.redirects;
  127. }
  128. fn(null, res);
  129. }
  130. }
  131. /**
  132. * Returns `true` if the provided cache's "freshness" is valid. That is, either
  133. * the Cache-Control header or Expires header values are still within the allowed
  134. * time period.
  135. *
  136. * @return {Boolean}
  137. * @api private
  138. */
  139. function isFresh (cache) {
  140. var cacheControl = cache.headers['cache-control'];
  141. var expires = cache.headers.expires;
  142. var fresh;
  143. if (cacheControl) {
  144. // for Cache-Control rules, see: http://www.mnot.net/cache_docs/#CACHE-CONTROL
  145. debug('Cache-Control: %o', cacheControl);
  146. var parts = cacheControl.split(/,\s*?\b/);
  147. for (var i = 0; i < parts.length; i++) {
  148. var part = parts[i];
  149. var subparts = part.split('=');
  150. var name = subparts[0];
  151. switch (name) {
  152. case 'max-age':
  153. var val = +subparts[1];
  154. expires = new Date(+cache.date + (val * 1000));
  155. fresh = new Date() < expires;
  156. if (fresh) debug('cache is "fresh" due to previous %o Cache-Control param', part);
  157. return fresh;
  158. case 'must-revalidate':
  159. // XXX: what we supposed to do here?
  160. break;
  161. case 'no-cache':
  162. case 'no-store':
  163. debug('cache is "stale" due to explicit %o Cache-Control param', name);
  164. return false;
  165. }
  166. }
  167. } else if (expires) {
  168. // for Expires rules, see: http://www.mnot.net/cache_docs/#EXPIRES
  169. debug('Expires: %o', expires);
  170. fresh = new Date() < new Date(expires);
  171. if (fresh) debug('cache is "fresh" due to previous Expires response header');
  172. return fresh;
  173. }
  174. return false;
  175. }
  176. /**
  177. * Attempts to return a previous Response object from a previous GET call to the
  178. * same URI.
  179. *
  180. * @api private
  181. */
  182. function getCache (parsed, cache) {
  183. if (!cache) return;
  184. var href = parsed.href;
  185. if (cache.parsed.href == href) {
  186. return cache;
  187. }
  188. var redirects = cache.redirects;
  189. if (redirects) {
  190. for (var i = 0; i < redirects.length; i++) {
  191. var c = getCache(parsed, redirects[i]);
  192. if (c) return c;
  193. }
  194. }
  195. }