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