Leave a connection more politely.
[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 and the irc client library at version >= 2.0.2: see
22
23 http://pypi.python.org/pypi/irc/
24 """
25 # These things might need tuning
26
27 HOST = "localhost"
28 PORT = 6659
29
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.5          # Anti-flood delay after transmissions, seconds
37 ANTI_BUZZ_DELAY = 0.09          # Anti-buzz delay after queue-empty check
38
39 # No user-serviceable parts below this line
40
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 imposter.  Threads then become
44 # ultra-light-weight and cooperatively scheduled.
45 try:
46     import eventlet
47     eventlet.monkey_patch()
48     green_threads = True
49     # With greenlets we don't worry about thread exhaustion, only the
50     # file descriptor limit (typically 1024 on modern Unixes). Thus we
51     # can handle a lot more concurrent sessions and generate less
52     # join/leave spam under heavy load.
53     CONNECTION_MAX = 1000
54 except ImportError:
55     # Threads are more expensive if we have to use OS-level ones
56     # rather than greenlets.  We need to avoid pushing thread limits
57     # as well as fd limits.  See security.txt for discussion.
58     CONNECTION_MAX = 200
59     green_threads = False
60
61 import sys, getopt, urlparse, time, random
62 import threading, Queue, SocketServer
63 import irc.client, logging
64 try:
65     import simplejson as json   # Faster, also makes us Python-2.4-compatible
66 except ImportError:
67     import json
68
69 version = "1.6"
70
71 # Sketch of implementation:
72 #
73 # One Irker object manages multiple IRC sessions.  It holds a map of
74 # Dispatcher objects, one per (server, port) combination, which are
75 # responsible for routing messages to one of any number of Connection
76 # objects that do the actual socket conversations.  The reason for the
77 # Dispatcher layer is that IRC daemons limit the number of channels a
78 # client (that is, from the daemon's point of view, a socket) can be
79 # joined to, so each session to a server needs a flock of Connection
80 # instances each with its own socket.
81 #
82 # Connections are timed out and removed when either they haven't seen a
83 # PING for a while (indicating that the server may be stalled or down)
84 # or there has been no message traffic to them for a while, or
85 # even if the queue is nonempty but efforts to connect have failed for
86 # a long time.
87 #
88 # There are multiple threads. One accepts incoming traffic from all servers.
89 # Each Connection also has a consumer thread and a thread-safe message queue.
90 # The program main appends messages to queues as JSON requests are received;
91 # the consumer threads try to ship them to servers.  When a socket write
92 # stalls, it only blocks an individual consumer thread; if it stalls long
93 # enough, the session will be timed out.
94 #
95 # Message delivery is thus not reliable in the face of network stalls,
96 # but this was considered acceptable because IRC (notoriously) has the
97 # same problem - there is little point in reliable delivery to a relay
98 # that is down or unreliable.
99 #
100 # This code uses only NICK, JOIN, MODE, and PRIVMSG. It is strictly
101 # compliant to RFC1459, except for the interpretation and use of the
102 # DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features.  CHANLIMIT
103 # is as described in the Internet RFC draft
104 # draft-brocklesby-irc-isupport-03 at <http://www.mirc.com/isupport.html>.
105
106 class Connection:
107     def __init__(self, irkerd, servername, port):
108         self.irker = irkerd
109         self.servername = servername
110         self.port = port
111         self.nick_trial = None
112         self.connection = None
113         self.status = "unseen"
114         self.last_xmit = time.time()
115         self.last_ping = time.time()
116         self.channels_joined = []
117         self.channel_limits = {}
118         # The consumer thread
119         self.queue = Queue.Queue()
120         self.thread = threading.Thread(target=self.dequeue)
121         self.thread.setDaemon(True)
122         self.thread.start()
123     def nickname(self, n=None):
124         "Return a name for the nth server connection."
125         if n is None:
126             n = self.nick_trial
127         return (NAMESTYLE % n)
128     def handle_ping(self):
129         "Register the fact that the server has pinged this connection."
130         self.last_ping = time.time()
131     def handle_welcome(self):
132         "The server says we're OK, with a non-conflicting nick."
133         self.status = "ready"
134         self.irker.debug(1, "nick %s accepted" % self.nickname())
135     def handle_badnick(self):
136         "The server says our nick has a conflict."
137         self.irker.debug(1, "nick %s rejected" % self.nickname())
138         # Randomness prevents a malicious user or bot from antcipating the
139         # next trial name in order to block us from completing the handshake.
140         self.nick_trial += random.randint(1, 3)
141         self.connection.nick(self.nickname())
142     def handle_disconnect(self):
143         "Server disconnected us for flooding or some other reason."
144         self.connection = None
145     def handle_kick(self, outof):
146         "We've been kicked."
147         self.status = "handshaking"
148         try:
149             self.channels_joined.remove(outof)
150         except ValueError:
151             self.irker.logerr("kicked by %s from %s that's not joined"
152                               % (self.servername, outof))
153         qcopy = []
154         while not self.queue.empty():
155             (channel, message) = self.queue.get()
156             if channel != outof:
157                 qcopy.append((channel, message))
158         for (channel, message) in qcopy:
159             self.queue.put((channel, message))
160         self.status = "ready"
161     def enqueue(self, channel, message):
162         "Enque a message for transmission."
163         self.queue.put((channel, message))
164     def dequeue(self):
165         "Try to ship pending messages from the queue."
166         while True:
167             # We want to be kind to the IRC servers and not hold unused
168             # sockets open forever, so they have a time-to-live.  The
169             # loop is coded this particular way so that we can drop
170             # the actual server connection when its time-to-live
171             # expires, then reconnect and resume transmission if the
172             # queue fills up again.
173             if not self.connection:
174                 self.connection = self.irker.irc.server()
175                 self.connection.context = self
176                 # Try to avoid colliding with other instances
177                 self.nick_trial = random.randint(1, 990)
178                 self.channels_joined = []
179                 # This will throw irc.client.ServerConnectionError on failure
180                 try:
181                     self.connection.connect(self.servername,
182                                         self.port,
183                                         nickname=self.nickname(),
184                                         username="irker",
185                                         ircname="irker relaying client")
186                     self.status = "handshaking"
187                     self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
188                     self.last_xmit = time.time()
189                 except irc.client.ServerConnectionError:
190                     self.status = "disconnected"
191             elif self.status == "handshaking":
192                 # Don't buzz on the empty-queue test while we're handshaking 
193                 time.sleep(ANTI_BUZZ_DELAY)
194             elif self.queue.empty():
195                 # Queue is empty, at some point we want to time out
196                 # the connection rather than holding a socket open in
197                 # the server forever.
198                 now = time.time()
199                 if now > self.last_xmit + XMIT_TTL \
200                        or now > self.last_ping + PING_TTL:
201                     self.irker.debug(1, "timing out inactive connection to %s at %s" % (self.servername, time.asctime()))
202                     self.connection.context = None
203                     self.connection.quit("transmission timeout")
204                     self.connection.close()
205                     self.connection = None
206                     self.status = "disconnected"
207                 else:
208                     # Prevent this thread from hogging the CPU by pausing
209                     # for just a little bit after the queue-empty check.
210                     # As long as this is less that the duration of a human
211                     # reflex arc it is highly unlikely any human will ever
212                     # notice.
213                     time.sleep(ANTI_BUZZ_DELAY)
214             elif self.status == "disconnected" \
215                      and time.time() > self.last_xmit + DISCONNECT_TTL:
216                 # Queue is nonempty, but the IRC server might be down. Letting
217                 # failed connections retain queue space forever would be a
218                 # memory leak.  
219                 self.status = "expired"
220                 break
221             elif self.status == "unseen" \
222                      and time.time() > self.last_xmit + UNSEEN_TTL:
223                 # Nasty people could attempt a denial-of-service
224                 # attack by flooding us with requests with invalid
225                 # servernames. We guard against this by rapidly
226                 # expiring connections that have a nonempty queue but
227                 # have never had a successful open.
228                 self.status = "expired"
229                 break
230             elif self.status == "ready":
231                 (channel, message) = self.queue.get()
232                 if channel not in self.channels_joined:
233                     self.channels_joined.append(channel)
234                     self.connection.join(channel)
235                     self.irker.debug(1, "joining %s on %s." % (channel, self.servername))
236                 for segment in message.split("\n"):
237                     self.connection.privmsg(channel, segment)
238                     time.sleep(ANTI_FLOOD_DELAY)
239                 self.last_xmit = time.time()
240                 self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
241                 self.queue.task_done()
242     def live(self):
243         "Should this connection not be scavenged?"
244         return self.status != "expired"
245     def joined_to(self, channel):
246         "Is this connection joined to the specified channel?"
247         return channel in self.channels_joined
248     def accepting(self, channel):
249         "Can this connection accept a join of this channel?"
250         if self.channel_limits:
251             match_count = 0
252             for already in self.channels_joined:
253                 if already[0] == channel[0]:
254                     match_count += 1
255             return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
256         else:
257             return len(self.channels_joined) < CHANNEL_MAX
258
259 class Target():
260     "Represent a transmission target."
261     def __init__(self, url):
262         parsed = urlparse.urlparse(url)
263         irchost, _, ircport = parsed.netloc.partition(':')
264         if not ircport:
265             ircport = 6667
266         self.servername = irchost
267         # IRC channel names are case-insensitive.  If we don't smash
268         # case here we may run into problems later. There was a bug
269         # observed on irc.rizon.net where an irkerd user specified #Channel,
270         # got kicked, and irkerd crashed because the server returned
271         # "#channel" in the notification that our kick handler saw.
272         self.channel = parsed.path.lstrip('/').lower()
273         if self.channel and self.channel[0] not in "#&+":
274             self.channel = "#" + self.channel
275         self.port = int(ircport)
276     def valid(self):
277         "Both components must be present for a valid target."
278         return self.servername and self.channel
279     def server(self):
280         "Return a hashable tuple representing the destination server."
281         return (self.servername, self.port)
282
283 class Dispatcher:
284     "Manage connections to a particular server-port combination."
285     def __init__(self, irkerd, servername, port):
286         self.irker = irkerd
287         self.servername = servername
288         self.port = port
289         self.connections = []
290     def dispatch(self, channel, message):
291         "Dispatch messages for our server-port combination."
292         connections = [x for x in self.connections if x.live()]
293         eligibles = [x for x in connections if x.joined_to(channel)] \
294                     or [x for x in connections if x.accepting(channel)]
295         if not eligibles:
296             newconn = Connection(self.irker,
297                                  self.servername,
298                                  self.port)
299             self.connections.append(newconn)
300             eligibles = [newconn]
301         eligibles[0].enqueue(channel, message)
302     def live(self):
303         "Does this server-port combination have any live connections?"
304         self.connections = [x for x in self.connections if x.live()]
305         return len(self.connections) > 0
306     def last_xmit(self):
307         "Return the time of the most recent transmission."
308         return max([x.last_xmit for x in self.connections])
309
310 class Irker:
311     "Persistent IRC multiplexer."
312     def __init__(self, debuglevel=0):
313         self.debuglevel = debuglevel
314         self.irc = irc.client.IRC()
315         self.irc.add_global_handler("ping", self._handle_ping)
316         self.irc.add_global_handler("welcome", self._handle_welcome)
317         self.irc.add_global_handler("erroneusnickname", self._handle_badnick)
318         self.irc.add_global_handler("nicknameinuse", self._handle_badnick)
319         self.irc.add_global_handler("nickcollision", self._handle_badnick)
320         self.irc.add_global_handler("unavailresource", self._handle_badnick)
321         self.irc.add_global_handler("featurelist", self._handle_features)
322         self.irc.add_global_handler("disconnect", self._handle_disconnect)
323         self.irc.add_global_handler("kick", self._handle_kick)
324         thread = threading.Thread(target=self.irc.process_forever)
325         thread.setDaemon(True)
326         self.irc._thread = thread
327         thread.start()
328         self.servers = {}
329     def logerr(self, errmsg):
330         "Log a processing error."
331         sys.stderr.write("irkerd: " + errmsg + "\n")
332     def debug(self, level, errmsg):
333         "Debugging information."
334         if self.debuglevel >= level:
335             sys.stderr.write("irkerd: %s\n" % errmsg)
336     def _handle_ping(self, connection, _event):
337         "PING arrived, bump the last-received time for the connection."
338         if connection.context:
339             connection.context.handle_ping()
340     def _handle_welcome(self, connection, _event):
341         "Welcome arrived, nick accepted for this connection."
342         if connection.context:
343             connection.context.handle_welcome()
344     def _handle_badnick(self, connection, _event):
345         "Nick not accepted for this connection."
346         if connection.context:
347             connection.context.handle_badnick()
348     def _handle_features(self, connection, event):
349         "Determine if and how we can set deaf mode."
350         if connection.context:
351             cxt = connection.context
352             for lump in event.arguments():
353                 if lump.startswith("DEAF="):
354                     connection.mode(cxt.nickname(), "+"+lump[5:])
355                 elif lump.startswith("MAXCHANNELS="):
356                     m = int(lump[12:])
357                     for pref in "#&+":
358                         cxt.channel_limits[pref] = m
359                     self.debug(1, "%s maxchannels is %d"
360                                % (connection.server, m))
361                 elif lump.startswith("CHANLIMIT=#:"):
362                     limits = lump[10:].split(",")
363                     try:
364                         for token in limits:
365                             (prefixes, limit) = token.split(":")
366                             limit = int(limit)
367                             for c in prefixes:
368                                 cxt.channel_limits[c] = limit
369                         self.debug(1, "%s channel limit map is %s"
370                                    % (connection.server, cxt.channel_limits))
371                     except ValueError:
372                         self.logerr("ill-formed CHANLIMIT property")
373     def _handle_disconnect(self, connection, _event):
374         "Server hung up the connection."
375         self.debug(1, "server %s disconnected" % connection.server)
376         if connection.context:
377             connection.context.handle_disconnect()
378     def _handle_kick(self, connection, event):
379         "Server hung up the connection."
380         self.debug(1, "irker has been kicked from %s on %s" % (event.target(), connection.server))
381         if connection.context:
382             connection.context.handle_kick(event.target())
383     def handle(self, line):
384         "Perform a JSON relay request."
385         try:
386             request = json.loads(line.strip())
387             if not isinstance(request, dict):
388                 self.logerr("request is not a JSON dictionary: %r" % request)
389             elif "to" not in request or "privmsg" not in request:
390                 self.logerr("malformed request - 'to' or 'privmsg' missing: %r" % request)
391             else:
392                 channels = request['to']
393                 message = request['privmsg']
394                 if not isinstance(channels, (list, unicode)) \
395                        and not isinstance(message, unicode):
396                     self.logerr("malformed request - unexpected types: %r" % request)
397                 else:
398                     if isinstance(channels, unicode):
399                         channels = [channels]
400                     for url in channels:
401                         if not type(url) in (type(""), type(u"")): 
402                             self.logerr("malformed request - URL has unexpected type: %r" % url)
403                         else:
404                             target = Target(url)
405                             if not target.valid():
406                                 return
407                             if target.server() not in self.servers:
408                                 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
409                             self.servers[target.server()].dispatch(target.channel, message)
410                             # GC dispatchers with no active connections
411                             servernames = self.servers.keys()
412                             for servername in servernames:
413                                 if not self.servers[servername].live():
414                                     del self.servers[servername]
415                             # If we might be pushing a resource limit
416                             # even after garbage collection, remove a
417                             # session.  The goal here is to head off
418                             # DoS attacks that aim at exhausting
419                             # thread space or file descriptors.  The
420                             # cost is that attempts to DoS this
421                             # service will cause lots of join/leave
422                             # spam as we scavenge old channels after
423                             # connecting to new ones. The particular
424                             # method used for selecting a session to
425                             # be terminated doesn't matter much; we
426                             # choose the one longest idle on the
427                             # assumption that message activity is likely
428                             # to be clumpy.
429                             oldest = None
430                             oldtime = float("inf")
431                             if len(self.servers) >= CONNECTION_MAX:
432                                 for (name, server) in self.servers.items():
433                                     if server.last_xmit() < oldtime:
434                                         oldest = name
435                                         oldtime = server.last_xmit()
436                                 del self.servers[oldest]
437         except ValueError:
438             self.logerr("can't recognize JSON on input: %r" % line)
439         except RuntimeError:
440             self.logerr("wildly malformed JSON blew the parser stack.")
441
442 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
443     def handle(self):
444         while True:
445             line = self.rfile.readline()
446             if not line:
447                 break
448             irker.handle(line.strip())
449
450 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
451     def handle(self):
452         data = self.request[0].strip()
453         #socket = self.request[1]
454         irker.handle(data)
455
456 if __name__ == '__main__':
457     debuglvl = 0
458     (options, arguments) = getopt.getopt(sys.argv[1:], "d:V")
459     for (opt, val) in options:
460         if opt == '-d':         # Enable debug/progress messages
461             debuglvl = int(val)
462             if debuglvl > 1:
463                 logging.basicConfig(level=logging.DEBUG)
464         elif opt == '-V':       # Emit version and exit
465             sys.stdout.write("irkerd version %s\n" % version)
466             sys.exit(0)
467     irker = Irker(debuglevel=debuglvl)
468     irker.debug(1, "irkerd version %s" % version)
469     tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
470     udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
471     for server in [tcpserver, udpserver]:
472         server = threading.Thread(target=server.serve_forever)
473         server.setDaemon(True)
474         server.start()
475     try:
476         while True:
477             time.sleep(10)
478     except KeyboardInterrupt:
479         raise SystemExit(1)
480
481 # end