libs/core: remove various uses of global vars in 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, i
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 local i
301
302 for i = 1, (len/4) - #hex do tmp = tmp .. '0' end
303
304 if swap and LITTLE_ENDIAN then
305 for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end
306 else
307 tmp = tmp .. hex
308 end
309
310 hex = tmp
311
312 for i = 1, ( len / 4 ), 4 do
313 local n = tonumber( hex:sub( i, i+3 ), 16 )
314 if n then
315 data[#data+1] = n
316 else
317 return nil
318 end
319 end
320
321 return __bless({ family, data, prefix })
322 end
323
324
325 --- LuCI IP Library / CIDR instances
326 -- @class module
327 -- @cstyle instance
328 -- @name luci.ip.cidr
329 cidr = util.class()
330
331 --- Test whether the instance is a IPv4 address.
332 -- @return Boolean indicating a IPv4 address type
333 -- @see cidr.is6
334 function cidr.is4( self )
335 return self[1] == FAMILY_INET4
336 end
337
338 --- Test whether this instance is an IPv4 RFC1918 private address
339 -- @return Boolean indicating whether this instance is an RFC1918 address
340 function cidr.is4rfc1918( self )
341 if self[1] == FAMILY_INET4 then
342 return ((self[2][1] >= 0x0A00) and (self[2][1] <= 0x0AFF)) or
343 ((self[2][1] >= 0xAC10) and (self[2][1] <= 0xAC1F)) or
344 (self[2][1] == 0xC0A8)
345 end
346 return false
347 end
348
349 --- Test whether this instance is an IPv4 link-local address (Zeroconf)
350 -- @return Boolean indicating whether this instance is IPv4 link-local
351 function cidr.is4linklocal( self )
352 if self[1] == FAMILY_INET4 then
353 return (self[2][1] == 0xA9FE)
354 end
355 return false
356 end
357
358 --- Test whether the instance is a IPv6 address.
359 -- @return Boolean indicating a IPv6 address type
360 -- @see cidr.is4
361 function cidr.is6( self )
362 return self[1] == FAMILY_INET6
363 end
364
365 --- Test whether this instance is an IPv6 link-local address
366 -- @return Boolean indicating whether this instance is IPv6 link-local
367 function cidr.is6linklocal( self )
368 if self[1] == FAMILY_INET6 then
369 return (self[2][1] >= 0xFE80) and (self[2][1] <= 0xFEBF)
370 end
371 return false
372 end
373
374 --- Return a corresponding string representation of the instance.
375 -- If the prefix length is lower then the maximum possible prefix length for the
376 -- corresponding address type then the address is returned in CIDR notation,
377 -- otherwise the prefix will be left out.
378 function cidr.string( self )
379 local str
380 if self:is4() then
381 str = string.format(
382 "%d.%d.%d.%d",
383 bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF),
384 bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF)
385 )
386 if self[3] < 32 then
387 str = str .. "/" .. self[3]
388 end
389 elseif self:is6() then
390 str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) )
391 if self[3] < 128 then
392 str = str .. "/" .. self[3]
393 end
394 end
395 return str
396 end
397
398 --- Test whether the value of the instance is lower then the given address.
399 -- This function will throw an exception if the given address has a different
400 -- family than this instance.
401 -- @param addr A luci.ip.cidr instance to compare against
402 -- @return Boolean indicating whether this instance is lower
403 -- @see cidr.higher
404 -- @see cidr.equal
405 function cidr.lower( self, addr )
406 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
407 local i
408 for i = 1, #self[2] do
409 if self[2][i] ~= addr[2][i] then
410 return self[2][i] < addr[2][i]
411 end
412 end
413 return false
414 end
415
416 --- Test whether the value of the instance is higher then the given address.
417 -- This function will throw an exception if the given address has a different
418 -- family than this instance.
419 -- @param addr A luci.ip.cidr instance to compare against
420 -- @return Boolean indicating whether this instance is higher
421 -- @see cidr.lower
422 -- @see cidr.equal
423 function cidr.higher( self, addr )
424 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
425 local i
426 for i = 1, #self[2] do
427 if self[2][i] ~= addr[2][i] then
428 return self[2][i] > addr[2][i]
429 end
430 end
431 return false
432 end
433
434 --- Test whether the value of the instance is equal to the given address.
435 -- This function will throw an exception if the given address is a different
436 -- family than this instance.
437 -- @param addr A luci.ip.cidr instance to compare against
438 -- @return Boolean indicating whether this instance is equal
439 -- @see cidr.lower
440 -- @see cidr.higher
441 function cidr.equal( self, addr )
442 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
443 local i
444 for i = 1, #self[2] do
445 if self[2][i] ~= addr[2][i] then
446 return false
447 end
448 end
449 return true
450 end
451
452 --- Return the prefix length of this CIDR instance.
453 -- @param mask Override instance prefix with given netmask (optional)
454 -- @return Prefix length in bit
455 function cidr.prefix( self, mask )
456 local prefix = self[3]
457
458 if mask then
459 prefix = 0
460
461 local stop = false
462 local obj = type(mask) ~= "table"
463 and ( self:is4() and IPv4(mask) or IPv6(mask) ) or mask
464
465 if not obj then return nil end
466
467 local _, word
468 for _, word in ipairs(obj[2]) do
469 if word == 0xFFFF then
470 prefix = prefix + 16
471 else
472 local bitmask = bit.lshift(1, 15)
473 while bit.band(word, bitmask) == bitmask do
474 prefix = prefix + 1
475 bitmask = bit.lshift(1, 15 - (prefix % 16))
476 end
477
478 break
479 end
480 end
481 end
482
483 return prefix
484 end
485
486 --- Return a corresponding CIDR representing the network address of this
487 -- instance.
488 -- @param bits Override prefix length of this instance (optional)
489 -- @return CIDR instance containing the network address
490 -- @see cidr.host
491 -- @see cidr.broadcast
492 -- @see cidr.mask
493 function cidr.network( self, bits )
494 local data = { }
495 bits = bits or self[3]
496
497 local i
498 for i = 1, math.floor( bits / 16 ) do
499 data[#data+1] = self[2][i]
500 end
501
502 if #data < #self[2] then
503 data[#data+1] = bit.band( self[2][1+#data], __mask16(bits) )
504
505 for i = #data + 1, #self[2] do
506 data[#data+1] = 0
507 end
508 end
509
510 return __bless({ self[1], data, __maxlen(self[1]) })
511 end
512
513 --- Return a corresponding CIDR representing the host address of this
514 -- instance. This is intended to extract the host address from larger subnet.
515 -- @return CIDR instance containing the network address
516 -- @see cidr.network
517 -- @see cidr.broadcast
518 -- @see cidr.mask
519 function cidr.host( self )
520 return __bless({ self[1], self[2], __maxlen(self[1]) })
521 end
522
523 --- Return a corresponding CIDR representing the netmask of this instance.
524 -- @param bits Override prefix length of this instance (optional)
525 -- @return CIDR instance containing the netmask
526 -- @see cidr.network
527 -- @see cidr.host
528 -- @see cidr.broadcast
529 function cidr.mask( self, bits )
530 local data = { }
531 bits = bits or self[3]
532
533 for i = 1, math.floor( bits / 16 ) do
534 data[#data+1] = 0xFFFF
535 end
536
537 if #data < #self[2] then
538 data[#data+1] = __mask16(bits)
539
540 for i = #data + 1, #self[2] do
541 data[#data+1] = 0
542 end
543 end
544
545 return __bless({ self[1], data, __maxlen(self[1]) })
546 end
547
548 --- Return CIDR containing the broadcast address of this instance.
549 -- @return CIDR instance containing the netmask, always nil for IPv6
550 -- @see cidr.network
551 -- @see cidr.host
552 -- @see cidr.mask
553 function cidr.broadcast( self )
554 -- IPv6 has no broadcast addresses (XXX: assert() instead?)
555 if self[1] == FAMILY_INET4 then
556 local data = { unpack(self[2]) }
557 local offset = math.floor( self[3] / 16 ) + 1
558
559 if offset <= #data then
560 data[offset] = bit.bor( data[offset], __not16(self[3]) )
561 for i = offset + 1, #data do data[i] = 0xFFFF end
562
563 return __bless({ self[1], data, __maxlen(self[1]) })
564 end
565 end
566 end
567
568 --- Test whether this instance fully contains the given CIDR instance.
569 -- @param addr CIDR instance to test against
570 -- @return Boolean indicating whether this instance contains the given CIDR
571 function cidr.contains( self, addr )
572 assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" )
573
574 if self:prefix() <= addr:prefix() then
575 return self:network() == addr:network(self:prefix())
576 end
577
578 return false
579 end
580
581 --- Add specified amount of hosts to this instance.
582 -- @param amount Number of hosts to add to this instance
583 -- @param inplace Boolen indicating whether to alter values inplace (optional)
584 -- @return CIDR representing the new address or nil on overflow error
585 -- @see cidr.sub
586 function cidr.add( self, amount, inplace )
587 local pos
588 local data = { unpack(self[2]) }
589 local shorts = __array16( amount, self[1] )
590
591 for pos = #data, 1, -1 do
592 local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
593 if ( data[pos] + add ) > 0xFFFF then
594 data[pos] = ( data[pos] + add ) % 0xFFFF
595 if pos > 1 then
596 data[pos-1] = data[pos-1] + ( add - data[pos] )
597 else
598 return nil
599 end
600 else
601 data[pos] = data[pos] + add
602 end
603 end
604
605 if inplace then
606 self[2] = data
607 return self
608 else
609 return __bless({ self[1], data, self[3] })
610 end
611 end
612
613 --- Substract specified amount of hosts from this instance.
614 -- @param amount Number of hosts to substract from this instance
615 -- @param inplace Boolen indicating whether to alter values inplace (optional)
616 -- @return CIDR representing the new address or nil on underflow error
617 -- @see cidr.add
618 function cidr.sub( self, amount, inplace )
619 local pos
620 local data = { unpack(self[2]) }
621 local shorts = __array16( amount, self[1] )
622
623 for pos = #data, 1, -1 do
624 local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0
625 if ( data[pos] - sub ) < 0 then
626 data[pos] = ( sub - data[pos] ) % 0xFFFF
627 if pos > 1 then
628 data[pos-1] = data[pos-1] - ( sub + data[pos] )
629 else
630 return nil
631 end
632 else
633 data[pos] = data[pos] - sub
634 end
635 end
636
637 if inplace then
638 self[2] = data
639 return self
640 else
641 return __bless({ self[1], data, self[3] })
642 end
643 end
644
645 --- Return CIDR containing the lowest available host address within this subnet.
646 -- @return CIDR containing the host address, nil if subnet is too small
647 -- @see cidr.maxhost
648 function cidr.minhost( self )
649 if self[3] <= __sublen(self[1]) then
650 -- 1st is Network Address in IPv4 and Subnet-Router Anycast Adresse in IPv6
651 return self:network():add(1, true)
652 end
653 end
654
655 --- Return CIDR containing the highest available host address within the subnet.
656 -- @return CIDR containing the host address, nil if subnet is too small
657 -- @see cidr.minhost
658 function cidr.maxhost( self )
659 if self[3] <= __sublen(self[1]) then
660 local i
661 local data = { unpack(self[2]) }
662 local offset = math.floor( self[3] / 16 ) + 1
663
664 data[offset] = bit.bor( data[offset], __not16(self[3]) )
665 for i = offset + 1, #data do data[i] = 0xFFFF end
666 data = __bless({ self[1], data, __maxlen(self[1]) })
667
668 -- Last address in reserved for Broadcast Address in IPv4
669 if data[1] == FAMILY_INET4 then data:sub(1, true) end
670
671 return data
672 end
673 end