3 LuCI ip calculation libarary
4 (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
5 (c) 2008 Steven Barth <steven@midlink.org>
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
11 http://www.apache.org/licenses/LICENSE-2.0
17 --- LuCI IP calculation library.
18 module( "luci.ip", package.seeall )
23 LITTLE_ENDIAN = not luci.util.bigendian()
24 BIG_ENDIAN = not LITTLE_ENDIAN
30 local function __bless(x)
31 return setmetatable( x, {
32 __index = luci.ip.cidr,
33 __add = luci.ip.cidr.add,
34 __sub = luci.ip.cidr.sub,
35 __lt = luci.ip.cidr.lower,
36 __eq = luci.ip.cidr.equal,
39 return luci.ip.cidr.equal(...) or luci.ip.cidr.lower(...)
44 local function __mask16(bits)
46 bit.rshift( 0xFFFF, 16 - bits % 16 ),
51 local function __length(family)
52 if family == FAMILY_INET4 then
59 --- Convert given short value to network byte order on little endian hosts
60 -- @param x Unsigned integer value between 0x0000 and 0xFFFF
61 -- @return Byte-swapped value
68 bit.band( bit.lshift( x, 8 ), 0xFF00 )
75 --- Convert given long value to network byte order on little endian hosts
76 -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
77 -- @return Byte-swapped value
83 bit.lshift( htons( bit.band( x, 0xFFFF ) ), 16 ),
84 htons( bit.rshift( x, 16 ) )
91 --- Convert given short value to host byte order on little endian hosts
92 -- @param x Unsigned integer value between 0x0000 and 0xFFFF
93 -- @return Byte-swapped value
98 --- Convert given short value to host byte order on little endian hosts
99 -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
100 -- @return Byte-swapped value
106 --- Parse given IPv4 address in dotted quad or CIDR notation. If an optional
107 -- netmask is given as second argument and the IP address is encoded in CIDR
108 -- notation then the netmask parameter takes precedence. If neither a CIDR
109 -- encoded prefix nor a netmask parameter is given, then a prefix length of
110 -- 32 bit is assumed.
111 -- @param address IPv4 address in dotted quad or CIDR notation
112 -- @param netmask IPv4 netmask in dotted quad notation (optional)
113 -- @return luci.ip.cidr instance or nil if given address was invalid
116 function IPv4(address, netmask)
117 address = address or "0.0.0.0/0"
119 local obj = __bless({ FAMILY_INET4 })
122 local prefix = address:match("/(.+)")
123 address = address:gsub("/.+","")
126 prefix = obj:prefix(netmask)
128 prefix = tonumber(prefix)
129 if not prefix or prefix < 0 or prefix > 32 then return nil end
134 local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
141 if b1 and b1 <= 255 and
147 table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
148 table.insert(obj, prefix)
153 --- Parse given IPv6 address in full, compressed, mixed or CIDR notation.
154 -- If an optional netmask is given as second argument and the IP address is
155 -- encoded in CIDR notation then the netmask parameter takes precedence.
156 -- If neither a CIDR encoded prefix nor a netmask parameter is given, then a
157 -- prefix length of 128 bit is assumed.
158 -- @param address IPv6 address in full/compressed/mixed or CIDR notation
159 -- @param netmask IPv6 netmask in full/compressed/mixed notation (optional)
160 -- @return luci.ip.cidr instance or nil if given address was invalid
163 function IPv6(address, netmask)
164 address = address or "::/0"
166 local obj = __bless({ FAMILY_INET6 })
169 local prefix = address:match("/(.+)")
170 address = address:gsub("/.+","")
173 prefix = obj:prefix(netmask)
175 prefix = tonumber(prefix)
176 if not prefix or prefix < 0 or prefix > 128 then return nil end
181 local borderl = address:sub(1, 1) == ":" and 2 or 1
182 local borderh, zeroh, chunk, block
184 if #address > 45 then return nil end
187 borderh = address:find(":", borderl, true)
188 if not borderh then break end
190 block = tonumber(address:sub(borderl, borderh - 1), 16)
191 if block and block <= 0xFFFF then
192 table.insert(data, block)
194 if zeroh or borderh - borderl > 1 then return nil end
198 borderl = borderh + 1
201 chunk = address:sub(borderl)
202 if #chunk > 0 and #chunk <= 4 then
203 block = tonumber(chunk, 16)
204 if not block or block > 0xFFFF then return nil end
206 table.insert(data, block)
207 elseif #chunk > 4 then
208 if #data == 7 or #chunk > 15 then return nil end
211 borderh = chunk:find(".", borderl, true)
212 if not borderh and i < 4 then return nil end
213 borderh = borderh and borderh - 1
215 block = tonumber(chunk:sub(borderl, borderh))
216 if not block or block > 255 then return nil end
218 if i == 1 or i == 3 then
219 table.insert(data, block * 256)
221 data[#data] = data[#data] + block
224 borderl = borderh and borderh + 2
229 if #data == 8 then return nil end
231 table.insert(data, zeroh, 0)
235 if #data == 8 and prefix then
236 table.insert(obj, data)
237 table.insert(obj, prefix)
242 --- Transform given hex-encoded value to luci.ip.cidr instance of specified
244 -- @param hex String containing hex encoded value
245 -- @param prefix Prefix length of CIDR instance (optional, default is 32/128)
246 -- @param family Address family, either luci.ip.FAMILY_INET4 or FAMILY_INET6
247 -- @param swap Bool indicating weather to swap byteorder on low endian host
248 -- @return luci.ip.cidr instance or nil if given value was invalid
251 function Hex( hex, prefix, family, swap )
252 family = ( family ~= nil ) and family or FAMILY_INET4
253 swap = ( swap == nil ) and true or swap
254 prefix = prefix or __length(family)
256 local len = __length(family)
260 for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
262 if swap and LITTLE_ENDIAN then
263 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
270 for i = 1, ( len / 4 ), 4 do
271 local n = tonumber( hex:sub( i, i+3 ), 16 )
273 table.insert( data, n )
279 return __bless({ family, data, len })
283 --- LuCI IP Library / CIDR instances
285 -- @name luci.ip.cidr
286 cidr = luci.util.class()
288 --- Test weather the instance is a IPv4 address.
289 -- @return Boolean indicating a IPv4 address type
291 function cidr.is4( self )
292 return self[1] == FAMILY_INET4
295 --- Test weather the instance is a IPv6 address.
296 -- @return Boolean indicating a IPv6 address type
298 function cidr.is6( self )
299 return self[1] == FAMILY_INET6
302 --- Return a corresponding string representation of the instance.
303 -- If the prefix length is lower then the maximum possible prefix length for the
304 -- corresponding address type then the address is returned in CIDR notation,
305 -- otherwise the prefix will be left out.
306 function cidr.string( self )
311 bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF),
312 bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF)
315 str = str .. "/" .. self[3]
317 elseif self:is6() then
318 str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) )
319 if self[3] < 128 then
320 str = str .. "/" .. self[3]
326 --- Test weather the value of the instance is lower then the given address.
327 -- This function will throw an exception if the given address has a different
328 -- family than this instance.
329 -- @param addr A luci.ip.cidr instance to compare against
330 -- @return Boolean indicating weather this instance is lower
333 function cidr.lower( self, addr )
334 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
335 for i = 1, #self[2] do
336 if self[2][i] ~= addr[2][i] then
337 return self[2][i] < addr[2][i]
343 --- Test weather the value of the instance is higher then the given address.
344 -- This function will throw an exception if the given address has a different
345 -- family than this instance.
346 -- @param addr A luci.ip.cidr instance to compare against
347 -- @return Boolean indicating weather this instance is higher
350 function cidr.higher( self, addr )
351 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
352 for i = 1, #self[2] do
353 if self[2][i] ~= addr[2][i] then
354 return self[2][i] > addr[2][i]
360 --- Test weather the value of the instance is uequal to the given address.
361 -- This function will throw an exception if the given address is a different
362 -- family than this instance.
363 -- @param addr A luci.ip.cidr instance to compare against
364 -- @return Boolean indicating weather this instance is equal
367 function cidr.equal( self, addr )
368 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
369 for i = 1, #self[2] do
370 if self[2][i] ~= addr[2][i] then
377 --- Return the prefix length of this CIDR instance.
378 -- @return Prefix length in bit
379 function cidr.prefix( self, mask )
380 local prefix = self[3]
385 local obj = self:is4() and IPv4(mask) or IPv6(mask)
391 for i, block in ipairs(obj[2]) do
392 local pos = bit.lshift(1, 15)
394 if bit.band(block, pos) == pos then
403 pos = bit.rshift(pos, 1)
411 --- Return a corresponding CIDR representing the network address of this
413 -- @param bits Override prefix length of this instance (optional)
414 -- @return CIDR instance containing the network address
417 function cidr.network( self, bits )
419 bits = bits or self[3]
421 for i = 1, math.floor( bits / 16 ) do
422 table.insert( data, self[2][i] )
425 if #data < #self[2] then
426 table.insert( data, bit.band( self[2][1+#data], __mask16(bits) ) )
428 for i = #data + 1, #self[2] do
429 table.insert( data, 0 )
433 return __bless({ self[1], data, __length(self[1]) })
436 --- Return a corresponding CIDR representing the host address of this
437 -- instance. This is intended to extract the host address from larger subnet.
438 -- @return CIDR instance containing the network address
441 function cidr.host( self )
442 return __bless({ self[1], data, __length(self[1]) })
445 --- Return a corresponding CIDR representing the netmask of this instance.
446 -- @param bits Override prefix length of this instance (optional)
447 -- @return CIDR instance containing the netmask
450 function cidr.mask( self, bits )
452 bits = bits or self[3]
454 for i = 1, math.floor( bits / 16 ) do
455 table.insert( data, 0xFFFF )
458 if #data < #self[2] then
459 table.insert( data, __mask16(bits) )
461 for i = #data + 1, #self[2] do
462 table.insert( data, 0 )
466 return __bless({ self[1], data, __length(self[1]) })
469 --- Test weather this instance fully contains the given CIDR instance.
470 -- @param addr CIDR instance to test against
471 -- @return Boolean indicating weather this instance contains the given CIDR
472 function cidr.contains( self, addr )
473 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
475 if self:prefix() <= addr:prefix() then
476 return self:network() == addr:network(self:prefix())
482 --- Add specified amount of hosts to this instance.
483 -- @param amount Number of hosts to add to this instance
484 -- @return CIDR representing the new address or nil on overflow error
486 function cidr.add( self, amount )
487 local shorts = { bit.rshift(amount, 16), bit.band(amount, 0xFFFF) }
488 local data = { unpack(self[2]) }
490 for pos = #data, 1, -1 do
491 local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
492 if ( data[pos] + add ) > 0xFFFF then
493 data[pos] = ( data[pos] + add ) % 0xFFFF
495 data[pos-1] = data[pos-1] + ( add - data[pos] )
500 data[pos] = data[pos] + add
504 return __bless({ self[1], data, self[3] })
507 --- Substract specified amount of hosts from this instance.
508 -- @param amount Number of hosts to substract from this instance
509 -- @return CIDR representing the new address or nil on underflow error
511 function cidr.sub( self, amount )
512 local shorts = { bit.rshift(amount, 16), bit.band(amount, 0xFFFF) }
513 local data = { unpack(self[2]) }
515 for pos = #data, 1, -1 do
516 local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
517 if ( data[pos] - sub ) < 0 then
518 data[pos] = ( sub - data[pos] ) % 0xFFFF
520 data[pos-1] = data[pos-1] - ( sub + data[pos] )
525 data[pos] = data[pos] - sub
529 return __bless({ self[1], data, self[3] })