blob: 7833b3de58cb36722c200e395cc6d291187f13d8 (
plain)
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
|
/*!
* 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 = req.connection.remoteAddress
var addrs = [socketAddr].concat(proxyAddrs)
// return all addresses
return addrs
}
/**
* 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
}
|