sandbox.lua 5.78 KB
Newer Older
1 2
-- Units
kB = 1024
3 4
MB = 1024*kB
GB = 1024*MB
5 6
-- Time
sec = 1000
7
second = sec
8
minute = 60 * sec
9
min = minute
10
hour = 60 * minute
11
day = 24 * hour
12

13 14 15 16 17 18 19 20 21 22 23
-- Logging
function panic(fmt, ...)
        error(string.format('error: '..fmt, ...))
end
function warn(fmt, ...)
        io.stderr:write(string.format(fmt..'\n', ...))
end
function log(fmt, ...)
        print(string.format(fmt, ...))
end

24 25
-- Resolver bindings
kres = require('kres')
26
trust_anchors = require('trust_anchors')
27
resolve = worker.resolve
28 29 30
if rawget(kres, 'str2dname') ~= nil then
	todname = kres.str2dname
end
31

32 33 34 35 36 37 38
-- Shorthand for aggregated per-worker information
worker.info = function ()
	local t = worker.stats()
	t.pid = worker.pid
	return t
end

39 40 41 42 43 44 45 46 47 48 49 50 51
-- Resolver mode of operation
local current_mode = 'normal'
local mode_table = { normal=0, strict=1, permissive=2 }
function mode(m)
	if not m then return current_mode end
	if not mode_table[m] then error('unsupported mode: '..m) end
	-- Update current operation mode
	current_mode = m
	option('STRICT', current_mode == 'strict')
	option('PERMISSIVE', current_mode == 'permissive')
	return true
end

52 53 54 55 56 57 58 59 60
-- Function aliases
-- `env.VAR returns os.getenv(VAR)`
env = {}
setmetatable(env, {
	__index = function (t, k) return os.getenv(k) end
})

-- Quick access to interfaces
-- `net.<iface>` => `net.interfaces()[iface]`
61
-- `net = {addr1, ..}` => `net.listen(name, addr1)`
62
-- `net.ipv{4,6} = {true, false}` => enable/disable IPv{4,6}
63 64 65 66
setmetatable(net, {
	__index = function (t, k)
		local v = rawget(t, k)
		if v then return v
67 68
		elseif k == 'ipv6' then return not option('NO_IPV6')
		elseif k == 'ipv4' then return not option('NO_IPV4')
69 70
		else return net.interfaces()[k]
		end
71 72
	end,
	__newindex = function (t,k,v)
73 74 75 76 77 78 79
		if     k == 'ipv6' then return option('NO_IPV6', not v)
		elseif k == 'ipv4' then return option('NO_IPV4', not v)
		else
			local iname = rawget(net.interfaces(), v)
			if iname then t.listen(iname)
			else t.listen(v)
			end
80
		end
81 82 83
	end
})

84 85
-- Syntactic sugar for module loading
-- `modules.<name> = <config>`
86
setmetatable(modules, {
87
	__newindex = function (t,k,v)
88
		if type(k) == 'number' then k = v v = nil end
89 90
		if not rawget(_G, k) then
			modules.load(k)
91
			k = string.match(k, '%w+')
92
			local mod = _G[k]
93
			local config = mod and rawget(mod, 'config')
94
			if mod ~= nil and config ~= nil then
Marek Vavruša's avatar
Marek Vavruša committed
95 96
				if k ~= v then config(v)
				else           config()
97
				end
98 99
			end
		end
100 101 102 103
	end
})

-- Syntactic sugar for cache
104 105
-- `#cache -> cache.count()`
-- `cache[x] -> cache.get(x)`
106 107
-- `cache.{size|storage} = value`
setmetatable(cache, {
108 109 110 111 112 113
	__len = function (t)
		return t.count()
	end,
	__index = function (t, k)
		return rawget(t, k) or (rawget(t, 'current_size') and t.get(k))
	end,
114
	__newindex = function (t,k,v)
115 116 117 118 119 120 121 122
		-- Defaults
		local storage = rawget(t, 'current_storage')
		if not storage then storage = 'lmdb://' end
		local size = rawget(t, 'current_size')
		if not size then size = 10*MB end
		-- Declarative interface for cache
		if     k == 'size'    then t.open(v, storage)
		elseif k == 'storage' then t.open(size, v)
123
		else   rawset(t, k, v) end
124
	end
125 126
})

127 128 129 130
-- Syntactic sugar for TA store
setmetatable(trust_anchors, {
	__newindex = function (t,k,v)
	if     k == 'file' then t.config(v)
131
	elseif k == 'negative' then t.set_insecure(v)
132 133 134 135
	else   rawset(t, k, v) end
	end,
})

136 137 138 139 140 141 142
-- Register module in Lua environment
function modules_register(module)
	-- Syntactic sugar for get() and set() properties
	setmetatable(module, {
		__index = function (t, k)
			local  v = rawget(t, k)
			if     v     then return v
143
			elseif rawget(t, 'get') then return t.get(k)
144 145 146 147
			end
		end,
		__newindex = function (t, k, v)
			local  old_v = rawget(t, k)
148
			if not old_v and rawget(t, 'set') then
149 150 151 152 153 154
				t.set(k..' '..v)
			end
		end
	})
end

155
-- Make sandboxed environment
156
local function make_sandbox(defined)
157
	local __protected = { modules = true, cache = true, net = true, trust_anchors = true }
158 159 160 161 162 163 164 165 166 167 168 169 170
	return setmetatable({}, {
		__index = defined,
		__newindex = function (t, k, v)
			if __protected[k] then
				for k2,v2 in pairs(v) do
					defined[k][k2] = v2
				end
			else
				defined[k] = v
			end
		end
	})
end
171

172
-- Compatibility sandbox
173 174 175 176 177 178
if setfenv then -- Lua 5.1 and less
	_G = make_sandbox(getfenv(0))
	setfenv(0, _G)
else -- Lua 5.2+
	_SANDBOX = make_sandbox(_ENV)
end
179

180
-- Interactive command evaluation
181
function eval_cmd(line, raw)
182 183 184 185 186 187 188 189 190
	-- Compatibility sandbox code loading
	local function load_code(code)
	    if getfenv then -- Lua 5.1
	        return loadstring(code)
	    else            -- Lua 5.2+
	        return load(code, nil, 't', _ENV)
	    end
	end
	local status, err, chunk
191
	chunk, err = load_code(raw and 'return '..line or 'return table_print('..line..')')
192 193 194 195
	if err then
		chunk, err = load_code(line)
	end
	if not err then
196 197 198
		return chunk()
	else
		error(err)
199 200 201
	end
end

202 203 204 205
-- Pretty printing
function table_print (tt, indent, done)
	done = done or {}
	indent = indent or 0
206
	result = ""
207 208 209 210 211 212 213 214 215 216 217 218 219
	-- Convert to printable string (escape unprintable)
	local function printable(value)
		value = tostring(value)
		local bytes = {}
		for i = 1, #value do
			local c = string.byte(value, i)
			if c >= 0x20 and c < 0x7f then table.insert(bytes, string.char(c))
			else                           table.insert(bytes, '\\'..tostring(c))
			end
			if i > 50 then table.insert(bytes, '...') break end
		end
		return table.concat(bytes)
	end
220 221
	if type(tt) == "table" then
		for key, value in pairs (tt) do
222
			result = result .. string.rep (" ", indent)
223 224
			if type (value) == "table" and not done [value] then
				done [value] = true
225
				result = result .. string.format("[%s] => {\n", printable (key))
226
				result = result .. table_print (value, indent + 4, done)
227 228
				result = result .. string.rep (" ", indent)
				result = result .. "}\n"
229
			else
230
				result = result .. string.format("[%s] => %s\n",
231
				         tostring (key), printable(value))
232 233 234
			end
		end
	else
235
		result = result .. tostring(tt) .. "\n"
236
	end
237
	return result
238
end