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