request.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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(...languages) {
  153. return accepts(this).languages(...languages);
  154. };
  155. /**
  156. * Parse Range header field, capping to the given `size`.
  157. *
  158. * Unspecified ranges such as "0-" require knowledge of your resource length. In
  159. * the case of a byte range this is of course the total number of bytes. If the
  160. * Range header field is not given `undefined` is returned, `-1` when unsatisfiable,
  161. * and `-2` when syntactically invalid.
  162. *
  163. * When ranges are returned, the array has a "type" property which is the type of
  164. * range that is required (most commonly, "bytes"). Each array element is an object
  165. * with a "start" and "end" property for the portion of the range.
  166. *
  167. * The "combine" option can be set to `true` and overlapping & adjacent ranges
  168. * will be combined into a single range.
  169. *
  170. * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
  171. * should respond with 4 users when available, not 3.
  172. *
  173. * @param {number} size
  174. * @param {object} [options]
  175. * @param {boolean} [options.combine=false]
  176. * @return {number|array}
  177. * @public
  178. */
  179. req.range = function range(size, options) {
  180. var range = this.get('Range');
  181. if (!range) return;
  182. return parseRange(size, range, options);
  183. };
  184. /**
  185. * Parse the query string of `req.url`.
  186. *
  187. * This uses the "query parser" setting to parse the raw
  188. * string into an object.
  189. *
  190. * @return {String}
  191. * @api public
  192. */
  193. defineGetter(req, 'query', function query(){
  194. var queryparse = this.app.get('query parser fn');
  195. if (!queryparse) {
  196. // parsing is disabled
  197. return Object.create(null);
  198. }
  199. var querystring = parse(this).query;
  200. return queryparse(querystring);
  201. });
  202. /**
  203. * Check if the incoming request contains the "Content-Type"
  204. * header field, and it contains the given mime `type`.
  205. *
  206. * Examples:
  207. *
  208. * // With Content-Type: text/html; charset=utf-8
  209. * req.is('html');
  210. * req.is('text/html');
  211. * req.is('text/*');
  212. * // => true
  213. *
  214. * // When Content-Type is application/json
  215. * req.is('json');
  216. * req.is('application/json');
  217. * req.is('application/*');
  218. * // => true
  219. *
  220. * req.is('html');
  221. * // => false
  222. *
  223. * @param {String|Array} types...
  224. * @return {String|false|null}
  225. * @public
  226. */
  227. req.is = function is(types) {
  228. var arr = types;
  229. // support flattened arguments
  230. if (!Array.isArray(types)) {
  231. arr = new Array(arguments.length);
  232. for (var i = 0; i < arr.length; i++) {
  233. arr[i] = arguments[i];
  234. }
  235. }
  236. return typeis(this, arr);
  237. };
  238. /**
  239. * Return the protocol string "http" or "https"
  240. * when requested with TLS. When the "trust proxy"
  241. * setting trusts the socket address, the
  242. * "X-Forwarded-Proto" header field will be trusted
  243. * and used if present.
  244. *
  245. * If you're running behind a reverse proxy that
  246. * supplies https for you this may be enabled.
  247. *
  248. * @return {String}
  249. * @public
  250. */
  251. defineGetter(req, 'protocol', function protocol(){
  252. var proto = this.socket.encrypted
  253. ? 'https'
  254. : 'http';
  255. var trust = this.app.get('trust proxy fn');
  256. if (!trust(this.socket.remoteAddress, 0)) {
  257. return proto;
  258. }
  259. // Note: X-Forwarded-Proto is normally only ever a
  260. // single value, but this is to be safe.
  261. var header = this.get('X-Forwarded-Proto') || proto
  262. var index = header.indexOf(',')
  263. return index !== -1
  264. ? header.substring(0, index).trim()
  265. : header.trim()
  266. });
  267. /**
  268. * Short-hand for:
  269. *
  270. * req.protocol === 'https'
  271. *
  272. * @return {Boolean}
  273. * @public
  274. */
  275. defineGetter(req, 'secure', function secure(){
  276. return this.protocol === 'https';
  277. });
  278. /**
  279. * Return the remote address from the trusted proxy.
  280. *
  281. * The is the remote address on the socket unless
  282. * "trust proxy" is set.
  283. *
  284. * @return {String}
  285. * @public
  286. */
  287. defineGetter(req, 'ip', function ip(){
  288. var trust = this.app.get('trust proxy fn');
  289. return proxyaddr(this, trust);
  290. });
  291. /**
  292. * When "trust proxy" is set, trusted proxy addresses + client.
  293. *
  294. * For example if the value were "client, proxy1, proxy2"
  295. * you would receive the array `["client", "proxy1", "proxy2"]`
  296. * where "proxy2" is the furthest down-stream and "proxy1" and
  297. * "proxy2" were trusted.
  298. *
  299. * @return {Array}
  300. * @public
  301. */
  302. defineGetter(req, 'ips', function ips() {
  303. var trust = this.app.get('trust proxy fn');
  304. var addrs = proxyaddr.all(this, trust);
  305. // reverse the order (to farthest -> closest)
  306. // and remove socket address
  307. addrs.reverse().pop()
  308. return addrs
  309. });
  310. /**
  311. * Return subdomains as an array.
  312. *
  313. * Subdomains are the dot-separated parts of the host before the main domain of
  314. * the app. By default, the domain of the app is assumed to be the last two
  315. * parts of the host. This can be changed by setting "subdomain offset".
  316. *
  317. * For example, if the domain is "tobi.ferrets.example.com":
  318. * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
  319. * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
  320. *
  321. * @return {Array}
  322. * @public
  323. */
  324. defineGetter(req, 'subdomains', function subdomains() {
  325. var hostname = this.hostname;
  326. if (!hostname) return [];
  327. var offset = this.app.get('subdomain offset');
  328. var subdomains = !isIP(hostname)
  329. ? hostname.split('.').reverse()
  330. : [hostname];
  331. return subdomains.slice(offset);
  332. });
  333. /**
  334. * Short-hand for `url.parse(req.url).pathname`.
  335. *
  336. * @return {String}
  337. * @public
  338. */
  339. defineGetter(req, 'path', function path() {
  340. return parse(this).pathname;
  341. });
  342. /**
  343. * Parse the "Host" header field to a host.
  344. *
  345. * When the "trust proxy" setting trusts the socket
  346. * address, the "X-Forwarded-Host" header field will
  347. * be trusted.
  348. *
  349. * @return {String}
  350. * @public
  351. */
  352. defineGetter(req, 'host', function host(){
  353. var trust = this.app.get('trust proxy fn');
  354. var val = this.get('X-Forwarded-Host');
  355. if (!val || !trust(this.socket.remoteAddress, 0)) {
  356. val = this.get('Host');
  357. } else if (val.indexOf(',') !== -1) {
  358. // Note: X-Forwarded-Host is normally only ever a
  359. // single value, but this is to be safe.
  360. val = val.substring(0, val.indexOf(',')).trimRight()
  361. }
  362. return val || undefined;
  363. });
  364. /**
  365. * Parse the "Host" header field to a hostname.
  366. *
  367. * When the "trust proxy" setting trusts the socket
  368. * address, the "X-Forwarded-Host" header field will
  369. * be trusted.
  370. *
  371. * @return {String}
  372. * @api public
  373. */
  374. defineGetter(req, 'hostname', function hostname(){
  375. var host = this.host;
  376. if (!host) return;
  377. // IPv6 literal support
  378. var offset = host[0] === '['
  379. ? host.indexOf(']') + 1
  380. : 0;
  381. var index = host.indexOf(':', offset);
  382. return index !== -1
  383. ? host.substring(0, index)
  384. : host;
  385. });
  386. /**
  387. * Check if the request is fresh, aka
  388. * Last-Modified or the ETag
  389. * still match.
  390. *
  391. * @return {Boolean}
  392. * @public
  393. */
  394. defineGetter(req, 'fresh', function(){
  395. var method = this.method;
  396. var res = this.res
  397. var status = res.statusCode
  398. // GET or HEAD for weak freshness validation only
  399. if ('GET' !== method && 'HEAD' !== method) return false;
  400. // 2xx or 304 as per rfc2616 14.26
  401. if ((status >= 200 && status < 300) || 304 === status) {
  402. return fresh(this.headers, {
  403. 'etag': res.get('ETag'),
  404. 'last-modified': res.get('Last-Modified')
  405. })
  406. }
  407. return false;
  408. });
  409. /**
  410. * Check if the request is stale, aka
  411. * "Last-Modified" and / or the "ETag" for the
  412. * resource has changed.
  413. *
  414. * @return {Boolean}
  415. * @public
  416. */
  417. defineGetter(req, 'stale', function stale(){
  418. return !this.fresh;
  419. });
  420. /**
  421. * Check if the request was an _XMLHttpRequest_.
  422. *
  423. * @return {Boolean}
  424. * @public
  425. */
  426. defineGetter(req, 'xhr', function xhr(){
  427. var val = this.get('X-Requested-With') || '';
  428. return val.toLowerCase() === 'xmlhttprequest';
  429. });
  430. /**
  431. * Helper function for creating a getter on an object.
  432. *
  433. * @param {Object} obj
  434. * @param {String} name
  435. * @param {Function} getter
  436. * @private
  437. */
  438. function defineGetter(obj, name, getter) {
  439. Object.defineProperty(obj, name, {
  440. configurable: true,
  441. enumerable: true,
  442. get: getter
  443. });
  444. }