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.125 # 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.
46 import eventlet; eventlet.monkey_patch()
48 # With greenlets we don't worry about thread exhaustion, only the
49 # file descriptor limit (typically 1024 on modern Unixes). Thus we
50 # can handle a lot more concurrent sessions and generate less
51 # join/leave spam under heavy load.
54 # Threads are more expensive if we have to use OS-level ones
55 # rather than greenlets. We need to avoid pushing thread limits
56 # as well as fd limits. See security.txt for discussion.
60 import sys, json, getopt, urlparse, time, random
61 import threading, Queue, SocketServer
62 import irc.client, logging
66 # Sketch of implementation:
68 # One Irker object manages multiple IRC sessions. It holds a map of
69 # Dispatcher objects, one per (server, port) combination, which are
70 # responsible for routing messages to one of any number of Connection
71 # objects that do the actual socket conversations. The reason for the
72 # Dispatcher layer is that IRC daemons limit the number of channels a
73 # client (that is, from the daemon's point of view, a socket) can be
74 # joined to, so each session to a server needs a flock of Connection
75 # instances each with its own socket.
77 # Connections are timed out and removed when either they haven't seen a
78 # PING for a while (indicating that the server may be stalled or down)
79 # or there has been no message traffic to them for a while, or
80 # even if the queue is nonempty but efforts to connect have failed for
83 # There are multiple threads. One accepts incoming traffic from all servers.
84 # Each Connection also has a consumer thread and a thread-safe message queue.
85 # The program main appends messages to queues as JSON requests are received;
86 # the consumer threads try to ship them to servers. When a socket write
87 # stalls, it only blocks an individual consumer thread; if it stalls long
88 # enough, the session will be timed out.
90 # Message delivery is thus not reliable in the face of network stalls,
91 # but this was considered acceptable because IRC (notoriously) has the
92 # same problem - there is little point in reliable delivery to a relay
93 # that is down or unreliable.
95 # This code uses only NICK, JOIN, MODE, and PRIVMSG. It is strictly
96 # compliant to RFC1459, except for the interpretation and use of the
97 # DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features. CHANLIMIT
98 # is as described in the Internet RFC draft
99 # draft-brocklesby-irc-isupport-03 at <http://www.mirc.com/isupport.html>.
102 def __init__(self, irkerd, servername, port, nick_base=1):
104 self.servername = servername
106 self.nick_trial = nick_base
107 self.connection = None
108 self.status = "unseen"
109 self.last_xmit = time.time()
110 self.last_ping = time.time()
111 self.channels_joined = []
112 self.channel_limits = {}
113 # The consumer thread
114 self.queue = Queue.Queue()
115 self.thread = threading.Thread(target=self.dequeue)
117 def nickname(self, n=None):
118 "Return a name for the nth server connection."
121 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())
129 def handle_badnick(self):
130 "The server says our nick has a conflict."
131 self.irker.debug(1, "nick %s rejected" % self.nickname())
132 # Randomness prevents a malicious user or bot from antcipating the
133 # next trial name in order to block us from completing the handshake.
134 self.nick_trial += random.randint(1, 3)
135 self.connection.nick(self.nickname())
136 def enqueue(self, channel, message):
137 "Enque a message for transmission."
138 self.queue.put((channel, message))
140 "Try to ship pending messages from the queue."
142 # We want to be kind to the IRC servers and not hold unused
143 # sockets open forever, so they have a time-to-live. The
144 # loop is coded this particular way so that we can drop
145 # the actual server connection when its time-to-live
146 # expires, then reconnect and resume transmission if the
147 # queue fills up again.
148 if not self.connection:
149 self.connection = self.irker.irc.server()
150 self.connection.context = self
152 self.channels_joined = []
153 # This will throw irc.client.ServerConnectionError on failure
155 self.connection.connect(self.servername,
157 nickname=self.nickname(),
159 ircname="irker relaying client")
160 self.status = "handshaking"
161 self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
162 self.last_xmit = time.time()
163 except irc.client.ServerConnectionError:
164 self.status = "disconnected"
165 elif self.status == "handshaking":
166 # Don't buzz on the empty-queue test while we're handshaking
167 time.sleep(ANTI_BUZZ_DELAY)
168 elif self.queue.empty():
169 # Queue is empty, at some point we want to time out
170 # the connection rather than holding a socket open in
171 # the server forever.
173 if now > self.last_xmit + XMIT_TTL \
174 or now > self.last_ping + PING_TTL:
175 self.irker.debug(1, "timing out inactive connection to %s at %s" % (self.servername, time.asctime()))
176 self.connection.context = None
177 self.connection.close()
178 self.connection = None
179 self.status = "disconnected"
181 # Prevent this thread from hogging the CPU by pausing
182 # for just a little bit after the queue-empty check.
183 # As long as this is less that the duration of a human
184 # reflex arc it is highly unlikely any human will ever
186 time.sleep(ANTI_BUZZ_DELAY)
187 elif self.status == "disconnected" \
188 and time.time() > self.last_xmit + DISCONNECT_TTL:
189 # Queue is nonempty, but the IRC server might be down. Letting
190 # failed connections retain queue space forever would be a
192 self.status = "expired"
194 elif self.status == "unseen" \
195 and time.time() > self.last_xmit + UNSEEN_TTL:
196 # Nasty people could attempt a denial-of-service
197 # attack by flooding us with requests with invalid
198 # servernames. We guard against this by rapidly
199 # expiring connections that have a nonempty queue but
200 # have never had a successful open.
201 self.status = "expired"
203 elif self.status == "ready":
204 (channel, message) = self.queue.get()
205 if channel not in self.channels_joined:
206 self.channels_joined.append(channel)
207 self.connection.join(channel)
208 for segment in message.split("\n"):
209 self.connection.privmsg(channel, segment)
210 self.last_xmit = time.time()
211 self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
212 self.queue.task_done()
213 time.sleep(ANTI_FLOOD_DELAY)
215 "Should this connection not be scavenged?"
216 return self.status != "expired"
217 def joined_to(self, channel):
218 "Is this connection joined to the specified channel?"
219 return channel in self.channels_joined
220 def accepting(self, channel):
221 "Can this connection accept a join of this channel?"
222 if self.channel_limits:
224 for already in self.channels_joined:
225 if already[0] == channel[0]:
227 return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
229 return len(self.channels_joined) < CHANNEL_MAX
232 "Represent a transmission target."
233 def __init__(self, url):
234 parsed = urlparse.urlparse(url)
235 irchost, _, ircport = parsed.netloc.partition(':')
238 self.servername = irchost
239 self.channel = parsed.path.lstrip('/')
240 if self.channel and self.channel[0] not in "#&+":
241 self.channel = "#" + self.channel
242 self.port = int(ircport)
244 "Both components must be present for a valid target."
245 return self.servername and self.channel
247 "Return a hashable tuple representing the destination server."
248 return (self.servername, self.port)
251 "Manage connections to a particular server-port combination."
252 def __init__(self, irkerd, servername, port):
254 self.servername = servername
256 self.connections = []
257 def dispatch(self, channel, message):
258 "Dispatch messages for our server-port combination."
259 connections = [x for x in self.connections if x.live()]
260 eligibles = [x for x in connections if x.joined_to(channel)] \
261 or [x for x in connections if x.accepting(channel)]
263 newconn = Connection(self.irker,
266 len(self.connections)+1)
267 self.connections.append(newconn)
268 eligibles = [newconn]
269 eligibles[0].enqueue(channel, message)
271 "Does this server-port combination have any live connections?"
272 self.connections = [x for x in self.connections if x.live()]
273 return len(self.connections) > 0
276 "Persistent IRC multiplexer."
277 def __init__(self, debuglevel=0):
278 self.debuglevel = debuglevel
279 self.irc = irc.client.IRC()
280 self.irc.add_global_handler("ping", self._handle_ping)
281 self.irc.add_global_handler("welcome", self._handle_welcome)
282 self.irc.add_global_handler("erroneusnickname", self._handle_badnick)
283 self.irc.add_global_handler("nicknameinuse", self._handle_badnick)
284 self.irc.add_global_handler("nickcollision", self._handle_badnick)
285 self.irc.add_global_handler("unavailresource", self._handle_badnick)
286 self.irc.add_global_handler("featurelist", self._handle_features)
287 thread = threading.Thread(target=self.irc.process_forever)
288 self.irc._thread = thread
291 def logerr(self, errmsg):
292 "Log a processing error."
293 sys.stderr.write("irkerd: " + errmsg + "\n")
294 def debug(self, level, errmsg):
295 "Debugging information."
296 if self.debuglevel >= level:
297 sys.stderr.write("irkerd: %s\n" % errmsg)
298 def _handle_ping(self, connection, _event):
299 "PING arrived, bump the last-received time for the connection."
300 if connection.context:
301 connection.context.handle_ping()
302 def _handle_welcome(self, connection, _event):
303 "Welcome arrived, nick accepted for this connection."
304 if connection.context:
305 connection.context.handle_welcome()
306 def _handle_badnick(self, connection, _event):
307 "Nick not accepted for this connection."
308 if connection.context:
309 connection.context.handle_badnick()
310 def _handle_features(self, connection, event):
311 "Determine if and how we can set deaf mode."
312 if connection.context:
313 cxt = connection.context
314 for lump in event.arguments():
315 if lump.startswith("DEAF="):
316 connection.mode(cxt.nickname(), "+"+lump[5:])
317 elif lump.startswith("MAXCHANNELS="):
320 cxt.channel_limits[pref] = m
321 self.debug(1, "%s maxchannels is %d" \
322 % (connection.server, m))
323 elif lump.startswith("CHANLIMIT=#:"):
324 limits = lump[10:].split(",")
327 (prefixes, limit) = token.split(":")
330 cxt.channel_limits[c] = limit
331 self.debug(1, "%s channel limit map is %s" \
332 % (connection.server, cxt.channel_limits))
334 self.logerr("ill-formed CHANLIMIT property")
335 def handle(self, line):
336 "Perform a JSON relay request."
338 request = json.loads(line.strip())
339 if type(request) != type({}):
340 self.logerr("request in tot a JSON dictionary: %s" % repr(request))
341 elif "to" not in request or "privmsg" not in request:
342 self.logerr("malformed reqest - 'to' or 'privmsg' missing: %s" % repr(request))
344 channels = request['to']
345 message = request['privmsg']
346 if type(channels) not in (type([]), type(u"")) \
347 or type(message) != type(u""):
348 self.logerr("malformed request - unexpected types: %s" % repr(request))
350 if type(channels) == type(u""):
351 channels = [channels]
353 if type(url) != type(u""):
354 self.logerr("malformed request - unexpected type: %s" % repr(request))
357 if not target.valid():
359 if target.server() not in self.servers:
360 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
361 self.servers[target.server()].dispatch(target.channel, message)
362 # GC dispatchers with no active connections
363 servernames = self.servers.keys()
364 for servername in servernames:
365 if not self.servers[servername].live():
366 del self.servers[servername]
367 # If we might be pushing a resource limit
368 # even after garbage collection, remove a
369 # session. The goal here is to head off
370 # DoS attacks that aim at exhausting
371 # thread space or file descriptors. The
372 # cost is that attempts to DoS this
373 # service will cause lots of join/leave
374 # spam as we scavenge old channels after
375 # connecting to new ones. The particular
376 # method used for selecting a session to
377 # be terminated doesn't matter much; we
378 # choose the one longest idle on the
379 # assumption that message activity is likely
382 if len(self.servers) >= CONNECTION_MAX:
383 for (name, server) in self.servers.items():
384 if not oldest or server.last_xmit < self.servers[oldest].last_xmit:
386 del self.servers[oldest]
388 self.logerr("can't recognize JSON on input: %s" % repr(line))
390 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
393 line = self.rfile.readline()
396 irker.handle(line.strip())
398 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
400 data = self.request[0].strip()
401 #socket = self.request[1]
404 if __name__ == '__main__':
406 (options, arguments) = getopt.getopt(sys.argv[1:], "d:V")
407 for (opt, val) in options:
408 if opt == '-d': # Enable debug/progress messages
411 logging.basicConfig(level=logging.DEBUG)
412 elif opt == '-V': # Emit version and exit
413 sys.stdout.write("irkerd version %s\n" % version)
415 irker = Irker(debuglevel=debuglvl)
416 tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
417 udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
418 threading.Thread(target=tcpserver.serve_forever).start()
419 threading.Thread(target=udpserver.serve_forever).start()
420 # Main thread has to stay alive forever for the cooperative
421 # scheduling of the green threads to work.