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 xmit_timeout = now > self.last_xmit + XMIT_TTL
189 ping_timeout = now > self.last_ping + PING_TTL
190 if (xmit_timeout or ping_timeout) and self.status != "disconnected":
191 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))
192 with self.irker.library_lock:
193 self.connection.context = None
194 self.connection.quit("transmission timeout")
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 with self.irker.library_lock:
207 self.connection = self.irker.irc.server()
208 self.connection.context = self
209 # Try to avoid colliding with other instances
210 self.nick_trial = random.randint(1, 990)
211 self.channels_joined = {}
214 # irc.client.ServerConnectionError on failure
215 self.connection.connect(self.servername,
217 nickname=self.nickname(),
219 ircname="irker relaying client")
220 self.status = "handshaking"
221 self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
222 self.last_xmit = time.time()
223 except irc.client.ServerConnectionError:
224 self.status = "disconnected"
225 elif self.status == "handshaking":
226 if time.time() > self.last_xmit + HANDSHAKE_TTL:
227 self.status = "expired"
230 # Don't buzz on the empty-queue test while we're
232 time.sleep(ANTI_BUZZ_DELAY)
233 elif self.status == "disconnected" \
234 and time.time() > self.last_xmit + DISCONNECT_TTL:
235 # Queue is nonempty, but the IRC server might be
236 # down. Letting failed connections retain queue
237 # space forever would be a memory leak.
238 self.status = "expired"
240 elif self.status == "unseen" \
241 and time.time() > self.last_xmit + UNSEEN_TTL:
242 # Nasty people could attempt a denial-of-service
243 # attack by flooding us with requests with invalid
244 # servernames. We guard against this by rapidly
245 # expiring connections that have a nonempty queue but
246 # have never had a successful open.
247 self.status = "expired"
249 elif self.status == "ready":
250 with self.irker.library_lock:
251 (channel, message) = self.queue.get()
252 if channel not in self.channels_joined:
253 self.connection.join(channel)
254 self.irker.debug(1, "joining %s on %s." % (channel, self.servername))
255 for segment in message.split("\n"):
256 self.connection.privmsg(channel, segment)
257 time.sleep(ANTI_FLOOD_DELAY)
258 self.last_xmit = self.channels_joined[channel] = time.time()
259 self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
260 self.queue.task_done()
262 (exc_type, _exc_value, exc_traceback) = sys.exc_info()
263 self.irker.logerr("exception %s in thread for %s" % \
264 (exc_type, self.servername))
265 # This is so we can see tracebacks for errors inside the thread
266 # when we need to be able to for debugging purposes.
268 raise exc_type, _exc_value, exc_traceback
270 "Should this connection not be scavenged?"
271 return self.status != "expired"
272 def joined_to(self, channel):
273 "Is this connection joined to the specified channel?"
274 return channel in self.channels_joined
275 def accepting(self, channel):
276 "Can this connection accept a join of this channel?"
277 if self.channel_limits:
279 for already in self.channels_joined:
280 if already[0] == channel[0]:
282 return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
284 return len(self.channels_joined) < CHANNEL_MAX
287 "Represent a transmission target."
288 def __init__(self, url):
289 parsed = urlparse.urlparse(url)
290 irchost, _, ircport = parsed.netloc.partition(':')
293 self.servername = irchost
294 # IRC channel names are case-insensitive. If we don't smash
295 # case here we may run into problems later. There was a bug
296 # observed on irc.rizon.net where an irkerd user specified #Channel,
297 # got kicked, and irkerd crashed because the server returned
298 # "#channel" in the notification that our kick handler saw.
299 self.channel = parsed.path.lstrip('/').lower()
300 isnick = self.channel.endswith(",isnick")
302 self.channel = self.channel[:-7]
303 if self.channel and not isnick and self.channel[0] not in "#&+":
304 self.channel = "#" + self.channel
305 self.port = int(ircport)
307 "Both components must be present for a valid target."
308 return self.servername and self.channel
310 "Return a hashable tuple representing the destination server."
311 return (self.servername, self.port)
314 "Manage connections to a particular server-port combination."
315 def __init__(self, irkerd, servername, port):
317 self.servername = servername
319 self.connections = []
320 def dispatch(self, channel, message):
321 "Dispatch messages for our server-port combination."
322 # First, check if there is room for another channel
323 # on any of our existing connections.
324 connections = [x for x in self.connections if x.live()]
325 eligibles = [x for x in connections if x.joined_to(channel)] \
326 or [x for x in connections if x.accepting(channel)]
328 eligibles[0].enqueue(channel, message)
330 # All connections are full up. Look for one old enough to be
333 for connection in connections:
334 for (chan, age) in connections.channels_joined.items():
335 if age < time.time() - CHANNEL_TTL:
336 ancients.append((connection, chan, age))
338 ancients.sort(key=lambda x: x[2])
339 (found_connection, drop_channel, _drop_age) = ancients[0]
340 found_connection.part(drop_channel, "scavenged by irkerd")
341 del found_connection.channels_joined[drop_channel]
342 #time.sleep(ANTI_FLOOD_DELAY)
343 found_connection.enqueue(channel, message)
345 # Didn't find any channels with no recent activity
346 newconn = Connection(self.irker,
349 self.connections.append(newconn)
350 newconn.enqueue(channel, message)
352 "Does this server-port combination have any live connections?"
353 self.connections = [x for x in self.connections if x.live()]
354 return len(self.connections) > 0
356 "Return the time of the most recent transmission."
357 return max([x.last_xmit for x in self.connections])
360 "Persistent IRC multiplexer."
361 def __init__(self, debuglevel=0):
362 self.debuglevel = debuglevel
363 self.irc = irc.client.IRC()
364 self.irc.add_global_handler("ping", self._handle_ping)
365 self.irc.add_global_handler("welcome", self._handle_welcome)
366 self.irc.add_global_handler("erroneusnickname", self._handle_badnick)
367 self.irc.add_global_handler("nicknameinuse", self._handle_badnick)
368 self.irc.add_global_handler("nickcollision", self._handle_badnick)
369 self.irc.add_global_handler("unavailresource", self._handle_badnick)
370 self.irc.add_global_handler("featurelist", self._handle_features)
371 self.irc.add_global_handler("disconnect", self._handle_disconnect)
372 self.irc.add_global_handler("kick", self._handle_kick)
373 self.library_lock = threading.Lock()
374 thread = threading.Thread(target=self._process_forever)
375 thread.setDaemon(True)
376 self.irc._thread = thread
379 def logerr(self, errmsg):
380 "Log a processing error."
381 sys.stderr.write("irkerd: " + errmsg + "\n")
382 def debug(self, level, errmsg):
383 "Debugging information."
384 if self.debuglevel >= level:
385 sys.stderr.write("irkerd: %s\n" % errmsg)
386 def _process_forever(self):
387 "IRC library process_forever with mutex."
388 self.debug(1, "process_forever()")
390 with self.library_lock:
391 self.irc.process_once(ANTI_BUZZ_DELAY)
392 def _handle_ping(self, connection, _event):
393 "PING arrived, bump the last-received time for the connection."
394 if connection.context:
395 connection.context.handle_ping()
396 def _handle_welcome(self, connection, _event):
397 "Welcome arrived, nick accepted for this connection."
398 if connection.context:
399 connection.context.handle_welcome()
400 def _handle_badnick(self, connection, _event):
401 "Nick not accepted for this connection."
402 if connection.context:
403 connection.context.handle_badnick()
404 def _handle_features(self, connection, event):
405 "Determine if and how we can set deaf mode."
406 if connection.context:
407 cxt = connection.context
408 for lump in event.arguments():
409 if lump.startswith("DEAF="):
410 connection.mode(cxt.nickname(), "+"+lump[5:])
411 elif lump.startswith("MAXCHANNELS="):
414 cxt.channel_limits[pref] = m
415 self.debug(1, "%s maxchannels is %d"
416 % (connection.server, m))
417 elif lump.startswith("CHANLIMIT=#:"):
418 limits = lump[10:].split(",")
421 (prefixes, limit) = token.split(":")
424 cxt.channel_limits[c] = limit
425 self.debug(1, "%s channel limit map is %s"
426 % (connection.server, cxt.channel_limits))
428 self.logerr("ill-formed CHANLIMIT property")
429 def _handle_disconnect(self, connection, _event):
430 "Server hung up the connection."
431 self.debug(1, "server %s disconnected" % connection.server)
433 if connection.context:
434 connection.context.handle_disconnect()
435 def _handle_kick(self, connection, event):
436 "Server hung up the connection."
437 self.debug(1, "irker has been kicked from %s on %s" % (event.target(), connection.server))
438 if connection.context:
439 connection.context.handle_kick(event.target())
440 def handle(self, line):
441 "Perform a JSON relay request."
443 request = json.loads(line.strip())
444 if not isinstance(request, dict):
445 self.logerr("request is not a JSON dictionary: %r" % request)
446 elif "to" not in request or "privmsg" not in request:
447 self.logerr("malformed request - 'to' or 'privmsg' missing: %r" % request)
449 channels = request['to']
450 message = request['privmsg']
451 if not isinstance(channels, (list, basestring)):
452 self.logerr("malformed request - unexpected channel type: %r" % channels)
453 if not isinstance(message, basestring):
454 self.logerr("malformed request - unexpected message type: %r" % message)
456 if not isinstance(channels, list):
457 channels = [channels]
459 if not isinstance(url, basestring):
460 self.logerr("malformed request - URL has unexpected type: %r" % url)
463 if not target.valid():
465 if target.server() not in self.servers:
466 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
467 self.servers[target.server()].dispatch(target.channel, message)
468 # GC dispatchers with no active connections
469 servernames = self.servers.keys()
470 for servername in servernames:
471 if not self.servers[servername].live():
472 del self.servers[servername]
473 # If we might be pushing a resource limit
474 # even after garbage collection, remove a
475 # session. The goal here is to head off
476 # DoS attacks that aim at exhausting
477 # thread space or file descriptors. The
478 # cost is that attempts to DoS this
479 # service will cause lots of join/leave
480 # spam as we scavenge old channels after
481 # connecting to new ones. The particular
482 # method used for selecting a session to
483 # be terminated doesn't matter much; we
484 # choose the one longest idle on the
485 # assumption that message activity is likely
488 oldtime = float("inf")
489 if len(self.servers) >= CONNECTION_MAX:
490 for (name, server) in self.servers.items():
491 if server.last_xmit() < oldtime:
493 oldtime = server.last_xmit()
494 del self.servers[oldest]
496 self.logerr("can't recognize JSON on input: %r" % line)
498 self.logerr("wildly malformed JSON blew the parser stack.")
500 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
503 line = self.rfile.readline()
506 irker.handle(line.strip())
508 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
510 data = self.request[0].strip()
511 #socket = self.request[1]
514 if __name__ == '__main__':
516 (options, arguments) = getopt.getopt(sys.argv[1:], "d:V")
517 for (opt, val) in options:
518 if opt == '-d': # Enable debug/progress messages
521 logging.basicConfig(level=logging.DEBUG)
522 elif opt == '-V': # Emit version and exit
523 sys.stdout.write("irkerd version %s\n" % version)
525 irker = Irker(debuglevel=debuglvl)
526 irker.debug(1, "irkerd version %s" % version)
528 tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
529 udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
530 for server in [tcpserver, udpserver]:
531 server = threading.Thread(target=server.serve_forever)
532 server.setDaemon(True)
537 except KeyboardInterrupt:
539 except socket.error, e:
540 sys.stderr.write("irkerd: server launch failed: %r\n" % e)