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