Skip to content
Myr

request.js

This file

Path

lib/request.js

554 lines · 12.2 KiB · JavaScript

Last changed by

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

History of this file

Take it

12/**3 * Module dependencies.4 */56var http = require('http')7  , utils = require('./utils')8  , connect = require('connect')9  , fresh = require('fresh')10  , parseRange = require('range-parser')11  , parse = require('parseurl')12  , proxyaddr = require('proxy-addr')13  , mime = connect.mime;1415/**16 * Request prototype.17 */1819var req = exports = module.exports = {20  __proto__: http.IncomingMessage.prototype21};2223/**24 * Return request header.25 *26 * The `Referrer` header field is special-cased,27 * both `Referrer` and `Referer` are interchangeable.28 *29 * Examples:30 *31 *     req.get('Content-Type');32 *     // => "text/plain"33 *34 *     req.get('content-type');35 *     // => "text/plain"36 *37 *     req.get('Something');38 *     // => undefined39 *40 * Aliased as `req.header()`.41 *42 * @param {String} name43 * @return {String}44 * @api public45 */4647req.get =48req.header = function(name){49  switch (name = name.toLowerCase()) {50    case 'referer':51    case 'referrer':52      return this.headers.referrer53        || this.headers.referer;54    default:55      return this.headers[name];56  }57};5859/**60 * Check if the given `type(s)` is acceptable, returning61 * the best match when true, otherwise `undefined`, in which62 * case you should respond with 406 "Not Acceptable".63 *64 * The `type` value may be a single mime type string65 * such as "application/json", the extension name66 * such as "json", a comma-delimted list such as "json, html, text/plain",67 * an argument list such as `"json", "html", "text/plain"`,68 * or an array `["json", "html", "text/plain"]`. When a list69 * or array is given the _best_ match, if any is returned.70 *71 * Examples:72 *73 *     // Accept: text/html74 *     req.accepts('html');75 *     // => "html"76 *77 *     // Accept: text/*, application/json78 *     req.accepts('html');79 *     // => "html"80 *     req.accepts('text/html');81 *     // => "text/html"82 *     req.accepts('json, text');83 *     // => "json"84 *     req.accepts('application/json');85 *     // => "application/json"86 *87 *     // Accept: text/*, application/json88 *     req.accepts('image/png');89 *     req.accepts('png');90 *     // => undefined91 *92 *     // Accept: text/*;q=.5, application/json93 *     req.accepts(['html', 'json']);94 *     req.accepts('html', 'json');95 *     req.accepts('html, json');96 *     // => "json"97 *98 * @param {String|Array} type(s)99 * @return {String}100 * @api public101 */102103req.accepts = function(type){104  var args = arguments.length > 1 ? [].slice.apply(arguments) : type;105  return utils.accepts(args, this.get('Accept'));106};107108/**109 * Check if the given `encoding` is accepted.110 *111 * @param {String} encoding112 * @return {Boolean}113 * @api public114 */115116req.acceptsEncoding = function(encoding){117  return !! ~this.acceptedEncodings.indexOf(encoding);118};119120/**121 * Check if the given `charset` is acceptable,122 * otherwise you should respond with 406 "Not Acceptable".123 *124 * @param {String} charset125 * @return {Boolean}126 * @api public127 */128129req.acceptsCharset = function(charset){130  var accepted = this.acceptedCharsets;131  return accepted.length132    ? !! ~accepted.indexOf(charset)133    : true;134};135136/**137 * Check if the given `lang` is acceptable,138 * otherwise you should respond with 406 "Not Acceptable".139 *140 * @param {String} lang141 * @return {Boolean}142 * @api public143 */144145req.acceptsLanguage = function(lang){146  var accepted = this.acceptedLanguages;147  return accepted.length148    ? !! ~accepted.indexOf(lang)149    : true;150};151152/**153 * Parse Range header field,154 * capping to the given `size`.155 *156 * Unspecified ranges such as "0-" require157 * knowledge of your resource length. In158 * the case of a byte range this is of course159 * the total number of bytes. If the Range160 * header field is not given `null` is returned,161 * `-1` when unsatisfiable, `-2` when syntactically invalid.162 *163 * NOTE: remember that ranges are inclusive, so164 * for example "Range: users=0-3" should respond165 * with 4 users when available, not 3.166 *167 * @param {Number} size168 * @return {Array}169 * @api public170 */171172req.range = function(size){173  var range = this.get('Range');174  if (!range) return;175  return parseRange(size, range);176};177178/**179 * Return an array of encodings.180 *181 * Examples:182 *183 *     ['gzip', 'deflate']184 *185 * @return {Array}186 * @api public187 */188189req.__defineGetter__('acceptedEncodings', function(){190  var accept = this.get('Accept-Encoding');191  return accept192    ? accept.trim().split(/ *, */)193    : [];194});195196/**197 * Return an array of Accepted media types198 * ordered from highest quality to lowest.199 *200 * Examples:201 *202 *     [ { value: 'application/json',203 *         quality: 1,204 *         type: 'application',205 *         subtype: 'json' },206 *       { value: 'text/html',207 *         quality: 0.5,208 *         type: 'text',209 *         subtype: 'html' } ]210 *211 * @return {Array}212 * @api public213 */214215req.__defineGetter__('accepted', function(){216  var accept = this.get('Accept');217  return accept218    ? utils.parseAccept(accept)219    : [];220});221222/**223 * Return an array of Accepted languages224 * ordered from highest quality to lowest.225 *226 * Examples:227 *228 *     Accept-Language: en;q=.5, en-us229 *     ['en-us', 'en']230 *231 * @return {Array}232 * @api public233 */234235req.__defineGetter__('acceptedLanguages', function(){236  var accept = this.get('Accept-Language');237  return accept238    ? utils239      .parseParams(accept)240      .map(function(obj){241        return obj.value;242      })243    : [];244});245246/**247 * Return an array of Accepted charsets248 * ordered from highest quality to lowest.249 *250 * Examples:251 *252 *     Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8253 *     ['unicode-1-1', 'iso-8859-5']254 *255 * @return {Array}256 * @api public257 */258259req.__defineGetter__('acceptedCharsets', function(){260  var accept = this.get('Accept-Charset');261  return accept262    ? utils263      .parseParams(accept)264      .map(function(obj){265        return obj.value;266      })267    : [];268});269270/**271 * Return the value of param `name` when present or `defaultValue`.272 *273 *  - Checks route placeholders, ex: _/user/:id_274 *  - Checks body params, ex: id=12, {"id":12}275 *  - Checks query string params, ex: ?id=12276 *277 * To utilize request bodies, `req.body`278 * should be an object. This can be done by using279 * the `connect.bodyParser()` middleware.280 *281 * @param {String} name282 * @param {Mixed} [defaultValue]283 * @return {String}284 * @api public285 */286287req.param = function(name, defaultValue){288  var params = this.params || {};289  var body = this.body || {};290  var query = this.query || {};291  if (null != params[name] && params.hasOwnProperty(name)) return params[name];292  if (null != body[name]) return body[name];293  if (null != query[name]) return query[name];294  return defaultValue;295};296297/**298 * Check if the incoming request contains the "Content-Type"299 * header field, and it contains the give mime `type`.300 *301 * Examples:302 *303 *      // With Content-Type: text/html; charset=utf-8304 *      req.is('html');305 *      req.is('text/html');306 *      req.is('text/*');307 *      // => true308 *309 *      // When Content-Type is application/json310 *      req.is('json');311 *      req.is('application/json');312 *      req.is('application/*');313 *      // => true314 *315 *      req.is('html');316 *      // => false317 *318 * @param {String} type319 * @return {Boolean}320 * @api public321 */322323req.is = function(type){324  var ct = this.get('Content-Type');325  if (!ct) return false;326  ct = ct.split(';')[0];327  if (!~type.indexOf('/')) type = mime.lookup(type);328  if (~type.indexOf('*')) {329    type = type.split('/');330    ct = ct.split('/');331    if ('*' == type[0] && type[1] == ct[1]) return true;332    if ('*' == type[1] && type[0] == ct[0]) return true;333    return false;334  }335  return !! ~ct.indexOf(type);336};337338/**339 * Return the protocol string "http" or "https"340 * when requested with TLS. When the "trust proxy"341 * setting trusts the socket address, the342 * "X-Forwarded-Proto" header field will be trusted.343 * If you're running behind a reverse proxy that344 * supplies https for you this may be enabled.345 *346 * @return {String}347 * @api public348 */349350req.__defineGetter__('protocol', function(){351  var trust = this.app.get('trust proxy fn');352353  if (!trust(this.connection.remoteAddress)) {354    return this.connection.encrypted355      ? 'https'356      : 'http';357  }358359  // Note: X-Forwarded-Proto is normally only ever a360  //       single value, but this is to be safe.361  var proto = this.get('X-Forwarded-Proto') || 'http';362  return proto.split(/\s*,\s*/)[0];363});364365/**366 * Short-hand for:367 *368 *    req.protocol == 'https'369 *370 * @return {Boolean}371 * @api public372 */373374req.__defineGetter__('secure', function(){375  return 'https' == this.protocol;376});377378/**379 * Return the remote address from the trusted proxy.380 *381 * The is the remote address on the socket unless382 * "trust proxy" is set.383 *384 * @return {String}385 * @api public386 */387388req.__defineGetter__('ip', function(){389  var trust = this.app.get('trust proxy fn');390  return proxyaddr(this, trust);391});392393/**394 * When "trust proxy" is set, trusted proxy addresses + client.395 *396 * For example if the value were "client, proxy1, proxy2"397 * you would receive the array `["client", "proxy1", "proxy2"]`398 * where "proxy2" is the furthest down-stream and "proxy1" and399 * "proxy2" were trusted.400 *401 * @return {Array}402 * @api public403 */404405req.__defineGetter__('ips', function(){406  var trust = this.app.get('trust proxy fn');407  var addrs = proxyaddr.all(this, trust);408  return addrs.slice(1).reverse();409});410411/**412 * Return basic auth credentials.413 *414 * Examples:415 *416 *    // http://tobi:hello@example.com417 *    req.auth418 *    // => { username: 'tobi', password: 'hello' }419 *420 * @return {Object} or undefined421 * @api public422 */423424req.__defineGetter__('auth', function(){425  // missing426  var auth = this.get('Authorization');427  if (!auth) return;428429  // malformed430  var parts = auth.split(' ');431  if ('basic' != parts[0].toLowerCase()) return;432  if (!parts[1]) return;433  auth = parts[1];434435  // credentials436  auth = new Buffer(auth, 'base64').toString().match(/^([^:]*):(.*)$/);437  if (!auth) return;438  return { username: auth[1], password: auth[2] };439});440441/**442 * Return subdomains as an array.443 *444 * Subdomains are the dot-separated parts of the host before the main domain of445 * the app. By default, the domain of the app is assumed to be the last two446 * parts of the host. This can be changed by setting "subdomain offset".447 *448 * For example, if the domain is "tobi.ferrets.example.com":449 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.450 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.451 *452 * @return {Array}453 * @api public454 */455456req.__defineGetter__('subdomains', function(){457  var offset = this.app.get('subdomain offset');458  return (this.host || '')459    .split('.')460    .reverse()461    .slice(offset);462});463464/**465 * Short-hand for `url.parse(req.url).pathname`.466 *467 * @return {String}468 * @api public469 */470471req.__defineGetter__('path', function(){472  return parse(this).pathname;473});474475/**476 * Parse the "Host" header field hostname.477 *478 * When the "trust proxy" setting trusts the socket479 * address, the "X-Forwarded-Host" header field will480 * be trusted.481 *482 * @return {String}483 * @api public484 */485486req.__defineGetter__('host', function(){487  var trust = this.app.get('trust proxy fn');488  var host = this.get('X-Forwarded-Host');489490  if (!host || !trust(this.connection.remoteAddress)) {491    host = this.get('Host');492  }493494  if (!host) return;495496  // IPv6 literal support497  var offset = host[0] === '['498    ? host.indexOf(']') + 1499    : 0;500  var index = host.indexOf(':', offset);501502  return ~index503    ? host.substring(0, index)504    : host;505});506507/**508 * Check if the request is fresh, aka509 * Last-Modified and/or the ETag510 * still match.511 *512 * @return {Boolean}513 * @api public514 */515516req.__defineGetter__('fresh', function(){517  var method = this.method;518  var s = this.res.statusCode;519520  // GET or HEAD for weak freshness validation only521  if ('GET' != method && 'HEAD' != method) return false;522523  // 2xx or 304 as per rfc2616 14.26524  if ((s >= 200 && s < 300) || 304 == s) {525    return fresh(this.headers, this.res._headers);526  }527528  return false;529});530531/**532 * Check if the request is stale, aka533 * "Last-Modified" and / or the "ETag" for the534 * resource has changed.535 *536 * @return {Boolean}537 * @api public538 */539540req.__defineGetter__('stale', function(){541  return !this.fresh;542});543544/**545 * Check if the request was an _XMLHttpRequest_.546 *547 * @return {Boolean}548 * @api public549 */550551req.__defineGetter__('xhr', function(){552  var val = this.get('X-Requested-With') || '';553  return 'xmlhttprequest' == val.toLowerCase();554});