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