Created
January 27, 2012 19:23
-
-
Save isaacs/1690458 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require("http") | |
// messages should be relatively short. | |
var maxLength = 1024 | |
var server = http.createServer(function (req, res) { | |
// requests come in as json | |
// need to parse the json to get from, to, and body fields. | |
// JSON is probably generated by some native C JSON encoder | |
// on a device, or in some other language, or perhaps from | |
// another node program (in which case, it'll already be broken). | |
var chunks = [] | |
var msgLen = 0 | |
req.on("data", onData) | |
req.on("end", onEnd) | |
function onData (chunk) { | |
chunks.push(chunk) | |
msgLen += chunk.length | |
if (msgLen > maxLength) { | |
// DoS protection. | |
res.writeHead(413, {"content-type":"application/json"}) | |
res.end(JSON.stringify({ok: false, error: "Request entity too large"})) | |
req.removeListener("data", onData) | |
req.removeListener("end", onEnd) | |
} | |
} | |
function onEnd () { | |
var message | |
switch (chunks.length) { | |
case 0: message = new Buffer(0); break | |
case 1: message = chunks[0]; break | |
default: | |
message = new Buffer(msgLen) | |
var i = 0 | |
chunks.forEach(function (c) { | |
c.copy(message, i) | |
i += c.length | |
}) | |
break | |
} | |
// so, now message is the full message | |
// it's a buffer, but we need to interpret it as JSON | |
// this is where the Bad Thing happens. | |
// if there were any characters outside the 2-byte plane, | |
// then they're going to now get turned into 2 garbage characters. | |
try { | |
message = JSON.decode(message.toString("utf8")) | |
} catch (ex) { | |
console.error(ex) | |
res.writeHead(400, {"content-type":"application/json"}) | |
res.end(JSON.stringify({ok:false, error:"Bad JSON"})) | |
return | |
} | |
// in real life, this console.error would be replaced with | |
// some nifty routing message passing thingie | |
console.error("From: %s\nTo: %s\n\n%s", | |
message.from, message.to, message.body); | |
res.writeHead(200, {"content-type": "application/json"}) | |
res.end(JSON.stringify({ok: true})) | |
}) | |
}) | |
server.listen(1337) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment