convert luci.fs users to nixio.fs api
[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 local os = require "os"
18 local fs = require "nixio.fs"
19 local sys = require "luci.sys"
20 local ERR = require "luci.uvl.errors"
21
22 local ipairs, unpack, type, tostring = ipairs, unpack, type, tostring
23
24 module "luci.uvl.validation"
25
26 function _exec( bin, args )
27         local cmd, output = "", nil
28
29         for _, v in ipairs({ bin, unpack(args) }) do
30                 cmd = cmd .. ("%q " % v):gsub("([%$`])","\\%1")
31         end
32
33         local tmpfile = "/tmp/uvl" .. sys.uniqueid(8)
34         local retval  = os.execute( cmd .. " 1>" .. tmpfile .. " 2>" .. tmpfile )
35
36         if fs.access(tmpfile) then
37                 output = fs.readfile(tmpfile)
38                 fs.unlink(tmpfile)
39         end
40
41         return retval, output
42 end
43
44 function check( self, object )
45         if object:scheme('validators') then
46                 for _, val in ipairs(object:scheme('validators')) do
47                         local ok, err = false, nil
48
49                         local values = object:value()
50                               values = type(values) == "table" and values or { values }
51
52                         local args = {
53                                 object:scheme('type'), object:scheme('datatype'),
54                                 object.cref[1], object.cref[2], object.cref[3] or '',
55                                 unpack(values)
56                         }
57
58                         if type(val) == "function" then
59                                 ok, err = val(unpack(args))
60                         else
61                                 ok, err = _exec( val, args )
62                                 ok = ( ok == 0 )
63                         end
64
65                         if not ok then
66                                 return false, ERR.SME_ERRVAL(object, {tostring(val), err})
67                         end
68                 end
69         end
70
71         return true, nil
72 end