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