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