3 irkerd - a simple IRC multiplexer daemon
5 Listens for JSON objects of the form {'to':<irc-url>, 'privmsg':<text>}
6 and relays messages to IRC channels. Each request must be followed by
9 The <text> must be a string. The value of the 'to' attribute can be a
10 string containing an IRC URL (e.g. 'irc://chat.freenet.net/botwar') or
11 a list of such strings; in the latter case the message is broadcast to
12 all listed channels. Note that the channel portion of the URL need
13 *not* have a leading '#' unless the channel name itself does.
15 Options: -d sets the debug-message level (probably only of interest to
16 developers). The -V option prints the program version and exits.
18 Design and code by Eric S. Raymond <esr@thyrsus.com>. See the project
19 resource page at <http://www.catb.org/~esr/irker/>.
21 Requires Python 2.6 or 2.5 with the simplejson library installed, and
22 the irc client library at version >= 3.2: see
24 http://pypi.python.org/pypi/irc/
26 # These things might need tuning
31 NAMESTYLE = "irker%03d" # IRC nick template - must contain '%d'
32 XMIT_TTL = (3 * 60 * 60) # Time to live, seconds from last transmit
33 PING_TTL = (15 * 60) # Time to live, seconds from last PING
34 HANDSHAKE_TTL = 60 # Time to live, seconds from nick transmit
35 CHANNEL_TTL = (3 * 60 * 60) # Time to live, seconds from last transmit
36 DISCONNECT_TTL = (24 * 60 * 60) # Time to live, seconds from last connect
37 UNSEEN_TTL = 60 # Time to live, seconds since first request
38 CHANNEL_MAX = 18 # Max channels open per socket (default)
39 ANTI_FLOOD_DELAY = 0.5 # Anti-flood delay after transmissions, seconds
40 ANTI_BUZZ_DELAY = 0.09 # Anti-buzz delay after queue-empty check
41 CONNECTION_MAX = 200 # To avoid hitting a thread limit
43 # No user-serviceable parts below this line
47 import sys, getopt, urlparse, time, random, socket, signal
48 import threading, Queue, SocketServer
49 import irc.client, logging
51 import simplejson as json # Faster, also makes us Python-2.4-compatible
55 # Sketch of implementation:
57 # One Irker object manages multiple IRC sessions. It holds a map of
58 # Dispatcher objects, one per (server, port) combination, which are
59 # responsible for routing messages to one of any number of Connection
60 # objects that do the actual socket conversations. The reason for the
61 # Dispatcher layer is that IRC daemons limit the number of channels a
62 # client (that is, from the daemon's point of view, a socket) can be
63 # joined to, so each session to a server needs a flock of Connection
64 # instances each with its own socket.
66 # Connections are timed out and removed when either they haven't seen a
67 # PING for a while (indicating that the server may be stalled or down)
68 # or there has been no message traffic to them for a while, or
69 # even if the queue is nonempty but efforts to connect have failed for
72 # There are multiple threads. One accepts incoming traffic from all
73 # servers. Each Connection also has a consumer thread and a
74 # thread-safe message queue. The program main appends messages to
75 # queues as JSON requests are received; the consumer threads try to
76 # ship them to servers. When a socket write stalls, it only blocks an
77 # individual consumer thread; if it stalls long enough, the session
78 # will be timed out. This solves the biggest problem with a
79 # single-threaded implementation, which is that you can't count on a
80 # single stalled write not hanging all other traffic - you're at the
81 # mercy of the length of the buffers in the TCP/IP layer.
83 # Message delivery is thus not reliable in the face of network stalls,
84 # but this was considered acceptable because IRC (notoriously) has the
85 # same problem - there is little point in reliable delivery to a relay
86 # that is down or unreliable.
88 # This code uses only NICK, JOIN, PART, MODE, and PRIVMSG. It is strictly
89 # compliant to RFC1459, except for the interpretation and use of the
90 # DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features. CHANLIMIT
91 # is as described in the Internet RFC draft
92 # draft-brocklesby-irc-isupport-03 at <http://www.mirc.com/isupport.html>.
93 # The ",isnick" feature is as described in
94 # <http://ftp.ics.uci.edu/pub/ietf/uri/draft-mirashi-url-irc-01.txt>.
97 def __init__(self, irkerd, servername, port):
99 self.servername = servername
101 self.nick_trial = None
102 self.connection = None
104 self.last_xmit = time.time()
105 self.last_ping = time.time()
106 self.channels_joined = {}
107 self.channel_limits = {}
108 # The consumer thread
109 self.queue = Queue.Queue()
111 def nickname(self, n=None):
112 "Return a name for the nth server connection."
115 return (NAMESTYLE % n)
116 def handle_ping(self):
117 "Register the fact that the server has pinged this connection."
118 self.last_ping = time.time()
119 def handle_welcome(self):
120 "The server says we're OK, with a non-conflicting nick."
121 self.status = "ready"
122 self.irker.debug(1, "nick %s accepted" % self.nickname())
123 def handle_badnick(self):
124 "The server says our nick has a conflict."
125 self.irker.debug(1, "nick %s rejected" % self.nickname())
126 # Randomness prevents a malicious user or bot from antcipating the
127 # next trial name in order to block us from completing the handshake.
128 self.nick_trial += random.randint(1, 3)
129 self.last_xmit = time.time()
130 self.connection.nick(self.nickname())
131 def handle_disconnect(self):
132 "Server disconnected us for flooding or some other reason."
133 self.connection = None
134 self.status = "disconnected"
135 def handle_kick(self, outof):
137 self.status = "handshaking"
139 del self.channels_joined[outof]
141 self.irker.logerr("kicked by %s from %s that's not joined"
142 % (self.servername, outof))
144 while not self.queue.empty():
145 (channel, message) = self.queue.get()
147 qcopy.append((channel, message))
148 for (channel, message) in qcopy:
149 self.queue.put((channel, message))
150 self.status = "ready"
151 def enqueue(self, channel, message):
152 "Enque a message for transmission."
153 if self.thread is None or not self.thread.is_alive():
154 self.status = "unseen"
155 self.thread = threading.Thread(target=self.dequeue)
156 self.thread.setDaemon(True)
158 self.queue.put((channel, message))
160 "Try to ship pending messages from the queue."
163 # We want to be kind to the IRC servers and not hold unused
164 # sockets open forever, so they have a time-to-live. The
165 # loop is coded this particular way so that we can drop
166 # the actual server connection when its time-to-live
167 # expires, then reconnect and resume transmission if the
168 # queue fills up again.
169 if self.queue.empty():
170 # Queue is empty, at some point we want to time out
171 # the connection rather than holding a socket open in
172 # the server forever.
174 xmit_timeout = now > self.last_xmit + XMIT_TTL
175 ping_timeout = now > self.last_ping + PING_TTL
176 if self.status == "disconnected":
177 # If the queue is empty, we can drop this connection.
178 self.status = "expired"
180 elif xmit_timeout or ping_timeout:
181 self.irker.debug(1, "timing out connection to %s at %s (ping_timeout=%s, xmit_timeout=%s)" % (self.servername, time.asctime(), ping_timeout, xmit_timeout))
182 with self.irker.irc.mutex:
183 self.connection.context = None
184 self.connection.quit("transmission timeout")
185 self.connection = None
186 self.status = "disconnected"
188 # Prevent this thread from hogging the CPU by pausing
189 # for just a little bit after the queue-empty check.
190 # As long as this is less that the duration of a human
191 # reflex arc it is highly unlikely any human will ever
193 time.sleep(ANTI_BUZZ_DELAY)
194 elif self.status == "disconnected" \
195 and time.time() > self.last_xmit + DISCONNECT_TTL:
196 # Queue is nonempty, but the IRC server might be
197 # down. Letting failed connections retain queue
198 # space forever would be a memory leak.
199 self.status = "expired"
201 elif not self.connection:
202 # Queue is nonempty but server isn't connected.
203 with self.irker.irc.mutex:
204 self.connection = self.irker.irc.server()
205 self.connection.context = self
206 # Try to avoid colliding with other instances
207 self.nick_trial = random.randint(1, 990)
208 self.channels_joined = {}
211 # irc.client.ServerConnectionError on failure
212 self.connection.connect(self.servername,
214 nickname=self.nickname(),
216 ircname="irker relaying client")
217 self.status = "handshaking"
218 self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
219 self.last_xmit = time.time()
220 self.last_ping = time.time()
221 except irc.client.ServerConnectionError:
222 self.status = "disconnected"
223 elif self.status == "handshaking":
224 if time.time() > self.last_xmit + HANDSHAKE_TTL:
225 self.status = "expired"
228 # Don't buzz on the empty-queue test while we're
230 time.sleep(ANTI_BUZZ_DELAY)
231 elif self.status == "unseen" \
232 and time.time() > self.last_xmit + UNSEEN_TTL:
233 # Nasty people could attempt a denial-of-service
234 # attack by flooding us with requests with invalid
235 # servernames. We guard against this by rapidly
236 # expiring connections that have a nonempty queue but
237 # have never had a successful open.
238 self.status = "expired"
240 elif self.status == "ready":
241 with self.irker.irc.mutex:
242 (channel, message) = self.queue.get()
243 if channel not in self.channels_joined:
244 self.connection.join(channel)
245 self.irker.debug(1, "joining %s on %s." % (channel, self.servername))
246 for segment in message.split("\n"):
247 self.connection.privmsg(channel, segment)
248 time.sleep(ANTI_FLOOD_DELAY)
249 self.last_xmit = self.channels_joined[channel] = time.time()
250 self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
251 self.queue.task_done()
253 (exc_type, _exc_value, exc_traceback) = sys.exc_info()
254 self.irker.logerr("exception %s in thread for %s" % \
255 (exc_type, self.servername))
256 # This is so we can see tracebacks for errors inside the thread
257 # when we need to be able to for debugging purposes.
259 raise exc_type, _exc_value, exc_traceback
261 "Should this connection not be scavenged?"
262 return self.status != "expired"
263 def joined_to(self, channel):
264 "Is this connection joined to the specified channel?"
265 return channel in self.channels_joined
266 def accepting(self, channel):
267 "Can this connection accept a join of this channel?"
268 if self.channel_limits:
270 for already in self.channels_joined:
271 # This obscure code is because the RFCs allow separate limits
272 # by channel type (indicated by the first character of the name)
273 # a feature that is almost never actually used.
274 if already[0] == channel[0]:
276 return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
278 return len(self.channels_joined) < CHANNEL_MAX
281 "Represent a transmission target."
282 def __init__(self, url):
283 parsed = urlparse.urlparse(url)
284 irchost, _, ircport = parsed.netloc.partition(':')
287 self.servername = irchost
288 # IRC channel names are case-insensitive. If we don't smash
289 # case here we may run into problems later. There was a bug
290 # observed on irc.rizon.net where an irkerd user specified #Channel,
291 # got kicked, and irkerd crashed because the server returned
292 # "#channel" in the notification that our kick handler saw.
293 self.channel = parsed.path.lstrip('/').lower()
294 isnick = self.channel.endswith(",isnick")
296 self.channel = self.channel[:-7]
297 if self.channel and not isnick and self.channel[0] not in "#&+":
298 self.channel = "#" + self.channel
299 self.port = int(ircport)
301 "Both components must be present for a valid target."
302 return self.servername and self.channel
304 "Return a hashable tuple representing the destination server."
305 return (self.servername, self.port)
308 "Manage connections to a particular server-port combination."
309 def __init__(self, irkerd, servername, port):
311 self.servername = servername
313 self.connections = []
314 def dispatch(self, channel, message):
315 "Dispatch messages for our server-port combination."
316 # First, check if there is room for another channel
317 # on any of our existing connections.
318 connections = [x for x in self.connections if x.live()]
319 eligibles = [x for x in connections if x.joined_to(channel)] \
320 or [x for x in connections if x.accepting(channel)]
322 eligibles[0].enqueue(channel, message)
324 # All connections are full up. Look for one old enough to be
327 for connection in connections:
328 for (chan, age) in connections.channels_joined.items():
329 if age < time.time() - CHANNEL_TTL:
330 ancients.append((connection, chan, age))
332 ancients.sort(key=lambda x: x[2])
333 (found_connection, drop_channel, _drop_age) = ancients[0]
334 found_connection.part(drop_channel, "scavenged by irkerd")
335 del found_connection.channels_joined[drop_channel]
336 #time.sleep(ANTI_FLOOD_DELAY)
337 found_connection.enqueue(channel, message)
339 # Didn't find any channels with no recent activity
340 newconn = Connection(self.irker,
343 self.connections.append(newconn)
344 newconn.enqueue(channel, message)
346 "Does this server-port combination have any live connections?"
347 self.connections = [x for x in self.connections if x.live()]
348 return len(self.connections) > 0
350 "Return the time of the most recent transmission."
351 return max(x.last_xmit for x in self.connections)
354 "Persistent IRC multiplexer."
355 def __init__(self, debuglevel=0):
356 self.debuglevel = debuglevel
357 self.irc = irc.client.IRC()
358 self.irc.add_global_handler("ping", self._handle_ping)
359 self.irc.add_global_handler("welcome", self._handle_welcome)
360 self.irc.add_global_handler("erroneusnickname", self._handle_badnick)
361 self.irc.add_global_handler("nicknameinuse", self._handle_badnick)
362 self.irc.add_global_handler("nickcollision", self._handle_badnick)
363 self.irc.add_global_handler("unavailresource", self._handle_badnick)
364 self.irc.add_global_handler("featurelist", self._handle_features)
365 self.irc.add_global_handler("disconnect", self._handle_disconnect)
366 self.irc.add_global_handler("kick", self._handle_kick)
367 thread = threading.Thread(target=self.irc.process_forever)
368 thread.setDaemon(True)
369 self.irc._thread = thread
372 def logerr(self, errmsg):
373 "Log a processing error."
374 sys.stderr.write("irkerd: " + errmsg + "\n")
375 def debug(self, level, errmsg):
376 "Debugging information."
377 if self.debuglevel >= level:
378 sys.stderr.write("irkerd: %s\n" % errmsg)
379 def _handle_ping(self, connection, _event):
380 "PING arrived, bump the last-received time for the connection."
381 if connection.context:
382 connection.context.handle_ping()
383 def _handle_welcome(self, connection, _event):
384 "Welcome arrived, nick accepted for this connection."
385 if connection.context:
386 connection.context.handle_welcome()
387 def _handle_badnick(self, connection, _event):
388 "Nick not accepted for this connection."
389 if connection.context:
390 connection.context.handle_badnick()
391 def _handle_features(self, connection, event):
392 "Determine if and how we can set deaf mode."
393 if connection.context:
394 cxt = connection.context
395 for lump in event.arguments():
396 if lump.startswith("DEAF="):
397 connection.mode(cxt.nickname(), "+"+lump[5:])
398 elif lump.startswith("MAXCHANNELS="):
401 cxt.channel_limits[pref] = m
402 self.debug(1, "%s maxchannels is %d"
403 % (connection.server, m))
404 elif lump.startswith("CHANLIMIT=#:"):
405 limits = lump[10:].split(",")
408 (prefixes, limit) = token.split(":")
411 cxt.channel_limits[c] = limit
412 self.debug(1, "%s channel limit map is %s"
413 % (connection.server, cxt.channel_limits))
415 self.logerr("ill-formed CHANLIMIT property")
416 def _handle_disconnect(self, connection, _event):
417 "Server hung up the connection."
418 self.debug(1, "server %s disconnected" % connection.server)
420 if connection.context:
421 connection.context.handle_disconnect()
422 def _handle_kick(self, connection, event):
423 "Server hung up the connection."
424 self.debug(1, "irker has been kicked from %s on %s" % (event.target(), connection.server))
425 if connection.context:
426 connection.context.handle_kick(event.target())
427 def handle(self, line):
428 "Perform a JSON relay request."
430 request = json.loads(line.strip())
431 if not isinstance(request, dict):
432 self.logerr("request is not a JSON dictionary: %r" % request)
433 elif "to" not in request or "privmsg" not in request:
434 self.logerr("malformed request - 'to' or 'privmsg' missing: %r" % request)
436 channels = request['to']
437 message = request['privmsg']
438 if not isinstance(channels, (list, basestring)):
439 self.logerr("malformed request - unexpected channel type: %r" % channels)
440 if not isinstance(message, basestring):
441 self.logerr("malformed request - unexpected message type: %r" % message)
443 if not isinstance(channels, list):
444 channels = [channels]
446 if not isinstance(url, basestring):
447 self.logerr("malformed request - URL has unexpected type: %r" % url)
450 if not target.valid():
452 if target.server() not in self.servers:
453 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
454 self.servers[target.server()].dispatch(target.channel, message)
455 # GC dispatchers with no active connections
456 servernames = self.servers.keys()
457 for servername in servernames:
458 if not self.servers[servername].live():
459 del self.servers[servername]
460 # If we might be pushing a resource limit
461 # even after garbage collection, remove a
462 # session. The goal here is to head off
463 # DoS attacks that aim at exhausting
464 # thread space or file descriptors. The
465 # cost is that attempts to DoS this
466 # service will cause lots of join/leave
467 # spam as we scavenge old channels after
468 # connecting to new ones. The particular
469 # method used for selecting a session to
470 # be terminated doesn't matter much; we
471 # choose the one longest idle on the
472 # assumption that message activity is likely
474 if len(self.servers) >= CONNECTION_MAX:
475 oldest = min(self.servers.keys(), key=lambda name: self.servers[name].last_xmit())
476 del self.servers[oldest]
478 self.logerr("can't recognize JSON on input: %r" % line)
480 self.logerr("wildly malformed JSON blew the parser stack.")
482 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
485 line = self.rfile.readline()
488 irker.handle(line.strip())
490 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
492 data = self.request[0].strip()
493 #socket = self.request[1]
496 if __name__ == '__main__':
498 (options, arguments) = getopt.getopt(sys.argv[1:], "d:V")
499 for (opt, val) in options:
500 if opt == '-d': # Enable debug/progress messages
503 logging.basicConfig(level=logging.DEBUG)
504 elif opt == '-V': # Emit version and exit
505 sys.stdout.write("irkerd version %s\n" % version)
507 irker = Irker(debuglevel=debuglvl)
508 irker.debug(1, "irkerd version %s" % version)
510 tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
511 udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
512 for server in [tcpserver, udpserver]:
513 server = threading.Thread(target=server.serve_forever)
514 server.setDaemon(True)
518 except KeyboardInterrupt:
520 except socket.error, e:
521 sys.stderr.write("irkerd: server launch failed: %r\n" % e)