request.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /*!
  2. * express
  3. * Copyright(c) 2009-2013 TJ Holowaychuk
  4. * Copyright(c) 2013 Roman Shtylman
  5. * Copyright(c) 2014-2015 Douglas Christopher Wilson
  6. * MIT Licensed
  7. */
  8. 'use strict';
  9. /**
  10. * Module dependencies.
  11. * @private
  12. */
  13. var accepts = require('accepts');
  14. var isIP = require('node:net').isIP;
  15. var typeis = require('type-is');
  16. var http = require('node:http');
  17. var fresh = require('fresh');
  18. var parseRange = require('range-parser');
  19. var parse = require('parseurl');
  20. var proxyaddr = require('proxy-addr');
  21. /**
  22. * Request prototype.
  23. * @public
  24. */
  25. var req = Object.create(http.IncomingMessage.prototype)
  26. /**
  27. * Module exports.
  28. * @public
  29. */
  30. module.exports = req
  31. /**
  32. * Return request header.
  33. *
  34. * The `Referrer` header field is special-cased,
  35. * both `Referrer` and `Referer` are interchangeable.
  36. *
  37. * Examples:
  38. *
  39. * req.get('Content-Type');
  40. * // => "text/plain"
  41. *
  42. * req.get('content-type');
  43. * // => "text/plain"
  44. *
  45. * req.get('Something');
  46. * // => undefined
  47. *
  48. * Aliased as `req.header()`.
  49. *
  50. * @param {String} name
  51. * @return {String}
  52. * @public
  53. */
  54. req.get =
  55. req.header = function header(name) {
  56. if (!name) {
  57. throw new TypeError('name argument is required to req.get');
  58. }
  59. if (typeof name !== 'string') {
  60. throw new TypeError('name must be a string to req.get');
  61. }
  62. var lc = name.toLowerCase();
  63. switch (lc) {
  64. case 'referer':
  65. case 'referrer':
  66. return this.headers.referrer
  67. || this.headers.referer;
  68. default:
  69. return this.headers[lc];
  70. }
  71. };
  72. /**
  73. * To do: update docs.
  74. *
  75. * Check if the given `type(s)` is acceptable, returning
  76. * the best match when true, otherwise `undefined`, in which
  77. * case you should respond with 406 "Not Acceptable".
  78. *
  79. * The `type` value may be a single MIME type string
  80. * such as "application/json", an extension name
  81. * such as "json", a comma-delimited list such as "json, html, text/plain",
  82. * an argument list such as `"json", "html", "text/plain"`,
  83. * or an array `["json", "html", "text/plain"]`. When a list
  84. * or array is given, the _best_ match, if any is returned.
  85. *
  86. * Examples:
  87. *
  88. * // Accept: text/html
  89. * req.accepts('html');
  90. * // => "html"
  91. *
  92. * // Accept: text/*, application/json
  93. * req.accepts('html');
  94. * // => "html"
  95. * req.accepts('text/html');
  96. * // => "text/html"
  97. * req.accepts('json, text');
  98. * // => "json"
  99. * req.accepts('application/json');
  100. * // => "application/json"
  101. *
  102. * // Accept: text/*, application/json
  103. * req.accepts('image/png');
  104. * req.accepts('png');
  105. * // => undefined
  106. *
  107. * // Accept: text/*;q=.5, application/json
  108. * req.accepts(['html', 'json']);
  109. * req.accepts('html', 'json');
  110. * req.accepts('html, json');
  111. * // => "json"
  112. *
  113. * @param {String|Array} type(s)
  114. * @return {String|Array|Boolean}
  115. * @public
  116. */
  117. req.accepts = function(){
  118. var accept = accepts(this);
  119. return accept.types.apply(accept, arguments);
  120. };
  121. /**
  122. * Check if the given `encoding`s are accepted.
  123. *
  124. * @param {String} ...encoding
  125. * @return {String|Array}
  126. * @public
  127. */
  128. req.acceptsEncodings = function(){
  129. var accept = accepts(this);
  130. return accept.encodings.apply(accept, arguments);
  131. };
  132. /**
  133. * Check if the given `charset`s are acceptable,
  134. * otherwise you should respond with 406 "Not Acceptable".
  135. *
  136. * @param {String} ...charset
  137. * @return {String|Array}
  138. * @public
  139. */
  140. req.acceptsCharsets = function(){
  141. var accept = accepts(this);
  142. return accept.charsets.apply(accept, arguments);
  143. };
  144. /**
  145. * Check if the given `lang`s are acceptable,
  146. * otherwise you should respond with 406 "Not Acceptable".
  147. *
  148. * @param {String} ...lang
  149. * @return {String|Array}
  150. * @public
  151. */
  152. req.acceptsLanguages = function(){
  153. var accept = accepts(this);
  154. return accept.languages.apply(accept, arguments);
  155. };
  156. /**
  157. * Parse Range header field, capping to the given `size`.
  158. *
  159. * Unspecified ranges such as "0-" require knowledge of your resource length. In
  160. * the case of a byte range this is of course the total number of bytes. If the
  161. * Range header field is not given `undefined` is returned, `-1` when unsatisfiable,
  162. * and `-2` when syntactically invalid.
  163. *
  164. * When ranges are returned, the array has a "type" property which is the type of
  165. * range that is required (most commonly, "bytes"). Each array element is an object
  166. * with a "start" and "end" property for the portion of the range.
  167. *
  168. * The "combine" option can be set to `true` and overlapping & adjacent ranges
  169. * will be combined into a single range.
  170. *
  171. * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
  172. * should respond with 4 users when available, not 3.
  173. *
  174. * @param {number} size
  175. * @param {object} [options]
  176. * @param {boolean} [options.combine=false]
  177. * @return {number|array}
  178. * @public
  179. */
  180. req.range = function range(size, options) {
  181. var range = this.get('Range');
  182. if (!range) return;
  183. return parseRange(size, range, options);
  184. };
  185. /**
  186. * Parse the query string of `req.url`.
  187. *
  188. * This uses the "query parser" setting to parse the raw
  189. * string into an object.
  190. *
  191. * @return {String}
  192. * @api public
  193. */
  194. defineGetter(req, 'query', function query(){
  195. var queryparse = this.app.get('query parser fn');
  196. if (!queryparse) {
  197. // parsing is disabled
  198. return Object.create(null);
  199. }
  200. var querystring = parse(this).query;
  201. return queryparse(querystring);
  202. });
  203. /**
  204. * Check if the incoming request contains the "Content-Type"
  205. * header field, and it contains the given mime `type`.
  206. *
  207. * Examples:
  208. *
  209. * // With Content-Type: text/html; charset=utf-8
  210. * req.is('html');
  211. * req.is('text/html');
  212. * req.is('text/*');
  213. * // => true
  214. *
  215. * // When Content-Type is application/json
  216. * req.is('json');
  217. * req.is('application/json');
  218. * req.is('application/*');
  219. * // => true
  220. *
  221. * req.is('html');
  222. * // => false
  223. *
  224. * @param {String|Array} types...
  225. * @return {String|false|null}
  226. * @public
  227. */
  228. req.is = function is(types) {
  229. var arr = types;
  230. // support flattened arguments
  231. if (!Array.isArray(types)) {
  232. arr = new Array(arguments.length);
  233. for (var i = 0; i < arr.length; i++) {
  234. arr[i] = arguments[i];
  235. }
  236. }
  237. return typeis(this, arr);
  238. };
  239. /**
  240. * Return the protocol string "http" or "https"
  241. * when requested with TLS. When the "trust proxy"
  242. * setting trusts the socket address, the
  243. * "X-Forwarded-Proto" header field will be trusted
  244. * and used if present.
  245. *
  246. * If you're running behind a reverse proxy that
  247. * supplies https for you this may be enabled.
  248. *
  249. * @return {String}
  250. * @public
  251. */
  252. defineGetter(req, 'protocol', function protocol(){
  253. var proto = this.connection.encrypted
  254. ? 'https'
  255. : 'http';
  256. var trust = this.app.get('trust proxy fn');
  257. if (!trust(this.connection.remoteAddress, 0)) {
  258. return proto;
  259. }
  260. // Note: X-Forwarded-Proto is normally only ever a
  261. // single value, but this is to be safe.
  262. var header = this.get('X-Forwarded-Proto') || proto
  263. var index = header.indexOf(',')
  264. return index !== -1
  265. ? header.substring(0, index).trim()
  266. : header.trim()
  267. });
  268. /**
  269. * Short-hand for:
  270. *
  271. * req.protocol === 'https'
  272. *
  273. * @return {Boolean}
  274. * @public
  275. */
  276. defineGetter(req, 'secure', function secure(){
  277. return this.protocol === 'https';
  278. });
  279. /**
  280. * Return the remote address from the trusted proxy.
  281. *
  282. * The is the remote address on the socket unless
  283. * "trust proxy" is set.
  284. *
  285. * @return {String}
  286. * @public
  287. */
  288. defineGetter(req, 'ip', function ip(){
  289. var trust = this.app.get('trust proxy fn');
  290. return proxyaddr(this, trust);
  291. });
  292. /**
  293. * When "trust proxy" is set, trusted proxy addresses + client.
  294. *
  295. * For example if the value were "client, proxy1, proxy2"
  296. * you would receive the array `["client", "proxy1", "proxy2"]`
  297. * where "proxy2" is the furthest down-stream and "proxy1" and
  298. * "proxy2" were trusted.
  299. *
  300. * @return {Array}
  301. * @public
  302. */
  303. defineGetter(req, 'ips', function ips() {
  304. var trust = this.app.get('trust proxy fn');
  305. var addrs = proxyaddr.all(this, trust);
  306. // reverse the order (to farthest -> closest)
  307. // and remove socket address
  308. addrs.reverse().pop()
  309. return addrs
  310. });
  311. /**
  312. * Return subdomains as an array.
  313. *
  314. * Subdomains are the dot-separated parts of the host before the main domain of
  315. * the app. By default, the domain of the app is assumed to be the last two
  316. * parts of the host. This can be changed by setting "subdomain offset".
  317. *
  318. * For example, if the domain is "tobi.ferrets.example.com":
  319. * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
  320. * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
  321. *
  322. * @return {Array}
  323. * @public
  324. */
  325. defineGetter(req, 'subdomains', function subdomains() {
  326. var hostname = this.hostname;
  327. if (!hostname) return [];
  328. var offset = this.app.get('subdomain offset');
  329. var subdomains = !isIP(hostname)
  330. ? hostname.split('.').reverse()
  331. : [hostname];
  332. return subdomains.slice(offset);
  333. });
  334. /**
  335. * Short-hand for `url.parse(req.url).pathname`.
  336. *
  337. * @return {String}
  338. * @public
  339. */
  340. defineGetter(req, 'path', function path() {
  341. return parse(this).pathname;
  342. });
  343. /**
  344. * Parse the "Host" header field to a host.
  345. *
  346. * When the "trust proxy" setting trusts the socket
  347. * address, the "X-Forwarded-Host" header field will
  348. * be trusted.
  349. *
  350. * @return {String}
  351. * @public
  352. */
  353. defineGetter(req, 'host', function host(){
  354. var trust = this.app.get('trust proxy fn');
  355. var val = this.get('X-Forwarded-Host');
  356. if (!val || !trust(this.connection.remoteAddress, 0)) {
  357. val = this.get('Host');
  358. } else if (val.indexOf(',') !== -1) {
  359. // Note: X-Forwarded-Host is normally only ever a
  360. // single value, but this is to be safe.
  361. val = val.substring(0, val.indexOf(',')).trimRight()
  362. }
  363. return val || undefined;
  364. });
  365. /**
  366. * Parse the "Host" header field to a hostname.
  367. *
  368. * When the "trust proxy" setting trusts the socket
  369. * address, the "X-Forwarded-Host" header field will
  370. * be trusted.
  371. *
  372. * @return {String}
  373. * @api public
  374. */
  375. defineGetter(req, 'hostname', function hostname(){
  376. var host = this.host;
  377. if (!host) return;
  378. // IPv6 literal support
  379. var offset = host[0] === '['
  380. ? host.indexOf(']') + 1
  381. : 0;
  382. var index = host.indexOf(':', offset);
  383. return index !== -1
  384. ? host.substring(0, index)
  385. : host;
  386. });
  387. /**
  388. * Check if the request is fresh, aka
  389. * Last-Modified or the ETag
  390. * still match.
  391. *
  392. * @return {Boolean}
  393. * @public
  394. */
  395. defineGetter(req, 'fresh', function(){
  396. var method = this.method;
  397. var res = this.res
  398. var status = res.statusCode
  399. // GET or HEAD for weak freshness validation only
  400. if ('GET' !== method && 'HEAD' !== method) return false;
  401. // 2xx or 304 as per rfc2616 14.26
  402. if ((status >= 200 && status < 300) || 304 === status) {
  403. return fresh(this.headers, {
  404. 'etag': res.get('ETag'),
  405. 'last-modified': res.get('Last-Modified')
  406. })
  407. }
  408. return false;
  409. });
  410. /**
  411. * Check if the request is stale, aka
  412. * "Last-Modified" and / or the "ETag" for the
  413. * resource has changed.
  414. *
  415. * @return {Boolean}
  416. * @public
  417. */
  418. defineGetter(req, 'stale', function stale(){
  419. return !this.fresh;
  420. });
  421. /**
  422. * Check if the request was an _XMLHttpRequest_.
  423. *
  424. * @return {Boolean}
  425. * @public
  426. */
  427. defineGetter(req, 'xhr', function xhr(){
  428. var val = this.get('X-Requested-With') || '';
  429. return val.toLowerCase() === 'xmlhttprequest';
  430. });
  431. /**
  432. * Helper function for creating a getter on an object.
  433. *
  434. * @param {Object} obj
  435. * @param {String} name
  436. * @param {Function} getter
  437. * @private
  438. */
  439. function defineGetter(obj, name, getter) {
  440. Object.defineProperty(obj, name, {
  441. configurable: true,
  442. enumerable: true,
  443. get: getter
  444. });
  445. }