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>.
109 def __init__(self, irkerd, servername, port):
111 self.servername = servername
113 self.nick_trial = None
114 self.connection = None
116 self.last_xmit = time.time()
117 self.last_ping = time.time()
118 self.channels_joined = {}
119 self.channel_limits = {}
120 # The consumer thread
121 self.queue = Queue.Queue()
123 def nickname(self, n=None):
124 "Return a name for the nth server connection."
127 return (NAMESTYLE % n)
128 def handle_ping(self):
129 "Register the fact that the server has pinged this connection."
130 self.last_ping = time.time()
131 def handle_welcome(self):
132 "The server says we're OK, with a non-conflicting nick."
133 self.status = "ready"
134 self.irker.debug(1, "nick %s accepted" % self.nickname())
135 def handle_badnick(self):
136 "The server says our nick has a conflict."
137 self.irker.debug(1, "nick %s rejected" % self.nickname())
138 # Randomness prevents a malicious user or bot from antcipating the
139 # next trial name in order to block us from completing the handshake.
140 self.nick_trial += random.randint(1, 3)
141 self.last_xmit = time.time()
142 self.connection.nick(self.nickname())
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 if (now > self.last_xmit + XMIT_TTL \
187 or now > self.last_ping + PING_TTL) \
188 and self.status != "disconnected":
189 self.irker.debug(1, "timing out inactive connection to %s at %s" % (self.servername, time.asctime()))
190 self.connection.context = None
191 self.connection.quit("transmission timeout")
192 self.connection.close()
193 self.connection = None
194 self.status = "disconnected"
196 # Prevent this thread from hogging the CPU by pausing
197 # for just a little bit after the queue-empty check.
198 # As long as this is less that the duration of a human
199 # reflex arc it is highly unlikely any human will ever
201 time.sleep(ANTI_BUZZ_DELAY)
202 elif not self.connection:
203 # Queue is nonempty but server isn't connected.
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 = {}
209 # This will throw irc.client.ServerConnectionError on failure
211 self.connection.connect(self.servername,
213 nickname=self.nickname(),
215 ircname="irker relaying client")
216 self.status = "handshaking"
217 self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
218 self.last_xmit = time.time()
219 except irc.client.ServerConnectionError:
220 self.status = "disconnected"
221 elif self.status == "handshaking":
222 if time.time() > self.last_xmit + HANDSHAKE_TTL:
223 self.status = "expired"
226 # Don't buzz on the empty-queue test while we're
228 time.sleep(ANTI_BUZZ_DELAY)
229 elif self.status == "disconnected" \
230 and time.time() > self.last_xmit + DISCONNECT_TTL:
231 # Queue is nonempty, but the IRC server might be
232 # down. Letting failed connections retain queue
233 # space forever would be a memory leak.
234 self.status = "expired"
236 elif self.status == "unseen" \
237 and time.time() > self.last_xmit + UNSEEN_TTL:
238 # Nasty people could attempt a denial-of-service
239 # attack by flooding us with requests with invalid
240 # servernames. We guard against this by rapidly
241 # expiring connections that have a nonempty queue but
242 # have never had a successful open.
243 self.status = "expired"
245 elif self.status == "ready":
246 (channel, message) = self.queue.get()
247 if channel not in self.channels_joined:
248 self.connection.join(channel)
249 self.irker.debug(1, "joining %s on %s." % (channel, self.servername))
250 for segment in message.split("\n"):
251 self.connection.privmsg(channel, segment)
252 time.sleep(ANTI_FLOOD_DELAY)
253 self.last_xmit = self.channels_joined[channel] = time.time()
254 self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
255 self.queue.task_done()
257 (exc_type, _exc_value, exc_traceback) = sys.exc_info()
258 self.irker.logerr("exception %s in thread for %s" % \
259 (exc_type, self.servername))
260 # This is so we can see tracebacks for errors inside the thread
261 # when we need to be able to for debugging purposes.
263 raise exc_type, exc_value, exc_traceback
265 "Should this connection not be scavenged?"
266 return self.status != "expired"
267 def joined_to(self, channel):
268 "Is this connection joined to the specified channel?"
269 return channel in self.channels_joined
270 def accepting(self, channel):
271 "Can this connection accept a join of this channel?"
272 if self.channel_limits:
274 for already in self.channels_joined:
275 if already[0] == channel[0]:
277 return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
279 return len(self.channels_joined) < CHANNEL_MAX
282 "Represent a transmission target."
283 def __init__(self, url):
284 parsed = urlparse.urlparse(url)
285 irchost, _, ircport = parsed.netloc.partition(':')
288 self.servername = irchost
289 # IRC channel names are case-insensitive. If we don't smash
290 # case here we may run into problems later. There was a bug
291 # observed on irc.rizon.net where an irkerd user specified #Channel,
292 # got kicked, and irkerd crashed because the server returned
293 # "#channel" in the notification that our kick handler saw.
294 self.channel = parsed.path.lstrip('/').lower()
295 if self.channel and self.channel[0] not in "#&+":
296 self.channel = "#" + self.channel
297 self.port = int(ircport)
299 "Both components must be present for a valid target."
300 return self.servername and self.channel
302 "Return a hashable tuple representing the destination server."
303 return (self.servername, self.port)
306 "Manage connections to a particular server-port combination."
307 def __init__(self, irkerd, servername, port):
309 self.servername = servername
311 self.connections = []
312 def dispatch(self, channel, message):
313 "Dispatch messages for our server-port combination."
314 # First, check if there is room for another channel
315 # on any of our existing connections.
316 connections = [x for x in self.connections if x.live()]
317 eligibles = [x for x in connections if x.joined_to(channel)] \
318 or [x for x in connections if x.accepting(channel)]
320 eligibles[0].enqueue(channel, message)
322 # All connections are full up. Look for one old enough to be
325 for connection in connections:
326 for (chan, age) in connections.channels_joined.items():
327 if age < time.time() - CHANNEL_TTL:
328 ancients.append((connection, chan, age))
330 ancients.sort(key=lambda x: x[2])
331 (found_connection, drop_channel, _drop_age) = ancients[0]
332 found_connection.part(drop_channel, "scavenged by irkerd")
333 del found_connection.channels_joined[drop_channel]
334 #time.sleep(ANTI_FLOOD_DELAY)
335 found_connection.enqueue(channel, message)
337 # Didn't find any channels with no recent activity
338 newconn = Connection(self.irker,
341 self.connections.append(newconn)
342 newconn.enqueue(channel, message)
344 "Does this server-port combination have any live connections?"
345 self.connections = [x for x in self.connections if x.live()]
346 return len(self.connections) > 0
348 "Return the time of the most recent transmission."
349 return max([x.last_xmit for x in self.connections])
352 "Persistent IRC multiplexer."
353 def __init__(self, debuglevel=0):
354 self.debuglevel = debuglevel
355 self.irc = irc.client.IRC()
356 self.irc.add_global_handler("ping", self._handle_ping)
357 self.irc.add_global_handler("welcome", self._handle_welcome)
358 self.irc.add_global_handler("erroneusnickname", self._handle_badnick)
359 self.irc.add_global_handler("nicknameinuse", self._handle_badnick)
360 self.irc.add_global_handler("nickcollision", self._handle_badnick)
361 self.irc.add_global_handler("unavailresource", self._handle_badnick)
362 self.irc.add_global_handler("featurelist", self._handle_features)
363 self.irc.add_global_handler("disconnect", self._handle_disconnect)
364 self.irc.add_global_handler("kick", self._handle_kick)
365 thread = threading.Thread(target=self.irc.process_forever)
366 thread.setDaemon(True)
367 self.irc._thread = thread
370 def logerr(self, errmsg):
371 "Log a processing error."
372 sys.stderr.write("irkerd: " + errmsg + "\n")
373 def debug(self, level, errmsg):
374 "Debugging information."
375 if self.debuglevel >= level:
376 sys.stderr.write("irkerd: %s\n" % errmsg)
377 def _handle_ping(self, connection, _event):
378 "PING arrived, bump the last-received time for the connection."
379 if connection.context:
380 connection.context.handle_ping()
381 def _handle_welcome(self, connection, _event):
382 "Welcome arrived, nick accepted for this connection."
383 if connection.context:
384 connection.context.handle_welcome()
385 def _handle_badnick(self, connection, _event):
386 "Nick not accepted for this connection."
387 if connection.context:
388 connection.context.handle_badnick()
389 def _handle_features(self, connection, event):
390 "Determine if and how we can set deaf mode."
391 if connection.context:
392 cxt = connection.context
393 for lump in event.arguments():
394 if lump.startswith("DEAF="):
395 connection.mode(cxt.nickname(), "+"+lump[5:])
396 elif lump.startswith("MAXCHANNELS="):
399 cxt.channel_limits[pref] = m
400 self.debug(1, "%s maxchannels is %d"
401 % (connection.server, m))
402 elif lump.startswith("CHANLIMIT=#:"):
403 limits = lump[10:].split(",")
406 (prefixes, limit) = token.split(":")
409 cxt.channel_limits[c] = limit
410 self.debug(1, "%s channel limit map is %s"
411 % (connection.server, cxt.channel_limits))
413 self.logerr("ill-formed CHANLIMIT property")
414 def _handle_disconnect(self, connection, _event):
415 "Server hung up the connection."
416 self.debug(1, "server %s disconnected" % connection.server)
417 if connection.context:
418 connection.context.handle_disconnect()
419 def _handle_kick(self, connection, event):
420 "Server hung up the connection."
421 self.debug(1, "irker has been kicked from %s on %s" % (event.target(), connection.server))
422 if connection.context:
423 connection.context.handle_kick(event.target())
424 def handle(self, line):
425 "Perform a JSON relay request."
427 request = json.loads(line.strip())
428 if not isinstance(request, dict):
429 self.logerr("request is not a JSON dictionary: %r" % request)
430 elif "to" not in request or "privmsg" not in request:
431 self.logerr("malformed request - 'to' or 'privmsg' missing: %r" % request)
433 channels = request['to']
434 message = request['privmsg']
435 if not isinstance(channels, (list, basestring)):
436 self.logerr("malformed request - unexpected channel type: %r" % channels)
437 if not isinstance(message, basestring):
438 self.logerr("malformed request - unexpected message type: %r" % message)
440 if not isinstance(channels, list):
441 channels = [channels]
443 if not isinstance(url, basestring):
444 self.logerr("malformed request - URL has unexpected type: %r" % url)
447 if not target.valid():
449 if target.server() not in self.servers:
450 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
451 self.servers[target.server()].dispatch(target.channel, message)
452 # GC dispatchers with no active connections
453 servernames = self.servers.keys()
454 for servername in servernames:
455 if not self.servers[servername].live():
456 del self.servers[servername]
457 # If we might be pushing a resource limit
458 # even after garbage collection, remove a
459 # session. The goal here is to head off
460 # DoS attacks that aim at exhausting
461 # thread space or file descriptors. The
462 # cost is that attempts to DoS this
463 # service will cause lots of join/leave
464 # spam as we scavenge old channels after
465 # connecting to new ones. The particular
466 # method used for selecting a session to
467 # be terminated doesn't matter much; we
468 # choose the one longest idle on the
469 # assumption that message activity is likely
472 oldtime = float("inf")
473 if len(self.servers) >= CONNECTION_MAX:
474 for (name, server) in self.servers.items():
475 if server.last_xmit() < oldtime:
477 oldtime = server.last_xmit()
478 del self.servers[oldest]
480 self.logerr("can't recognize JSON on input: %r" % line)
482 self.logerr("wildly malformed JSON blew the parser stack.")
484 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
487 line = self.rfile.readline()
490 irker.handle(line.strip())
492 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
494 data = self.request[0].strip()
495 #socket = self.request[1]
498 if __name__ == '__main__':
500 (options, arguments) = getopt.getopt(sys.argv[1:], "d:V")
501 for (opt, val) in options:
502 if opt == '-d': # Enable debug/progress messages
505 logging.basicConfig(level=logging.DEBUG)
506 elif opt == '-V': # Emit version and exit
507 sys.stdout.write("irkerd version %s\n" % version)
509 irker = Irker(debuglevel=debuglvl)
510 irker.debug(1, "irkerd version %s" % version)
512 tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
513 udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
514 for server in [tcpserver, udpserver]:
515 server = threading.Thread(target=server.serve_forever)
516 server.setDaemon(True)
521 except KeyboardInterrupt:
523 except socket.error, e:
524 sys.stderr.write("irkerd: server launch failed: %r\n" % e)