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 DISCONNECT_TTL = (24 * 60 * 60) # Time to live, seconds from last connect
34 UNSEEN_TTL = 60 # Time to live, seconds since first request
35 CHANNEL_MAX = 18 # Max channels open per socket (default)
36 ANTI_FLOOD_DELAY = 0.5 # Anti-flood delay after transmissions, seconds
37 ANTI_BUZZ_DELAY = 0.09 # Anti-buzz delay after queue-empty check
39 # No user-serviceable parts below this line
41 # This black magic imports support for green threads (coroutines),
42 # then has kinky sex with the import library internals, replacing
43 # "threading" with a coroutine-using impostor. Threads then become
44 # ultra-light-weight and cooperatively scheduled.
47 eventlet.monkey_patch()
49 # With greenlets we don't worry about thread exhaustion, only the
50 # file descriptor limit (typically 1024 on modern Unixes). Thus we
51 # can handle a lot more concurrent sessions and generate less
52 # join/leave spam under heavy load.
55 # Threads are more expensive if we have to use OS-level ones
56 # rather than greenlets. We need to avoid pushing thread limits
57 # as well as fd limits. See security.txt for discussion.
61 import sys, json, getopt, urlparse, time, random
62 import threading, Queue, SocketServer
63 import irc.client, logging
67 # Sketch of implementation:
69 # One Irker object manages multiple IRC sessions. It holds a map of
70 # Dispatcher objects, one per (server, port) combination, which are
71 # responsible for routing messages to one of any number of Connection
72 # objects that do the actual socket conversations. The reason for the
73 # Dispatcher layer is that IRC daemons limit the number of channels a
74 # client (that is, from the daemon's point of view, a socket) can be
75 # joined to, so each session to a server needs a flock of Connection
76 # instances each with its own socket.
78 # Connections are timed out and removed when either they haven't seen a
79 # PING for a while (indicating that the server may be stalled or down)
80 # or there has been no message traffic to them for a while, or
81 # even if the queue is nonempty but efforts to connect have failed for
84 # There are multiple threads. One accepts incoming traffic from all servers.
85 # Each Connection also has a consumer thread and a thread-safe message queue.
86 # The program main appends messages to queues as JSON requests are received;
87 # the consumer threads try to ship them to servers. When a socket write
88 # stalls, it only blocks an individual consumer thread; if it stalls long
89 # enough, the session will be timed out.
91 # Message delivery is thus not reliable in the face of network stalls,
92 # but this was considered acceptable because IRC (notoriously) has the
93 # same problem - there is little point in reliable delivery to a relay
94 # that is down or unreliable.
96 # This code uses only NICK, JOIN, MODE, and PRIVMSG. It is strictly
97 # compliant to RFC1459, except for the interpretation and use of the
98 # DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features. CHANLIMIT
99 # is as described in the Internet RFC draft
100 # draft-brocklesby-irc-isupport-03 at <http://www.mirc.com/isupport.html>.
103 def __init__(self, irkerd, servername, port):
105 self.servername = servername
107 self.nick_trial = random.randint(1, 990)
108 self.connection = None
109 self.status = "unseen"
110 self.last_xmit = time.time()
111 self.last_ping = time.time()
112 self.channels_joined = []
113 self.channel_limits = {}
114 # The consumer thread
115 self.queue = Queue.Queue()
116 self.thread = threading.Thread(target=self.dequeue)
118 def nickname(self, n=None):
119 "Return a name for the nth server connection."
122 return (NAMESTYLE % n)
123 def handle_ping(self):
124 "Register the fact that the server has pinged this connection."
125 self.last_ping = time.time()
126 def handle_welcome(self):
127 "The server says we're OK, with a non-conflicting nick."
128 self.status = "ready"
129 self.irker.debug(1, "nick %s accepted" % self.nickname())
130 def handle_badnick(self):
131 "The server says our nick has a conflict."
132 self.irker.debug(1, "nick %s rejected" % self.nickname())
133 # Randomness prevents a malicious user or bot from antcipating the
134 # next trial name in order to block us from completing the handshake.
135 self.nick_trial += random.randint(1, 3)
136 self.connection.nick(self.nickname())
137 def handle_disconnect(self):
138 "Server disconnected us for flooding or some other reason."
139 self.connection = None
140 def handle_kick(self, outof):
142 self.status = "handshaking"
143 self.channels_joined.remove(outof)
145 while not self.queue.empty():
146 (channel, message) = self.queue.get()
148 qcopy.append((channel, message))
149 for (channel, message) in qcopy:
150 self.queue.put((channel, message))
151 self.status = "ready"
152 def enqueue(self, channel, message):
153 "Enque a message for transmission."
154 self.queue.put((channel, message))
156 "Try to ship pending messages from the queue."
158 # We want to be kind to the IRC servers and not hold unused
159 # sockets open forever, so they have a time-to-live. The
160 # loop is coded this particular way so that we can drop
161 # the actual server connection when its time-to-live
162 # expires, then reconnect and resume transmission if the
163 # queue fills up again.
164 if not self.connection:
165 self.connection = self.irker.irc.server()
166 self.connection.context = self
168 self.channels_joined = []
169 # This will throw irc.client.ServerConnectionError on failure
171 self.connection.connect(self.servername,
173 nickname=self.nickname(),
175 ircname="irker relaying client")
176 self.status = "handshaking"
177 self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
178 self.last_xmit = time.time()
179 except irc.client.ServerConnectionError:
180 self.status = "disconnected"
181 elif self.status == "handshaking":
182 # Don't buzz on the empty-queue test while we're handshaking
183 time.sleep(ANTI_BUZZ_DELAY)
184 elif self.queue.empty():
185 # Queue is empty, at some point we want to time out
186 # the connection rather than holding a socket open in
187 # the server forever.
189 if now > self.last_xmit + XMIT_TTL \
190 or now > self.last_ping + PING_TTL:
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.close()
194 self.connection = None
195 self.status = "disconnected"
197 # Prevent this thread from hogging the CPU by pausing
198 # for just a little bit after the queue-empty check.
199 # As long as this is less that the duration of a human
200 # reflex arc it is highly unlikely any human will ever
202 time.sleep(ANTI_BUZZ_DELAY)
203 elif self.status == "disconnected" \
204 and time.time() > self.last_xmit + DISCONNECT_TTL:
205 # Queue is nonempty, but the IRC server might be down. Letting
206 # failed connections retain queue space forever would be a
208 self.status = "expired"
210 elif self.status == "unseen" \
211 and time.time() > self.last_xmit + UNSEEN_TTL:
212 # Nasty people could attempt a denial-of-service
213 # attack by flooding us with requests with invalid
214 # servernames. We guard against this by rapidly
215 # expiring connections that have a nonempty queue but
216 # have never had a successful open.
217 self.status = "expired"
219 elif self.status == "ready":
220 (channel, message) = self.queue.get()
221 if channel not in self.channels_joined:
222 self.channels_joined.append(channel)
223 self.connection.join(channel)
224 self.irker.debug(1, "joining %s on %s." % (channel, self.servername))
225 for segment in message.split("\n"):
226 self.connection.privmsg(channel, segment)
227 time.sleep(ANTI_FLOOD_DELAY)
228 self.last_xmit = time.time()
229 self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
230 self.queue.task_done()
232 "Should this connection not be scavenged?"
233 return self.status != "expired"
234 def joined_to(self, channel):
235 "Is this connection joined to the specified channel?"
236 return channel in self.channels_joined
237 def accepting(self, channel):
238 "Can this connection accept a join of this channel?"
239 if self.channel_limits:
241 for already in self.channels_joined:
242 if already[0] == channel[0]:
244 return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
246 return len(self.channels_joined) < CHANNEL_MAX
249 "Represent a transmission target."
250 def __init__(self, url):
251 parsed = urlparse.urlparse(url)
252 irchost, _, ircport = parsed.netloc.partition(':')
255 self.servername = irchost
256 self.channel = parsed.path.lstrip('/')
257 if self.channel and self.channel[0] not in "#&+":
258 self.channel = "#" + self.channel
259 self.port = int(ircport)
261 "Both components must be present for a valid target."
262 return self.servername and self.channel
264 "Return a hashable tuple representing the destination server."
265 return (self.servername, self.port)
268 "Manage connections to a particular server-port combination."
269 def __init__(self, irkerd, servername, port):
271 self.servername = servername
273 self.connections = []
274 def dispatch(self, channel, message):
275 "Dispatch messages for our server-port combination."
276 connections = [x for x in self.connections if x.live()]
277 eligibles = [x for x in connections if x.joined_to(channel)] \
278 or [x for x in connections if x.accepting(channel)]
280 newconn = Connection(self.irker,
283 self.connections.append(newconn)
284 eligibles = [newconn]
285 eligibles[0].enqueue(channel, message)
287 "Does this server-port combination have any live connections?"
288 self.connections = [x for x in self.connections if x.live()]
289 return len(self.connections) > 0
292 "Persistent IRC multiplexer."
293 def __init__(self, debuglevel=0):
294 self.debuglevel = debuglevel
295 self.irc = irc.client.IRC()
296 self.irc.add_global_handler("ping", self._handle_ping)
297 self.irc.add_global_handler("welcome", self._handle_welcome)
298 self.irc.add_global_handler("erroneusnickname", self._handle_badnick)
299 self.irc.add_global_handler("nicknameinuse", self._handle_badnick)
300 self.irc.add_global_handler("nickcollision", self._handle_badnick)
301 self.irc.add_global_handler("unavailresource", self._handle_badnick)
302 self.irc.add_global_handler("featurelist", self._handle_features)
303 self.irc.add_global_handler("disconnect", self._handle_disconnect)
304 self.irc.add_global_handler("kick", self._handle_kick)
305 thread = threading.Thread(target=self.irc.process_forever)
306 self.irc._thread = thread
309 def logerr(self, errmsg):
310 "Log a processing error."
311 sys.stderr.write("irkerd: " + errmsg + "\n")
312 def debug(self, level, errmsg):
313 "Debugging information."
314 if self.debuglevel >= level:
315 sys.stderr.write("irkerd: %s\n" % errmsg)
316 def _handle_ping(self, connection, _event):
317 "PING arrived, bump the last-received time for the connection."
318 if connection.context:
319 connection.context.handle_ping()
320 def _handle_welcome(self, connection, _event):
321 "Welcome arrived, nick accepted for this connection."
322 if connection.context:
323 connection.context.handle_welcome()
324 def _handle_badnick(self, connection, _event):
325 "Nick not accepted for this connection."
326 if connection.context:
327 connection.context.handle_badnick()
328 def _handle_features(self, connection, event):
329 "Determine if and how we can set deaf mode."
330 if connection.context:
331 cxt = connection.context
332 for lump in event.arguments():
333 if lump.startswith("DEAF="):
334 connection.mode(cxt.nickname(), "+"+lump[5:])
335 elif lump.startswith("MAXCHANNELS="):
338 cxt.channel_limits[pref] = m
339 self.debug(1, "%s maxchannels is %d" \
340 % (connection.server, m))
341 elif lump.startswith("CHANLIMIT=#:"):
342 limits = lump[10:].split(",")
345 (prefixes, limit) = token.split(":")
348 cxt.channel_limits[c] = limit
349 self.debug(1, "%s channel limit map is %s" \
350 % (connection.server, cxt.channel_limits))
352 self.logerr("ill-formed CHANLIMIT property")
353 def _handle_disconnect(self, connection, _event):
354 "Server hung up the connection."
355 self.debug(1, "server %s disconnected" % connection.server)
356 if connection.context:
357 connection.context.handle_disconnect()
358 def _handle_kick(self, connection, event):
359 "Server hung up the connection."
360 self.debug(1, "irker has been kicked from %s on %s" % (event.target(), connection.server))
361 if connection.context:
362 connection.context.handle_kick(event.target())
363 def handle(self, line):
364 "Perform a JSON relay request."
366 request = json.loads(line.strip())
367 if type(request) != type({}):
368 self.logerr("request in tot a JSON dictionary: %s" % repr(request))
369 elif "to" not in request or "privmsg" not in request:
370 self.logerr("malformed reqest - 'to' or 'privmsg' missing: %s" % repr(request))
372 channels = request['to']
373 message = request['privmsg']
374 if type(channels) not in (type([]), type(u"")) \
375 or type(message) != type(u""):
376 self.logerr("malformed request - unexpected types: %s" % repr(request))
378 if type(channels) == type(u""):
379 channels = [channels]
381 if type(url) != type(u""):
382 self.logerr("malformed request - unexpected type: %s" % repr(request))
385 if not target.valid():
387 if target.server() not in self.servers:
388 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
389 self.servers[target.server()].dispatch(target.channel, message)
390 # GC dispatchers with no active connections
391 servernames = self.servers.keys()
392 for servername in servernames:
393 if not self.servers[servername].live():
394 del self.servers[servername]
395 # If we might be pushing a resource limit
396 # even after garbage collection, remove a
397 # session. The goal here is to head off
398 # DoS attacks that aim at exhausting
399 # thread space or file descriptors. The
400 # cost is that attempts to DoS this
401 # service will cause lots of join/leave
402 # spam as we scavenge old channels after
403 # connecting to new ones. The particular
404 # method used for selecting a session to
405 # be terminated doesn't matter much; we
406 # choose the one longest idle on the
407 # assumption that message activity is likely
410 if len(self.servers) >= CONNECTION_MAX:
411 for (name, server) in self.servers.items():
412 if not oldest or server.last_xmit < self.servers[oldest].last_xmit:
414 del self.servers[oldest]
416 self.logerr("can't recognize JSON on input: %s" % repr(line))
418 self.logerr("wildly malformed JSON blew the parser stack.")
420 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
423 line = self.rfile.readline()
426 irker.handle(line.strip())
428 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
430 data = self.request[0].strip()
431 #socket = self.request[1]
434 if __name__ == '__main__':
436 (options, arguments) = getopt.getopt(sys.argv[1:], "d:V")
437 for (opt, val) in options:
438 if opt == '-d': # Enable debug/progress messages
441 logging.basicConfig(level=logging.DEBUG)
442 elif opt == '-V': # Emit version and exit
443 sys.stdout.write("irkerd version %s\n" % version)
445 irker = Irker(debuglevel=debuglvl)
446 tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
447 udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
448 threading.Thread(target=tcpserver.serve_forever).start()
449 threading.Thread(target=udpserver.serve_forever).start()
450 # Main thread has to stay alive forever for the cooperative
451 # scheduling of the green threads to work.