3 LuCI - Configuration Bind Interface - Datatype Tests
4 (c) 2010 Jo-Philipp Wich <xm@subsignal.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
16 local fs = require "nixio.fs"
17 local ip = require "luci.ip"
18 local math = require "math"
19 local util = require "luci.util"
21 local tonumber = tonumber
23 module "luci.cbi.datatypes"
27 if val == "1" or val == "yes" or val == "on" or val == "true" then
29 elseif val == "0" or val == "no" or val == "off" or val == "false" then
31 elseif val == "" or val == nil then
39 local n = tonumber(val)
40 if n ~= nil and math.floor(n) == n and n >= 0 then
48 local n = tonumber(val)
49 if n ~= nil and math.floor(n) == n then
57 return ( tonumber(val) ~= nil )
60 function ipaddr( val )
61 return ip4addr(val) or ip6addr(val)
64 function ip4addr( val )
66 return ip.IPv4(val) and true or false
72 function ip4prefix( val )
74 return ( val and val >= 0 and val <= 32 )
77 function ip6addr( val )
79 return ip.IPv6(val) and true or false
85 function ip6prefix( val )
87 return ( val and val >= 0 and val <= 128 )
92 return ( val and val >= 1 and val <= 65535 )
95 function portrange( val )
96 local p1, p2 = val:match("^(%d+)%-(%d+)$")
97 if p1 and p2 and port(p1) and port(p2) then
104 function macaddr( val )
105 if val and val:match(
106 "^[a-fA-F0-9]+:[a-fA-F0-9]+:[a-fA-F0-9]+:" ..
107 "[a-fA-F0-9]+:[a-fA-F0-9]+:[a-fA-F0-9]+$"
109 local parts = util.split( val, ":" )
112 parts[i] = tonumber( parts[i], 16 )
113 if parts[i] < 0 or parts[i] > 255 then
124 function hostname( val )
125 if val and val:match("[a-zA-Z0-9_][a-zA-Z0-9_%-%.]*") then
126 return true -- XXX: ToDo: need better solution
133 return hostname(val) or ipaddr(val)
136 function string( val )
137 return true -- Everything qualifies as valid string
140 function directory( val, seen )
141 local s = fs.stat( val )
144 if s and not seen[s.ino] then
146 if s.type == "dir" then
148 elseif s.type == "lnk" then
149 return directory( fs.readlink(val), seen )
156 function file( val, seen )
157 local s = fs.stat( val )
160 if s and not seen[s.ino] then
162 if s.type == "reg" then
164 elseif s.type == "lnk" then
165 return file( fs.readlink(val), seen )
172 function device( val, seen )
173 local s = fs.stat( val )
176 if s and not seen[s.ino] then
178 if s.type == "chr" or s.type == "blk" then
180 elseif s.type == "lnk" then
181 return device( fs.readlink(val), seen )