libs/uvl: fix some memory wasting
[project/luci.git] / libs / uvl / luasrc / uvl.lua
1 --[[
2
3 UCI Validation Layer - Main Library
4 (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
5 (c) 2008 Steven Barth <steven@midlink.org>
6
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
10
11                 http://www.apache.org/licenses/LICENSE-2.0
12
13 $Id$
14
15 ]]--
16
17
18 --- UVL - UCI Validation Layer
19 -- @class       module
20 -- @cstyle      instance
21
22 local fs = require "nixio.fs"
23 local uci = require "luci.model.uci"
24 local util = require "luci.util"
25 local nutil = require "nixio.util"
26 local table = require "table"
27 local string = require "string"
28
29 local require, pcall, ipairs, pairs = require, pcall, ipairs, pairs
30 local type, error, tonumber, tostring = type, error, tonumber, tostring
31 local unpack, loadfile, collectgarbage = unpack, loadfile, collectgarbage
32
33 module "luci.uvl"
34
35 local ERR = require "luci.uvl.errors"
36 local datatypes = require "luci.uvl.datatypes"
37 local validation = require "luci.uvl.validation"
38 local dependencies = require "luci.uvl.dependencies"
39
40 local TYPE_SCHEME   = 0x00
41 local TYPE_CONFIG   = 0x01
42 local TYPE_SECTION  = 0x02
43 local TYPE_OPTION   = 0x03
44 local TYPE_ENUM     = 0x04
45
46 local PAT_EXPR1         = "^%$?[%w_]+$"
47 local PAT_EXPR2         = "^%$?[%w_]+%.%$?[%w_]+$"
48 local PAT_EXPR3         = "^%$?[%w_]+%.%$?[%w_]+%.%$?[%w_]+$"
49
50 --- Boolean; default true;
51 -- treat sections found in config but not in scheme as error
52 STRICT_UNKNOWN_SECTIONS    = true
53
54 --- Boolean; default true;
55 -- treat options found in config but not in scheme as error
56 STRICT_UNKNOWN_OPTIONS     = true
57
58 --- Boolean; default true;
59 -- treat failed external validators as error
60 STRICT_EXTERNAL_VALIDATORS = true
61
62 --- Boolean; default true;
63 -- treat list values stored as options like errors
64 STRICT_LIST_TYPE           = true
65
66
67 local default_schemedir = "/lib/uci/schema"
68 local default_savedir = "/tmp/.uvl"
69
70
71 --- Object constructor
72 -- @class                       function
73 -- @name                        UVL
74 -- @param schemedir     Path to the scheme directory (optional)
75 -- @param configdir     Override config directory (optional)
76 -- @return                      Instance object
77 UVL = util.class()
78
79 function UVL.__init__( self, schemedir, configdir )
80         self.schemedir  = schemedir or default_schemedir
81         self.configdir  = configdir
82         self.packages   = { }
83         self.beenthere  = { }
84         self.depseen    = { }
85         self.uci                = uci
86         self.err                = ERR
87         self.dep                = dependencies
88         self.datatypes  = datatypes
89 end
90
91
92 --- Parse given scheme and return the scheme tree.
93 -- @param scheme        Name of the scheme to parse
94 -- @return                      Table containing the parsed scheme or nil on error
95 -- @return                      String containing the reason for errors (if any)
96 function UVL.get_scheme( self, scheme )
97         if not self.packages[scheme] then
98                 local ok, err = self:read_scheme( scheme )
99                 if not ok then
100                         return nil, err
101                 end
102         end
103         return self.packages[scheme], nil
104 end
105
106 --- Validate given configuration, section or option.
107 -- @param config        Name of the configuration to validate
108 -- @param section       Name of the section to validate (optional)
109 -- @param option        Name of the option to validate (optional)
110 -- @return                      Boolean indicating whether the given config validates
111 -- @return                      String containing the reason for errors (if any)
112 function UVL.validate( self, config, section, option )
113         if config and section and option then
114                 return self:validate_option( config, section, option )
115         elseif config and section then
116                 return self:validate_section( config, section )
117         elseif config then
118                 return self:validate_config( config )
119         end
120 end
121
122 --- Validate given configuration.
123 -- @param cfg   Name of the configuration to validate
124 -- @return                      Boolean indicating whether the given config validates
125 -- @return                      String containing the reason for errors (if any)
126 function UVL.validate_config( self, cfg, uci )
127
128         if not self.packages[cfg] then
129                 local ok, err = self:read_scheme(cfg)
130                 if not ok then
131                         return false, err
132                 end
133         end
134
135         local co = config( self, uci or cfg, uci and cfg )
136         local sc = { }
137
138         self.beenthere = { }
139         self.depseen   = { }
140
141         if not co:config() then
142                 return false, co:errors()
143         end
144
145         local function _uci_foreach( type, func )
146                 for k, v in pairs(co:config()) do
147                         if v['.type'] == type then
148                                 sc[type] = sc[type] + 1
149                                 local ok, err = func( k, v )
150                                 if not ok then co:error(err) end
151                         end
152                 end
153         end
154
155         for k, v in pairs( self.packages[cfg].sections ) do
156                 sc[k] = 0
157                 _uci_foreach( k,
158                         function(s)
159                                 return self:_validate_section( co:section(s) )
160                         end
161                 )
162         end
163
164         if STRICT_UNKNOWN_SECTIONS then
165                 for k, v in pairs(co:config()) do
166                         local so = co:section(k)
167                         if not self.beenthere[so:cid()] then
168                                 co:error(ERR.SECT_UNKNOWN(so))
169                         end
170                 end
171         end
172
173         for _, k in ipairs(util.keys(sc)) do
174                 local so = co:section(k)
175                 if so:scheme('required') and sc[k] == 0 then
176                         co:error(ERR.SECT_REQUIRED(so))
177                 elseif so:scheme('unique') and sc[k] > 1 then
178                         co:error(ERR.SECT_UNIQUE(so))
179                 end
180         end
181
182         return co:ok(), co:errors()
183 end
184
185 --- Validate given config section.
186 -- @param config        Name of the configuration to validate
187 -- @param section       Name of the section to validate
188 -- @return                      Boolean indicating whether the given config validates
189 -- @return                      String containing the reason for errors (if any)
190 function UVL.validate_section( self, cfg, section, uci )
191
192         if not self.packages[cfg] then
193                 local ok, err = self:read_scheme( cfg )
194                 if not ok then
195                         return false, err
196                 end
197         end
198
199         local co = config( self, uci or cfg, uci and cfg )
200         local so = co:section( section )
201
202         self.beenthere = { }
203         self.depseen   = { }
204
205         if not co:config() then
206                 return false, co:errors()
207         end
208
209         if so:config() then
210                 return self:_validate_section( so )
211         else
212                 return false, ERR.SECT_NOTFOUND(so)
213         end
214 end
215
216 --- Validate given config option.
217 -- @param config        Name of the configuration to validate
218 -- @param section       Name of the section to validate
219 -- @param option        Name of the option to validate
220 -- @return                      Boolean indicating whether the given config validates
221 -- @return                      String containing the reason for errors (if any)
222 function UVL.validate_option( self, cfg, section, option, uci )
223
224         if not self.packages[cfg] then
225                 local ok, err = self:read_scheme( cfg )
226                 if not ok then
227                         return false, err
228                 end
229         end
230
231         local co = config( self, uci or cfg, uci and cfg )
232         local so = co:section( section )
233         local oo = so:option( option )
234
235         if not co:config() then
236                 return false, co:errors()
237         end
238
239         if so:config() and oo:config() then
240                 return self:_validate_option( oo )
241         else
242                 return false, ERR.OPT_NOTFOUND(oo)
243         end
244 end
245
246
247 function UVL._validate_section( self, section )
248
249         self.beenthere[section:cid()] = true
250
251         if section:config() then
252                 if section:scheme('named') == true and
253                    section:config('.anonymous') == true
254                 then
255                         return false, ERR.SECT_NAMED(section)
256                 end
257
258                 for _, v in ipairs(section:variables()) do
259                         local ok, err = self:_validate_option( v )
260                         if not ok and (
261                                 v:scheme('required') or v:scheme('type') == "enum" or (
262                                         not err:is(ERR.ERR_DEP_NOTEQUAL) and
263                                         not err:is(ERR.ERR_DEP_NOVALUE)
264                                 )
265                         ) then
266                                 section:error(err)
267                         end
268                 end
269
270                 local ok, err = dependencies.check( self, section )
271                 if not ok then
272                         section:error(err)
273                 end
274         else
275                 return false, ERR.SECT_NOTFOUND(section)
276         end
277
278         if STRICT_UNKNOWN_OPTIONS and not section:scheme('dynamic') then
279                 for k, v in pairs(section:config()) do
280                         local oo = section:option(k)
281                         if k:byte(1) == 46 and not self.beenthere[oo:cid()] then
282                                 section:error(ERR.OPT_UNKNOWN(oo))
283                         end
284                 end
285         end
286
287         return section:ok(), section:errors()
288 end
289
290 function UVL._validate_option( self, option, nodeps )
291
292         self.beenthere[option:cid()] = true
293
294         if not option:scheme() and not option:parent():scheme('dynamic') then
295                 if STRICT_UNKNOWN_OPTIONS then
296                         return false, option:error(ERR.OPT_UNKNOWN(option))
297                 else
298                         return true
299                 end
300
301         elseif option:scheme() then
302                 if not nodeps then
303                         local ok, err = dependencies.check( self, option )
304                         if not ok then
305                                 if not err:is_all(
306                                         ERR.ERR_OPT_REQUIRED,
307                                         ERR.ERR_DEP_NOTEQUAL,
308                                         ERR.ERR_DEP_NOVALUE
309                                 ) then
310                                         option:error(err)
311                                         return false, option:errors()
312                                 else
313                                         return true
314                                 end
315                         end
316                 end
317
318                 if option:scheme('required') and not option:value() then
319                         return false, option:error(ERR.OPT_REQUIRED(option))
320
321                 elseif option:value() then
322                         local val = option:value()
323
324                         if option:scheme('type') == "reference" or
325                            option:scheme('type') == "enum"
326                         then
327                                 local scheme_values = option:scheme('values') or { }
328                                 local config_values = ( type(val) == "table" and val or { val } )
329                                 for _, v in ipairs(config_values) do
330                                         if not scheme_values[v] then
331                                                 return false, option:error( ERR.OPT_BADVALUE(
332                                                         option, { v, util.serialize_data(
333                                                                 util.keys(scheme_values)
334                                                         ) }
335                                                 ) )
336                                         end
337                                 end
338                         elseif option:scheme('type') == "list" then
339                                 if type(val) ~= "table" and STRICT_LIST_TYPE then
340                                         return false, option:error(ERR.OPT_NOTLIST(option))
341                                 end
342                         end
343
344                         if option:scheme('datatype') then
345                                 local dt = option:scheme('datatype')
346
347                                 if self.datatypes[dt] then
348                                         val = ( type(val) == "table" and val or { val } )
349                                         for i, v in ipairs(val) do
350                                                 if not self.datatypes[dt]( v ) then
351                                                         return false, option:error(
352                                                                 ERR.OPT_INVVALUE(option, { v, dt })
353                                                         )
354                                                 end
355                                         end
356                                 else
357                                         return false, option:error(ERR.OPT_DATATYPE(option, dt))
358                                 end
359                         end
360
361                         val = ( type(val) == "table" and val or { val } )
362                         for _, v in ipairs(val) do
363                                 if option:scheme('minlength') then
364                                         if #v < option:scheme('minlength') then
365                                                 return false, option:error(ERR.OPT_RANGE(option))
366                                         end
367                                 end
368
369                                 if option:scheme('maxlength') then
370                                         if #v > option:scheme('maxlength') then
371                                                 return false, option:error(ERR.OPT_RANGE(option))
372                                         end
373                                 end
374
375                                 local w = tonumber(v)
376
377                                 if option:scheme('minimum') then
378                                         if not w or w < option:scheme('minimum') then
379                                                 return false, option:error(ERR.OPT_RANGE(option))
380                                         end
381                                 end
382
383                                 if option:scheme('maximum') then
384                                         if not w or w > option:scheme('maximum') then
385                                                 return false, option:error(ERR.OPT_RANGE(option))
386                                         end
387                                 end
388                         end
389                 end
390
391                 local ok, err = validation.check( self, option )
392                 if not ok and STRICT_EXTERNAL_VALIDATORS then
393                         return false, option:error(err)
394                 end
395         end
396
397         return option:ok(), option:errors()
398 end
399
400 --- Find all parts of given scheme and construct validation tree.
401 -- This is normally done on demand, so you don't have to call this function
402 -- by yourself.
403 -- @param shm   Name of the scheme to parse
404 -- @param alias         Create an alias for the loaded scheme
405 function UVL.read_scheme( self, shm, alias )
406
407         local so = scheme( self, shm )
408         local bc = "%s/bytecode/%s.lua" %{ self.schemedir, shm }
409
410         if not fs.access(bc) then
411                 local files = nutil.consume((fs.glob(self.schemedir .. '/*/' .. shm)))
412
413                 if #files > 0 then
414                         local ok, err
415                         for _, file in ipairs(files) do
416                                 if not fs.access(file) then
417                                         return false, so:error(ERR.SME_READ(so,file))
418                                 end
419
420                                 local uci = uci.cursor( fs.dirname(file), default_savedir )
421
422                                 local sname = fs.basename(file)
423                                 local sd, err = uci:load( sname )
424
425                                 if not sd then
426                                         return false, ERR.UCILOAD(so, err)
427                                 end
428
429                                 ok, err = pcall(function()
430                                         uci:foreach(sname, "package", function(s)
431                                                 self:_parse_package(so, s[".name"], s)
432                                         end)
433                                         uci:foreach(sname, "section", function(s)
434                                                 self:_parse_section(so, s[".name"], s)
435                                         end)
436                                         uci:foreach(sname, "variable", function(s)
437                                                 self:_parse_var(so, s[".name"], s)
438                                         end)
439                                         uci:foreach(sname, "enum", function(s)
440                                                 self:_parse_enum(so, s[".name"], s)
441                                         end)
442
443                                 end)
444                         end
445
446                         if ok and alias then self.packages[alias] = self.packages[shm] end
447                         return ok and self, err
448                 else
449                         return false, so:error(ERR.SME_FIND(so, self.schemedir))
450                 end
451         else
452                 local sc = loadfile(bc)
453                 if sc then
454                         self.packages[shm] = sc()
455                         return true
456                 else
457                         return false, so:error(ERR.SME_READ(so,bc))
458                 end
459         end
460 end
461
462 -- helper function to check for required fields
463 local function _req( t, n, c, r )
464         for i, v in ipairs(r) do
465                 if not c[v] then
466                         local p, o = scheme:sid(), nil
467
468                         if t == TYPE_SECTION then
469                                 o = section( scheme, nil, p, n )
470                         elseif t == TYPE_OPTION then
471                                 o = option( scheme, nil, p, '(nil)', n )
472                         elseif t == TYPE_ENUM then
473                                 o = enum( scheme, nil, p, '(nil)', '(nil)', n )
474                         end
475
476                         return false, ERR.SME_REQFLD(o,v)
477                 end
478         end
479         return true
480 end
481
482 -- helper function to validate references
483 local function _ref( c, t )
484         local r, k, n = {}
485         if c == TYPE_SECTION then
486                 k = "package"
487                 n = 1
488         elseif c == TYPE_OPTION then
489                 k = "section"
490                 n = 2
491         elseif c == TYPE_ENUM then
492                 k = "variable"
493                 n = 3
494         end
495
496         for o in t[k]:gmatch("[^.]+") do
497                 r[#r+1] = o
498         end
499         r[1] = ( #r[1] > 0 and r[1] or scheme:sid() )
500
501         if #r ~= n then
502                 return false, ERR.SME_BADREF(scheme, k)
503         end
504
505         return r
506 end
507
508 -- helper function to read bools
509 local function _bool( v )
510         return ( v == "true" or v == "yes" or v == "on" or v == "1" )
511 end
512
513 -- Step 0: get package meta information
514 function UVL._parse_package(self, scheme, k, v)
515         local sid = scheme:sid()
516         local pkg = self.packages[sid] or {
517                 ["name"]      = sid;
518                 ["sections"]  = { };
519                 ["variables"] = { };
520         }
521
522         pkg.title = v.title
523         pkg.description = v.description
524
525         self.packages[sid] = pkg
526 end
527
528 -- Step 1: get all sections
529 function UVL._parse_section(self, scheme, k, v)
530         local ok, err = _req( TYPE_SECTION, k, v, { "name", "package" } )
531         if err then error(scheme:error(err)) end
532
533         local r, err = _ref( TYPE_SECTION, v )
534         if err then error(scheme:error(err)) end
535
536         local p = self.packages[r[1]] or {
537                 ["name"]      = r[1];
538                 ["sections"]  = { };
539                 ["variables"] = { };
540         }
541         p.sections[v.name]  = p.sections[v.name]  or { }
542         p.variables[v.name] = p.variables[v.name] or { }
543         self.packages[r[1]] = p
544
545         local s  = p.sections[v.name]
546         local so = scheme:section(v.name)
547
548         for k, v2 in pairs(v) do
549                 if k ~= "name" and k ~= "package" and k:byte(1) == 46 then
550                         if k == "depends" then
551                                 s.depends = self:_read_dependency( v2, s.depends )
552                                 if not s.depends then
553                                         return false, scheme:error(
554                                                 ERR.SME_BADDEP(so, util.serialize_data(s.depends))
555                                         )
556                                 end
557                         elseif k == "dynamic" or k == "unique" or
558                                k == "required" or k == "named"
559                         then
560                                 s[k] = _bool(v2)
561                         else
562                                 s[k] = v2
563                         end
564                 end
565         end
566
567         s.dynamic  = s.dynamic  or false
568         s.unique   = s.unique   or false
569         s.required = s.required or false
570         s.named    = s.named    or false
571 end
572
573 -- Step 2: get all variables
574 function UVL._parse_var(self, scheme, k, v)
575         local ok, err = _req( TYPE_OPTION, k, v, { "name", "section" } )
576         if err then error(scheme:error(err)) end
577
578         local r, err = _ref( TYPE_OPTION, v )
579         if err then error(scheme:error(err)) end
580
581         local p = self.packages[r[1]]
582         if not p then
583                 error(scheme:error(
584                         ERR.SME_VBADPACK({scheme:sid(), '', v.name}, r[1])
585                 ))
586         end
587
588         local s = p.variables[r[2]]
589         if not s then
590                 error(scheme:error(
591                         ERR.SME_VBADSECT({scheme:sid(), '', v.name}, r[2])
592                 ))
593         end
594
595         s[v.name] = s[v.name] or { }
596
597         local t  = s[v.name]
598         local so = scheme:section(r[2])
599         local to = so:option(v.name)
600
601         for k, v2 in pairs(v) do
602                 if k ~= "name" and k ~= "section" and k:byte(1) == 46 then
603                         if k == "depends" then
604                                 t.depends = self:_read_dependency( v2, t.depends )
605                                 if not t.depends then
606                                         error(scheme:error(so:error(
607                                                 ERR.SME_BADDEP(to, util.serialize_data(v2))
608                                         )))
609                                 end
610                         elseif k == "validator" then
611                                 t.validators = self:_read_validator( v2, t.validators )
612                                 if not t.validators then
613                                         error(scheme:error(so:error(
614                                                 ERR.SME_BADVAL(to, util.serialize_data(v2))
615                                         )))
616                                 end
617                         elseif k == "valueof" then
618                                 local values, err = self:_read_reference( v2 )
619                                 if err then
620                                         error(scheme:error(so:error(
621                                                 ERR.REFERENCE(to, util.serialize_data(v2)):child(err)
622                                         )))
623                                 end
624                                 t.type   = "reference"
625                                 t.values = values
626                                 t.valueof = type(v2) == "table" and v2 or {v2}
627                         elseif k == "required" then
628                                 t[k] = _bool(v2)
629                         elseif k == "minlength" or k == "maxlength" or
630                    k == "minimum" or k == "maximum"
631             then
632                                 t[k] = tonumber(v2)
633                         else
634                                 t[k] = t[k] or v2
635                         end
636                 end
637         end
638
639         t.type     = t.type     or "variable"
640         t.datatype = t.datatype or "string"
641         t.required = t.required or false
642 end
643
644 -- Step 3: get all enums
645 function UVL._parse_enum(self, scheme, k, v)
646         local ok, err = _req( TYPE_ENUM, k, v, { "value", "variable" } )
647         if err then error(scheme:error(err)) end
648
649         local r, err = _ref( TYPE_ENUM, v )
650         if err then error(scheme:error(err)) end
651
652         local p = self.packages[r[1]]
653         if not p then
654                 error(scheme:error(
655                         ERR.SME_EBADPACK({scheme:sid(), '', '', v.value}, r[1])
656                 ))
657         end
658
659         local s = p.variables[r[2]]
660         if not s then
661                 error(scheme:error(
662                         ERR.SME_EBADSECT({scheme:sid(), '', '', v.value}, r[2])
663                 ))
664         end
665
666         local t = s[r[3]]
667         if not t then
668                 error(scheme:error(
669                         ERR.SME_EBADOPT({scheme:sid(), '', '', v.value}, r[3])
670                 ))
671         end
672
673
674         local so = scheme:section(r[2])
675         local oo = so:option(r[3])
676         local eo = oo:enum(v.value)
677
678         if t.type ~= "enum" and t.type ~= "reference" then
679                 error(scheme:error(ERR.SME_EBADTYPE(eo)))
680         end
681
682         if not t.values then
683                 t.values = { [v.value] = v.title or v.value }
684                 t.valuelist = { {value = v.value, title = v.title} }
685         else
686                 t.values[v.value] = v.title or v.value
687                 t.valuelist[#t.valuelist + 1] = {value = v.value, title = v.title}
688         end
689
690         if not t.enum_depends then
691                 t.enum_depends = { }
692         end
693
694         if v.default then
695                 if t.default then
696                         error(scheme:error(ERR.SME_EBADDEF(eo)))
697                 end
698                 t.default = v.value
699         end
700
701         if v.depends then
702                 t.enum_depends[v.value] = self:_read_dependency(
703                         v.depends, t.enum_depends[v.value]
704                 )
705
706                 if not t.enum_depends[v.value] then
707                         error(scheme:error(so:error(oo:error(
708                                 ERR.SME_BADDEP(eo, util.serialize_data(v.depends))
709                         ))))
710                 end
711         end
712 end
713
714 -- Read a dependency specification
715 function UVL._read_dependency( self, values, deps )
716         local expr = "%$?[%w_]+"
717         if values then
718                 values = ( type(values) == "table" and values or { values } )
719                 for _, value in ipairs(values) do
720                         local condition = { }
721                         for val in value:gmatch("[^,]+") do
722                                 local k, e, v = val:match("%s*([%w$_.]+)%s*(=?)%s*(.*)")
723
724                                 if k and (
725                                         k:match(PAT_EXPR1) or k:match(PAT_EXPR2) or k:match(PAT_EXPR3)
726                                 ) then
727                                         condition[k] = (e == '=') and v or true
728                                 else
729                                         return nil
730                                 end
731                         end
732
733                         if not deps then
734                                 deps = { condition }
735                         else
736                                 deps[#deps+1] = condition
737                         end
738                 end
739         end
740
741         return deps
742 end
743
744 -- Read a validator specification
745 function UVL._read_validator( self, values, validators )
746         if values then
747                 values = ( type(values) == "table" and values or { values } )
748                 for _, value in ipairs(values) do
749                         local validator
750
751                         if value:match("^exec:") then
752                                 validator = value:gsub("^exec:","")
753                         elseif value:match("^lua:") then
754                                 validator = self:_resolve_function( (value:gsub("^lua:","") ) )
755                         elseif value:match("^regexp:") then
756                                 local pattern = value:gsub("^regexp:","")
757                                 validator = function( type, dtype, pack, sect, optn, arg1, arg2, arg3, arg4, arg5 )
758                                         local values = { arg1, arg2, arg3, arg4, arg5 }
759                                         for _, v in ipairs(values) do
760                                                 local ok, match =
761                                                         pcall( string.match, v, pattern )
762
763                                                 if not ok then
764                                                         return false, match
765                                                 elseif not match then
766                                                         return false,
767                                                                 'Value "%s" does not match pattern "%s"' % {
768                                                                         v, pattern
769                                                                 }
770                                                 end
771                                         end
772                                         return true
773                                 end
774                         end
775
776                         if validator then
777                                 if not validators then
778                                         validators = { validator }
779                                 else
780                                         validators[#validators+1] = validator
781                                 end
782                         else
783                                 return nil
784                         end
785                 end
786
787                 return validators
788         end
789 end
790
791 -- Read a reference specification (XXX: We should validate external configs too...)
792 function UVL._read_reference( self, values )
793         local val = { }
794         values = ( type(values) == "table" and values or { values } )
795
796         for _, value in ipairs(values) do
797                 local ref = util.split(value, ".")
798
799                 if #ref == 2 or #ref == 3 then
800                         local co = config( self, ref[1] )
801                         if not co:config() then return false, co:errors() end
802
803                         for k, v in pairs(co:config()) do
804                                 if v['.type'] == ref[2] then
805                                         if #ref == 2 then
806                                                 if v['.anonymous'] == true then
807                                                         return false, ERR.SME_INVREF('', value)
808                                                 end
809                                                 val[k] = k      -- XXX: title/description would be nice
810                                         elseif v[ref[3]] then
811                                                 val[v[ref[3]]] = v[ref[3]]  -- XXX: dito
812                                         end
813                                 end
814                         end
815                 else
816                         return false, ERR.SME_BADREF('', value)
817                 end
818         end
819
820         return val, nil
821 end
822
823 -- Resolve given path
824 function UVL._resolve_function( self, value )
825         local path = util.split(value, ".")
826
827         for i=1, #path-1 do
828                 local stat, mod = pcall(
829                         require, table.concat(path, ".", 1, i)
830                 )
831
832                 if stat and mod then
833                         for j=i+1, #path-1 do
834                                 if not type(mod) == "table" then
835                                         break
836                                 end
837                                 mod = mod[path[j]]
838                                 if not mod then
839                                         break
840                                 end
841                         end
842                         mod = type(mod) == "table" and mod[path[#path]] or nil
843                         if type(mod) == "function" then
844                                 return mod
845                         end
846                 end
847         end
848 end
849
850
851 --- Object representation of an uvl item - base class.
852 uvlitem = util.class()
853
854 function uvlitem.cid(self)
855         if #self.cref == 1 then
856                 return self.cref[1]
857         else
858                 local r = { unpack(self.cref) }
859                 local c = self.c
860                 if c and c[r[2]] and c[r[2]]['.anonymous'] and c[r[2]]['.index'] then
861                         r[2] = '@' .. c[r[2]]['.type'] ..
862                                    '[' .. tostring(c[r[2]]['.index']) .. ']'
863                 end
864                 return table.concat( r, '.' )
865         end
866 end
867
868 function uvlitem.sid(self)
869         return table.concat( self.sref, '.' )
870 end
871
872 function uvlitem.scheme(self, opt)
873         local s = self.s and self.s.packages
874         s = s      and s[self.sref[1]]
875         if #self.sref == 4 or #self.sref == 3 then
876                 s = s      and s.variables
877                 s = s      and s[self.sref[2]]
878                 s = s      and s[self.sref[3]]
879         elseif #self.sref == 2 then
880                 s = s      and s.sections
881                 s = s      and s[self.sref[2]]
882         end
883
884         if s and opt then
885                 return s[opt]
886         elseif s then
887                 return s
888         end
889 end
890
891 function uvlitem.config(self, opt)
892         local c = self.c
893
894         if #self.cref >= 2 and #self.cref <= 4 then
895                 c = c and self.c[self.cref[2]] or nil
896                 if #self.cref >= 3 then
897                         c = c and c[self.cref[3]] or nil
898                 end
899         end
900
901         if c and opt then
902                 return c[opt]
903         elseif c then
904                 return c
905         end
906 end
907
908 function uvlitem.title(self)
909         return self:scheme() and self:scheme('title') or
910                 self.cref[3] or self.cref[2] or self.cref[1]
911 end
912
913 function uvlitem.type(self)
914         if self.t == TYPE_CONFIG then
915                 return 'config'
916         elseif self.t == TYPE_SECTION then
917                 return 'section'
918         elseif self.t == TYPE_OPTION then
919                 return 'option'
920         elseif self.t == TYPE_ENUM then
921                 return 'enum'
922         end
923 end
924
925 function uvlitem.error(self, arg1, arg2, arg3, arg4, arg5)
926         if not self.e then
927                 local errconst = { ERR.CONFIG, ERR.SECTION, ERR.OPTION, ERR.OPTION }
928                 self.e = errconst[#self.cref]( self )
929         end
930
931         return self.e:child( arg1, arg2, arg3, arg4, arg5 )
932 end
933
934 function uvlitem.errors(self)
935         return self.e
936 end
937
938 function uvlitem.ok(self)
939         return not self:errors()
940 end
941
942 function uvlitem.parent(self)
943         if self.p then
944                 return self.p
945         elseif #self.cref == 3 or #self.cref == 4 then
946                 return section( self.s, self.c, self.cref[1], self.cref[2] )
947         elseif #self.cref == 2 then
948                 return config( self.s, self.c, self.cref[1] )
949         else
950                 return nil
951         end
952 end
953
954 function uvlitem._loadconf(self, co, c, configdir)
955         co = co or self._configcache
956         if not co then
957                 local err
958                 co, err = uci.cursor(configdir):get_all(c)
959
960                 if err then
961                         self:error(ERR.UCILOAD(self, err))
962                 end
963
964                 self._configcache = co
965         end
966         return co
967 end
968
969
970 --- Object representation of a scheme.
971 -- @class       scheme
972 -- @cstyle      instance
973 -- @name        luci.uvl.scheme
974
975 --- Scheme instance constructor.
976 -- @class                       function
977 -- @name                        scheme
978 -- @param scheme        Scheme instance
979 -- @param co            Configuration data
980 -- @param c                     Configuration name
981 -- @return                      Config instance
982 scheme = util.class(uvlitem)
983
984 function scheme.__init__(self, scheme, co, c)
985         if not c then
986                 c, co = co, nil
987         end
988
989         self.cref = { c }
990         self.sref = { c }
991         self.c    = self:_loadconf(co, c, scheme.configdir)
992         self.s    = scheme
993         self.t    = TYPE_SCHEME
994 end
995
996 --- Add an error to scheme.
997 -- @return      Scheme error context
998 function scheme.error(self, arg1, arg2, arg3, arg4, arg5)
999         if not self.e then self.e = ERR.SCHEME( self ) end
1000         return self.e:child( arg1, arg2, arg3, arg4, arg5 )
1001 end
1002
1003 --- Get an associated config object.
1004 -- @return      Config instance
1005 function scheme.config(self)
1006         local co = config( self.s, self.cref[1] )
1007               co.p = self
1008
1009         return co
1010 end
1011
1012 --- Get all section objects associated with this scheme.
1013 -- @return      Table containing all associated luci.uvl.section instances
1014 function scheme.sections(self)
1015         local v = { }
1016         if self.s.packages[self.sref[1]].sections then
1017                 for o, _ in pairs( self.s.packages[self.sref[1]].sections ) do
1018                         v[#v+1] = option(
1019                                 self.s, self.c, self.cref[1], self.cref[2], o
1020                         )
1021                 end
1022         end
1023         return v
1024 end
1025
1026 --- Get an associated section object.
1027 -- @param s     Section to select
1028 -- @return      Section instance
1029 function scheme.section(self, s)
1030         local so = section( self.s, self.c, self.cref[1], s )
1031               so.p = self
1032
1033         return so
1034 end
1035
1036
1037 --- Object representation of a config.
1038 -- @class       config
1039 -- @cstyle      instance
1040 -- @name        luci.uvl.config
1041
1042 --- Config instance constructor.
1043 -- @class                       function
1044 -- @name                        config
1045 -- @param scheme        Scheme instance
1046 -- @param co            Configuration data
1047 -- @param c                     Configuration name
1048 -- @return                      Config instance
1049 config = util.class(uvlitem)
1050
1051 function config.__init__(self, scheme, co, c)
1052         if not c then
1053                 c, co = co, nil
1054         end
1055         self.cref = { c }
1056         self.sref = { c }
1057         self.c    = self:_loadconf(co, c, scheme.configdir)
1058         self.s    = scheme
1059         self.t    = TYPE_CONFIG
1060 end
1061
1062 --- Get all section objects associated with this config.
1063 -- @return      Table containing all associated luci.uvl.section instances
1064 function config.sections(self)
1065         local v = { }
1066         if self.s.packages[self.sref[1]].sections then
1067                 for o, _ in pairs( self.s.packages[self.sref[1]].sections ) do
1068                         v[#v+1] = option(
1069                                 self.s, self.c, self.cref[1], self.cref[2], o
1070                         )
1071                 end
1072         end
1073         return v
1074 end
1075
1076 --- Get an associated section object.
1077 -- @param s     Section to select
1078 -- @return      Section instance
1079 function config.section(self, s)
1080         local so = section( self.s, self.c, self.cref[1], s )
1081               so.p = self
1082
1083         return so
1084 end
1085
1086
1087 --- Object representation of a scheme/config section.
1088 -- @class       module
1089 -- @cstyle      instance
1090 -- @name        luci.uvl.section
1091
1092 --- Section instance constructor.
1093 -- @class                       function
1094 -- @name                        section
1095 -- @param scheme        Scheme instance
1096 -- @param co            Configuration data
1097 -- @param c                     Configuration name
1098 -- @param s                     Section name
1099 -- @return                      Section instance
1100 section = util.class(uvlitem)
1101
1102 function section.__init__(self, scheme, co, c, s)
1103         self.cref = { c, s }
1104         self.sref = { c, co and co[s] and co[s]['.type'] or s }
1105         self.c    = self:_loadconf(co, c, scheme.configdir)
1106         self.s    = scheme
1107         self.t    = TYPE_SECTION
1108 end
1109
1110 --- Get all option objects associated with this section.
1111 -- @return      Table containing all associated luci.uvl.option instances
1112 function section.variables(self)
1113         local v = { }
1114         if self.s.packages[self.sref[1]].variables[self.sref[2]] then
1115                 for o, _ in pairs(
1116                         self.s.packages[self.sref[1]].variables[self.sref[2]]
1117                 ) do
1118                         v[#v+1] = option(
1119                                 self.s, self.c, self.cref[1], self.cref[2], o
1120                         )
1121                 end
1122         end
1123         return v
1124 end
1125
1126 --- Get an associated option object.
1127 -- @param o     Option to select
1128 -- @return      Option instance
1129 function section.option(self, o)
1130         local oo = option( self.s, self.c, self.cref[1], self.cref[2], o )
1131               oo.p = self
1132
1133         return oo
1134 end
1135
1136
1137 --- Object representation of a scheme/config option.
1138 -- @class       module
1139 -- @cstyle      instance
1140 -- @name        luci.uvl.option
1141
1142 --- Section instance constructor.
1143 -- @class                       function
1144 -- @name                        option
1145 -- @param scheme        Scheme instance
1146 -- @param co            Configuration data
1147 -- @param c                     Configuration name
1148 -- @param s                     Section name
1149 -- @param o                     Option name
1150 -- @return                      Option instance
1151 option = util.class(uvlitem)
1152
1153 function option.__init__(self, scheme, co, c, s, o)
1154         self.cref = { c, s, o }
1155         self.sref = { c, co and co[s] and co[s]['.type'] or s, o }
1156         self.c    = self:_loadconf(co, c, scheme.configdir)
1157         self.s    = scheme
1158         self.t    = TYPE_OPTION
1159 end
1160
1161 --- Get the value of this option.
1162 -- @return      The associated configuration value
1163 function option.value(self)
1164         local v = self:config() or self:scheme('default')
1165         if v and self:scheme('multival') then
1166                 v = util.split( v, "%s+", nil, true )
1167         end
1168         return v
1169 end
1170
1171 --- Get the associated section information in scheme.
1172 -- @return      Table containing the scheme properties
1173 function option.section(self)
1174         return self.s.packages[self.sref[1]].sections[self.sref[2]]
1175 end
1176
1177 --- Construct an enum object instance from given or default value.
1178 -- @param v     Value to select
1179 -- @return      Enum instance for selected value
1180 function option.enum(self, val)
1181         return enum(
1182                 self.s, self.c,
1183                 self.cref[1], self.cref[2], self.cref[3],
1184                 val or self:value()
1185         )
1186 end
1187
1188
1189 --- Object representation of a enum value.
1190 -- @class       module
1191 -- @cstyle      instance
1192 -- @name        luci.uvl.enum
1193
1194 --- Section instance constructor.
1195 -- @class                       function
1196 -- @name                        enum
1197 -- @param scheme        Scheme instance
1198 -- @param co            Configuration data
1199 -- @param c                     Configuration name
1200 -- @param s                     Section name
1201 -- @param o                     Enum name
1202 -- @param v                     Enum value
1203 -- @return                      Enum value instance
1204 enum = util.class(option)
1205
1206 function enum.__init__(self, scheme, co, c, s, o, v)
1207         self.cref = { c, s, o, v }
1208         self.sref = { c, co and co[s] and co[s]['.type'] or s, o, v }
1209         self.c    = self:_loadconf(co, c, scheme.configdir)
1210         self.s    = scheme
1211         self.t    = TYPE_ENUM
1212 end