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
94 -- @param x Unsigned integer value between 0x0000 and 0xFFFF
95 -- @return Byte-swapped value
100 --- Convert given short value to host byte order on little endian hosts
103 -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
104 -- @return Byte-swapped value
110 --- Parse given IPv4 address in dotted quad or CIDR notation. If an optional
111 -- netmask is given as second argument and the IP address is encoded in CIDR
112 -- notation then the netmask parameter takes precedence. If neither a CIDR
113 -- encoded prefix nor a netmask parameter is given, then a prefix length of
114 -- 32 bit is assumed.
115 -- @param address IPv4 address in dotted quad or CIDR notation
116 -- @param netmask IPv4 netmask in dotted quad notation (optional)
117 -- @return luci.ip.cidr instance or nil if given address was invalid
120 function IPv4(address, netmask)
121 address = address or "0.0.0.0/0"
123 local obj = __bless({ FAMILY_INET4 })
126 local prefix = address:match("/(.+)")
127 address = address:gsub("/.+","")
130 prefix = obj:prefix(netmask)
132 prefix = tonumber(prefix)
133 if not prefix or prefix < 0 or prefix > 32 then return nil end
138 local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
145 if b1 and b1 <= 255 and
151 table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
152 table.insert(obj, prefix)
157 --- Parse given IPv6 address in full, compressed, mixed or CIDR notation.
158 -- If an optional netmask is given as second argument and the IP address is
159 -- encoded in CIDR notation then the netmask parameter takes precedence.
160 -- If neither a CIDR encoded prefix nor a netmask parameter is given, then a
161 -- prefix length of 128 bit is assumed.
162 -- @param address IPv6 address in full/compressed/mixed or CIDR notation
163 -- @param netmask IPv6 netmask in full/compressed/mixed notation (optional)
164 -- @return luci.ip.cidr instance or nil if given address was invalid
167 function IPv6(address, netmask)
168 address = address or "::/0"
170 local obj = __bless({ FAMILY_INET6 })
173 local prefix = address:match("/(.+)")
174 address = address:gsub("/.+","")
177 prefix = obj:prefix(netmask)
179 prefix = tonumber(prefix)
180 if not prefix or prefix < 0 or prefix > 128 then return nil end
185 local borderl = address:sub(1, 1) == ":" and 2 or 1
186 local borderh, zeroh, chunk, block
188 if #address > 45 then return nil end
191 borderh = address:find(":", borderl, true)
192 if not borderh then break end
194 block = tonumber(address:sub(borderl, borderh - 1), 16)
195 if block and block <= 0xFFFF then
196 table.insert(data, block)
198 if zeroh or borderh - borderl > 1 then return nil end
202 borderl = borderh + 1
205 chunk = address:sub(borderl)
206 if #chunk > 0 and #chunk <= 4 then
207 block = tonumber(chunk, 16)
208 if not block or block > 0xFFFF then return nil end
210 table.insert(data, block)
211 elseif #chunk > 4 then
212 if #data == 7 or #chunk > 15 then return nil end
215 borderh = chunk:find(".", borderl, true)
216 if not borderh and i < 4 then return nil end
217 borderh = borderh and borderh - 1
219 block = tonumber(chunk:sub(borderl, borderh))
220 if not block or block > 255 then return nil end
222 if i == 1 or i == 3 then
223 table.insert(data, block * 256)
225 data[#data] = data[#data] + block
228 borderl = borderh and borderh + 2
233 if #data == 8 then return nil end
235 table.insert(data, zeroh, 0)
239 if #data == 8 and prefix then
240 table.insert(obj, data)
241 table.insert(obj, prefix)
246 --- Transform given hex-encoded value to luci.ip.cidr instance of specified
248 -- @param hex String containing hex encoded value
249 -- @param prefix Prefix length of CIDR instance (optional, default is 32/128)
250 -- @param family Address family, either luci.ip.FAMILY_INET4 or FAMILY_INET6
251 -- @param swap Bool indicating whether to swap byteorder on low endian host
252 -- @return luci.ip.cidr instance or nil if given value was invalid
255 function Hex( hex, prefix, family, swap )
256 family = ( family ~= nil ) and family or FAMILY_INET4
257 swap = ( swap == nil ) and true or swap
258 prefix = prefix or __length(family)
260 local len = __length(family)
264 for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
266 if swap and LITTLE_ENDIAN then
267 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
274 for i = 1, ( len / 4 ), 4 do
275 local n = tonumber( hex:sub( i, i+3 ), 16 )
277 table.insert( data, n )
283 return __bless({ family, data, len })
287 --- LuCI IP Library / CIDR instances
289 -- @name luci.ip.cidr
290 cidr = luci.util.class()
292 --- Test whether the instance is a IPv4 address.
293 -- @return Boolean indicating a IPv4 address type
295 function cidr.is4( self )
296 return self[1] == FAMILY_INET4
299 --- Test whether the instance is a IPv6 address.
300 -- @return Boolean indicating a IPv6 address type
302 function cidr.is6( self )
303 return self[1] == FAMILY_INET6
306 --- Return a corresponding string representation of the instance.
307 -- If the prefix length is lower then the maximum possible prefix length for the
308 -- corresponding address type then the address is returned in CIDR notation,
309 -- otherwise the prefix will be left out.
310 function cidr.string( self )
315 bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF),
316 bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF)
319 str = str .. "/" .. self[3]
321 elseif self:is6() then
322 str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) )
323 if self[3] < 128 then
324 str = str .. "/" .. self[3]
330 --- Test whether the value of the instance is lower then the given address.
331 -- This function will throw an exception if the given address has a different
332 -- family than this instance.
333 -- @param addr A luci.ip.cidr instance to compare against
334 -- @return Boolean indicating whether this instance is lower
337 function cidr.lower( self, addr )
338 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
339 for i = 1, #self[2] do
340 if self[2][i] ~= addr[2][i] then
341 return self[2][i] < addr[2][i]
347 --- Test whether the value of the instance is higher then the given address.
348 -- This function will throw an exception if the given address has a different
349 -- family than this instance.
350 -- @param addr A luci.ip.cidr instance to compare against
351 -- @return Boolean indicating whether this instance is higher
354 function cidr.higher( self, addr )
355 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
356 for i = 1, #self[2] do
357 if self[2][i] ~= addr[2][i] then
358 return self[2][i] > addr[2][i]
364 --- Test whether the value of the instance is uequal to the given address.
365 -- This function will throw an exception if the given address is a different
366 -- family than this instance.
367 -- @param addr A luci.ip.cidr instance to compare against
368 -- @return Boolean indicating whether this instance is equal
371 function cidr.equal( self, addr )
372 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
373 for i = 1, #self[2] do
374 if self[2][i] ~= addr[2][i] then
381 --- Return the prefix length of this CIDR instance.
382 -- @return Prefix length in bit
383 function cidr.prefix( self, mask )
384 local prefix = self[3]
389 local obj = self:is4() and IPv4(mask) or IPv6(mask)
395 for i, block in ipairs(obj[2]) do
396 local pos = bit.lshift(1, 15)
398 if bit.band(block, pos) == pos then
407 pos = bit.rshift(pos, 1)
415 --- Return a corresponding CIDR representing the network address of this
417 -- @param bits Override prefix length of this instance (optional)
418 -- @return CIDR instance containing the network address
421 function cidr.network( self, bits )
423 bits = bits or self[3]
425 for i = 1, math.floor( bits / 16 ) do
426 table.insert( data, self[2][i] )
429 if #data < #self[2] then
430 table.insert( data, bit.band( self[2][1+#data], __mask16(bits) ) )
432 for i = #data + 1, #self[2] do
433 table.insert( data, 0 )
437 return __bless({ self[1], data, __length(self[1]) })
440 --- Return a corresponding CIDR representing the host address of this
441 -- instance. This is intended to extract the host address from larger subnet.
442 -- @return CIDR instance containing the network address
445 function cidr.host( self )
446 return __bless({ self[1], data, __length(self[1]) })
449 --- Return a corresponding CIDR representing the netmask of this instance.
450 -- @param bits Override prefix length of this instance (optional)
451 -- @return CIDR instance containing the netmask
454 function cidr.mask( self, bits )
456 bits = bits or self[3]
458 for i = 1, math.floor( bits / 16 ) do
459 table.insert( data, 0xFFFF )
462 if #data < #self[2] then
463 table.insert( data, __mask16(bits) )
465 for i = #data + 1, #self[2] do
466 table.insert( data, 0 )
470 return __bless({ self[1], data, __length(self[1]) })
473 --- Test whether this instance fully contains the given CIDR instance.
474 -- @param addr CIDR instance to test against
475 -- @return Boolean indicating whether this instance contains the given CIDR
476 function cidr.contains( self, addr )
477 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
479 if self:prefix() <= addr:prefix() then
480 return self:network() == addr:network(self:prefix())
486 --- Add specified amount of hosts to this instance.
487 -- @param amount Number of hosts to add to this instance
488 -- @return CIDR representing the new address or nil on overflow error
490 function cidr.add( self, amount )
491 local shorts = { bit.rshift(amount, 16), bit.band(amount, 0xFFFF) }
492 local data = { unpack(self[2]) }
494 for pos = #data, 1, -1 do
495 local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
496 if ( data[pos] + add ) > 0xFFFF then
497 data[pos] = ( data[pos] + add ) % 0xFFFF
499 data[pos-1] = data[pos-1] + ( add - data[pos] )
504 data[pos] = data[pos] + add
508 return __bless({ self[1], data, self[3] })
511 --- Substract specified amount of hosts from this instance.
512 -- @param amount Number of hosts to substract from this instance
513 -- @return CIDR representing the new address or nil on underflow error
515 function cidr.sub( self, amount )
516 local shorts = { bit.rshift(amount, 16), bit.band(amount, 0xFFFF) }
517 local data = { unpack(self[2]) }
519 for pos = #data, 1, -1 do
520 local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
521 if ( data[pos] - sub ) < 0 then
522 data[pos] = ( sub - data[pos] ) % 0xFFFF
524 data[pos-1] = data[pos-1] - ( sub + data[pos] )
529 data[pos] = data[pos] - sub
533 return __bless({ self[1], data, self[3] })