Scheme parsing optimizations
[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 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         local r = luci.util.split( t[k], "." )
448         r[1] = ( #r[1] > 0 and r[1] or scheme:sid() )
449
450         if #r ~= n then
451                 return false, ERR.SME_BADREF(scheme, k)
452         end
453
454         return r
455 end
456
457 -- helper function to read bools
458 local function _bool( v )
459         return ( v == "true" or v == "yes" or v == "on" or v == "1" )
460 end
461
462 -- Step 0: get package meta information
463 function UVL._parse_package(self, scheme, k, v)
464         local sid = scheme:sid()
465         local pkg = self.packages[sid] or {
466                 ["name"]      = sid;
467                 ["sections"]  = { };
468                 ["variables"] = { };
469         }
470
471         pkg.title = v.title
472         pkg.description = v.description
473
474         self.packages[sid] = pkg
475 end
476
477 -- Step 1: get all sections
478 function UVL._parse_section(self, scheme, k, v)
479         local ok, err = _req( TYPE_SECTION, k, v, { "name", "package" } )
480         if err then error(scheme:error(err)) end
481
482         local r, err = _ref( TYPE_SECTION, v )
483         if err then error(scheme:error(err)) end
484
485         local p = self.packages[r[1]] or {
486                 ["name"]      = r[1];
487                 ["sections"]  = { };
488                 ["variables"] = { };
489         }
490         p.sections[v.name]  = p.sections[v.name]  or { }
491         p.variables[v.name] = p.variables[v.name] or { }
492         self.packages[r[1]] = p
493
494         local s  = p.sections[v.name]
495         local so = scheme:section(v.name)
496
497         for k, v2 in pairs(v) do
498                 if k ~= "name" and k ~= "package" and k:sub(1,1) ~= "." then
499                         if k == "depends" then
500                                 s.depends = self:_read_dependency( v2, s.depends )
501                                 if not s.depends then
502                                         return false, scheme:error(
503                                                 ERR.SME_BADDEP(so, luci.util.serialize_data(s.depends))
504                                         )
505                                 end
506                         elseif k == "dynamic" or k == "unique" or
507                                k == "required" or k == "named"
508                         then
509                                 s[k] = _bool(v2)
510                         else
511                                 s[k] = v2
512                         end
513                 end
514         end
515
516         s.dynamic  = s.dynamic  or false
517         s.unique   = s.unique   or false
518         s.required = s.required or false
519         s.named    = s.named    or false
520 end
521
522
523         -- Step 2: get all variables
524 function UVL._parse_var(self, scheme, k, v)
525         local ok, err = _req( TYPE_OPTION, k, v, { "name", "section" } )
526         if err then error(scheme:error(err)) end
527
528         local r, err = _ref( TYPE_OPTION, v )
529         if err then error(scheme:error(err)) end
530
531         local p = self.packages[r[1]]
532         if not p then
533                 error(scheme:error(
534                         ERR.SME_VBADPACK({scheme:sid(), '', v.name}, r[1])
535                 ))
536         end
537
538         local s = p.variables[r[2]]
539         if not s then
540                 error(scheme:error(
541                         ERR.SME_VBADSECT({scheme:sid(), '', v.name}, r[2])
542                 ))
543         end
544
545         s[v.name] = s[v.name] or { }
546
547         local t  = s[v.name]
548         local so = scheme:section(r[2])
549         local to = so:option(v.name)
550
551         for k, v2 in pairs(v) do
552                 if k ~= "name" and k ~= "section" and k:sub(1,1) ~= "." then
553                         if k == "depends" then
554                                 t.depends = self:_read_dependency( v2, t.depends )
555                                 if not t.depends then
556                                         error(scheme:error(so:error(
557                                                 ERR.SME_BADDEP(to, luci.util.serialize_data(v2))
558                                         )))
559                                 end
560                         elseif k == "validator" then
561                                 t.validators = self:_read_validator( v2, t.validators )
562                                 if not t.validators then
563                                         error(scheme:error(so:error(
564                                                 ERR.SME_BADVAL(to, luci.util.serialize_data(v2))
565                                         )))
566                                 end
567                         elseif k == "valueof" then
568                                 local values, err = self:_read_reference( v2 )
569                                 if err then
570                                         error(scheme:error(so:error(
571                                                 ERR.REFERENCE(to, luci.util.serialize_data(v2)):child(err)
572                                         )))
573                                 end
574                                 t.type   = "reference"
575                                 t.values = values
576                         elseif k == "required" then
577                                 t[k] = _bool(v2)
578                         else
579                                 t[k] = t[k] or v2
580                         end
581                 end
582         end
583
584         t.type     = t.type     or "variable"
585         t.datatype = t.datatype or "string"
586         t.required = t.required or false
587 end
588
589 -- Step 3: get all enums
590 function UVL._parse_enum(self, scheme, k, v)
591         local ok, err = _req( TYPE_ENUM, k, v, { "value", "variable" } )
592         if err then error(scheme:error(err)) end
593
594         local r, err = _ref( TYPE_ENUM, v )
595         if err then error(scheme:error(err)) end
596
597         local p = self.packages[r[1]]
598         if not p then
599                 error(scheme:error(
600                         ERR.SME_EBADPACK({scheme:sid(), '', '', v.value}, r[1])
601                 ))
602         end
603
604         local s = p.variables[r[2]]
605         if not s then
606                 error(scheme:error(
607                         ERR.SME_EBADSECT({scheme:sid(), '', '', v.value}, r[2])
608                 ))
609         end
610
611         local t = s[r[3]]
612         if not t then
613                 error(scheme:error(
614                         ERR.SME_EBADOPT({scheme:sid(), '', '', v.value}, r[3])
615                 ))
616         end
617
618
619         local so = scheme:section(r[2])
620         local oo = so:option(r[3])
621         local eo = oo:enum(v.value)
622
623         if t.type ~= "enum" and t.type ~= "reference" then
624                 error(scheme:error(ERR.SME_EBADTYPE(eo)))
625         end
626
627         if not t.values then
628                 t.values = { [v.value] = v.title or v.value }
629         else
630                 t.values[v.value] = v.title or v.value
631         end
632
633         if not t.enum_depends then
634                 t.enum_depends = { }
635         end
636
637         if v.default then
638                 if t.default then
639                         error(scheme:error(ERR.SME_EBADDEF(eo)))
640                 end
641                 t.default = v.value
642         end
643
644         if v.depends then
645                 t.enum_depends[v.value] = self:_read_dependency(
646                         v.depends, t.enum_depends[v.value]
647                 )
648
649                 if not t.enum_depends[v.value] then
650                         error(scheme:error(so:error(oo:error(
651                                 ERR.SME_BADDEP(eo, luci.util.serialize_data(v.depends))
652                         ))))
653                 end
654         end
655 end
656
657 -- Read a dependency specification
658 function UVL._read_dependency( self, values, deps )
659         local expr = "%$?[a-zA-Z0-9_]+"
660         if values then
661                 values = ( type(values) == "table" and values or { values } )
662                 for _, value in ipairs(values) do
663                         local parts     = luci.util.split( value, "%s*,%s*", nil, true )
664                         local condition = { }
665                         for i, val in ipairs(parts) do
666                                 local k, v = unpack(luci.util.split(val, "%s*=%s*", nil, true))
667
668                                 if k and (
669                                         k:match("^"..expr.."%."..expr.."%."..expr.."$") or
670                                         k:match("^"..expr.."%."..expr.."$") or
671                                         k:match("^"..expr.."$")
672                                 ) then
673                                         condition[k] = v or true
674                                 else
675                                         return nil
676                                 end
677                         end
678
679                         if not deps then
680                                 deps = { condition }
681                         else
682                                 table.insert( deps, condition )
683                         end
684                 end
685         end
686
687         return deps
688 end
689
690 -- Read a validator specification
691 function UVL._read_validator( self, values, validators )
692         if values then
693                 values = ( type(values) == "table" and values or { values } )
694                 for _, value in ipairs(values) do
695                         local validator
696
697                         if value:match("^exec:") then
698                                 validator = value:gsub("^exec:","")
699                         elseif value:match("^lua:") then
700                                 validator = self:_resolve_function( (value:gsub("^lua:","") ) )
701                         elseif value:match("^regexp:") then
702                                 local pattern = value:gsub("^regexp:","")
703                                 validator = function( type, dtype, pack, sect, optn, ... )
704                                         local values = { ... }
705                                         for _, v in ipairs(values) do
706                                                 local ok, match =
707                                                         luci.util.copcall( string.match, v, pattern )
708
709                                                 if not ok then
710                                                         return false, match
711                                                 elseif not match then
712                                                         return false,
713                                                                 'Value "%s" does not match pattern "%s"' % {
714                                                                         v, pattern
715                                                                 }
716                                                 end
717                                         end
718                                         return true
719                                 end
720                         end
721
722                         if validator then
723                                 if not validators then
724                                         validators = { validator }
725                                 else
726                                         table.insert( validators, validator )
727                                 end
728                         else
729                                 return nil
730                         end
731                 end
732
733                 return validators
734         end
735 end
736
737 -- Read a reference specification (XXX: We should validate external configs too...)
738 function UVL._read_reference( self, values )
739         local val = { }
740         values = ( type(values) == "table" and values or { values } )
741
742         for _, value in ipairs(values) do
743                 local ref = luci.util.split(value, ".")
744
745                 if #ref == 2 or #ref == 3 then
746                         local co = luci.uvl.config( self, ref[1] )
747                         if not co:config() then return false, co:errors() end
748
749                         for k, v in pairs(co:config()) do
750                                 if v['.type'] == ref[2] then
751                                         if #ref == 2 then
752                                                 if v['.anonymous'] == true then
753                                                         return false, ERR.SME_INVREF('', value)
754                                                 end
755                                                 val[k] = k      -- XXX: title/description would be nice
756                                         elseif v[ref[3]] then
757                                                 val[v[ref[3]]] = v[ref[3]]  -- XXX: dito
758                                         end
759                                 end
760                         end
761                 else
762                         return false, ERR.SME_BADREF('', value)
763                 end
764         end
765
766         return val, nil
767 end
768
769 -- Resolve given path
770 function UVL._resolve_function( self, value )
771         local path = luci.util.split(value, ".")
772
773         for i=1, #path-1 do
774                 local stat, mod = luci.util.copcall(
775                         require, table.concat(path, ".", 1, i)
776                 )
777
778                 if stat and mod then
779                         for j=i+1, #path-1 do
780                                 if not type(mod) == "table" then
781                                         break
782                                 end
783                                 mod = mod[path[j]]
784                                 if not mod then
785                                         break
786                                 end
787                         end
788                         mod = type(mod) == "table" and mod[path[#path]] or nil
789                         if type(mod) == "function" then
790                                 return mod
791                         end
792                 end
793         end
794 end
795
796
797 --- Object representation of an uvl item - base class.
798 uvlitem = luci.util.class()
799
800 function uvlitem.cid(self)
801         if #self.cref == 1 then
802                 return self.cref[1]
803         else
804                 local r = { unpack(self.cref) }
805                 local c = self.c
806                 if c and c[r[2]] and c[r[2]]['.anonymous'] and c[r[2]]['.index'] then
807                         r[2] = '@' .. c[r[2]]['.type'] ..
808                                '[' .. tostring(c[r[2]]['.index']) .. ']'
809                 end
810                 return table.concat( r, '.' )
811         end
812 end
813
814 function uvlitem.sid(self)
815         return table.concat( self.sref, '.' )
816 end
817
818 function uvlitem.scheme(self, opt)
819         local s
820
821         if #self.sref == 4 or #self.sref == 3 then
822                 s = self.s and self.s.packages
823                 s = s      and s[self.sref[1]]
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 = self.s and self.s.packages
829                 s = s      and s[self.sref[1]]
830                 s = s      and s.sections
831                 s = s      and s[self.sref[2]]
832         else
833                 s = self.s and self.s.packages
834                 s = s      and s[self.sref[1]]
835         end
836
837         if s and opt then
838                 return s[opt]
839         elseif s then
840                 return s
841         end
842 end
843
844 function uvlitem.config(self, opt)
845         local c
846
847         if #self.cref == 4 or #self.cref == 3 then
848                 c = self.c and self.c[self.cref[2]] or nil
849                 c = c      and c[self.cref[3]]      or nil
850         elseif #self.cref == 2 then
851                 c = self.c and self.c[self.cref[2]] or nil
852         else
853                 c = self.c
854         end
855
856         if c and opt then
857                 return c[opt]
858         elseif c then
859                 return c
860         end
861 end
862
863 function uvlitem.title(self)
864         return self:scheme() and self:scheme('title') or
865                 self.cref[3] or self.cref[2] or self.cref[1]
866 end
867
868 function uvlitem.type(self)
869         if self.t == luci.uvl.TYPE_CONFIG then
870                 return 'config'
871         elseif self.t == luci.uvl.TYPE_SECTION then
872                 return 'section'
873         elseif self.t == luci.uvl.TYPE_OPTION then
874                 return 'option'
875         elseif self.t == luci.uvl.TYPE_ENUM then
876                 return 'enum'
877         end
878 end
879
880 function uvlitem.error(self, ...)
881         if not self.e then
882                 local errconst = { ERR.CONFIG, ERR.SECTION, ERR.OPTION, ERR.OPTION }
883                 self.e = errconst[#self.cref]( self )
884         end
885
886         return self.e:child( ... )
887 end
888
889 function uvlitem.errors(self)
890         return self.e
891 end
892
893 function uvlitem.ok(self)
894         return not self:errors()
895 end
896
897 function uvlitem.parent(self)
898         if self.p then
899                 return self.p
900         elseif #self.cref == 3 or #self.cref == 4 then
901                 return luci.uvl.section( self.s, self.c, self.cref[1], self.cref[2] )
902         elseif #self.cref == 2 then
903                 return luci.uvl.config( self.s, self.c, self.cref[1] )
904         else
905                 return nil
906         end
907 end
908
909 function uvlitem._loadconf(self, co, c)
910         if not co then
911                 local uci, err = luci.model.uci.cursor(), nil
912                 co, err = uci:get_all(c)
913
914                 if err then
915                         self:error(ERR.UCILOAD(self, err))
916                 end
917         end
918         return co
919 end
920
921
922 --- Object representation of a scheme.
923 -- @class       scheme
924 -- @cstyle      instance
925 -- @name        luci.uvl.scheme
926
927 --- Scheme instance constructor.
928 -- @class                       function
929 -- @name                        scheme
930 -- @param scheme        Scheme instance
931 -- @param co            Configuration data
932 -- @param c                     Configuration name
933 -- @return                      Config instance
934 scheme = luci.util.class(uvlitem)
935
936 function scheme.__init__(self, scheme, co, c)
937         if not c then
938                 c, co = co, nil
939         end
940
941         self.cref = { c }
942         self.sref = { c }
943         self.c    = self:_loadconf(co, c)
944         self.s    = scheme
945         self.t    = luci.uvl.TYPE_SCHEME
946 end
947
948 --- Add an error to scheme.
949 -- @return      Scheme error context
950 function scheme.error(self, ...)
951         if not self.e then self.e = ERR.SCHEME( self ) end
952         return self.e:child( ... )
953 end
954
955 --- Get an associated config object.
956 -- @return      Config instance
957 function scheme.config(self)
958         local co = luci.uvl.config( self.s, self.cref[1] )
959               co.p = self
960
961         return co
962 end
963
964 --- Get all section objects associated with this scheme.
965 -- @return      Table containing all associated luci.uvl.section instances
966 function scheme.sections(self)
967         local v = { }
968         if self.s.packages[self.sref[1]].sections then
969                 for o, _ in pairs( self.s.packages[self.sref[1]].sections ) do
970                         table.insert( v, luci.uvl.option(
971                                 self.s, self.c, self.cref[1], self.cref[2], o
972                         ) )
973                 end
974         end
975         return v
976 end
977
978 --- Get an associated section object.
979 -- @param s     Section to select
980 -- @return      Section instance
981 function scheme.section(self, s)
982         local so = luci.uvl.section( self.s, self.c, self.cref[1], s )
983               so.p = self
984
985         return so
986 end
987
988
989 --- Object representation of a config.
990 -- @class       config
991 -- @cstyle      instance
992 -- @name        luci.uvl.config
993
994 --- Config instance constructor.
995 -- @class                       function
996 -- @name                        config
997 -- @param scheme        Scheme instance
998 -- @param co            Configuration data
999 -- @param c                     Configuration name
1000 -- @return                      Config instance
1001 config = luci.util.class(uvlitem)
1002
1003 function config.__init__(self, scheme, co, c)
1004         if not c then
1005                 c, co = co, nil
1006         end
1007
1008         self.cref = { c }
1009         self.sref = { c }
1010         self.c    = self:_loadconf(co, c)
1011         self.s    = scheme
1012         self.t    = luci.uvl.TYPE_CONFIG
1013 end
1014
1015 --- Get all section objects associated with this config.
1016 -- @return      Table containing all associated luci.uvl.section instances
1017 function config.sections(self)
1018         local v = { }
1019         if self.s.packages[self.sref[1]].sections then
1020                 for o, _ in pairs( self.s.packages[self.sref[1]].sections ) do
1021                         table.insert( v, luci.uvl.option(
1022                                 self.s, self.c, self.cref[1], self.cref[2], o
1023                         ) )
1024                 end
1025         end
1026         return v
1027 end
1028
1029 --- Get an associated section object.
1030 -- @param s     Section to select
1031 -- @return      Section instance
1032 function config.section(self, s)
1033         local so = luci.uvl.section( self.s, self.c, self.cref[1], s )
1034               so.p = self
1035
1036         return so
1037 end
1038
1039
1040 --- Object representation of a scheme/config section.
1041 -- @class       module
1042 -- @cstyle      instance
1043 -- @name        luci.uvl.section
1044
1045 --- Section instance constructor.
1046 -- @class                       function
1047 -- @name                        section
1048 -- @param scheme        Scheme instance
1049 -- @param co            Configuration data
1050 -- @param c                     Configuration name
1051 -- @param s                     Section name
1052 -- @return                      Section instance
1053 section = luci.util.class(uvlitem)
1054
1055 function section.__init__(self, scheme, co, c, s)
1056         self.cref = { c, s }
1057         self.sref = { c, co and co[s] and co[s]['.type'] or s }
1058         self.c    = self:_loadconf(co, c)
1059         self.s    = scheme
1060         self.t    = luci.uvl.TYPE_SECTION
1061 end
1062
1063 --- Get all option objects associated with this section.
1064 -- @return      Table containing all associated luci.uvl.option instances
1065 function section.variables(self)
1066         local v = { }
1067         if self.s.packages[self.sref[1]].variables[self.sref[2]] then
1068                 for o, _ in pairs(
1069                         self.s.packages[self.sref[1]].variables[self.sref[2]]
1070                 ) do
1071                         table.insert( v, luci.uvl.option(
1072                                 self.s, self.c, self.cref[1], self.cref[2], o
1073                         ) )
1074                 end
1075         end
1076         return v
1077 end
1078
1079 --- Get an associated option object.
1080 -- @param o     Option to select
1081 -- @return      Option instance
1082 function section.option(self, o)
1083         local oo = luci.uvl.option( self.s, self.c, self.cref[1], self.cref[2], o )
1084               oo.p = self
1085
1086         return oo
1087 end
1088
1089
1090 --- Object representation of a scheme/config option.
1091 -- @class       module
1092 -- @cstyle      instance
1093 -- @name        luci.uvl.option
1094
1095 --- Section instance constructor.
1096 -- @class                       function
1097 -- @name                        option
1098 -- @param scheme        Scheme instance
1099 -- @param co            Configuration data
1100 -- @param c                     Configuration name
1101 -- @param s                     Section name
1102 -- @param o                     Option name
1103 -- @return                      Option instance
1104 option = luci.util.class(uvlitem)
1105
1106 function option.__init__(self, scheme, co, c, s, o)
1107         self.cref = { c, s, o }
1108         self.sref = { c, co and co[s] and co[s]['.type'] or s, o }
1109         self.c    = self:_loadconf(co, c)
1110         self.s    = scheme
1111         self.t    = luci.uvl.TYPE_OPTION
1112 end
1113
1114 --- Get the value of this option.
1115 -- @return      The associated configuration value
1116 function option.value(self)
1117         local v = self:config() or self:scheme('default')
1118         if v and self:scheme('multival') then
1119                 v = luci.util.split( v, "%s+", nil, true )
1120         end
1121         return v
1122 end
1123
1124 --- Get the associated section information in scheme.
1125 -- @return      Table containing the scheme properties
1126 function option.section(self)
1127         return self.s.packages[self.sref[1]].sections[self.sref[2]]
1128 end
1129
1130 --- Construct an enum object instance from given or default value.
1131 -- @param v     Value to select
1132 -- @return      Enum instance for selected value
1133 function option.enum(self, val)
1134         return enum(
1135                 self.s, self.c,
1136                 self.cref[1], self.cref[2], self.cref[3],
1137                 val or self:value()
1138         )
1139 end
1140
1141
1142 --- Object representation of a enum value.
1143 -- @class       module
1144 -- @cstyle      instance
1145 -- @name        luci.uvl.enum
1146
1147 --- Section instance constructor.
1148 -- @class                       function
1149 -- @name                        enum
1150 -- @param scheme        Scheme instance
1151 -- @param co            Configuration data
1152 -- @param c                     Configuration name
1153 -- @param s                     Section name
1154 -- @param o                     Enum name
1155 -- @param v                     Enum value
1156 -- @return                      Enum value instance
1157 enum = luci.util.class(option)
1158
1159 function enum.__init__(self, scheme, co, c, s, o, v)
1160         self.cref = { c, s, o, v }
1161         self.sref = { c, co and co[s] and co[s]['.type'] or s, o, v }
1162         self.c    = self:_loadconf(co, c)
1163         self.s    = scheme
1164         self.t    = luci.uvl.TYPE_ENUM
1165 end