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