From 3e2d86693f6e8920c97fe296491e7741e31f922c Mon Sep 17 00:00:00 2001 From: Natanael Copa Date: Fri, 8 Mar 2013 16:42:03 +0100 Subject: implement one lua state per connection This allows you load various modules into a server lua state and give a performance boost when calling the privileged functions --- server/handler.lua | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 server/handler.lua (limited to 'server/handler.lua') diff --git a/server/handler.lua b/server/handler.lua new file mode 100644 index 0000000..41a02fb --- /dev/null +++ b/server/handler.lua @@ -0,0 +1,64 @@ + +--print("DEBUG: got message:", msg) + +--ipcmsg = require("json") +ipcmsg = require("cmsgpack") +ipcmsg.encode = ipcmsg.pack +ipcmsg.decode = ipcmsg.unpack + +ml = require("ml") + +modules_path = "../modules/" + +mods = {} + +local function ret_error(errmsg) + io.stderr:write("ERROR: "..tostring(errmsg).."\n") + return ipcmsg.encode{ status = false, errmsg = errmsg} +end + +local function ret_success(...) + return ipcmsg.encode{ status = true, errmsg = "success", + result = {...} } +end + +reqhandler = {} +function reqhandler.load(req) + -- make sure we dont have any path elements in modname so we cannot pass + -- modnames like '../myevilmod' + local file = modules_path..string.gsub(req.modname, ".*/", "")..".lua" + mods[req.modidx] = dofile(file) + if mods[req.modidx] == nil then + return ret_error(file) + end + return true +end + +function reqhandler.call(req) + if req.modidx == nil or req.func == nil then + return ret_error("failed to call function "..tostring(req.func)) + end + local m = mods[req.modidx] + -- check that the func we want exists + if type(m[req.func]) ~= "function" then + ret_error(func..": not a function in '".. mfile .."'") + end + + -- TODO: check permissions here +-- print("DEBUG: Calling mods["..req.modidx.."]."..req.func) + + -- execute the func and pack the return values into a table + return m[req.func](unpack(req.args)) +end + +function handler(msg) + local req = ipcmsg.decode(msg) +-- print("DEBUG: req="..ml.tstring(req)) + if type(req.type) ~= "string" then + return ret_error("request type missing") + end + if type(reqhandler[req.type]) == "function" then + return ret_success(reqhandler[req.type](req)) + end + return ret_error("no handler for request type "..req.type) +end -- cgit v1.2.3