3 * brisk - Obj/ipclass.phh
5 * Copyright (C) 2015 Matteo Nastasi
6 * mailto: nastasi@alternativeoutput.it
7 * matteo.nastasi@milug.org
8 * web: http://www.alternativeoutput.it
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABLILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * General Public License for more details. You should have received a
19 * copy of the GNU General Public License along with this program; if
20 * not, write to the Free Software Foundation, Inc, 59 Temple Place -
21 * Suite 330, Boston, MA 02111-1307, USA.
29 function IPClassItem($ipset)
32 $elem = split("/", $ipset, 2);
34 if (!isset($elem[1])) {
35 fprintf(STDERR, "ORIG: %s\n", $ipset);
37 $mask = (int)$elem[1];
41 $this->mask = ((1<<($mask))-1) << (32 - $mask);
42 $this->addr = ip2long($addr) & $this->mask;
44 fprintf(STDERR, "New ipclass item: %x (%x)\n", $this->addr, $this->mask);
49 // fprintf(STDERR, "IP: %x, ADDR: %x, MASK: %x -> (%d)\n",
50 // $ip, $this->addr, $this->mask, ((ip2long($ip) & $this->mask) == $this->addr));
51 return (($ip & $this->mask) == $this->addr);
54 static function compare($a, $b)
56 if ($a->addr == $b->addr)
58 return (($a->addr < $b->addr) ? -1 : 1);
70 static function create($ip_in=NULL)
72 $thiz = new IPClass();
75 $thiz->update($ip_in);
81 function update($ip_in)
85 $this->ipcl = array();
86 for ($i = 0 ; $i < count($ip_in) ; $i++) {
87 $this->ipcl[$i] = new IPClassItem($ip_in[$i]);
89 usort($this->ipcl, array("IPClassItem", "compare"));
94 if ($this->ipcl != NULL) {
95 $ct = count($this->ipcl);
96 for ($i = 0 ; $i < $ct ; $i++) {
97 unset($this->ipcl[$i]);
103 function check($ip_str)
105 $ip = ip2long($ip_str);
107 if (count($this->ipcl) == 0) {
111 if ($ip < $this->ipcl[0]->addr)
115 $imax = count($this->ipcl) - 1;
117 while ($imax >= $imin) {
118 $imid = intval($imin + (($imax - $imin) / 2));
119 // printf("X: %d M: %d N: %d | ", $arr[$imin], $arr[$imid], $arr[$imax]);
120 if ($this->ipcl[$imid]->addr == $ip) {
123 else if ($this->ipcl[$imid]->addr > $ip) {
130 if ($this->ipcl[$imid]->addr > $ip) {
140 if ($this->ipcl[$imid]->match($ip)) {
141 fprintf(STDERR, "ban_list[%d] = %x (%x) MATCH\n", $imid,
142 $this->ipcl[$imid]->addr, $this->ipcl[$imid]->mask);