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 __array16( x, family )
47 if type(x) == "number" then
48 list = { bit.rshift(x, 16), bit.band(x, 0xFFFF) }
50 elseif type(x) == "string" then
51 if x:find(":") then x = IPv6(x) else x = IPv4(x) end
53 assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
54 list = { unpack(x[2]) }
57 elseif type(x) == "table" and type(x[2]) == "table" then
58 assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
59 list = { unpack(x[2]) }
61 elseif type(x) == "table" then
65 assert( list, "Invalid operand" )
70 local function __mask16(bits)
71 return bit.lshift( bit.rshift( 0xFFFF, 16 - bits % 16 ), 16 - bits % 16 )
74 local function __not16(bits)
75 return bit.band( bit.bnot( __mask16(bits) ), 0xFFFF )
78 local function __maxlen(family)
79 return ( family == FAMILY_INET4 ) and 32 or 128
82 local function __sublen(family)
83 return ( family == FAMILY_INET4 ) and 30 or 127
87 --- Convert given short value to network byte order on little endian hosts
88 -- @param x Unsigned integer value between 0x0000 and 0xFFFF
89 -- @return Byte-swapped value
96 bit.band( bit.lshift( x, 8 ), 0xFF00 )
103 --- Convert given long value to network byte order on little endian hosts
104 -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
105 -- @return Byte-swapped value
109 if LITTLE_ENDIAN then
111 bit.lshift( htons( bit.band( x, 0xFFFF ) ), 16 ),
112 htons( bit.rshift( x, 16 ) )
119 --- Convert given short value to host byte order on little endian hosts
122 -- @param x Unsigned integer value between 0x0000 and 0xFFFF
123 -- @return Byte-swapped value
128 --- Convert given short value to host byte order on little endian hosts
131 -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
132 -- @return Byte-swapped value
138 --- Parse given IPv4 address in dotted quad or CIDR notation. If an optional
139 -- netmask is given as second argument and the IP address is encoded in CIDR
140 -- notation then the netmask parameter takes precedence. If neither a CIDR
141 -- encoded prefix nor a netmask parameter is given, then a prefix length of
142 -- 32 bit is assumed.
143 -- @param address IPv4 address in dotted quad or CIDR notation
144 -- @param netmask IPv4 netmask in dotted quad notation (optional)
145 -- @return luci.ip.cidr instance or nil if given address was invalid
148 function IPv4(address, netmask)
149 address = address or "0.0.0.0/0"
151 local obj = __bless({ FAMILY_INET4 })
154 local prefix = address:match("/(.+)")
155 address = address:gsub("/.+","")
158 prefix = obj:prefix(netmask)
160 prefix = tonumber(prefix)
161 if not prefix or prefix < 0 or prefix > 32 then return nil end
166 local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
173 if b1 and b1 <= 255 and
179 table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
180 table.insert(obj, prefix)
185 --- Parse given IPv6 address in full, compressed, mixed or CIDR notation.
186 -- If an optional netmask is given as second argument and the IP address is
187 -- encoded in CIDR notation then the netmask parameter takes precedence.
188 -- If neither a CIDR encoded prefix nor a netmask parameter is given, then a
189 -- prefix length of 128 bit is assumed.
190 -- @param address IPv6 address in full/compressed/mixed or CIDR notation
191 -- @param netmask IPv6 netmask in full/compressed/mixed notation (optional)
192 -- @return luci.ip.cidr instance or nil if given address was invalid
195 function IPv6(address, netmask)
196 address = address or "::/0"
198 local obj = __bless({ FAMILY_INET6 })
201 local prefix = address:match("/(.+)")
202 address = address:gsub("/.+","")
205 prefix = obj:prefix(netmask)
207 prefix = tonumber(prefix)
208 if not prefix or prefix < 0 or prefix > 128 then return nil end
213 local borderl = address:sub(1, 1) == ":" and 2 or 1
214 local borderh, zeroh, chunk, block
216 if #address > 45 then return nil end
219 borderh = address:find(":", borderl, true)
220 if not borderh then break end
222 block = tonumber(address:sub(borderl, borderh - 1), 16)
223 if block and block <= 0xFFFF then
224 table.insert(data, block)
226 if zeroh or borderh - borderl > 1 then return nil end
230 borderl = borderh + 1
233 chunk = address:sub(borderl)
234 if #chunk > 0 and #chunk <= 4 then
235 block = tonumber(chunk, 16)
236 if not block or block > 0xFFFF then return nil end
238 table.insert(data, block)
239 elseif #chunk > 4 then
240 if #data == 7 or #chunk > 15 then return nil end
243 borderh = chunk:find(".", borderl, true)
244 if not borderh and i < 4 then return nil end
245 borderh = borderh and borderh - 1
247 block = tonumber(chunk:sub(borderl, borderh))
248 if not block or block > 255 then return nil end
250 if i == 1 or i == 3 then
251 table.insert(data, block * 256)
253 data[#data] = data[#data] + block
256 borderl = borderh and borderh + 2
261 if #data == 8 then return nil end
263 table.insert(data, zeroh, 0)
267 if #data == 8 and prefix then
268 table.insert(obj, data)
269 table.insert(obj, prefix)
274 --- Transform given hex-encoded value to luci.ip.cidr instance of specified
276 -- @param hex String containing hex encoded value
277 -- @param prefix Prefix length of CIDR instance (optional, default is 32/128)
278 -- @param family Address family, either luci.ip.FAMILY_INET4 or FAMILY_INET6
279 -- @param swap Bool indicating whether to swap byteorder on low endian host
280 -- @return luci.ip.cidr instance or nil if given value was invalid
283 function Hex( hex, prefix, family, swap )
284 family = ( family ~= nil ) and family or FAMILY_INET4
285 swap = ( swap == nil ) and true or swap
286 prefix = prefix or __maxlen(family)
288 local len = __maxlen(family)
292 for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
294 if swap and LITTLE_ENDIAN then
295 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
302 for i = 1, ( len / 4 ), 4 do
303 local n = tonumber( hex:sub( i, i+3 ), 16 )
305 table.insert( data, n )
311 return __bless({ family, data, len })
315 --- LuCI IP Library / CIDR instances
317 -- @name luci.ip.cidr
318 cidr = luci.util.class()
320 --- Test whether the instance is a IPv4 address.
321 -- @return Boolean indicating a IPv4 address type
323 function cidr.is4( self )
324 return self[1] == FAMILY_INET4
327 --- Test whether the instance is a IPv6 address.
328 -- @return Boolean indicating a IPv6 address type
330 function cidr.is6( self )
331 return self[1] == FAMILY_INET6
334 --- Return a corresponding string representation of the instance.
335 -- If the prefix length is lower then the maximum possible prefix length for the
336 -- corresponding address type then the address is returned in CIDR notation,
337 -- otherwise the prefix will be left out.
338 function cidr.string( self )
343 bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF),
344 bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF)
347 str = str .. "/" .. self[3]
349 elseif self:is6() then
350 str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) )
351 if self[3] < 128 then
352 str = str .. "/" .. self[3]
358 --- Test whether the value of the instance is lower then the given address.
359 -- This function will throw an exception if the given address has a different
360 -- family than this instance.
361 -- @param addr A luci.ip.cidr instance to compare against
362 -- @return Boolean indicating whether this instance is lower
365 function cidr.lower( self, addr )
366 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
367 for i = 1, #self[2] do
368 if self[2][i] ~= addr[2][i] then
369 return self[2][i] < addr[2][i]
375 --- Test whether the value of the instance is higher then the given address.
376 -- This function will throw an exception if the given address has a different
377 -- family than this instance.
378 -- @param addr A luci.ip.cidr instance to compare against
379 -- @return Boolean indicating whether this instance is higher
382 function cidr.higher( self, addr )
383 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
384 for i = 1, #self[2] do
385 if self[2][i] ~= addr[2][i] then
386 return self[2][i] > addr[2][i]
392 --- Test whether the value of the instance is uequal to the given address.
393 -- This function will throw an exception if the given address is a different
394 -- family than this instance.
395 -- @param addr A luci.ip.cidr instance to compare against
396 -- @return Boolean indicating whether this instance is equal
399 function cidr.equal( self, addr )
400 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
401 for i = 1, #self[2] do
402 if self[2][i] ~= addr[2][i] then
409 --- Return the prefix length of this CIDR instance.
410 -- @return Prefix length in bit
411 function cidr.prefix( self, mask )
412 local prefix = self[3]
417 local obj = self:is4() and IPv4(mask) or IPv6(mask)
423 for i, block in ipairs(obj[2]) do
424 local pos = bit.lshift(1, 15)
426 if bit.band(block, pos) == pos then
435 pos = bit.rshift(pos, 1)
443 --- Return a corresponding CIDR representing the network address of this
445 -- @param bits Override prefix length of this instance (optional)
446 -- @return CIDR instance containing the network address
450 function cidr.network( self, bits )
452 bits = bits or self[3]
454 for i = 1, math.floor( bits / 16 ) do
455 table.insert( data, self[2][i] )
458 if #data < #self[2] then
459 table.insert( data, bit.band( self[2][1+#data], __mask16(bits) ) )
461 for i = #data + 1, #self[2] do
462 table.insert( data, 0 )
466 return __bless({ self[1], data, __maxlen(self[1]) })
469 --- Return a corresponding CIDR representing the host address of this
470 -- instance. This is intended to extract the host address from larger subnet.
471 -- @return CIDR instance containing the network address
475 function cidr.host( self )
476 return __bless({ self[1], data, __maxlen(self[1]) })
479 --- Return a corresponding CIDR representing the netmask of this instance.
480 -- @param bits Override prefix length of this instance (optional)
481 -- @return CIDR instance containing the netmask
485 function cidr.mask( self, bits )
487 bits = bits or self[3]
489 for i = 1, math.floor( bits / 16 ) do
490 table.insert( data, 0xFFFF )
493 if #data < #self[2] then
494 table.insert( data, __mask16(bits) )
496 for i = #data + 1, #self[2] do
497 table.insert( data, 0 )
501 return __bless({ self[1], data, __maxlen(self[1]) })
504 --- Return CIDR containing the broadcast address of this instance.
505 -- @return CIDR instance containing the netmask, always nil for IPv6
509 function cidr.broadcast( self )
510 -- IPv6 has no broadcast addresses (XXX: assert() instead?)
511 if self[1] == FAMILY_INET4 then
512 local data = { unpack(self[2]) }
513 local offset = math.floor( self[3] / 16 ) + 1
515 if offset <= #data then
516 data[offset] = bit.bor( data[offset], __not16(self[3]) )
517 for i = offset + 1, #data do data[i] = 0xFFFF end
519 return __bless({ self[1], data, __maxlen(self[1]) })
524 --- Test whether this instance fully contains the given CIDR instance.
525 -- @param addr CIDR instance to test against
526 -- @return Boolean indicating whether this instance contains the given CIDR
527 function cidr.contains( self, addr )
528 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
530 if self:prefix() <= addr:prefix() then
531 return self:network() == addr:network(self:prefix())
537 --- Add specified amount of hosts to this instance.
538 -- @param amount Number of hosts to add to this instance
539 -- @param inplace Boolen indicating whether to alter values inplace (optional)
540 -- @return CIDR representing the new address or nil on overflow error
542 function cidr.add( self, amount, inplace )
543 local data = { unpack(self[2]) }
544 local shorts = __array16( amount, self[1] )
547 for pos = #data, 1, -1 do
548 local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
549 if ( data[pos] + add ) > 0xFFFF then
550 data[pos] = ( data[pos] + add ) % 0xFFFF
552 data[pos-1] = data[pos-1] + ( add - data[pos] )
557 data[pos] = data[pos] + add
566 return __bless({ self[1], data, self[3] })
570 --- Substract specified amount of hosts from this instance.
571 -- @param amount Number of hosts to substract from this instance
572 -- @param inplace Boolen indicating whether to alter values inplace (optional)
573 -- @return CIDR representing the new address or nil on underflow error
575 function cidr.sub( self, amount, inplace )
576 local data = { unpack(self[2]) }
577 local shorts = __array16( amount, self[1] )
580 for pos = #data, 1, -1 do
581 local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
582 if ( data[pos] - sub ) < 0 then
583 data[pos] = ( sub - data[pos] ) % 0xFFFF
585 data[pos-1] = data[pos-1] - ( sub + data[pos] )
590 data[pos] = data[pos] - sub
599 return __bless({ self[1], data, self[3] })
603 --- Return CIDR containing the lowest available host address within this subnet.
604 -- @return CIDR containing the host address, nil if subnet is too small
606 function cidr.minhost( self )
607 if self[3] <= __sublen(self[1]) then
608 -- 1st is Network Address in IPv4 and Subnet-Router Anycast Adresse in IPv6
609 return self:network():add(1, true)
613 --- Return CIDR containing the highest available host address within the subnet.
614 -- @return CIDR containing the host address, nil if subnet is too small
616 function cidr.maxhost( self )
617 if self[3] <= __sublen(self[1]) then
618 local data = { unpack(self[2]) }
619 local offset = math.floor( self[3] / 16 ) + 1
621 data[offset] = bit.bor( data[offset], __not16(self[3]) )
622 for i = offset + 1, #data do data[i] = 0xFFFF end
623 data = __bless({ self[1], data, __maxlen(self[1]) })
625 -- Last address in reserved for Broadcast Address in IPv4
626 if data[1] == FAMILY_INET4 then data:sub(1, true) end