a7e6bab65a349eb5472fe4421e4a52401fcb4bde
[project/luci.git] / libs / core / luasrc / ip.lua
1 --[[
2
3 LuCI ip calculation libarary
4 (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
5 (c) 2008 Steven Barth <steven@midlink.org>
6
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
10
11         http://www.apache.org/licenses/LICENSE-2.0
12
13 $Id$
14
15 ]]--
16
17 --- LuCI IP calculation library.
18 module( "luci.ip", package.seeall )
19
20 require("bit")
21 require("luci.util")
22
23 LITTLE_ENDIAN = not luci.util.bigendian()
24 BIG_ENDIAN    = not LITTLE_ENDIAN
25
26 FAMILY_INET4  = 0x04
27 FAMILY_INET6  = 0x06
28
29
30 local function __bless(x)
31         return setmetatable( x, {
32                 __index = luci.ip.cidr,
33                 __add   = luci.ip.cidr.add,
34                 __sub   = luci.ip.cidr.sub,
35                 __lt    = luci.ip.cidr.lower,
36                 __eq    = luci.ip.cidr.equal,
37                 __le    =
38                         function(...)
39                                 return luci.ip.cidr.equal(...) or luci.ip.cidr.lower(...)
40                         end
41         } )
42 end
43
44 local function __mask16(bits)
45         return bit.lshift(
46                 bit.rshift( 0xFFFF, 16 - bits % 16 ),
47                 16 - bits % 16
48         )
49 end
50
51 local function __length(family)
52         if family == FAMILY_INET4 then
53                 return 32
54         else
55                 return 128
56         end
57 end
58
59 --- Convert given short value to network byte order on little endian hosts
60 -- @param x     Unsigned integer value between 0x0000 and 0xFFFF
61 -- @return      Byte-swapped value
62 -- @see         htonl
63 -- @see         ntohs
64 function htons(x)
65         if LITTLE_ENDIAN then
66                 return bit.bor(
67                         bit.rshift( x, 8 ),
68                         bit.band( bit.lshift( x, 8 ), 0xFF00 )
69                 )
70         else
71                 return x
72         end
73 end
74
75 --- Convert given long value to network byte order on little endian hosts
76 -- @param x     Unsigned integer value between 0x00000000 and 0xFFFFFFFF
77 -- @return      Byte-swapped value
78 -- @see         htons
79 -- @see         ntohl
80 function htonl(x)
81         if LITTLE_ENDIAN then
82                 return bit.bor(
83                         bit.lshift( htons( bit.band( x, 0xFFFF ) ), 16 ),
84                         htons( bit.rshift( x, 16 ) )
85                 )
86         else
87                 return x
88         end
89 end
90
91 --- Convert given short value to host byte order on little endian hosts
92 -- @param x     Unsigned integer value between 0x0000 and 0xFFFF
93 -- @return      Byte-swapped value
94 -- @see         htonl
95 -- @see         ntohs
96 ntohs = htons
97
98 --- Convert given short value to host 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 ntohl = htonl
104
105
106 --- Parse given IPv4 address in dotted quad or CIDR notation. If an optional
107 -- netmask is given as second argument and the IP address is encoded in CIDR
108 -- notation then the netmask parameter takes precedence. If neither a CIDR
109 -- encoded prefix nor a netmask parameter is given, then a prefix length of
110 -- 32 bit is assumed.
111 -- @param address       IPv4 address in dotted quad or CIDR notation
112 -- @param netmask       IPv4 netmask in dotted quad notation (optional)
113 -- @return                      luci.ip.cidr instance or nil if given address was invalid
114 -- @see                         IPv6
115 -- @see                         Hex
116 function IPv4(address, netmask)
117         address = address or "0.0.0.0/0"
118
119         local obj = __bless({ FAMILY_INET4 })
120
121         local data = {}
122         local prefix = address:match("/(.+)")
123         address = address:gsub("/.+","")
124
125         if netmask then
126                 prefix = obj:prefix(netmask)
127         elseif prefix then
128                 prefix = tonumber(prefix)
129                 if not prefix or prefix < 0 or prefix > 32 then return nil end
130         else
131                 prefix = 32
132         end
133
134         local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
135
136         b1 = tonumber(b1)
137         b2 = tonumber(b2)
138         b3 = tonumber(b3)
139         b4 = tonumber(b4)
140
141         if b1 and b1 <= 255 and
142            b2 and b2 <= 255 and
143            b3 and b3 <= 255 and
144            b4 and b4 <= 255 and
145            prefix
146         then
147                 table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
148                 table.insert(obj, prefix)
149                 return obj
150         end
151 end
152
153 --- Parse given IPv6 address in full, compressed, mixed or CIDR notation.
154 -- If an optional netmask is given as second argument and the IP address is
155 -- encoded in CIDR notation then the netmask parameter takes precedence.
156 -- If neither a CIDR encoded prefix nor a netmask parameter is given, then a
157 -- prefix length of 128 bit is assumed.
158 -- @param address       IPv6 address in full/compressed/mixed or CIDR notation
159 -- @param netmask       IPv6 netmask in full/compressed/mixed notation (optional)
160 -- @return                      luci.ip.cidr instance or nil if given address was invalid
161 -- @see                         IPv4
162 -- @see                         Hex
163 function IPv6(address, netmask)
164         address = address or "::/0"
165
166         local obj = __bless({ FAMILY_INET6 })
167
168         local data = {}
169         local prefix = address:match("/(.+)")
170         address = address:gsub("/.+","")
171
172         if netmask then
173                 prefix = obj:prefix(netmask)
174         elseif prefix then
175                 prefix = tonumber(prefix)
176                 if not prefix or prefix < 0 or prefix > 128 then return nil end
177         else
178                 prefix = 128
179         end
180
181         local borderl = address:sub(1, 1) == ":" and 2 or 1
182         local borderh, zeroh, chunk, block
183
184         if #address > 45 then return nil end
185
186         repeat
187                 borderh = address:find(":", borderl, true)
188                 if not borderh then break end
189
190                 block = tonumber(address:sub(borderl, borderh - 1), 16)
191                 if block and block <= 0xFFFF then
192                         table.insert(data, block)
193                 else
194                         if zeroh or borderh - borderl > 1 then return nil end
195                         zeroh = #data + 1
196                 end
197
198                 borderl = borderh + 1
199         until #data == 7
200
201         chunk = address:sub(borderl)
202         if #chunk > 0 and #chunk <= 4 then
203                 block = tonumber(chunk, 16)
204                 if not block or block > 0xFFFF then return nil end
205
206                 table.insert(data, block)
207         elseif #chunk > 4 then
208                 if #data == 7 or #chunk > 15 then return nil end
209                 borderl = 1
210                 for i=1, 4 do
211                         borderh = chunk:find(".", borderl, true)
212                         if not borderh and i < 4 then return nil end
213                         borderh = borderh and borderh - 1
214
215                         block = tonumber(chunk:sub(borderl, borderh))
216                         if not block or block > 255 then return nil end
217
218                         if i == 1 or i == 3 then
219                                 table.insert(data, block * 256)
220                         else
221                                 data[#data] = data[#data] + block
222                         end
223
224                         borderl = borderh and borderh + 2
225                 end
226         end
227
228         if zeroh then
229                 if #data == 8 then return nil end
230                 while #data < 8 do
231                         table.insert(data, zeroh, 0)
232                 end
233         end
234
235         if #data == 8 and prefix then
236                 table.insert(obj, data)
237                 table.insert(obj, prefix)
238                 return obj
239         end
240 end
241
242 --- Transform given hex-encoded value to luci.ip.cidr instance of specified
243 -- address family.
244 -- @param hex           String containing hex encoded value
245 -- @param prefix        Prefix length of CIDR instance (optional, default is 32/128)
246 -- @param family        Address family, either luci.ip.FAMILY_INET4 or FAMILY_INET6
247 -- @param swap          Bool indicating weather to swap byteorder on low endian host
248 -- @return                      luci.ip.cidr instance or nil if given value was invalid
249 -- @see                         IPv4
250 -- @see                         IPv6
251 function Hex( hex, prefix, family, swap )
252         family = ( family ~= nil ) and family or FAMILY_INET4
253         swap   = ( swap   == nil ) and true   or swap
254         prefix = prefix or __length(family)
255
256         local len  = __length(family)
257         local tmp  = ""
258         local data = { }
259
260         for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
261
262         if swap and LITTLE_ENDIAN then
263                 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
264         else
265                 tmp = tmp .. hex
266         end
267
268         hex = tmp
269
270         for i = 1, ( len / 4 ), 4 do
271                 local n = tonumber( hex:sub( i, i+3 ), 16 )
272                 if n then
273                         table.insert( data, n )
274                 else
275                         return nil
276                 end
277         end
278
279         return __bless({ family, data, len })
280 end
281
282
283 --- LuCI IP Library / CIDR instances
284 -- @class       module
285 -- @name        luci.ip.cidr
286 cidr = luci.util.class()
287
288 --- Test weather the instance is a IPv4 address.
289 -- @return      Boolean indicating a IPv4 address type
290 -- @see         is6
291 function cidr.is4( self )
292         return self[1] == FAMILY_INET4
293 end
294
295 --- Test weather the instance is a IPv6 address.
296 -- @return      Boolean indicating a IPv6 address type
297 -- @see         is4
298 function cidr.is6( self )
299         return self[1] == FAMILY_INET6
300 end
301
302 --- Return a corresponding string representation of the instance.
303 -- If the prefix length is lower then the maximum possible prefix length for the
304 -- corresponding address type then the address is returned in CIDR notation,
305 -- otherwise the prefix will be left out.
306 function cidr.string( self )
307         local str
308         if self:is4() then
309                 str = string.format(
310                         "%d.%d.%d.%d",
311                         bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF),
312                         bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF)
313                 )
314                 if self[3] < 32 then
315                         str = str .. "/" .. self[3]
316                 end
317         elseif self:is6() then
318                 str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) )
319                 if self[3] < 128 then
320                         str = str .. "/" .. self[3]
321                 end
322         end
323         return str
324 end
325
326 --- Test weather the value of the instance is lower then the given address.
327 -- This function will throw an exception if the given address has a different
328 -- family than this instance.
329 -- @param addr  A luci.ip.cidr instance to compare against
330 -- @return              Boolean indicating weather this instance is lower
331 -- @see                 higher
332 -- @see                 equal
333 function cidr.lower( self, addr )
334         assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
335         for i = 1, #self[2] do
336                 if self[2][i] ~= addr[2][i] then
337                         return self[2][i] < addr[2][i]
338                 end
339         end
340         return false
341 end
342
343 --- Test weather the value of the instance is higher then the given address.
344 -- This function will throw an exception if the given address has a different
345 -- family than this instance.
346 -- @param addr  A luci.ip.cidr instance to compare against
347 -- @return              Boolean indicating weather this instance is higher
348 -- @see                 lower
349 -- @see                 equal
350 function cidr.higher( self, addr )
351         assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
352         for i = 1, #self[2] do
353                 if self[2][i] ~= addr[2][i] then
354                         return self[2][i] > addr[2][i]
355                 end
356         end
357         return false
358 end
359
360 --- Test weather the value of the instance is uequal to the given address.
361 -- This function will throw an exception if the given address is a different
362 -- family than this instance.
363 -- @param addr  A luci.ip.cidr instance to compare against
364 -- @return              Boolean indicating weather this instance is equal
365 -- @see                 lower
366 -- @see                 higher
367 function cidr.equal( self, addr )
368         assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
369         for i = 1, #self[2] do
370                 if self[2][i] ~= addr[2][i] then
371                         return false
372                 end
373         end
374         return true
375 end
376
377 --- Return the prefix length of this CIDR instance.
378 -- @return      Prefix length in bit
379 function cidr.prefix( self, mask )
380         local prefix = self[3]
381
382         if mask then
383                 prefix = 0
384                 local stop = false
385                 local obj = self:is4() and IPv4(mask) or IPv6(mask)
386
387                 if not obj then
388                         return nil
389                 end
390
391                 for i, block in ipairs(obj[2]) do
392                         local pos = bit.lshift(1, 15)
393                         for i=15, 0, -1 do
394                                 if bit.band(block, pos) == pos then
395                                         if not stop then
396                                                 prefix = prefix + 1
397                                         else
398                                                 return nil
399                                         end
400                                 else
401                                         stop = true
402                                 end
403                                 pos = bit.rshift(pos, 1)
404                         end
405                 end
406         end
407
408         return prefix
409 end
410
411 --- Return a corresponding CIDR representing the network address of this
412 -- instance.
413 -- @param bits  Override prefix length of this instance (optional)
414 -- @return              CIDR instance containing the network address
415 -- @see                 host
416 -- @see                 mask
417 function cidr.network( self, bits )
418         local data = { }
419         bits = bits or self[3]
420
421         for i = 1, math.floor( bits / 16 ) do
422                 table.insert( data, self[2][i] )
423         end
424
425         if #data < #self[2] then
426                 table.insert( data, bit.band( self[2][1+#data], __mask16(bits) ) )
427
428                 for i = #data + 1, #self[2] do
429                         table.insert( data, 0 )
430                 end
431         end
432
433         return __bless({ self[1], data, __length(self[1]) })
434 end
435
436 --- Return a corresponding CIDR representing the host address of this
437 -- instance. This is intended to extract the host address from larger subnet.
438 -- @return              CIDR instance containing the network address
439 -- @see                 network
440 -- @see                 mask
441 function cidr.host( self )
442         return __bless({ self[1], data, __length(self[1]) })
443 end
444
445 --- Return a corresponding CIDR representing the netmask of this instance.
446 -- @param bits  Override prefix length of this instance (optional)
447 -- @return              CIDR instance containing the netmask
448 -- @see                 network
449 -- @see                 host
450 function cidr.mask( self, bits )
451         local data = { }
452         bits = bits or self[3]
453
454         for i = 1, math.floor( bits / 16 ) do
455                 table.insert( data, 0xFFFF )
456         end
457
458         if #data < #self[2] then
459                 table.insert( data, __mask16(bits) )
460
461                 for i = #data + 1, #self[2] do
462                         table.insert( data, 0 )
463                 end
464         end
465
466         return __bless({ self[1], data, __length(self[1]) })
467 end
468
469 --- Test weather this instance fully contains the given CIDR instance.
470 -- @param addr  CIDR instance to test against
471 -- @return              Boolean indicating weather this instance contains the given CIDR
472 function cidr.contains( self, addr )
473         assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
474
475         if self:prefix() <= addr:prefix() then
476                 return self:network() == addr:network(self:prefix())
477         end
478
479         return false
480 end
481
482 --- Add specified amount of hosts to this instance.
483 -- @param amount        Number of hosts to add to this instance
484 -- @return                      CIDR representing the new address or nil on overflow error
485 -- @see                         sub
486 function cidr.add( self, amount )
487         local shorts = { bit.rshift(amount, 16), bit.band(amount, 0xFFFF) }
488         local data   = { unpack(self[2]) }
489
490         for pos = #data, 1, -1 do
491                 local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
492                 if ( data[pos] + add ) > 0xFFFF then
493                         data[pos] = ( data[pos] + add ) % 0xFFFF
494                         if pos > 1 then
495                                 data[pos-1] = data[pos-1] + ( add - data[pos] )
496                         else
497                                 return nil
498                         end
499                 else
500                         data[pos] = data[pos] + add
501                 end
502         end
503
504         return __bless({ self[1], data, self[3] })
505 end
506
507 --- Substract specified amount of hosts from this instance.
508 -- @param amount        Number of hosts to substract from this instance
509 -- @return                      CIDR representing the new address or nil on underflow error
510 -- @see                         add
511 function cidr.sub( self, amount )
512         local shorts = { bit.rshift(amount, 16), bit.band(amount, 0xFFFF) }
513         local data   = { unpack(self[2]) }
514
515         for pos = #data, 1, -1 do
516                 local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
517                 if ( data[pos] - sub ) < 0 then
518                         data[pos] = ( sub - data[pos] ) % 0xFFFF
519                         if pos > 1 then
520                                 data[pos-1] = data[pos-1] - ( sub + data[pos] )
521                         else
522                                 return nil
523                         end
524                 else
525                         data[pos] = data[pos] - sub
526                 end
527         end
528
529         return __bless({ self[1], data, self[3] })
530 end