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