Passed
Push — master ( bfb764...c00e59 )
by Christoph
15:35 queued 13s
created

IpAddressClassifier   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
dl 0
loc 41
rs 10
c 1
b 0
f 0
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A isLocalAddress() 0 26 5
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * @copyright 2022 Christoph Wurst <[email protected]>
7
 *
8
 * @author 2022 Christoph Wurst <[email protected]>
9
 *
10
 * @license GNU AGPL version 3 or any later version
11
 *
12
 * This program is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License as
14
 * published by the Free Software Foundation, either version 3 of the
15
 * License, or (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU Affero General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License
23
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24
 */
25
26
namespace OC\Net;
27
28
use IPLib\Address\IPv6;
29
use IPLib\Factory;
30
use IPLib\ParseStringFlag;
31
use Symfony\Component\HttpFoundation\IpUtils;
32
use function filter_var;
33
34
/**
35
 * Classifier for IP addresses
36
 *
37
 * @internal
38
 */
39
class IpAddressClassifier {
40
	private const LOCAL_ADDRESS_RANGES = [
41
		'100.64.0.0/10', // See RFC 6598
42
		'192.0.0.0/24', // See RFC 6890
43
	];
44
45
	/**
46
	 * Check host identifier for local IPv4 and IPv6 address ranges
47
	 *
48
	 * Hostnames are not considered local. Use the HostnameClassifier for those.
49
	 *
50
	 * @param string $ip
51
	 *
52
	 * @return bool
53
	 */
54
	public function isLocalAddress(string $ip): bool {
55
		$parsedIp = Factory::parseAddressString(
56
			$ip,
57
			ParseStringFlag::IPV4_MAYBE_NON_DECIMAL | ParseStringFlag::IPV4ADDRESS_MAYBE_NON_QUAD_DOTTED
58
		);
59
		if ($parsedIp === null) {
60
			/* Not an IP */
61
			return false;
62
		}
63
		/* Replace by normalized form */
64
		if ($parsedIp instanceof IPv6) {
65
			$ip = (string)($parsedIp->toIPv4() ?? $parsedIp);
66
		} else {
67
			$ip = (string)$parsedIp;
68
		}
69
70
		if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
71
			/* Range address */
72
			return true;
73
		}
74
		if (IpUtils::checkIp($ip, self::LOCAL_ADDRESS_RANGES)) {
75
			/* Within local range */
76
			return true;
77
		}
78
79
		return false;
80
	}
81
}
82