1<?php
2/*
3** Zabbix
4** Copyright (C) 2001-2021 Zabbix SIA
5**
6** This program is free software; you can redistribute it and/or modify
7** it under the terms of the GNU General Public License as published by
8** the Free Software Foundation; either version 2 of the License, or
9** (at your option) any later version.
10**
11** This program is distributed in the hope that it will be useful,
12** but WITHOUT ANY WARRANTY; without even the implied warranty of
13** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14** GNU General Public License for more details.
15**
16** You should have received a copy of the GNU General Public License
17** along with this program; if not, write to the Free Software
18** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19**/
20
21
22/**
23 * Class containing methods for IP address validation.
24 */
25class CIPValidator extends CValidator {
26
27	/**
28	 * Checks if the given IP address is a valid IPv4 or IPv6 address. If IP address is invalid, sets an error
29	 * and returns false. Otherwise returns true.
30	 *
31	 * @param string $ip
32	 *
33	 * @return bool
34	 */
35	public function validate($ip) {
36		if (!is_string($ip)) {
37			$this->setError(_s('Invalid IP address "%1$s": must be a string.', $this->stringify($ip)));
38
39			return false;
40		}
41
42		if ($ip === '') {
43			$this->setError(_('IP address cannot be empty.'));
44
45			return false;
46		}
47
48		if (!$this->isValidIPv4($ip) && !$this->isValidIPv6($ip)) {
49			$this->setError(_s('Invalid IP address "%1$s".', $ip));
50
51			return false;
52		}
53
54		return true;
55	}
56
57	/**
58	 * Validate IPv4 address.
59	 *
60	 * @param string $ip
61	 *
62	 * @return bool
63	 */
64	protected function isValidIPv4($ip) {
65		if (!preg_match('/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/', $ip, $matches)) {
66			return false;
67		}
68
69		for ($i = 1; $i <= 4; $i++) {
70			if ($matches[$i] > 255) {
71				return false;
72			}
73		}
74
75		return true;
76	}
77
78	/**
79	 * Validate IPv6 address.
80	 *
81	 * @param string $ip
82	 *
83	 * @return bool
84	 */
85	protected function isValidIPv6($ip) {
86		if (!ZBX_HAVE_IPV6) {
87			return false;
88		}
89
90		$patterns = [
91			'([a-f0-9]{1,4}:){7}[a-f0-9]{1,4}',
92			':(:[a-f0-9]{1,4}){1,7}',
93			'[a-f0-9]{1,4}::([a-f0-9]{1,4}:){0,5}[a-f0-9]{1,4}',
94			'([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}[a-f0-9]{1,4}',
95			'([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}[a-f0-9]{1,4}',
96			'([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}[a-f0-9]{1,4}',
97			'([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1}[a-f0-9]{1,4}',
98			'([a-f0-9]{1,4}:){6}:[a-f0-9]{1,4}',
99			'([a-f0-9]{1,4}:){1,7}:',
100			'::'
101		];
102
103		$pattern = '/^('.implode(')$|^(', $patterns).')$/i';
104
105		if (!preg_match($pattern, $ip)) {
106			return false;
107		}
108
109		return true;
110	}
111}
112