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