* luci/libs/lua: process option dependencies first, allows mixing of required flags...
[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                                 -- XXX: maybe this needs to be more specific
299                                 if not err:is(ERR.ERR_DEP_NOTEQUAL) and
300                                    not err:is(ERR.ERR_DEP_NOVALUE)
301                                 then
302                                         option:error(err)
303                                         return false, option:errors()
304                                 else
305                                         return true
306                                 end
307                         end
308                 end
309
310                 if option:scheme('required') and not option:value() then
311                         return false, option:error(ERR.OPT_REQUIRED(option))
312
313                 elseif option:value() then
314                         local val = option:value()
315
316                         if option:scheme('type') == "reference" or
317                            option:scheme('type') == "enum"
318                         then
319                                 local scheme_values = option:scheme('values') or { }
320                                 local config_values = ( type(val) == "table" and val or { val } )
321                                 for _, v in ipairs(config_values) do
322                                         if not scheme_values[v] then
323                                                 return false, option:error( ERR.OPT_BADVALUE(
324                                                         option, { v, util.serialize_data(
325                                                                 util.keys(scheme_values)
326                                                         ) }
327                                                 ) )
328                                         end
329                                 end
330                         elseif option:scheme('type') == "list" then
331                                 if type(val) ~= "table" and STRICT_LIST_TYPE then
332                                         return false, option:error(ERR.OPT_NOTLIST(option))
333                                 end
334                         end
335
336                         if option:scheme('datatype') then
337                                 local dt = option:scheme('datatype')
338
339                                 if self.datatypes[dt] then
340                                         val = ( type(val) == "table" and val or { val } )
341                                         for i, v in ipairs(val) do
342                                                 if not self.datatypes[dt]( v ) then
343                                                         return false, option:error(
344                                                                 ERR.OPT_INVVALUE(option, { v, dt })
345                                                         )
346                                                 end
347                                         end
348                                 else
349                                         return false, option:error(ERR.OPT_DATATYPE(option, dt))
350                                 end
351                         end
352
353                         val = ( type(val) == "table" and val or { val } )
354                         for _, v in ipairs(val) do
355                                 if option:scheme('minlength') then
356                                         if #v < option:scheme('minlength') then
357                                                 return false, option:error(ERR.OPT_RANGE(option))
358                                         end
359                                 end
360
361                                 if option:scheme('maxlength') then
362                                         if #v > option:scheme('maxlength') then
363                                                 return false, option:error(ERR.OPT_RANGE(option))
364                                         end
365                                 end
366
367                                 v = tonumber(v)
368
369                                 if option:scheme('minimum') then
370                                         if not v or v < option:scheme('minimum') then
371                                                 return false, option:error(ERR.OPT_RANGE(option))
372                                         end
373                                 end
374
375                                 if option:scheme('maximum') then
376                                         if not v or v > option:scheme('maximum') then
377                                                 return false, option:error(ERR.OPT_RANGE(option))
378                                         end
379                                 end
380                         end
381                 end
382
383                 local ok, err = validation.check( self, option )
384                 if not ok and STRICT_EXTERNAL_VALIDATORS then
385                         return false, option:error(err)
386                 end
387         end
388
389         return option:ok(), option:errors()
390 end
391
392 --- Find all parts of given scheme and construct validation tree.
393 -- This is normally done on demand, so you don't have to call this function
394 -- by yourself.
395 -- @param shm   Name of the scheme to parse
396 -- @param alias         Create an alias for the loaded scheme
397 function UVL.read_scheme( self, shm, alias )
398
399         local so = scheme( self, shm )
400         local bc = "%s/bytecode/%s.lua" %{ self.schemedir, shm }
401
402         if not fs.access(bc) then
403                 local files = fs.glob(self.schemedir .. '/*/' .. shm)
404
405                 if files then
406                         local ok, err
407                         for i, file in ipairs( files ) do
408                                 if not fs.access(file) then
409                                         return false, so:error(ERR.SME_READ(so,file))
410                                 end
411
412                                 local uci = uci.cursor( fs.dirname(file), default_savedir )
413
414                                 local sname = fs.basename(file)
415                                 local sd, err = uci:load( sname )
416
417                                 if not sd then
418                                         return false, ERR.UCILOAD(so, err)
419                                 end
420
421                                 ok, err = pcall(function()
422                                         uci:foreach(sname, "package", function(s)
423                                                 self:_parse_package(so, s[".name"], s)
424                                         end)
425                                         uci:foreach(sname, "section", function(s)
426                                                 self:_parse_section(so, s[".name"], s)
427                                         end)
428                                         uci:foreach(sname, "variable", function(s)
429                                                 self:_parse_var(so, s[".name"], s)
430                                         end)
431                                         uci:foreach(sname, "enum", function(s)
432                                                 self:_parse_enum(so, s[".name"], s)
433                                         end)
434
435                                 end)
436                         end
437
438                         if ok and alias then self.packages[alias] = self.packages[shm] end
439                         return ok and self, err
440                 else
441                         return false, so:error(ERR.SME_FIND(so, self.schemedir))
442                 end
443         else
444                 local sc = loadfile(bc)
445                 if sc then
446                         self.packages[shm] = sc()
447                         return true
448                 else
449                         return false, so:error(ERR.SME_READ(so,bc))
450                 end
451         end
452 end
453
454 -- helper function to check for required fields
455 local function _req( t, n, c, r )
456         for i, v in ipairs(r) do
457                 if not c[v] then
458                         local p, o = scheme:sid(), nil
459
460                         if t == TYPE_SECTION then
461                                 o = section( scheme, nil, p, n )
462                         elseif t == TYPE_OPTION then
463                                 o = option( scheme, nil, p, '(nil)', n )
464                         elseif t == TYPE_ENUM then
465                                 o = enum( scheme, nil, p, '(nil)', '(nil)', n )
466                         end
467
468                         return false, ERR.SME_REQFLD(o,v)
469                 end
470         end
471         return true
472 end
473
474 -- helper function to validate references
475 local function _ref( c, t )
476         local r, k, n = {}
477         if c == TYPE_SECTION then
478                 k = "package"
479                 n = 1
480         elseif c == TYPE_OPTION then
481                 k = "section"
482                 n = 2
483         elseif c == TYPE_ENUM then
484                 k = "variable"
485                 n = 3
486         end
487
488         for o in t[k]:gmatch("[^.]+") do
489                 r[#r+1] = o
490         end
491         r[1] = ( #r[1] > 0 and r[1] or scheme:sid() )
492
493         if #r ~= n then
494                 return false, ERR.SME_BADREF(scheme, k)
495         end
496
497         return r
498 end
499
500 -- helper function to read bools
501 local function _bool( v )
502         return ( v == "true" or v == "yes" or v == "on" or v == "1" )
503 end
504
505 -- Step 0: get package meta information
506 function UVL._parse_package(self, scheme, k, v)
507         local sid = scheme:sid()
508         local pkg = self.packages[sid] or {
509                 ["name"]      = sid;
510                 ["sections"]  = { };
511                 ["variables"] = { };
512         }
513
514         pkg.title = v.title
515         pkg.description = v.description
516
517         self.packages[sid] = pkg
518 end
519
520 -- Step 1: get all sections
521 function UVL._parse_section(self, scheme, k, v)
522         local ok, err = _req( TYPE_SECTION, k, v, { "name", "package" } )
523         if err then error(scheme:error(err)) end
524
525         local r, err = _ref( TYPE_SECTION, v )
526         if err then error(scheme:error(err)) end
527
528         local p = self.packages[r[1]] or {
529                 ["name"]      = r[1];
530                 ["sections"]  = { };
531                 ["variables"] = { };
532         }
533         p.sections[v.name]  = p.sections[v.name]  or { }
534         p.variables[v.name] = p.variables[v.name] or { }
535         self.packages[r[1]] = p
536
537         local s  = p.sections[v.name]
538         local so = scheme:section(v.name)
539
540         for k, v2 in pairs(v) do
541                 if k ~= "name" and k ~= "package" and k:sub(1,1) ~= "." then
542                         if k == "depends" then
543                                 s.depends = self:_read_dependency( v2, s.depends )
544                                 if not s.depends then
545                                         return false, scheme:error(
546                                                 ERR.SME_BADDEP(so, util.serialize_data(s.depends))
547                                         )
548                                 end
549                         elseif k == "dynamic" or k == "unique" or
550                                k == "required" or k == "named"
551                         then
552                                 s[k] = _bool(v2)
553                         else
554                                 s[k] = v2
555                         end
556                 end
557         end
558
559         s.dynamic  = s.dynamic  or false
560         s.unique   = s.unique   or false
561         s.required = s.required or false
562         s.named    = s.named    or false
563 end
564
565 -- Step 2: get all variables
566 function UVL._parse_var(self, scheme, k, v)
567         local ok, err = _req( TYPE_OPTION, k, v, { "name", "section" } )
568         if err then error(scheme:error(err)) end
569
570         local r, err = _ref( TYPE_OPTION, v )
571         if err then error(scheme:error(err)) end
572
573         local p = self.packages[r[1]]
574         if not p then
575                 error(scheme:error(
576                         ERR.SME_VBADPACK({scheme:sid(), '', v.name}, r[1])
577                 ))
578         end
579
580         local s = p.variables[r[2]]
581         if not s then
582                 error(scheme:error(
583                         ERR.SME_VBADSECT({scheme:sid(), '', v.name}, r[2])
584                 ))
585         end
586
587         s[v.name] = s[v.name] or { }
588
589         local t  = s[v.name]
590         local so = scheme:section(r[2])
591         local to = so:option(v.name)
592
593         for k, v2 in pairs(v) do
594                 if k ~= "name" and k ~= "section" and k:sub(1,1) ~= "." then
595                         if k == "depends" then
596                                 t.depends = self:_read_dependency( v2, t.depends )
597                                 if not t.depends then
598                                         error(scheme:error(so:error(
599                                                 ERR.SME_BADDEP(to, util.serialize_data(v2))
600                                         )))
601                                 end
602                         elseif k == "validator" then
603                                 t.validators = self:_read_validator( v2, t.validators )
604                                 if not t.validators then
605                                         error(scheme:error(so:error(
606                                                 ERR.SME_BADVAL(to, util.serialize_data(v2))
607                                         )))
608                                 end
609                         elseif k == "valueof" then
610                                 local values, err = self:_read_reference( v2 )
611                                 if err then
612                                         error(scheme:error(so:error(
613                                                 ERR.REFERENCE(to, util.serialize_data(v2)):child(err)
614                                         )))
615                                 end
616                                 t.type   = "reference"
617                                 t.values = values
618                                 t.valueof = type(v2) == "table" and v2 or {v2}
619                         elseif k == "required" then
620                                 t[k] = _bool(v2)
621                         elseif k == "minlength" or k == "maxlength" or
622                    k == "minimum" or k == "maximum"
623             then
624                                 t[k] = tonumber(v2)
625                         else
626                                 t[k] = t[k] or v2
627                         end
628                 end
629         end
630
631         t.type     = t.type     or "variable"
632         t.datatype = t.datatype or "string"
633         t.required = t.required or false
634 end
635
636 -- Step 3: get all enums
637 function UVL._parse_enum(self, scheme, k, v)
638         local ok, err = _req( TYPE_ENUM, k, v, { "value", "variable" } )
639         if err then error(scheme:error(err)) end
640
641         local r, err = _ref( TYPE_ENUM, v )
642         if err then error(scheme:error(err)) end
643
644         local p = self.packages[r[1]]
645         if not p then
646                 error(scheme:error(
647                         ERR.SME_EBADPACK({scheme:sid(), '', '', v.value}, r[1])
648                 ))
649         end
650
651         local s = p.variables[r[2]]
652         if not s then
653                 error(scheme:error(
654                         ERR.SME_EBADSECT({scheme:sid(), '', '', v.value}, r[2])
655                 ))
656         end
657
658         local t = s[r[3]]
659         if not t then
660                 error(scheme:error(
661                         ERR.SME_EBADOPT({scheme:sid(), '', '', v.value}, r[3])
662                 ))
663         end
664
665
666         local so = scheme:section(r[2])
667         local oo = so:option(r[3])
668         local eo = oo:enum(v.value)
669
670         if t.type ~= "enum" and t.type ~= "reference" then
671                 error(scheme:error(ERR.SME_EBADTYPE(eo)))
672         end
673
674         if not t.values then
675                 t.values = { [v.value] = v.title or v.value }
676                 t.valuelist = { {value = v.value, title = v.title} }
677         else
678                 t.values[v.value] = v.title or v.value
679                 t.valuelist[#t.valuelist + 1] = {value = v.value, title = v.title}
680         end
681
682         if not t.enum_depends then
683                 t.enum_depends = { }
684         end
685
686         if v.default then
687                 if t.default then
688                         error(scheme:error(ERR.SME_EBADDEF(eo)))
689                 end
690                 t.default = v.value
691         end
692
693         if v.depends then
694                 t.enum_depends[v.value] = self:_read_dependency(
695                         v.depends, t.enum_depends[v.value]
696                 )
697
698                 if not t.enum_depends[v.value] then
699                         error(scheme:error(so:error(oo:error(
700                                 ERR.SME_BADDEP(eo, util.serialize_data(v.depends))
701                         ))))
702                 end
703         end
704 end
705
706 -- Read a dependency specification
707 function UVL._read_dependency( self, values, deps )
708         local expr = "%$?[%w_]+"
709         if values then
710                 values = ( type(values) == "table" and values or { values } )
711                 for _, value in ipairs(values) do
712                         local condition = { }
713                         for val in value:gmatch("[^,]+") do
714                                 local k, e, v = val:match("%s*([%w$_.]+)%s*(=?)%s*(.*)")
715
716                                 if k and (
717                                         k:match("^"..expr.."%."..expr.."%."..expr.."$") or
718                                         k:match("^"..expr.."%."..expr.."$") or
719                                         k:match("^"..expr.."$")
720                                 ) then
721                                         condition[k] = (e == '=') and v or true
722                                 else
723                                         return nil
724                                 end
725                         end
726
727                         if not deps then
728                                 deps = { condition }
729                         else
730                                 deps[#deps+1] = condition
731                         end
732                 end
733         end
734
735         return deps
736 end
737
738 -- Read a validator specification
739 function UVL._read_validator( self, values, validators )
740         if values then
741                 values = ( type(values) == "table" and values or { values } )
742                 for _, value in ipairs(values) do
743                         local validator
744
745                         if value:match("^exec:") then
746                                 validator = value:gsub("^exec:","")
747                         elseif value:match("^lua:") then
748                                 validator = self:_resolve_function( (value:gsub("^lua:","") ) )
749                         elseif value:match("^regexp:") then
750                                 local pattern = value:gsub("^regexp:","")
751                                 validator = function( type, dtype, pack, sect, optn, ... )
752                                         local values = { ... }
753                                         for _, v in ipairs(values) do
754                                                 local ok, match =
755                                                         pcall( string.match, v, pattern )
756
757                                                 if not ok then
758                                                         return false, match
759                                                 elseif not match then
760                                                         return false,
761                                                                 'Value "%s" does not match pattern "%s"' % {
762                                                                         v, pattern
763                                                                 }
764                                                 end
765                                         end
766                                         return true
767                                 end
768                         end
769
770                         if validator then
771                                 if not validators then
772                                         validators = { validator }
773                                 else
774                                         validators[#validators+1] = validator
775                                 end
776                         else
777                                 return nil
778                         end
779                 end
780
781                 return validators
782         end
783 end
784
785 -- Read a reference specification (XXX: We should validate external configs too...)
786 function UVL._read_reference( self, values )
787         local val = { }
788         values = ( type(values) == "table" and values or { values } )
789
790         for _, value in ipairs(values) do
791                 local ref = util.split(value, ".")
792
793                 if #ref == 2 or #ref == 3 then
794                         local co = config( self, ref[1] )
795                         if not co:config() then return false, co:errors() end
796
797                         for k, v in pairs(co:config()) do
798                                 if v['.type'] == ref[2] then
799                                         if #ref == 2 then
800                                                 if v['.anonymous'] == true then
801                                                         return false, ERR.SME_INVREF('', value)
802                                                 end
803                                                 val[k] = k      -- XXX: title/description would be nice
804                                         elseif v[ref[3]] then
805                                                 val[v[ref[3]]] = v[ref[3]]  -- XXX: dito
806                                         end
807                                 end
808                         end
809                 else
810                         return false, ERR.SME_BADREF('', value)
811                 end
812         end
813
814         return val, nil
815 end
816
817 -- Resolve given path
818 function UVL._resolve_function( self, value )
819         local path = util.split(value, ".")
820
821         for i=1, #path-1 do
822                 local stat, mod = pcall(
823                         require, table.concat(path, ".", 1, i)
824                 )
825
826                 if stat and mod then
827                         for j=i+1, #path-1 do
828                                 if not type(mod) == "table" then
829                                         break
830                                 end
831                                 mod = mod[path[j]]
832                                 if not mod then
833                                         break
834                                 end
835                         end
836                         mod = type(mod) == "table" and mod[path[#path]] or nil
837                         if type(mod) == "function" then
838                                 return mod
839                         end
840                 end
841         end
842 end
843
844
845 --- Object representation of an uvl item - base class.
846 uvlitem = util.class()
847
848 function uvlitem.cid(self)
849         if #self.cref == 1 then
850                 return self.cref[1]
851         else
852                 local r = { unpack(self.cref) }
853                 local c = self.c
854                 if c and c[r[2]] and c[r[2]]['.anonymous'] and c[r[2]]['.index'] then
855                         r[2] = '@' .. c[r[2]]['.type'] ..
856                                    '[' .. tostring(c[r[2]]['.index']) .. ']'
857                 end
858                 return table.concat( r, '.' )
859         end
860 end
861
862 function uvlitem.sid(self)
863         return table.concat( self.sref, '.' )
864 end
865
866 function uvlitem.scheme(self, opt)
867         local s = self.s and self.s.packages
868         s = s      and s[self.sref[1]]
869         if #self.sref == 4 or #self.sref == 3 then
870                 s = s      and s.variables
871                 s = s      and s[self.sref[2]]
872                 s = s      and s[self.sref[3]]
873         elseif #self.sref == 2 then
874                 s = s      and s.sections
875                 s = s      and s[self.sref[2]]
876         end
877
878         if s and opt then
879                 return s[opt]
880         elseif s then
881                 return s
882         end
883 end
884
885 function uvlitem.config(self, opt)
886         local c = self.c
887
888         if #self.cref >= 2 and #self.cref <= 4 then
889                 c = c and self.c[self.cref[2]] or nil
890                 if #self.cref >= 3 then
891                         c = c and c[self.cref[3]] or nil
892                 end
893         end
894
895         if c and opt then
896                 return c[opt]
897         elseif c then
898                 return c
899         end
900 end
901
902 function uvlitem.title(self)
903         return self:scheme() and self:scheme('title') or
904                 self.cref[3] or self.cref[2] or self.cref[1]
905 end
906
907 function uvlitem.type(self)
908         if self.t == TYPE_CONFIG then
909                 return 'config'
910         elseif self.t == TYPE_SECTION then
911                 return 'section'
912         elseif self.t == TYPE_OPTION then
913                 return 'option'
914         elseif self.t == TYPE_ENUM then
915                 return 'enum'
916         end
917 end
918
919 function uvlitem.error(self, ...)
920         if not self.e then
921                 local errconst = { ERR.CONFIG, ERR.SECTION, ERR.OPTION, ERR.OPTION }
922                 self.e = errconst[#self.cref]( self )
923         end
924
925         return self.e:child( ... )
926 end
927
928 function uvlitem.errors(self)
929         return self.e
930 end
931
932 function uvlitem.ok(self)
933         return not self:errors()
934 end
935
936 function uvlitem.parent(self)
937         if self.p then
938                 return self.p
939         elseif #self.cref == 3 or #self.cref == 4 then
940                 return section( self.s, self.c, self.cref[1], self.cref[2] )
941         elseif #self.cref == 2 then
942                 return config( self.s, self.c, self.cref[1] )
943         else
944                 return nil
945         end
946 end
947
948 function uvlitem._loadconf(self, co, c)
949         co = co or self._configcache
950         if not co then
951                 local err
952                 co, err = uci.cursor():get_all(c)
953
954                 if err then
955                         self:error(ERR.UCILOAD(self, err))
956                 end
957
958                 self._configcache = co
959         end
960         return co
961 end
962
963
964 --- Object representation of a scheme.
965 -- @class       scheme
966 -- @cstyle      instance
967 -- @name        luci.uvl.scheme
968
969 --- Scheme instance constructor.
970 -- @class                       function
971 -- @name                        scheme
972 -- @param scheme        Scheme instance
973 -- @param co            Configuration data
974 -- @param c                     Configuration name
975 -- @return                      Config instance
976 scheme = util.class(uvlitem)
977
978 function scheme.__init__(self, scheme, co, c)
979         if not c then
980                 c, co = co, nil
981         end
982
983         self.cref = { c }
984         self.sref = { c }
985         self.c    = self:_loadconf(co, c)
986         self.s    = scheme
987         self.t    = TYPE_SCHEME
988 end
989
990 --- Add an error to scheme.
991 -- @return      Scheme error context
992 function scheme.error(self, ...)
993         if not self.e then self.e = ERR.SCHEME( self ) end
994         return self.e:child( ... )
995 end
996
997 --- Get an associated config object.
998 -- @return      Config instance
999 function scheme.config(self)
1000         local co = config( self.s, self.cref[1] )
1001               co.p = self
1002
1003         return co
1004 end
1005
1006 --- Get all section objects associated with this scheme.
1007 -- @return      Table containing all associated luci.uvl.section instances
1008 function scheme.sections(self)
1009         local v = { }
1010         if self.s.packages[self.sref[1]].sections then
1011                 for o, _ in pairs( self.s.packages[self.sref[1]].sections ) do
1012                         v[#v+1] = option(
1013                                 self.s, self.c, self.cref[1], self.cref[2], o
1014                         )
1015                 end
1016         end
1017         return v
1018 end
1019
1020 --- Get an associated section object.
1021 -- @param s     Section to select
1022 -- @return      Section instance
1023 function scheme.section(self, s)
1024         local so = section( self.s, self.c, self.cref[1], s )
1025               so.p = self
1026
1027         return so
1028 end
1029
1030
1031 --- Object representation of a config.
1032 -- @class       config
1033 -- @cstyle      instance
1034 -- @name        luci.uvl.config
1035
1036 --- Config instance constructor.
1037 -- @class                       function
1038 -- @name                        config
1039 -- @param scheme        Scheme instance
1040 -- @param co            Configuration data
1041 -- @param c                     Configuration name
1042 -- @return                      Config instance
1043 config = util.class(uvlitem)
1044
1045 function config.__init__(self, scheme, co, c)
1046         if not c then
1047                 c, co = co, nil
1048         end
1049
1050         self.cref = { c }
1051         self.sref = { c }
1052         self.c    = self:_loadconf(co, c)
1053         self.s    = scheme
1054         self.t    = TYPE_CONFIG
1055 end
1056
1057 --- Get all section objects associated with this config.
1058 -- @return      Table containing all associated luci.uvl.section instances
1059 function config.sections(self)
1060         local v = { }
1061         if self.s.packages[self.sref[1]].sections then
1062                 for o, _ in pairs( self.s.packages[self.sref[1]].sections ) do
1063                         v[#v+1] = option(
1064                                 self.s, self.c, self.cref[1], self.cref[2], o
1065                         )
1066                 end
1067         end
1068         return v
1069 end
1070
1071 --- Get an associated section object.
1072 -- @param s     Section to select
1073 -- @return      Section instance
1074 function config.section(self, s)
1075         local so = section( self.s, self.c, self.cref[1], s )
1076               so.p = self
1077
1078         return so
1079 end
1080
1081
1082 --- Object representation of a scheme/config section.
1083 -- @class       module
1084 -- @cstyle      instance
1085 -- @name        luci.uvl.section
1086
1087 --- Section instance constructor.
1088 -- @class                       function
1089 -- @name                        section
1090 -- @param scheme        Scheme instance
1091 -- @param co            Configuration data
1092 -- @param c                     Configuration name
1093 -- @param s                     Section name
1094 -- @return                      Section instance
1095 section = util.class(uvlitem)
1096
1097 function section.__init__(self, scheme, co, c, s)
1098         self.cref = { c, s }
1099         self.sref = { c, co and co[s] and co[s]['.type'] or s }
1100         self.c    = self:_loadconf(co, c)
1101         self.s    = scheme
1102         self.t    = TYPE_SECTION
1103 end
1104
1105 --- Get all option objects associated with this section.
1106 -- @return      Table containing all associated luci.uvl.option instances
1107 function section.variables(self)
1108         local v = { }
1109         if self.s.packages[self.sref[1]].variables[self.sref[2]] then
1110                 for o, _ in pairs(
1111                         self.s.packages[self.sref[1]].variables[self.sref[2]]
1112                 ) do
1113                         v[#v+1] = option(
1114                                 self.s, self.c, self.cref[1], self.cref[2], o
1115                         )
1116                 end
1117         end
1118         return v
1119 end
1120
1121 --- Get an associated option object.
1122 -- @param o     Option to select
1123 -- @return      Option instance
1124 function section.option(self, o)
1125         local oo = option( self.s, self.c, self.cref[1], self.cref[2], o )
1126               oo.p = self
1127
1128         return oo
1129 end
1130
1131
1132 --- Object representation of a scheme/config option.
1133 -- @class       module
1134 -- @cstyle      instance
1135 -- @name        luci.uvl.option
1136
1137 --- Section instance constructor.
1138 -- @class                       function
1139 -- @name                        option
1140 -- @param scheme        Scheme instance
1141 -- @param co            Configuration data
1142 -- @param c                     Configuration name
1143 -- @param s                     Section name
1144 -- @param o                     Option name
1145 -- @return                      Option instance
1146 option = util.class(uvlitem)
1147
1148 function option.__init__(self, scheme, co, c, s, o)
1149         self.cref = { c, s, o }
1150         self.sref = { c, co and co[s] and co[s]['.type'] or s, o }
1151         self.c    = self:_loadconf(co, c)
1152         self.s    = scheme
1153         self.t    = TYPE_OPTION
1154 end
1155
1156 --- Get the value of this option.
1157 -- @return      The associated configuration value
1158 function option.value(self)
1159         local v = self:config() or self:scheme('default')
1160         if v and self:scheme('multival') then
1161                 v = util.split( v, "%s+", nil, true )
1162         end
1163         return v
1164 end
1165
1166 --- Get the associated section information in scheme.
1167 -- @return      Table containing the scheme properties
1168 function option.section(self)
1169         return self.s.packages[self.sref[1]].sections[self.sref[2]]
1170 end
1171
1172 --- Construct an enum object instance from given or default value.
1173 -- @param v     Value to select
1174 -- @return      Enum instance for selected value
1175 function option.enum(self, val)
1176         return enum(
1177                 self.s, self.c,
1178                 self.cref[1], self.cref[2], self.cref[3],
1179                 val or self:value()
1180         )
1181 end
1182
1183
1184 --- Object representation of a enum value.
1185 -- @class       module
1186 -- @cstyle      instance
1187 -- @name        luci.uvl.enum
1188
1189 --- Section instance constructor.
1190 -- @class                       function
1191 -- @name                        enum
1192 -- @param scheme        Scheme instance
1193 -- @param co            Configuration data
1194 -- @param c                     Configuration name
1195 -- @param s                     Section name
1196 -- @param o                     Enum name
1197 -- @param v                     Enum value
1198 -- @return                      Enum value instance
1199 enum = util.class(option)
1200
1201 function enum.__init__(self, scheme, co, c, s, o, v)
1202         self.cref = { c, s, o, v }
1203         self.sref = { c, co and co[s] and co[s]['.type'] or s, o, v }
1204         self.c    = self:_loadconf(co, c)
1205         self.s    = scheme
1206         self.t    = TYPE_ENUM
1207 end