3 UCI Validation Layer - Datatype Tests
4 (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
5 (c) 2008 Steven Barth <steven@midlink.org>
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
11 http://www.apache.org/licenses/LICENSE-2.0
17 local fs = require "luci.fs"
18 local ip = require "luci.ip"
19 local math = require "math"
20 local util = require "luci.util"
22 local tonumber = tonumber
24 module "luci.uvl.datatypes"
27 function boolean( val )
28 if val == "1" or val == "yes" or val == "on" or val == "true" then
30 elseif val == "0" or val == "no" or val == "off" or val == "false" then
32 elseif val == "" or val == nil then
40 local n = tonumber(val)
41 if n ~= nil and math.floor(n) == n and n >= 0 then
48 function integer( val )
49 local n = tonumber(val)
50 if n ~= nil and math.floor(n) == n then
58 return ( tonumber(val) ~= nil )
61 function ipaddr( val )
62 return ip4addr(val) or ip6addr(val)
65 function ip4addr( val )
67 return ip.IPv4(val) and true or false
73 function ip4prefix( val )
75 return ( val and val >= 0 and val <= 32 )
78 function ip6addr( val )
80 return ip.IPv6(val) and true or false
86 function ip6prefix( val )
88 return ( val and val >= 0 and val <= 128 )
93 return ( val and val >= 1 and val <= 65535 )
96 function portrange( val )
97 local p1, p2 = val:match("^(%d+)%-(%d+)$")
98 if p1 and p2 and port(p1) and port(p2) then
105 function macaddr( val )
106 if val and val:match(
107 "^[a-fA-F0-9]+:[a-fA-F0-9]+:[a-fA-F0-9]+:" ..
108 "[a-fA-F0-9]+:[a-fA-F0-9]+:[a-fA-F0-9]+$"
110 local parts = util.split( val, ":" )
113 parts[i] = tonumber( parts[i], 16 )
114 if parts[i] < 0 or parts[i] > 255 then
125 function hostname( val )
126 if val and val:match("[a-zA-Z0-9_][a-zA-Z0-9_%-%.]*") then
127 return true -- XXX: ToDo: need better solution
134 return hostname(val) or ipaddr(val)
137 function string( val )
138 return true -- Everything qualifies as valid string
141 function directory( val, seen )
142 local s = fs.stat( val )
145 if s and not seen[s.ino] then
147 if s.type == "directory" then
149 elseif s.type == "link" then
150 return directory( fs.readlink(val), seen )
157 function file( val, seen )
158 local s = fs.stat( val )
161 if s and not seen[s.ino] then
163 if s.type == "regular" then
165 elseif s.type == "link" then
166 return file( fs.readlink(val), seen )
173 function device( val, seen )
174 local s = fs.stat( val )
177 if s and not seen[s.ino] then
179 if s.type == "character device" or s.type == "block device" then
181 elseif s.type == "link" then
182 return device( fs.readlink(val), seen )