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). -l sets a logfile to capture message traffic from
17 channels. -n sets the nick and -p the nickserv password. The -V
18 option prints the program version and exits.
20 Design and code by Eric S. Raymond <esr@thyrsus.com>. See the project
21 resource page at <http://www.catb.org/~esr/irker/>.
23 Requires Python 2.6 or 2.5 with the simplejson library installed, and
24 the irc client library at version >= 3.4 which requires 2.6: see
26 http://pypi.python.org/pypi/irc/
28 from __future__ import with_statement
30 # These things might need tuning
35 XMIT_TTL = (3 * 60 * 60) # Time to live, seconds from last transmit
36 PING_TTL = (15 * 60) # Time to live, seconds from last PING
37 HANDSHAKE_TTL = 60 # Time to live, seconds from nick transmit
38 CHANNEL_TTL = (3 * 60 * 60) # Time to live, seconds from last transmit
39 DISCONNECT_TTL = (24 * 60 * 60) # Time to live, seconds from last connect
40 UNSEEN_TTL = 60 # Time to live, seconds since first request
41 CHANNEL_MAX = 18 # Max channels open per socket (default)
42 ANTI_FLOOD_DELAY = 1.0 # Anti-flood delay after transmissions, seconds
43 ANTI_BUZZ_DELAY = 0.09 # Anti-buzz delay after queue-empty check
44 CONNECTION_MAX = 200 # To avoid hitting a thread limit
46 # No user-serviceable parts below this line
50 import sys, getopt, urlparse, time, random, socket, signal, re
51 import threading, Queue, SocketServer
52 import irc.client, logging
54 import simplejson as json # Faster, also makes us Python-2.4-compatible
58 # Sketch of implementation:
60 # One Irker object manages multiple IRC sessions. It holds a map of
61 # Dispatcher objects, one per (server, port) combination, which are
62 # responsible for routing messages to one of any number of Connection
63 # objects that do the actual socket conversations. The reason for the
64 # Dispatcher layer is that IRC daemons limit the number of channels a
65 # client (that is, from the daemon's point of view, a socket) can be
66 # joined to, so each session to a server needs a flock of Connection
67 # instances each with its own socket.
69 # Connections are timed out and removed when either they haven't seen a
70 # PING for a while (indicating that the server may be stalled or down)
71 # or there has been no message traffic to them for a while, or
72 # even if the queue is nonempty but efforts to connect have failed for
75 # There are multiple threads. One accepts incoming traffic from all
76 # servers. Each Connection also has a consumer thread and a
77 # thread-safe message queue. The program main appends messages to
78 # queues as JSON requests are received; the consumer threads try to
79 # ship them to servers. When a socket write stalls, it only blocks an
80 # individual consumer thread; if it stalls long enough, the session
81 # will be timed out. This solves the biggest problem with a
82 # single-threaded implementation, which is that you can't count on a
83 # single stalled write not hanging all other traffic - you're at the
84 # mercy of the length of the buffers in the TCP/IP layer.
86 # Message delivery is thus not reliable in the face of network stalls,
87 # but this was considered acceptable because IRC (notoriously) has the
88 # same problem - there is little point in reliable delivery to a relay
89 # that is down or unreliable.
91 # This code uses only NICK, JOIN, PART, MODE, and PRIVMSG. It is strictly
92 # compliant to RFC1459, except for the interpretation and use of the
93 # DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features. CHANLIMIT
94 # is as described in the Internet RFC draft
95 # draft-brocklesby-irc-isupport-03 at <http://www.mirc.com/isupport.html>.
96 # The ",isnick" feature is as described in
97 # <http://ftp.ics.uci.edu/pub/ietf/uri/draft-mirashi-url-irc-01.txt>.
100 def __init__(self, irkerd, servername, port):
102 self.servername = servername
104 self.nick_trial = None
105 self.connection = None
107 self.last_xmit = time.time()
108 self.last_ping = time.time()
109 self.channels_joined = {}
110 self.channel_limits = {}
111 # The consumer thread
112 self.queue = Queue.Queue()
114 def nickname(self, n=None):
115 "Return a name for the nth server connection."
119 return (namestyle % n)
122 def handle_ping(self):
123 "Register the fact that the server has pinged this connection."
124 self.last_ping = time.time()
125 def handle_welcome(self):
126 "The server says we're OK, with a non-conflicting nick."
127 self.status = "ready"
128 self.irker.debug(1, "nick %s accepted" % self.nickname())
130 self.connection.privmsg("nickserv", "identify %s" % password)
131 def handle_badnick(self):
132 "The server says our nick is ill-formed or has a conflict."
133 self.irker.debug(1, "nick %s rejected" % self.nickname())
135 # Randomness prevents a malicious user or bot from
136 # anticipating the next trial name in order to block us
137 # from completing the handshake.
138 self.nick_trial += random.randint(1, 3)
139 self.last_xmit = time.time()
140 self.connection.nick(self.nickname())
141 # Otherwise fall through, it might be possible to
143 def handle_disconnect(self):
144 "Server disconnected us for flooding or some other reason."
145 self.connection = None
146 self.status = "disconnected"
147 def handle_kick(self, outof):
149 self.status = "handshaking"
151 del self.channels_joined[outof]
153 self.irker.logerr("kicked by %s from %s that's not joined"
154 % (self.servername, outof))
156 while not self.queue.empty():
157 (channel, message) = self.queue.get()
159 qcopy.append((channel, message))
160 for (channel, message) in qcopy:
161 self.queue.put((channel, message))
162 self.status = "ready"
163 def enqueue(self, channel, message):
164 "Enque a message for transmission."
165 if self.thread is None or not self.thread.is_alive():
166 self.status = "unseen"
167 self.thread = threading.Thread(target=self.dequeue)
168 self.thread.setDaemon(True)
170 self.queue.put((channel, message))
172 "Try to ship pending messages from the queue."
175 # We want to be kind to the IRC servers and not hold unused
176 # sockets open forever, so they have a time-to-live. The
177 # loop is coded this particular way so that we can drop
178 # the actual server connection when its time-to-live
179 # expires, then reconnect and resume transmission if the
180 # queue fills up again.
181 if self.queue.empty():
182 # Queue is empty, at some point we want to time out
183 # the connection rather than holding a socket open in
184 # the server forever.
186 xmit_timeout = now > self.last_xmit + XMIT_TTL
187 ping_timeout = now > self.last_ping + PING_TTL
188 if self.status == "disconnected":
189 # If the queue is empty, we can drop this connection.
190 self.status = "expired"
192 elif xmit_timeout or ping_timeout:
193 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))
194 with self.irker.irc.mutex:
195 self.connection.context = None
196 self.connection.quit("transmission timeout")
197 self.connection = None
198 self.status = "disconnected"
200 # Prevent this thread from hogging the CPU by pausing
201 # for just a little bit after the queue-empty check.
202 # As long as this is less that the duration of a human
203 # reflex arc it is highly unlikely any human will ever
205 time.sleep(ANTI_BUZZ_DELAY)
206 elif self.status == "disconnected" \
207 and time.time() > self.last_xmit + DISCONNECT_TTL:
208 # Queue is nonempty, but the IRC server might be
209 # down. Letting failed connections retain queue
210 # space forever would be a memory leak.
211 self.status = "expired"
213 elif not self.connection:
214 # Queue is nonempty but server isn't connected.
215 with self.irker.irc.mutex:
216 self.connection = self.irker.irc.server()
217 self.connection.context = self
218 # Try to avoid colliding with other instances
219 self.nick_trial = random.randint(1, 990)
220 self.channels_joined = {}
223 # irc.client.ServerConnectionError on failure
224 self.connection.connect(self.servername,
226 nickname=self.nickname(),
228 ircname="irker relaying client")
229 if hasattr(self.connection, "buffer"):
230 self.connection.buffer.errors = 'replace'
231 self.status = "handshaking"
232 self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
233 self.last_xmit = time.time()
234 self.last_ping = time.time()
235 except irc.client.ServerConnectionError:
236 self.status = "disconnected"
237 elif self.status == "handshaking":
238 if time.time() > self.last_xmit + HANDSHAKE_TTL:
239 self.status = "expired"
242 # Don't buzz on the empty-queue test while we're
244 time.sleep(ANTI_BUZZ_DELAY)
245 elif self.status == "unseen" \
246 and time.time() > self.last_xmit + UNSEEN_TTL:
247 # Nasty people could attempt a denial-of-service
248 # attack by flooding us with requests with invalid
249 # servernames. We guard against this by rapidly
250 # expiring connections that have a nonempty queue but
251 # have never had a successful open.
252 self.status = "expired"
254 elif self.status == "ready":
255 (channel, message) = self.queue.get()
256 if channel not in self.channels_joined:
257 self.connection.join(channel)
258 self.irker.debug(1, "joining %s on %s." % (channel, self.servername))
259 # An empty message might be used as a keepalive or
260 # to join a channel for logging, so suppress the
261 # privmsg send unless there is actual traffic.
263 for segment in message.split("\n"):
264 # Truncate the message if it's too long,
265 # but we're working with characters here,
266 # not bytes, so we could be off.
267 # 500 = 512 - CRLF - 'PRIVMSG ' - ' :'
268 maxlength = 500 - len(channel)
269 if len(segment) > maxlength:
270 segment = segment[:maxlength]
272 self.connection.privmsg(channel, segment)
273 except ValueError as err:
274 self.irker.debug(1, "irclib rejected a message to %s on %s because: %s" % (channel, self.servername, str(err)))
275 time.sleep(ANTI_FLOOD_DELAY)
276 self.last_xmit = self.channels_joined[channel] = time.time()
277 self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
278 self.queue.task_done()
280 (exc_type, _exc_value, exc_traceback) = sys.exc_info()
281 self.irker.logerr("exception %s in thread for %s" % \
282 (exc_type, self.servername))
284 # Maybe this should have its own status?
285 self.status = "expired"
287 # This is so we can see tracebacks for errors inside the thread
288 # when we need to be able to for debugging purposes.
290 raise exc_type, _exc_value, exc_traceback
293 # Make sure we don't leave any zombies behind
294 self.connection.close()
296 # Irclib has a habit of throwing fresh exceptions here. Ignore that
299 "Should this connection not be scavenged?"
300 return self.status != "expired"
301 def joined_to(self, channel):
302 "Is this connection joined to the specified channel?"
303 return channel in self.channels_joined
304 def accepting(self, channel):
305 "Can this connection accept a join of this channel?"
306 if self.channel_limits:
308 for already in self.channels_joined:
309 # This obscure code is because the RFCs allow separate limits
310 # by channel type (indicated by the first character of the name)
311 # a feature that is almost never actually used.
312 if already[0] == channel[0]:
314 return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
316 return len(self.channels_joined) < CHANNEL_MAX
319 "Represent a transmission target."
320 def __init__(self, url):
321 # Pre-2.6 Pythons don't recognize irc: as a valid URL prefix.
322 url = url.replace("irc://", "http://")
323 parsed = urlparse.urlparse(url)
324 irchost, _, ircport = parsed.netloc.partition(':')
327 self.servername = irchost
328 # IRC channel names are case-insensitive. If we don't smash
329 # case here we may run into problems later. There was a bug
330 # observed on irc.rizon.net where an irkerd user specified #Channel,
331 # got kicked, and irkerd crashed because the server returned
332 # "#channel" in the notification that our kick handler saw.
333 self.channel = parsed.path.lstrip('/').lower()
334 # This deals with a tweak in recent versions of urlparse.
336 self.channel += "#" + parsed.fragment
337 isnick = self.channel.endswith(",isnick")
339 self.channel = self.channel[:-7]
340 if self.channel and not isnick and self.channel[0] not in "#&+":
341 self.channel = "#" + self.channel
342 self.port = int(ircport)
344 "Both components must be present for a valid target."
345 return self.servername and self.channel
347 "Return a hashable tuple representing the destination server."
348 return (self.servername, self.port)
351 "Manage connections to a particular server-port combination."
352 def __init__(self, irkerd, servername, port):
354 self.servername = servername
356 self.connections = []
357 def dispatch(self, channel, message):
358 "Dispatch messages for our server-port combination."
359 # First, check if there is room for another channel
360 # on any of our existing connections.
361 connections = [x for x in self.connections if x.live()]
362 eligibles = [x for x in connections if x.joined_to(channel)] \
363 or [x for x in connections if x.accepting(channel)]
365 eligibles[0].enqueue(channel, message)
367 # All connections are full up. Look for one old enough to be
370 for connection in connections:
371 for (chan, age) in connections.channels_joined.items():
372 if age < time.time() - CHANNEL_TTL:
373 ancients.append((connection, chan, age))
375 ancients.sort(key=lambda x: x[2])
376 (found_connection, drop_channel, _drop_age) = ancients[0]
377 found_connection.part(drop_channel, "scavenged by irkerd")
378 del found_connection.channels_joined[drop_channel]
379 #time.sleep(ANTI_FLOOD_DELAY)
380 found_connection.enqueue(channel, message)
382 # Didn't find any channels with no recent activity
383 newconn = Connection(self.irker,
386 self.connections.append(newconn)
387 newconn.enqueue(channel, message)
389 "Does this server-port combination have any live connections?"
390 self.connections = [x for x in self.connections if x.live()]
391 return len(self.connections) > 0
393 "Return the time of the most recent transmission."
394 return max(x.last_xmit for x in self.connections)
397 "Persistent IRC multiplexer."
398 def __init__(self, debuglevel=0):
399 self.debuglevel = debuglevel
400 self.irc = irc.client.IRC()
401 self.irc.add_global_handler("ping", self._handle_ping)
402 self.irc.add_global_handler("welcome", self._handle_welcome)
403 self.irc.add_global_handler("erroneusnickname", self._handle_badnick)
404 self.irc.add_global_handler("nicknameinuse", self._handle_badnick)
405 self.irc.add_global_handler("nickcollision", self._handle_badnick)
406 self.irc.add_global_handler("unavailresource", self._handle_badnick)
407 self.irc.add_global_handler("featurelist", self._handle_features)
408 self.irc.add_global_handler("disconnect", self._handle_disconnect)
409 self.irc.add_global_handler("kick", self._handle_kick)
410 self.irc.add_global_handler("all_raw_messages", self._handle_all_raw_messages)
411 thread = threading.Thread(target=self.irc.process_forever)
412 thread.setDaemon(True)
413 self.irc._thread = thread
416 def logerr(self, errmsg):
417 "Log a processing error."
418 sys.stderr.write("irkerd: " + errmsg + "\n")
419 def debug(self, level, errmsg):
420 "Debugging information."
421 if self.debuglevel >= level:
422 sys.stderr.write("irkerd: %s\n" % errmsg)
423 def _handle_ping(self, connection, _event):
424 "PING arrived, bump the last-received time for the connection."
425 if connection.context:
426 connection.context.handle_ping()
427 def _handle_welcome(self, connection, _event):
428 "Welcome arrived, nick accepted for this connection."
429 if connection.context:
430 connection.context.handle_welcome()
431 def _handle_badnick(self, connection, _event):
432 "Nick not accepted for this connection."
433 if connection.context:
434 connection.context.handle_badnick()
435 def _handle_features(self, connection, event):
436 "Determine if and how we can set deaf mode."
437 if connection.context:
438 cxt = connection.context
439 arguments = event.arguments
440 # irclib 5.0 compatibility, because the maintainer is a fool
441 if callable(arguments):
442 arguments = arguments()
443 for lump in arguments:
444 if lump.startswith("DEAF="):
446 connection.mode(cxt.nickname(), "+"+lump[5:])
447 elif lump.startswith("MAXCHANNELS="):
450 cxt.channel_limits[pref] = m
451 self.debug(1, "%s maxchannels is %d"
452 % (connection.server, m))
453 elif lump.startswith("CHANLIMIT=#:"):
454 limits = lump[10:].split(",")
457 (prefixes, limit) = token.split(":")
460 cxt.channel_limits[c] = limit
461 self.debug(1, "%s channel limit map is %s"
462 % (connection.server, cxt.channel_limits))
464 self.logerr("ill-formed CHANLIMIT property")
465 def _handle_disconnect(self, connection, _event):
466 "Server hung up the connection."
467 self.debug(1, "server %s disconnected" % connection.server)
469 if connection.context:
470 connection.context.handle_disconnect()
471 def _handle_kick(self, connection, event):
472 "Server hung up the connection."
473 target = event.target
474 # irclib 5.0 compatibility, because the maintainer continues
478 self.debug(1, "irker has been kicked from %s on %s" % (target, connection.server))
479 if connection.context:
480 connection.context.handle_kick(target)
481 def _handle_all_raw_messages(self, _connection, event):
482 "Log all messages when in watcher mode."
484 with open(logfile, "a") as logfp:
485 logfp.write("%03f|%s|%s\n" % \
486 (time.time(), event.source, event.arguments[0]))
487 def handle(self, line):
488 "Perform a JSON relay request."
490 request = json.loads(line.strip())
491 if not isinstance(request, dict):
492 self.logerr("request is not a JSON dictionary: %r" % request)
493 elif "to" not in request or "privmsg" not in request:
494 self.logerr("malformed request - 'to' or 'privmsg' missing: %r" % request)
496 channels = request['to']
497 message = request['privmsg']
498 if not isinstance(channels, (list, basestring)):
499 self.logerr("malformed request - unexpected channel type: %r" % channels)
500 if not isinstance(message, basestring):
501 self.logerr("malformed request - unexpected message type: %r" % message)
503 if not isinstance(channels, list):
504 channels = [channels]
506 if not isinstance(url, basestring):
507 self.logerr("malformed request - URL has unexpected type: %r" % url)
510 if not target.valid():
512 if target.server() not in self.servers:
513 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
514 self.servers[target.server()].dispatch(target.channel, message)
515 # GC dispatchers with no active connections
516 servernames = self.servers.keys()
517 for servername in servernames:
518 if not self.servers[servername].live():
519 del self.servers[servername]
520 # If we might be pushing a resource limit
521 # even after garbage collection, remove a
522 # session. The goal here is to head off
523 # DoS attacks that aim at exhausting
524 # thread space or file descriptors. The
525 # cost is that attempts to DoS this
526 # service will cause lots of join/leave
527 # spam as we scavenge old channels after
528 # connecting to new ones. The particular
529 # method used for selecting a session to
530 # be terminated doesn't matter much; we
531 # choose the one longest idle on the
532 # assumption that message activity is likely
534 if len(self.servers) >= CONNECTION_MAX:
535 oldest = min(self.servers.keys(), key=lambda name: self.servers[name].last_xmit())
536 del self.servers[oldest]
538 self.logerr("can't recognize JSON on input: %r" % line)
540 self.logerr("wildly malformed JSON blew the parser stack.")
542 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
545 line = self.rfile.readline()
548 irker.handle(line.strip())
550 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
552 data = self.request[0].strip()
553 #socket = self.request[1]
559 irkerd [-d debuglevel] [-l logfile] [-n nick] [-p password] [-V] [-h]
565 -p set nickserv password
566 -V return irkerd version
567 -h print this help dialog
570 if __name__ == '__main__':
572 namestyle = "irker%03d"
576 (options, arguments) = getopt.getopt(sys.argv[1:], "d:l:n:p:Vh")
577 except getopt.GetoptError as e:
578 sys.stderr.write("%s" % e)
581 for (opt, val) in options:
582 if opt == '-d': # Enable debug/progress messages
585 logging.basicConfig(level=logging.DEBUG)
586 elif opt == '-l': # Logfile mode - report traffic read in
588 elif opt == '-n': # Force the nick
590 elif opt == '-p': # Set a nickserv password
592 elif opt == '-V': # Emit version and exit
593 sys.stdout.write("irkerd version %s\n" % version)
598 fallback = re.search("%.*d", namestyle)
599 irker = Irker(debuglevel=debuglvl)
600 irker.debug(1, "irkerd version %s" % version)
602 tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
603 udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
604 for server in [tcpserver, udpserver]:
605 server = threading.Thread(target=server.serve_forever)
606 server.setDaemon(True)
610 except KeyboardInterrupt:
612 except socket.error, e:
613 sys.stderr.write("irkerd: server launch failed: %r\n" % e)