ffab60cb07429a6f51eec3c7785d2b50d40f6ba4
[project/luci.git] / libs / core / luasrc / util.lua
1 --[[
2 LuCI - Utility library
3
4 Description:
5 Several common useful Lua functions
6
7 FileId:
8 $Id$
9
10 License:
11 Copyright 2008 Steven Barth <steven@midlink.org>
12
13 Licensed under the Apache License, Version 2.0 (the "License");
14 you may not use this file except in compliance with the License.
15 You may obtain a copy of the License at
16
17         http://www.apache.org/licenses/LICENSE-2.0
18
19 Unless required by applicable law or agreed to in writing, software
20 distributed under the License is distributed on an "AS IS" BASIS,
21 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 See the License for the specific language governing permissions and
23 limitations under the License.
24
25 ]]--
26
27 local io = require "io"
28 local math = require "math"
29 local table = require "table"
30 local debug = require "debug"
31 local ldebug = require "luci.debug"
32 local string = require "string"
33 local coroutine = require "coroutine"
34 local cutil = require "luci.cutil"
35
36 local getmetatable, setmetatable = getmetatable, setmetatable
37 local rawget, rawset, unpack = rawget, rawset, unpack
38 local tostring, type, assert = tostring, type, assert
39 local ipairs, pairs, loadstring = ipairs, pairs, loadstring
40 local require, pcall, xpcall = require, pcall, xpcall
41
42 --- LuCI utility functions.
43 module "luci.util"
44
45 --
46 -- Pythonic string formatting extension
47 --
48 --[[
49 getmetatable("").__mod = function(a, b)
50         if not b then
51                 return a
52         elseif type(b) == "table" then
53                 return a:format(unpack(b))
54         else
55                 return a:format(b)
56         end
57 end
58 ]]--
59
60
61 --
62 -- Class helper routines
63 --
64
65 -- Instantiates a class
66 --[[
67 local function _instantiate(class, ...)
68         local inst = setmetatable({}, {__index = class})
69
70         if inst.__init__ then
71                 inst:__init__(...)
72         end
73
74         return inst
75 end
76 ]]--
77
78 --- Create a Class object (Python-style object model).
79 -- The class object can be instantiated by calling itself.
80 -- Any class functions or shared parameters can be attached to this object.
81 -- Attaching a table to the class object makes this table shared between
82 -- all instances of this class. For object parameters use the __init__ function.
83 -- Classes can inherit member functions and values from a base class.
84 -- Class can be instantiated by calling them. All parameters will be passed
85 -- to the __init__ function of this class - if such a function exists.
86 -- The __init__ function must be used to set any object parameters that are not shared
87 -- with other objects of this class. Any return values will be ignored.
88 -- @param base  The base class to inherit from (optional)
89 -- @return              A class object
90 -- @see                 instanceof
91 -- @see                 clone
92 --[[
93 function class(base)
94         return setmetatable({}, {
95                 __call  = _instantiate,
96                 __index = base
97         })
98 end
99 ]]--
100 class = cutil.class
101
102 --- Test whether the given object is an instance of the given class.
103 -- @param object        Object instance
104 -- @param class         Class object to test against
105 -- @return                      Boolean indicating whether the object is an instance
106 -- @see                         class
107 -- @see                         clone
108 function instanceof(object, class)
109         local meta = getmetatable(object)
110         while meta and meta.__index do
111                 if meta.__index == class then
112                         return true
113                 end
114                 meta = getmetatable(meta.__index)
115         end
116         return false
117 end
118
119
120 --
121 -- Scope manipulation routines
122 --
123
124 --- Create a new or get an already existing thread local store associated with
125 -- the current active coroutine. A thread local store is private a table object
126 -- whose values can't be accessed from outside of the running coroutine.
127 -- @return      Table value representing the corresponding thread local store
128 function threadlocal()
129         local tbl = {}
130
131         local function get(self, key)
132                 local c = coroutine.running()
133                 local thread = coxpt[c] or c or 0
134                 if not rawget(self, thread) then
135                         return nil
136                 end
137                 return rawget(self, thread)[key]
138         end
139
140         local function set(self, key, value)
141                 local c = coroutine.running()
142                 local thread = coxpt[c] or c or 0
143                 if not rawget(self, thread) then
144                         rawset(self, thread, {})
145                 end
146                 rawget(self, thread)[key] = value
147         end
148
149         setmetatable(tbl, {__index = get, __newindex = set, __mode = "k"})
150
151         return tbl
152 end
153
154
155 --
156 -- Debugging routines
157 --
158
159 --- Write given object to stderr.
160 -- @param obj   Value to write to stderr
161 -- @return              Boolean indicating whether the write operation was successful
162 function perror(obj)
163         return io.stderr:write(tostring(obj) .. "\n")
164 end
165
166 --- Recursively dumps a table to stdout, useful for testing and debugging.
167 -- @param t     Table value to dump
168 -- @param maxdepth      Maximum depth
169 -- @return      Always nil
170 function dumptable(t, maxdepth, i, seen)
171         i = i or 0
172         seen = seen or setmetatable({}, {__mode="k"})
173
174         for k,v in pairs(t) do
175                 perror(string.rep("\t", i) .. tostring(k) .. "\t" .. tostring(v))
176                 if type(v) == "table" and (not maxdepth or i < maxdepth) then
177                         if not seen[v] then
178                                 seen[v] = true
179                                 dumptable(v, maxdepth, i+1, seen)
180                         else
181                                 perror(string.rep("\t", i) .. "*** RECURSION ***")
182                         end
183                 end
184         end
185 end
186
187
188 --
189 -- String and data manipulation routines
190 --
191
192 --- Escapes all occurrences of the given character in given string.
193 -- @param s     String value containing unescaped characters
194 -- @param c     String value with character to escape (optional, defaults to "\")
195 -- @return      String value with each occurrence of character escaped with "\"
196 function escape(s, c)
197         c = c or "\\"
198         return s:gsub(c, "\\" .. c)
199 end
200
201 --- Create valid XML PCDATA from given string.
202 -- @param value String value containing the data to escape
203 -- @return              String value containing the escaped data
204 function pcdata(value)
205         return value and tostring(value):gsub("[&\"'<>]", {
206                 ["&"] = "&#38;",
207                 ['"'] = "&#34;",
208                 ["'"] = "&#39;",
209                 ["<"] = "&#60;",
210                 [">"] = "&#62;"
211         })
212 end
213
214 --- Strip HTML tags from given string.
215 -- @param value String containing the HTML text
216 -- @return      String with HTML tags stripped of
217 function striptags(s)
218         return pcdata(s:gsub("</?[A-Za-z][A-Za-z0-9:_%-]*[^>]*>", " "):gsub("%s+", " "))
219 end
220
221 --- Splits given string on a defined separator sequence and return a table
222 -- containing the resulting substrings. The optional max parameter specifies
223 -- the number of bytes to process, regardless of the actual length of the given
224 -- string. The optional last parameter, regex, specifies whether the separator
225 -- sequence is interpreted as regular expression.
226 -- @param str           String value containing the data to split up
227 -- @param pat           String with separator pattern (optional, defaults to "\n")
228 -- @param max           Maximum times to split (optional)
229 -- @param regex         Boolean indicating whether to interpret the separator
230 --                                      pattern as regular expression (optional, default is false)
231 -- @return                      Table containing the resulting substrings
232 function split(str, pat, max, regex)
233         pat = pat or "\n"
234         max = max or #str
235
236         local t = {}
237         local c = 1
238
239         if #str == 0 then
240                 return {""}
241         end
242
243         if #pat == 0 then
244                 return nil
245         end
246
247         if max == 0 then
248                 return str
249         end
250
251         repeat
252                 local s, e = str:find(pat, c, not regex)
253                 max = max - 1
254                 if s and max < 0 then
255                         t[#t+1] = str:sub(c)
256                 else
257                         t[#t+1] = str:sub(c, s and s - 1)
258                 end
259                 c = e and e + 1 or #str + 1
260         until not s or max < 0
261
262         return t
263 end
264
265 --- Remove leading and trailing whitespace from given string value.
266 -- @param str   String value containing whitespace padded data
267 -- @return              String value with leading and trailing space removed
268 function trim(str)
269         return (str:gsub("^%s*(.-)%s*$", "%1"))
270 end
271
272 --- Count the occurences of given substring in given string.
273 -- @param str           String to search in
274 -- @param pattern       String containing pattern to find
275 -- @return                      Number of found occurences
276 function cmatch(str, pat)
277         local count = 0
278         for _ in str:gmatch(pat) do count = count + 1 end
279         return count
280 end
281
282 --- Parse certain units from the given string and return the canonical integer
283 -- value or 0 if the unit is unknown. Upper- or lower case is irrelevant.
284 -- Recognized units are:
285 --      o "y"   - one year   (60*60*24*366)
286 --  o "m"       - one month  (60*60*24*31)
287 --  o "w"       - one week   (60*60*24*7)
288 --  o "d"       - one day    (60*60*24)
289 --  o "h"       - one hour       (60*60)
290 --  o "min"     - one minute (60)
291 --  o "kb"  - one kilobyte (1024)
292 --  o "mb"      - one megabyte (1024*1024)
293 --  o "gb"      - one gigabyte (1024*1024*1024)
294 --  o "kib" - one si kilobyte (1000)
295 --  o "mib"     - one si megabyte (1000*1000)
296 --  o "gib"     - one si gigabyte (1000*1000*1000)
297 -- @param ustr  String containing a numerical value with trailing unit
298 -- @return              Number containing the canonical value
299 function parse_units(ustr)
300
301         local val = 0
302
303         -- unit map
304         local map = {
305                 -- date stuff
306                 y   = 60 * 60 * 24 * 366,
307                 m   = 60 * 60 * 24 * 31,
308                 w   = 60 * 60 * 24 * 7,
309                 d   = 60 * 60 * 24,
310                 h   = 60 * 60,
311                 min = 60,
312
313                 -- storage sizes
314                 kb  = 1024,
315                 mb  = 1024 * 1024,
316                 gb  = 1024 * 1024 * 1024,
317
318                 -- storage sizes (si)
319                 kib = 1000,
320                 mib = 1000 * 1000,
321                 gib = 1000 * 1000 * 1000
322         }
323
324         -- parse input string
325         for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
326
327                 local num = spec:gsub("[^0-9%.]+$","")
328                 local spn = spec:gsub("^[0-9%.]+", "")
329
330                 if map[spn] or map[spn:sub(1,1)] then
331                         val = val + num * ( map[spn] or map[spn:sub(1,1)] )
332                 else
333                         val = val + num
334                 end
335         end
336
337
338         return val
339 end
340
341 -- also register functions above in the central string class for convenience
342 string.escape      = escape
343 string.pcdata      = pcdata
344 string.striptags   = striptags
345 string.split       = split
346 string.trim        = trim
347 string.cmatch      = cmatch
348 string.parse_units = parse_units
349
350
351 --- Appends numerically indexed tables or single objects to a given table.
352 -- @param src   Target table
353 -- @param ...   Objects to insert
354 -- @return              Target table
355 function append(src, ...)
356         for i, a in ipairs({...}) do
357                 if type(a) == "table" then
358                         for j, v in ipairs(a) do
359                                 src[#src+1] = v
360                         end
361                 else
362                         src[#src+1] = a
363                 end
364         end
365         return src
366 end
367
368 --- Combines two or more numerically indexed tables and single objects into one table.
369 -- @param tbl1  Table value to combine
370 -- @param tbl2  Table value to combine
371 -- @param ...   More tables to combine
372 -- @return              Table value containing all values of given tables
373 function combine(...)
374         return append({}, ...)
375 end
376
377 --- Checks whether the given table contains the given value.
378 -- @param table Table value
379 -- @param value Value to search within the given table
380 -- @return              Boolean indicating whether the given value occurs within table
381 function contains(table, value)
382         for k, v in pairs(table) do
383                 if value == v then
384                         return k
385                 end
386         end
387         return false
388 end
389
390 --- Update values in given table with the values from the second given table.
391 -- Both table are - in fact - merged together.
392 -- @param t                     Table which should be updated
393 -- @param updates       Table containing the values to update
394 -- @return                      Always nil
395 function update(t, updates)
396         for k, v in pairs(updates) do
397                 t[k] = v
398         end
399 end
400
401 --- Retrieve all keys of given associative table.
402 -- @param t     Table to extract keys from
403 -- @return      Sorted table containing the keys
404 function keys(t)
405         local keys = { }
406         if t then
407                 for k, _ in kspairs(t) do
408                         keys[#keys+1] = k
409                 end
410         end
411         return keys
412 end
413
414 --- Clones the given object and return it's copy.
415 -- @param object        Table value to clone
416 -- @param deep          Boolean indicating whether to do recursive cloning
417 -- @return                      Cloned table value
418 function clone(object, deep)
419         local copy = {}
420
421         for k, v in pairs(object) do
422                 if deep and type(v) == "table" then
423                         v = clone(v, deep)
424                 end
425                 copy[k] = v
426         end
427
428         return setmetatable(copy, getmetatable(object))
429 end
430
431
432 --- Create a dynamic table which automatically creates subtables.
433 -- @return      Dynamic Table
434 function dtable()
435         return setmetatable({}, { __index =
436                 function(tbl, key)
437                         return rawget(tbl, key)
438                          or rawget(rawset(tbl, key, dtable()), key)
439                 end
440         })
441 end
442
443
444 -- Serialize the contents of a table value.
445 function _serialize_table(t, seen)
446         assert(not seen[t], "Recursion detected.")
447         seen[t] = true
448
449         local data  = ""
450         local idata = ""
451         local ilen  = 0
452
453         for k, v in pairs(t) do
454                 if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then
455                         k = serialize_data(k, seen)
456                         v = serialize_data(v, seen)
457                         data = data .. ( #data > 0 and ", " or "" ) ..
458                                 '[' .. k .. '] = ' .. v
459                 elseif k > ilen then
460                         ilen = k
461                 end
462         end
463
464         for i = 1, ilen do
465                 local v = serialize_data(t[i], seen)
466                 idata = idata .. ( #idata > 0 and ", " or "" ) .. v
467         end
468
469         return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data
470 end
471
472 --- Recursively serialize given data to lua code, suitable for restoring
473 -- with loadstring().
474 -- @param val   Value containing the data to serialize
475 -- @return              String value containing the serialized code
476 -- @see                 restore_data
477 -- @see                 get_bytecode
478 function serialize_data(val, seen)
479         seen = seen or setmetatable({}, {__mode="k"})
480
481         if val == nil then
482                 return "nil"
483         elseif type(val) == "number" then
484                 return val
485         elseif type(val) == "string" then
486                 return "%q" % val
487         elseif type(val) == "boolean" then
488                 return val and "true" or "false"
489         elseif type(val) == "function" then
490                 return "loadstring(%q)" % get_bytecode(val)
491         elseif type(val) == "table" then
492                 return "{ " .. _serialize_table(val, seen) .. " }"
493         else
494                 return '"[unhandled data type:' .. type(val) .. ']"'
495         end
496 end
497
498 --- Restore data previously serialized with serialize_data().
499 -- @param str   String containing the data to restore
500 -- @return              Value containing the restored data structure
501 -- @see                 serialize_data
502 -- @see                 get_bytecode
503 function restore_data(str)
504         return loadstring("return " .. str)()
505 end
506
507
508 --
509 -- Byte code manipulation routines
510 --
511
512 --- Return the current runtime bytecode of the given data. The byte code
513 -- will be stripped before it is returned.
514 -- @param val   Value to return as bytecode
515 -- @return              String value containing the bytecode of the given data
516 function get_bytecode(val)
517         local code
518
519         if type(val) == "function" then
520                 code = string.dump(val)
521         else
522                 code = string.dump( loadstring( "return " .. serialize_data(val) ) )
523         end
524
525         return code and strip_bytecode(code)
526 end
527
528 --- Strips unnescessary lua bytecode from given string. Information like line
529 -- numbers and debugging numbers will be discarded. Original version by
530 -- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
531 -- @param code  String value containing the original lua byte code
532 -- @return              String value containing the stripped lua byte code
533 function strip_bytecode(code)
534         local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
535         local subint
536         if endian == 1 then
537                 subint = function(code, i, l)
538                         local val = 0
539                         for n = l, 1, -1 do
540                                 val = val * 256 + code:byte(i + n - 1)
541                         end
542                         return val, i + l
543                 end
544         else
545                 subint = function(code, i, l)
546                         local val = 0
547                         for n = 1, l, 1 do
548                                 val = val * 256 + code:byte(i + n - 1)
549                         end
550                         return val, i + l
551                 end
552         end
553
554         local strip_function
555         strip_function = function(code)
556                 local count, offset = subint(code, 1, size)
557                 local stripped, dirty = string.rep("\0", size), offset + count
558                 offset = offset + count + int * 2 + 4
559                 offset = offset + int + subint(code, offset, int) * ins
560                 count, offset = subint(code, offset, int)
561                 for n = 1, count do
562                         local t
563                         t, offset = subint(code, offset, 1)
564                         if t == 1 then
565                                 offset = offset + 1
566                         elseif t == 4 then
567                                 offset = offset + size + subint(code, offset, size)
568                         elseif t == 3 then
569                                 offset = offset + num
570                         elseif t == 254 or t == 9 then
571                                 offset = offset + lnum
572                         end
573                 end
574                 count, offset = subint(code, offset, int)
575                 stripped = stripped .. code:sub(dirty, offset - 1)
576                 for n = 1, count do
577                         local proto, off = strip_function(code:sub(offset, -1))
578                         stripped, offset = stripped .. proto, offset + off - 1
579                 end
580                 offset = offset + subint(code, offset, int) * int + int
581                 count, offset = subint(code, offset, int)
582                 for n = 1, count do
583                         offset = offset + subint(code, offset, size) + size + int * 2
584                 end
585                 count, offset = subint(code, offset, int)
586                 for n = 1, count do
587                         offset = offset + subint(code, offset, size) + size
588                 end
589                 stripped = stripped .. string.rep("\0", int * 3)
590                 return stripped, offset
591         end
592
593         return code:sub(1,12) .. strip_function(code:sub(13,-1))
594 end
595
596
597 --
598 -- Sorting iterator functions
599 --
600
601 function _sortiter( t, f )
602         local keys = { }
603
604         for k, v in pairs(t) do
605                 keys[#keys+1] = k
606         end
607
608         local _pos = 0
609
610         table.sort( keys, f )
611
612         return function()
613                 _pos = _pos + 1
614                 if _pos <= #keys then
615                         return keys[_pos], t[keys[_pos]]
616                 end
617         end
618 end
619
620 --- Return a key, value iterator which returns the values sorted according to
621 -- the provided callback function.
622 -- @param t     The table to iterate
623 -- @param f A callback function to decide the order of elements
624 -- @return      Function value containing the corresponding iterator
625 function spairs(t,f)
626         return _sortiter( t, f )
627 end
628
629 --- Return a key, value iterator for the given table.
630 -- The table pairs are sorted by key.
631 -- @param t     The table to iterate
632 -- @return      Function value containing the corresponding iterator
633 function kspairs(t)
634         return _sortiter( t )
635 end
636
637 --- Return a key, value iterator for the given table.
638 -- The table pairs are sorted by value.
639 -- @param t     The table to iterate
640 -- @return      Function value containing the corresponding iterator
641 function vspairs(t)
642         return _sortiter( t, function (a,b) return t[a] < t[b] end )
643 end
644
645
646 --
647 -- System utility functions
648 --
649
650 --- Test whether the current system is operating in big endian mode.
651 -- @return      Boolean value indicating whether system is big endian
652 function bigendian()
653         return string.byte(string.dump(function() end), 7) == 0
654 end
655
656 --- Execute given commandline and gather stdout.
657 -- @param command       String containing command to execute
658 -- @return                      String containing the command's stdout
659 function exec(command)
660         local pp   = io.popen(command)
661         local data = pp:read("*a")
662         pp:close()
663
664         return data
665 end
666
667 --- Return a line-buffered iterator over the output of given command.
668 -- @param command       String containing the command to execute
669 -- @return                      Iterator
670 function execi(command)
671         local pp = io.popen(command)
672
673         return pp and function()
674                 local line = pp:read()
675
676                 if not line then
677                         pp:close()
678                 end
679
680                 return line
681         end
682 end
683
684 -- Deprecated
685 function execl(command)
686         local pp   = io.popen(command)
687         local line = ""
688         local data = {}
689
690         while true do
691                 line = pp:read()
692                 if (line == nil) then break end
693                 data[#data+1] = line
694         end
695         pp:close()
696
697         return data
698 end
699
700 --- Returns the absolute path to LuCI base directory.
701 -- @return              String containing the directory path
702 function libpath()
703         return require "luci.fs".dirname(ldebug.__file__)
704 end
705
706
707 --
708 -- Coroutine safe xpcall and pcall versions modified for Luci
709 -- original version:
710 -- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
711 --
712 -- Copyright © 2005 Kepler Project.
713 -- Permission is hereby granted, free of charge, to any person obtaining a
714 -- copy of this software and associated documentation files (the "Software"),
715 -- to deal in the Software without restriction, including without limitation
716 -- the rights to use, copy, modify, merge, publish, distribute, sublicense,
717 -- and/or sell copies of the Software, and to permit persons to whom the
718 -- Software is furnished to do so, subject to the following conditions:
719 --
720 -- The above copyright notice and this permission notice shall be
721 -- included in all copies or substantial portions of the Software.
722 --
723 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
724 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
725 -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
726 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
727 -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
728 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
729 -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
730
731 local performResume, handleReturnValue
732 local oldpcall, oldxpcall = pcall, xpcall
733 coxpt = {}
734 setmetatable(coxpt, {__mode = "kv"})
735
736 -- Identity function for copcall
737 local function copcall_id(trace, ...)
738   return ...
739 end
740
741 --- This is a coroutine-safe drop-in replacement for Lua's "xpcall"-function
742 -- @param f             Lua function to be called protected
743 -- @param err   Custom error handler
744 -- @param ...   Parameters passed to the function
745 -- @return              A boolean whether the function call succeeded and the return
746 --                              values of either the function or the error handler
747 function coxpcall(f, err, ...)
748         local res, co = oldpcall(coroutine.create, f)
749         if not res then
750                 local params = {...}
751                 local newf = function() return f(unpack(params)) end
752                 co = coroutine.create(newf)
753         end
754         local c = coroutine.running()
755         coxpt[co] = coxpt[c] or c or 0
756
757         return performResume(err, co, ...)
758 end
759
760 --- This is a coroutine-safe drop-in replacement for Lua's "pcall"-function
761 -- @param f             Lua function to be called protected
762 -- @param ...   Parameters passed to the function
763 -- @return              A boolean whether the function call succeeded and the returns
764 --                              values of the function or the error object
765 function copcall(f, ...)
766         return coxpcall(f, copcall_id, ...)
767 end
768
769 -- Handle return value of protected call
770 function handleReturnValue(err, co, status, ...)
771         if not status then
772                 return false, err(debug.traceback(co, (...)), ...)
773         end
774         if coroutine.status(co) == 'suspended' then
775                 return performResume(err, co, coroutine.yield(...))
776         else
777                 return true, ...
778         end
779 end
780
781 -- Resume execution of protected function call
782 function performResume(err, co, ...)
783         return handleReturnValue(err, co, coroutine.resume(co, ...))
784 end