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 and the irc client library at version >= 2.0.2: see
23 http://pypi.python.org/pypi/irc/
25 # These things might need tuning
30 NAMESTYLE = "irker%03d" # IRC nick template - must contain '%d'
31 XMIT_TTL = (3 * 60 * 60) # Time to live, seconds from last transmit
32 PING_TTL = (15 * 60) # Time to live, seconds from last PING
33 HANDSHAKE_TTL = 60 # Time to live, seconds from nick transmit
34 CHANNEL_TTL = (3 * 60 * 60) # Time to live, seconds from last transmit
35 DISCONNECT_TTL = (24 * 60 * 60) # Time to live, seconds from last connect
36 UNSEEN_TTL = 60 # Time to live, seconds since first request
37 CHANNEL_MAX = 18 # Max channels open per socket (default)
38 ANTI_FLOOD_DELAY = 0.5 # Anti-flood delay after transmissions, seconds
39 ANTI_BUZZ_DELAY = 0.09 # Anti-buzz delay after queue-empty check
41 # No user-serviceable parts below this line
45 # This black magic imports support for green threads (coroutines),
46 # then has kinky sex with the import library internals, replacing
47 # "threading" with a coroutine-using imposter. Threads then become
48 # ultra-light-weight and cooperatively scheduled.
51 eventlet.monkey_patch()
53 # With greenlets we don't worry about thread exhaustion, only the
54 # file descriptor limit (typically 1024 on modern Unixes). Thus we
55 # can handle a lot more concurrent sessions and generate less
56 # join/leave spam under heavy load.
59 # Threads are more expensive if we have to use OS-level ones
60 # rather than greenlets. We need to avoid pushing thread limits
61 # as well as fd limits. See security.txt for discussion.
65 import sys, getopt, urlparse, time, random, socket
66 import threading, Queue, SocketServer
67 import irc.client, logging
69 import simplejson as json # Faster, also makes us Python-2.4-compatible
73 # Sketch of implementation:
75 # One Irker object manages multiple IRC sessions. It holds a map of
76 # Dispatcher objects, one per (server, port) combination, which are
77 # responsible for routing messages to one of any number of Connection
78 # objects that do the actual socket conversations. The reason for the
79 # Dispatcher layer is that IRC daemons limit the number of channels a
80 # client (that is, from the daemon's point of view, a socket) can be
81 # joined to, so each session to a server needs a flock of Connection
82 # instances each with its own socket.
84 # Connections are timed out and removed when either they haven't seen a
85 # PING for a while (indicating that the server may be stalled or down)
86 # or there has been no message traffic to them for a while, or
87 # even if the queue is nonempty but efforts to connect have failed for
90 # There are multiple threads. One accepts incoming traffic from all servers.
91 # Each Connection also has a consumer thread and a thread-safe message queue.
92 # The program main appends messages to queues as JSON requests are received;
93 # the consumer threads try to ship them to servers. When a socket write
94 # stalls, it only blocks an individual consumer thread; if it stalls long
95 # enough, the session will be timed out.
97 # Message delivery is thus not reliable in the face of network stalls,
98 # but this was considered acceptable because IRC (notoriously) has the
99 # same problem - there is little point in reliable delivery to a relay
100 # that is down or unreliable.
102 # This code uses only NICK, JOIN, MODE, and PRIVMSG. It is strictly
103 # compliant to RFC1459, except for the interpretation and use of the
104 # DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features. CHANLIMIT
105 # is as described in the Internet RFC draft
106 # draft-brocklesby-irc-isupport-03 at <http://www.mirc.com/isupport.html>.
107 # The ",isnick" feature is as described in
108 # <http://ftp.ics.uci.edu/pub/ietf/uri/draft-mirashi-url-irc-01.txt>.
111 def __init__(self, irkerd, servername, port):
113 self.servername = servername
115 self.nick_trial = None
116 self.connection = None
118 self.last_xmit = time.time()
119 self.last_ping = time.time()
120 self.channels_joined = {}
121 self.channel_limits = {}
122 # The consumer thread
123 self.queue = Queue.Queue()
125 def nickname(self, n=None):
126 "Return a name for the nth server connection."
129 return (NAMESTYLE % n)
130 def handle_ping(self):
131 "Register the fact that the server has pinged this connection."
132 self.last_ping = time.time()
133 def handle_welcome(self):
134 "The server says we're OK, with a non-conflicting nick."
135 self.status = "ready"
136 self.irker.debug(1, "nick %s accepted" % self.nickname())
137 def handle_badnick(self):
138 "The server says our nick has a conflict."
139 self.irker.debug(1, "nick %s rejected" % self.nickname())
140 # Randomness prevents a malicious user or bot from antcipating the
141 # next trial name in order to block us from completing the handshake.
142 self.nick_trial += random.randint(1, 3)
143 self.last_xmit = time.time()
144 self.connection.nick(self.nickname())
145 def handle_disconnect(self):
146 "Server disconnected us for flooding or some other reason."
147 self.connection = None
148 self.status = "disconnected"
149 def handle_kick(self, outof):
151 self.status = "handshaking"
153 del self.channels_joined[outof]
155 self.irker.logerr("kicked by %s from %s that's not joined"
156 % (self.servername, outof))
158 while not self.queue.empty():
159 (channel, message) = self.queue.get()
161 qcopy.append((channel, message))
162 for (channel, message) in qcopy:
163 self.queue.put((channel, message))
164 self.status = "ready"
165 def enqueue(self, channel, message):
166 "Enque a message for transmission."
167 if self.thread is None or not self.thread.is_alive():
168 self.status = "unseen"
169 self.thread = threading.Thread(target=self.dequeue)
170 self.thread.setDaemon(True)
172 self.queue.put((channel, message))
174 "Try to ship pending messages from the queue."
177 # We want to be kind to the IRC servers and not hold unused
178 # sockets open forever, so they have a time-to-live. The
179 # loop is coded this particular way so that we can drop
180 # the actual server connection when its time-to-live
181 # expires, then reconnect and resume transmission if the
182 # queue fills up again.
183 if self.queue.empty():
184 # Queue is empty, at some point we want to time out
185 # the connection rather than holding a socket open in
186 # the server forever.
188 if (now > self.last_xmit + XMIT_TTL \
189 or now > self.last_ping + PING_TTL) \
190 and self.status != "disconnected":
191 self.irker.debug(1, "timing out inactive connection to %s at %s" % (self.servername, time.asctime()))
192 self.connection.context = None
193 self.connection.quit("transmission timeout")
194 self.connection.close()
195 self.connection = None
196 self.status = "disconnected"
198 # Prevent this thread from hogging the CPU by pausing
199 # for just a little bit after the queue-empty check.
200 # As long as this is less that the duration of a human
201 # reflex arc it is highly unlikely any human will ever
203 time.sleep(ANTI_BUZZ_DELAY)
204 elif not self.connection:
205 # Queue is nonempty but server isn't connected.
206 self.connection = self.irker.irc.server()
207 self.connection.context = self
208 # Try to avoid colliding with other instances
209 self.nick_trial = random.randint(1, 990)
210 self.channels_joined = {}
211 # This will throw irc.client.ServerConnectionError on failure
213 self.connection.connect(self.servername,
215 nickname=self.nickname(),
217 ircname="irker relaying client")
218 self.status = "handshaking"
219 self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
220 self.last_xmit = 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 == "disconnected" \
232 and time.time() > self.last_xmit + DISCONNECT_TTL:
233 # Queue is nonempty, but the IRC server might be
234 # down. Letting failed connections retain queue
235 # space forever would be a memory leak.
236 self.status = "expired"
238 elif self.status == "unseen" \
239 and time.time() > self.last_xmit + UNSEEN_TTL:
240 # Nasty people could attempt a denial-of-service
241 # attack by flooding us with requests with invalid
242 # servernames. We guard against this by rapidly
243 # expiring connections that have a nonempty queue but
244 # have never had a successful open.
245 self.status = "expired"
247 elif self.status == "ready":
248 (channel, message) = self.queue.get()
249 if channel not in self.channels_joined:
250 self.connection.join(channel)
251 self.irker.debug(1, "joining %s on %s." % (channel, self.servername))
252 for segment in message.split("\n"):
253 self.connection.privmsg(channel, segment + "\n")
254 time.sleep(ANTI_FLOOD_DELAY)
255 self.last_xmit = self.channels_joined[channel] = time.time()
256 self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
257 self.queue.task_done()
259 (exc_type, _exc_value, exc_traceback) = sys.exc_info()
260 self.irker.logerr("exception %s in thread for %s" % \
261 (exc_type, self.servername))
262 # This is so we can see tracebacks for errors inside the thread
263 # when we need to be able to for debugging purposes.
265 raise exc_type, _exc_value, exc_traceback
267 "Should this connection not be scavenged?"
268 return self.status != "expired"
269 def joined_to(self, channel):
270 "Is this connection joined to the specified channel?"
271 return channel in self.channels_joined
272 def accepting(self, channel):
273 "Can this connection accept a join of this channel?"
274 if self.channel_limits:
276 for already in self.channels_joined:
277 if already[0] == channel[0]:
279 return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
281 return len(self.channels_joined) < CHANNEL_MAX
284 "Represent a transmission target."
285 def __init__(self, url):
286 parsed = urlparse.urlparse(url)
287 irchost, _, ircport = parsed.netloc.partition(':')
290 self.servername = irchost
291 # IRC channel names are case-insensitive. If we don't smash
292 # case here we may run into problems later. There was a bug
293 # observed on irc.rizon.net where an irkerd user specified #Channel,
294 # got kicked, and irkerd crashed because the server returned
295 # "#channel" in the notification that our kick handler saw.
296 self.channel = parsed.path.lstrip('/').lower()
297 isnick = self.channel.endswith(",isnick")
299 self.channel = self.channel[:-7]
300 if self.channel and not isnick and self.channel[0] not in "#&+":
301 self.channel = "#" + self.channel
302 self.port = int(ircport)
304 "Both components must be present for a valid target."
305 return self.servername and self.channel
307 "Return a hashable tuple representing the destination server."
308 return (self.servername, self.port)
311 "Manage connections to a particular server-port combination."
312 def __init__(self, irkerd, servername, port):
314 self.servername = servername
316 self.connections = []
317 def dispatch(self, channel, message):
318 "Dispatch messages for our server-port combination."
319 # First, check if there is room for another channel
320 # on any of our existing connections.
321 connections = [x for x in self.connections if x.live()]
322 eligibles = [x for x in connections if x.joined_to(channel)] \
323 or [x for x in connections if x.accepting(channel)]
325 eligibles[0].enqueue(channel, message)
327 # All connections are full up. Look for one old enough to be
330 for connection in connections:
331 for (chan, age) in connections.channels_joined.items():
332 if age < time.time() - CHANNEL_TTL:
333 ancients.append((connection, chan, age))
335 ancients.sort(key=lambda x: x[2])
336 (found_connection, drop_channel, _drop_age) = ancients[0]
337 found_connection.part(drop_channel, "scavenged by irkerd")
338 del found_connection.channels_joined[drop_channel]
339 #time.sleep(ANTI_FLOOD_DELAY)
340 found_connection.enqueue(channel, message)
342 # Didn't find any channels with no recent activity
343 newconn = Connection(self.irker,
346 self.connections.append(newconn)
347 newconn.enqueue(channel, message)
349 "Does this server-port combination have any live connections?"
350 self.connections = [x for x in self.connections if x.live()]
351 return len(self.connections) > 0
353 "Return the time of the most recent transmission."
354 return max([x.last_xmit for x in self.connections])
357 "Persistent IRC multiplexer."
358 def __init__(self, debuglevel=0):
359 self.debuglevel = debuglevel
360 self.irc = irc.client.IRC()
361 self.irc.add_global_handler("ping", self._handle_ping)
362 self.irc.add_global_handler("welcome", self._handle_welcome)
363 self.irc.add_global_handler("erroneusnickname", self._handle_badnick)
364 self.irc.add_global_handler("nicknameinuse", self._handle_badnick)
365 self.irc.add_global_handler("nickcollision", self._handle_badnick)
366 self.irc.add_global_handler("unavailresource", self._handle_badnick)
367 self.irc.add_global_handler("featurelist", self._handle_features)
368 self.irc.add_global_handler("disconnect", self._handle_disconnect)
369 self.irc.add_global_handler("kick", self._handle_kick)
370 thread = threading.Thread(target=self.irc.process_forever)
371 thread.setDaemon(True)
372 self.irc._thread = thread
375 def logerr(self, errmsg):
376 "Log a processing error."
377 sys.stderr.write("irkerd: " + errmsg + "\n")
378 def debug(self, level, errmsg):
379 "Debugging information."
380 if self.debuglevel >= level:
381 sys.stderr.write("irkerd: %s\n" % errmsg)
382 def _handle_ping(self, connection, _event):
383 "PING arrived, bump the last-received time for the connection."
384 if connection.context:
385 connection.context.handle_ping()
386 def _handle_welcome(self, connection, _event):
387 "Welcome arrived, nick accepted for this connection."
388 if connection.context:
389 connection.context.handle_welcome()
390 def _handle_badnick(self, connection, _event):
391 "Nick not accepted for this connection."
392 if connection.context:
393 connection.context.handle_badnick()
394 def _handle_features(self, connection, event):
395 "Determine if and how we can set deaf mode."
396 if connection.context:
397 cxt = connection.context
398 for lump in event.arguments():
399 if lump.startswith("DEAF="):
400 connection.mode(cxt.nickname(), "+"+lump[5:])
401 elif lump.startswith("MAXCHANNELS="):
404 cxt.channel_limits[pref] = m
405 self.debug(1, "%s maxchannels is %d"
406 % (connection.server, m))
407 elif lump.startswith("CHANLIMIT=#:"):
408 limits = lump[10:].split(",")
411 (prefixes, limit) = token.split(":")
414 cxt.channel_limits[c] = limit
415 self.debug(1, "%s channel limit map is %s"
416 % (connection.server, cxt.channel_limits))
418 self.logerr("ill-formed CHANLIMIT property")
419 def _handle_disconnect(self, connection, _event):
420 "Server hung up the connection."
421 self.debug(1, "server %s disconnected" % connection.server)
422 if connection.context:
423 connection.context.handle_disconnect()
424 def _handle_kick(self, connection, event):
425 "Server hung up the connection."
426 self.debug(1, "irker has been kicked from %s on %s" % (event.target(), connection.server))
427 if connection.context:
428 connection.context.handle_kick(event.target())
429 def handle(self, line):
430 "Perform a JSON relay request."
432 request = json.loads(line.strip())
433 if not isinstance(request, dict):
434 self.logerr("request is not a JSON dictionary: %r" % request)
435 elif "to" not in request or "privmsg" not in request:
436 self.logerr("malformed request - 'to' or 'privmsg' missing: %r" % request)
438 channels = request['to']
439 message = request['privmsg']
440 if not isinstance(channels, (list, basestring)):
441 self.logerr("malformed request - unexpected channel type: %r" % channels)
442 if not isinstance(message, basestring):
443 self.logerr("malformed request - unexpected message type: %r" % message)
445 if not isinstance(channels, list):
446 channels = [channels]
448 if not isinstance(url, basestring):
449 self.logerr("malformed request - URL has unexpected type: %r" % url)
452 if not target.valid():
454 if target.server() not in self.servers:
455 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
456 self.servers[target.server()].dispatch(target.channel, message)
457 # GC dispatchers with no active connections
458 servernames = self.servers.keys()
459 for servername in servernames:
460 if not self.servers[servername].live():
461 del self.servers[servername]
462 # If we might be pushing a resource limit
463 # even after garbage collection, remove a
464 # session. The goal here is to head off
465 # DoS attacks that aim at exhausting
466 # thread space or file descriptors. The
467 # cost is that attempts to DoS this
468 # service will cause lots of join/leave
469 # spam as we scavenge old channels after
470 # connecting to new ones. The particular
471 # method used for selecting a session to
472 # be terminated doesn't matter much; we
473 # choose the one longest idle on the
474 # assumption that message activity is likely
477 oldtime = float("inf")
478 if len(self.servers) >= CONNECTION_MAX:
479 for (name, server) in self.servers.items():
480 if server.last_xmit() < oldtime:
482 oldtime = server.last_xmit()
483 del self.servers[oldest]
485 self.logerr("can't recognize JSON on input: %r" % line)
487 self.logerr("wildly malformed JSON blew the parser stack.")
489 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
492 line = self.rfile.readline()
495 irker.handle(line.strip())
497 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
499 data = self.request[0].strip()
500 #socket = self.request[1]
503 if __name__ == '__main__':
505 (options, arguments) = getopt.getopt(sys.argv[1:], "d:V")
506 for (opt, val) in options:
507 if opt == '-d': # Enable debug/progress messages
510 logging.basicConfig(level=logging.DEBUG)
511 elif opt == '-V': # Emit version and exit
512 sys.stdout.write("irkerd version %s\n" % version)
514 irker = Irker(debuglevel=debuglvl)
515 irker.debug(1, "irkerd version %s" % version)
517 tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
518 udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
519 for server in [tcpserver, udpserver]:
520 server = threading.Thread(target=server.serve_forever)
521 server.setDaemon(True)
526 except KeyboardInterrupt:
528 except socket.error, e:
529 sys.stderr.write("irkerd: server launch failed: %r\n" % e)