Test Failed
Push — master ( 15baa9...dd81ec )
by Andrew
07:08
created

Util::get_single_subnet()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 10
nc 4
nop 2
1
<?php
2
3
namespace AndrewAndante\SubMuncher;
4
5
// The bulk of the following code is from /etc/inc/util.inc in pfSense v2.0.2
6
// See https://www.pfsense.org - seriously good open source router software
7
8
class Util
9
{
10
    /**
11
     * This class should not be instantiated.
12
     */
13
    private function __construct()
14
    {
15
    }
16
17
    /* Convert IP address to long int, truncated to 32-bits to avoid sign extension
18
    on 64-bit platforms. */
19
    public static function ip2long32($ip)
20
    {
21
        return (ip2long($ip) & 0xFFFFFFFF);
22
    }
23
24
    /* Convert IP address to unsigned long int. */
25
    public static function ip2ulong($ip)
26
    {
27
        return sprintf("%u", self::ip2long32($ip));
28
    }
29
30
    /* Convert long int to IP address, truncating to 32-bits. */
31
    public static function long2ip32($ip)
32
    {
33
        return long2ip($ip & 0xFFFFFFFF);
34
    }
35
36
    /* returns true if $ipaddr is a valid dotted IPv4 address */
37
    public static function is_ipaddr($ipaddr)
38
    {
39
        if (!is_string($ipaddr)) {
40
            return false;
41
        }
42
43
        $ip_long = ip2long($ipaddr);
44
        $ip_reverse = self::long2ip32($ip_long);
45
46
        return ($ipaddr == $ip_reverse);
47
    }
48
49
    /* Return true if the first IP is 'before' the second */
50
    public static function ip_less_than($ip1, $ip2)
51
    {
52
        // Compare as unsigned long because otherwise it wouldn't work when
53
        // crossing over from 127.255.255.255 / 128.0.0.0 barrier
54
        return self::ip2ulong($ip1) < self::ip2ulong($ip2);
55
    }
56
57
    /* Return true if the first IP is 'after' the second */
58
    public static function ip_greater_than($ip1, $ip2)
59
    {
60
        // Compare as unsigned long because otherwise it wouldn't work
61
        // when crossing over from 127.255.255.255 / 128.0.0.0 barrier
62
        return self::ip2ulong($ip1) > self::ip2ulong($ip2);
63
    }
64
65
    /* Return the next IP address after the given address */
66
    public static function ip_after($ip, $increment = 1)
67
    {
68
        return self::long2ip32(ip2long($ip) + $increment);
69
    }
70
71
    /* Return the next IP address after the given address */
72
    public static function ip_before($ip, $decrement = 1)
73
    {
74
        return self::long2ip32(ip2long($ip) - $decrement);
75
    }
76
77
    /* Find the smallest possible subnet mask which can contain a given number of IPs
78
    *  e.g. 512 IPs can fit in a /23, but 513 IPs need a /22
79
    */
80
    public static function find_smallest_cidr($number)
81
    {
82
        $smallest = 1;
83
        for ($b = 32; $b > 0; $b--) {
84
            $smallest = ($number <= pow(2, $b)) ? $b : $smallest;
85
        }
86
        return (32 - $smallest);
87
    }
88
89
    /* Find out how many IPs are contained within a given IP range
90
    *  e.g. 192.168.0.0 to 192.168.0.255 returns 256
91
    */
92
    public static function ip_range_size($startip, $endip)
93
    {
94
        if (self::is_ipaddr($startip) && self::is_ipaddr($endip)) {
95
            // Operate as unsigned long because otherwise it wouldn't work
96
            // when crossing over from 127.255.255.255 / 128.0.0.0 barrier
97
            return abs(self::ip2ulong($startip) - self::ip2ulong($endip)) + 1;
98
        }
99
        return -1;
100
    }
101
102
103
    public static function get_single_subnet($startip, $endip)
104
    {
105
        if (!self::is_ipaddr($startip) || !self::is_ipaddr($endip)) {
106
            return [];
107
        }
108
109
        $cidr = self::find_smallest_cidr(self::ip_range_size($startip, $endip));
110
        $lowestCommonIP = self::find_smallest_common_IP($startip, $endip);
111
112
        while (!self::ip_less_than($endip, self::gen_subnet_max($lowestCommonIP, $cidr))) {
113
            $cidr--;
114
            if ($cidr == 0) {
115
                return [];
116
            }
117
        }
118
        return $lowestCommonIP . '/' . $cidr;
119
    }
120
121
    public static function find_smallest_common_IP($startip, $endip)
122
    {
123
        $startBits = explode('.', $startip);
124
        $endBits = explode('.', $endip);
125
126
        $returnIP = [];
127
        $broken = false;
128
        for ($i = 0; $i < 4; ++$i) {
129
            if ($broken) {
130
                $returnIP[$i] = "00000000";
131
                continue;
132
            }
133
            $startAsBinary = str_pad(decbin($startBits[$i]), 8, "0", STR_PAD_LEFT);
134
            $endAsBinary = str_pad(decbin($endBits[$i]), 8, "0", STR_PAD_LEFT);
135
136
            if ($startAsBinary === $endAsBinary) {
137
                $returnIP[$i] = $startAsBinary;
138
                continue;
139
            }
140
141
            $returnOctet = [];
142
            for ($j = 0; $j < 8; ++$j) {
143
                if (!$broken && $startAsBinary[$j] == $endAsBinary[$j]) {
144
                    $returnOctet[$j] = $startAsBinary[$j];
145
                    continue;
146
                } else {
147
                    $returnOctet[$j] = "0";
148
                    $broken = true;
149
                }
150
            }
151
152
            $returnIP[$i] = implode('', $returnOctet);
153
        }
154
        $returnIPDec = [];
155
        foreach ($returnIP as $returnIPBin) {
156
            $returnIPDec[] = bindec($returnIPBin);
157
        }
158
        return implode('.', $returnIPDec);
159
    }
160
161
    public static function subnet_range_size($subnetmask)
162
    {
163
        return (2 ** (32 - (int) $subnetmask));
164
    }
165
166
    public static function cidr_to_ips_array($cidr)
167
    {
168
        $parts = explode('/', $cidr);
169
        if (!self::is_ipaddr($parts[0])) {
170
            return false;
171
        }
172
173
        $subnetMask = isset($parts[1]) ? $parts[1] : "32";
174
        $ips = [];
175
        $currentIP = $parts[0];
176
177
        for ($i = 0; $i < self::subnet_range_size($subnetMask); ++$i) {
178
            $ips[] = $currentIP;
179
            $currentIP = self::ip_after($currentIP);
180
        }
181
182
        return $ips;
183
    }
184
185
    /* return the subnet address given a host address and a subnet bit count */
186 View Code Duplication
    public static function gen_subnet($ipaddr, $bits)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
187
    {
188
        if (!self::is_ipaddr($ipaddr) || !is_numeric($bits)) {
189
            return "";
190
        }
191
192
        return long2ip(ip2long($ipaddr) & self::gen_subnet_mask_long($bits));
193
    }
194
195
    /* returns a subnet mask (long given a bit count) */
196
    public static function gen_subnet_mask_long($bits)
197
    {
198
        $sm = 0;
199
        for ($i = 0; $i < $bits; $i++) {
200
            $sm >>= 1;
201
            $sm |= 0x80000000;
202
        }
203
        return $sm;
204
    }
205
206
    /* return the highest (broadcast) address in the subnet given a host address and
207
    a subnet bit count */
208 View Code Duplication
    public static function gen_subnet_max($ipaddr, $bits)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
209
    {
210
        if (!self::is_ipaddr($ipaddr) || !is_numeric($bits)) {
211
            return "";
212
        }
213
214
        return self::long2ip32(ip2long($ipaddr) | ~self::gen_subnet_mask_long($bits));
215
    }
216
217
    /* takes an array of ip address, sorts and returns as an array */
218
    public static function sort_addresses($ipaddr)
219
    {
220
        $bitAddresses = [];
221
        $ipAddresses = [];
222
        foreach ($ipaddr as $ipv4) {
223
            $bitAddresses[] = self::ip2ulong($ipv4);
224
        }
225
        sort($bitAddresses);
226
        foreach ($bitAddresses as $raw) {
227
            $ipAddresses[] = self::long2ip32($raw);
228
        }
229
        return $ipAddresses;
230
    }
231
}
232