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 import sys, json, getopt, urlparse, time, random
42 import threading, Queue, SocketServer
43 import irc.client, logging
47 # Sketch of implementation:
49 # One Irker object manages multiple IRC sessions. It holds a map of
50 # Dispatcher objects, one per (server, port) combination, which are
51 # responsible for routing messages to one of any number of Connection
52 # objects that do the actual socket conversations. The reason for the
53 # Dispatcher layer is that IRC daemons limit the number of channels a
54 # client (that is, from the daemon's point of view, a socket) can be
55 # joined to, so each session to a server needs a flock of Connection
56 # instances each with its own socket.
58 # Connections are timed out and removed when either they haven't seen a
59 # PING for a while (indicating that the server may be stalled or down)
60 # or there has been no message traffic to them for a while, or
61 # even if the queue is nonempty but efforts to connect have failed for
64 # There are multiple threads. One accepts incoming traffic from all servers.
65 # Each Connection also has a consumer thread and a thread-safe message queue.
66 # The program main appends messages to queues as JSON requests are received;
67 # the consumer threads try to ship them to servers. When a socket write
68 # stalls, it only blocks an individual consumer thread; if it stalls long
69 # enough, the session will be timed out.
71 # Message delivery is thus not reliable in the face of network stalls,
72 # but this was considered acceptable because IRC (notoriously) has the
73 # same problem - there is little point in reliable delivery to a relay
74 # that is down or unreliable.
76 # This code uses only NICK, JOIN, MODE, and PRIVMSG. It is strictly
77 # compliant to RFC1459, except for the interpretation and use of the
78 # DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features. CHANLIMIT
79 # is as described in the Internet RFC draft
80 # draft-brocklesby-irc-isupport-03 at <http://www.mirc.com/isupport.html>.
83 def __init__(self, irkerd, servername, port, nick_base=1):
85 self.servername = servername
87 self.nick_trial = nick_base
88 self.connection = None
89 self.status = "unseen"
90 self.last_xmit = time.time()
91 self.last_ping = time.time()
92 self.channels_joined = []
93 self.channel_limits = {}
95 self.queue = Queue.Queue()
96 self.thread = threading.Thread(target=self.dequeue)
98 def nickname(self, n=None):
99 "Return a name for the nth server connection."
102 return (NAMESTYLE % n)
103 def handle_ping(self):
104 "Register the fact that the server has pinged this connection."
105 self.last_ping = time.time()
106 def handle_welcome(self):
107 "The server says we're OK, with a non-conflicting nick."
108 self.status = "ready"
109 self.irker.debug(1, "nick %s accepted" % self.nickname())
110 def handle_badnick(self):
111 "The server says our nick has a conflict."
112 self.irker.debug(1, "nick %s rejected" % self.nickname())
113 # Randomness prevents a malicious user or bot from antcipating the
114 # next trial name in order to block us from completing the handshake.
115 self.nick_trial += random.randint(1, 3)
116 self.connection.nick(self.nickname())
117 def enqueue(self, channel, message):
118 "Enque a message for transmission."
119 self.queue.put((channel, message))
121 "Try to ship pending messages from the queue."
123 # We want to be kind to the IRC servers and not hold unused
124 # sockets open forever, so they have a time-to-live. The
125 # loop is coded this particular way so that we can drop
126 # the actual server connection when its time-to-live
127 # expires, then reconnect and resume transmission if the
128 # queue fills up again.
129 if not self.connection:
130 self.connection = self.irker.irc.server()
131 self.connection.context = self
133 self.channels_joined = []
134 # This will throw irc.client.ServerConnectionError on failure
136 self.connection.connect(self.servername,
138 nickname=self.nickname(),
140 ircname="irker relaying client")
141 self.status = "handshaking"
142 self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
143 self.last_xmit = time.time()
144 except irc.client.ServerConnectionError:
145 self.status = "disconnected"
146 elif self.status == "handshaking":
147 # Don't buzz on the empty-queue test while we're handshaking
148 time.sleep(ANTI_BUZZ_DELAY)
149 elif self.queue.empty():
150 # Queue is empty, at some point we want to time out
151 # the connection rather than holding a socket open in
152 # the server forever.
154 if now > self.last_xmit + XMIT_TTL \
155 or now > self.last_ping + PING_TTL:
156 self.irker.debug(1, "timing out inactive connection to %s at %s" % (self.servername, time.asctime()))
157 self.connection.context = None
158 self.connection.close()
159 self.connection = None
160 self.status = "disconnected"
162 # Prevent this thread from hogging the CPU by pausing
163 # for just a little bit after the queue-empty check.
164 # As long as this is less that the duration of a human
165 # reflex arc it is highly unlikely any human will ever
167 time.sleep(ANTI_BUZZ_DELAY)
168 elif self.status == "disconnected" \
169 and time.time() > self.last_xmit + DISCONNECT_TTL:
170 # Queue is nonempty, but the IRC server might be down. Letting
171 # failed connections retain queue space forever would be a
173 self.status = "expired"
175 elif self.status == "unseen" \
176 and time.time() > self.last_xmit + UNSEEN_TTL:
177 # Nasty people could attempt a denial-of-service
178 # attack by flooding us with requests with invalid
179 # servernames. We guard against this by rapidly
180 # expiring connections that have a nonempty queue but
181 # have never had a successful open.
182 self.status = "expired"
184 elif self.status == "ready":
185 (channel, message) = self.queue.get()
186 if channel not in self.channels_joined:
187 self.channels_joined.append(channel)
188 if channel[0] not in "#&+":
189 channel = "#" + channel
190 self.connection.join(channel)
191 for segment in message.split("\n"):
192 self.connection.privmsg(channel, segment)
193 self.last_xmit = time.time()
194 self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
195 self.queue.task_done()
196 time.sleep(ANTI_FLOOD_DELAY)
198 "Should this connection not be scavenged?"
199 return self.status != "expired"
200 def joined_to(self, channel):
201 "Is this connection joined to the specified channel?"
202 return channel in self.channels_joined
203 def accepting(self, channel):
204 "Can this connection accept a join of this channel?"
205 if self.channel_limits:
207 for already in self.channels_joined:
208 if already[0] == channel[0]:
210 return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
212 return len(self.channels_joined) < CHANNEL_MAX
215 "Represent a transmission target."
216 def __init__(self, url):
217 parsed = urlparse.urlparse(url)
218 irchost, _, ircport = parsed.netloc.partition(':')
221 self.servername = irchost
222 self.channel = parsed.path.lstrip('/')
223 self.port = int(ircport)
225 "Return a hashable tuple representing the destination server."
226 return (self.servername, self.port)
229 "Manage connections to a particular server-port combination."
230 def __init__(self, irkerd, servername, port):
232 self.servername = servername
234 self.connections = []
235 def dispatch(self, channel, message):
236 "Dispatch messages for our server-port combination."
237 connections = [x for x in self.connections if x.live()]
238 eligibles = [x for x in connections if x.joined_to(channel)] \
239 or [x for x in connections if x.accepting(channel)]
241 newconn = Connection(self.irker,
244 len(self.connections)+1)
245 self.connections.append(newconn)
246 eligibles = [newconn]
247 eligibles[0].enqueue(channel, message)
249 "Does this server-port combination have any live connections?"
250 self.connections = [x for x in self.connections if x.live()]
251 return len(self.connections) > 0
254 "Persistent IRC multiplexer."
255 def __init__(self, debuglevel=0):
256 self.debuglevel = debuglevel
257 self.irc = irc.client.IRC()
258 self.irc.add_global_handler("ping", self._handle_ping)
259 self.irc.add_global_handler("welcome", self._handle_welcome)
260 self.irc.add_global_handler("erroneusnickname", self._handle_badnick)
261 self.irc.add_global_handler("nicknameinuse", self._handle_badnick)
262 self.irc.add_global_handler("nickcollision", self._handle_badnick)
263 self.irc.add_global_handler("unavailresource", self._handle_badnick)
264 self.irc.add_global_handler("featurelist", self._handle_features)
265 thread = threading.Thread(target=self.irc.process_forever)
266 self.irc._thread = thread
269 def logerr(self, errmsg):
270 "Log a processing error."
271 sys.stderr.write("irkerd: " + errmsg + "\n")
272 def debug(self, level, errmsg):
273 "Debugging information."
274 if self.debuglevel >= level:
275 sys.stderr.write("irkerd: %s\n" % errmsg)
276 def _handle_ping(self, connection, _event):
277 "PING arrived, bump the last-received time for the connection."
278 if connection.context:
279 connection.context.handle_ping()
280 def _handle_welcome(self, connection, _event):
281 "Welcome arrived, nick accepted for this connection."
282 if connection.context:
283 connection.context.handle_welcome()
284 def _handle_badnick(self, connection, _event):
285 "Nick not accepted for this connection."
286 if connection.context:
287 connection.context.handle_badnick()
288 def _handle_features(self, connection, event):
289 "Determine if and how we can set deaf mode."
290 if connection.context:
291 cxt = connection.context
292 for lump in event.arguments():
293 if lump.startswith("DEAF="):
294 connection.mode(cxt.nickname(), "+"+lump[5:])
295 elif lump.startswith("MAXCHANNELS="):
298 cxt.channel_limits[pref] = m
299 self.debug(1, "%s maxchannels is %d" \
300 % (connection.server, m))
301 elif lump.startswith("CHANLIMIT=#:"):
302 limits = lump[10:].split(",")
305 (prefixes, limit) = token.split(":")
308 cxt.channel_limits[c] = limit
309 self.debug(1, "%s channel limit map is %s" \
310 % (connection.server, cxt.channel_limits))
312 self.logerr("ill-formed CHANLIMIT property")
313 def handle(self, line):
314 "Perform a JSON relay request."
316 request = json.loads(line.strip())
317 if type(request) != type({}):
318 self.logerr("request in tot a JSON dictionary: %s" % repr(request))
319 elif "to" not in request or "privmsg" not in request:
320 self.logerr("malformed reqest - 'to' or 'privmsg' missing: %s" % repr(request))
322 channels = request['to']
323 message = request['privmsg']
324 if type(channels) not in (type([]), type(u"")) \
325 or type(message) != type(u""):
326 self.logerr("malformed request - unexpected types: %s" % repr(request))
328 if type(channels) == type(u""):
329 channels = [channels]
331 if type(url) != type(u""):
332 self.logerr("malformed request - unexpected type: %s" % repr(request))
335 if target.server() not in self.servers:
336 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
337 self.servers[target.server()].dispatch(target.channel, message)
338 # GC dispatchers with no active connections
339 servernames = self.servers.keys()
340 for servername in servernames:
341 if not self.servers[servername].live():
342 del self.servers[servername]
344 self.logerr("can't recognize JSON on input: %s" % repr(line))
346 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
349 line = self.rfile.readline()
352 irker.handle(line.strip())
354 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
356 data = self.request[0].strip()
357 #socket = self.request[1]
360 if __name__ == '__main__':
362 (options, arguments) = getopt.getopt(sys.argv[1:], "d:V")
363 for (opt, val) in options:
364 if opt == '-d': # Enable debug/progress messages
367 logging.basicConfig(level=logging.DEBUG)
368 elif opt == '-V': # Emit version and exit
369 sys.stdout.write("irkerd version %s\n" % version)
371 irker = Irker(debuglevel=debuglvl)
372 tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
373 udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
374 threading.Thread(target=tcpserver.serve_forever).start()
375 threading.Thread(target=udpserver.serve_forever).start()