Update ParseForwarded to use strrchr

This commit is contained in:
Paul Kulchenko 2022-03-09 22:54:08 -08:00
parent 8cb44277b0
commit 4c75fa363d
3 changed files with 13 additions and 11 deletions

View file

@ -38,17 +38,14 @@
int ParseForwarded(const char *s, size_t n, uint32_t *ip, uint16_t *port) { int ParseForwarded(const char *s, size_t n, uint32_t *ip, uint16_t *port) {
int c, t; int c, t;
size_t i; size_t i;
char *r;
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 = 0; t = x = i = 0;
i = n; if ((r = strrchr(s, ','))) {
while (i > 0) { i = r - s;
if (s[--i] & 255 == ',') { if ((s[++i] & 255) == ' ') ++i; // skip optional space
// 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;

View file

@ -574,7 +574,8 @@ FUNCTIONS
Returns client ip4 address and port, e.g. 0x01020304,31337 would Returns client ip4 address and port, e.g. 0x01020304,31337 would
represent 1.2.3.4:31337. This is the same as GetClientAddr except represent 1.2.3.4:31337. This is the same as GetClientAddr except
it will use the ip:port from the X-Forwarded-For header, only if it will use the ip:port from the X-Forwarded-For header, only if
IsPrivateIp or IsLoopbackIp return true. IsPrivateIp or IsLoopbackIp return true. When multiple addresses
are present in the header, the last/right-most address is used.
GetClientAddr() → ip:uint32,port:uint16 GetClientAddr() → ip:uint32,port:uint16
Returns client socket ip4 address and port, e.g. 0x01020304,31337 Returns client socket ip4 address and port, e.g. 0x01020304,31337

View file

@ -818,8 +818,12 @@ static inline void GetRemoteAddr(uint32_t *ip, uint16_t *port) {
GetClientAddr(ip, port); GetClientAddr(ip, port);
if (HasHeader(kHttpXForwardedFor) && if (HasHeader(kHttpXForwardedFor) &&
(IsPrivateIp(*ip) || IsLoopbackIp(*ip))) { (IsPrivateIp(*ip) || IsLoopbackIp(*ip))) {
ParseForwarded(HeaderData(kHttpXForwardedFor), if (ParseForwarded(HeaderData(kHttpXForwardedFor),
HeaderLength(kHttpXForwardedFor), ip, port); HeaderLength(kHttpXForwardedFor),
ip, port) == -1)
WARNF("invalid X-Forwarded-For value: %`'.*s",
HeaderLength(kHttpXForwardedFor),
HeaderData(kHttpXForwardedFor));
} }
} }