Spaces:
Sleeping
Sleeping
File size: 1,578 Bytes
f9f0fec |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
/*!
* forwarded
* Copyright(c) 2014-2017 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module exports.
* @public
*/
module.exports = forwarded
/**
* Get all addresses in the request, using the `X-Forwarded-For` header.
*
* @param {object} req
* @return {array}
* @public
*/
function forwarded (req) {
if (!req) {
throw new TypeError('argument req is required')
}
// simple header parsing
var proxyAddrs = parse(req.headers['x-forwarded-for'] || '')
var socketAddr = getSocketAddr(req)
var addrs = [socketAddr].concat(proxyAddrs)
// return all addresses
return addrs
}
/**
* Get the socket address for a request.
*
* @param {object} req
* @return {string}
* @private
*/
function getSocketAddr (req) {
return req.socket
? req.socket.remoteAddress
: req.connection.remoteAddress
}
/**
* Parse the X-Forwarded-For header.
*
* @param {string} header
* @private
*/
function parse (header) {
var end = header.length
var list = []
var start = header.length
// gather addresses, backwards
for (var i = header.length - 1; i >= 0; i--) {
switch (header.charCodeAt(i)) {
case 0x20: /* */
if (start === end) {
start = end = i
}
break
case 0x2c: /* , */
if (start !== end) {
list.push(header.substring(start, end))
}
start = end = i
break
default:
start = i
break
}
}
// final address
if (start !== end) {
list.push(header.substring(start, end))
}
return list
}
|