678e36e4110d00e7f533f3cd20653edcf6808f31
[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
35 local getmetatable, setmetatable = getmetatable, setmetatable
36 local getfenv, setfenv = getfenv, setfenv
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 function pcdata(value)
198         return value and tostring(value):gsub("[&\"'<>]", {
199                 ["&"] = "&amp;",
200                 ['"'] = "&quot;",
201                 ["'"] = "&apos;",
202                 ["<"] = "&lt;",
203                 [">"] = "&gt;"
204         })
205 end
206
207 --- Strip HTML tags from given string.
208 -- @param value String containing the HTML text
209 -- @return      String with HTML tags stripped of
210 function striptags(s)
211         return pcdata(s:gsub("</?[A-Za-z][A-Za-z0-9:_%-]*[^>]*>", " "):gsub("%s+", " "))
212 end
213
214 --- Splits given string on a defined separator sequence and return a table
215 -- containing the resulting substrings. The optional max parameter specifies
216 -- the number of bytes to process, regardless of the actual length of the given
217 -- string. The optional last parameter, regex, specifies whether the separator
218 -- sequence is interpreted as regular expression.
219 -- @param str           String value containing the data to split up
220 -- @param pat           String with separator pattern (optional, defaults to "\n")
221 -- @param max           Maximum times to split (optional)
222 -- @param regex         Boolean indicating whether to interpret the separator
223 --                                      pattern as regular expression (optional, default is false)
224 -- @return                      Table containing the resulting substrings
225 function split(str, pat, max, regex)
226         pat = pat or "\n"
227         max = max or #str
228
229         local t = {}
230         local c = 1
231
232         if #str == 0 then
233                 return {""}
234         end
235
236         if #pat == 0 then
237                 return nil
238         end
239
240         if max == 0 then
241                 return str
242         end
243
244         repeat
245                 local s, e = str:find(pat, c, not regex)
246                 max = max - 1
247                 if s and max < 0 then
248                         t[#t+1] = str:sub(c)
249                 else
250                         t[#t+1] = str:sub(c, s and s - 1)
251                 end
252                 c = e and e + 1 or #str + 1
253         until not s or max < 0
254
255         return t
256 end
257
258 --- Remove leading and trailing whitespace from given string value.
259 -- @param str   String value containing whitespace padded data
260 -- @return              String value with leading and trailing space removed
261 function trim(str)
262         return (str:gsub("^%s*(.-)%s*$", "%1"))
263 end
264
265 --- Parse certain units from the given string and return the canonical integer
266 -- value or 0 if the unit is unknown. Upper- or lower case is irrelevant.
267 -- Recognized units are:
268 --      o "y"   - one year   (60*60*24*366)
269 --  o "m"       - one month  (60*60*24*31)
270 --  o "w"       - one week   (60*60*24*7)
271 --  o "d"       - one day    (60*60*24)
272 --  o "h"       - one hour       (60*60)
273 --  o "min"     - one minute (60)
274 --  o "kb"  - one kilobyte (1024)
275 --  o "mb"      - one megabyte (1024*1024)
276 --  o "gb"      - one gigabyte (1024*1024*1024)
277 --  o "kib" - one si kilobyte (1000)
278 --  o "mib"     - one si megabyte (1000*1000)
279 --  o "gib"     - one si gigabyte (1000*1000*1000)
280 -- @param ustr  String containing a numerical value with trailing unit
281 -- @return              Number containing the canonical value
282 function parse_units(ustr)
283
284         local val = 0
285
286         -- unit map
287         local map = {
288                 -- date stuff
289                 y   = 60 * 60 * 24 * 366,
290                 m   = 60 * 60 * 24 * 31,
291                 w   = 60 * 60 * 24 * 7,
292                 d   = 60 * 60 * 24,
293                 h   = 60 * 60,
294                 min = 60,
295
296                 -- storage sizes
297                 kb  = 1024,
298                 mb  = 1024 * 1024,
299                 gb  = 1024 * 1024 * 1024,
300
301                 -- storage sizes (si)
302                 kib = 1000,
303                 mib = 1000 * 1000,
304                 gib = 1000 * 1000 * 1000
305         }
306
307         -- parse input string
308         for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
309
310                 local num = spec:gsub("[^0-9%.]+$","")
311                 local spn = spec:gsub("^[0-9%.]+", "")
312
313                 if map[spn] or map[spn:sub(1,1)] then
314                         val = val + num * ( map[spn] or map[spn:sub(1,1)] )
315                 else
316                         val = val + num
317                 end
318         end
319
320
321         return val
322 end
323
324 --- Combines two or more numerically indexed tables into one.
325 -- @param tbl1  Table value to combine
326 -- @param tbl2  Table value to combine
327 -- @param ...   More tables to combine
328 -- @return              Table value containing all values of given tables
329 function combine(...)
330         local result = {}
331         for i, a in ipairs(arg) do
332                 for j, v in ipairs(a) do
333                         result[#result+1] = v
334                 end
335         end
336         return result
337 end
338
339 --- Checks whether the given table contains the given value.
340 -- @param table Table value
341 -- @param value Value to search within the given table
342 -- @return              Boolean indicating whether the given value occurs within table
343 function contains(table, value)
344         for k, v in pairs(table) do
345                 if value == v then
346                         return k
347                 end
348         end
349         return false
350 end
351
352 --- Update values in given table with the values from the second given table.
353 -- Both table are - in fact - merged together.
354 -- @param t                     Table which should be updated
355 -- @param updates       Table containing the values to update
356 -- @return                      Always nil
357 function update(t, updates)
358         for k, v in pairs(updates) do
359                 t[k] = v
360         end
361 end
362
363 --- Retrieve all keys of given associative table.
364 -- @param t     Table to extract keys from
365 -- @return      Sorted table containing the keys
366 function keys(t)
367         local keys = { }
368         if t then
369                 for k, _ in kspairs(t) do
370                         keys[#keys+1] = k
371                 end
372         end
373         return keys
374 end
375
376 --- Clones the given object and return it's copy.
377 -- @param object        Table value to clone
378 -- @param deep          Boolean indicating whether to do recursive cloning
379 -- @return                      Cloned table value
380 function clone(object, deep)
381         local copy = {}
382
383         for k, v in pairs(object) do
384                 if deep and type(v) == "table" then
385                         v = clone(v, deep)
386                 end
387                 copy[k] = v
388         end
389
390         return setmetatable(copy, getmetatable(object))
391 end
392
393
394 --- Create a dynamic table which automatically creates subtables.
395 -- @return      Dynamic Table
396 function dtable()
397         return setmetatable({}, { __index =
398                 function(tbl, key)
399                         return rawget(tbl, key)
400                          or rawget(rawset(tbl, key, dtable()), key)
401                 end
402         })
403 end
404
405
406 -- Serialize the contents of a table value.
407 function _serialize_table(t, seen)
408         assert(not seen[t], "Recursion detected.")
409         seen[t] = true
410         
411         local data  = ""
412         local idata = ""
413         local ilen  = 0
414
415         for k, v in pairs(t) do
416                 if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then
417                         k = serialize_data(k, seen)
418                         v = serialize_data(v, seen)
419                         data = data .. ( #data > 0 and ", " or "" ) ..
420                                 '[' .. k .. '] = ' .. v
421                 elseif k > ilen then
422                         ilen = k
423                 end
424         end
425
426         for i = 1, ilen do
427                 local v = serialize_data(t[i], seen)
428                 idata = idata .. ( #idata > 0 and ", " or "" ) .. v
429         end             
430
431         return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data
432 end
433
434 --- Recursively serialize given data to lua code, suitable for restoring
435 -- with loadstring().
436 -- @param val   Value containing the data to serialize
437 -- @return              String value containing the serialized code
438 -- @see                 restore_data
439 -- @see                 get_bytecode
440 function serialize_data(val, seen)
441         seen = seen or setmetatable({}, {__mode="k"})
442         
443         if val == nil then
444                 return "nil"
445         elseif type(val) == "number" then
446                 return val
447         elseif type(val) == "string" then
448                 return "%q" % val
449         elseif type(val) == "boolean" then
450                 return val and "true" or "false"
451         elseif type(val) == "function" then
452                 return "loadstring(%q)" % get_bytecode(val)
453         elseif type(val) == "table" then
454                 return "{ " .. _serialize_table(val, seen) .. " }"
455         else
456                 return '"[unhandled data type:' .. type(val) .. ']"'
457         end
458 end
459
460 --- Restore data previously serialized with serialize_data().
461 -- @param str   String containing the data to restore
462 -- @return              Value containing the restored data structure
463 -- @see                 serialize_data
464 -- @see                 get_bytecode
465 function restore_data(str)
466         return loadstring("return " .. str)()
467 end
468
469
470 --
471 -- Byte code manipulation routines
472 --
473
474 --- Return the current runtime bytecode of the given data. The byte code
475 -- will be stripped before it is returned.
476 -- @param val   Value to return as bytecode
477 -- @return              String value containing the bytecode of the given data
478 function get_bytecode(val)
479         local code
480
481         if type(val) == "function" then
482                 code = string.dump(val)
483         else
484                 code = string.dump( loadstring( "return " .. serialize_data(val) ) )
485         end
486
487         return code and strip_bytecode(code)
488 end
489
490 --- Strips unnescessary lua bytecode from given string. Information like line
491 -- numbers and debugging numbers will be discarded. Original version by
492 -- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
493 -- @param code  String value containing the original lua byte code
494 -- @return              String value containing the stripped lua byte code
495 function strip_bytecode(code)
496         local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
497         local subint
498         if endian == 1 then
499                 subint = function(code, i, l)
500                         local val = 0
501                         for n = l, 1, -1 do
502                                 val = val * 256 + code:byte(i + n - 1)
503                         end
504                         return val, i + l
505                 end
506         else
507                 subint = function(code, i, l)
508                         local val = 0
509                         for n = 1, l, 1 do
510                                 val = val * 256 + code:byte(i + n - 1)
511                         end
512                         return val, i + l
513                 end
514         end
515
516         local strip_function
517         strip_function = function(code)
518                 local count, offset = subint(code, 1, size)
519                 local stripped, dirty = string.rep("\0", size), offset + count
520                 offset = offset + count + int * 2 + 4
521                 offset = offset + int + subint(code, offset, int) * ins
522                 count, offset = subint(code, offset, int)
523                 for n = 1, count do
524                         local t
525                         t, offset = subint(code, offset, 1)
526                         if t == 1 then
527                                 offset = offset + 1
528                         elseif t == 4 then
529                                 offset = offset + size + subint(code, offset, size)
530                         elseif t == 3 then
531                                 offset = offset + num
532                         elseif t == 254 or t == 9 then
533                                 offset = offset + lnum
534                         end
535                 end
536                 count, offset = subint(code, offset, int)
537                 stripped = stripped .. code:sub(dirty, offset - 1)
538                 for n = 1, count do
539                         local proto, off = strip_function(code:sub(offset, -1))
540                         stripped, offset = stripped .. proto, offset + off - 1
541                 end
542                 offset = offset + subint(code, offset, int) * int + int
543                 count, offset = subint(code, offset, int)
544                 for n = 1, count do
545                         offset = offset + subint(code, offset, size) + size + int * 2
546                 end
547                 count, offset = subint(code, offset, int)
548                 for n = 1, count do
549                         offset = offset + subint(code, offset, size) + size
550                 end
551                 stripped = stripped .. string.rep("\0", int * 3)
552                 return stripped, offset
553         end
554
555         return code:sub(1,12) .. strip_function(code:sub(13,-1))
556 end
557
558
559 --
560 -- Sorting iterator functions
561 --
562
563 function _sortiter( t, f )
564         local keys = { }
565
566         for k, v in pairs(t) do
567                 keys[#keys+1] = k
568         end
569
570         local _pos = 0
571
572         table.sort( keys, f )
573
574         return function()
575                 _pos = _pos + 1
576                 if _pos <= #keys then
577                         return keys[_pos], t[keys[_pos]]
578                 end
579         end
580 end
581
582 --- Return a key, value iterator which returns the values sorted according to
583 -- the provided callback function.
584 -- @param t     The table to iterate
585 -- @param f A callback function to decide the order of elements
586 -- @return      Function value containing the corresponding iterator
587 function spairs(t,f)
588         return _sortiter( t, f )
589 end
590
591 --- Return a key, value iterator for the given table.
592 -- The table pairs are sorted by key.
593 -- @param t     The table to iterate
594 -- @return      Function value containing the corresponding iterator
595 function kspairs(t)
596         return _sortiter( t )
597 end
598
599 --- Return a key, value iterator for the given table.
600 -- The table pairs are sorted by value.
601 -- @param t     The table to iterate
602 -- @return      Function value containing the corresponding iterator
603 function vspairs(t)
604         return _sortiter( t, function (a,b) return t[a] < t[b] end )
605 end
606
607
608 --
609 -- System utility functions
610 --
611
612 --- Test whether the current system is operating in big endian mode.
613 -- @return      Boolean value indicating whether system is big endian
614 function bigendian()
615         return string.byte(string.dump(function() end), 7) == 0
616 end
617
618 --- Execute given commandline and gather stdout.
619 -- @param command       String containing command to execute
620 -- @return                      String containing the command's stdout
621 function exec(command)
622         local pp   = io.popen(command)
623         local data = pp:read("*a")
624         pp:close()
625
626         return data
627 end
628
629 --- Return a line-buffered iterator over the output of given command.
630 -- @param command       String containing the command to execute
631 -- @return                      Iterator
632 function execi(command)
633         local pp = io.popen(command)
634
635         return pp and function()
636                 local line = pp:read()
637                 
638                 if not line then
639                         pp:close()
640                 end
641                 
642                 return line
643         end
644 end
645
646 -- Deprecated
647 function execl(command)
648         local pp   = io.popen(command)
649         local line = ""
650         local data = {}
651
652         while true do
653                 line = pp:read()
654                 if (line == nil) then break end
655                 data[#data+1] = line
656         end
657         pp:close()
658
659         return data
660 end
661
662 --- Returns the absolute path to LuCI base directory.
663 -- @return              String containing the directory path
664 function libpath()
665         return require "luci.fs".dirname(ldebug.__file__)
666 end
667
668
669 --
670 -- Coroutine safe xpcall and pcall versions modified for Luci
671 -- original version:
672 -- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
673 --
674 -- Copyright © 2005 Kepler Project.
675 -- Permission is hereby granted, free of charge, to any person obtaining a
676 -- copy of this software and associated documentation files (the "Software"),
677 -- to deal in the Software without restriction, including without limitation
678 -- the rights to use, copy, modify, merge, publish, distribute, sublicense,
679 -- and/or sell copies of the Software, and to permit persons to whom the
680 -- Software is furnished to do so, subject to the following conditions:
681 --
682 -- The above copyright notice and this permission notice shall be
683 -- included in all copies or substantial portions of the Software.
684 --
685 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
686 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
687 -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
688 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
689 -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
690 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
691 -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
692
693 local performResume, handleReturnValue
694 local oldpcall, oldxpcall = pcall, xpcall
695 coxpt = {}
696 setmetatable(coxpt, {__mode = "kv"})
697
698 -- Identity function for copcall
699 local function copcall_id(trace, ...)
700   return ...
701 end
702
703 --- This is a coroutine-safe drop-in replacement for Lua's "xpcall"-function
704 -- @param f             Lua function to be called protected
705 -- @param err   Custom error handler
706 -- @param ...   Parameters passed to the function
707 -- @return              A boolean whether the function call succeeded and the return
708 --                              values of either the function or the error handler
709 function coxpcall(f, err, ...)
710         local res, co = oldpcall(coroutine.create, f)
711         if not res then
712                 local params = {...}
713                 local newf = function() return f(unpack(params)) end
714                 co = coroutine.create(newf)
715         end
716         local c = coroutine.running()
717         coxpt[co] = coxpt[c] or c or 0
718
719         return performResume(err, co, ...)
720 end
721
722 --- This is a coroutine-safe drop-in replacement for Lua's "pcall"-function
723 -- @param f             Lua function to be called protected
724 -- @param ...   Parameters passed to the function
725 -- @return              A boolean whether the function call succeeded and the returns
726 --                              values of the function or the error object
727 function copcall(f, ...)
728         return coxpcall(f, copcall_id, ...)
729 end
730
731 -- Handle return value of protected call
732 function handleReturnValue(err, co, status, ...)
733         if not status then
734                 return false, err(debug.traceback(co, (...)), ...)
735         end
736         if coroutine.status(co) == 'suspended' then
737                 return performResume(err, co, coroutine.yield(...))
738         else
739                 return true, ...
740         end
741 end
742
743 -- Resume execution of protected function call
744 function performResume(err, co, ...)
745         return handleReturnValue(err, co, coroutine.resume(co, ...))
746 end