Prepare 1.15 release, with a minor bugfix in the Subversion hook..
[irker.git] / irkerd
1 #!/usr/bin/env python
2 """
3 irkerd - a simple IRC multiplexer daemon
4
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
7 a newline.
8
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.
14
15 Options: -d sets the debug-message level (probably only of interest to
16 developers). The -V option prints the program version and exits.
17
18 Design and code by Eric S. Raymond <esr@thyrsus.com>. See the project
19 resource page at <http://www.catb.org/~esr/irker/>.
20
21 Requires Python 2.6 or 2.5 with the simplejson library installed, and
22 the irc client library at version >= 3.4 which requires 2.6: see
23
24 http://pypi.python.org/pypi/irc/
25 """
26 # These things might need tuning
27
28 HOST = "localhost"
29 PORT = 6659
30
31 NAMESTYLE = "irker%03d"         # IRC nick template - must contain '%d'
32 XMIT_TTL = (3 * 60 * 60)        # Time to live, seconds from last transmit
33 PING_TTL = (15 * 60)            # Time to live, seconds from last PING
34 HANDSHAKE_TTL = 60              # Time to live, seconds from nick transmit
35 CHANNEL_TTL = (3 * 60 * 60)     # Time to live, seconds from last transmit
36 DISCONNECT_TTL = (24 * 60 * 60) # Time to live, seconds from last connect
37 UNSEEN_TTL = 60                 # Time to live, seconds since first request
38 CHANNEL_MAX = 18                # Max channels open per socket (default)
39 ANTI_FLOOD_DELAY = 0.5          # Anti-flood delay after transmissions, seconds
40 ANTI_BUZZ_DELAY = 0.09          # Anti-buzz delay after queue-empty check
41 CONNECTION_MAX = 200            # To avoid hitting a thread limit
42
43 # No user-serviceable parts below this line
44
45 version = "1.15"
46
47 import sys, getopt, urlparse, time, random, socket, signal
48 import threading, Queue, SocketServer
49 import irc.client, logging
50 try:
51     import simplejson as json   # Faster, also makes us Python-2.4-compatible
52 except ImportError:
53     import json
54
55 # Sketch of implementation:
56 #
57 # One Irker object manages multiple IRC sessions.  It holds a map of
58 # Dispatcher objects, one per (server, port) combination, which are
59 # responsible for routing messages to one of any number of Connection
60 # objects that do the actual socket conversations.  The reason for the
61 # Dispatcher layer is that IRC daemons limit the number of channels a
62 # client (that is, from the daemon's point of view, a socket) can be
63 # joined to, so each session to a server needs a flock of Connection
64 # instances each with its own socket.
65 #
66 # Connections are timed out and removed when either they haven't seen a
67 # PING for a while (indicating that the server may be stalled or down)
68 # or there has been no message traffic to them for a while, or
69 # even if the queue is nonempty but efforts to connect have failed for
70 # a long time.
71 #
72 # There are multiple threads. One accepts incoming traffic from all
73 # servers.  Each Connection also has a consumer thread and a
74 # thread-safe message queue.  The program main appends messages to
75 # queues as JSON requests are received; the consumer threads try to
76 # ship them to servers.  When a socket write stalls, it only blocks an
77 # individual consumer thread; if it stalls long enough, the session
78 # will be timed out. This solves the biggest problem with a
79 # single-threaded implementation, which is that you can't count on a
80 # single stalled write not hanging all other traffic - you're at the
81 # mercy of the length of the buffers in the TCP/IP layer.
82 #
83 # Message delivery is thus not reliable in the face of network stalls,
84 # but this was considered acceptable because IRC (notoriously) has the
85 # same problem - there is little point in reliable delivery to a relay
86 # that is down or unreliable.
87 #
88 # This code uses only NICK, JOIN, PART, MODE, and PRIVMSG. It is strictly
89 # compliant to RFC1459, except for the interpretation and use of the
90 # DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features.  CHANLIMIT
91 # is as described in the Internet RFC draft
92 # draft-brocklesby-irc-isupport-03 at <http://www.mirc.com/isupport.html>.
93 # The ",isnick" feature is as described in
94 # <http://ftp.ics.uci.edu/pub/ietf/uri/draft-mirashi-url-irc-01.txt>.
95
96 class Connection:
97     def __init__(self, irkerd, servername, port):
98         self.irker = irkerd
99         self.servername = servername
100         self.port = port
101         self.nick_trial = None
102         self.connection = None
103         self.status = None
104         self.last_xmit = time.time()
105         self.last_ping = time.time()
106         self.channels_joined = {}
107         self.channel_limits = {}
108         # The consumer thread
109         self.queue = Queue.Queue()
110         self.thread = None
111     def nickname(self, n=None):
112         "Return a name for the nth server connection."
113         if n is None:
114             n = self.nick_trial
115         return (NAMESTYLE % n)
116     def handle_ping(self):
117         "Register the fact that the server has pinged this connection."
118         self.last_ping = time.time()
119     def handle_welcome(self):
120         "The server says we're OK, with a non-conflicting nick."
121         self.status = "ready"
122         self.irker.debug(1, "nick %s accepted" % self.nickname())
123     def handle_badnick(self):
124         "The server says our nick has a conflict."
125         self.irker.debug(1, "nick %s rejected" % self.nickname())
126         # Randomness prevents a malicious user or bot from antcipating the
127         # next trial name in order to block us from completing the handshake.
128         self.nick_trial += random.randint(1, 3)
129         self.last_xmit = time.time()
130         self.connection.nick(self.nickname())
131     def handle_disconnect(self):
132         "Server disconnected us for flooding or some other reason."
133         self.connection = None
134         self.status = "disconnected"
135     def handle_kick(self, outof):
136         "We've been kicked."
137         self.status = "handshaking"
138         try:
139             del self.channels_joined[outof]
140         except KeyError:
141             self.irker.logerr("kicked by %s from %s that's not joined"
142                               % (self.servername, outof))
143         qcopy = []
144         while not self.queue.empty():
145             (channel, message) = self.queue.get()
146             if channel != outof:
147                 qcopy.append((channel, message))
148         for (channel, message) in qcopy:
149             self.queue.put((channel, message))
150         self.status = "ready"
151     def enqueue(self, channel, message):
152         "Enque a message for transmission."
153         if self.thread is None or not self.thread.is_alive():
154             self.status = "unseen"
155             self.thread = threading.Thread(target=self.dequeue)
156             self.thread.setDaemon(True)
157             self.thread.start()
158         self.queue.put((channel, message))
159     def dequeue(self):
160         "Try to ship pending messages from the queue."
161         try:
162             while True:
163                 # We want to be kind to the IRC servers and not hold unused
164                 # sockets open forever, so they have a time-to-live.  The
165                 # loop is coded this particular way so that we can drop
166                 # the actual server connection when its time-to-live
167                 # expires, then reconnect and resume transmission if the
168                 # queue fills up again.
169                 if self.queue.empty():
170                     # Queue is empty, at some point we want to time out
171                     # the connection rather than holding a socket open in
172                     # the server forever.
173                     now = time.time()
174                     xmit_timeout = now > self.last_xmit + XMIT_TTL
175                     ping_timeout = now > self.last_ping + PING_TTL
176                     if self.status == "disconnected":
177                         # If the queue is empty, we can drop this connection.
178                         self.status = "expired"
179                         break
180                     elif xmit_timeout or ping_timeout:
181                         self.irker.debug(1, "timing out connection to %s at %s (ping_timeout=%s, xmit_timeout=%s)" % (self.servername, time.asctime(), ping_timeout, xmit_timeout))
182                         with self.irker.irc.mutex:
183                             self.connection.context = None
184                             self.connection.quit("transmission timeout")
185                             self.connection = None
186                         self.status = "disconnected"
187                     else:
188                         # Prevent this thread from hogging the CPU by pausing
189                         # for just a little bit after the queue-empty check.
190                         # As long as this is less that the duration of a human
191                         # reflex arc it is highly unlikely any human will ever
192                         # notice.
193                         time.sleep(ANTI_BUZZ_DELAY)
194                 elif self.status == "disconnected" \
195                          and time.time() > self.last_xmit + DISCONNECT_TTL:
196                     # Queue is nonempty, but the IRC server might be
197                     # down. Letting failed connections retain queue
198                     # space forever would be a memory leak.
199                     self.status = "expired"
200                     break
201                 elif not self.connection:
202                     # Queue is nonempty but server isn't connected.
203                     with self.irker.irc.mutex:
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                         try:
210                             # This will throw
211                             # irc.client.ServerConnectionError on failure
212                             self.connection.connect(self.servername,
213                                                 self.port,
214                                                 nickname=self.nickname(),
215                                                 username="irker",
216                                                 ircname="irker relaying client")
217                             if hasattr(self.connection, "buffer"):
218                                 self.connection.buffer.errors = 'replace'
219                             self.status = "handshaking"
220                             self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
221                             self.last_xmit = time.time()
222                             self.last_ping = time.time()
223                         except irc.client.ServerConnectionError:
224                             self.status = "disconnected"
225                 elif self.status == "handshaking":
226                     if time.time() > self.last_xmit + HANDSHAKE_TTL:
227                         self.status = "expired"
228                         break
229                     else:
230                         # Don't buzz on the empty-queue test while we're
231                         # handshaking
232                         time.sleep(ANTI_BUZZ_DELAY)
233                 elif self.status == "unseen" \
234                          and time.time() > self.last_xmit + UNSEEN_TTL:
235                     # Nasty people could attempt a denial-of-service
236                     # attack by flooding us with requests with invalid
237                     # servernames. We guard against this by rapidly
238                     # expiring connections that have a nonempty queue but
239                     # have never had a successful open.
240                     self.status = "expired"
241                     break
242                 elif self.status == "ready":
243                     (channel, message) = self.queue.get()
244                     if channel not in self.channels_joined:
245                         self.connection.join(channel)
246                         self.irker.debug(1, "joining %s on %s." % (channel, self.servername))
247                     for segment in message.split("\n"):
248                         self.connection.privmsg(channel, segment)
249                         time.sleep(ANTI_FLOOD_DELAY)
250                     self.last_xmit = self.channels_joined[channel] = time.time()
251                     self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
252                     self.queue.task_done()
253         except:
254             (exc_type, _exc_value, exc_traceback) = sys.exc_info()
255             self.irker.logerr("exception %s in thread for %s" % \
256                               (exc_type, self.servername))
257             # This is so we can see tracebacks for errors inside the thread
258             # when we need to be able to for debugging purposes.
259             if debuglvl > 0:
260                 raise exc_type, _exc_value, exc_traceback
261             else:
262                 # Maybe this should have its own status?
263                 self.status = "expired"
264     def live(self):
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:
273             match_count = 0
274             for already in self.channels_joined:
275                 # This obscure code is because the RFCs allow separate limits
276                 # by channel type (indicated by the first character of the name)
277                 # a feature that is almost never actually used.
278                 if already[0] == channel[0]:
279                     match_count += 1
280             return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
281         else:
282             return len(self.channels_joined) < CHANNEL_MAX
283
284 class Target():
285     "Represent a transmission target."
286     def __init__(self, url):
287         # Pre-2.6 Pythons don't recognize irc: as a valid URL prefix.
288         url = url.replace("irc://", "http://")
289         parsed = urlparse.urlparse(url)
290         irchost, _, ircport = parsed.netloc.partition(':')
291         if not ircport:
292             ircport = 6667
293         self.servername = irchost
294         # IRC channel names are case-insensitive.  If we don't smash
295         # case here we may run into problems later. There was a bug
296         # observed on irc.rizon.net where an irkerd user specified #Channel,
297         # got kicked, and irkerd crashed because the server returned
298         # "#channel" in the notification that our kick handler saw.
299         self.channel = parsed.path.lstrip('/').lower()
300         # This deals with a tweak in recent versions of urlparse.
301         if parsed.fragment:
302             self.channel += "#" + parsed.fragment
303         isnick = self.channel.endswith(",isnick")
304         if isnick:
305             self.channel = self.channel[:-7]
306         if self.channel and not isnick and self.channel[0] not in "#&+":
307             self.channel = "#" + self.channel
308         self.port = int(ircport)
309     def valid(self):
310         "Both components must be present for a valid target."
311         return self.servername and self.channel
312     def server(self):
313         "Return a hashable tuple representing the destination server."
314         return (self.servername, self.port)
315
316 class Dispatcher:
317     "Manage connections to a particular server-port combination."
318     def __init__(self, irkerd, servername, port):
319         self.irker = irkerd
320         self.servername = servername
321         self.port = port
322         self.connections = []
323     def dispatch(self, channel, message):
324         "Dispatch messages for our server-port combination."
325         # First, check if there is room for another channel
326         # on any of our existing connections.
327         connections = [x for x in self.connections if x.live()]
328         eligibles = [x for x in connections if x.joined_to(channel)] \
329                     or [x for x in connections if x.accepting(channel)]
330         if eligibles:
331             eligibles[0].enqueue(channel, message)
332             return
333         # All connections are full up. Look for one old enough to be
334         # scavenged.
335         ancients = []
336         for connection in connections:
337             for (chan, age) in connections.channels_joined.items():
338                 if age < time.time() - CHANNEL_TTL:
339                     ancients.append((connection, chan, age))
340         if ancients:
341             ancients.sort(key=lambda x: x[2]) 
342             (found_connection, drop_channel, _drop_age) = ancients[0]
343             found_connection.part(drop_channel, "scavenged by irkerd")
344             del found_connection.channels_joined[drop_channel]
345             #time.sleep(ANTI_FLOOD_DELAY)
346             found_connection.enqueue(channel, message)
347             return
348         # Didn't find any channels with no recent activity
349         newconn = Connection(self.irker,
350                              self.servername,
351                              self.port)
352         self.connections.append(newconn)
353         newconn.enqueue(channel, message)
354     def live(self):
355         "Does this server-port combination have any live connections?"
356         self.connections = [x for x in self.connections if x.live()]
357         return len(self.connections) > 0
358     def last_xmit(self):
359         "Return the time of the most recent transmission."
360         return max(x.last_xmit for x in self.connections)
361
362 class Irker:
363     "Persistent IRC multiplexer."
364     def __init__(self, debuglevel=0):
365         self.debuglevel = debuglevel
366         self.irc = irc.client.IRC()
367         self.irc.add_global_handler("ping", self._handle_ping)
368         self.irc.add_global_handler("welcome", self._handle_welcome)
369         self.irc.add_global_handler("erroneusnickname", self._handle_badnick)
370         self.irc.add_global_handler("nicknameinuse", self._handle_badnick)
371         self.irc.add_global_handler("nickcollision", self._handle_badnick)
372         self.irc.add_global_handler("unavailresource", self._handle_badnick)
373         self.irc.add_global_handler("featurelist", self._handle_features)
374         self.irc.add_global_handler("disconnect", self._handle_disconnect)
375         self.irc.add_global_handler("kick", self._handle_kick)
376         thread = threading.Thread(target=self.irc.process_forever)
377         thread.setDaemon(True)
378         self.irc._thread = thread
379         thread.start()
380         self.servers = {}
381     def logerr(self, errmsg):
382         "Log a processing error."
383         sys.stderr.write("irkerd: " + errmsg + "\n")
384     def debug(self, level, errmsg):
385         "Debugging information."
386         if self.debuglevel >= level:
387             sys.stderr.write("irkerd: %s\n" % errmsg)
388     def _handle_ping(self, connection, _event):
389         "PING arrived, bump the last-received time for the connection."
390         if connection.context:
391             connection.context.handle_ping()
392     def _handle_welcome(self, connection, _event):
393         "Welcome arrived, nick accepted for this connection."
394         if connection.context:
395             connection.context.handle_welcome()
396     def _handle_badnick(self, connection, _event):
397         "Nick not accepted for this connection."
398         if connection.context:
399             connection.context.handle_badnick()
400     def _handle_features(self, connection, event):
401         "Determine if and how we can set deaf mode."
402         if connection.context:
403             cxt = connection.context
404             arguments = event.arguments
405             # irclib 5.0 compatibility, because the maintainer is a fool
406             if callable(arguments):
407                 arguments = arguments()
408             for lump in arguments:
409                 if lump.startswith("DEAF="):
410                     connection.mode(cxt.nickname(), "+"+lump[5:])
411                 elif lump.startswith("MAXCHANNELS="):
412                     m = int(lump[12:])
413                     for pref in "#&+":
414                         cxt.channel_limits[pref] = m
415                     self.debug(1, "%s maxchannels is %d"
416                                % (connection.server, m))
417                 elif lump.startswith("CHANLIMIT=#:"):
418                     limits = lump[10:].split(",")
419                     try:
420                         for token in limits:
421                             (prefixes, limit) = token.split(":")
422                             limit = int(limit)
423                             for c in prefixes:
424                                 cxt.channel_limits[c] = limit
425                         self.debug(1, "%s channel limit map is %s"
426                                    % (connection.server, cxt.channel_limits))
427                     except ValueError:
428                         self.logerr("ill-formed CHANLIMIT property")
429     def _handle_disconnect(self, connection, _event):
430         "Server hung up the connection."
431         self.debug(1, "server %s disconnected" % connection.server)
432         connection.close()
433         if connection.context:
434             connection.context.handle_disconnect()
435     def _handle_kick(self, connection, event):
436         "Server hung up the connection."
437         target = event.target
438         # irclib 5.0 compatibility, because the maintainer continues to be a
439         # fool.
440         if callable(target):
441             target = target()
442         self.debug(1, "irker has been kicked from %s on %s" % (target, connection.server))
443         if connection.context:
444             connection.context.handle_kick(target)
445     def handle(self, line):
446         "Perform a JSON relay request."
447         try:
448             request = json.loads(line.strip())
449             if not isinstance(request, dict):
450                 self.logerr("request is not a JSON dictionary: %r" % request)
451             elif "to" not in request or "privmsg" not in request:
452                 self.logerr("malformed request - 'to' or 'privmsg' missing: %r" % request)
453             else:
454                 channels = request['to']
455                 message = request['privmsg']
456                 if not isinstance(channels, (list, basestring)):
457                     self.logerr("malformed request - unexpected channel type: %r" % channels)
458                 if not isinstance(message, basestring):
459                     self.logerr("malformed request - unexpected message type: %r" % message)
460                 else:
461                     if not isinstance(channels, list):
462                         channels = [channels]
463                     for url in channels:
464                         if not isinstance(url, basestring):
465                             self.logerr("malformed request - URL has unexpected type: %r" % url)
466                         else:
467                             target = Target(url)
468                             if not target.valid():
469                                 return
470                             if target.server() not in self.servers:
471                                 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
472                             self.servers[target.server()].dispatch(target.channel, message)
473                             # GC dispatchers with no active connections
474                             servernames = self.servers.keys()
475                             for servername in servernames:
476                                 if not self.servers[servername].live():
477                                     del self.servers[servername]
478                             # If we might be pushing a resource limit
479                             # even after garbage collection, remove a
480                             # session.  The goal here is to head off
481                             # DoS attacks that aim at exhausting
482                             # thread space or file descriptors.  The
483                             # cost is that attempts to DoS this
484                             # service will cause lots of join/leave
485                             # spam as we scavenge old channels after
486                             # connecting to new ones. The particular
487                             # method used for selecting a session to
488                             # be terminated doesn't matter much; we
489                             # choose the one longest idle on the
490                             # assumption that message activity is likely
491                             # to be clumpy.
492                             if len(self.servers) >= CONNECTION_MAX:
493                                 oldest = min(self.servers.keys(), key=lambda name: self.servers[name].last_xmit())
494                                 del self.servers[oldest]
495         except ValueError:
496             self.logerr("can't recognize JSON on input: %r" % line)
497         except RuntimeError:
498             self.logerr("wildly malformed JSON blew the parser stack.")
499
500 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
501     def handle(self):
502         while True:
503             line = self.rfile.readline()
504             if not line:
505                 break
506             irker.handle(line.strip())
507
508 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
509     def handle(self):
510         data = self.request[0].strip()
511         #socket = self.request[1]
512         irker.handle(data)
513
514 if __name__ == '__main__':
515     debuglvl = 0
516     (options, arguments) = getopt.getopt(sys.argv[1:], "d:V")
517     for (opt, val) in options:
518         if opt == '-d':         # Enable debug/progress messages
519             debuglvl = int(val)
520             if debuglvl > 1:
521                 logging.basicConfig(level=logging.DEBUG)
522         elif opt == '-V':       # Emit version and exit
523             sys.stdout.write("irkerd version %s\n" % version)
524             sys.exit(0)
525     irker = Irker(debuglevel=debuglvl)
526     irker.debug(1, "irkerd version %s" % version)
527     try:
528         tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
529         udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
530         for server in [tcpserver, udpserver]:
531             server = threading.Thread(target=server.serve_forever)
532             server.setDaemon(True)
533             server.start()
534         try:
535             signal.pause()
536         except KeyboardInterrupt:
537             raise SystemExit(1)
538     except socket.error, e:
539         sys.stderr.write("irkerd: server launch failed: %r\n" % e)
540
541 # end