* luci/libs: uvl: add support for external validation commands, various cleanups
[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
23 function _exec( bin, args )
24         local cmd, output = "", nil
25
26         for _, v in ipairs({ bin, unpack(args) }) do
27                 cmd = cmd .. string.format("%q ",v):gsub("([%$`])","\\%1")
28         end
29
30         local tmpfile = "/tmp/uvl" .. luci.sys.uniqueid(8)
31         local retval  = os.execute( cmd .. " 1>" .. tmpfile .. " 2>" .. tmpfile )
32
33         if luci.fs.access(tmpfile) then
34                 output = luci.fs.readfile(tmpfile)
35                 luci.fs.unlink(tmpfile)
36         end
37
38         return retval, output
39 end
40
41 function check( self, object )
42         local item = object:option()
43
44         if item.validators then
45                 for _, val in ipairs(item.validators) do
46                         local ok, err = false, nil
47                         local args = {
48                                 item.type, unpack(object.cref), item.datatype, object:value()
49                         }
50
51                         if type(val) == "function" then
52                                 ok, err = val(unpack(args))
53                         else
54                                 ok, err = _exec( val, args )
55                                 ok = ( ok == 0 )
56                         end
57
58                         if not ok then
59                                 return false, err
60                         end
61                 end
62         end
63
64         return true, nil
65 end