1 -- Copyright 2008 Steven Barth <steven@midlink.org>
2 -- Licensed to the public under the Apache License 2.0.
4 local io = require "io"
5 local math = require "math"
6 local table = require "table"
7 local debug = require "debug"
8 local ldebug = require "luci.debug"
9 local string = require "string"
10 local coroutine = require "coroutine"
11 local tparser = require "luci.template.parser"
12 local json = require "luci.jsonc"
14 local _ubus = require "ubus"
15 local _ubus_connection = nil
17 local getmetatable, setmetatable = getmetatable, setmetatable
18 local rawget, rawset, unpack = rawget, rawset, unpack
19 local tostring, type, assert = tostring, type, assert
20 local ipairs, pairs, next, loadstring = ipairs, pairs, next, loadstring
21 local require, pcall, xpcall = require, pcall, xpcall
22 local collectgarbage, get_memory_limit = collectgarbage, get_memory_limit
27 -- Pythonic string formatting extension
29 getmetatable("").__mod = function(a, b)
32 elseif type(b) == "table" then
33 for k, _ in pairs(b) do if type(b[k]) == "userdata" then b[k] = tostring(b[k]) end end
34 return a:format(unpack(b))
36 if type(b) == "userdata" then b = tostring(b) end
43 -- Class helper routines
46 -- Instantiates a class
47 local function _instantiate(class, ...)
48 local inst = setmetatable({}, {__index = class})
57 -- The class object can be instantiated by calling itself.
58 -- Any class functions or shared parameters can be attached to this object.
59 -- Attaching a table to the class object makes this table shared between
60 -- all instances of this class. For object parameters use the __init__ function.
61 -- Classes can inherit member functions and values from a base class.
62 -- Class can be instantiated by calling them. All parameters will be passed
63 -- to the __init__ function of this class - if such a function exists.
64 -- The __init__ function must be used to set any object parameters that are not shared
65 -- with other objects of this class. Any return values will be ignored.
67 return setmetatable({}, {
68 __call = _instantiate,
73 function instanceof(object, class)
74 local meta = getmetatable(object)
75 while meta and meta.__index do
76 if meta.__index == class then
79 meta = getmetatable(meta.__index)
86 -- Scope manipulation routines
92 __index = function(self, key)
93 local t = rawget(self, coxpt[coroutine.running()]
94 or coroutine.running() or 0)
98 __newindex = function(self, key, value)
99 local c = coxpt[coroutine.running()] or coroutine.running() or 0
100 local r = rawget(self, c)
102 rawset(self, c, { [key] = value })
109 -- the current active coroutine. A thread local store is private a table object
110 -- whose values can't be accessed from outside of the running coroutine.
111 function threadlocal(tbl)
112 return setmetatable(tbl or {}, tl_meta)
117 -- Debugging routines
121 return io.stderr:write(tostring(obj) .. "\n")
124 function dumptable(t, maxdepth, i, seen)
126 seen = seen or setmetatable({}, {__mode="k"})
128 for k,v in pairs(t) do
129 perror(string.rep("\t", i) .. tostring(k) .. "\t" .. tostring(v))
130 if type(v) == "table" and (not maxdepth or i < maxdepth) then
133 dumptable(v, maxdepth, i+1, seen)
135 perror(string.rep("\t", i) .. "*** RECURSION ***")
143 -- String and data manipulation routines
146 function pcdata(value)
147 return value and tparser.pcdata(tostring(value))
150 function striptags(value)
151 return value and tparser.striptags(tostring(value))
154 -- containing the resulting substrings. The optional max parameter specifies
155 -- the number of bytes to process, regardless of the actual length of the given
156 -- string. The optional last parameter, regex, specifies whether the separator
157 -- sequence is interpreted as regular expression.
158 -- pattern as regular expression (optional, default is false)
159 function split(str, pat, max, regex)
179 local s, e = str:find(pat, c, not regex)
181 if s and max < 0 then
184 t[#t+1] = str:sub(c, s and s - 1)
186 c = e and e + 1 or #str + 1
187 until not s or max < 0
193 return (str:gsub("^%s*(.-)%s*$", "%1"))
196 function cmatch(str, pat)
198 for _ in str:gmatch(pat) do count = count + 1 end
202 -- one token per invocation, the tokens are separated by whitespace. If the
203 -- input value is a table, it is transformed into a string first. A nil value
204 -- will result in a valid interator which aborts with the first invocation.
206 if type(v) == "table" then
213 elseif type(v) == "number" or type(v) == "boolean" then
222 elseif type(v) == "userdata" or type(v) == "string" then
223 return tostring(v):gmatch("%S+")
226 return function() end
229 -- value or 0 if the unit is unknown. Upper- or lower case is irrelevant.
230 -- Recognized units are:
231 -- o "y" - one year (60*60*24*366)
232 -- o "m" - one month (60*60*24*31)
233 -- o "w" - one week (60*60*24*7)
234 -- o "d" - one day (60*60*24)
235 -- o "h" - one hour (60*60)
236 -- o "min" - one minute (60)
237 -- o "kb" - one kilobyte (1024)
238 -- o "mb" - one megabyte (1024*1024)
239 -- o "gb" - one gigabyte (1024*1024*1024)
240 -- o "kib" - one si kilobyte (1000)
241 -- o "mib" - one si megabyte (1000*1000)
242 -- o "gib" - one si gigabyte (1000*1000*1000)
243 function parse_units(ustr)
250 y = 60 * 60 * 24 * 366,
251 m = 60 * 60 * 24 * 31,
252 w = 60 * 60 * 24 * 7,
260 gb = 1024 * 1024 * 1024,
262 -- storage sizes (si)
265 gib = 1000 * 1000 * 1000
268 -- parse input string
269 for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
271 local num = spec:gsub("[^0-9%.]+$","")
272 local spn = spec:gsub("^[0-9%.]+", "")
274 if map[spn] or map[spn:sub(1,1)] then
275 val = val + num * ( map[spn] or map[spn:sub(1,1)] )
285 -- also register functions above in the central string class for convenience
286 string.pcdata = pcdata
287 string.striptags = striptags
290 string.cmatch = cmatch
291 string.parse_units = parse_units
294 function append(src, ...)
295 for i, a in ipairs({...}) do
296 if type(a) == "table" then
297 for j, v in ipairs(a) do
307 function combine(...)
308 return append({}, ...)
311 function contains(table, value)
312 for k, v in pairs(table) do
320 -- Both table are - in fact - merged together.
321 function update(t, updates)
322 for k, v in pairs(updates) do
330 for k, _ in kspairs(t) do
337 function clone(object, deep)
340 for k, v in pairs(object) do
341 if deep and type(v) == "table" then
347 return setmetatable(copy, getmetatable(object))
352 return setmetatable({}, { __index =
354 return rawget(tbl, key)
355 or rawget(rawset(tbl, key, dtable()), key)
361 -- Serialize the contents of a table value.
362 function _serialize_table(t, seen)
363 assert(not seen[t], "Recursion detected.")
370 for k, v in pairs(t) do
371 if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then
372 k = serialize_data(k, seen)
373 v = serialize_data(v, seen)
374 data = data .. ( #data > 0 and ", " or "" ) ..
375 '[' .. k .. '] = ' .. v
382 local v = serialize_data(t[i], seen)
383 idata = idata .. ( #idata > 0 and ", " or "" ) .. v
386 return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data
389 -- with loadstring().
390 function serialize_data(val, seen)
391 seen = seen or setmetatable({}, {__mode="k"})
395 elseif type(val) == "number" then
397 elseif type(val) == "string" then
399 elseif type(val) == "boolean" then
400 return val and "true" or "false"
401 elseif type(val) == "function" then
402 return "loadstring(%q)" % get_bytecode(val)
403 elseif type(val) == "table" then
404 return "{ " .. _serialize_table(val, seen) .. " }"
406 return '"[unhandled data type:' .. type(val) .. ']"'
410 function restore_data(str)
411 return loadstring("return " .. str)()
416 -- Byte code manipulation routines
419 -- will be stripped before it is returned.
420 function get_bytecode(val)
423 if type(val) == "function" then
424 code = string.dump(val)
426 code = string.dump( loadstring( "return " .. serialize_data(val) ) )
429 return code -- and strip_bytecode(code)
432 -- numbers and debugging numbers will be discarded. Original version by
433 -- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
434 function strip_bytecode(code)
435 local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
438 subint = function(code, i, l)
441 val = val * 256 + code:byte(i + n - 1)
446 subint = function(code, i, l)
449 val = val * 256 + code:byte(i + n - 1)
455 local function strip_function(code)
456 local count, offset = subint(code, 1, size)
457 local stripped = { string.rep("\0", size) }
458 local dirty = offset + count
459 offset = offset + count + int * 2 + 4
460 offset = offset + int + subint(code, offset, int) * ins
461 count, offset = subint(code, offset, int)
464 t, offset = subint(code, offset, 1)
468 offset = offset + size + subint(code, offset, size)
470 offset = offset + num
471 elseif t == 254 or t == 9 then
472 offset = offset + lnum
475 count, offset = subint(code, offset, int)
476 stripped[#stripped+1] = code:sub(dirty, offset - 1)
478 local proto, off = strip_function(code:sub(offset, -1))
479 stripped[#stripped+1] = proto
480 offset = offset + off - 1
482 offset = offset + subint(code, offset, int) * int + int
483 count, offset = subint(code, offset, int)
485 offset = offset + subint(code, offset, size) + size + int * 2
487 count, offset = subint(code, offset, int)
489 offset = offset + subint(code, offset, size) + size
491 stripped[#stripped+1] = string.rep("\0", int * 3)
492 return table.concat(stripped), offset
495 return code:sub(1,12) .. strip_function(code:sub(13,-1))
500 -- Sorting iterator functions
503 function _sortiter( t, f )
507 for k, v in pairs(t) do
513 table.sort( keys, f )
517 if _pos <= #keys then
518 return keys[_pos], t[keys[_pos]], _pos
523 -- the provided callback function.
525 return _sortiter( t, f )
528 -- The table pairs are sorted by key.
530 return _sortiter( t )
533 -- The table pairs are sorted by value.
535 return _sortiter( t, function (a,b) return t[a] < t[b] end )
540 -- System utility functions
544 return string.byte(string.dump(function() end), 7) == 0
547 function exec(command)
548 local pp = io.popen(command)
549 local data = pp:read("*a")
555 function execi(command)
556 local pp = io.popen(command)
558 return pp and function()
559 local line = pp:read()
570 function execl(command)
571 local pp = io.popen(command)
577 if (line == nil) then break end
585 function ubus(object, method, data)
586 if not _ubus_connection then
587 _ubus_connection = _ubus.connect()
588 assert(_ubus_connection, "Unable to establish ubus connection")
591 if object and method then
592 if type(data) ~= "table" then
595 return _ubus_connection:call(object, method, data)
597 return _ubus_connection:signatures(object)
599 return _ubus_connection:objects()
603 function serialize_json(x, cb)
604 local js = json.stringify(x)
605 if type(cb) == "function" then
614 return require "nixio.fs".dirname(ldebug.__file__)
619 -- Coroutine safe xpcall and pcall versions modified for Luci
621 -- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
623 -- Copyright © 2005 Kepler Project.
624 -- Permission is hereby granted, free of charge, to any person obtaining a
625 -- copy of this software and associated documentation files (the "Software"),
626 -- to deal in the Software without restriction, including without limitation
627 -- the rights to use, copy, modify, merge, publish, distribute, sublicense,
628 -- and/or sell copies of the Software, and to permit persons to whom the
629 -- Software is furnished to do so, subject to the following conditions:
631 -- The above copyright notice and this permission notice shall be
632 -- included in all copies or substantial portions of the Software.
634 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
635 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
636 -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
637 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
638 -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
639 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
640 -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
642 local performResume, handleReturnValue
643 local oldpcall, oldxpcall = pcall, xpcall
645 setmetatable(coxpt, {__mode = "kv"})
647 -- Identity function for copcall
648 local function copcall_id(trace, ...)
652 -- values of either the function or the error handler
653 function coxpcall(f, err, ...)
654 local res, co = oldpcall(coroutine.create, f)
657 local newf = function() return f(unpack(params)) end
658 co = coroutine.create(newf)
660 local c = coroutine.running()
661 coxpt[co] = coxpt[c] or c or 0
663 return performResume(err, co, ...)
666 -- values of the function or the error object
667 function copcall(f, ...)
668 return coxpcall(f, copcall_id, ...)
671 -- Handle return value of protected call
672 function handleReturnValue(err, co, status, ...)
674 return false, err(debug.traceback(co, (...)), ...)
677 if coroutine.status(co) ~= 'suspended' then
681 return performResume(err, co, coroutine.yield(...))
684 -- Resume execution of protected function call
685 function performResume(err, co, ...)
686 return handleReturnValue(err, co, coroutine.resume(co, ...))