Skip to content

Commit 2124e16

Browse files
committed
[api] correctly process ip addresses with ports, and handle ipv6 addresses in square brackets. Also support for partial ip addresses as masks for ignoring proxy
1 parent 6b5c744 commit 2124e16

File tree

1 file changed

+40
-3
lines changed

1 file changed

+40
-3
lines changed

api/utils/common.js

+40-3
Original file line numberDiff line numberDiff line change
@@ -1134,20 +1134,57 @@ common.getIpAddress = function(req) {
11341134
//if ignoreProxies not setup, use outmost left ip address
11351135
if (!countlyConfig.ignoreProxies || !countlyConfig.ignoreProxies.length) {
11361136
ipLogger.d("From %s found ip %s", ipAddress, ips[0]);
1137-
return ips[0];
1137+
return stripPort(ips[0]);
11381138
}
11391139
//search for the outmost right ip address ignoring provided proxies
11401140
var ip = "";
11411141
for (var i = ips.length - 1; i >= 0; i--) {
1142-
if (ips[i].trim() !== "127.0.0.1" && (!countlyConfig.ignoreProxies || countlyConfig.ignoreProxies.indexOf(ips[i].trim()) === -1)) {
1143-
ip = ips[i].trim();
1142+
ips[i] = stripPort(ips[i]);
1143+
var masks = false;
1144+
if (countlyConfig.ignoreProxies && countlyConfig.ignoreProxies.length) {
1145+
masks = countlyConfig.ignoreProxies.some(function(elem) {
1146+
return ips[i].startsWith(elem);
1147+
});
1148+
}
1149+
if (ips[i] !== "127.0.0.1" && (!countlyConfig.ignoreProxies || !masks)) {
1150+
ip = ips[i];
11441151
break;
11451152
}
11461153
}
11471154
ipLogger.d("From %s found ip %s", ipAddress, ip);
11481155
return ip;
11491156
};
11501157

1158+
/**
1159+
* This function takes ipv4 or ipv6 with possible port, removes port information and returns plain ip address
1160+
* @param {string} ip - ip address to check for port and return plain ip
1161+
* @returns returns plain ip address
1162+
*/
1163+
function stripPort(ip) {
1164+
var parts = (ip + "").split(".");
1165+
//check if ipv4
1166+
if (parts.length === 4) {
1167+
return ip.split(":")[0].trim();
1168+
}
1169+
else {
1170+
parts = (ip + "").split(":");
1171+
if (parts.length === 9) {
1172+
parts.pop();
1173+
}
1174+
if (parts.length === 8) {
1175+
ip = parts.join(":");
1176+
//remove enclosing [] for ipv6 if they are there
1177+
if (ip[0] === "[") {
1178+
ip = ip.substring(1);
1179+
}
1180+
if (ip[ip.length - 1] === "]") {
1181+
ip = ip.slice(0, -1);
1182+
}
1183+
}
1184+
}
1185+
return (ip + "").trim();
1186+
}
1187+
11511188
/**
11521189
* Modifies provided object filling properties used in zero documents in the format object["2012.7.20.property"] = increment.
11531190
* Usualy used when filling up Countly metric model zero document

0 commit comments

Comments
 (0)