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