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, error = tostring, type, assert, error
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)
34 elseif type(b) == "table" then
36 for k, _ in pairs(b) do if type(b[k]) == "userdata" then b[k] = tostring(b[k]) end end
38 ok, res = pcall(a.format, a, unpack(b))
44 if type(b) == "userdata" then b = tostring(b) end
46 ok, res = pcall(a.format, a, b)
56 -- Class helper routines
59 -- Instantiates a class
60 local function _instantiate(class, ...)
61 local inst = setmetatable({}, {__index = class})
70 -- The class object can be instantiated by calling itself.
71 -- Any class functions or shared parameters can be attached to this object.
72 -- Attaching a table to the class object makes this table shared between
73 -- all instances of this class. For object parameters use the __init__ function.
74 -- Classes can inherit member functions and values from a base class.
75 -- Class can be instantiated by calling them. All parameters will be passed
76 -- to the __init__ function of this class - if such a function exists.
77 -- The __init__ function must be used to set any object parameters that are not shared
78 -- with other objects of this class. Any return values will be ignored.
80 return setmetatable({}, {
81 __call = _instantiate,
86 function instanceof(object, class)
87 local meta = getmetatable(object)
88 while meta and meta.__index do
89 if meta.__index == class then
92 meta = getmetatable(meta.__index)
99 -- Scope manipulation routines
105 __index = function(self, key)
106 local t = rawget(self, coxpt[coroutine.running()]
107 or coroutine.running() or 0)
111 __newindex = function(self, key, value)
112 local c = coxpt[coroutine.running()] or coroutine.running() or 0
113 local r = rawget(self, c)
115 rawset(self, c, { [key] = value })
122 -- the current active coroutine. A thread local store is private a table object
123 -- whose values can't be accessed from outside of the running coroutine.
124 function threadlocal(tbl)
125 return setmetatable(tbl or {}, tl_meta)
130 -- Debugging routines
134 return io.stderr:write(tostring(obj) .. "\n")
137 function dumptable(t, maxdepth, i, seen)
139 seen = seen or setmetatable({}, {__mode="k"})
141 for k,v in pairs(t) do
142 perror(string.rep("\t", i) .. tostring(k) .. "\t" .. tostring(v))
143 if type(v) == "table" and (not maxdepth or i < maxdepth) then
146 dumptable(v, maxdepth, i+1, seen)
148 perror(string.rep("\t", i) .. "*** RECURSION ***")
156 -- String and data manipulation routines
159 function pcdata(value)
160 return value and tparser.pcdata(tostring(value))
163 function striptags(value)
164 return value and tparser.striptags(tostring(value))
167 -- for bash, ash and similar shells single-quoted strings are taken
168 -- literally except for single quotes (which terminate the string)
169 -- (and the exception noted below for dash (-) at the start of a
170 -- command line parameter).
171 function shellsqescape(value)
173 res, _ = string.gsub(value, "'", "'\\''")
177 -- bash, ash and other similar shells interpret a dash (-) at the start
178 -- of a command-line parameters as an option indicator regardless of
179 -- whether it is inside a single-quoted string. It must be backlash
180 -- escaped to resolve this. This requires in some funky special-case
181 -- handling. It may actually be a property of the getopt function
182 -- rather than the shell proper.
183 function shellstartsqescape(value)
184 res, _ = string.gsub(value, "^\-", "\\-")
185 res, _ = string.gsub(res, "^-", "\-")
186 return shellsqescape(value)
189 -- containing the resulting substrings. The optional max parameter specifies
190 -- the number of bytes to process, regardless of the actual length of the given
191 -- string. The optional last parameter, regex, specifies whether the separator
192 -- sequence is interpreted as regular expression.
193 -- pattern as regular expression (optional, default is false)
194 function split(str, pat, max, regex)
214 local s, e = str:find(pat, c, not regex)
216 if s and max < 0 then
219 t[#t+1] = str:sub(c, s and s - 1)
221 c = e and e + 1 or #str + 1
222 until not s or max < 0
228 return (str:gsub("^%s*(.-)%s*$", "%1"))
231 function cmatch(str, pat)
233 for _ in str:gmatch(pat) do count = count + 1 end
237 -- one token per invocation, the tokens are separated by whitespace. If the
238 -- input value is a table, it is transformed into a string first. A nil value
239 -- will result in a valid interator which aborts with the first invocation.
241 if type(v) == "table" then
248 elseif type(v) == "number" or type(v) == "boolean" then
257 elseif type(v) == "userdata" or type(v) == "string" then
258 return tostring(v):gmatch("%S+")
261 return function() end
264 -- value or 0 if the unit is unknown. Upper- or lower case is irrelevant.
265 -- Recognized units are:
266 -- o "y" - one year (60*60*24*366)
267 -- o "m" - one month (60*60*24*31)
268 -- o "w" - one week (60*60*24*7)
269 -- o "d" - one day (60*60*24)
270 -- o "h" - one hour (60*60)
271 -- o "min" - one minute (60)
272 -- o "kb" - one kilobyte (1024)
273 -- o "mb" - one megabyte (1024*1024)
274 -- o "gb" - one gigabyte (1024*1024*1024)
275 -- o "kib" - one si kilobyte (1000)
276 -- o "mib" - one si megabyte (1000*1000)
277 -- o "gib" - one si gigabyte (1000*1000*1000)
278 function parse_units(ustr)
285 y = 60 * 60 * 24 * 366,
286 m = 60 * 60 * 24 * 31,
287 w = 60 * 60 * 24 * 7,
295 gb = 1024 * 1024 * 1024,
297 -- storage sizes (si)
300 gib = 1000 * 1000 * 1000
303 -- parse input string
304 for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
306 local num = spec:gsub("[^0-9%.]+$","")
307 local spn = spec:gsub("^[0-9%.]+", "")
309 if map[spn] or map[spn:sub(1,1)] then
310 val = val + num * ( map[spn] or map[spn:sub(1,1)] )
320 -- also register functions above in the central string class for convenience
321 string.pcdata = pcdata
322 string.striptags = striptags
325 string.cmatch = cmatch
326 string.parse_units = parse_units
329 function append(src, ...)
330 for i, a in ipairs({...}) do
331 if type(a) == "table" then
332 for j, v in ipairs(a) do
342 function combine(...)
343 return append({}, ...)
346 function contains(table, value)
347 for k, v in pairs(table) do
355 -- Both table are - in fact - merged together.
356 function update(t, updates)
357 for k, v in pairs(updates) do
365 for k, _ in kspairs(t) do
372 function clone(object, deep)
375 for k, v in pairs(object) do
376 if deep and type(v) == "table" then
382 return setmetatable(copy, getmetatable(object))
387 return setmetatable({}, { __index =
389 return rawget(tbl, key)
390 or rawget(rawset(tbl, key, dtable()), key)
396 -- Serialize the contents of a table value.
397 function _serialize_table(t, seen)
398 assert(not seen[t], "Recursion detected.")
405 for k, v in pairs(t) do
406 if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then
407 k = serialize_data(k, seen)
408 v = serialize_data(v, seen)
409 data = data .. ( #data > 0 and ", " or "" ) ..
410 '[' .. k .. '] = ' .. v
417 local v = serialize_data(t[i], seen)
418 idata = idata .. ( #idata > 0 and ", " or "" ) .. v
421 return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data
424 -- with loadstring().
425 function serialize_data(val, seen)
426 seen = seen or setmetatable({}, {__mode="k"})
430 elseif type(val) == "number" then
432 elseif type(val) == "string" then
434 elseif type(val) == "boolean" then
435 return val and "true" or "false"
436 elseif type(val) == "function" then
437 return "loadstring(%q)" % get_bytecode(val)
438 elseif type(val) == "table" then
439 return "{ " .. _serialize_table(val, seen) .. " }"
441 return '"[unhandled data type:' .. type(val) .. ']"'
445 function restore_data(str)
446 return loadstring("return " .. str)()
451 -- Byte code manipulation routines
454 -- will be stripped before it is returned.
455 function get_bytecode(val)
458 if type(val) == "function" then
459 code = string.dump(val)
461 code = string.dump( loadstring( "return " .. serialize_data(val) ) )
464 return code -- and strip_bytecode(code)
467 -- numbers and debugging numbers will be discarded. Original version by
468 -- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
469 function strip_bytecode(code)
470 local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
473 subint = function(code, i, l)
476 val = val * 256 + code:byte(i + n - 1)
481 subint = function(code, i, l)
484 val = val * 256 + code:byte(i + n - 1)
490 local function strip_function(code)
491 local count, offset = subint(code, 1, size)
492 local stripped = { string.rep("\0", size) }
493 local dirty = offset + count
494 offset = offset + count + int * 2 + 4
495 offset = offset + int + subint(code, offset, int) * ins
496 count, offset = subint(code, offset, int)
499 t, offset = subint(code, offset, 1)
503 offset = offset + size + subint(code, offset, size)
505 offset = offset + num
506 elseif t == 254 or t == 9 then
507 offset = offset + lnum
510 count, offset = subint(code, offset, int)
511 stripped[#stripped+1] = code:sub(dirty, offset - 1)
513 local proto, off = strip_function(code:sub(offset, -1))
514 stripped[#stripped+1] = proto
515 offset = offset + off - 1
517 offset = offset + subint(code, offset, int) * int + int
518 count, offset = subint(code, offset, int)
520 offset = offset + subint(code, offset, size) + size + int * 2
522 count, offset = subint(code, offset, int)
524 offset = offset + subint(code, offset, size) + size
526 stripped[#stripped+1] = string.rep("\0", int * 3)
527 return table.concat(stripped), offset
530 return code:sub(1,12) .. strip_function(code:sub(13,-1))
535 -- Sorting iterator functions
538 function _sortiter( t, f )
542 for k, v in pairs(t) do
548 table.sort( keys, f )
552 if _pos <= #keys then
553 return keys[_pos], t[keys[_pos]], _pos
558 -- the provided callback function.
560 return _sortiter( t, f )
563 -- The table pairs are sorted by key.
565 return _sortiter( t )
568 -- The table pairs are sorted by value.
570 return _sortiter( t, function (a,b) return t[a] < t[b] end )
575 -- System utility functions
579 return string.byte(string.dump(function() end), 7) == 0
582 function exec(command)
583 local pp = io.popen(command)
584 local data = pp:read("*a")
590 function execi(command)
591 local pp = io.popen(command)
593 return pp and function()
594 local line = pp:read()
605 function execl(command)
606 local pp = io.popen(command)
612 if (line == nil) then break end
620 function ubus(object, method, data)
621 if not _ubus_connection then
622 _ubus_connection = _ubus.connect()
623 assert(_ubus_connection, "Unable to establish ubus connection")
626 if object and method then
627 if type(data) ~= "table" then
630 return _ubus_connection:call(object, method, data)
632 return _ubus_connection:signatures(object)
634 return _ubus_connection:objects()
638 function serialize_json(x, cb)
639 local js = json.stringify(x)
640 if type(cb) == "function" then
649 return require "nixio.fs".dirname(ldebug.__file__)
652 function checklib(fullpathexe, wantedlib)
653 local fs = require "nixio.fs"
654 local haveldd = fs.access('/usr/bin/ldd')
658 local libs = exec("/usr/bin/ldd " .. fullpathexe)
662 for k, v in ipairs(split(libs)) do
663 if v:find(wantedlib) then
671 -- Coroutine safe xpcall and pcall versions modified for Luci
673 -- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
675 -- Copyright © 2005 Kepler Project.
676 -- Permission is hereby granted, free of charge, to any person obtaining a
677 -- copy of this software and associated documentation files (the "Software"),
678 -- to deal in the Software without restriction, including without limitation
679 -- the rights to use, copy, modify, merge, publish, distribute, sublicense,
680 -- and/or sell copies of the Software, and to permit persons to whom the
681 -- Software is furnished to do so, subject to the following conditions:
683 -- The above copyright notice and this permission notice shall be
684 -- included in all copies or substantial portions of the Software.
686 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
687 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
688 -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
689 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
690 -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
691 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
692 -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
694 local performResume, handleReturnValue
695 local oldpcall, oldxpcall = pcall, xpcall
697 setmetatable(coxpt, {__mode = "kv"})
699 -- Identity function for copcall
700 local function copcall_id(trace, ...)
704 -- values of either the function or the error handler
705 function coxpcall(f, err, ...)
706 local res, co = oldpcall(coroutine.create, f)
709 local newf = function() return f(unpack(params)) end
710 co = coroutine.create(newf)
712 local c = coroutine.running()
713 coxpt[co] = coxpt[c] or c or 0
715 return performResume(err, co, ...)
718 -- values of the function or the error object
719 function copcall(f, ...)
720 return coxpcall(f, copcall_id, ...)
723 -- Handle return value of protected call
724 function handleReturnValue(err, co, status, ...)
726 return false, err(debug.traceback(co, (...)), ...)
729 if coroutine.status(co) ~= 'suspended' then
733 return performResume(err, co, coroutine.yield(...))
736 -- Resume execution of protected function call
737 function performResume(err, co, ...)
738 return handleReturnValue(err, co, coroutine.resume(co, ...))