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