* luci/libs: uvl: Major rewrite of internal element handling, reworked error model...
[project/luci.git] / libs / uvl / luasrc / uvl / validation.lua
1 --[[
2
3 UCI Validation Layer - Validation helper
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 module( "luci.uvl.validation", package.seeall )
18
19 require("luci.fs")
20 require("luci.sys")
21
22 local ERR = luci.uvl.errors
23
24 function _exec( bin, args )
25         local cmd, output = "", nil
26
27         for _, v in ipairs({ bin, unpack(args) }) do
28                 cmd = cmd .. string.format("%q ",v):gsub("([%$`])","\\%1")
29         end
30
31         local tmpfile = "/tmp/uvl" .. luci.sys.uniqueid(8)
32         local retval  = os.execute( cmd .. " 1>" .. tmpfile .. " 2>" .. tmpfile )
33
34         if luci.fs.access(tmpfile) then
35                 output = luci.fs.readfile(tmpfile)
36                 luci.fs.unlink(tmpfile)
37         end
38
39         return retval, output
40 end
41
42 function check( self, object )
43         if object:scheme('validators') then
44                 for _, val in ipairs(object:scheme('validators')) do
45                         local ok, err = false, nil
46                         local args = {
47                                 object:scheme('type'),
48                                 object.cref[1], object.cref[2], object.cref[3],
49                                 object:scheme('datatype'), object:value()
50                         }
51
52                         if type(val) == "function" then
53                                 ok, err = val(unpack(args))
54                         else
55                                 ok, err = _exec( val, args )
56                                 ok = ( ok == 0 )
57                         end
58
59                         if not ok then
60                                 return false, ERR.SME_ERRVAL(object, {tostring(val), err})
61                         end
62                 end
63         end
64
65         return true, nil
66 end