comparison webttyd.js @ 0:bd412f63ce0d

Put this project under version control, finally.
author John "Elwin" Edwards <elwin@sdf.org>
date Sun, 06 May 2012 08:45:40 -0700
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:bd412f63ce0d
1 #!/usr/bin/env node
2
3 // If you can't quite trust node to find it on its own
4 var localModules = '/usr/local/lib/node_modules/';
5 var http = require('http');
6 var url = require('url');
7 var path = require('path');
8 var fs = require('fs');
9 //var tty = require("tty");
10 var child_process = require('child_process');
11 var daemon = require(path.join(localModules, "daemon"));
12
13 var chrootDir = "/var/dgl/";
14 var dropToUID = 501;
15 var dropToGID = 501;
16 var serveStaticRoot = "/var/www/"; // inside the chroot
17 var passwdfile = "/dgldir/dgl-login";
18 var sessions = {};
19
20 var games = {
21 "rogue3": {
22 "name": "Rogue V3",
23 "uname": "rogue3",
24 "path": "/bin/rogue3"
25 },
26 "rogue4": {
27 "name": "Rogue V4",
28 "uname": "rogue4",
29 "path": "/bin/rogue4"
30 },
31 "rogue5": {
32 "name": "Rogue V5",
33 "uname": "rogue5",
34 "path": "/bin/rogue5"
35 },
36 "srogue": {
37 "name": "Super-Rogue",
38 "uname": "srogue",
39 "path": "/bin/srogue"
40 }
41 };
42
43 /* Constructor for TermSessions. Note that it opens the terminal and
44 * adds itself to the sessions dict. It currently assumes the user has
45 * been authenticated.
46 */
47 function TermSession(game, user, files) {
48 /* First make sure starting the game will work. */
49 if (!(game in games)) {
50 // TODO: throw an exception instead
51 return null;
52 }
53 /* This order seems to best avoid race conditions... */
54 this.alive = false;
55 this.sessid = randkey();
56 while (this.sessid in sessions) {
57 this.sessid = randkey();
58 }
59 /* Grab a spot in the sessions table. */
60 sessions[this.sessid] = this;
61 /* TODO handle tty-opening errors */
62 //var pterm = tty.open(games[game].path, ["-n", user.toString()]);
63 /* TODO make argument-finding into a method */
64 args = [games[game].path, "-n", user.toString()];
65 this.child = child_process.spawn("/bin/ptyhelper", args);
66 var ss = this;
67 //this.ptmx = pterm[0];
68 //this.child = pterm[1];
69 this.alive = true;
70 this.data = [];
71 this.lock = files[0];
72 fs.writeFile(this.lock, this.child.pid.toString() + '\n80\n24\n', "utf8");
73 this.record = fs.createWriteStream(files[1], { mode: 0664 });
74 /* END setup */
75 function ttyrec_chunk(buf) {
76 var ts = new Date();
77 var chunk = new Buffer(buf.length + 12);
78 /* TTYREC headers */
79 chunk.writeUInt32LE(Math.floor(ts.getTime() / 1000), 0);
80 chunk.writeUInt32LE(1000 * (ts.getTime() % 1000), 4);
81 chunk.writeUInt32LE(buf.length, 8);
82 buf.copy(chunk, 12);
83 ss.data.push(chunk);
84 ss.record.write(chunk);
85 }
86 this.child.stdout.on("data", ttyrec_chunk);
87 this.child.stderr.on("data", ttyrec_chunk);
88 this.child.on("exit", function (code, signal) {
89 ss.exitcode = (code != null ? code : 255);
90 ss.alive = false;
91 fs.unlink(ss.lock);
92 /* Wait for all the data to get collected */
93 setTimeout(ss.cleanup, 1000);
94 });
95 this.write = function (data) {
96 if (this.alive)
97 this.child.stdin.write(data);
98 /* Otherwise, throw some kind of exception? */
99 };
100 this.read = function () {
101 if (this.data.length == 0)
102 return null;
103 var pos = 0;
104 var i = 0;
105 for (i = 0; i < this.data.length; i++)
106 pos += this.data[i].length - 12;
107 var nbuf = new Buffer(pos);
108 var tptr;
109 pos = 0;
110 while (this.data.length > 0) {
111 tptr = this.data.shift();
112 tptr.copy(nbuf, pos, 12);
113 pos += tptr.length - 12;
114 }
115 return nbuf;
116 };
117 this.close = function () {
118 if (this.alive)
119 this.child.kill('SIGHUP');
120 };
121 this.cleanup = function () {
122 /* Call this when the child is dead. */
123 if (this.alive)
124 return;
125 //ss.ptmx.destroy();
126 ss.record.end();
127 /* Give the client a chance to read any leftover data. */
128 if (ss.data.length > 0)
129 setTimeout(ss.remove, 8000);
130 else
131 ss.remove();
132 };
133 this.remove = function () {
134 delete sessions[ss.sessid];
135 console.log("Session " + this.sessid + " removed.");
136 };
137 }
138
139 /* A few utility functions */
140 function timestamp() {
141 dd = new Date();
142 sd = dd.toISOString();
143 sd = sd.slice(0, sd.indexOf("."));
144 return sd.replace("T", ".");
145 }
146
147 function randkey() {
148 rnum = Math.floor(Math.random() * 65536 * 65536);
149 hexstr = rnum.toString(16);
150 while (hexstr.length < 8)
151 hexstr = "0" + hexstr;
152 return hexstr;
153 }
154
155 /* Returns a list of the cookies in the request, obviously. */
156 function getCookies(req) {
157 cookies = [];
158 if ("cookie" in req.headers) {
159 cookstrs = req.headers["cookie"].split("; ");
160 for (var i = 0; i < cookstrs.length; i++) {
161 eqsign = cookstrs[i].indexOf("=");
162 if (eqsign > 0) {
163 name = cookstrs[i].slice(0, eqsign).toLowerCase();
164 val = cookstrs[i].slice(eqsign + 1);
165 cookies[name] = val;
166 }
167 else if (eqsign < 0)
168 cookies[cookstrs[i]] = null;
169 }
170 }
171 return cookies;
172 }
173
174 function urlDec(encstr) {
175 var decstr = "";
176 var tnum;
177 for (var i = 0; i < encstr.length; i++)
178 {
179 if (encstr.charAt(i) == "+")
180 decstr += " ";
181 else if (encstr.charAt(i) == "%")
182 {
183 tnum = Number("0x" + encstr.slice(i + 1, 2));
184 if (!isNaN(tnum) && tnum >= 0)
185 decstr += String.fromCharCode(tnum);
186 i += 2;
187 }
188 else
189 decstr += encstr.charAt(i);
190 }
191 return decstr;
192 }
193
194 /* Returns the contents of a form */
195 function getFormValues(formtext) {
196 var pairstrs = formtext.split("&");
197 var data = {};
198 for (var i = 0; i < pairstrs.length; i++)
199 {
200 var eqsign = pairstrs[i].indexOf("=");
201 if (eqsign > 0) {
202 rawname = pairstrs[i].slice(0, eqsign);
203 rawval = pairstrs[i].slice(eqsign + 1);
204 name = urlDec(rawname);
205 val = urlDec(rawval);
206 if (!(name in data))
207 data[name] = [];
208 data[name].push(val);
209 }
210 }
211 return data;
212 }
213
214 function auth(username, password) {
215 // Real authentication not implemented
216 return true;
217 }
218
219 function login(req, res, formdata) {
220 if (!("game" in formdata)) {
221 sendError(res, 2, "No game specified.");
222 return;
223 }
224 else if (!("name" in formdata)) {
225 sendError(res, 2, "Username not given.");
226 return;
227 }
228 else if (!("pw" in formdata)) {
229 sendError(res, 2, "Password not given.");
230 return;
231 }
232 var username = formdata["name"][0];
233 var password = formdata["pw"][0];
234 var gname = formdata["game"][0];
235 if (!(gname in games)) {
236 sendError(res, 2, "No such game: " + gname);
237 console.log("Request for nonexistant game \"" + gname + "\"");
238 return;
239 }
240 var progressdir = "/dgldir/inprogress-" + games[gname].uname;
241
242 // This sets up the game once starting is approved.
243 function startgame() {
244 var ts = timestamp();
245 var lockfile = path.join(progressdir, username + ":node:" + ts + ".ttyrec");
246 var ttyrec = path.join("/dgldir/ttyrec", username, gname, ts + ".ttyrec");
247 var nsession = new TermSession(gname, username, [lockfile, ttyrec]);
248 if (nsession) {
249 /* Technically there's a race condition for the "lock"file, but since
250 * it requires the user deliberately starting two games at similar times,
251 * it's not too serious. We can't get O_EXCL in Node anyway. */
252 res.writeHead(200, {'Content-Type': 'text/plain'});
253 res.write("l1\n" + nsession.sessid + "\n");
254 res.end();
255 console.log("%s playing %s (key %s, pid %d)", username, gname,
256 nsession.sessid, nsession.child.pid);
257 }
258 else {
259 sendError(res, 5, "Failed to open TTY");
260 console.log("Unable to allocate TTY for " + gname);
261 }
262 }
263 function checkit(code, signal) {
264 // check the password
265 if (code != 0) {
266 sendError(res, 3);
267 console.log("Password check failed for user " + username);
268 return;
269 }
270 // check for an existing game
271 fs.readdir(progressdir, function(err, files) {
272 if (!err) {
273 var fre = RegExp("^" + username + ":");
274 for (var i = 0; i < files.length; i++) {
275 if (files[i].match(fre)) {
276 sendError(res, 4, null);
277 return;
278 }
279 }
280 }
281 // If progressdir isn't readable, start a new game anyway.
282 startgame();
283 });
284 }
285 /* Look for the user in the password file */
286 fs.readFile(passwdfile, "utf8", function(err, data) {
287 if (err) {
288 sendError(res, 3);
289 console.log("Can't authenticate: " + err.toString());
290 return;
291 }
292 var dlines = data.split('\n');
293 for (var n = 0; n < dlines.length; n++) {
294 var fields = dlines[n].split(':');
295 if (fields[0] == username) {
296 // check the password with the quickrypt utility
297 checker = require('child_process').spawn("/bin/quickrypt")
298 checker.on("exit", checkit);
299 checker.stdin.end(password + '\n' + fields[2] + '\n', "utf8");
300 return;
301 }
302 }
303 sendError(res, 3);
304 console.log("Attempted login by nonexistent user " + username);
305 });
306 return;
307 }
308
309 function logout(term, res) {
310 if (!term.alive) {
311 sendError(res, 1, null);
312 return;
313 }
314 cterm.close();
315 var resheaders = {'Content-Type': 'text/plain'};
316 res.writeHead(200, resheaders);
317 res.write("q1\n\n");
318 res.end();
319 return;
320 }
321
322 function findTermSession(formdata) {
323 if ("id" in formdata) {
324 var sessid = formdata["id"][0];
325 if (sessid in sessions) {
326 return sessions[sessid];
327 }
328 }
329 return null;
330 }
331
332 function serveStatic(req, res, fname) {
333 var nname = path.normalize(fname);
334 if (nname == "" || nname == "/")
335 nname = "index.html";
336 if (nname.match(/\/$/))
337 path.join(nname, "index.html"); /* it was a directory */
338 var realname = path.join(serveStaticRoot, nname);
339 var extension = path.extname(realname);
340 path.exists(realname, function (exists) {
341 var resheaders = {};
342 if (!exists || !extension || extension == ".html")
343 resheaders["Content-Type"] = "text/html";
344 else if (extension == ".png")
345 resheaders["Content-Type"] = "image/png";
346 else if (extension == ".css")
347 resheaders["Content-Type"] = "text/css";
348 else if (extension == ".js")
349 resheaders["Content-Type"] = "text/javascript";
350 else if (extension == ".svg")
351 resheaders["Content-Type"] = "image/svg+xml";
352 else
353 resheaders["Content-Type"] = "application/octet-stream";
354 if (exists) {
355 fs.readFile(realname, function (error, data) {
356 if (error) {
357 res.writeHead(500, {});
358 res.end();
359 }
360 else {
361 res.writeHead(200, resheaders);
362 res.write(data);
363 res.end();
364 }
365 });
366 }
367 else {
368 res.writeHead(404, resheaders);
369 res.write("<html><head><title>" + nname + "</title></head>\n<body><h1>" + nname + " Not Found</h1></body></html>\n");
370 res.end();
371 }
372 });
373 return;
374 }
375
376 function readFeed(res, term) {
377 if (term) {
378 var result = term.read();
379 res.writeHead(200, { "Content-Type": "text/plain" });
380 if (result == null)
381 resultstr = "";
382 else
383 resultstr = result.toString("hex");
384 if (result == null && !term.alive) {
385 /* Child has terminated and data is flushed. */
386 res.write("q1\n\n");
387 }
388 else
389 res.write("d" + resultstr.length.toString() + "\n" + resultstr + "\n");
390 res.end();
391 }
392 else {
393 //console.log("Where's the term?");
394 sendError(res, 1, null);
395 }
396 }
397
398 var errorcodes = [ "Generic Error", "Not logged in", "Invalid data",
399 "Login failed", "Already playing", "Game launch failed" ];
400
401 function sendError(res, ecode, msg) {
402 res.writeHead(200, { "Content-Type": "text/plain" });
403 if (ecode < errorcodes.length && ecode > 0) {
404 var emsg = errorcodes[ecode];
405 if (msg)
406 emsg += ": " + msg;
407 res.write("E" + ecode + '\n' + emsg + '\n');
408 }
409 else
410 res.write("E0\nGeneric Error\n");
411 res.end();
412 }
413
414 function handler(req, res) {
415 /* default headers for the response */
416 var resheaders = {'Content-Type': 'text/html'};
417 /* The request body will be added to this as it arrives. */
418 var reqbody = "";
419 var formdata;
420
421 /* Register a listener to get the body. */
422 function moredata(chunk) {
423 reqbody += chunk;
424 }
425 req.on('data', moredata);
426
427 /* This will send the response once the whole request is here. */
428 function respond() {
429 formdata = getFormValues(reqbody);
430 var target = url.parse(req.url).pathname;
431 var cterm = findTermSession(formdata);
432 /* First figure out if the client is POSTing to a command interface. */
433 if (req.method == 'POST') {
434 if (target == '/feed') {
435 if (!cterm) {
436 sendError(res, 1, null);
437 return;
438 }
439 if ("quit" in formdata) {
440 /* The client wants to terminate the process. */
441 logout(cterm, res);
442 }
443 else if (formdata["keys"]) {
444 /* process the keys */
445 hexstr = formdata["keys"][0].replace(/[^0-9a-f]/gi, "");
446 if (hexstr.length % 2 != 0) {
447 sendError(res, 2, "incomplete byte");
448 return;
449 }
450 keybuf = new Buffer(hexstr, "hex");
451 cterm.write(keybuf);
452 }
453 readFeed(res, cterm);
454 }
455 else if (target == "/login") {
456 login(req, res, formdata);
457 }
458 else {
459 res.writeHead(405, resheaders);
460 res.end();
461 }
462 }
463 else if (req.method == 'GET' || req.method == 'HEAD') {
464 if (target == '/feed') {
465 if (!cterm) {
466 sendError(res, 1, null);
467 return;
468 }
469 readFeed(res, cterm);
470 }
471 /* Default page, create a new term */
472 /* FIXME New term not created anymore, is a special case still needed? */
473 else if (target == '/') {
474 serveStatic(req, res, "/");
475 }
476 else /* Go look for it in the filesystem */
477 serveStatic(req, res, target);
478 }
479 else { /* Some other method */
480 res.writeHead(501, resheaders);
481 res.write("<html><head><title>501</title></head>\n<body><h1>501 Not Implemented</h1></body></html>\n");
482 res.end();
483 }
484 return;
485 }
486 req.on('end', respond);
487
488 }
489
490 process.on("exit", function () {
491 for (var sessid in sessions) {
492 if (sessions[sessid].alive)
493 sessions[sessid].child.kill('SIGHUP');
494 }
495 console.log("Quitting...");
496 return;
497 });
498
499 /* Initialization STARTS HERE */
500 process.env["TERM"] = "xterm-256color";
501
502 if (process.getuid() != 0) {
503 console.log("Not running as root, cannot chroot.");
504 process.exit(1);
505 }
506 try {
507 process.chdir(chrootDir);
508 }
509 catch (err) {
510 console.log("Cannot enter " + chrootDir + " : " + err);
511 process.exit(1);
512 }
513 try {
514 daemon.chroot(chrootDir);
515 }
516 catch (err) {
517 console.log("chroot to " + chrootDir + " failed: " + err);
518 process.exit(1);
519 }
520 try {
521 // drop gid first, that requires UID=0
522 process.setgid(dropToGID);
523 process.setuid(dropToUID);
524 }
525 catch (err) {
526 console.log("Could not drop permissions: " + err);
527 process.exit(1);
528 }
529
530 http.createServer(handler).listen(8080, "127.0.0.1");
531 console.log('webttyd running at http://127.0.0.1:8080/');