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.

527 lines
11 KiB

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