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("/.+","")
164 prefix = obj:prefix(netmask)
166 prefix = tonumber(prefix)
167 if not prefix or prefix < 0 or prefix > 32 then return nil end
172 local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
179 if b1 and b1 <= 255 and
185 table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
186 table.insert(obj, prefix)
191 --- Parse given IPv6 address in full, compressed, mixed or CIDR notation.
192 -- If an optional netmask is given as second argument and the IP address is
193 -- encoded in CIDR notation then the netmask parameter takes precedence.
194 -- If neither a CIDR encoded prefix nor a netmask parameter is given, then a
195 -- prefix length of 128 bit is assumed.
196 -- @param address IPv6 address in full/compressed/mixed or CIDR notation
197 -- @param netmask IPv6 netmask in full/compressed/mixed notation (optional)
198 -- @return luci.ip.cidr instance or nil if given address was invalid
201 function IPv6(address, netmask)
202 address = address or "::/0"
204 local obj = __bless({ FAMILY_INET6 })
207 local prefix = address:match("/(.+)")
208 address = address:gsub("/.+","")
211 prefix = obj:prefix(netmask)
213 prefix = tonumber(prefix)
214 if not prefix or prefix < 0 or prefix > 128 then return nil end
219 local borderl = address:sub(1, 1) == ":" and 2 or 1
220 local borderh, zeroh, chunk, block
222 if #address > 45 then return nil end
225 borderh = address:find(":", borderl, true)
226 if not borderh then break end
228 block = tonumber(address:sub(borderl, borderh - 1), 16)
229 if block and block <= 0xFFFF then
230 data[#data+1] = block
232 if zeroh or borderh - borderl > 1 then return nil end
236 borderl = borderh + 1
239 chunk = address:sub(borderl)
240 if #chunk > 0 and #chunk <= 4 then
241 block = tonumber(chunk, 16)
242 if not block or block > 0xFFFF then return nil end
244 data[#data+1] = block
245 elseif #chunk > 4 then
246 if #data == 7 or #chunk > 15 then return nil end
249 borderh = chunk:find(".", borderl, true)
250 if not borderh and i < 4 then return nil end
251 borderh = borderh and borderh - 1
253 block = tonumber(chunk:sub(borderl, borderh))
254 if not block or block > 255 then return nil end
256 if i == 1 or i == 3 then
257 data[#data+1] = block * 256
259 data[#data] = data[#data] + block
262 borderl = borderh and borderh + 2
267 if #data == 8 then return nil end
269 table.insert(data, zeroh, 0)
273 if #data == 8 and prefix then
274 table.insert(obj, data)
275 table.insert(obj, prefix)
280 --- Transform given hex-encoded value to luci.ip.cidr instance of specified
282 -- @param hex String containing hex encoded value
283 -- @param prefix Prefix length of CIDR instance (optional, default is 32/128)
284 -- @param family Address family, either luci.ip.FAMILY_INET4 or FAMILY_INET6
285 -- @param swap Bool indicating whether to swap byteorder on low endian host
286 -- @return luci.ip.cidr instance or nil if given value was invalid
289 function Hex( hex, prefix, family, swap )
290 family = ( family ~= nil ) and family or FAMILY_INET4
291 swap = ( swap == nil ) and true or swap
292 prefix = prefix or __maxlen(family)
294 local len = __maxlen(family)
298 for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
300 if swap and LITTLE_ENDIAN then
301 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
308 for i = 1, ( len / 4 ), 4 do
309 local n = tonumber( hex:sub( i, i+3 ), 16 )
317 return __bless({ family, data, prefix })
321 --- LuCI IP Library / CIDR instances
324 -- @name luci.ip.cidr
325 cidr = luci.util.class()
327 --- Test whether the instance is a IPv4 address.
328 -- @return Boolean indicating a IPv4 address type
330 function cidr.is4( self )
331 return self[1] == FAMILY_INET4
334 --- Test whether the instance is a IPv6 address.
335 -- @return Boolean indicating a IPv6 address type
337 function cidr.is6( self )
338 return self[1] == FAMILY_INET6
341 --- Return a corresponding string representation of the instance.
342 -- If the prefix length is lower then the maximum possible prefix length for the
343 -- corresponding address type then the address is returned in CIDR notation,
344 -- otherwise the prefix will be left out.
345 function cidr.string( self )
350 bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF),
351 bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF)
354 str = str .. "/" .. self[3]
356 elseif self:is6() then
357 str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) )
358 if self[3] < 128 then
359 str = str .. "/" .. self[3]
365 --- Test whether the value of the instance is lower then the given address.
366 -- This function will throw an exception if the given address has a different
367 -- family than this instance.
368 -- @param addr A luci.ip.cidr instance to compare against
369 -- @return Boolean indicating whether this instance is lower
372 function cidr.lower( self, addr )
373 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
374 for i = 1, #self[2] do
375 if self[2][i] ~= addr[2][i] then
376 return self[2][i] < addr[2][i]
382 --- Test whether the value of the instance is higher then the given address.
383 -- This function will throw an exception if the given address has a different
384 -- family than this instance.
385 -- @param addr A luci.ip.cidr instance to compare against
386 -- @return Boolean indicating whether this instance is higher
389 function cidr.higher( self, addr )
390 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
391 for i = 1, #self[2] do
392 if self[2][i] ~= addr[2][i] then
393 return self[2][i] > addr[2][i]
399 --- Test whether the value of the instance is equal to the given address.
400 -- This function will throw an exception if the given address is a different
401 -- family than this instance.
402 -- @param addr A luci.ip.cidr instance to compare against
403 -- @return Boolean indicating whether this instance is equal
406 function cidr.equal( self, addr )
407 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
408 for i = 1, #self[2] do
409 if self[2][i] ~= addr[2][i] then
416 --- Return the prefix length of this CIDR instance.
417 -- @param mask Override instance prefix with given netmask (optional)
418 -- @return Prefix length in bit
419 function cidr.prefix( self, mask )
420 local prefix = self[3]
426 local obj = type(mask) ~= "table"
427 and ( self:is4() and IPv4(mask) or IPv6(mask) ) or mask
429 if not obj then return nil end
431 for _, word in ipairs(obj[2]) do
432 if word == 0xFFFF then
435 local bitmask = bit.lshift(1, 15)
436 while bit.band(word, bitmask) == bitmask do
438 bitmask = bit.lshift(1, 15 - (prefix % 16))
449 --- Return a corresponding CIDR representing the network address of this
451 -- @param bits Override prefix length of this instance (optional)
452 -- @return CIDR instance containing the network address
454 -- @see cidr.broadcast
456 function cidr.network( self, bits )
458 bits = bits or self[3]
460 for i = 1, math.floor( bits / 16 ) do
461 data[#data+1] = self[2][i]
464 if #data < #self[2] then
465 data[#data+1] = bit.band( self[2][1+#data], __mask16(bits) )
467 for i = #data + 1, #self[2] do
472 return __bless({ self[1], data, __maxlen(self[1]) })
475 --- Return a corresponding CIDR representing the host address of this
476 -- instance. This is intended to extract the host address from larger subnet.
477 -- @return CIDR instance containing the network address
479 -- @see cidr.broadcast
481 function cidr.host( self )
482 return __bless({ self[1], self[2], __maxlen(self[1]) })
485 --- Return a corresponding CIDR representing the netmask of this instance.
486 -- @param bits Override prefix length of this instance (optional)
487 -- @return CIDR instance containing the netmask
490 -- @see cidr.broadcast
491 function cidr.mask( self, bits )
493 bits = bits or self[3]
495 for i = 1, math.floor( bits / 16 ) do
496 data[#data+1] = 0xFFFF
499 if #data < #self[2] then
500 data[#data+1] = __mask16(bits)
502 for i = #data + 1, #self[2] do
507 return __bless({ self[1], data, __maxlen(self[1]) })
510 --- Return CIDR containing the broadcast address of this instance.
511 -- @return CIDR instance containing the netmask, always nil for IPv6
515 function cidr.broadcast( self )
516 -- IPv6 has no broadcast addresses (XXX: assert() instead?)
517 if self[1] == FAMILY_INET4 then
518 local data = { unpack(self[2]) }
519 local offset = math.floor( self[3] / 16 ) + 1
521 if offset <= #data then
522 data[offset] = bit.bor( data[offset], __not16(self[3]) )
523 for i = offset + 1, #data do data[i] = 0xFFFF end
525 return __bless({ self[1], data, __maxlen(self[1]) })
530 --- Test whether this instance fully contains the given CIDR instance.
531 -- @param addr CIDR instance to test against
532 -- @return Boolean indicating whether this instance contains the given CIDR
533 function cidr.contains( self, addr )
534 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
536 if self:prefix() <= addr:prefix() then
537 return self:network() == addr:network(self:prefix())
543 --- Add specified amount of hosts to this instance.
544 -- @param amount Number of hosts to add to this instance
545 -- @param inplace Boolen indicating whether to alter values inplace (optional)
546 -- @return CIDR representing the new address or nil on overflow error
548 function cidr.add( self, amount, inplace )
549 local data = { unpack(self[2]) }
550 local shorts = __array16( amount, self[1] )
552 for pos = #data, 1, -1 do
553 local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
554 if ( data[pos] + add ) > 0xFFFF then
555 data[pos] = ( data[pos] + add ) % 0xFFFF
557 data[pos-1] = data[pos-1] + ( add - data[pos] )
562 data[pos] = data[pos] + add
570 return __bless({ self[1], data, self[3] })
574 --- Substract specified amount of hosts from this instance.
575 -- @param amount Number of hosts to substract from this instance
576 -- @param inplace Boolen indicating whether to alter values inplace (optional)
577 -- @return CIDR representing the new address or nil on underflow error
579 function cidr.sub( self, amount, inplace )
580 local data = { unpack(self[2]) }
581 local shorts = __array16( amount, self[1] )
583 for pos = #data, 1, -1 do
584 local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
585 if ( data[pos] - sub ) < 0 then
586 data[pos] = ( sub - data[pos] ) % 0xFFFF
588 data[pos-1] = data[pos-1] - ( sub + data[pos] )
593 data[pos] = data[pos] - sub
601 return __bless({ self[1], data, self[3] })
605 --- Return CIDR containing the lowest available host address within this subnet.
606 -- @return CIDR containing the host address, nil if subnet is too small
608 function cidr.minhost( self )
609 if self[3] <= __sublen(self[1]) then
610 -- 1st is Network Address in IPv4 and Subnet-Router Anycast Adresse in IPv6
611 return self:network():add(1, true)
615 --- Return CIDR containing the highest available host address within the subnet.
616 -- @return CIDR containing the host address, nil if subnet is too small
618 function cidr.maxhost( self )
619 if self[3] <= __sublen(self[1]) then
620 local data = { unpack(self[2]) }
621 local offset = math.floor( self[3] / 16 ) + 1
623 data[offset] = bit.bor( data[offset], __not16(self[3]) )
624 for i = offset + 1, #data do data[i] = 0xFFFF end
625 data = __bless({ self[1], data, __maxlen(self[1]) })
627 -- Last address in reserved for Broadcast Address in IPv4
628 if data[1] == FAMILY_INET4 then data:sub(1, true) end