Javascript: Writing a firefox extension with sockets
- by Johnny Grass
I need to write a firefox extension that creates a server socket (I think that's what it's called) and returns the browser's current url when a client application (running on the same computer) sends it a request. The thing is that I have no Java/Javascript background at all and I'm pressed for time so I am trying to hack something together from code samples. So far I've been mildly successful.
I've been working with code from this question which is used in the open source Firefox exension PolyChrome
I have the following code:
var reader = {
onInputStreamReady : function(input) {
var input_stream = Components.classes["@mozilla.org/scriptableinputstream;1"]
.createInstance(Components.interfaces.nsIScriptableInputStream);
input_stream.init(input);
input_stream.available();
var request = '';
while (input_stream.available()) {
request = request + input_stream.read(512);
}
var checkString = "foo"
if (request.toString() == checkString.toString()) {
output_console('URL: ' + content.location.href);
}
else
output_console("nothing");
var thread_manager = Components.classes["@mozilla.org/thread-manager;1"].getService();
input.asyncWait(reader,0,0,thread_manager.mainThread);
}
}
var listener = {
onSocketAccepted: function(serverSocket, clientSocket) {
output_console("Accepted connection on "+clientSocket.host+":"+clientSocket.port);
input = clientSocket.openInputStream(0, 0, 0).QueryInterface(Components.interfaces.nsIAsyncInputStream);
output = clientSocket.openOutputStream(Components.interfaces.nsITransport.OPEN_BLOCKING, 0, 0);
var thread_manager = Components.classes["@mozilla.org/thread-manager;1"].getService();
input.asyncWait(reader,0,0,thread_manager.mainThread);
}
}
var serverSocket = Components.classes["@mozilla.org/network/server-socket;1"].
createInstance(Components.interfaces.nsIServerSocket);
serverSocket.init(9999, true, 5);
output_console("Opened socket on " + serverSocket.port);
serverSocket.asyncListen(listener);
I have a few questions.
So far I can telnet into localhost and get a response, but my string comparison in the reader seems to fail even if I enter "foo". I don't get why. What am I missing?
The sample code I'm using opens up a console window and prints output when I telnet into localhost. Ideally I would like the output to be returned as a response when the client sends a request to the server socket with a passphrase. How do I go about doing that?
Is doing this a good idea? Does it create security vulnerabilities on the computer? How can I block connections to the socket from other computers?
What is a good place to read about javascript sockets? My google searches have been pretty fruitless but then maybe I'm not using the right keywords.