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