Blame view

server.lua 1.65 KB
1 2 3 4
require("love.filesystem")
require("love.math")
require("love.thread")

5
local dbg = os.getenv("DEBUG") and print or function() end
6 7 8 9 10 11
local output, input, os_name, hostname = ...
local os_ok, os = pcall(require, "os." .. os_name .. ".init")
if(not os_ok) then print("Couldn't load OS:", os) return end

local sessions = {}

12
local new_session = function(username, password)
13 14 15 16
   if(not os.is_authorized(hostname, username, password)) then
      return output:push({op="status", out="Login failed."})
   end
   local session_id = string.format("%x", love.math.random(42949672))
17 18 19
   local stdin = love.thread.newChannel()
   sessions[session_id] = os.new_session(stdin, output, username, hostname)
   sessions[session_id].stdin = stdin
20 21
   output:push({op="status", ok=true, ["new-session"] = session_id})
   return true
22 23 24 25
end

while true do
   local msg = input:demand()
26
   -- TODO: range check
Phil Hagelberg committed
27
   dbg(">", require("lume").serialize(msg))
Phil Hagelberg committed
28
   if(msg.op == "kill") then
Phil Hagelberg committed
29 30 31 32 33
      for session_id,session in pairs(sessions) do
         if(os.kill) then
            os.kill(session)
            sessions[session_id] = nil
         end
Phil Hagelberg committed
34 35
      end
      return
36
   elseif(msg.op == "login") then
37 38
      local handle = function() print(debug.traceback()) end
      if(not xpcall(new_session, handle, msg.username, msg.password)) then
39
         output:push({op="status", out="Login error."})
40
      end
41
   elseif(msg.op == "stdin" or msg.ssrpc) then -- ssrpc for server-side RPC
42 43
      local session = sessions[msg.session]
      if(session) then
44
         session.stdin:push(msg)
45 46 47 48 49 50 51
      else
         print("Warning: no session", msg.session)
      end
   elseif(msg.op == "debug") then
      pp(sessions)
   end
end