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