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