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