libs/uvl: rework error handling to prevent triggering lvm issues
[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, collectgarbage = unpack, loadfile, collectgarbage
32
33 module "luci.uvl"
34
35 local ERR = require "luci.uvl.errors".error
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 local PAT_EXPR1         = "^%$?[%w_]+$"
47 local PAT_EXPR2         = "^%$?[%w_]+%.%$?[%w_]+$"
48 local PAT_EXPR3         = "^%$?[%w_]+%.%$?[%w_]+%.%$?[%w_]+$"
49
50 --- Boolean; default true;
51 -- treat sections found in config but not in scheme as error
52 STRICT_UNKNOWN_SECTIONS    = true
53
54 --- Boolean; default true;
55 -- treat options found in config but not in scheme as error
56 STRICT_UNKNOWN_OPTIONS     = true
57
58 --- Boolean; default true;
59 -- treat failed external validators as error
60 STRICT_EXTERNAL_VALIDATORS = true
61
62 --- Boolean; default true;
63 -- treat list values stored as options like errors
64 STRICT_LIST_TYPE           = true
65
66
67 local default_schemedir = "/lib/uci/schema"
68 local default_savedir = "/tmp/.uvl"
69
70
71 --- Object constructor
72 -- @class                       function
73 -- @name                        UVL
74 -- @param schemedir     Path to the scheme directory (optional)
75 -- @param configdir     Override config directory (optional)
76 -- @return                      Instance object
77 UVL = util.class()
78
79 function UVL.__init__( self, schemedir, configdir )
80         self.schemedir  = schemedir or default_schemedir
81         self.configdir  = configdir
82         self.packages   = { }
83         self.beenthere  = { }
84         self.depseen    = { }
85         self.uci                = uci
86         self.err                = ERR
87         self.dep                = dependencies
88         self.datatypes  = datatypes
89 end
90
91
92 --- Parse given scheme and return the scheme tree.
93 -- @param scheme        Name of the scheme to parse
94 -- @return                      Table containing the parsed scheme or nil on error
95 -- @return                      String containing the reason for errors (if any)
96 function UVL.get_scheme( self, scheme )
97         if not self.packages[scheme] then
98                 local ok, err = self:read_scheme( scheme )
99                 if not ok then
100                         return nil, err
101                 end
102         end
103         return self.packages[scheme], nil
104 end
105
106 --- Validate given configuration, section or option.
107 -- @param config        Name of the configuration to validate
108 -- @param section       Name of the section to validate (optional)
109 -- @param option        Name of the option to validate (optional)
110 -- @return                      Boolean indicating whether the given config validates
111 -- @return                      String containing the reason for errors (if any)
112 function UVL.validate( self, config, section, option )
113         if config and section and option then
114                 return self:validate_option( config, section, option )
115         elseif config and section then
116                 return self:validate_section( config, section )
117         elseif config then
118                 return self:validate_config( config )
119         end
120 end
121
122 --- Validate given configuration.
123 -- @param cfg   Name of the configuration to validate
124 -- @return                      Boolean indicating whether the given config validates
125 -- @return                      String containing the reason for errors (if any)
126 function UVL.validate_config( self, cfg, uci )
127
128         if not self.packages[cfg] then
129                 local ok, err = self:read_scheme(cfg)
130                 if not ok then
131                         return false, err
132                 end
133         end
134
135         local co = config( self, uci or cfg, uci and cfg )
136         local sc = { }
137
138         self.beenthere = { }
139         self.depseen   = { }
140
141         if not co:config() then
142                 return false, co:errors()
143         end
144
145         local function _uci_foreach( type, func )
146                 for k, v in pairs(co:config()) do
147                         if v['.type'] == type then
148                                 sc[type] = sc[type] + 1
149                                 local ok, err = func( k, v )
150                                 if not ok then co:error(err) end
151                         end
152                 end
153         end
154
155         for k, v in pairs( self.packages[cfg].sections ) do
156                 sc[k] = 0
157                 _uci_foreach( k,
158                         function(s)
159                                 return self:_validate_section( co:section(s) )
160                         end
161                 )
162         end
163
164         if STRICT_UNKNOWN_SECTIONS then
165                 for k, v in pairs(co:config()) do
166                         local so = co:section(k)
167                         if not self.beenthere[so:cid()] then
168                                 co:error(ERR('SECT_UNKNOWN', so))
169                         end
170                 end
171         end
172
173         for _, k in ipairs(util.keys(sc)) do
174                 local so = co:section(k)
175                 if so:scheme('required') and sc[k] == 0 then
176                         co:error(ERR('SECT_REQUIRED', so))
177                 elseif so:scheme('unique') and sc[k] > 1 then
178                         co:error(ERR('SECT_UNIQUE', so))
179                 end
180         end
181
182         return co:ok(), co:errors()
183 end
184
185 --- Validate given config section.
186 -- @param config        Name of the configuration to validate
187 -- @param section       Name of the section to validate
188 -- @return                      Boolean indicating whether the given config validates
189 -- @return                      String containing the reason for errors (if any)
190 function UVL.validate_section( self, cfg, section, uci )
191
192         if not self.packages[cfg] then
193                 local ok, err = self:read_scheme( cfg )
194                 if not ok then
195                         return false, err
196                 end
197         end
198
199         local co = config( self, uci or cfg, uci and cfg )
200         local so = co:section( section )
201
202         self.beenthere = { }
203         self.depseen   = { }
204
205         if not co:config() then
206                 return false, co:errors()
207         end
208
209         if so:config() then
210                 return self:_validate_section( so )
211         else
212                 return false, ERR('SECT_NOTFOUND', so)
213         end
214 end
215
216 --- Validate given config option.
217 -- @param config        Name of the configuration to validate
218 -- @param section       Name of the section to validate
219 -- @param option        Name of the option to validate
220 -- @return                      Boolean indicating whether the given config validates
221 -- @return                      String containing the reason for errors (if any)
222 function UVL.validate_option( self, cfg, section, option, uci )
223
224         if not self.packages[cfg] then
225                 local ok, err = self:read_scheme( cfg )
226                 if not ok then
227                         return false, err
228                 end
229         end
230
231         local co = config( self, uci or cfg, uci and cfg )
232         local so = co:section( section )
233         local oo = so:option( option )
234
235         if not co:config() then
236                 return false, co:errors()
237         end
238
239         if so:config() and oo:config() then
240                 return self:_validate_option( oo )
241         else
242                 return false, ERR('OPT_NOTFOUND', oo)
243         end
244 end
245
246
247 function UVL._validate_section( self, section )
248
249         self.beenthere[section:cid()] = true
250
251         if section:config() then
252                 if section:scheme('named') == true and
253                    section:config('.anonymous') == true
254                 then
255                         return false, ERR('SECT_NAMED', section)
256                 end
257
258                 for _, v in ipairs(section:variables()) do
259                         local ok, err = self:_validate_option( v )
260                         if not ok and (
261                                 v:scheme('required') or v:scheme('type') == "enum" or (
262                                         not err:is('DEP_NOTEQUAL') and
263                                         not err:is('DEP_NOVALUE')
264                                 )
265                         ) then
266                                 section:error(err)
267                         end
268                 end
269
270                 local ok, err = dependencies.check( self, section )
271                 if not ok then
272                         section:error(err)
273                 end
274         else
275                 return false, ERR('SECT_NOTFOUND', section)
276         end
277
278         if STRICT_UNKNOWN_OPTIONS and not section:scheme('dynamic') then
279                 for k, v in pairs(section:config()) do
280                         local oo = section:option(k)
281                         if k:byte(1) == 46 and not self.beenthere[oo:cid()] then
282                                 section:error(ERR('OPT_UNKNOWN', oo))
283                         end
284                 end
285         end
286
287         return section:ok(), section:errors()
288 end
289
290 function UVL._validate_option( self, option, nodeps )
291
292         self.beenthere[option:cid()] = true
293
294         if not option:scheme() and not option:parent():scheme('dynamic') then
295                 if STRICT_UNKNOWN_OPTIONS then
296                         return false, option:error(ERR('OPT_UNKNOWN', option))
297                 else
298                         return true
299                 end
300
301         elseif option:scheme() then
302                 if not nodeps then
303                         local ok, err = dependencies.check( self, option )
304                         if not ok then
305                                 if not err:is_all(
306                                         'OPT_REQUIRED',
307                                         'DEP_NOTEQUAL',
308                                         'DEP_NOVALUE'
309                                 ) then
310                                         option:error(err)
311                                         return false, option:errors()
312                                 else
313                                         return true
314                                 end
315                         end
316                 end
317
318                 if option:scheme('required') and not option:value() then
319                         return false, option:error(ERR('OPT_REQUIRED', option))
320
321                 elseif option:value() then
322                         local val = option:value()
323
324                         if option:scheme('type') == "reference" or
325                            option:scheme('type') == "enum"
326                         then
327                                 local scheme_values = option:scheme('values') or { }
328                                 local config_values = ( type(val) == "table" and val or { val } )
329                                 for _, v in ipairs(config_values) do
330                                         if not scheme_values[v] then
331                                                 return false, option:error( ERR(
332                                                         'OPT_BADVALUE',
333                                                         option, { v, util.serialize_data(
334                                                                 util.keys(scheme_values)
335                                                         ) }
336                                                 ) )
337                                         end
338                                 end
339                         elseif option:scheme('type') == "list" then
340                                 if type(val) ~= "table" and STRICT_LIST_TYPE then
341                                         return false, option:error(ERR('OPT_NOTLIST', option))
342                                 end
343                         end
344
345                         if option:scheme('datatype') then
346                                 local dt = option:scheme('datatype')
347
348                                 if self.datatypes[dt] then
349                                         val = ( type(val) == "table" and val or { val } )
350                                         for i, v in ipairs(val) do
351                                                 if not self.datatypes[dt]( v ) then
352                                                         return false, option:error(
353                                                                 ERR('OPT_INVVALUE', option, { v, dt })
354                                                         )
355                                                 end
356                                         end
357                                 else
358                                         return false, option:error(ERR('OPT_DATATYPE', option, dt))
359                                 end
360                         end
361
362                         val = ( type(val) == "table" and val or { val } )
363                         for _, v in ipairs(val) do
364                                 if option:scheme('minlength') then
365                                         if #v < option:scheme('minlength') then
366                                                 return false, option:error(ERR('OPT_RANGE', option))
367                                         end
368                                 end
369
370                                 if option:scheme('maxlength') then
371                                         if #v > option:scheme('maxlength') then
372                                                 return false, option:error(ERR('OPT_RANGE', option))
373                                         end
374                                 end
375
376                                 local w = tonumber(v)
377
378                                 if option:scheme('minimum') then
379                                         if not w or w < option:scheme('minimum') then
380                                                 return false, option:error(ERR('OPT_RANGE', option))
381                                         end
382                                 end
383
384                                 if option:scheme('maximum') then
385                                         if not w or w > option:scheme('maximum') then
386                                                 return false, option:error(ERR('OPT_RANGE', option))
387                                         end
388                                 end
389                         end
390                 end
391
392                 local ok, err = validation.check( self, option )
393                 if not ok and STRICT_EXTERNAL_VALIDATORS then
394                         return false, option:error(err)
395                 end
396         end
397
398         return option:ok(), option:errors()
399 end
400
401 --- Find all parts of given scheme and construct validation tree.
402 -- This is normally done on demand, so you don't have to call this function
403 -- by yourself.
404 -- @param shm   Name of the scheme to parse
405 -- @param alias         Create an alias for the loaded scheme
406 function UVL.read_scheme( self, shm, alias )
407
408         local so = scheme( self, shm )
409         local bc = "%s/bytecode/%s.lua" %{ self.schemedir, shm }
410
411         if not fs.access(bc) then
412                 local files = nutil.consume((fs.glob(self.schemedir .. '/*/' .. shm)))
413
414                 if #files > 0 then
415                         local ok, err
416                         for _, file in ipairs(files) do
417                                 if not fs.access(file) then
418                                         return false, so:error(ERR('SME_READ', so,file))
419                                 end
420
421                                 local uci = uci.cursor( fs.dirname(file), default_savedir )
422
423                                 local sname = fs.basename(file)
424                                 local sd, err = uci:load( sname )
425
426                                 if not sd then
427                                         return false, ERR('UCILOAD', so, err)
428                                 end
429
430                                 ok, err = pcall(function()
431                                         uci:foreach(sname, "package", function(s)
432                                                 self:_parse_package(so, s[".name"], s)
433                                         end)
434                                         uci:foreach(sname, "section", function(s)
435                                                 self:_parse_section(so, s[".name"], s)
436                                         end)
437                                         uci:foreach(sname, "variable", function(s)
438                                                 self:_parse_var(so, s[".name"], s)
439                                         end)
440                                         uci:foreach(sname, "enum", function(s)
441                                                 self:_parse_enum(so, s[".name"], s)
442                                         end)
443
444                                 end)
445                         end
446
447                         if ok and alias then self.packages[alias] = self.packages[shm] end
448                         return ok and self, err
449                 else
450                         return false, so:error(ERR('SME_FIND', so, self.schemedir))
451                 end
452         else
453                 local sc = loadfile(bc)
454                 if sc then
455                         self.packages[shm] = sc()
456                         return true
457                 else
458                         return false, so:error(ERR('SME_READ',so,bc))
459                 end
460         end
461 end
462
463 -- helper function to check for required fields
464 local function _req( t, n, c, r )
465         for i, v in ipairs(r) do
466                 if not c[v] then
467                         local p, o = scheme:sid(), nil
468
469                         if t == TYPE_SECTION then
470                                 o = section( scheme, nil, p, n )
471                         elseif t == TYPE_OPTION then
472                                 o = option( scheme, nil, p, '(nil)', n )
473                         elseif t == TYPE_ENUM then
474                                 o = enum( scheme, nil, p, '(nil)', '(nil)', n )
475                         end
476
477                         return false, ERR('SME_REQFLD',o,v)
478                 end
479         end
480         return true
481 end
482
483 -- helper function to validate references
484 local function _ref( c, t )
485         local r, k, n = {}
486         if c == TYPE_SECTION then
487                 k = "package"
488                 n = 1
489         elseif c == TYPE_OPTION then
490                 k = "section"
491                 n = 2
492         elseif c == TYPE_ENUM then
493                 k = "variable"
494                 n = 3
495         end
496
497         for o in t[k]:gmatch("[^.]+") do
498                 r[#r+1] = o
499         end
500         r[1] = ( #r[1] > 0 and r[1] or scheme:sid() )
501
502         if #r ~= n then
503                 return false, ERR('SME_BADREF', scheme, k)
504         end
505
506         return r
507 end
508
509 -- helper function to read bools
510 local function _bool( v )
511         return ( v == "true" or v == "yes" or v == "on" or v == "1" )
512 end
513
514 -- Step 0: get package meta information
515 function UVL._parse_package(self, scheme, k, v)
516         local sid = scheme:sid()
517         local pkg = self.packages[sid] or {
518                 ["name"]      = sid;
519                 ["sections"]  = { };
520                 ["variables"] = { };
521         }
522
523         pkg.title = v.title
524         pkg.description = v.description
525
526         self.packages[sid] = pkg
527 end
528
529 -- Step 1: get all sections
530 function UVL._parse_section(self, scheme, k, v)
531         local ok, err = _req( TYPE_SECTION, k, v, { "name", "package" } )
532         if err then error(scheme:error(err)) end
533
534         local r, err = _ref( TYPE_SECTION, v )
535         if err then error(scheme:error(err)) end
536
537         local p = self.packages[r[1]] or {
538                 ["name"]      = r[1];
539                 ["sections"]  = { };
540                 ["variables"] = { };
541         }
542         p.sections[v.name]  = p.sections[v.name]  or { }
543         p.variables[v.name] = p.variables[v.name] or { }
544         self.packages[r[1]] = p
545
546         local s  = p.sections[v.name]
547         local so = scheme:section(v.name)
548
549         for k, v2 in pairs(v) do
550                 if k ~= "name" and k ~= "package" and k:byte(1) == 46 then
551                         if k == "depends" then
552                                 s.depends = self:_read_dependency( v2, s.depends )
553                                 if not s.depends then
554                                         return false, scheme:error(
555                                                 ERR('SME_BADDEP', so, util.serialize_data(s.depends))
556                                         )
557                                 end
558                         elseif k == "dynamic" or k == "unique" or
559                                k == "required" or k == "named"
560                         then
561                                 s[k] = _bool(v2)
562                         else
563                                 s[k] = v2
564                         end
565                 end
566         end
567
568         s.dynamic  = s.dynamic  or false
569         s.unique   = s.unique   or false
570         s.required = s.required or false
571         s.named    = s.named    or false
572 end
573
574 -- Step 2: get all variables
575 function UVL._parse_var(self, scheme, k, v)
576         local ok, err = _req( TYPE_OPTION, k, v, { "name", "section" } )
577         if err then error(scheme:error(err)) end
578
579         local r, err = _ref( TYPE_OPTION, v )
580         if err then error(scheme:error(err)) end
581
582         local p = self.packages[r[1]]
583         if not p then
584                 error(scheme:error(
585                         ERR('SME_VBADPACK', {scheme:sid(), '', v.name}, r[1])
586                 ))
587         end
588
589         local s = p.variables[r[2]]
590         if not s then
591                 error(scheme:error(
592                         ERR('SME_VBADSECT', {scheme:sid(), '', v.name}, r[2])
593                 ))
594         end
595
596         s[v.name] = s[v.name] or { }
597
598         local t  = s[v.name]
599         local so = scheme:section(r[2])
600         local to = so:option(v.name)
601
602         for k, v2 in pairs(v) do
603                 if k ~= "name" and k ~= "section" and k:byte(1) == 46 then
604                         if k == "depends" then
605                                 t.depends = self:_read_dependency( v2, t.depends )
606                                 if not t.depends then
607                                         error(scheme:error(so:error(
608                                                 ERR('SME_BADDEP', to, util.serialize_data(v2))
609                                         )))
610                                 end
611                         elseif k == "validator" then
612                                 t.validators = self:_read_validator( v2, t.validators )
613                                 if not t.validators then
614                                         error(scheme:error(so:error(
615                                                 ERR('SME_BADVAL', to, util.serialize_data(v2))
616                                         )))
617                                 end
618                         elseif k == "valueof" then
619                                 local values, err = self:_read_reference( v2 )
620                                 if err then
621                                         error(scheme:error(so:error(
622                                                 ERR('REFERENCE', to, util.serialize_data(v2)):child(err)
623                                         )))
624                                 end
625                                 t.type   = "reference"
626                                 t.values = values
627                                 t.valueof = type(v2) == "table" and v2 or {v2}
628                         elseif k == "required" then
629                                 t[k] = _bool(v2)
630                         elseif k == "minlength" or k == "maxlength" or
631                    k == "minimum" or k == "maximum"
632             then
633                                 t[k] = tonumber(v2)
634                         else
635                                 t[k] = t[k] or v2
636                         end
637                 end
638         end
639
640         t.type     = t.type     or "variable"
641         t.datatype = t.datatype or "string"
642         t.required = t.required or false
643 end
644
645 -- Step 3: get all enums
646 function UVL._parse_enum(self, scheme, k, v)
647         local ok, err = _req( TYPE_ENUM, k, v, { "value", "variable" } )
648         if err then error(scheme:error(err)) end
649
650         local r, err = _ref( TYPE_ENUM, v )
651         if err then error(scheme:error(err)) end
652
653         local p = self.packages[r[1]]
654         if not p then
655                 error(scheme:error(
656                         ERR('SME_EBADPACK', {scheme:sid(), '', '', v.value}, r[1])
657                 ))
658         end
659
660         local s = p.variables[r[2]]
661         if not s then
662                 error(scheme:error(
663                         ERR('SME_EBADSECT', {scheme:sid(), '', '', v.value}, r[2])
664                 ))
665         end
666
667         local t = s[r[3]]
668         if not t then
669                 error(scheme:error(
670                         ERR('SME_EBADOPT', {scheme:sid(), '', '', v.value}, r[3])
671                 ))
672         end
673
674
675         local so = scheme:section(r[2])
676         local oo = so:option(r[3])
677         local eo = oo:enum(v.value)
678
679         if t.type ~= "enum" and t.type ~= "reference" then
680                 error(scheme:error(ERR('SME_EBADTYPE', eo)))
681         end
682
683         if not t.values then
684                 t.values = { [v.value] = v.title or v.value }
685                 t.valuelist = { {value = v.value, title = v.title} }
686         else
687                 t.values[v.value] = v.title or v.value
688                 t.valuelist[#t.valuelist + 1] = {value = v.value, title = v.title}
689         end
690
691         if not t.enum_depends then
692                 t.enum_depends = { }
693         end
694
695         if v.default then
696                 if t.default then
697                         error(scheme:error(ERR('SME_EBADDEF', eo)))
698                 end
699                 t.default = v.value
700         end
701
702         if v.depends then
703                 t.enum_depends[v.value] = self:_read_dependency(
704                         v.depends, t.enum_depends[v.value]
705                 )
706
707                 if not t.enum_depends[v.value] then
708                         error(scheme:error(so:error(oo:error(
709                                 ERR('SME_BADDEP', eo, util.serialize_data(v.depends))
710                         ))))
711                 end
712         end
713 end
714
715 -- Read a dependency specification
716 function UVL._read_dependency( self, values, deps )
717         local expr = "%$?[%w_]+"
718         if values then
719                 values = ( type(values) == "table" and values or { values } )
720                 for _, value in ipairs(values) do
721                         local condition = { }
722                         for val in value:gmatch("[^,]+") do
723                                 local k, e, v = val:match("%s*([%w$_.]+)%s*(=?)%s*(.*)")
724
725                                 if k and (
726                                         k:match(PAT_EXPR1) or k:match(PAT_EXPR2) or k:match(PAT_EXPR3)
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, arg1, arg2, arg3, arg4, arg5 )
759                                         local values = { arg1, arg2, arg3, arg4, arg5 }
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, arg1, arg2, arg3, arg4, arg5)
927         if not self.e then
928                 local errconst = { 'CONFIG', 'SECTION', 'OPTION', 'OPTION' }
929                 self.e = ERR( errconst[#self.cref], self )
930         end
931
932         return self.e:child( arg1, arg2, arg3, arg4, arg5 )
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, configdir)
956         co = co or self._configcache
957         if not co then
958                 local err
959                 co, err = uci.cursor(configdir):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, scheme.configdir)
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, arg1, arg2, arg3, arg4, arg5)
1000         if not self.e then self.e = ERR( 'SCHEME', self ) end
1001         return self.e:child( arg1, arg2, arg3, arg4, arg5 )
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         self.cref = { c }
1057         self.sref = { c }
1058         self.c    = self:_loadconf(co, c, scheme.configdir)
1059         self.s    = scheme
1060         self.t    = TYPE_CONFIG
1061 end
1062
1063 --- Get all section objects associated with this config.
1064 -- @return      Table containing all associated luci.uvl.section instances
1065 function config.sections(self)
1066         local v = { }
1067         if self.s.packages[self.sref[1]].sections then
1068                 for o, _ in pairs( self.s.packages[self.sref[1]].sections ) do
1069                         v[#v+1] = option(
1070                                 self.s, self.c, self.cref[1], self.cref[2], o
1071                         )
1072                 end
1073         end
1074         return v
1075 end
1076
1077 --- Get an associated section object.
1078 -- @param s     Section to select
1079 -- @return      Section instance
1080 function config.section(self, s)
1081         local so = section( self.s, self.c, self.cref[1], s )
1082               so.p = self
1083
1084         return so
1085 end
1086
1087
1088 --- Object representation of a scheme/config section.
1089 -- @class       module
1090 -- @cstyle      instance
1091 -- @name        luci.uvl.section
1092
1093 --- Section instance constructor.
1094 -- @class                       function
1095 -- @name                        section
1096 -- @param scheme        Scheme instance
1097 -- @param co            Configuration data
1098 -- @param c                     Configuration name
1099 -- @param s                     Section name
1100 -- @return                      Section instance
1101 section = util.class(uvlitem)
1102
1103 function section.__init__(self, scheme, co, c, s)
1104         self.cref = { c, s }
1105         self.sref = { c, co and co[s] and co[s]['.type'] or s }
1106         self.c    = self:_loadconf(co, c, scheme.configdir)
1107         self.s    = scheme
1108         self.t    = TYPE_SECTION
1109 end
1110
1111 --- Get all option objects associated with this section.
1112 -- @return      Table containing all associated luci.uvl.option instances
1113 function section.variables(self)
1114         local v = { }
1115         if self.s.packages[self.sref[1]].variables[self.sref[2]] then
1116                 for o, _ in pairs(
1117                         self.s.packages[self.sref[1]].variables[self.sref[2]]
1118                 ) do
1119                         v[#v+1] = option(
1120                                 self.s, self.c, self.cref[1], self.cref[2], o
1121                         )
1122                 end
1123         end
1124         return v
1125 end
1126
1127 --- Get an associated option object.
1128 -- @param o     Option to select
1129 -- @return      Option instance
1130 function section.option(self, o)
1131         local oo = option( self.s, self.c, self.cref[1], self.cref[2], o )
1132               oo.p = self
1133
1134         return oo
1135 end
1136
1137
1138 --- Object representation of a scheme/config option.
1139 -- @class       module
1140 -- @cstyle      instance
1141 -- @name        luci.uvl.option
1142
1143 --- Section instance constructor.
1144 -- @class                       function
1145 -- @name                        option
1146 -- @param scheme        Scheme instance
1147 -- @param co            Configuration data
1148 -- @param c                     Configuration name
1149 -- @param s                     Section name
1150 -- @param o                     Option name
1151 -- @return                      Option instance
1152 option = util.class(uvlitem)
1153
1154 function option.__init__(self, scheme, co, c, s, o)
1155         self.cref = { c, s, o }
1156         self.sref = { c, co and co[s] and co[s]['.type'] or s, o }
1157         self.c    = self:_loadconf(co, c, scheme.configdir)
1158         self.s    = scheme
1159         self.t    = TYPE_OPTION
1160 end
1161
1162 --- Get the value of this option.
1163 -- @return      The associated configuration value
1164 function option.value(self)
1165         local v = self:config() or self:scheme('default')
1166         if v and self:scheme('multival') then
1167                 v = util.split( v, "%s+", nil, true )
1168         end
1169         return v
1170 end
1171
1172 --- Get the associated section information in scheme.
1173 -- @return      Table containing the scheme properties
1174 function option.section(self)
1175         return self.s.packages[self.sref[1]].sections[self.sref[2]]
1176 end
1177
1178 --- Construct an enum object instance from given or default value.
1179 -- @param v     Value to select
1180 -- @return      Enum instance for selected value
1181 function option.enum(self, val)
1182         return enum(
1183                 self.s, self.c,
1184                 self.cref[1], self.cref[2], self.cref[3],
1185                 val or self:value()
1186         )
1187 end
1188
1189
1190 --- Object representation of a enum value.
1191 -- @class       module
1192 -- @cstyle      instance
1193 -- @name        luci.uvl.enum
1194
1195 --- Section instance constructor.
1196 -- @class                       function
1197 -- @name                        enum
1198 -- @param scheme        Scheme instance
1199 -- @param co            Configuration data
1200 -- @param c                     Configuration name
1201 -- @param s                     Section name
1202 -- @param o                     Enum name
1203 -- @param v                     Enum value
1204 -- @return                      Enum value instance
1205 enum = util.class(option)
1206
1207 function enum.__init__(self, scheme, co, c, s, o, v)
1208         self.cref = { c, s, o, v }
1209         self.sref = { c, co and co[s] and co[s]['.type'] or s, o, v }
1210         self.c    = self:_loadconf(co, c, scheme.configdir)
1211         self.s    = scheme
1212         self.t    = TYPE_ENUM
1213 end