IRC via SSH tunnel

So maybe you have wondered how it's possible that there's, at the time of writing, 37 people logged on to the IRC server at tilde.town, but when you type in "who", you only see 12 unique users logged on.

How do these people connect to the IRC server? When you start up an irc client on your home computer and try to connect to "irc.tilde.town", this doesn't work. You have to connect from the server itself. Very mysterious.

The answer is an SSH tunnel. You're already using SSH to log into tilde.town remotely. You can use the same tool to create a "tunnel" from your machine to tilde.town. Any connection that you make through that tunnel will look like a local connection to the IRC server.

So if you're on a mac like me, all you have to do is use SSH with a couple of options: "-N" to tell SSH that you don't want to run a command, and "-L localhost:6667:localhost:6667" to create a tunnel from port 6667 on your machine to port 6667 on tilde.town.

Now, with the command line, laziness is a virtue. "ssh -N nick@tilde.town -L localhost:6667:localhost:6667" is a lot of typing, and nobody wants to remember all of that. Secondly, it only creates the tunnel: you then also have to launch the IRC client. Finally: when you type this into a terminal, you don't get a prompt back while the SSH tunnel is running. So what we want to do is run the tunnel in the background. But then we also have to remember the process ID, so that we can later kill it again. That's way too many steps to do by hand every time. We need a script!

Here's our startup script:

#!/bin/bash
ssh -N tilde.town -L localhost:6667:localhost:6667 &
echo $! > ssh_pid
open /Applications/Colloquy.app
	

The ampersand after the ssh command launches the process into the background. Then we write the process ID to a file, so that we can retrieve it later. Finally (this is a Mac-specific command), we open the IRC client, in this case Colloquy.

Here's how we shut the tunnel down again:

#!/bin/bash
if [ -e ssh_pid ] 
then
	kill `cat ssh_pid`
	rm ssh_pid
fi

If the ssh_pid file exists, we kill the process with that pid (which closes the ssh tunnel) and then delete the file.

So now we only have to call the first script to start up the SSH tunnel, and the second one to close it again. Easy!