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