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