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