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