libs/ip: return a copy of given tables in __mask16() to avoid destroying them later
[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 --- Boolean; true if system is little endian
24 LITTLE_ENDIAN = not luci.util.bigendian()
25
26 --- Boolean; true if system is big endian
27 BIG_ENDIAN    = not LITTLE_ENDIAN
28
29 --- Specifier for IPv4 address family
30 FAMILY_INET4  = 0x04
31
32 --- Specifier for IPv6 address family
33 FAMILY_INET6  = 0x06
34
35
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,
43                 __le    =
44                         function(...)
45                                 return luci.ip.cidr.equal(...) or luci.ip.cidr.lower(...)
46                         end
47         } )
48 end
49
50 local function __array16( x, family )
51         local list
52
53         if type(x) == "number" then
54                 list = { bit.rshift(x, 16), bit.band(x, 0xFFFF) }
55
56         elseif type(x) == "string" then
57                 if x:find(":") then x = IPv6(x) else x = IPv4(x) end
58                 if x then
59                         assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
60                         list = { unpack(x[2]) }
61                 end
62
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]) }
66
67         elseif type(x) == "table" then
68                 list = { unpack(x) }
69         end
70
71         assert( list, "Invalid operand" )
72
73         return list
74 end
75
76 local function __mask16(bits)
77         return bit.lshift( bit.rshift( 0xFFFF, 16 - bits % 16 ), 16 - bits % 16 )
78 end
79
80 local function __not16(bits)
81         return bit.band( bit.bnot( __mask16(bits) ), 0xFFFF )
82 end
83
84 local function __maxlen(family)
85         return ( family == FAMILY_INET4 ) and 32 or 128
86 end
87
88 local function __sublen(family)
89         return ( family == FAMILY_INET4 ) and 30 or 127
90 end
91
92
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
96 -- @see         htonl
97 -- @see         ntohs
98 function htons(x)
99         if LITTLE_ENDIAN then
100                 return bit.bor(
101                         bit.rshift( x, 8 ),
102                         bit.band( bit.lshift( x, 8 ), 0xFF00 )
103                 )
104         else
105                 return x
106         end
107 end
108
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
112 -- @see         htons
113 -- @see         ntohl
114 function htonl(x)
115         if LITTLE_ENDIAN then
116                 return bit.bor(
117                         bit.lshift( htons( bit.band( x, 0xFFFF ) ), 16 ),
118                         htons( bit.rshift( x, 16 ) )
119                 )
120         else
121                 return x
122         end
123 end
124
125 --- Convert given short value to host byte order on little endian hosts
126 -- @class       function
127 -- @name        ntohs
128 -- @param x     Unsigned integer value between 0x0000 and 0xFFFF
129 -- @return      Byte-swapped value
130 -- @see         htonl
131 -- @see         ntohs
132 ntohs = htons
133
134 --- Convert given short value to host byte order on little endian hosts
135 -- @class       function
136 -- @name        ntohl
137 -- @param x     Unsigned integer value between 0x00000000 and 0xFFFFFFFF
138 -- @return      Byte-swapped value
139 -- @see         htons
140 -- @see         ntohl
141 ntohl = htonl
142
143
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
152 -- @see                         IPv6
153 -- @see                         Hex
154 function IPv4(address, netmask)
155         address = address or "0.0.0.0/0"
156
157         local obj = __bless({ FAMILY_INET4 })
158
159         local data = {}
160         local prefix = address:match("/(.+)")
161         address = address:gsub("/.+","")
162
163         if netmask then
164                 prefix = obj:prefix(netmask)
165         elseif prefix then
166                 prefix = tonumber(prefix)
167                 if not prefix or prefix < 0 or prefix > 32 then return nil end
168         else
169                 prefix = 32
170         end
171
172         local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
173
174         b1 = tonumber(b1)
175         b2 = tonumber(b2)
176         b3 = tonumber(b3)
177         b4 = tonumber(b4)
178
179         if b1 and b1 <= 255 and
180            b2 and b2 <= 255 and
181            b3 and b3 <= 255 and
182            b4 and b4 <= 255 and
183            prefix
184         then
185                 table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
186                 table.insert(obj, prefix)
187                 return obj
188         end
189 end
190
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
199 -- @see                         IPv4
200 -- @see                         Hex
201 function IPv6(address, netmask)
202         address = address or "::/0"
203
204         local obj = __bless({ FAMILY_INET6 })
205
206         local data = {}
207         local prefix = address:match("/(.+)")
208         address = address:gsub("/.+","")
209
210         if netmask then
211                 prefix = obj:prefix(netmask)
212         elseif prefix then
213                 prefix = tonumber(prefix)
214                 if not prefix or prefix < 0 or prefix > 128 then return nil end
215         else
216                 prefix = 128
217         end
218
219         local borderl = address:sub(1, 1) == ":" and 2 or 1
220         local borderh, zeroh, chunk, block
221
222         if #address > 45 then return nil end
223
224         repeat
225                 borderh = address:find(":", borderl, true)
226                 if not borderh then break end
227
228                 block = tonumber(address:sub(borderl, borderh - 1), 16)
229                 if block and block <= 0xFFFF then
230                         data[#data+1] = block
231                 else
232                         if zeroh or borderh - borderl > 1 then return nil end
233                         zeroh = #data + 1
234                 end
235
236                 borderl = borderh + 1
237         until #data == 7
238
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
243
244                 data[#data+1] = block
245         elseif #chunk > 4 then
246                 if #data == 7 or #chunk > 15 then return nil end
247                 borderl = 1
248                 for i=1, 4 do
249                         borderh = chunk:find(".", borderl, true)
250                         if not borderh and i < 4 then return nil end
251                         borderh = borderh and borderh - 1
252
253                         block = tonumber(chunk:sub(borderl, borderh))
254                         if not block or block > 255 then return nil end
255
256                         if i == 1 or i == 3 then
257                                 data[#data+1] = block * 256
258                         else
259                                 data[#data] = data[#data] + block
260                         end
261
262                         borderl = borderh and borderh + 2
263                 end
264         end
265
266         if zeroh then
267                 if #data == 8 then return nil end
268                 while #data < 8 do
269                         table.insert(data, zeroh, 0)
270                 end
271         end
272
273         if #data == 8 and prefix then
274                 table.insert(obj, data)
275                 table.insert(obj, prefix)
276                 return obj
277         end
278 end
279
280 --- Transform given hex-encoded value to luci.ip.cidr instance of specified
281 -- address family.
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
287 -- @see                         IPv4
288 -- @see                         IPv6
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)
293
294         local len  = __maxlen(family)
295         local tmp  = ""
296         local data = { }
297
298         for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
299
300         if swap and LITTLE_ENDIAN then
301                 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
302         else
303                 tmp = tmp .. hex
304         end
305
306         hex = tmp
307
308         for i = 1, ( len / 4 ), 4 do
309                 local n = tonumber( hex:sub( i, i+3 ), 16 )
310                 if n then
311                         data[#data+1] = n
312                 else
313                         return nil
314                 end
315         end
316
317         return __bless({ family, data, prefix })
318 end
319
320
321 --- LuCI IP Library / CIDR instances
322 -- @class       module
323 -- @cstyle      instance
324 -- @name        luci.ip.cidr
325 cidr = luci.util.class()
326
327 --- Test whether the instance is a IPv4 address.
328 -- @return      Boolean indicating a IPv4 address type
329 -- @see         cidr.is6
330 function cidr.is4( self )
331         return self[1] == FAMILY_INET4
332 end
333
334 --- Test whether the instance is a IPv6 address.
335 -- @return      Boolean indicating a IPv6 address type
336 -- @see         cidr.is4
337 function cidr.is6( self )
338         return self[1] == FAMILY_INET6
339 end
340
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 )
346         local str
347         if self:is4() then
348                 str = string.format(
349                         "%d.%d.%d.%d",
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)
352                 )
353                 if self[3] < 32 then
354                         str = str .. "/" .. self[3]
355                 end
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]
360                 end
361         end
362         return str
363 end
364
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
370 -- @see                 cidr.higher
371 -- @see                 cidr.equal
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]
377                 end
378         end
379         return false
380 end
381
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
387 -- @see                 cidr.lower
388 -- @see                 cidr.equal
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]
394                 end
395         end
396         return false
397 end
398
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
404 -- @see                 cidr.lower
405 -- @see                 cidr.higher
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
410                         return false
411                 end
412         end
413         return true
414 end
415
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]
421
422         if mask then
423                 prefix = 0
424
425                 local stop = false
426                 local obj = type(mask) ~= "table"
427                         and ( self:is4() and IPv4(mask) or IPv6(mask) ) or mask
428
429                 if not obj then return nil end
430
431                 for _, word in ipairs(obj[2]) do
432                         if word == 0xFFFF then
433                                 prefix = prefix + 16
434                         else
435                                 local bitmask = bit.lshift(1, 15)
436                                 while bit.band(word, bitmask) == bitmask do
437                                         prefix  = prefix + 1
438                                         bitmask = bit.lshift(1, 15 - (prefix % 16))
439                                 end
440
441                                 break
442                         end
443                 end
444         end
445
446         return prefix
447 end
448
449 --- Return a corresponding CIDR representing the network address of this
450 -- instance.
451 -- @param bits  Override prefix length of this instance (optional)
452 -- @return              CIDR instance containing the network address
453 -- @see                 cidr.host
454 -- @see                 cidr.broadcast
455 -- @see                 cidr.mask
456 function cidr.network( self, bits )
457         local data = { }
458         bits = bits or self[3]
459
460         for i = 1, math.floor( bits / 16 ) do
461                 data[#data+1] = self[2][i]
462         end
463
464         if #data < #self[2] then
465                 data[#data+1] = bit.band( self[2][1+#data], __mask16(bits) )
466
467                 for i = #data + 1, #self[2] do
468                         data[#data+1] = 0
469                 end
470         end
471
472         return __bless({ self[1], data, __maxlen(self[1]) })
473 end
474
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
478 -- @see                 cidr.network
479 -- @see                 cidr.broadcast
480 -- @see                 cidr.mask
481 function cidr.host( self )
482         return __bless({ self[1], self[2], __maxlen(self[1]) })
483 end
484
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
488 -- @see                 cidr.network
489 -- @see                 cidr.host
490 -- @see                 cidr.broadcast
491 function cidr.mask( self, bits )
492         local data = { }
493         bits = bits or self[3]
494
495         for i = 1, math.floor( bits / 16 ) do
496                 data[#data+1] = 0xFFFF
497         end
498
499         if #data < #self[2] then
500                 data[#data+1] = __mask16(bits)
501
502                 for i = #data + 1, #self[2] do
503                         data[#data+1] = 0
504                 end
505         end
506
507         return __bless({ self[1], data, __maxlen(self[1]) })
508 end
509
510 --- Return CIDR containing the broadcast address of this instance.
511 -- @return              CIDR instance containing the netmask, always nil for IPv6
512 -- @see                 cidr.network
513 -- @see                 cidr.host
514 -- @see                 cidr.mask
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
520
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
524
525                         return __bless({ self[1], data, __maxlen(self[1]) })
526                 end
527         end
528 end
529
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" )
535
536         if self:prefix() <= addr:prefix() then
537                 return self:network() == addr:network(self:prefix())
538         end
539
540         return false
541 end
542
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
547 -- @see                         cidr.sub
548 function cidr.add( self, amount, inplace )
549         local data   = { unpack(self[2]) }
550         local shorts = __array16( amount, self[1] )
551
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
556                         if pos > 1 then
557                                 data[pos-1] = data[pos-1] + ( add - data[pos] )
558                         else
559                                 return nil
560                         end
561                 else
562                         data[pos] = data[pos] + add
563                 end
564         end
565
566         if inplace then
567                 self[2] = data
568                 return self
569         else
570                 return __bless({ self[1], data, self[3] })
571         end
572 end
573
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
578 -- @see                         cidr.add
579 function cidr.sub( self, amount, inplace )
580         local data   = { unpack(self[2]) }
581         local shorts = __array16( amount, self[1] )
582
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
587                         if pos > 1 then
588                                 data[pos-1] = data[pos-1] - ( sub + data[pos] )
589                         else
590                                 return nil
591                         end
592                 else
593                         data[pos] = data[pos] - sub
594                 end
595         end
596
597         if inplace then
598                 self[2] = data
599                 return self
600         else
601                 return __bless({ self[1], data, self[3] })
602         end
603 end
604
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
607 -- @see                 cidr.maxhost
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)
612         end
613 end
614
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
617 -- @see                 cidr.minhost
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
622
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]) })
626
627                 -- Last address in reserved for Broadcast Address in IPv4
628                 if data[1] == FAMILY_INET4 then data:sub(1, true) end
629
630                 return data
631         end
632 end