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