[PATCH] make luci.ip.IPvX a bit more forgiving
[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         address = address:gsub("^%[(.*)%]$", "%1"):upper():gsub("^::FFFF:", "")
163
164         if netmask then
165                 prefix = obj:prefix(netmask)
166         elseif prefix then
167                 prefix = tonumber(prefix)
168                 if not prefix or prefix < 0 or prefix > 32 then return nil end
169         else
170                 prefix = 32
171         end
172
173         local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
174
175         b1 = tonumber(b1)
176         b2 = tonumber(b2)
177         b3 = tonumber(b3)
178         b4 = tonumber(b4)
179
180         if b1 and b1 <= 255 and
181            b2 and b2 <= 255 and
182            b3 and b3 <= 255 and
183            b4 and b4 <= 255 and
184            prefix
185         then
186                 table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
187                 table.insert(obj, prefix)
188                 return obj
189         end
190 end
191
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
200 -- @see                         IPv4
201 -- @see                         Hex
202 function IPv6(address, netmask)
203         address = address or "::/0"
204
205         local obj = __bless({ FAMILY_INET6 })
206
207         local data = {}
208         local prefix = address:match("/(.+)")
209         address = address:gsub("/.+","")
210         address = address:gsub("^%[(.*)%]$", "%1")
211
212         if netmask then
213                 prefix = obj:prefix(netmask)
214         elseif prefix then
215                 prefix = tonumber(prefix)
216                 if not prefix or prefix < 0 or prefix > 128 then return nil end
217         else
218                 prefix = 128
219         end
220
221         local borderl = address:sub(1, 1) == ":" and 2 or 1
222         local borderh, zeroh, chunk, block
223
224         if #address > 45 then return nil end
225
226         repeat
227                 borderh = address:find(":", borderl, true)
228                 if not borderh then break end
229
230                 block = tonumber(address:sub(borderl, borderh - 1), 16)
231                 if block and block <= 0xFFFF then
232                         data[#data+1] = block
233                 else
234                         if zeroh or borderh - borderl > 1 then return nil end
235                         zeroh = #data + 1
236                 end
237
238                 borderl = borderh + 1
239         until #data == 7
240
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
245
246                 data[#data+1] = block
247         elseif #chunk > 4 then
248                 if #data == 7 or #chunk > 15 then return nil end
249                 borderl = 1
250                 for i=1, 4 do
251                         borderh = chunk:find(".", borderl, true)
252                         if not borderh and i < 4 then return nil end
253                         borderh = borderh and borderh - 1
254
255                         block = tonumber(chunk:sub(borderl, borderh))
256                         if not block or block > 255 then return nil end
257
258                         if i == 1 or i == 3 then
259                                 data[#data+1] = block * 256
260                         else
261                                 data[#data] = data[#data] + block
262                         end
263
264                         borderl = borderh and borderh + 2
265                 end
266         end
267
268         if zeroh then
269                 if #data == 8 then return nil end
270                 while #data < 8 do
271                         table.insert(data, zeroh, 0)
272                 end
273         end
274
275         if #data == 8 and prefix then
276                 table.insert(obj, data)
277                 table.insert(obj, prefix)
278                 return obj
279         end
280 end
281
282 --- Transform given hex-encoded value to luci.ip.cidr instance of specified
283 -- address family.
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
289 -- @see                         IPv4
290 -- @see                         IPv6
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)
295
296         local len  = __maxlen(family)
297         local tmp  = ""
298         local data = { }
299
300         for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
301
302         if swap and LITTLE_ENDIAN then
303                 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
304         else
305                 tmp = tmp .. hex
306         end
307
308         hex = tmp
309
310         for i = 1, ( len / 4 ), 4 do
311                 local n = tonumber( hex:sub( i, i+3 ), 16 )
312                 if n then
313                         data[#data+1] = n
314                 else
315                         return nil
316                 end
317         end
318
319         return __bless({ family, data, prefix })
320 end
321
322
323 --- LuCI IP Library / CIDR instances
324 -- @class       module
325 -- @cstyle      instance
326 -- @name        luci.ip.cidr
327 cidr = luci.util.class()
328
329 --- Test whether the instance is a IPv4 address.
330 -- @return      Boolean indicating a IPv4 address type
331 -- @see         cidr.is6
332 function cidr.is4( self )
333         return self[1] == FAMILY_INET4
334 end
335
336 --- Test whether the instance is a IPv6 address.
337 -- @return      Boolean indicating a IPv6 address type
338 -- @see         cidr.is4
339 function cidr.is6( self )
340         return self[1] == FAMILY_INET6
341 end
342
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 )
348         local str
349         if self:is4() then
350                 str = string.format(
351                         "%d.%d.%d.%d",
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)
354                 )
355                 if self[3] < 32 then
356                         str = str .. "/" .. self[3]
357                 end
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]
362                 end
363         end
364         return str
365 end
366
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
372 -- @see                 cidr.higher
373 -- @see                 cidr.equal
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]
379                 end
380         end
381         return false
382 end
383
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
389 -- @see                 cidr.lower
390 -- @see                 cidr.equal
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]
396                 end
397         end
398         return false
399 end
400
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
406 -- @see                 cidr.lower
407 -- @see                 cidr.higher
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
412                         return false
413                 end
414         end
415         return true
416 end
417
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]
423
424         if mask then
425                 prefix = 0
426
427                 local stop = false
428                 local obj = type(mask) ~= "table"
429                         and ( self:is4() and IPv4(mask) or IPv6(mask) ) or mask
430
431                 if not obj then return nil end
432
433                 for _, word in ipairs(obj[2]) do
434                         if word == 0xFFFF then
435                                 prefix = prefix + 16
436                         else
437                                 local bitmask = bit.lshift(1, 15)
438                                 while bit.band(word, bitmask) == bitmask do
439                                         prefix  = prefix + 1
440                                         bitmask = bit.lshift(1, 15 - (prefix % 16))
441                                 end
442
443                                 break
444                         end
445                 end
446         end
447
448         return prefix
449 end
450
451 --- Return a corresponding CIDR representing the network address of this
452 -- instance.
453 -- @param bits  Override prefix length of this instance (optional)
454 -- @return              CIDR instance containing the network address
455 -- @see                 cidr.host
456 -- @see                 cidr.broadcast
457 -- @see                 cidr.mask
458 function cidr.network( self, bits )
459         local data = { }
460         bits = bits or self[3]
461
462         for i = 1, math.floor( bits / 16 ) do
463                 data[#data+1] = self[2][i]
464         end
465
466         if #data < #self[2] then
467                 data[#data+1] = bit.band( self[2][1+#data], __mask16(bits) )
468
469                 for i = #data + 1, #self[2] do
470                         data[#data+1] = 0
471                 end
472         end
473
474         return __bless({ self[1], data, __maxlen(self[1]) })
475 end
476
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
480 -- @see                 cidr.network
481 -- @see                 cidr.broadcast
482 -- @see                 cidr.mask
483 function cidr.host( self )
484         return __bless({ self[1], self[2], __maxlen(self[1]) })
485 end
486
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
490 -- @see                 cidr.network
491 -- @see                 cidr.host
492 -- @see                 cidr.broadcast
493 function cidr.mask( self, bits )
494         local data = { }
495         bits = bits or self[3]
496
497         for i = 1, math.floor( bits / 16 ) do
498                 data[#data+1] = 0xFFFF
499         end
500
501         if #data < #self[2] then
502                 data[#data+1] = __mask16(bits)
503
504                 for i = #data + 1, #self[2] do
505                         data[#data+1] = 0
506                 end
507         end
508
509         return __bless({ self[1], data, __maxlen(self[1]) })
510 end
511
512 --- Return CIDR containing the broadcast address of this instance.
513 -- @return              CIDR instance containing the netmask, always nil for IPv6
514 -- @see                 cidr.network
515 -- @see                 cidr.host
516 -- @see                 cidr.mask
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
522
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
526
527                         return __bless({ self[1], data, __maxlen(self[1]) })
528                 end
529         end
530 end
531
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" )
537
538         if self:prefix() <= addr:prefix() then
539                 return self:network() == addr:network(self:prefix())
540         end
541
542         return false
543 end
544
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
549 -- @see                         cidr.sub
550 function cidr.add( self, amount, inplace )
551         local data   = { unpack(self[2]) }
552         local shorts = __array16( amount, self[1] )
553
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
558                         if pos > 1 then
559                                 data[pos-1] = data[pos-1] + ( add - data[pos] )
560                         else
561                                 return nil
562                         end
563                 else
564                         data[pos] = data[pos] + add
565                 end
566         end
567
568         if inplace then
569                 self[2] = data
570                 return self
571         else
572                 return __bless({ self[1], data, self[3] })
573         end
574 end
575
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
580 -- @see                         cidr.add
581 function cidr.sub( self, amount, inplace )
582         local data   = { unpack(self[2]) }
583         local shorts = __array16( amount, self[1] )
584
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
589                         if pos > 1 then
590                                 data[pos-1] = data[pos-1] - ( sub + data[pos] )
591                         else
592                                 return nil
593                         end
594                 else
595                         data[pos] = data[pos] - sub
596                 end
597         end
598
599         if inplace then
600                 self[2] = data
601                 return self
602         else
603                 return __bless({ self[1], data, self[3] })
604         end
605 end
606
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
609 -- @see                 cidr.maxhost
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)
614         end
615 end
616
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
619 -- @see                 cidr.minhost
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
624
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]) })
628
629                 -- Last address in reserved for Broadcast Address in IPv4
630                 if data[1] == FAMILY_INET4 then data:sub(1, true) end
631
632                 return data
633         end
634 end