option to extract client's IP from HTTP header (ie X-Real-IP)

This commit is contained in:
Doug Hoyte
2023-02-08 16:08:03 -05:00
parent 4eb7a4fe53
commit 51243ce62f
6 changed files with 26 additions and 2 deletions

View File

@ -94,7 +94,15 @@ void RelayServer::runWebsocket(ThreadPool<MsgWebsocket>::Thread &thr) {
uint64_t connId = nextConnectionId++;
Connection *c = new Connection(ws, connId);
c->ipAddr = ws->getAddressBytes();
if (cfg().relay__realIpHeader.size()) {
auto header = req.getHeader(cfg().relay__realIpHeader.c_str()).toString();
c->ipAddr = parseIP(header);
if (c->ipAddr.size() == 0) LW << "Couldn't parse IP from header " << cfg().relay__realIpHeader << ": " << header;
}
if (c->ipAddr.size() == 0) c->ipAddr = ws->getAddressBytes();
ws->setUserData((void*)c);
connIdToConnection.emplace(connId, c);

View File

@ -19,3 +19,4 @@ std::string renderIP(std::string_view ipBytes);
std::string renderSize(uint64_t si);
std::string renderPercent(double p);
uint64_t parseUint64(const std::string &s);
std::string parseIP(const std::string &ip);

View File

@ -21,6 +21,16 @@ std::string renderIP(std::string_view ipBytes) {
return std::string(buf);
}
std::string parseIP(const std::string &ip) {
int af = ip.find(':') != std::string::npos ? AF_INET6 : AF_INET;
unsigned char buf[16];
int ret = inet_pton(af, ip.c_str(), &buf[0]);
if (ret == 0) return "";
return std::string((const char*)&buf[0], af == AF_INET6 ? 16 : 4);
}
std::string renderSize(uint64_t si) {
if (si < 1024) return std::to_string(si) + "b";