* luci/libs/uvl:
[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
47                         local values = object:value()
48                               values = type(values) == "table" and values or { values }
49
50                         local args = {
51                                 object:scheme('type'), object:scheme('datatype'),
52                                 object.cref[1], object.cref[2], object.cref[3] or '',
53                                 unpack(values)
54                         }
55
56                         if type(val) == "function" then
57                                 ok, err = val(unpack(args))
58                         else
59                                 ok, err = _exec( val, args )
60                                 ok = ( ok == 0 )
61                         end
62
63                         if not ok then
64                                 return false, ERR.SME_ERRVAL(object, {tostring(val), err})
65                         end
66                 end
67         end
68
69         return true, nil
70 end