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 --- Boolean; true if system is little endian
24 LITTLE_ENDIAN = not luci.util.bigendian()
26 --- Boolean; true if system is big endian
27 BIG_ENDIAN = not LITTLE_ENDIAN
29 --- Specifier for IPv4 address family
32 --- Specifier for IPv6 address family
36 local function __bless(x)
37 return setmetatable( x, {
38 __index = luci.ip.cidr,
39 __add = luci.ip.cidr.add,
40 __sub = luci.ip.cidr.sub,
41 __lt = luci.ip.cidr.lower,
42 __eq = luci.ip.cidr.equal,
45 return luci.ip.cidr.equal(...) or luci.ip.cidr.lower(...)
50 local function __array16( x, family )
53 if type(x) == "number" then
54 list = { bit.rshift(x, 16), bit.band(x, 0xFFFF) }
56 elseif type(x) == "string" then
57 if x:find(":") then x = IPv6(x) else x = IPv4(x) end
59 assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
60 list = { unpack(x[2]) }
63 elseif type(x) == "table" and type(x[2]) == "table" then
64 assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
65 list = { unpack(x[2]) }
67 elseif type(x) == "table" then
71 assert( list, "Invalid operand" )
76 local function __mask16(bits)
77 return bit.lshift( bit.rshift( 0xFFFF, 16 - bits % 16 ), 16 - bits % 16 )
80 local function __not16(bits)
81 return bit.band( bit.bnot( __mask16(bits) ), 0xFFFF )
84 local function __maxlen(family)
85 return ( family == FAMILY_INET4 ) and 32 or 128
88 local function __sublen(family)
89 return ( family == FAMILY_INET4 ) and 30 or 127
93 --- Convert given short value to network byte order on little endian hosts
94 -- @param x Unsigned integer value between 0x0000 and 0xFFFF
95 -- @return Byte-swapped value
102 bit.band( bit.lshift( x, 8 ), 0xFF00 )
109 --- Convert given long value to network byte order on little endian hosts
110 -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
111 -- @return Byte-swapped value
115 if LITTLE_ENDIAN then
117 bit.lshift( htons( bit.band( x, 0xFFFF ) ), 16 ),
118 htons( bit.rshift( x, 16 ) )
125 --- Convert given short value to host byte order on little endian hosts
128 -- @param x Unsigned integer value between 0x0000 and 0xFFFF
129 -- @return Byte-swapped value
134 --- Convert given short value to host byte order on little endian hosts
137 -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
138 -- @return Byte-swapped value
144 --- Parse given IPv4 address in dotted quad or CIDR notation. If an optional
145 -- netmask is given as second argument and the IP address is encoded in CIDR
146 -- notation then the netmask parameter takes precedence. If neither a CIDR
147 -- encoded prefix nor a netmask parameter is given, then a prefix length of
148 -- 32 bit is assumed.
149 -- @param address IPv4 address in dotted quad or CIDR notation
150 -- @param netmask IPv4 netmask in dotted quad notation (optional)
151 -- @return luci.ip.cidr instance or nil if given address was invalid
154 function IPv4(address, netmask)
155 address = address or "0.0.0.0/0"
157 local obj = __bless({ FAMILY_INET4 })
160 local prefix = address:match("/(.+)")
161 address = address:gsub("/.+","")
162 address = address:gsub("^%[(.*)%]$", "%1"):upper():gsub("^::FFFF:", "")
165 prefix = obj:prefix(netmask)
167 prefix = tonumber(prefix)
168 if not prefix or prefix < 0 or prefix > 32 then return nil end
173 local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
180 if b1 and b1 <= 255 and
186 table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
187 table.insert(obj, prefix)
192 --- Parse given IPv6 address in full, compressed, mixed or CIDR notation.
193 -- If an optional netmask is given as second argument and the IP address is
194 -- encoded in CIDR notation then the netmask parameter takes precedence.
195 -- If neither a CIDR encoded prefix nor a netmask parameter is given, then a
196 -- prefix length of 128 bit is assumed.
197 -- @param address IPv6 address in full/compressed/mixed or CIDR notation
198 -- @param netmask IPv6 netmask in full/compressed/mixed notation (optional)
199 -- @return luci.ip.cidr instance or nil if given address was invalid
202 function IPv6(address, netmask)
203 address = address or "::/0"
205 local obj = __bless({ FAMILY_INET6 })
208 local prefix = address:match("/(.+)")
209 address = address:gsub("/.+","")
210 address = address:gsub("^%[(.*)%]$", "%1")
213 prefix = obj:prefix(netmask)
215 prefix = tonumber(prefix)
216 if not prefix or prefix < 0 or prefix > 128 then return nil end
221 local borderl = address:sub(1, 1) == ":" and 2 or 1
222 local borderh, zeroh, chunk, block
224 if #address > 45 then return nil end
227 borderh = address:find(":", borderl, true)
228 if not borderh then break end
230 block = tonumber(address:sub(borderl, borderh - 1), 16)
231 if block and block <= 0xFFFF then
232 data[#data+1] = block
234 if zeroh or borderh - borderl > 1 then return nil end
238 borderl = borderh + 1
241 chunk = address:sub(borderl)
242 if #chunk > 0 and #chunk <= 4 then
243 block = tonumber(chunk, 16)
244 if not block or block > 0xFFFF then return nil end
246 data[#data+1] = block
247 elseif #chunk > 4 then
248 if #data == 7 or #chunk > 15 then return nil end
251 borderh = chunk:find(".", borderl, true)
252 if not borderh and i < 4 then return nil end
253 borderh = borderh and borderh - 1
255 block = tonumber(chunk:sub(borderl, borderh))
256 if not block or block > 255 then return nil end
258 if i == 1 or i == 3 then
259 data[#data+1] = block * 256
261 data[#data] = data[#data] + block
264 borderl = borderh and borderh + 2
269 if #data == 8 then return nil end
271 table.insert(data, zeroh, 0)
275 if #data == 8 and prefix then
276 table.insert(obj, data)
277 table.insert(obj, prefix)
282 --- Transform given hex-encoded value to luci.ip.cidr instance of specified
284 -- @param hex String containing hex encoded value
285 -- @param prefix Prefix length of CIDR instance (optional, default is 32/128)
286 -- @param family Address family, either luci.ip.FAMILY_INET4 or FAMILY_INET6
287 -- @param swap Bool indicating whether to swap byteorder on low endian host
288 -- @return luci.ip.cidr instance or nil if given value was invalid
291 function Hex( hex, prefix, family, swap )
292 family = ( family ~= nil ) and family or FAMILY_INET4
293 swap = ( swap == nil ) and true or swap
294 prefix = prefix or __maxlen(family)
296 local len = __maxlen(family)
300 for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
302 if swap and LITTLE_ENDIAN then
303 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
310 for i = 1, ( len / 4 ), 4 do
311 local n = tonumber( hex:sub( i, i+3 ), 16 )
319 return __bless({ family, data, prefix })
323 --- LuCI IP Library / CIDR instances
326 -- @name luci.ip.cidr
327 cidr = luci.util.class()
329 --- Test whether the instance is a IPv4 address.
330 -- @return Boolean indicating a IPv4 address type
332 function cidr.is4( self )
333 return self[1] == FAMILY_INET4
336 --- Test whether the instance is a IPv6 address.
337 -- @return Boolean indicating a IPv6 address type
339 function cidr.is6( self )
340 return self[1] == FAMILY_INET6
343 --- Return a corresponding string representation of the instance.
344 -- If the prefix length is lower then the maximum possible prefix length for the
345 -- corresponding address type then the address is returned in CIDR notation,
346 -- otherwise the prefix will be left out.
347 function cidr.string( self )
352 bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF),
353 bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF)
356 str = str .. "/" .. self[3]
358 elseif self:is6() then
359 str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) )
360 if self[3] < 128 then
361 str = str .. "/" .. self[3]
367 --- Test whether the value of the instance is lower then the given address.
368 -- This function will throw an exception if the given address has a different
369 -- family than this instance.
370 -- @param addr A luci.ip.cidr instance to compare against
371 -- @return Boolean indicating whether this instance is lower
374 function cidr.lower( self, addr )
375 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
376 for i = 1, #self[2] do
377 if self[2][i] ~= addr[2][i] then
378 return self[2][i] < addr[2][i]
384 --- Test whether the value of the instance is higher then the given address.
385 -- This function will throw an exception if the given address has a different
386 -- family than this instance.
387 -- @param addr A luci.ip.cidr instance to compare against
388 -- @return Boolean indicating whether this instance is higher
391 function cidr.higher( self, addr )
392 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
393 for i = 1, #self[2] do
394 if self[2][i] ~= addr[2][i] then
395 return self[2][i] > addr[2][i]
401 --- Test whether the value of the instance is equal to the given address.
402 -- This function will throw an exception if the given address is a different
403 -- family than this instance.
404 -- @param addr A luci.ip.cidr instance to compare against
405 -- @return Boolean indicating whether this instance is equal
408 function cidr.equal( self, addr )
409 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
410 for i = 1, #self[2] do
411 if self[2][i] ~= addr[2][i] then
418 --- Return the prefix length of this CIDR instance.
419 -- @param mask Override instance prefix with given netmask (optional)
420 -- @return Prefix length in bit
421 function cidr.prefix( self, mask )
422 local prefix = self[3]
428 local obj = type(mask) ~= "table"
429 and ( self:is4() and IPv4(mask) or IPv6(mask) ) or mask
431 if not obj then return nil end
433 for _, word in ipairs(obj[2]) do
434 if word == 0xFFFF then
437 local bitmask = bit.lshift(1, 15)
438 while bit.band(word, bitmask) == bitmask do
440 bitmask = bit.lshift(1, 15 - (prefix % 16))
451 --- Return a corresponding CIDR representing the network address of this
453 -- @param bits Override prefix length of this instance (optional)
454 -- @return CIDR instance containing the network address
456 -- @see cidr.broadcast
458 function cidr.network( self, bits )
460 bits = bits or self[3]
462 for i = 1, math.floor( bits / 16 ) do
463 data[#data+1] = self[2][i]
466 if #data < #self[2] then
467 data[#data+1] = bit.band( self[2][1+#data], __mask16(bits) )
469 for i = #data + 1, #self[2] do
474 return __bless({ self[1], data, __maxlen(self[1]) })
477 --- Return a corresponding CIDR representing the host address of this
478 -- instance. This is intended to extract the host address from larger subnet.
479 -- @return CIDR instance containing the network address
481 -- @see cidr.broadcast
483 function cidr.host( self )
484 return __bless({ self[1], self[2], __maxlen(self[1]) })
487 --- Return a corresponding CIDR representing the netmask of this instance.
488 -- @param bits Override prefix length of this instance (optional)
489 -- @return CIDR instance containing the netmask
492 -- @see cidr.broadcast
493 function cidr.mask( self, bits )
495 bits = bits or self[3]
497 for i = 1, math.floor( bits / 16 ) do
498 data[#data+1] = 0xFFFF
501 if #data < #self[2] then
502 data[#data+1] = __mask16(bits)
504 for i = #data + 1, #self[2] do
509 return __bless({ self[1], data, __maxlen(self[1]) })
512 --- Return CIDR containing the broadcast address of this instance.
513 -- @return CIDR instance containing the netmask, always nil for IPv6
517 function cidr.broadcast( self )
518 -- IPv6 has no broadcast addresses (XXX: assert() instead?)
519 if self[1] == FAMILY_INET4 then
520 local data = { unpack(self[2]) }
521 local offset = math.floor( self[3] / 16 ) + 1
523 if offset <= #data then
524 data[offset] = bit.bor( data[offset], __not16(self[3]) )
525 for i = offset + 1, #data do data[i] = 0xFFFF end
527 return __bless({ self[1], data, __maxlen(self[1]) })
532 --- Test whether this instance fully contains the given CIDR instance.
533 -- @param addr CIDR instance to test against
534 -- @return Boolean indicating whether this instance contains the given CIDR
535 function cidr.contains( self, addr )
536 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
538 if self:prefix() <= addr:prefix() then
539 return self:network() == addr:network(self:prefix())
545 --- Add specified amount of hosts to this instance.
546 -- @param amount Number of hosts to add to this instance
547 -- @param inplace Boolen indicating whether to alter values inplace (optional)
548 -- @return CIDR representing the new address or nil on overflow error
550 function cidr.add( self, amount, inplace )
551 local data = { unpack(self[2]) }
552 local shorts = __array16( amount, self[1] )
554 for pos = #data, 1, -1 do
555 local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
556 if ( data[pos] + add ) > 0xFFFF then
557 data[pos] = ( data[pos] + add ) % 0xFFFF
559 data[pos-1] = data[pos-1] + ( add - data[pos] )
564 data[pos] = data[pos] + add
572 return __bless({ self[1], data, self[3] })
576 --- Substract specified amount of hosts from this instance.
577 -- @param amount Number of hosts to substract from this instance
578 -- @param inplace Boolen indicating whether to alter values inplace (optional)
579 -- @return CIDR representing the new address or nil on underflow error
581 function cidr.sub( self, amount, inplace )
582 local data = { unpack(self[2]) }
583 local shorts = __array16( amount, self[1] )
585 for pos = #data, 1, -1 do
586 local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
587 if ( data[pos] - sub ) < 0 then
588 data[pos] = ( sub - data[pos] ) % 0xFFFF
590 data[pos-1] = data[pos-1] - ( sub + data[pos] )
595 data[pos] = data[pos] - sub
603 return __bless({ self[1], data, self[3] })
607 --- Return CIDR containing the lowest available host address within this subnet.
608 -- @return CIDR containing the host address, nil if subnet is too small
610 function cidr.minhost( self )
611 if self[3] <= __sublen(self[1]) then
612 -- 1st is Network Address in IPv4 and Subnet-Router Anycast Adresse in IPv6
613 return self:network():add(1, true)
617 --- Return CIDR containing the highest available host address within the subnet.
618 -- @return CIDR containing the host address, nil if subnet is too small
620 function cidr.maxhost( self )
621 if self[3] <= __sublen(self[1]) then
622 local data = { unpack(self[2]) }
623 local offset = math.floor( self[3] / 16 ) + 1
625 data[offset] = bit.bor( data[offset], __not16(self[3]) )
626 for i = offset + 1, #data do data[i] = 0xFFFF end
627 data = __bless({ self[1], data, __maxlen(self[1]) })
629 -- Last address in reserved for Broadcast Address in IPv4
630 if data[1] == FAMILY_INET4 then data:sub(1, true) end