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.

502 lines
12 KiB

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