libs/core: add is4linklocal(), is4rfc1918() and is6linklocal() to luci.ip
[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 "nixio"
21 local bit  = nixio.bit
22 local util = require "luci.util"
23
24 --- Boolean; true if system is little endian
25 LITTLE_ENDIAN = not util.bigendian()
26
27 --- Boolean; true if system is big endian
28 BIG_ENDIAN    = not LITTLE_ENDIAN
29
30 --- Specifier for IPv4 address family
31 FAMILY_INET4  = 0x04
32
33 --- Specifier for IPv6 address family
34 FAMILY_INET6  = 0x06
35
36
37 local function __bless(x)
38         return setmetatable( x, {
39                 __index = luci.ip.cidr,
40                 __add   = luci.ip.cidr.add,
41                 __sub   = luci.ip.cidr.sub,
42                 __lt    = luci.ip.cidr.lower,
43                 __eq    = luci.ip.cidr.equal,
44                 __le    =
45                         function(...)
46                                 return luci.ip.cidr.equal(...) or luci.ip.cidr.lower(...)
47                         end
48         } )
49 end
50
51 local function __array16( x, family )
52         local list
53
54         if type(x) == "number" then
55                 list = { bit.rshift(x, 16), bit.band(x, 0xFFFF) }
56
57         elseif type(x) == "string" then
58                 if x:find(":") then x = IPv6(x) else x = IPv4(x) end
59                 if x then
60                         assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
61                         list = { unpack(x[2]) }
62                 end
63
64         elseif type(x) == "table" and type(x[2]) == "table" then
65                 assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" )
66                 list = { unpack(x[2]) }
67
68         elseif type(x) == "table" then
69                 list = { unpack(x) }
70         end
71
72         assert( list, "Invalid operand" )
73
74         return list
75 end
76
77 local function __mask16(bits)
78         return bit.lshift( bit.rshift( 0xFFFF, 16 - bits % 16 ), 16 - bits % 16 )
79 end
80
81 local function __not16(bits)
82         return bit.band( bit.bnot( __mask16(bits) ), 0xFFFF )
83 end
84
85 local function __maxlen(family)
86         return ( family == FAMILY_INET4 ) and 32 or 128
87 end
88
89 local function __sublen(family)
90         return ( family == FAMILY_INET4 ) and 30 or 127
91 end
92
93
94 --- Convert given short value to network byte order on little endian hosts
95 -- @param x     Unsigned integer value between 0x0000 and 0xFFFF
96 -- @return      Byte-swapped value
97 -- @see         htonl
98 -- @see         ntohs
99 function htons(x)
100         if LITTLE_ENDIAN then
101                 return bit.bor(
102                         bit.rshift( x, 8 ),
103                         bit.band( bit.lshift( x, 8 ), 0xFF00 )
104                 )
105         else
106                 return x
107         end
108 end
109
110 --- Convert given long value to network byte order on little endian hosts
111 -- @param x     Unsigned integer value between 0x00000000 and 0xFFFFFFFF
112 -- @return      Byte-swapped value
113 -- @see         htons
114 -- @see         ntohl
115 function htonl(x)
116         if LITTLE_ENDIAN then
117                 return bit.bor(
118                         bit.lshift( htons( bit.band( x, 0xFFFF ) ), 16 ),
119                         htons( bit.rshift( x, 16 ) )
120                 )
121         else
122                 return x
123         end
124 end
125
126 --- Convert given short value to host byte order on little endian hosts
127 -- @class       function
128 -- @name        ntohs
129 -- @param x     Unsigned integer value between 0x0000 and 0xFFFF
130 -- @return      Byte-swapped value
131 -- @see         htonl
132 -- @see         ntohs
133 ntohs = htons
134
135 --- Convert given short value to host byte order on little endian hosts
136 -- @class       function
137 -- @name        ntohl
138 -- @param x     Unsigned integer value between 0x00000000 and 0xFFFFFFFF
139 -- @return      Byte-swapped value
140 -- @see         htons
141 -- @see         ntohl
142 ntohl = htonl
143
144
145 --- Parse given IPv4 address in dotted quad or CIDR notation. If an optional
146 -- netmask is given as second argument and the IP address is encoded in CIDR
147 -- notation then the netmask parameter takes precedence. If neither a CIDR
148 -- encoded prefix nor a netmask parameter is given, then a prefix length of
149 -- 32 bit is assumed.
150 -- @param address       IPv4 address in dotted quad or CIDR notation
151 -- @param netmask       IPv4 netmask in dotted quad notation (optional)
152 -- @return                      luci.ip.cidr instance or nil if given address was invalid
153 -- @see                         IPv6
154 -- @see                         Hex
155 function IPv4(address, netmask)
156         address = address or "0.0.0.0/0"
157
158         local obj = __bless({ FAMILY_INET4 })
159
160         local data = {}
161         local prefix = address:match("/(.+)")
162         address = address:gsub("/.+","")
163         address = address:gsub("^%[(.*)%]$", "%1"):upper():gsub("^::FFFF:", "")
164
165         if netmask then
166                 prefix = obj:prefix(netmask)
167         elseif prefix then
168                 prefix = tonumber(prefix)
169                 if not prefix or prefix < 0 or prefix > 32 then return nil end
170         else
171                 prefix = 32
172         end
173
174         local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
175
176         b1 = tonumber(b1)
177         b2 = tonumber(b2)
178         b3 = tonumber(b3)
179         b4 = tonumber(b4)
180
181         if b1 and b1 <= 255 and
182            b2 and b2 <= 255 and
183            b3 and b3 <= 255 and
184            b4 and b4 <= 255 and
185            prefix
186         then
187                 table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
188                 table.insert(obj, prefix)
189                 return obj
190         end
191 end
192
193 --- Parse given IPv6 address in full, compressed, mixed or CIDR notation.
194 -- If an optional netmask is given as second argument and the IP address is
195 -- encoded in CIDR notation then the netmask parameter takes precedence.
196 -- If neither a CIDR encoded prefix nor a netmask parameter is given, then a
197 -- prefix length of 128 bit is assumed.
198 -- @param address       IPv6 address in full/compressed/mixed or CIDR notation
199 -- @param netmask       IPv6 netmask in full/compressed/mixed notation (optional)
200 -- @return                      luci.ip.cidr instance or nil if given address was invalid
201 -- @see                         IPv4
202 -- @see                         Hex
203 function IPv6(address, netmask)
204         address = address or "::/0"
205
206         local obj = __bless({ FAMILY_INET6 })
207
208         local data = {}
209         local prefix = address:match("/(.+)")
210         address = address:gsub("/.+","")
211         address = address:gsub("^%[(.*)%]$", "%1")
212
213         if netmask then
214                 prefix = obj:prefix(netmask)
215         elseif prefix then
216                 prefix = tonumber(prefix)
217                 if not prefix or prefix < 0 or prefix > 128 then return nil end
218         else
219                 prefix = 128
220         end
221
222         local borderl = address:sub(1, 1) == ":" and 2 or 1
223         local borderh, zeroh, chunk, block
224
225         if #address > 45 then return nil end
226
227         repeat
228                 borderh = address:find(":", borderl, true)
229                 if not borderh then break end
230
231                 block = tonumber(address:sub(borderl, borderh - 1), 16)
232                 if block and block <= 0xFFFF then
233                         data[#data+1] = block
234                 else
235                         if zeroh or borderh - borderl > 1 then return nil end
236                         zeroh = #data + 1
237                 end
238
239                 borderl = borderh + 1
240         until #data == 7
241
242         chunk = address:sub(borderl)
243         if #chunk > 0 and #chunk <= 4 then
244                 block = tonumber(chunk, 16)
245                 if not block or block > 0xFFFF then return nil end
246
247                 data[#data+1] = block
248         elseif #chunk > 4 then
249                 if #data == 7 or #chunk > 15 then return nil end
250                 borderl = 1
251                 for i=1, 4 do
252                         borderh = chunk:find(".", borderl, true)
253                         if not borderh and i < 4 then return nil end
254                         borderh = borderh and borderh - 1
255
256                         block = tonumber(chunk:sub(borderl, borderh))
257                         if not block or block > 255 then return nil end
258
259                         if i == 1 or i == 3 then
260                                 data[#data+1] = block * 256
261                         else
262                                 data[#data] = data[#data] + block
263                         end
264
265                         borderl = borderh and borderh + 2
266                 end
267         end
268
269         if zeroh then
270                 if #data == 8 then return nil end
271                 while #data < 8 do
272                         table.insert(data, zeroh, 0)
273                 end
274         end
275
276         if #data == 8 and prefix then
277                 table.insert(obj, data)
278                 table.insert(obj, prefix)
279                 return obj
280         end
281 end
282
283 --- Transform given hex-encoded value to luci.ip.cidr instance of specified
284 -- address family.
285 -- @param hex           String containing hex encoded value
286 -- @param prefix        Prefix length of CIDR instance (optional, default is 32/128)
287 -- @param family        Address family, either luci.ip.FAMILY_INET4 or FAMILY_INET6
288 -- @param swap          Bool indicating whether to swap byteorder on low endian host
289 -- @return                      luci.ip.cidr instance or nil if given value was invalid
290 -- @see                         IPv4
291 -- @see                         IPv6
292 function Hex( hex, prefix, family, swap )
293         family = ( family ~= nil ) and family or FAMILY_INET4
294         swap   = ( swap   == nil ) and true   or swap
295         prefix = prefix or __maxlen(family)
296
297         local len  = __maxlen(family)
298         local tmp  = ""
299         local data = { }
300
301         for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
302
303         if swap and LITTLE_ENDIAN then
304                 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
305         else
306                 tmp = tmp .. hex
307         end
308
309         hex = tmp
310
311         for i = 1, ( len / 4 ), 4 do
312                 local n = tonumber( hex:sub( i, i+3 ), 16 )
313                 if n then
314                         data[#data+1] = n
315                 else
316                         return nil
317                 end
318         end
319
320         return __bless({ family, data, prefix })
321 end
322
323
324 --- LuCI IP Library / CIDR instances
325 -- @class       module
326 -- @cstyle      instance
327 -- @name        luci.ip.cidr
328 cidr = util.class()
329
330 --- Test whether the instance is a IPv4 address.
331 -- @return      Boolean indicating a IPv4 address type
332 -- @see         cidr.is6
333 function cidr.is4( self )
334         return self[1] == FAMILY_INET4
335 end
336
337 --- Test whether this instance is an IPv4 RFC1918 private address
338 -- @return      Boolean indicating whether this instance is an RFC1918 address
339 function cidr.is4rfc1918( self )
340         if self[1] == FAMILY_INET4 then
341                 return ((self[2][1] >= 0x0A00) and (self[2][1] <= 0x0AFF)) or
342                        ((self[2][1] >= 0xAC10) and (self[2][1] <= 0xAC1F)) or
343                            (self[2][1] == 0xC0A8)
344         end
345         return false
346 end
347
348 --- Test whether this instance is an IPv4 link-local address (Zeroconf)
349 -- @return      Boolean indicating whether this instance is IPv4 link-local
350 function cidr.is4linklocal( self )
351         if self[1] == FAMILY_INET4 then
352                 return (self[2][1] == 0xA9FE)
353         end
354         return false
355 end
356
357 --- Test whether the instance is a IPv6 address.
358 -- @return      Boolean indicating a IPv6 address type
359 -- @see         cidr.is4
360 function cidr.is6( self )
361         return self[1] == FAMILY_INET6
362 end
363
364 --- Test whether this instance is an IPv6 link-local address
365 -- @return      Boolean indicating whether this instance is IPv6 link-local
366 function cidr.is6linklocal( self )
367         if self[1] == FAMILY_INET6 then
368                 return (self[2][1] >= 0xFE80) and (self[2][1] <= 0xFEBF)
369         end
370         return false
371 end
372
373 --- Return a corresponding string representation of the instance.
374 -- If the prefix length is lower then the maximum possible prefix length for the
375 -- corresponding address type then the address is returned in CIDR notation,
376 -- otherwise the prefix will be left out.
377 function cidr.string( self )
378         local str
379         if self:is4() then
380                 str = string.format(
381                         "%d.%d.%d.%d",
382                         bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF),
383                         bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF)
384                 )
385                 if self[3] < 32 then
386                         str = str .. "/" .. self[3]
387                 end
388         elseif self:is6() then
389                 str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) )
390                 if self[3] < 128 then
391                         str = str .. "/" .. self[3]
392                 end
393         end
394         return str
395 end
396
397 --- Test whether the value of the instance is lower then the given address.
398 -- This function will throw an exception if the given address has a different
399 -- family than this instance.
400 -- @param addr  A luci.ip.cidr instance to compare against
401 -- @return              Boolean indicating whether this instance is lower
402 -- @see                 cidr.higher
403 -- @see                 cidr.equal
404 function cidr.lower( self, addr )
405         assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
406         for i = 1, #self[2] do
407                 if self[2][i] ~= addr[2][i] then
408                         return self[2][i] < addr[2][i]
409                 end
410         end
411         return false
412 end
413
414 --- Test whether the value of the instance is higher then the given address.
415 -- This function will throw an exception if the given address has a different
416 -- family than this instance.
417 -- @param addr  A luci.ip.cidr instance to compare against
418 -- @return              Boolean indicating whether this instance is higher
419 -- @see                 cidr.lower
420 -- @see                 cidr.equal
421 function cidr.higher( self, addr )
422         assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
423         for i = 1, #self[2] do
424                 if self[2][i] ~= addr[2][i] then
425                         return self[2][i] > addr[2][i]
426                 end
427         end
428         return false
429 end
430
431 --- Test whether the value of the instance is equal to the given address.
432 -- This function will throw an exception if the given address is a different
433 -- family than this instance.
434 -- @param addr  A luci.ip.cidr instance to compare against
435 -- @return              Boolean indicating whether this instance is equal
436 -- @see                 cidr.lower
437 -- @see                 cidr.higher
438 function cidr.equal( self, addr )
439         assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
440         for i = 1, #self[2] do
441                 if self[2][i] ~= addr[2][i] then
442                         return false
443                 end
444         end
445         return true
446 end
447
448 --- Return the prefix length of this CIDR instance.
449 -- @param mask  Override instance prefix with given netmask (optional)
450 -- @return              Prefix length in bit
451 function cidr.prefix( self, mask )
452         local prefix = self[3]
453
454         if mask then
455                 prefix = 0
456
457                 local stop = false
458                 local obj = type(mask) ~= "table"
459                         and ( self:is4() and IPv4(mask) or IPv6(mask) ) or mask
460
461                 if not obj then return nil end
462
463                 for _, word in ipairs(obj[2]) do
464                         if word == 0xFFFF then
465                                 prefix = prefix + 16
466                         else
467                                 local bitmask = bit.lshift(1, 15)
468                                 while bit.band(word, bitmask) == bitmask do
469                                         prefix  = prefix + 1
470                                         bitmask = bit.lshift(1, 15 - (prefix % 16))
471                                 end
472
473                                 break
474                         end
475                 end
476         end
477
478         return prefix
479 end
480
481 --- Return a corresponding CIDR representing the network address of this
482 -- instance.
483 -- @param bits  Override prefix length of this instance (optional)
484 -- @return              CIDR instance containing the network address
485 -- @see                 cidr.host
486 -- @see                 cidr.broadcast
487 -- @see                 cidr.mask
488 function cidr.network( self, bits )
489         local data = { }
490         bits = bits or self[3]
491
492         for i = 1, math.floor( bits / 16 ) do
493                 data[#data+1] = self[2][i]
494         end
495
496         if #data < #self[2] then
497                 data[#data+1] = bit.band( self[2][1+#data], __mask16(bits) )
498
499                 for i = #data + 1, #self[2] do
500                         data[#data+1] = 0
501                 end
502         end
503
504         return __bless({ self[1], data, __maxlen(self[1]) })
505 end
506
507 --- Return a corresponding CIDR representing the host address of this
508 -- instance. This is intended to extract the host address from larger subnet.
509 -- @return              CIDR instance containing the network address
510 -- @see                 cidr.network
511 -- @see                 cidr.broadcast
512 -- @see                 cidr.mask
513 function cidr.host( self )
514         return __bless({ self[1], self[2], __maxlen(self[1]) })
515 end
516
517 --- Return a corresponding CIDR representing the netmask of this instance.
518 -- @param bits  Override prefix length of this instance (optional)
519 -- @return              CIDR instance containing the netmask
520 -- @see                 cidr.network
521 -- @see                 cidr.host
522 -- @see                 cidr.broadcast
523 function cidr.mask( self, bits )
524         local data = { }
525         bits = bits or self[3]
526
527         for i = 1, math.floor( bits / 16 ) do
528                 data[#data+1] = 0xFFFF
529         end
530
531         if #data < #self[2] then
532                 data[#data+1] = __mask16(bits)
533
534                 for i = #data + 1, #self[2] do
535                         data[#data+1] = 0
536                 end
537         end
538
539         return __bless({ self[1], data, __maxlen(self[1]) })
540 end
541
542 --- Return CIDR containing the broadcast address of this instance.
543 -- @return              CIDR instance containing the netmask, always nil for IPv6
544 -- @see                 cidr.network
545 -- @see                 cidr.host
546 -- @see                 cidr.mask
547 function cidr.broadcast( self )
548         -- IPv6 has no broadcast addresses (XXX: assert() instead?)
549         if self[1] == FAMILY_INET4 then
550                 local data   = { unpack(self[2]) }
551                 local offset = math.floor( self[3] / 16 ) + 1
552
553                 if offset <= #data then
554                         data[offset] = bit.bor( data[offset], __not16(self[3]) )
555                         for i = offset + 1, #data do data[i] = 0xFFFF end
556
557                         return __bless({ self[1], data, __maxlen(self[1]) })
558                 end
559         end
560 end
561
562 --- Test whether this instance fully contains the given CIDR instance.
563 -- @param addr  CIDR instance to test against
564 -- @return              Boolean indicating whether this instance contains the given CIDR
565 function cidr.contains( self, addr )
566         assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
567
568         if self:prefix() <= addr:prefix() then
569                 return self:network() == addr:network(self:prefix())
570         end
571
572         return false
573 end
574
575 --- Add specified amount of hosts to this instance.
576 -- @param amount        Number of hosts to add to this instance
577 -- @param inplace       Boolen indicating whether to alter values inplace (optional)
578 -- @return                      CIDR representing the new address or nil on overflow error
579 -- @see                         cidr.sub
580 function cidr.add( self, amount, inplace )
581         local data   = { unpack(self[2]) }
582         local shorts = __array16( amount, self[1] )
583
584         for pos = #data, 1, -1 do
585                 local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
586                 if ( data[pos] + add ) > 0xFFFF then
587                         data[pos] = ( data[pos] + add ) % 0xFFFF
588                         if pos > 1 then
589                                 data[pos-1] = data[pos-1] + ( add - data[pos] )
590                         else
591                                 return nil
592                         end
593                 else
594                         data[pos] = data[pos] + add
595                 end
596         end
597
598         if inplace then
599                 self[2] = data
600                 return self
601         else
602                 return __bless({ self[1], data, self[3] })
603         end
604 end
605
606 --- Substract specified amount of hosts from this instance.
607 -- @param amount        Number of hosts to substract from this instance
608 -- @param inplace       Boolen indicating whether to alter values inplace (optional)
609 -- @return                      CIDR representing the new address or nil on underflow error
610 -- @see                         cidr.add
611 function cidr.sub( self, amount, inplace )
612         local data   = { unpack(self[2]) }
613         local shorts = __array16( amount, self[1] )
614
615         for pos = #data, 1, -1 do
616                 local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
617                 if ( data[pos] - sub ) < 0 then
618                         data[pos] = ( sub - data[pos] ) % 0xFFFF
619                         if pos > 1 then
620                                 data[pos-1] = data[pos-1] - ( sub + data[pos] )
621                         else
622                                 return nil
623                         end
624                 else
625                         data[pos] = data[pos] - sub
626                 end
627         end
628
629         if inplace then
630                 self[2] = data
631                 return self
632         else
633                 return __bless({ self[1], data, self[3] })
634         end
635 end
636
637 --- Return CIDR containing the lowest available host address within this subnet.
638 -- @return              CIDR containing the host address, nil if subnet is too small
639 -- @see                 cidr.maxhost
640 function cidr.minhost( self )
641         if self[3] <= __sublen(self[1]) then
642                 -- 1st is Network Address in IPv4 and Subnet-Router Anycast Adresse in IPv6
643                 return self:network():add(1, true)
644         end
645 end
646
647 --- Return CIDR containing the highest available host address within the subnet.
648 -- @return              CIDR containing the host address, nil if subnet is too small
649 -- @see                 cidr.minhost
650 function cidr.maxhost( self )
651         if self[3] <= __sublen(self[1]) then
652                 local data   = { unpack(self[2]) }
653                 local offset = math.floor( self[3] / 16 ) + 1
654
655                 data[offset] = bit.bor( data[offset], __not16(self[3]) )
656                 for i = offset + 1, #data do data[i] = 0xFFFF end
657                 data = __bless({ self[1], data, __maxlen(self[1]) })
658
659                 -- Last address in reserved for Broadcast Address in IPv4
660                 if data[1] == FAMILY_INET4 then data:sub(1, true) end
661
662                 return data
663         end
664 end