aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/factoids/sandbox.lua
diff options
context:
space:
mode:
authorJokler <jokler.contact@gmail.com>2018-03-12 16:02:51 +0100
committerJokler <jokler.contact@gmail.com>2018-03-12 16:02:51 +0100
commit909cabe9280722e43c5fb283f768051bb85e1890 (patch)
tree506ac34b7e22cdb95568cef9e649ee64cb3b0fdb /src/plugins/factoids/sandbox.lua
parent15e855ddecfdac31ddda26b12fcfd1a142a0ec21 (diff)
parent8e40e919aca8b8592be43e2c5bbcc0717bf14a6b (diff)
downloadfrippy-909cabe9280722e43c5fb283f768051bb85e1890.tar.gz
frippy-909cabe9280722e43c5fb283f768051bb85e1890.zip
Merge branch 'dev'
Diffstat (limited to 'src/plugins/factoids/sandbox.lua')
-rw-r--r--src/plugins/factoids/sandbox.lua86
1 files changed, 86 insertions, 0 deletions
diff --git a/src/plugins/factoids/sandbox.lua b/src/plugins/factoids/sandbox.lua
new file mode 100644
index 0000000..3fc74cd
--- /dev/null
+++ b/src/plugins/factoids/sandbox.lua
@@ -0,0 +1,86 @@
+function send(text)
+ local text = tostring(text)
+ local len = #output
+ if len < 1 then
+ output = { text }
+ else
+ output[len] = output[len] .. text
+ end
+end
+
+function sendln(text)
+ send(text)
+ table.insert(output, "")
+end
+
+local sandbox_env = {
+ print = send,
+ println = sendln,
+ eval = nil,
+ args = args,
+ input = input,
+ user = user,
+ channel = channel,
+ request = download,
+ string = string,
+ math = math,
+ table = table,
+ pairs = pairs,
+ ipairs = ipairs,
+ next = next,
+ select = select,
+ unpack = unpack,
+ tostring = tostring,
+ tonumber = tonumber,
+ type = type,
+ assert = assert,
+ error = error,
+ pcall = pcall,
+ xpcall = xpcall,
+ _VERSION = _VERSION
+}
+
+sandbox_env.os = {
+ clock = os.clock,
+ time = os.time,
+ difftime = os.difftime
+}
+
+sandbox_env.string.rep = nil
+sandbox_env.string.dump = nil
+sandbox_env.math.randomseed = nil
+
+-- Temporary evaluation function
+function eval(code)
+ local c, e = load(code, nil, nil, sandbox_env)
+ if c then
+ return c()
+ else
+ error(e)
+ end
+end
+
+sandbox_env.eval = eval
+
+-- Check if the factoid timed out
+function checktime(event, line)
+ if os.time() - time >= timeout then
+ error("Timed out after " .. timeout .. " seconds", 0)
+ else
+ -- Limit the cpu usage of factoids
+ sleep(1)
+ end
+end
+
+local f, e = load(factoid, nil, nil, sandbox_env)
+
+-- Add timeout hook
+time = os.time()
+timeout = 30
+debug.sethook(checktime, "l")
+
+if f then
+ f()
+else
+ error(e)
+end