* luci/libs: added broadcast(), minhost() and maxhost() to luci.ip, allow various...
[project/luci.git] / libs / core / luasrc / ip.lua
1 --[[
2
3 LuCI ip calculation libarary
4 (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
5 (c) 2008 Steven Barth <steven@midlink.org>
6
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
10
11         http://www.apache.org/licenses/LICENSE-2.0
12
13 $Id$
14
15 ]]--
16
17 --- LuCI IP calculation library.
18 module( "luci.ip", package.seeall )
19
20 require("bit")
21 require("luci.util")
22
23 LITTLE_ENDIAN = not luci.util.bigendian()
24 BIG_ENDIAN    = not LITTLE_ENDIAN
25
26 FAMILY_INET4  = 0x04
27 FAMILY_INET6  = 0x06
28
29
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,
37                 __le    =
38                         function(...)
39                                 return luci.ip.cidr.equal(...) or luci.ip.cidr.lower(...)
40                         end
41         } )
42 end
43
44 local function __array16( x, family )
45         local list
46
47         if type(x) == "number" then
48                 list = { bit.rshift(x, 16), bit.band(x, 0xFFFF) }
49
50         elseif type(x) == "string" then
51                 if x:find(":") then x = IPv6(x) else x = IPv4(x) end
52                 if x then
53                         assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
54                         list = { unpack(x[2]) }
55                 end
56
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]) }
60
61         elseif type(x) == "table" then
62                 list = x
63         end
64
65         assert( list, "Invalid operand" )
66
67         return list
68 end
69
70 local function __mask16(bits)
71         return bit.lshift( bit.rshift( 0xFFFF, 16 - bits % 16 ), 16 - bits % 16 )
72 end
73
74 local function __not16(bits)
75         return bit.band( bit.bnot( __mask16(bits) ), 0xFFFF )
76 end
77
78 local function __maxlen(family)
79         return ( family == FAMILY_INET4 ) and 32 or 128
80 end
81
82 local function __sublen(family)
83         return ( family == FAMILY_INET4 ) and 30 or 127
84 end
85
86
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
90 -- @see         htonl
91 -- @see         ntohs
92 function htons(x)
93         if LITTLE_ENDIAN then
94                 return bit.bor(
95                         bit.rshift( x, 8 ),
96                         bit.band( bit.lshift( x, 8 ), 0xFF00 )
97                 )
98         else
99                 return x
100         end
101 end
102
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
106 -- @see         htons
107 -- @see         ntohl
108 function htonl(x)
109         if LITTLE_ENDIAN then
110                 return bit.bor(
111                         bit.lshift( htons( bit.band( x, 0xFFFF ) ), 16 ),
112                         htons( bit.rshift( x, 16 ) )
113                 )
114         else
115                 return x
116         end
117 end
118
119 --- Convert given short value to host byte order on little endian hosts
120 -- @class       function
121 -- @name        ntohs
122 -- @param x     Unsigned integer value between 0x0000 and 0xFFFF
123 -- @return      Byte-swapped value
124 -- @see         htonl
125 -- @see         ntohs
126 ntohs = htons
127
128 --- Convert given short value to host byte order on little endian hosts
129 -- @class       function
130 -- @name        ntohl
131 -- @param x     Unsigned integer value between 0x00000000 and 0xFFFFFFFF
132 -- @return      Byte-swapped value
133 -- @see         htons
134 -- @see         ntohl
135 ntohl = htonl
136
137
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
146 -- @see                         IPv6
147 -- @see                         Hex
148 function IPv4(address, netmask)
149         address = address or "0.0.0.0/0"
150
151         local obj = __bless({ FAMILY_INET4 })
152
153         local data = {}
154         local prefix = address:match("/(.+)")
155         address = address:gsub("/.+","")
156
157         if netmask then
158                 prefix = obj:prefix(netmask)
159         elseif prefix then
160                 prefix = tonumber(prefix)
161                 if not prefix or prefix < 0 or prefix > 32 then return nil end
162         else
163                 prefix = 32
164         end
165
166         local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
167
168         b1 = tonumber(b1)
169         b2 = tonumber(b2)
170         b3 = tonumber(b3)
171         b4 = tonumber(b4)
172
173         if b1 and b1 <= 255 and
174            b2 and b2 <= 255 and
175            b3 and b3 <= 255 and
176            b4 and b4 <= 255 and
177            prefix
178         then
179                 table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
180                 table.insert(obj, prefix)
181                 return obj
182         end
183 end
184
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
193 -- @see                         IPv4
194 -- @see                         Hex
195 function IPv6(address, netmask)
196         address = address or "::/0"
197
198         local obj = __bless({ FAMILY_INET6 })
199
200         local data = {}
201         local prefix = address:match("/(.+)")
202         address = address:gsub("/.+","")
203
204         if netmask then
205                 prefix = obj:prefix(netmask)
206         elseif prefix then
207                 prefix = tonumber(prefix)
208                 if not prefix or prefix < 0 or prefix > 128 then return nil end
209         else
210                 prefix = 128
211         end
212
213         local borderl = address:sub(1, 1) == ":" and 2 or 1
214         local borderh, zeroh, chunk, block
215
216         if #address > 45 then return nil end
217
218         repeat
219                 borderh = address:find(":", borderl, true)
220                 if not borderh then break end
221
222                 block = tonumber(address:sub(borderl, borderh - 1), 16)
223                 if block and block <= 0xFFFF then
224                         table.insert(data, block)
225                 else
226                         if zeroh or borderh - borderl > 1 then return nil end
227                         zeroh = #data + 1
228                 end
229
230                 borderl = borderh + 1
231         until #data == 7
232
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
237
238                 table.insert(data, block)
239         elseif #chunk > 4 then
240                 if #data == 7 or #chunk > 15 then return nil end
241                 borderl = 1
242                 for i=1, 4 do
243                         borderh = chunk:find(".", borderl, true)
244                         if not borderh and i < 4 then return nil end
245                         borderh = borderh and borderh - 1
246
247                         block = tonumber(chunk:sub(borderl, borderh))
248                         if not block or block > 255 then return nil end
249
250                         if i == 1 or i == 3 then
251                                 table.insert(data, block * 256)
252                         else
253                                 data[#data] = data[#data] + block
254                         end
255
256                         borderl = borderh and borderh + 2
257                 end
258         end
259
260         if zeroh then
261                 if #data == 8 then return nil end
262                 while #data < 8 do
263                         table.insert(data, zeroh, 0)
264                 end
265         end
266
267         if #data == 8 and prefix then
268                 table.insert(obj, data)
269                 table.insert(obj, prefix)
270                 return obj
271         end
272 end
273
274 --- Transform given hex-encoded value to luci.ip.cidr instance of specified
275 -- address family.
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
281 -- @see                         IPv4
282 -- @see                         IPv6
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)
287
288         local len  = __maxlen(family)
289         local tmp  = ""
290         local data = { }
291
292         for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
293
294         if swap and LITTLE_ENDIAN then
295                 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
296         else
297                 tmp = tmp .. hex
298         end
299
300         hex = tmp
301
302         for i = 1, ( len / 4 ), 4 do
303                 local n = tonumber( hex:sub( i, i+3 ), 16 )
304                 if n then
305                         table.insert( data, n )
306                 else
307                         return nil
308                 end
309         end
310
311         return __bless({ family, data, len })
312 end
313
314
315 --- LuCI IP Library / CIDR instances
316 -- @class       module
317 -- @name        luci.ip.cidr
318 cidr = luci.util.class()
319
320 --- Test whether the instance is a IPv4 address.
321 -- @return      Boolean indicating a IPv4 address type
322 -- @see         is6
323 function cidr.is4( self )
324         return self[1] == FAMILY_INET4
325 end
326
327 --- Test whether the instance is a IPv6 address.
328 -- @return      Boolean indicating a IPv6 address type
329 -- @see         is4
330 function cidr.is6( self )
331         return self[1] == FAMILY_INET6
332 end
333
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 )
339         local str
340         if self:is4() then
341                 str = string.format(
342                         "%d.%d.%d.%d",
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)
345                 )
346                 if self[3] < 32 then
347                         str = str .. "/" .. self[3]
348                 end
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]
353                 end
354         end
355         return str
356 end
357
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
363 -- @see                 higher
364 -- @see                 equal
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]
370                 end
371         end
372         return false
373 end
374
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
380 -- @see                 lower
381 -- @see                 equal
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]
387                 end
388         end
389         return false
390 end
391
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
397 -- @see                 lower
398 -- @see                 higher
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
403                         return false
404                 end
405         end
406         return true
407 end
408
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]
413
414         if mask then
415                 prefix = 0
416                 local stop = false
417                 local obj = self:is4() and IPv4(mask) or IPv6(mask)
418
419                 if not obj then
420                         return nil
421                 end
422
423                 for i, block in ipairs(obj[2]) do
424                         local pos = bit.lshift(1, 15)
425                         for i=15, 0, -1 do
426                                 if bit.band(block, pos) == pos then
427                                         if not stop then
428                                                 prefix = prefix + 1
429                                         else
430                                                 return nil
431                                         end
432                                 else
433                                         stop = true
434                                 end
435                                 pos = bit.rshift(pos, 1)
436                         end
437                 end
438         end
439
440         return prefix
441 end
442
443 --- Return a corresponding CIDR representing the network address of this
444 -- instance.
445 -- @param bits  Override prefix length of this instance (optional)
446 -- @return              CIDR instance containing the network address
447 -- @see                 host
448 -- @see                 broadcast
449 -- @see                 mask
450 function cidr.network( self, bits )
451         local data = { }
452         bits = bits or self[3]
453
454         for i = 1, math.floor( bits / 16 ) do
455                 table.insert( data, self[2][i] )
456         end
457
458         if #data < #self[2] then
459                 table.insert( data, bit.band( self[2][1+#data], __mask16(bits) ) )
460
461                 for i = #data + 1, #self[2] do
462                         table.insert( data, 0 )
463                 end
464         end
465
466         return __bless({ self[1], data, __maxlen(self[1]) })
467 end
468
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
472 -- @see                 network
473 -- @see                 broadcast
474 -- @see                 mask
475 function cidr.host( self )
476         return __bless({ self[1], data, __maxlen(self[1]) })
477 end
478
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
482 -- @see                 network
483 -- @see                 host
484 -- @see                 broadcast
485 function cidr.mask( self, bits )
486         local data = { }
487         bits = bits or self[3]
488
489         for i = 1, math.floor( bits / 16 ) do
490                 table.insert( data, 0xFFFF )
491         end
492
493         if #data < #self[2] then
494                 table.insert( data, __mask16(bits) )
495
496                 for i = #data + 1, #self[2] do
497                         table.insert( data, 0 )
498                 end
499         end
500
501         return __bless({ self[1], data, __maxlen(self[1]) })
502 end
503
504 --- Return CIDR containing the broadcast address of this instance.
505 -- @param bits  Override prefix length of this instance (optional)
506 -- @return              CIDR instance containing the netmask, always nil for IPv6
507 -- @see                 network
508 -- @see                 host
509 -- @see                 mask
510 function cidr.broadcast( self )
511         -- IPv6 has no broadcast addresses (XXX: assert() instead?)
512         if self[1] == FAMILY_INET4 then
513                 local data   = { unpack(self[2]) }
514                 local offset = math.floor( self[3] / 16 ) + 1
515
516                 if offset <= #data then
517                         data[offset] = bit.bor( data[offset], __not16(self[3]) )
518                         for i = offset + 1, #data do data[i] = 0xFFFF end
519
520                         return __bless({ self[1], data, __maxlen(self[1]) })
521                 end
522         end
523 end
524
525 --- Test whether this instance fully contains the given CIDR instance.
526 -- @param addr  CIDR instance to test against
527 -- @return              Boolean indicating whether this instance contains the given CIDR
528 function cidr.contains( self, addr )
529         assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
530
531         if self:prefix() <= addr:prefix() then
532                 return self:network() == addr:network(self:prefix())
533         end
534
535         return false
536 end
537
538 --- Add specified amount of hosts to this instance.
539 -- @param amount        Number of hosts to add to this instance
540 -- @param inplace       Boolen indicating whether to alter values inplace (optional)
541 -- @return                      CIDR representing the new address or nil on overflow error
542 -- @see                         sub
543 function cidr.add( self, amount, inplace )
544         local data   = { unpack(self[2]) }
545         local shorts = __array16( amount, self[1] )
546
547         if shorts then
548                 for pos = #data, 1, -1 do
549                         local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
550                         if ( data[pos] + add ) > 0xFFFF then
551                                 data[pos] = ( data[pos] + add ) % 0xFFFF
552                                 if pos > 1 then
553                                         data[pos-1] = data[pos-1] + ( add - data[pos] )
554                                 else
555                                         return nil
556                                 end
557                         else
558                                 data[pos] = data[pos] + add
559                         end
560                 end
561         end
562
563         if inplace then
564                 self[2] = data
565                 return self
566         else
567                 return __bless({ self[1], data, self[3] })
568         end
569 end
570
571 --- Substract specified amount of hosts from this instance.
572 -- @param amount        Number of hosts to substract from this instance
573 -- @param inplace       Boolen indicating whether to alter values inplace (optional)
574 -- @return                      CIDR representing the new address or nil on underflow error
575 -- @see                         add
576 function cidr.sub( self, amount, inplace )
577         local data   = { unpack(self[2]) }
578         local shorts = __array16( amount, self[1] )
579
580         if shorts then
581                 for pos = #data, 1, -1 do
582                         local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
583                         if ( data[pos] - sub ) < 0 then
584                                 data[pos] = ( sub - data[pos] ) % 0xFFFF
585                                 if pos > 1 then
586                                         data[pos-1] = data[pos-1] - ( sub + data[pos] )
587                                 else
588                                         return nil
589                                 end
590                         else
591                                 data[pos] = data[pos] - sub
592                         end
593                 end
594         end
595
596         if inplace then
597                 self[2] = data
598                 return self
599         else
600                 return __bless({ self[1], data, self[3] })
601         end
602 end
603
604 --- Return CIDR containing the lowest available host address within this subnet.
605 -- @return              CIDR containing the host address, nil if subnet is too small
606 -- @see                 maxhost
607 function cidr.minhost( self )
608         if self[3] <= __sublen(self[1]) then
609                 -- 1st is Network Address in IPv4 and Subnet-Router Anycast Adresse in IPv6
610                 return self:network():add(1, true)
611         end
612 end
613
614 --- Return CIDR containing the highest available host address within the subnet.
615 -- @return              CIDR containing the host address, nil if subnet is too small
616 -- @see                 minhost
617 function cidr.maxhost( self )
618         if self[3] <= __sublen(self[1]) then
619                 local data   = { unpack(self[2]) }
620                 local offset = math.floor( self[3] / 16 ) + 1
621
622                 data[offset] = bit.bor( data[offset], __not16(self[3]) )
623                 for i = offset + 1, #data do data[i] = 0xFFFF end
624                 data = __bless({ self[1], data, __maxlen(self[1]) })
625
626                 -- Last address in reserved for Broadcast Address in IPv4
627                 if data[1] == FAMILY_INET4 then data:sub(1, true) end
628
629                 return data
630         end
631 end