luci-0.8: merge r3809-r3822
[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 = x
69 end
70
71 assert( list, "Invalid operand" )
72
73 return list
74 end
75
76 local function __mask16(bits)
77 return bit.lshift( bit.rshift( 0xFFFF, 16 - bits % 16 ), 16 - bits % 16 )
78 end
79
80 local function __not16(bits)
81 return bit.band( bit.bnot( __mask16(bits) ), 0xFFFF )
82 end
83
84 local function __maxlen(family)
85 return ( family == FAMILY_INET4 ) and 32 or 128
86 end
87
88 local function __sublen(family)
89 return ( family == FAMILY_INET4 ) and 30 or 127
90 end
91
92
93 --- Convert given short value to network byte order on little endian hosts
94 -- @param x Unsigned integer value between 0x0000 and 0xFFFF
95 -- @return Byte-swapped value
96 -- @see htonl
97 -- @see ntohs
98 function htons(x)
99 if LITTLE_ENDIAN then
100 return bit.bor(
101 bit.rshift( x, 8 ),
102 bit.band( bit.lshift( x, 8 ), 0xFF00 )
103 )
104 else
105 return x
106 end
107 end
108
109 --- Convert given long value to network byte order on little endian hosts
110 -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
111 -- @return Byte-swapped value
112 -- @see htons
113 -- @see ntohl
114 function htonl(x)
115 if LITTLE_ENDIAN then
116 return bit.bor(
117 bit.lshift( htons( bit.band( x, 0xFFFF ) ), 16 ),
118 htons( bit.rshift( x, 16 ) )
119 )
120 else
121 return x
122 end
123 end
124
125 --- Convert given short value to host byte order on little endian hosts
126 -- @class function
127 -- @name ntohs
128 -- @param x Unsigned integer value between 0x0000 and 0xFFFF
129 -- @return Byte-swapped value
130 -- @see htonl
131 -- @see ntohs
132 ntohs = htons
133
134 --- Convert given short value to host byte order on little endian hosts
135 -- @class function
136 -- @name ntohl
137 -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF
138 -- @return Byte-swapped value
139 -- @see htons
140 -- @see ntohl
141 ntohl = htonl
142
143
144 --- Parse given IPv4 address in dotted quad or CIDR notation. If an optional
145 -- netmask is given as second argument and the IP address is encoded in CIDR
146 -- notation then the netmask parameter takes precedence. If neither a CIDR
147 -- encoded prefix nor a netmask parameter is given, then a prefix length of
148 -- 32 bit is assumed.
149 -- @param address IPv4 address in dotted quad or CIDR notation
150 -- @param netmask IPv4 netmask in dotted quad notation (optional)
151 -- @return luci.ip.cidr instance or nil if given address was invalid
152 -- @see IPv6
153 -- @see Hex
154 function IPv4(address, netmask)
155 address = address or "0.0.0.0/0"
156
157 local obj = __bless({ FAMILY_INET4 })
158
159 local data = {}
160 local prefix = address:match("/(.+)")
161 address = address:gsub("/.+","")
162
163 if netmask then
164 prefix = obj:prefix(netmask)
165 elseif prefix then
166 prefix = tonumber(prefix)
167 if not prefix or prefix < 0 or prefix > 32 then return nil end
168 else
169 prefix = 32
170 end
171
172 local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
173
174 b1 = tonumber(b1)
175 b2 = tonumber(b2)
176 b3 = tonumber(b3)
177 b4 = tonumber(b4)
178
179 if b1 and b1 <= 255 and
180 b2 and b2 <= 255 and
181 b3 and b3 <= 255 and
182 b4 and b4 <= 255 and
183 prefix
184 then
185 table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 })
186 table.insert(obj, prefix)
187 return obj
188 end
189 end
190
191 --- Parse given IPv6 address in full, compressed, mixed or CIDR notation.
192 -- If an optional netmask is given as second argument and the IP address is
193 -- encoded in CIDR notation then the netmask parameter takes precedence.
194 -- If neither a CIDR encoded prefix nor a netmask parameter is given, then a
195 -- prefix length of 128 bit is assumed.
196 -- @param address IPv6 address in full/compressed/mixed or CIDR notation
197 -- @param netmask IPv6 netmask in full/compressed/mixed notation (optional)
198 -- @return luci.ip.cidr instance or nil if given address was invalid
199 -- @see IPv4
200 -- @see Hex
201 function IPv6(address, netmask)
202 address = address or "::/0"
203
204 local obj = __bless({ FAMILY_INET6 })
205
206 local data = {}
207 local prefix = address:match("/(.+)")
208 address = address:gsub("/.+","")
209
210 if netmask then
211 prefix = obj:prefix(netmask)
212 elseif prefix then
213 prefix = tonumber(prefix)
214 if not prefix or prefix < 0 or prefix > 128 then return nil end
215 else
216 prefix = 128
217 end
218
219 local borderl = address:sub(1, 1) == ":" and 2 or 1
220 local borderh, zeroh, chunk, block
221
222 if #address > 45 then return nil end
223
224 repeat
225 borderh = address:find(":", borderl, true)
226 if not borderh then break end
227
228 block = tonumber(address:sub(borderl, borderh - 1), 16)
229 if block and block <= 0xFFFF then
230 table.insert(data, block)
231 else
232 if zeroh or borderh - borderl > 1 then return nil end
233 zeroh = #data + 1
234 end
235
236 borderl = borderh + 1
237 until #data == 7
238
239 chunk = address:sub(borderl)
240 if #chunk > 0 and #chunk <= 4 then
241 block = tonumber(chunk, 16)
242 if not block or block > 0xFFFF then return nil end
243
244 table.insert(data, block)
245 elseif #chunk > 4 then
246 if #data == 7 or #chunk > 15 then return nil end
247 borderl = 1
248 for i=1, 4 do
249 borderh = chunk:find(".", borderl, true)
250 if not borderh and i < 4 then return nil end
251 borderh = borderh and borderh - 1
252
253 block = tonumber(chunk:sub(borderl, borderh))
254 if not block or block > 255 then return nil end
255
256 if i == 1 or i == 3 then
257 table.insert(data, block * 256)
258 else
259 data[#data] = data[#data] + block
260 end
261
262 borderl = borderh and borderh + 2
263 end
264 end
265
266 if zeroh then
267 if #data == 8 then return nil end
268 while #data < 8 do
269 table.insert(data, zeroh, 0)
270 end
271 end
272
273 if #data == 8 and prefix then
274 table.insert(obj, data)
275 table.insert(obj, prefix)
276 return obj
277 end
278 end
279
280 --- Transform given hex-encoded value to luci.ip.cidr instance of specified
281 -- address family.
282 -- @param hex String containing hex encoded value
283 -- @param prefix Prefix length of CIDR instance (optional, default is 32/128)
284 -- @param family Address family, either luci.ip.FAMILY_INET4 or FAMILY_INET6
285 -- @param swap Bool indicating whether to swap byteorder on low endian host
286 -- @return luci.ip.cidr instance or nil if given value was invalid
287 -- @see IPv4
288 -- @see IPv6
289 function Hex( hex, prefix, family, swap )
290 family = ( family ~= nil ) and family or FAMILY_INET4
291 swap = ( swap == nil ) and true or swap
292 prefix = prefix or __maxlen(family)
293
294 local len = __maxlen(family)
295 local tmp = ""
296 local data = { }
297
298 for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
299
300 if swap and LITTLE_ENDIAN then
301 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
302 else
303 tmp = tmp .. hex
304 end
305
306 hex = tmp
307
308 for i = 1, ( len / 4 ), 4 do
309 local n = tonumber( hex:sub( i, i+3 ), 16 )
310 if n then
311 table.insert( data, n )
312 else
313 return nil
314 end
315 end
316
317 return __bless({ family, data, prefix })
318 end
319
320
321 --- LuCI IP Library / CIDR instances
322 -- @class module
323 -- @cstyle instance
324 -- @name luci.ip.cidr
325 cidr = luci.util.class()
326
327 --- Test whether the instance is a IPv4 address.
328 -- @return Boolean indicating a IPv4 address type
329 -- @see cidr.is6
330 function cidr.is4( self )
331 return self[1] == FAMILY_INET4
332 end
333
334 --- Test whether the instance is a IPv6 address.
335 -- @return Boolean indicating a IPv6 address type
336 -- @see cidr.is4
337 function cidr.is6( self )
338 return self[1] == FAMILY_INET6
339 end
340
341 --- Return a corresponding string representation of the instance.
342 -- If the prefix length is lower then the maximum possible prefix length for the
343 -- corresponding address type then the address is returned in CIDR notation,
344 -- otherwise the prefix will be left out.
345 function cidr.string( self )
346 local str
347 if self:is4() then
348 str = string.format(
349 "%d.%d.%d.%d",
350 bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF),
351 bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF)
352 )
353 if self[3] < 32 then
354 str = str .. "/" .. self[3]
355 end
356 elseif self:is6() then
357 str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) )
358 if self[3] < 128 then
359 str = str .. "/" .. self[3]
360 end
361 end
362 return str
363 end
364
365 --- Test whether the value of the instance is lower then the given address.
366 -- This function will throw an exception if the given address has a different
367 -- family than this instance.
368 -- @param addr A luci.ip.cidr instance to compare against
369 -- @return Boolean indicating whether this instance is lower
370 -- @see cidr.higher
371 -- @see cidr.equal
372 function cidr.lower( self, addr )
373 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
374 for i = 1, #self[2] do
375 if self[2][i] ~= addr[2][i] then
376 return self[2][i] < addr[2][i]
377 end
378 end
379 return false
380 end
381
382 --- Test whether the value of the instance is higher then the given address.
383 -- This function will throw an exception if the given address has a different
384 -- family than this instance.
385 -- @param addr A luci.ip.cidr instance to compare against
386 -- @return Boolean indicating whether this instance is higher
387 -- @see cidr.lower
388 -- @see cidr.equal
389 function cidr.higher( self, addr )
390 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
391 for i = 1, #self[2] do
392 if self[2][i] ~= addr[2][i] then
393 return self[2][i] > addr[2][i]
394 end
395 end
396 return false
397 end
398
399 --- Test whether the value of the instance is equal to the given address.
400 -- This function will throw an exception if the given address is a different
401 -- family than this instance.
402 -- @param addr A luci.ip.cidr instance to compare against
403 -- @return Boolean indicating whether this instance is equal
404 -- @see cidr.lower
405 -- @see cidr.higher
406 function cidr.equal( self, addr )
407 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
408 for i = 1, #self[2] do
409 if self[2][i] ~= addr[2][i] then
410 return false
411 end
412 end
413 return true
414 end
415
416 --- Return the prefix length of this CIDR instance.
417 -- @param mask Override instance prefix with given netmask (optional)
418 -- @return Prefix length in bit
419 function cidr.prefix( self, mask )
420 local prefix = self[3]
421
422 if mask then
423 prefix = 0
424 local stop = false
425 local obj = self:is4() and IPv4(mask) or IPv6(mask)
426
427 if not obj then
428 return nil
429 end
430
431 for i, block in ipairs(obj[2]) do
432 local pos = bit.lshift(1, 15)
433 for i=15, 0, -1 do
434 if bit.band(block, pos) == pos then
435 if not stop then
436 prefix = prefix + 1
437 else
438 return nil
439 end
440 else
441 stop = true
442 end
443 pos = bit.rshift(pos, 1)
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 table.insert( data, self[2][i] )
464 end
465
466 if #data < #self[2] then
467 table.insert( data, bit.band( self[2][1+#data], __mask16(bits) ) )
468
469 for i = #data + 1, #self[2] do
470 table.insert( data, 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 table.insert( data, 0xFFFF )
499 end
500
501 if #data < #self[2] then
502 table.insert( data, __mask16(bits) )
503
504 for i = #data + 1, #self[2] do
505 table.insert( data, 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