getKey('limit', 'traffic')); self::setExemptedIp($conf->getKey('exemptedIp', 'traffic')); if (($option = $conf->getKey('header', 'traffic')) !== null) { $httpHeader = 'HTTP_' . $option; if (array_key_exists($httpHeader, $_SERVER) && !empty($_SERVER[$httpHeader])) { self::$_ipKey = $httpHeader; } } } /** * get a HMAC of the current visitors IP address * * @access public * @static * @param string $algo * @return string */ public static function getHash($algo = 'sha512') { return hash_hmac($algo, $_SERVER[self::$_ipKey], ServerSalt::get()); } /** * Validate $_ipKey against configured ipranges. If matched we will ignore the ip * * @access private * @static * @param string $ipRange * @return bool */ private static function matchIp($ipRange = null) { if (is_string($ipRange)) { $ipRange = trim($ipRange); } $address = Factory::addressFromString($_SERVER[self::$_ipKey]); $range = Factory::rangeFromString($ipRange); // address could not be parsed, we might not be in IP space and try a string comparison instead if (is_null($address)) { return $_SERVER[self::$_ipKey] === $ipRange; } // range could not be parsed, possibly an invalid ip range given in config if (is_null($range)) { return false; } return $address->matches($range); } /** * traffic limiter * * Make sure the IP address makes at most 1 request every 10 seconds. * * @access public * @static * @return bool */ public static function canPass() { // disable limits if set to less then 1 if (self::$_limit < 1) { return true; } // Check if $_ipKey is exempted from ratelimiting if (!is_null(self::$_exemptedIp)) { $exIp_array = explode(',', self::$_exemptedIp); foreach ($exIp_array as $ipRange) { if (self::matchIp($ipRange) === true) { return true; } } } // this hash is used as an array key, hence a shorter algo is used $hash = self::getHash('sha256'); $now = time(); $tl = (int) self::$_store->getValue('traffic_limiter', $hash); self::$_store->purgeValues('traffic_limiter', $now - self::$_limit); if ($tl > 0 && ($tl + self::$_limit >= $now)) { $result = false; } else { $tl = time(); $result = true; } if (!self::$_store->setValue((string) $tl, 'traffic_limiter', $hash)) { error_log('failed to store the traffic limiter, it probably contains outdated information'); } return $result; } }