Update ParseForwarded to use right-most IP from X-Forwarded-For

This commit is contained in:
Paul Kulchenko 2022-03-09 21:14:48 -08:00
parent abac6f729c
commit 8cb44277b0
2 changed files with 12 additions and 3 deletions

View file

@ -77,6 +77,7 @@ const bool kHttpRepeatable[kHttpHeadersMax] = {
[kHttpVia] = true, [kHttpVia] = true,
[kHttpWarning] = true, [kHttpWarning] = true,
[kHttpWwwAuthenticate] = true, [kHttpWwwAuthenticate] = true,
[kHttpXForwardedFor] = true,
[kHttpAccessControlAllowHeaders] = true, [kHttpAccessControlAllowHeaders] = true,
[kHttpAccessControlAllowMethods] = true, [kHttpAccessControlAllowMethods] = true,
[kHttpAccessControlRequestHeaders] = true, [kHttpAccessControlRequestHeaders] = true,

View file

@ -24,13 +24,13 @@
* *
* This header is used by reverse proxies. For example: * This header is used by reverse proxies. For example:
* *
* X-Forwarded-For: 203.0.113.42:31337 * X-Forwarded-For: 203.0.110.2, 203.0.113.42:31337
* *
* The port is optional and will be set to zero if absent. * The port is optional and will be set to zero if absent.
* *
* @param s is input data * @param s is input data
* @param n if -1 implies strlen * @param n if -1 implies strlen
* @param ip receives ip on success if not NULL * @param ip receives last/right ip on success if not NULL
* @param port receives port on success if not NULL * @param port receives port on success if not NULL
* @return 0 on success or -1 on failure * @return 0 on success or -1 on failure
* @see RFC7239's poorly designed Forwarded header * @see RFC7239's poorly designed Forwarded header
@ -41,7 +41,15 @@ int ParseForwarded(const char *s, size_t n, uint32_t *ip, uint16_t *port) {
uint32_t x; uint32_t x;
if (n == -1) n = s ? strlen(s) : 0; if (n == -1) n = s ? strlen(s) : 0;
if (n) { if (n) {
t = x = i = 0; t = x = 0;
i = n;
while (i > 0) {
if (s[--i] & 255 == ',') {
// skip optional space
if (s[++i] & 255 == ' ') ++i;
break; // i points to the start of the address
}
}
do { do {
c = s[i++] & 255; c = s[i++] & 255;
if (isdigit(c)) { if (isdigit(c)) {