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