-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredis_env.lua
More file actions
80 lines (66 loc) · 1.7 KB
/
Copy pathredis_env.lua
File metadata and controls
80 lines (66 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
local redis = require('redis')
local cjson = require('cjson')
local client
local redis_env = {}
function redis_env.connect(params)
client = redis.connect(params)
if params.password then
client:auth(params.password)
end
client:select(params.db)
end
function redis_env.call(cmd, ...)
cmd = string.lower(cmd)
local fn = client[cmd]
if not fn then
error("unknown redis command: " .. cmd)
end
return fn(client, ...)
end
function redis_env.pcall(cmd, ...)
local ok, res = pcall(redis_env.call, cmd, ...)
if ok then
return res
else
return { err = res }
end
end
local function createSandbox(keys, argv)
local scope = {
-- 注入 Redis 接口
redis = redis,
-- Redis 标准变量
KEYS = keys or {},
ARGV = argv or {},
-- 基础安全函数(白名单)
ipairs = ipairs,
pairs = pairs,
tonumber = tonumber,
tostring = tostring,
type = type,
string = string,
table = table,
math = math,
unpack = unpack or table.unpack,
cjson = cjson
}
local env = setmetatable(scope, {
__index = _G,
__newindex = function(_, k)
error("global '" .. k .. "' is readonly", 2)
end
})
return env
end
function redis_env.runLuaFile(path, keys, argv)
local env = createSandbox(keys, argv)
env.redis.call = function(cmd, ...)
return redis_env.call(cmd, ...)
end
local func, err = loadfile(path, "t", env)
if not func then
error(err)
end
return func()
end
return redis_env