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

The walk stopped after 200 commits: lines older than 2fe46b3 point at it.

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 1–10why, one step back
1
2/**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')

update connect to 2.16.1Douglas Christopher Wilsonbefore adoption65f13c3

line 11why, one step back
11 , parse = require('parseurl')

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 12why, one step back
12 , proxyaddr = require('proxy-addr')

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 13–66why, one step back
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",

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption752b5f7

line 67why, one step back
67 * an argument list such as `"json", "html", "text/plain"`,

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 68–93why, one step back
68 * or an array `["json", "html", "text/plain"]`. When a list
69 * 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']);

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption752b5f7

line 94why, one step back
94 * req.accepts('html', 'json');

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 95–103why, one step back
95 * req.accepts('html, json');
96 * // => "json"97 *98 * @param {String|Array} type(s)99 * @return {String}100 * @api public101 */102103req.accepts = function(type){

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption752b5f7

lines 104–105why, one step back
104 var args = arguments.length > 1 ? [].slice.apply(arguments) : type;
105 return utils.accepts(args, this.get('Accept'));

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 106–116why, one step back
106};
107108/**109 * Check if the given `encoding` is accepted.110 *111 * @param {String} encoding112 * @return {Boolean}113 * @api public114 */115116req.acceptsEncoding = function(encoding){

return actual booleans from req.accept* functionsTJ Holowaychukbefore adoption19d685b

line 117why, one step back
117 return !! ~this.acceptedEncodings.indexOf(encoding);

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 118–131why, one step back
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.length

return actual booleans from req.accept* functionsTJ Holowaychukbefore adoption19d685b

line 132why, one step back
132 ? !! ~accepted.indexOf(charset)

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 133–147why, one step back
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.length

return actual booleans from req.accept* functionsTJ Holowaychukbefore adoption19d685b

line 148why, one step back
148 ? !! ~accepted.indexOf(lang)

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 149–340why, one step back
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"

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 341–344why, one step back
341 * setting trusts the socket address, the
342 * "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.

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 345–350why, one step back
345 *
346 * @return {String}347 * @api public348 */349350req.__defineGetter__('protocol', function(){

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 351–360why, one step back
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.

add support for multiple X-Forwarded-Proto values. Closes #1646TJ Holowaychukbefore adoption8ab4408

lines 361–362why, one step back
361 var proto = this.get('X-Forwarded-Proto') || 'http';
362 return proto.split(/\s*,\s*/)[0];

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 363–378why, one step back
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/**

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 379why, one step back
379 * Return the remote address from the trusted proxy.

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

line 380why, one step back
380 *

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 381–383why, one step back
381 * The is the remote address on the socket unless
382 * "trust proxy" is set.383 *

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 384–388why, one step back
384 * @return {String}
385 * @api public386 */387388req.__defineGetter__('ip', function(){

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 389–390why, one step back
389 var trust = this.app.get('trust proxy fn');
390 return proxyaddr(this, trust);

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 391–393why, one step back
391});
392393/**

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 394why, one step back
394 * When "trust proxy" is set, trusted proxy addresses + client.

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 395–397why, one step back
395 *
396 * For example if the value were "client, proxy1, proxy2"397 * you would receive the array `["client", "proxy1", "proxy2"]`

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 398–399why, one step back
398 * where "proxy2" is the furthest down-stream and "proxy1" and
399 * "proxy2" were trusted.

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 400–405why, one step back
400 *
401 * @return {Array}402 * @api public403 */404405req.__defineGetter__('ips', function(){

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 406–408why, one step back
406 var trust = this.app.get('trust proxy fn');
407 var addrs = proxyaddr.all(this, trust);408 return addrs.slice(1).reverse();

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 409–477why, one step back
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 *

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 478–481why, one step back
478 * When the "trust proxy" setting trusts the socket
479 * address, the "X-Forwarded-Host" header field will480 * be trusted.481 *

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 482–486why, one step back
482 * @return {String}
483 * @api public484 */485486req.__defineGetter__('host', function(){

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 487–493why, one step back
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 }493

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

line 494why, one step back
494 if (!host) return;

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 495–496why, one step back
495
496 // IPv6 literal support

Merge branch '3.5.x' into 3.xDouglas Christopher Wilsonbefore adoption66b38b5

lines 497–500why, one step back
497 var offset = host[0] === '['
498 ? host.indexOf(']') + 1499 : 0;500 var index = host.indexOf(':', offset);

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 501why, one step back
501

Merge branch '3.5.x' into 3.xDouglas Christopher Wilsonbefore adoption66b38b5

lines 502–504why, one step back
502 return ~index
503 ? host.substring(0, index)504 : host;

Release 3.2.5TJ Holowaychukbefore adoption2fe46b3

lines 505–554why, one step back
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});