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