Created
March 29, 2012 11:22
-
-
Save amitu/2236069 to your computer and use it in GitHub Desktop.
dtrace based blocking http api to map local port to uid
This file contains hidden or 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'); | |
var spawn = require('child_process').spawn; | |
var dtrace = spawn("dtrace", ["-s", "dtrace.d", "-C"]); | |
var known_ports = {}; | |
var pending_requests = {}; | |
dtrace.stdout.on("data", function(data){ | |
var lines = data.toString().split("\n"); | |
for (i in lines) { | |
line = lines[i]; | |
if (line === "") continue; | |
var parts = line.split(" "); | |
if (parts.length < 5) continue; | |
var uid = parts[parts.length-4]; | |
var port = parts[parts.length-3]; | |
console.log("uid", uid, port); | |
known_ports[port] = uid; | |
if (pending_requests[port] !== undefined) { | |
res.end(uid); | |
delete pending_requests[port]; | |
console.log("returned port to pending request"); | |
} | |
}; | |
}); | |
dtrace.stderr.on("data", function(data){ | |
console.log("got error: ", data.toString()); | |
}); | |
dtrace.on("exit", function(data){ | |
console.log("got exit: ", data); | |
}); | |
http.createServer(function (req, res) { | |
var port = req.url.substr(1); | |
console.log("requested port", port); | |
res.writeHead(200, {'Content-Type': 'text/plain'}); | |
if (known_ports[port] !== undefined) { | |
res.end(known_ports[port]); | |
console.log("port is already known"); | |
// delete known_ports[port]; | |
} else { | |
pending_requests[port] = res; | |
console.log("port is not known, queing request"); | |
setTimeout(function(){ | |
delete pending_requests[port]; | |
res.end("not found"); | |
console.log("timing out"); | |
}, 1000) | |
} | |
}).listen(1337, '127.0.0.1'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment