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 )
22 local util = require "luci.util"
24 --- Boolean; true if system is little endian
25 LITTLE_ENDIAN = not util.bigendian()
27 --- Boolean; true if system is big endian
28 BIG_ENDIAN = not LITTLE_ENDIAN
30 --- Specifier for IPv4 address family
33 --- Specifier for IPv6 address family
37 local function __bless(x)
38 return setmetatable( x, {
39 __index = luci.ip.cidr,
40 __add = luci.ip.cidr.add,
41 __sub = luci.ip.cidr.sub,
42 __lt = luci.ip.cidr.lower,
43 __eq = luci.ip.cidr.equal,
46 return luci.ip.cidr.equal(...) or luci.ip.cidr.lower(...)
51 local function __array16( x, family )
54 if type(x) == "number" then
55 list = { bit.rshift(x, 16), bit.band(x, 0xFFFF) }
57 elseif type(x) == "string" then
58 if x:find(":") then x = IPv6(x) else x = IPv4(x) end
60 assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
61 list = { unpack(x[2]) }
64 elseif type(x) == "table" and type(x[2]) == "table" then
65 assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
66 list = { unpack(x[2]) }
68 elseif type(x) == "table" then
72 assert( list, "Invalid operand" )
77 local function __mask16(bits)
78 return bit.lshift( bit.rshift( 0xFFFF, 16 - bits % 16 ), 16 - bits % 16 )
81 local function __not16(bits)
82 return bit.band( bit.bnot( __mask16(bits) ), 0xFFFF )
85 local function __maxlen(family)
86 return ( family == FAMILY_INET4 ) and 32 or 128
89 local function __sublen(family)
90 return ( family == FAMILY_INET4 ) and 30 or 127
94 --- Convert given short value to network byte order on little endian hosts
95 -- @param x Unsigned integer value between 0x0000 and 0xFFFF
96 -- @return Byte-swapped value
100 if LITTLE_ENDIAN then
103 bit.band( bit.lshift( x, 8 ), 0xFF00 )
110 --- Convert given long value to network byte order on little endian hosts
111 -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
112 -- @return Byte-swapped value
116 if LITTLE_ENDIAN then
118 bit.lshift( htons( bit.band( x, 0xFFFF ) ), 16 ),
119 htons( bit.rshift( x, 16 ) )
126 --- Convert given short value to host byte order on little endian hosts
129 -- @param x Unsigned integer value between 0x0000 and 0xFFFF
130 -- @return Byte-swapped value
135 --- Convert given short value to host byte order on little endian hosts
138 -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
139 -- @return Byte-swapped value
145 --- Parse given IPv4 address in dotted quad or CIDR notation. If an optional
146 -- netmask is given as second argument and the IP address is encoded in CIDR
147 -- notation then the netmask parameter takes precedence. If neither a CIDR
148 -- encoded prefix nor a netmask parameter is given, then a prefix length of
149 -- 32 bit is assumed.
150 -- @param address IPv4 address in dotted quad or CIDR notation
151 -- @param netmask IPv4 netmask in dotted quad notation (optional)
152 -- @return luci.ip.cidr instance or nil if given address was invalid
155 function IPv4(address, netmask)
156 address = address or "0.0.0.0/0"
158 local obj = __bless({ FAMILY_INET4 })
161 local prefix = address:match("/(.+)")
162 address = address:gsub("/.+","")
163 address = address:gsub("^%[(.*)%]$", "%1"):upper():gsub("^::FFFF:", "")
166 prefix = obj:prefix(netmask)
168 prefix = tonumber(prefix)
169 if not prefix or prefix < 0 or prefix > 32 then return nil end
174 local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
181 if b1 and b1 <= 255 and
187 table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
188 table.insert(obj, prefix)
193 --- Parse given IPv6 address in full, compressed, mixed or CIDR notation.
194 -- If an optional netmask is given as second argument and the IP address is
195 -- encoded in CIDR notation then the netmask parameter takes precedence.
196 -- If neither a CIDR encoded prefix nor a netmask parameter is given, then a
197 -- prefix length of 128 bit is assumed.
198 -- @param address IPv6 address in full/compressed/mixed or CIDR notation
199 -- @param netmask IPv6 netmask in full/compressed/mixed notation (optional)
200 -- @return luci.ip.cidr instance or nil if given address was invalid
203 function IPv6(address, netmask)
204 address = address or "::/0"
206 local obj = __bless({ FAMILY_INET6 })
209 local prefix = address:match("/(.+)")
210 address = address:gsub("/.+","")
211 address = address:gsub("^%[(.*)%]$", "%1")
214 prefix = obj:prefix(netmask)
216 prefix = tonumber(prefix)
217 if not prefix or prefix < 0 or prefix > 128 then return nil end
222 local borderl = address:sub(1, 1) == ":" and 2 or 1
223 local borderh, zeroh, chunk, block
225 if #address > 45 then return nil end
228 borderh = address:find(":", borderl, true)
229 if not borderh then break end
231 block = tonumber(address:sub(borderl, borderh - 1), 16)
232 if block and block <= 0xFFFF then
233 data[#data+1] = block
235 if zeroh or borderh - borderl > 1 then return nil end
239 borderl = borderh + 1
242 chunk = address:sub(borderl)
243 if #chunk > 0 and #chunk <= 4 then
244 block = tonumber(chunk, 16)
245 if not block or block > 0xFFFF then return nil end
247 data[#data+1] = block
248 elseif #chunk > 4 then
249 if #data == 7 or #chunk > 15 then return nil end
252 borderh = chunk:find(".", borderl, true)
253 if not borderh and i < 4 then return nil end
254 borderh = borderh and borderh - 1
256 block = tonumber(chunk:sub(borderl, borderh))
257 if not block or block > 255 then return nil end
259 if i == 1 or i == 3 then
260 data[#data+1] = block * 256
262 data[#data] = data[#data] + block
265 borderl = borderh and borderh + 2
270 if #data == 8 then return nil end
272 table.insert(data, zeroh, 0)
276 if #data == 8 and prefix then
277 table.insert(obj, data)
278 table.insert(obj, prefix)
283 --- Transform given hex-encoded value to luci.ip.cidr instance of specified
285 -- @param hex String containing hex encoded value
286 -- @param prefix Prefix length of CIDR instance (optional, default is 32/128)
287 -- @param family Address family, either luci.ip.FAMILY_INET4 or FAMILY_INET6
288 -- @param swap Bool indicating whether to swap byteorder on low endian host
289 -- @return luci.ip.cidr instance or nil if given value was invalid
292 function Hex( hex, prefix, family, swap )
293 family = ( family ~= nil ) and family or FAMILY_INET4
294 swap = ( swap == nil ) and true or swap
295 prefix = prefix or __maxlen(family)
297 local len = __maxlen(family)
301 for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
303 if swap and LITTLE_ENDIAN then
304 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
311 for i = 1, ( len / 4 ), 4 do
312 local n = tonumber( hex:sub( i, i+3 ), 16 )
320 return __bless({ family, data, prefix })
324 --- LuCI IP Library / CIDR instances
327 -- @name luci.ip.cidr
330 --- Test whether the instance is a IPv4 address.
331 -- @return Boolean indicating a IPv4 address type
333 function cidr.is4( self )
334 return self[1] == FAMILY_INET4
337 --- Test whether the instance is a IPv6 address.
338 -- @return Boolean indicating a IPv6 address type
340 function cidr.is6( self )
341 return self[1] == FAMILY_INET6
344 --- Return a corresponding string representation of the instance.
345 -- If the prefix length is lower then the maximum possible prefix length for the
346 -- corresponding address type then the address is returned in CIDR notation,
347 -- otherwise the prefix will be left out.
348 function cidr.string( self )
353 bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF),
354 bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF)
357 str = str .. "/" .. self[3]
359 elseif self:is6() then
360 str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) )
361 if self[3] < 128 then
362 str = str .. "/" .. self[3]
368 --- Test whether the value of the instance is lower then the given address.
369 -- This function will throw an exception if the given address has a different
370 -- family than this instance.
371 -- @param addr A luci.ip.cidr instance to compare against
372 -- @return Boolean indicating whether this instance is lower
375 function cidr.lower( self, addr )
376 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
377 for i = 1, #self[2] do
378 if self[2][i] ~= addr[2][i] then
379 return self[2][i] < addr[2][i]
385 --- Test whether the value of the instance is higher then the given address.
386 -- This function will throw an exception if the given address has a different
387 -- family than this instance.
388 -- @param addr A luci.ip.cidr instance to compare against
389 -- @return Boolean indicating whether this instance is higher
392 function cidr.higher( self, addr )
393 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
394 for i = 1, #self[2] do
395 if self[2][i] ~= addr[2][i] then
396 return self[2][i] > addr[2][i]
402 --- Test whether the value of the instance is equal to the given address.
403 -- This function will throw an exception if the given address is a different
404 -- family than this instance.
405 -- @param addr A luci.ip.cidr instance to compare against
406 -- @return Boolean indicating whether this instance is equal
409 function cidr.equal( self, addr )
410 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
411 for i = 1, #self[2] do
412 if self[2][i] ~= addr[2][i] then
419 --- Return the prefix length of this CIDR instance.
420 -- @param mask Override instance prefix with given netmask (optional)
421 -- @return Prefix length in bit
422 function cidr.prefix( self, mask )
423 local prefix = self[3]
429 local obj = type(mask) ~= "table"
430 and ( self:is4() and IPv4(mask) or IPv6(mask) ) or mask
432 if not obj then return nil end
434 for _, word in ipairs(obj[2]) do
435 if word == 0xFFFF then
438 local bitmask = bit.lshift(1, 15)
439 while bit.band(word, bitmask) == bitmask do
441 bitmask = bit.lshift(1, 15 - (prefix % 16))
452 --- Return a corresponding CIDR representing the network address of this
454 -- @param bits Override prefix length of this instance (optional)
455 -- @return CIDR instance containing the network address
457 -- @see cidr.broadcast
459 function cidr.network( self, bits )
461 bits = bits or self[3]
463 for i = 1, math.floor( bits / 16 ) do
464 data[#data+1] = self[2][i]
467 if #data < #self[2] then
468 data[#data+1] = bit.band( self[2][1+#data], __mask16(bits) )
470 for i = #data + 1, #self[2] do
475 return __bless({ self[1], data, __maxlen(self[1]) })
478 --- Return a corresponding CIDR representing the host address of this
479 -- instance. This is intended to extract the host address from larger subnet.
480 -- @return CIDR instance containing the network address
482 -- @see cidr.broadcast
484 function cidr.host( self )
485 return __bless({ self[1], self[2], __maxlen(self[1]) })
488 --- Return a corresponding CIDR representing the netmask of this instance.
489 -- @param bits Override prefix length of this instance (optional)
490 -- @return CIDR instance containing the netmask
493 -- @see cidr.broadcast
494 function cidr.mask( self, bits )
496 bits = bits or self[3]
498 for i = 1, math.floor( bits / 16 ) do
499 data[#data+1] = 0xFFFF
502 if #data < #self[2] then
503 data[#data+1] = __mask16(bits)
505 for i = #data + 1, #self[2] do
510 return __bless({ self[1], data, __maxlen(self[1]) })
513 --- Return CIDR containing the broadcast address of this instance.
514 -- @return CIDR instance containing the netmask, always nil for IPv6
518 function cidr.broadcast( self )
519 -- IPv6 has no broadcast addresses (XXX: assert() instead?)
520 if self[1] == FAMILY_INET4 then
521 local data = { unpack(self[2]) }
522 local offset = math.floor( self[3] / 16 ) + 1
524 if offset <= #data then
525 data[offset] = bit.bor( data[offset], __not16(self[3]) )
526 for i = offset + 1, #data do data[i] = 0xFFFF end
528 return __bless({ self[1], data, __maxlen(self[1]) })
533 --- Test whether this instance fully contains the given CIDR instance.
534 -- @param addr CIDR instance to test against
535 -- @return Boolean indicating whether this instance contains the given CIDR
536 function cidr.contains( self, addr )
537 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
539 if self:prefix() <= addr:prefix() then
540 return self:network() == addr:network(self:prefix())
546 --- Add specified amount of hosts to this instance.
547 -- @param amount Number of hosts to add to this instance
548 -- @param inplace Boolen indicating whether to alter values inplace (optional)
549 -- @return CIDR representing the new address or nil on overflow error
551 function cidr.add( self, amount, inplace )
552 local data = { unpack(self[2]) }
553 local shorts = __array16( amount, self[1] )
555 for pos = #data, 1, -1 do
556 local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
557 if ( data[pos] + add ) > 0xFFFF then
558 data[pos] = ( data[pos] + add ) % 0xFFFF
560 data[pos-1] = data[pos-1] + ( add - data[pos] )
565 data[pos] = data[pos] + add
573 return __bless({ self[1], data, self[3] })
577 --- Substract specified amount of hosts from this instance.
578 -- @param amount Number of hosts to substract from this instance
579 -- @param inplace Boolen indicating whether to alter values inplace (optional)
580 -- @return CIDR representing the new address or nil on underflow error
582 function cidr.sub( self, amount, inplace )
583 local data = { unpack(self[2]) }
584 local shorts = __array16( amount, self[1] )
586 for pos = #data, 1, -1 do
587 local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
588 if ( data[pos] - sub ) < 0 then
589 data[pos] = ( sub - data[pos] ) % 0xFFFF
591 data[pos-1] = data[pos-1] - ( sub + data[pos] )
596 data[pos] = data[pos] - sub
604 return __bless({ self[1], data, self[3] })
608 --- Return CIDR containing the lowest available host address within this subnet.
609 -- @return CIDR containing the host address, nil if subnet is too small
611 function cidr.minhost( self )
612 if self[3] <= __sublen(self[1]) then
613 -- 1st is Network Address in IPv4 and Subnet-Router Anycast Adresse in IPv6
614 return self:network():add(1, true)
618 --- Return CIDR containing the highest available host address within the subnet.
619 -- @return CIDR containing the host address, nil if subnet is too small
621 function cidr.maxhost( self )
622 if self[3] <= __sublen(self[1]) then
623 local data = { unpack(self[2]) }
624 local offset = math.floor( self[3] / 16 ) + 1
626 data[offset] = bit.bor( data[offset], __not16(self[3]) )
627 for i = offset + 1, #data do data[i] = 0xFFFF end
628 data = __bless({ self[1], data, __maxlen(self[1]) })
630 -- Last address in reserved for Broadcast Address in IPv4
631 if data[1] == FAMILY_INET4 then data:sub(1, true) end