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

HostnameClassifier::isLocalHostname()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 6
nc 3
nop 1
dl 0
loc 13
rs 9.6111
c 1
b 0
f 0
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 function filter_var;
29
use function in_array;
30
use function strrchr;
31
use function substr;
32
use function substr_count;
33
34
/**
35
 * Classifier for network hostnames
36
 *
37
 * @internal
38
 */
39
class HostnameClassifier {
40
	private const LOCAL_TOPLEVEL_DOMAINS = [
41
		'local',
42
		'localhost',
43
		'intranet',
44
		'internal',
45
		'private',
46
		'corp',
47
		'home',
48
		'lan',
49
	];
50
51
	/**
52
	 * Check host identifier for local hostname
53
	 *
54
	 * IP addresses are not considered local. Use the IpAddressClassifier for those.
55
	 *
56
	 * @param string $hostname
57
	 *
58
	 * @return bool
59
	 */
60
	public function isLocalHostname(string $hostname): bool {
61
		// Disallow local network top-level domains from RFC 6762
62
		$topLevelDomain = substr((strrchr($hostname, '.') ?: ''), 1);
63
		if (in_array($topLevelDomain, self::LOCAL_TOPLEVEL_DOMAINS)) {
64
			return true;
65
		}
66
67
		// Disallow hostname only
68
		if (substr_count($hostname, '.') === 0 && !filter_var($hostname, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
69
			return true;
70
		}
71
72
		return false;
73
	}
74
}
75