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