Another anti-buzz delay.
[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://sourceforge.net/projects/python-irclib
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 import sys, json, getopt, urlparse, time
42 import threading, Queue, SocketServer
43 import irc.client, logging
44
45 version = "1.1"
46
47 # Sketch of implementation:
48 #
49 # One Irker object manages multiple IRC sessions.  It holds a map of
50 # Dispatcher objects, one per (server, port) combination, which are
51 # responsible for routing messages to one of any number of Connection
52 # objects that do the actual socket conversations.  The reason for the
53 # Dispatcher layer is that IRC daemons limit the number of channels a
54 # client (that is, from the daemon's point of view, a socket) can be
55 # joined to, so each session to a server needs a flock of Connection
56 # instances each with its own socket.
57 #
58 # Connections are timed out and removed when either they haven't seen a
59 # PING for a while (indicating that the server may be stalled or down)
60 # or there has been no message traffic to them for a while, or
61 # even if the queue is nonempty but efforts to connect have failed for
62 # a long time.
63 #
64 # There are multiple threads. One accepts incoming traffic from all servers.
65 # Each Connection also has a consumer thread and a thread-safe message queue.
66 # The program main appends messages to queues as JSON requests are received;
67 # the consumer threads try to ship them to servers.  When a socket write
68 # stalls, it only blocks an individual consumer thread; if it stalls long
69 # enough, the session will be timed out.
70 #
71 # Message delivery is thus not reliable in the face of network stalls,
72 # but this was considered acceptable because IRC (notoriously) has the
73 # same problem - there is little point in reliable delivery to a relay
74 # that is down or unreliable.
75 #
76 # This code uses only NICK, JOIN, MODE, and PRIVMSG. It is strictly
77 # compliant to RFC1459, except for the interpretation and use of the
78 # DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features.  CHANLIMIT
79 # is as described in the Internet RFC draft
80 # draft-brocklesby-irc-isupport-03 at <http://www.mirc.com/isupport.html>.
81
82 class Connection:
83     def __init__(self, irkerd, servername, port, nick_base=1):
84         self.irker = irkerd
85         self.servername = servername
86         self.port = port
87         self.nick_trial = nick_base
88         self.connection = None
89         self.status = "unseen"
90         self.last_xmit = time.time()
91         self.last_ping = time.time()
92         self.channels_joined = []
93         self.channel_limits = {}
94         # The consumer thread
95         self.queue = Queue.Queue()
96         self.thread = threading.Thread(target=self.dequeue)
97         self.thread.start()
98     def nickname(self, n=None):
99         "Return a name for the nth server connection."
100         if n is None:
101             n = self.nick_trial
102         return (NAMESTYLE % n)
103     def handle_ping(self):
104         "Register the fact that the server has pinged this connection."
105         self.last_ping = time.time()
106     def handle_welcome(self):
107         "The server says we're OK, with a non-conflicting nick."
108         self.status = "ready"
109         self.irker.debug(1, "nick %s accepted" % self.nickname())
110     def handle_badnick(self):
111         "The server says our nick has a conflict."
112         self.irker.debug(1, "nick %s rejected" % self.nickname())
113         self.nick_trial += 1
114         self.connection.nick(self.nickname())
115     def enqueue(self, channel, message):
116         "Enque a message for transmission."
117         self.queue.put((channel, message))
118     def dequeue(self):
119         "Try to ship pending messages from the queue."
120         while True:
121             # We want to be kind to the IRC servers and not hold unused
122             # sockets open forever, so they have a time-to-live.  The
123             # loop is coded this particular way so that we can drop
124             # the actual server connection when its time-to-live
125             # expires, then reconnect and resume transmission if the
126             # queue fills up again.
127             if not self.connection:
128                 self.connection = self.irker.irc.server()
129                 self.connection.context = self
130                 self.nick_trial = 1
131                 self.channels_joined = []
132                 # This will throw irc.client.ServerConnectionError on failure
133                 try:
134                     self.connection.connect(self.servername,
135                                         self.port,
136                                         nickname=self.nickname(),
137                                         username="irker",
138                                         ircname="irker relaying client")
139                     self.status = "handshaking"
140                     self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
141                     self.last_xmit = time.time()
142                 except irc.client.ServerConnectionError:
143                     self.status = "disconnected"
144             elif self.status == "handshaking":
145                 # Don't buzz on the empty-queue test while we're handshaking 
146                 time.sleep(ANTI_BUZZ_DELAY)
147             elif self.queue.empty():
148                 # Queue is empty, at some point we want to time out
149                 # the connection rather than holding a socket open in
150                 # the server forever.
151                 now = time.time()
152                 if now > self.last_xmit + XMIT_TTL \
153                        or now > self.last_ping + PING_TTL:
154                     self.irker.debug(1, "timing out inactive connection to %s at %s" % (self.servername, time.asctime()))
155                     self.connection.context = None
156                     self.connection.close()
157                     self.connection = None
158                     self.status = "disconnected"
159                 else:
160                     # Prevent this thread from hogging the CPU by pausing
161                     # for just a little bit after the queue-empty check.
162                     # As long as this is less that the duration of a human
163                     # reflex arc it is highly unlikely any human will ever
164                     # notice.
165                     time.sleep(ANTI_BUZZ_DELAY)
166             elif self.status == "disconnected" \
167                      and time.time() > self.last_xmit + DISCONNECT_TTL:
168                 # Queue is nonempty, but the IRC server might be down. Letting
169                 # failed connections retain queue space forever would be a
170                 # memory leak.  
171                 self.status = "expired"
172                 break
173             elif self.status == "unseen" \
174                      and time.time() > self.last_xmit + UNSEEN_TTL:
175                 # Nasty people could attempt a denial-of-service
176                 # attack by flooding us with requests with invalid
177                 # servernames. We guard against this by rapidly
178                 # expiring connections that have a nonempty queue but
179                 # have never had a successful open.
180                 self.status = "expired"
181                 break
182             elif self.status == "ready":
183                 (channel, message) = self.queue.get()
184                 if channel not in self.channels_joined:
185                     self.channels_joined.append(channel)
186                     if channel[0] not in "#&+":
187                         channel = "#" + channel
188                     self.connection.join(channel)
189                 self.connection.privmsg(channel, message)
190                 self.last_xmit = time.time()
191                 self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
192                 self.queue.task_done()
193                 time.sleep(ANTI_FLOOD_DELAY)
194     def live(self):
195         "Should this connection not be scavenged?"
196         return self.status != "expired"
197     def joined_to(self, channel):
198         "Is this connection joined to the specified channel?"
199         return channel in self.channels_joined
200     def accepting(self, channel):
201         "Can this connection accept a join of this channel?"
202         if self.channel_limits:
203             match_count = 0
204             for already in self.channels_joined:
205                 if already[0] == channel[0]:
206                     match_count += 1
207             return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
208         else:
209             return len(self.channels_joined) < CHANNEL_MAX
210
211 class Target():
212     "Represent a transmission target."
213     def __init__(self, url):
214         parsed = urlparse.urlparse(url)
215         irchost, _, ircport = parsed.netloc.partition(':')
216         if not ircport:
217             ircport = 6667
218         self.servername = irchost
219         self.channel = parsed.path.lstrip('/')
220         self.port = int(ircport)
221     def server(self):
222         "Return a hashable tuple representing the destination server."
223         return (self.servername, self.port)
224
225 class Dispatcher:
226     "Manage connections to a particular server-port combination."
227     def __init__(self, irkerd, servername, port):
228         self.irker = irkerd
229         self.servername = servername
230         self.port = port
231         self.connections = []
232     def dispatch(self, channel, message):
233         "Dispatch messages for our server-port combination."
234         connections = [x for x in self.connections if x.live()]
235         eligibles = [x for x in connections if x.joined_to(channel)] \
236                     or [x for x in connections if x.accepting(channel)]
237         if not eligibles:
238             newconn = Connection(self.irker,
239                                  self.servername,
240                                  self.port,
241                                  len(self.connections)+1)
242             self.connections.append(newconn)
243             eligibles = [newconn]
244         eligibles[0].enqueue(channel, message)
245     def live(self):
246         "Does this server-port combination have any live connections?"
247         self.connections = [x for x in self.connections if x.live()]
248         return len(self.connections) > 0
249
250 class Irker:
251     "Persistent IRC multiplexer."
252     def __init__(self, debuglevel=0):
253         self.debuglevel = debuglevel
254         self.irc = irc.client.IRC()
255         self.irc.add_global_handler("ping", self._handle_ping)
256         self.irc.add_global_handler("welcome", self._handle_welcome)
257         self.irc.add_global_handler("erroneusnickname", self._handle_badnick)
258         self.irc.add_global_handler("nicknameinuse", self._handle_badnick)
259         self.irc.add_global_handler("nickcollision", self._handle_badnick)
260         self.irc.add_global_handler("unavailresource", self._handle_badnick)
261         self.irc.add_global_handler("featurelist", self._handle_features)
262         thread = threading.Thread(target=self.irc.process_forever)
263         self.irc._thread = thread
264         thread.start()
265         self.servers = {}
266     def logerr(self, errmsg):
267         "Log a processing error."
268         sys.stderr.write("irkerd: " + errmsg + "\n")
269     def debug(self, level, errmsg):
270         "Debugging information."
271         if self.debuglevel >= level:
272             sys.stderr.write("irkerd: %s\n" % errmsg)
273     def _handle_ping(self, connection, _event):
274         "PING arrived, bump the last-received time for the connection."
275         if connection.context:
276             connection.context.handle_ping()
277     def _handle_welcome(self, connection, _event):
278         "Welcome arrived, nick accepted for this connection."
279         if connection.context:
280             connection.context.handle_welcome()
281     def _handle_badnick(self, connection, _event):
282         "Nick not accepted for this connection."
283         if connection.context:
284             connection.context.handle_badnick()
285     def _handle_features(self, connection, event):
286         "Determine if and how we can set deaf mode."
287         if connection.context:
288             cxt = connection.context
289             for lump in event.arguments():
290                 if lump.startswith("DEAF="):
291                     connection.mode(cxt.nickname(), "+"+lump[5:])
292                 elif lump.startswith("MAXCHANNELS="):
293                     m = int(lump[12:])
294                     for pref in "#&+":
295                         cxt.channel_limits[pref] = m
296                     self.debug(1, "%s maxchannels is %d" \
297                                % (connection.server, m))
298                 elif lump.startswith("CHANLIMIT=#:"):
299                     limits = lump[10:].split(",")
300                     try:
301                         for token in limits:
302                             (prefixes, limit) = token.split(":")
303                             limit = int(limit)
304                             for c in prefixes:
305                                 cxt.channel_limits[c] = limit
306                         self.debug(1, "%s channel limit map is %s" \
307                                    % (connection.server, cxt.channel_limits))
308                     except ValueError:
309                         self.logerr("ill-formed CHANLIMIT property")
310     def handle(self, line):
311         "Perform a JSON relay request."
312         try:
313             request = json.loads(line.strip())
314             if "to" not in request or "privmsg" not in request:
315                 self.logerr("malformed reqest - 'to' or 'privmsg' missing: %s" % repr(request))
316             else:
317                 channels = request['to']
318                 message = request['privmsg']
319                 if type(channels) not in (type([]), type(u"")) \
320                        or type(message) != type(u""):
321                     self.logerr("malformed request - unexpected types: %s" % repr(request))
322                 else:
323                     if type(channels) == type(u""):
324                         channels = [channels]
325                     for url in channels:
326                         if type(url) != type(u""):
327                             self.logerr("malformed request - unexpected type: %s" % repr(request))
328                         else:
329                             target = Target(url)
330                             if target.server() not in self.servers:
331                                 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
332                             self.servers[target.server()].dispatch(target.channel, message)
333                             # GC dispatchers with no active connections
334                             servernames = self.servers.keys()
335                             for servername in servernames:
336                                 if not self.servers[servername].live():
337                                     del self.servers[servername]
338         except ValueError:
339             self.logerr("can't recognize JSON on input: %s" % repr(line))
340
341 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
342     def handle(self):
343         while True:
344             line = self.rfile.readline()
345             if not line:
346                 break
347             irker.handle(line.strip())
348
349 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
350     def handle(self):
351         data = self.request[0].strip()
352         #socket = self.request[1]
353         irker.handle(data)
354
355 if __name__ == '__main__':
356     debuglvl = 0
357     (options, arguments) = getopt.getopt(sys.argv[1:], "d:V")
358     for (opt, val) in options:
359         if opt == '-d':         # Enable debug/progress messages
360             debuglvl = int(val)
361             if debuglvl > 1:
362                 logging.basicConfig(level=logging.DEBUG)
363         elif opt == '-V':       # Emit version and exit
364             sys.stdout.write("irkerd version %s\n" % version)
365             sys.exit(0)
366     irker = Irker(debuglevel=debuglvl)
367     tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
368     udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
369     threading.Thread(target=tcpserver.serve_forever).start()
370     threading.Thread(target=udpserver.serve_forever).start()
371
372 # end