Mercurial > hg > rlgwebd
view rlgwebd.js @ 55:96815eae4ebe
RLG-Web: make multiple watchers possible.
Split the TermSession class into the new TermSession, which handles the
PTY, and client classes, which handle HTTP sessions. These are Player
and Watcher. This allows multiple watchers per game, and other
improvements.
author | John "Elwin" Edwards <elwin@sdf.org> |
---|---|
date | Mon, 18 Jun 2012 13:43:51 -0700 |
parents | 423ef87ddc9b |
children | 31bb3cf4f25f |
line wrap: on
line source
#!/usr/bin/env node // If you can't quite trust node to find it on its own var localModules = '/usr/local/lib/node_modules/'; var http = require('http'); var net = require('net'); var url = require('url'); var path = require('path'); var fs = require('fs'); var events = require('events'); var child_process = require('child_process'); var daemon = require(path.join(localModules, "daemon")); /* Configuration variables */ // These first two files are NOT in the chroot. var ctlsocket = "/var/local/rlgwebd/ctl"; var logfile = "/var/local/rlgwebd/log"; var httpPort = 8080; var chrootDir = "/var/dgl/"; var dropToUID = 501; var dropToGID = 501; var serveStaticRoot = "/var/www/"; // inside the chroot var playtimeout = 3600000; // Idle time before games are autosaved, in ms /* Data on the games available. */ var games = { "rogue3": { "name": "Rogue V3", "uname": "rogue3", "suffix": ".r3sav", "path": "/bin/rogue3" }, "rogue4": { "name": "Rogue V4", "uname": "rogue4", "suffix": ".r4sav", "path": "/bin/rogue4" }, "rogue5": { "name": "Rogue V5", "uname": "rogue5", "suffix": ".r5sav", "path": "/bin/rogue5" }, "srogue": { "name": "Super-Rogue", "uname": "srogue", "suffix": ".srsav", "path": "/bin/srogue" } }; /* Global state */ var logins = {}; var sessions = {}; var clients = {}; var allowlogin = true; var nextsession = 0; /* Constructor. A TermSession handles a pty and the game running on it. * game: (String) Name of the game to launch. * lkey: (String, key) The user's id, a key into logins. * dims: (Array [Number, Number]) Height and width of the pty. * handlers: (Object) Key-value pairs, event names and functions to * install to handle them. * Events: * "open": Emitted on startup. Parameters: success (Boolean) * "data": Data generated by child. Parameters: buf (Buffer) * "exit": Child terminated. Parameters: exitcode, signal */ function TermSession(game, lkey, dims, handlers) { var ss = this; /* Subclass EventEmitter to do the hard work. */ events.EventEmitter.call(this); for (var evname in handlers) this.on(evname, handlers[evname]); /* Don't launch anything that's not a real game. */ if (game in games) { this.game = games[game]; } else { this.emit('open', false); return; } if (lkey in logins) { this.key = lkey; this.pname = logins[lkey].name; } else { this.emit('open', false); return; } /* Grab a spot in the sessions table. */ this.sessid = nextsession++; sessions[this.sessid] = this; /* Set up the sizes. */ this.w = Math.floor(Number(dims[1])); if (!(this.w > 0 && this.w < 256)) this.w = 80; this.h = Math.floor(Number(dims[0])); if (!(this.h > 0 && this.h < 256)) this.h = 24; /* Environment. */ var childenv = {}; for (var key in process.env) { childenv[key] = process.env[key]; } childenv["PTYHELPER"] = String(this.h) + "x" + String(this.w); args = [this.game.path, "-n", this.pname]; this.child = child_process.spawn("/bin/ptyhelper", args, {"env": childenv}); this.emit('open', true); /* Set up the lockfile and ttyrec */ var ts = timestamp(); var progressdir = "/dgldir/inprogress-" + this.game.uname; this.lock = path.join(progressdir, this.pname + ":node:" + ts + ".ttyrec"); var lmsg = this.child.pid.toString() + '\n' + this.w + '\n' + this.h + '\n'; fs.writeFile(this.lock, lmsg, "utf8"); var ttyrec = path.join("/dgldir/ttyrec", this.pname, this.game.uname, ts + ".ttyrec"); this.record = fs.createWriteStream(ttyrec, { mode: 0664 }); logins[lkey].sessions.push(this.sessid); tslog("%s playing %s (index %d, pid %d)", this.pname, this.game.uname, this.sessid, this.child.pid); /* END setup */ function ttyrec_chunk(buf) { var ts = new Date(); var chunk = new Buffer(buf.length + 12); /* TTYREC headers */ chunk.writeUInt32LE(Math.floor(ts.getTime() / 1000), 0); chunk.writeUInt32LE(1000 * (ts.getTime() % 1000), 4); chunk.writeUInt32LE(buf.length, 8); buf.copy(chunk, 12); ss.record.write(chunk); ss.emit('data', buf); } this.child.stdout.on("data", ttyrec_chunk); this.child.stderr.on("data", ttyrec_chunk); this.write = function(data) { this.child.stdin.write(data); }; this.child.on("exit", function (code, signal) { fs.unlink(ss.lock); ss.record.end(); ss.emit('exit', code, signal); var id = ss.sessid; delete sessions[id]; tslog("Session %s ended.", id); }); this.close = function () { this.child.kill('SIGHUP'); }; } TermSession.prototype = new events.EventEmitter(); function Watcher(session) { var ss = this; // that this.session = session; this.alive = true; /* State for messaging. */ this.nsend = 0; this.sendQ = []; /* Get a place in the table. */ this.id = randkey(2); while (this.id in clients) { this.id = randkey(2); } clients[this.id] = this; function dataH(buf) { var reply = {}; reply.t = "d"; reply.n = ss.nsend++; reply.d = buf.toString("hex"); ss.sendQ.push(reply); } function exitH(code, signal) { ss.alive = false; ss.sendQ.push({"t": "q"}); } session.on('data', dataH); session.on('exit', exitH); this.read = function() { /* Returns an array of all outstanding messages, empty if none. */ var temp = this.sendQ; this.sendQ = []; /* Clean up if finished. */ if (!this.alive) { delete clients[this.id]; } return temp; }; this.quit = function() { this.session.removeListener('data', dataH); this.session.removeListener('exit', exitH); delete clients[this.id]; }; } function Player(gamename, lkey, dims, callback) { var ss = this; this.alive = false; /* State for messaging. */ this.nsend = 0; this.nrecv = 0; this.sendQ = []; this.recvQ = [] this.Qtimeout = null; /* Get a place in the table. */ this.id = randkey(2); while (this.id in clients) { this.id = randkey(2); } clients[this.id] = this; this.read = function() { var temp = this.sendQ; this.sendQ = []; /* Clean up if finished. */ if (!this.alive) { clearTimeout(this.Qtimeout); delete clients[this.id]; } return temp; }; this.write = function (data, n) { if (!this.alive || typeof (n) != "number") { return; } var oindex = n - this.nrecv; if (oindex === 0) { this.session.write(data); this.nrecv++; var next; while ((next = this.recvQ.shift()) !== undefined) { this.session.write(next); this.nrecv++; } if (this.recvQ.length == 0 && this.Qtimeout) { clearTimeout(this.Qtimeout); this.Qtimeout = null; } } else if (oindex > 0 && oindex <= 1024) { tslog("Client %s: Stashing message %d at %d", this.id, n, oindex - 1); this.recvQ[oindex - 1] = data; if (!this.Qtimeout) { var nextn = this.nrecv + this.recvQ.length + 1; this.Qtimeout = setTimeout(this.flushQ, 30000, this, nextn); } } /* Otherwise, discard it */ return; }; this.flushQ = function (client, n) { /* Callback for when an unreceived message times out. * n is the first empty space that will not be given up on. */ if (!client.alive || client.nrecv >= n) return; client.nrecv++; var next; /* Clear the queue up to n */ while (client.nrecv < n) { next = client.recvQ.shift(); if (next !== undefined) client.session.write(next); client.nrecv++; } /* Clear out anything that's ready. */ while ((next = client.recvQ.shift()) !== undefined) { client.session.write(next); client.nrecv++; } /* Now set another timeout if necessary. */ if (client.recvQ.length != 0) { var nextn = client.nrecv + client.recvQ.length + 1; client.Qtimeout = setTimeout(client.flushQ, 30000, client, nextn); } tslog("Flushing queue for player %s", player.id); }; this.quit = function() { if (this.alive) this.session.close(); }; function openH(success) { if (success) { ss.alive = true; } callback(ss, success); } function dataH(chunk) { var reply = {}; reply.t = "d"; reply.n = ss.nsend++; reply.d = chunk.toString("hex"); ss.sendQ.push(reply); } function exitH(code, signal) { ss.alive = false; ss.sendQ.push({"t": "q"}); } var handlers = {'open': openH, 'data': dataH, 'exit': exitH}; this.session = new TermSession(gamename, lkey, dims, handlers); } /* Some functions which check whether a player is currently playing or * has a saved game. Maybe someday they will provide information on * the game. */ function checkprogress(user, game, callback, args) { var progressdir = "/dgldir/inprogress-" + game.uname; fs.readdir(progressdir, function(err, files) { if (err) { args.unshift(err, null); callback.apply(null, args); return; } var fre = RegExp("^" + user + ":"); for (var i = 0; i < files.length; i++) { if (files[i].match(fre)) { args.unshift(null, files[i]); callback.apply(null, args); return; } } args.unshift(null, false); callback.apply(null, args); }); } function checksaved(user, game, callback, args) { var savedirc = game.uname + "save"; var basename = String(dropToUID) + "-" + user + game.suffix; var savefile = path.join("/var/games/roguelike", savedirc, basename); path.exists(savefile, function (exist) { args.unshift(exist); callback.apply(null, args); }); } function playerstatus(user, callback) { var sdata = {}; function finishp() { for (var gname in games) { if (!(gname in sdata)) return; } callback(sdata); } function regsaved(exists, game) { if (exists) sdata[game.uname] = "s"; else sdata[game.uname] = "0"; finishp(); } function regactive(err, filename, game) { if (!err && filename) { sdata[game.uname] = "p"; finishp(); } else checksaved(user, game, regsaved, [game]); } for (var gname in games) { checkprogress(user, games[gname], regactive, [games[gname]]); } } /* A few utility functions */ function timestamp() { dd = new Date(); sd = dd.toISOString(); sd = sd.slice(0, sd.indexOf(".")); return sd.replace("T", "."); } function randkey(words) { if (!words || !(words > 0)) words = 1; function rand32() { rnum = Math.floor(Math.random() * 65536 * 65536); hexstr = rnum.toString(16); while (hexstr.length < 8) hexstr = "0" + hexstr; return hexstr; } var key = ""; for (var i = 0; i < words; i++) key += rand32(); return key; } function tslog() { arguments[0] = new Date().toISOString() + ": " + String(arguments[0]); console.log.apply(console, arguments); } /* Returns a list of the cookies in the request, obviously. */ function getCookies(req) { cookies = []; if ("cookie" in req.headers) { cookstrs = req.headers["cookie"].split("; "); for (var i = 0; i < cookstrs.length; i++) { eqsign = cookstrs[i].indexOf("="); if (eqsign > 0) { name = cookstrs[i].slice(0, eqsign).toLowerCase(); val = cookstrs[i].slice(eqsign + 1); cookies[name] = val; } else if (eqsign < 0) cookies[cookstrs[i]] = null; } } return cookies; } function getMsg(posttext) { var jsonobj; if (!posttext) return {}; try { jsonobj = JSON.parse(posttext); } catch (e) { if (e instanceof SyntaxError) return {}; } if (typeof(jsonobj) != "object") return {}; return jsonobj; } function reaper() { var now = new Date(); function reapcheck(session) { fs.fstat(session.record.fd, function (err, stats) { if (!err && now - stats.mtime > playtimeout) { tslog("Reaping session %s", session.sessid); /* Dissociate it with its login name. */ var sn = logins[session.key].sessions.indexOf(session.sessid); if (sn >= 0) { logins[session.key].sessions.splice(sn, 1); if (now - logins[session.key].ts > playtimeout) logins[session.key].ts = new Date(now - playtimeout); } /* Shut it down. */ session.close(); } }); } for (var sessid in sessions) { reapcheck(sessions[sessid]); } /* HELPME this is about as clever as I can code, so I can't tell whether * there are any bugs. */ for (var lkey in logins) { if (logins[lkey].sessions.length == 0) { /* A login with no current games can be killed for inactivity. */ if (now - logins[lkey].ts > playtimeout * 4) { tslog("Login for %s (key %s) timed out", logins[lkey].name, lkey); delete logins[lkey]; } } else { /* Check for games that have terminated normally, and update * the timestamp. */ var expired = []; var targarray = logins[lkey].sessions; /* Let's not find out what happens if you modify an array * you're iterating through. */ for (var i = 0; i < targarray.length; i++) { if (!(targarray[i] in sessions)) expired.push(targarray[i]); } if (expired.length > 0) { logins[lkey].ts = new Date(now); for (var j = 0; j < expired.length; j++) { targarray.splice(targarray.indexOf(expired[j]), 1); } } } } } function login(req, res, formdata) { if (!allowlogin) { sendError(res, 6, null, false); return; } if (!("name" in formdata)) { sendError(res, 2, "Username not given.", false); return; } else if (!("pw" in formdata)) { sendError(res, 2, "Password not given.", false); return; } var username = String(formdata["name"]); var password = String(formdata["pw"]); function checkit(code, signal) { /* Checks the exit status, see sqlickrypt.c for details. */ if (code != 0) { sendError(res, 3); if (code == 1) tslog("Password check failed for user %s", username); else if (code == 2) tslog("Attempted login by nonexistent user %s", username); else tslog("Login failed: sqlickrypt error %d", code); return; } var lkey = randkey(2); while (lkey in logins) lkey = randkey(2); logins[lkey] = {"name": username, "ts": new Date(), "sessions": []}; res.writeHead(200, {'Content-Type': 'application/json'}); var reply = {"t": "l", "k": lkey, "u": username}; res.write(JSON.stringify(reply)); res.end(); tslog("%s has logged in (key %s)", username, lkey); return; } /* Launch the sqlickrypt utility to check the password. */ var pwchecker = child_process.spawn("/bin/sqlickrypt", ["check"]); pwchecker.on("exit", checkit); pwchecker.stdin.end(username + '\n' + password + '\n', "utf8"); return; } function startgame(req, res, formdata) { if (!allowlogin) { sendError(res, 6, null); return; } if (!("key" in formdata)) { sendError(res, 2, "No key given."); return; } else if (!("game" in formdata)) { sendError(res, 2, "No game specified."); return; } var lkey = String(formdata["key"]); if (!(lkey in logins)) { sendError(res, 1, null); return; } else { logins[lkey].ts = new Date(); } var username = logins[lkey].name; var gname = formdata["game"]; // If dims are not given or invalid, the constructor will handle it. var dims = [formdata["h"], formdata["w"]]; if (!(gname in games)) { sendError(res, 2, "No such game: " + gname); tslog("Request for nonexistant game \"%s\"", gname); return; } // A callback to pass to the game-in-progress checker. var launch = function(err, fname) { if (fname) { sendError(res, 4, null); tslog("%s is already playing %s", username, gname); return; } // Game starting has been approved. var respondlaunch = function(nclient, success) { if (success) { res.writeHead(200, {'Content-Type': 'application/json'}); var reply = {"t": "s", "id": nclient.id, "w": nclient.w, "h": nclient.h}; res.write(JSON.stringify(reply)); res.end(); } else { sendError(res, 5, "Failed to open TTY"); tslog("Unable to allocate TTY for %s", gname); } }; new Player(gname, lkey, dims, respondlaunch); }; checkprogress(username, games[gname], launch, []); } function watch(req, res, formdata) { if (!("n" in formdata)) { sendError(res, 2, "Game number not given"); return; } var gamenumber = Number(formdata["n"]); if (!(gamenumber in sessions)) { sendError(res, 7); return; } var session = sessions[gamenumber]; var watch = new Watcher(session); var reply = {"t": "w", "id": watch.id, "w": session.w, "h": session.h}; res.writeHead(200, {'Content-Type': 'application/json'}); res.write(JSON.stringify(reply)); res.end(); tslog("Game %d is being watched (key %s)", gamenumber, watch.id); } /* Sets things up for a new user, like dgamelaunch's commands[register] */ function regsetup(username) { function regsetup_l2(err) { for (var g in games) { fs.mkdir(path.join("/dgldir/ttyrec", username, games[g].uname), 0755); } } fs.mkdir(path.join("/dgldir/userdata", username), 0755); fs.mkdir(path.join("/dgldir/ttyrec/", username), 0755, regsetup_l2); } function register(req, res, formdata) { var uname, passwd, email; if (typeof (formdata.name) != "string" || formdata.name === "") { sendError(res, 2, "No name given."); return; } else uname = formdata["name"]; if (typeof (formdata.pw) != "string" || formdata.pw === "") { sendError(res, 2, "No password given."); return; } else passwd = formdata["pw"]; if (typeof (formdata.email) != "string" || formdata.email === "") { /* E-mail is optional */ email = "nobody@nowhere.not"; } else email = formdata["email"]; function checkreg(code, signal) { if (code === 0) { var lkey = randkey(2); while (lkey in logins) lkey = randkey(2); logins[lkey] = {"name": uname, "ts": new Date(), "sessions": []}; var reply = {"t": "r", "k": lkey, "u": uname}; res.writeHead(200, {'Content-Type': 'application/json'}); res.write(JSON.stringify(reply)); res.end(); tslog("Added new user: %s", uname); regsetup(uname); } else if (code == 4) { sendError(res, 2, "Invalid characters in name or email."); tslog("Attempted registration: %s %s", uname, email); } else if (code == 1) { sendError(res, 2, "Username " + uname + " is already being used."); tslog("Attempted duplicate registration: %s", uname); } else { sendError(res, 0, null); tslog("sqlickrypt register failed with code %d", code); } } var child_adder = child_process.spawn("/bin/sqlickrypt", ["register"]); child_adder.on("exit", checkreg); child_adder.stdin.end(uname + '\n' + passwd + '\n' + email + '\n', "utf8"); return; } /* Ends the game, obviously. Less obviously, stops watching the game if * the client is a Watcher instead of a Player. */ function endgame(client, res) { if (!client.alive) { sendError(res, 7, null, true); return; } client.quit(); // Give things some time to happen. if (client instanceof Player) setTimeout(readFeed, 200, client, res); return; } function findClient(formdata, playersOnly) { if (typeof(formdata) != "object") return null; if ("id" in formdata) { var id = formdata["id"]; if (id in clients && (!playersOnly || clients[id] instanceof Player)) { return clients[id]; } } return null; } function serveStatic(req, res, fname) { var nname = path.normalize(fname); if (nname == "" || nname == "/") nname = "index.html"; if (nname.match(/\/$/)) path.join(nname, "index.html"); /* it was a directory */ var realname = path.join(serveStaticRoot, nname); var extension = path.extname(realname); path.exists(realname, function (exists) { var resheaders = {}; if (!exists || !extension || extension == ".html") resheaders["Content-Type"] = "text/html; charset=utf-8"; else if (extension == ".png") resheaders["Content-Type"] = "image/png"; else if (extension == ".css") resheaders["Content-Type"] = "text/css"; else if (extension == ".js") resheaders["Content-Type"] = "text/javascript"; else if (extension == ".svg") resheaders["Content-Type"] = "image/svg+xml"; else resheaders["Content-Type"] = "application/octet-stream"; if (exists) { fs.readFile(realname, function (error, data) { if (error) { res.writeHead(500, {}); res.end(); } else { res.writeHead(200, resheaders); if (req.method != 'HEAD') res.write(data); res.end(); } }); } else { res.writeHead(404, resheaders); if (req.method != 'HEAD') { res.write("<html><head><title>" + nname + "</title></head>\n<body><h1>" + nname + " Not Found</h1></body></html>\n"); } res.end(); } }); return; } function readFeed(client, res) { if (!client) { sendError(res, 7, null, true); return; } var msgs = client.read(); if (!allowlogin && !msgs.length) { sendError(res, 6, null, true); return; } res.writeHead(200, { "Content-Type": "application/json" }); res.write(JSON.stringify(msgs)); res.end(); } function statusmsg(req, res) { var reply = {"s": allowlogin, "g": []}; for (var sessid in sessions) { var gamedesc = {}; gamedesc["n"] = sessid; gamedesc["p"] = sessions[sessid].pname; gamedesc["g"] = sessions[sessid].game.name; reply["g"].push(gamedesc); } res.writeHead(200, { "Content-Type": "application/json" }); if (req.method != 'HEAD') res.write(JSON.stringify(reply)); res.end(); } function pstatusmsg(req, res) { if (req.method == 'HEAD') { res.writeHead(200, { "Content-Type": "application/json" }); res.end(); return; } var target = url.parse(req.url).pathname; var pmatch = target.match(/^\/pstatus\/(.*)/); if (pmatch && pmatch[1]) var pname = pmatch[1]; else { sendError(res, 2, "No name given."); return; } var reply = {"name": pname}; playerstatus(pname, function (pdata) { reply["stat"] = pdata; res.writeHead(200, { "Content-Type": "application/json" }); res.write(JSON.stringify(reply)); res.end(); }); } var errorcodes = [ "Generic Error", "Not logged in", "Invalid data", "Login failed", "Already playing", "Game launch failed", "Server shutting down", "Game not in progress" ]; function sendError(res, ecode, msg, box) { res.writeHead(200, { "Content-Type": "application/json" }); var edict = {"t": "E"}; if (!(ecode < errorcodes.length && ecode > 0)) ecode = 0; edict["c"] = ecode; edict["s"] = errorcodes[ecode]; if (msg) edict["s"] += ": " + msg; if (box) res.write(JSON.stringify([edict])); else res.write(JSON.stringify(edict)); res.end(); } // TODO new-objects done to here function webHandler(req, res) { /* default headers for the response */ var resheaders = {'Content-Type': 'text/html'}; /* The request body will be added to this as it arrives. */ var reqbody = "";