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