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