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