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