Put the ip-matching function in a private function

This commit is contained in:
Rodehoed 2021-05-06 12:13:03 +02:00
parent 63d6816c7c
commit 89bdc92451

View file

@ -107,6 +107,39 @@ class TrafficLimiter extends AbstractPersistence
return hash_hmac($algo, $_SERVER[self::$_ipKey], ServerSalt::get()); return hash_hmac($algo, $_SERVER[self::$_ipKey], ServerSalt::get());
} }
/**
* Validate $_ipKey against configured ipranges. If matched ratelimiter will ignore ip
*
* @access private
* @static
* @param string $algo
* @return string
*/
private static function matchIp($ipRange = null)
{
// Match $_ipKey to $ipRange and if it matches it will return with a true
$address = \IPLib\Factory::addressFromString($_SERVER[self::$_ipKey]);
$range = \IPLib\Factory::rangeFromString(trim($ipRange));
// If $range is null something went wrong (possible invalid ip given in config)
if ($range == null) {
return false;
} else {
// Ip-lib does throws and exception when something goes wrong, if so we want to catch it and set contained to false
try {
$contained = $address->matches($range);
} catch (\Exception $e) {
// If something is wrong with matching the ip, we set $contained to false
return false;
}
}
// Matches return true!
if ($contained === true) {
return true;
} else {
return false;
}
}
/** /**
* traffic limiter * traffic limiter
* *
@ -123,28 +156,13 @@ class TrafficLimiter extends AbstractPersistence
if (self::$_limit < 1) { if (self::$_limit < 1) {
return true; return true;
} }
error_reporting(-1);
// Check if $_ipKey is exempted from ratelimiting // Check if $_ipKey is exempted from ratelimiting
if (!is_null(self::$_exemptedIp)) { if (!is_null(self::$_exemptedIp)) {
$exIp_array = explode(',', self::$_exemptedIp); $exIp_array = explode(',', self::$_exemptedIp);
foreach ($exIp_array as $ipRange) { foreach ($exIp_array as $ipRange) {
// Match $_ipKey to $ipRange and if it matches it will return with a true if (self::matchIp($ipRange) === true)
$address = \IPLib\Factory::addressFromString($_SERVER[self::$_ipKey]); {
$range = \IPLib\Factory::rangeFromString(trim($ipRange));
// If $range is null something went wrong (possible invalid ip given in config)
if ($range == null) {
$contained = false;
} else {
// Ip-lib does throws and exception when something goes wrong, if so we want to catch it and set contained to false
try {
$contained = $address->matches($range);
} catch (\Exception $e) {
// If something is wrong with matching the ip, we set $contained to false
$contained = false;
}
}
// Matches return true!
if ($contained == true) {
return true; return true;
} }
} }