1 -- Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
2 -- Copyright 2008 Steven Barth <steven@midlink.org>
3 -- Licensed to the public under the Apache License 2.0.
5 --- LuCI IP calculation library.
6 module( "luci.ip", package.seeall )
10 local util = require "luci.util"
12 --- Boolean; true if system is little endian
13 LITTLE_ENDIAN = not util.bigendian()
15 --- Boolean; true if system is big endian
16 BIG_ENDIAN = not LITTLE_ENDIAN
18 --- Specifier for IPv4 address family
21 --- Specifier for IPv6 address family
25 local function __bless(x)
26 return setmetatable( x, {
27 __index = luci.ip.cidr,
28 __add = luci.ip.cidr.add,
29 __sub = luci.ip.cidr.sub,
30 __lt = luci.ip.cidr.lower,
31 __eq = luci.ip.cidr.equal,
34 return luci.ip.cidr.equal(...) or luci.ip.cidr.lower(...)
39 local function __array16( x, family )
42 if type(x) == "number" then
43 list = { bit.rshift(x, 16), bit.band(x, 0xFFFF) }
45 elseif type(x) == "string" then
46 if x:find(":") then x = IPv6(x) else x = IPv4(x) end
48 assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
49 list = { unpack(x[2]) }
52 elseif type(x) == "table" and type(x[2]) == "table" then
53 assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
54 list = { unpack(x[2]) }
56 elseif type(x) == "table" then
60 assert( list, "Invalid operand" )
65 local function __mask16(bits)
66 return bit.lshift( bit.rshift( 0xFFFF, 16 - bits % 16 ), 16 - bits % 16 )
69 local function __not16(bits)
70 return bit.band( bit.bnot( __mask16(bits) ), 0xFFFF )
73 local function __maxlen(family)
74 return ( family == FAMILY_INET4 ) and 32 or 128
77 local function __sublen(family)
78 return ( family == FAMILY_INET4 ) and 30 or 127
82 --- Convert given short value to network byte order on little endian hosts
83 -- @param x Unsigned integer value between 0x0000 and 0xFFFF
84 -- @return Byte-swapped value
91 bit.band( bit.lshift( x, 8 ), 0xFF00 )
98 --- Convert given long value to network byte order on little endian hosts
99 -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
100 -- @return Byte-swapped value
104 if LITTLE_ENDIAN then
106 bit.lshift( htons( bit.band( x, 0xFFFF ) ), 16 ),
107 htons( bit.rshift( x, 16 ) )
114 --- Convert given short value to host byte order on little endian hosts
117 -- @param x Unsigned integer value between 0x0000 and 0xFFFF
118 -- @return Byte-swapped value
123 --- Convert given short value to host byte order on little endian hosts
126 -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
127 -- @return Byte-swapped value
133 --- Parse given IPv4 address in dotted quad or CIDR notation. If an optional
134 -- netmask is given as second argument and the IP address is encoded in CIDR
135 -- notation then the netmask parameter takes precedence. If neither a CIDR
136 -- encoded prefix nor a netmask parameter is given, then a prefix length of
137 -- 32 bit is assumed.
138 -- @param address IPv4 address in dotted quad or CIDR notation
139 -- @param netmask IPv4 netmask in dotted quad notation (optional)
140 -- @return luci.ip.cidr instance or nil if given address was invalid
143 function IPv4(address, netmask)
144 address = address or "0.0.0.0/0"
146 local obj = __bless({ FAMILY_INET4 })
149 local prefix = address:match("/(.+)")
150 address = address:gsub("/.+","")
151 address = address:gsub("^%[(.*)%]$", "%1"):upper():gsub("^::FFFF:", "")
154 prefix = obj:prefix(netmask)
156 prefix = tonumber(prefix)
157 if not prefix or prefix < 0 or prefix > 32 then return nil end
162 local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
169 if b1 and b1 <= 255 and
175 table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
176 table.insert(obj, prefix)
181 --- Parse given IPv6 address in full, compressed, mixed or CIDR notation.
182 -- If an optional netmask is given as second argument and the IP address is
183 -- encoded in CIDR notation then the netmask parameter takes precedence.
184 -- If neither a CIDR encoded prefix nor a netmask parameter is given, then a
185 -- prefix length of 128 bit is assumed.
186 -- @param address IPv6 address in full/compressed/mixed or CIDR notation
187 -- @param netmask IPv6 netmask in full/compressed/mixed notation (optional)
188 -- @return luci.ip.cidr instance or nil if given address was invalid
191 function IPv6(address, netmask)
192 address = address or "::/0"
194 local obj = __bless({ FAMILY_INET6 })
197 local prefix = address:match("/(.+)")
198 address = address:gsub("/.+","")
199 address = address:gsub("^%[(.*)%]$", "%1")
202 prefix = obj:prefix(netmask)
204 prefix = tonumber(prefix)
205 if not prefix or prefix < 0 or prefix > 128 then return nil end
210 local borderl = address:sub(1, 1) == ":" and 2 or 1
211 local borderh, zeroh, chunk, block, i
213 if #address > 45 then return nil end
216 borderh = address:find(":", borderl, true)
217 if not borderh then break end
219 block = tonumber(address:sub(borderl, borderh - 1), 16)
220 if block and block <= 0xFFFF then
221 data[#data+1] = block
223 if zeroh or borderh - borderl > 1 then return nil end
227 borderl = borderh + 1
230 chunk = address:sub(borderl)
231 if #chunk > 0 and #chunk <= 4 then
232 block = tonumber(chunk, 16)
233 if not block or block > 0xFFFF then return nil end
235 data[#data+1] = block
236 elseif #chunk > 4 then
237 if #data == 7 or #chunk > 15 then return nil end
240 borderh = chunk:find(".", borderl, true)
241 if not borderh and i < 4 then return nil end
242 borderh = borderh and borderh - 1
244 block = tonumber(chunk:sub(borderl, borderh))
245 if not block or block > 255 then return nil end
247 if i == 1 or i == 3 then
248 data[#data+1] = block * 256
250 data[#data] = data[#data] + block
253 borderl = borderh and borderh + 2
258 if #data == 8 then return nil end
260 table.insert(data, zeroh, 0)
264 if #data == 8 and prefix then
265 table.insert(obj, data)
266 table.insert(obj, prefix)
271 --- Transform given hex-encoded value to luci.ip.cidr instance of specified
273 -- @param hex String containing hex encoded value
274 -- @param prefix Prefix length of CIDR instance (optional, default is 32/128)
275 -- @param family Address family, either luci.ip.FAMILY_INET4 or FAMILY_INET6
276 -- @param swap Bool indicating whether to swap byteorder on low endian host
277 -- @return luci.ip.cidr instance or nil if given value was invalid
280 function Hex( hex, prefix, family, swap )
281 family = ( family ~= nil ) and family or FAMILY_INET4
282 swap = ( swap == nil ) and true or swap
283 prefix = prefix or __maxlen(family)
285 local len = __maxlen(family)
290 for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
292 if swap and LITTLE_ENDIAN then
293 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
300 for i = 1, ( len / 4 ), 4 do
301 local n = tonumber( hex:sub( i, i+3 ), 16 )
309 return __bless({ family, data, prefix })
313 --- LuCI IP Library / CIDR instances
316 -- @name luci.ip.cidr
319 --- Test whether the instance is a IPv4 address.
320 -- @return Boolean indicating a IPv4 address type
322 function cidr.is4( self )
323 return self[1] == FAMILY_INET4
326 --- Test whether this instance is an IPv4 RFC1918 private address
327 -- @return Boolean indicating whether this instance is an RFC1918 address
328 function cidr.is4rfc1918( self )
329 if self[1] == FAMILY_INET4 then
330 return ((self[2][1] >= 0x0A00) and (self[2][1] <= 0x0AFF)) or
331 ((self[2][1] >= 0xAC10) and (self[2][1] <= 0xAC1F)) or
332 (self[2][1] == 0xC0A8)
337 --- Test whether this instance is an IPv4 link-local address (Zeroconf)
338 -- @return Boolean indicating whether this instance is IPv4 link-local
339 function cidr.is4linklocal( self )
340 if self[1] == FAMILY_INET4 then
341 return (self[2][1] == 0xA9FE)
346 --- Test whether the instance is a IPv6 address.
347 -- @return Boolean indicating a IPv6 address type
349 function cidr.is6( self )
350 return self[1] == FAMILY_INET6
353 --- Test whether this instance is an IPv6 link-local address
354 -- @return Boolean indicating whether this instance is IPv6 link-local
355 function cidr.is6linklocal( self )
356 if self[1] == FAMILY_INET6 then
357 return (self[2][1] >= 0xFE80) and (self[2][1] <= 0xFEBF)
362 --- Return a corresponding string representation of the instance.
363 -- If the prefix length is lower then the maximum possible prefix length for the
364 -- corresponding address type then the address is returned in CIDR notation,
365 -- otherwise the prefix will be left out.
366 function cidr.string( self )
371 bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF),
372 bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF)
375 str = str .. "/" .. self[3]
377 elseif self:is6() then
378 str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) )
379 if self[3] < 128 then
380 str = str .. "/" .. self[3]
386 --- Test whether the value of the instance is lower then the given address.
387 -- This function will throw an exception if the given address has a different
388 -- family than this instance.
389 -- @param addr A luci.ip.cidr instance to compare against
390 -- @return Boolean indicating whether this instance is lower
393 function cidr.lower( self, addr )
394 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
396 for i = 1, #self[2] do
397 if self[2][i] ~= addr[2][i] then
398 return self[2][i] < addr[2][i]
404 --- Test whether the value of the instance is higher then the given address.
405 -- This function will throw an exception if the given address has a different
406 -- family than this instance.
407 -- @param addr A luci.ip.cidr instance to compare against
408 -- @return Boolean indicating whether this instance is higher
411 function cidr.higher( self, addr )
412 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
414 for i = 1, #self[2] do
415 if self[2][i] ~= addr[2][i] then
416 return self[2][i] > addr[2][i]
422 --- Test whether the value of the instance is equal to the given address.
423 -- This function will throw an exception if the given address is a different
424 -- family than this instance.
425 -- @param addr A luci.ip.cidr instance to compare against
426 -- @return Boolean indicating whether this instance is equal
429 function cidr.equal( self, addr )
430 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
432 for i = 1, #self[2] do
433 if self[2][i] ~= addr[2][i] then
440 --- Return the prefix length of this CIDR instance.
441 -- @param mask Override instance prefix with given netmask (optional)
442 -- @return Prefix length in bit
443 function cidr.prefix( self, mask )
444 local prefix = self[3]
450 local obj = type(mask) ~= "table"
451 and ( self:is4() and IPv4(mask) or IPv6(mask) ) or mask
453 if not obj then return nil end
456 for _, word in ipairs(obj[2]) do
457 if word == 0xFFFF then
460 local bitmask = bit.lshift(1, 15)
461 while bit.band(word, bitmask) == bitmask do
463 bitmask = bit.lshift(1, 15 - (prefix % 16))
474 --- Return a corresponding CIDR representing the network address of this
476 -- @param bits Override prefix length of this instance (optional)
477 -- @return CIDR instance containing the network address
479 -- @see cidr.broadcast
481 function cidr.network( self, bits )
483 bits = bits or self[3]
486 for i = 1, math.floor( bits / 16 ) do
487 data[#data+1] = self[2][i]
490 if #data < #self[2] then
491 data[#data+1] = bit.band( self[2][1+#data], __mask16(bits) )
493 for i = #data + 1, #self[2] do
498 return __bless({ self[1], data, __maxlen(self[1]) })
501 --- Return a corresponding CIDR representing the host address of this
502 -- instance. This is intended to extract the host address from larger subnet.
503 -- @return CIDR instance containing the network address
505 -- @see cidr.broadcast
507 function cidr.host( self )
508 return __bless({ self[1], self[2], __maxlen(self[1]) })
511 --- Return a corresponding CIDR representing the netmask of this instance.
512 -- @param bits Override prefix length of this instance (optional)
513 -- @return CIDR instance containing the netmask
516 -- @see cidr.broadcast
517 function cidr.mask( self, bits )
519 bits = bits or self[3]
521 for i = 1, math.floor( bits / 16 ) do
522 data[#data+1] = 0xFFFF
525 if #data < #self[2] then
526 data[#data+1] = __mask16(bits)
528 for i = #data + 1, #self[2] do
533 return __bless({ self[1], data, __maxlen(self[1]) })
536 --- Return CIDR containing the broadcast address of this instance.
537 -- @return CIDR instance containing the netmask, always nil for IPv6
541 function cidr.broadcast( self )
542 -- IPv6 has no broadcast addresses (XXX: assert() instead?)
543 if self[1] == FAMILY_INET4 then
544 local data = { unpack(self[2]) }
545 local offset = math.floor( self[3] / 16 ) + 1
547 if offset <= #data then
548 data[offset] = bit.bor( data[offset], __not16(self[3]) )
549 for i = offset + 1, #data do data[i] = 0xFFFF end
551 return __bless({ self[1], data, __maxlen(self[1]) })
556 --- Test whether this instance fully contains the given CIDR instance.
557 -- @param addr CIDR instance to test against
558 -- @return Boolean indicating whether this instance contains the given CIDR
559 function cidr.contains( self, addr )
560 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
562 if self:prefix() <= addr:prefix() then
563 return self:network() == addr:network(self:prefix())
569 --- Add specified amount of hosts to this instance.
570 -- @param amount Number of hosts to add to this instance
571 -- @param inplace Boolen indicating whether to alter values inplace (optional)
572 -- @return CIDR representing the new address or nil on overflow error
574 function cidr.add( self, amount, inplace )
576 local data = { unpack(self[2]) }
577 local shorts = __array16( amount, self[1] )
579 for pos = #data, 1, -1 do
580 local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
581 if ( data[pos] + add ) > 0xFFFF then
582 data[pos] = ( data[pos] + add ) % 0xFFFF
584 data[pos-1] = data[pos-1] + ( add - data[pos] )
589 data[pos] = data[pos] + add
597 return __bless({ self[1], data, self[3] })
601 --- Substract specified amount of hosts from this instance.
602 -- @param amount Number of hosts to substract from this instance
603 -- @param inplace Boolen indicating whether to alter values inplace (optional)
604 -- @return CIDR representing the new address or nil on underflow error
606 function cidr.sub( self, amount, inplace )
608 local data = { unpack(self[2]) }
609 local shorts = __array16( amount, self[1] )
611 for pos = #data, 1, -1 do
612 local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
613 if ( data[pos] - sub ) < 0 then
614 data[pos] = ( sub - data[pos] ) % 0xFFFF
616 data[pos-1] = data[pos-1] - ( sub + data[pos] )
621 data[pos] = data[pos] - sub
629 return __bless({ self[1], data, self[3] })
633 --- Return CIDR containing the lowest available host address within this subnet.
634 -- @return CIDR containing the host address, nil if subnet is too small
636 function cidr.minhost( self )
637 if self[3] <= __sublen(self[1]) then
638 -- 1st is Network Address in IPv4 and Subnet-Router Anycast Adresse in IPv6
639 return self:network():add(1, true)
643 --- Return CIDR containing the highest available host address within the subnet.
644 -- @return CIDR containing the host address, nil if subnet is too small
646 function cidr.maxhost( self )
647 if self[3] <= __sublen(self[1]) then
649 local data = { unpack(self[2]) }
650 local offset = math.floor( self[3] / 16 ) + 1
652 data[offset] = bit.bor( data[offset], __not16(self[3]) )
653 for i = offset + 1, #data do data[i] = 0xFFFF end
654 data = __bless({ self[1], data, __maxlen(self[1]) })
656 -- Last address in reserved for Broadcast Address in IPv4
657 if data[1] == FAMILY_INET4 then data:sub(1, true) end