3d156cf2affce9d8a1ed106a4c70b17d0bbd131a
[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.
24 """
25
26 from __future__ import with_statement
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 = 1.0          # 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 = "2.2"
47
48 import sys, getopt, urlparse, time, random, socket, signal, re
49 import threading, Queue, SocketServer, select
50 try:
51     import simplejson as json   # Faster, also makes us Python-2.4-compatible
52 except ImportError:
53     import json
54
55 # Sketch of implementation:
56 #
57 # One Irker object manages multiple IRC sessions.  It holds a map of
58 # Dispatcher objects, one per (server, port) combination, which are
59 # responsible for routing messages to one of any number of Connection
60 # objects that do the actual socket conversations.  The reason for the
61 # Dispatcher layer is that IRC daemons limit the number of channels a
62 # client (that is, from the daemon's point of view, a socket) can be
63 # joined to, so each session to a server needs a flock of Connection
64 # instances each with its own socket.
65 #
66 # Connections are timed out and removed when either they haven't seen a
67 # PING for a while (indicating that the server may be stalled or down)
68 # or there has been no message traffic to them for a while, or
69 # even if the queue is nonempty but efforts to connect have failed for
70 # a long time.
71 #
72 # There are multiple threads. One accepts incoming traffic from all
73 # servers.  Each Connection also has a consumer thread and a
74 # thread-safe message queue.  The program main appends messages to
75 # queues as JSON requests are received; the consumer threads try to
76 # ship them to servers.  When a socket write stalls, it only blocks an
77 # individual consumer thread; if it stalls long enough, the session
78 # will be timed out. This solves the biggest problem with a
79 # single-threaded implementation, which is that you can't count on a
80 # single stalled write not hanging all other traffic - you're at the
81 # mercy of the length of the buffers in the TCP/IP layer.
82 #
83 # Message delivery is thus not reliable in the face of network stalls,
84 # but this was considered acceptable because IRC (notoriously) has the
85 # same problem - there is little point in reliable delivery to a relay
86 # that is down or unreliable.
87 #
88 # This code uses only NICK, JOIN, PART, MODE, PRIVMSG, USER, and QUIT. 
89 # It is strictly compliant to RFC1459, except for the interpretation and
90 # use of the DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features.
91 #
92 # CHANLIMIT 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 # Historical note: the IRCClient and IRCServerConnection classes
98 # (~270LOC) replace the overweight, overcomplicated 3KLOC mass of
99 # irclib code that irker formerly used as a service library.  They
100 # still look similar to parts of irclib because I contributed to that
101 # code before giving up on it.
102
103 class IRCError(Exception):
104     "An IRC exception"
105     pass
106
107 class IRCClient():
108     "An IRC client session to one or more servers."
109     def __init__(self, debuglevel):
110         self.mutex = threading.RLock()
111         self.server_connections = []
112         self.event_handlers = {}
113         self.add_event_handler("ping",
114                                lambda c, e: c.ship("PONG %s" % e.target))
115         self.debuglevel = debuglevel
116
117     def newserver(self):
118         "Initialize a new server-connection object."
119         conn = IRCServerConnection(self)
120         with self.mutex:
121             self.server_connections.append(conn)
122         return conn
123
124     def spin(self, predicate=None, timeout=0.2):
125         "Spin processing data from connections forever."
126         # Outer loop should specifically *not* be mutex-locked.
127         # Otherwise no other thread would ever be able to change
128         # the shared state of an IRC object running this function.
129         while predicate is None or predicate():
130             with self.mutex:
131                 connected = [x for x in self.server_connections
132                              if x is not None and x.socket is not None]
133                 sockets = [x.socket for x in connected]
134                 if sockets:
135                     connmap = dict([(c.socket.fileno(), c) for c in connected])
136                     (insocks, _o, _e) = select.select(sockets, [], [], timeout)
137                     for s in insocks:
138                         connmap[s.fileno()].consume()
139                 else:
140                     time.sleep(timeout)
141
142     def add_event_handler(self, event, handler):
143         "Set a handler to be called later."
144         with self.mutex:
145             event_handlers = self.event_handlers.setdefault(event, [])
146             event_handlers.append(handler)
147
148     def handle_event(self, connection, event):
149         with self.mutex:
150             h = self.event_handlers
151             th = sorted(h.get("all_events", []) + h.get(event.type, []))
152             for handler in th:
153                 handler(connection, event)
154
155     def drop_connection(self, connection):
156         with self.mutex:
157             self.server_connections.remove(connection)
158
159     def debug(self, level, errmsg):
160         "Debugging information."
161         if self.debuglevel >= level:
162             sys.stderr.write("irkerd: %s\n" % errmsg)
163
164 class LineBufferedStream():
165     "Line-buffer a read stream."
166     crlf_re = re.compile(b'\r?\n')
167
168     def __init__(self):
169         self.buffer = ''
170
171     def append(self, newbytes):
172         self.buffer += newbytes
173
174     def lines(self):
175         "Iterate over lines in the buffer."
176         lines = LineBufferedStream.crlf_re.split(self.buffer)
177         self.buffer = lines.pop()
178         return iter(lines)
179
180     def __iter__(self):
181         return self.lines()
182
183 class IRCServerConnectionError(IRCError):
184     pass
185
186 class IRCServerConnection():
187     command_re = re.compile("^(:(?P<prefix>[^ ]+) +)?(?P<command>[^ ]+)( *(?P<argument> .+))?")
188     # The full list of numeric-to-event mappings is in Perl's Net::IRC.
189     # We only need to ensure that if some ancient server throws numerics
190     # for the ones we actually want to catch, they're mapped.
191     codemap = {
192         "001": "welcome",
193         "005": "featurelist",
194         "432": "erroneusnickname",
195         "433": "nicknameinuse",
196         "436": "nickcollision",
197         "437": "unavailresource",
198     }
199
200     def __init__(self, master):
201         self.master = master
202         self.socket = None
203
204     def connect(self, server, port, nickname,
205                 password=None, username=None, ircname=None):
206         self.master.debug(2, "connect(server=%r, port=%r, nickname=%r, ...)" %
207                           (server, port, nickname))
208         if self.socket is not None:
209             self.disconnect("Changing servers")
210
211         self.buffer = LineBufferedStream()
212         self.event_handlers = {}
213         self.real_server_name = ""
214         self.server = server
215         self.port = port
216         self.server_address = (server, port)
217         self.nickname = nickname
218         self.username = username or nickname
219         self.ircname = ircname or nickname
220         self.password = password
221         try:
222             self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
223             self.socket.bind(('', 0))
224             self.socket.connect(self.server_address)
225         except socket.error as err:
226             raise IRCServerConnectionError("Couldn't connect to socket: %s" % err)
227
228         if self.password:
229             self.ship("PASS " + self.password)
230         self.nick(self.nickname)
231         self.user(self.username, self.ircname)
232         return self
233
234     def close(self):
235         # Without this thread lock, there is a window during which
236         # select() can find a closed socket, leading to an EBADF error.
237         with self.master.mutex:
238             self.disconnect("Closing object")
239             self.master.drop_connection(self)
240
241     def consume(self):
242         try:
243             incoming = self.socket.recv(16384)
244         except socket.error:
245             # Server hung up on us.
246             self.disconnect("Connection reset by peer")
247             return
248         if not incoming:
249             # Dead air also indicates a connection reset.
250             self.disconnect("Connection reset by peer")
251             return
252
253         self.buffer.append(incoming)
254
255         for line in self.buffer:
256             self.master.debug(2, "FROM: %s" % line)
257
258             if not line:
259                 continue
260
261             prefix = None
262             command = None
263             arguments = None
264             self.handle_event(Event("every_raw_message",
265                                      self.real_server_name,
266                                      None,
267                                      [line]))
268
269             m = IRCServerConnection.command_re.match(line)
270             if m.group("prefix"):
271                 prefix = m.group("prefix")
272                 if not self.real_server_name:
273                     self.real_server_name = prefix
274             if m.group("command"):
275                 command = m.group("command").lower()
276             if m.group("argument"):
277                 a = m.group("argument").split(" :", 1)
278                 arguments = a[0].split()
279                 if len(a) == 2:
280                     arguments.append(a[1])
281
282             command = IRCServerConnection.codemap.get(command, command)
283             if command in ["privmsg", "notice"]:
284                 target = arguments.pop(0)
285             else:
286                 target = None
287
288                 if command == "quit":
289                     arguments = [arguments[0]]
290                 elif command == "ping":
291                     target = arguments[0]
292                 else:
293                     target = arguments[0]
294                     arguments = arguments[1:]
295
296             self.master.debug(2,
297                               "command: %s, source: %s, target: %s, arguments: %s" % (command, prefix, target, arguments))
298             self.handle_event(Event(command, prefix, target, arguments))
299
300     def handle_event(self, event):
301         self.master.handle_event(self, event)
302         if event.type in self.event_handlers:
303             for fn in self.event_handlers[event.type]:
304                 fn(self, event)
305
306     def is_connected(self):
307         return self.socket is not None
308
309     def disconnect(self, message=""):
310         if self.socket is None:
311             return
312         # Don't send a QUIT here - causes infinite loop!
313         try:
314             self.socket.shutdown(socket.SHUT_WR)
315             self.socket.close()
316         except socket.error:
317             pass
318         del self.socket
319         self.socket = None
320         self.handle_event(Event("disconnect", self.server, "", [message]))
321
322     def join(self, channel, key=""):
323         self.ship("JOIN %s%s" % (channel, (key and (" " + key))))
324
325     def mode(self, target, command):
326         self.ship("MODE %s %s" % (target, command))
327
328     def nick(self, newnick):
329         self.ship("NICK " + newnick)
330
331     def part(self, channel, message=""):
332         cmd_parts = ['PART', channel]
333         if message:
334             cmd_parts.append(message)
335         self.ship(' '.join(cmd_parts))
336
337     def privmsg(self, target, text):
338         self.ship("PRIVMSG %s :%s" % (target, text))
339
340     def quit(self, message=""):
341         # Triggers an error that forces a disconnect.
342         self.ship("QUIT" + (message and (" :" + message)))
343
344     def user(self, username, realname):
345         self.ship("USER %s 0 * :%s" % (username, realname))
346
347     def ship(self, string):
348         "Ship a command to the server, appending CR/LF"
349         try:
350             self.socket.send(string.encode('utf-8') + b'\r\n')
351             self.master.debug(2, "TO: %s" % string)
352         except socket.error:
353             self.disconnect("Connection reset by peer.")
354
355 class Event(object):
356     def __init__(self, evtype, source, target, arguments=None):
357         self.type = evtype
358         self.source = source
359         self.target = target
360         if arguments is None:
361             arguments = []
362         self.arguments = arguments
363
364 def is_channel(string):
365     return string and string[0] in "#&+!"
366
367 class Connection:
368     def __init__(self, irkerd, servername, port):
369         self.irker = irkerd
370         self.servername = servername
371         self.port = port
372         self.nick_trial = None
373         self.connection = None
374         self.status = None
375         self.last_xmit = time.time()
376         self.last_ping = time.time()
377         self.channels_joined = {}
378         self.channel_limits = {}
379         # The consumer thread
380         self.queue = Queue.Queue()
381         self.thread = None
382     def nickname(self, n=None):
383         "Return a name for the nth server connection."
384         if n is None:
385             n = self.nick_trial
386         if fallback:
387             return (namestyle % n)
388         else:
389             return namestyle
390     def handle_ping(self):
391         "Register the fact that the server has pinged this connection."
392         self.last_ping = time.time()
393     def handle_welcome(self):
394         "The server says we're OK, with a non-conflicting nick."
395         self.status = "ready"
396         self.irker.irc.debug(1, "nick %s accepted" % self.nickname())
397         if password:
398             self.connection.privmsg("nickserv", "identify %s" % password)
399     def handle_badnick(self):
400         "The server says our nick is ill-formed or has a conflict."
401         self.irker.irc.debug(1, "nick %s rejected" % self.nickname())
402         if fallback:
403             # Randomness prevents a malicious user or bot from
404             # anticipating the next trial name in order to block us
405             # from completing the handshake.
406             self.nick_trial += random.randint(1, 3)
407             self.last_xmit = time.time()
408             self.connection.nick(self.nickname())
409         # Otherwise fall through, it might be possible to
410         # recover manually.
411     def handle_disconnect(self):
412         "Server disconnected us for flooding or some other reason."
413         self.connection = None
414         if self.status != "expired":
415             self.status = "disconnected"
416     def handle_kick(self, outof):
417         "We've been kicked."
418         self.status = "handshaking"
419         try:
420             del self.channels_joined[outof]
421         except KeyError:
422             self.irker.logerr("kicked by %s from %s that's not joined"
423                               % (self.servername, outof))
424         qcopy = []
425         while not self.queue.empty():
426             (channel, message, key) = self.queue.get()
427             if channel != outof:
428                 qcopy.append((channel, message, key))
429         for (channel, message, key) in qcopy:
430             self.queue.put((channel, message, key))
431         self.status = "ready"
432     def enqueue(self, channel, message, key):
433         "Enque a message for transmission."
434         if self.thread is None or not self.thread.is_alive():
435             self.status = "unseen"
436             self.thread = threading.Thread(target=self.dequeue)
437             self.thread.setDaemon(True)
438             self.thread.start()
439         self.queue.put((channel, message, key))
440     def dequeue(self):
441         "Try to ship pending messages from the queue."
442         try:
443             while True:
444                 # We want to be kind to the IRC servers and not hold unused
445                 # sockets open forever, so they have a time-to-live.  The
446                 # loop is coded this particular way so that we can drop
447                 # the actual server connection when its time-to-live
448                 # expires, then reconnect and resume transmission if the
449                 # queue fills up again.
450                 if self.queue.empty():
451                     # Queue is empty, at some point we want to time out
452                     # the connection rather than holding a socket open in
453                     # the server forever.
454                     now = time.time()
455                     xmit_timeout = now > self.last_xmit + XMIT_TTL
456                     ping_timeout = now > self.last_ping + PING_TTL
457                     if self.status == "disconnected":
458                         # If the queue is empty, we can drop this connection.
459                         self.status = "expired"
460                         break
461                     elif xmit_timeout or ping_timeout:
462                         self.irker.irc.debug(1, "timing out connection to %s at %s (ping_timeout=%s, xmit_timeout=%s)" % (self.servername, time.asctime(), ping_timeout, xmit_timeout))
463                         with self.irker.irc.mutex:
464                             self.connection.context = None
465                             self.connection.quit("transmission timeout")
466                             self.connection = None
467                         self.status = "disconnected"
468                     else:
469                         # Prevent this thread from hogging the CPU by pausing
470                         # for just a little bit after the queue-empty check.
471                         # As long as this is less that the duration of a human
472                         # reflex arc it is highly unlikely any human will ever
473                         # notice.
474                         time.sleep(ANTI_BUZZ_DELAY)
475                 elif self.status == "disconnected" \
476                          and time.time() > self.last_xmit + DISCONNECT_TTL:
477                     # Queue is nonempty, but the IRC server might be
478                     # down. Letting failed connections retain queue
479                     # space forever would be a memory leak.
480                     self.status = "expired"
481                     break
482                 elif not self.connection and self.status != "expired":
483                     # Queue is nonempty but server isn't connected.
484                     with self.irker.irc.mutex:
485                         self.connection = self.irker.irc.newserver()
486                         self.connection.context = self
487                         # Try to avoid colliding with other instances
488                         self.nick_trial = random.randint(1, 990)
489                         self.channels_joined = {}
490                         try:
491                             # This will throw
492                             # IRCServerConnectionError on failure
493                             self.connection.connect(self.servername,
494                                                 self.port,
495                                                 nickname=self.nickname(),
496                                                 username="irker",
497                                                 ircname="irker relaying client")
498                             self.status = "handshaking"
499                             self.irker.irc.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
500                             self.last_xmit = time.time()
501                             self.last_ping = time.time()
502                         except IRCServerConnectionError:
503                             self.status = "expired"
504                 elif self.status == "handshaking":
505                     if time.time() > self.last_xmit + HANDSHAKE_TTL:
506                         self.status = "expired"
507                         break
508                     else:
509                         # Don't buzz on the empty-queue test while we're
510                         # handshaking
511                         time.sleep(ANTI_BUZZ_DELAY)
512                 elif self.status == "unseen" \
513                          and time.time() > self.last_xmit + UNSEEN_TTL:
514                     # Nasty people could attempt a denial-of-service
515                     # attack by flooding us with requests with invalid
516                     # servernames. We guard against this by rapidly
517                     # expiring connections that have a nonempty queue but
518                     # have never had a successful open.
519                     self.status = "expired"
520                     break
521                 elif self.status == "ready":
522                     (channel, message, key) = self.queue.get()
523                     if channel not in self.channels_joined:
524                         self.connection.join(channel, key=key)
525                         self.irker.irc.debug(1, "joining %s on %s." % (channel, self.servername))
526                     # An empty message might be used as a keepalive or
527                     # to join a channel for logging, so suppress the
528                     # privmsg send unless there is actual traffic.
529                     if message:
530                         for segment in message.split("\n"):
531                             # Truncate the message if it's too long,
532                             # but we're working with characters here,
533                             # not bytes, so we could be off.
534                             # 500 = 512 - CRLF - 'PRIVMSG ' - ' :'
535                             maxlength = 500 - len(channel)
536                             if len(segment) > maxlength:
537                                 segment = segment[:maxlength]
538                             try:
539                                 self.connection.privmsg(channel, segment)
540                             except ValueError as err:
541                                 self.irker.irc.debug(1, "irclib rejected a message to %s on %s because: %s" % (channel, self.servername, str(err)))
542                                 self.irker.irc.debug(50, err.format_exc())
543                             time.sleep(ANTI_FLOOD_DELAY)
544                     self.last_xmit = self.channels_joined[channel] = time.time()
545                     self.irker.irc.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
546                     self.queue.task_done()
547         except:
548             (exc_type, _exc_value, exc_traceback) = sys.exc_info()
549             self.irker.logerr("exception %s in thread for %s" % \
550                               (exc_type, self.servername))
551
552             # Maybe this should have its own status?
553             self.status = "expired"
554
555             # This is so we can see tracebacks for errors inside the thread
556             # when we need to be able to for debugging purposes.
557             if debuglvl > 0:
558                 raise exc_type, _exc_value, exc_traceback
559         finally:
560             try:
561                 # Make sure we don't leave any zombies behind
562                 self.connection.close()
563             except:
564                 # Irclib has a habit of throwing fresh exceptions here. Ignore that
565                 pass
566     def live(self):
567         "Should this connection not be scavenged?"
568         return self.status != "expired"
569     def joined_to(self, channel):
570         "Is this connection joined to the specified channel?"
571         return channel in self.channels_joined
572     def accepting(self, channel):
573         "Can this connection accept a join of this channel?"
574         if self.channel_limits:
575             match_count = 0
576             for already in self.channels_joined:
577                 # This obscure code is because the RFCs allow separate limits
578                 # by channel type (indicated by the first character of the name)
579                 # a feature that is almost never actually used.
580                 if already[0] == channel[0]:
581                     match_count += 1
582             return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
583         else:
584             return len(self.channels_joined) < CHANNEL_MAX
585
586 class Target():
587     "Represent a transmission target."
588     def __init__(self, url):
589         # Pre-2.6 Pythons don't recognize irc: as a valid URL prefix.
590         url = url.replace("irc://", "http://")
591         parsed = urlparse.urlparse(url)
592         irchost, _, ircport = parsed.netloc.partition(':')
593         if not ircport:
594             ircport = 6667
595         self.servername = irchost
596         # IRC channel names are case-insensitive.  If we don't smash
597         # case here we may run into problems later. There was a bug
598         # observed on irc.rizon.net where an irkerd user specified #Channel,
599         # got kicked, and irkerd crashed because the server returned
600         # "#channel" in the notification that our kick handler saw.
601         self.channel = parsed.path.lstrip('/').lower()
602         # This deals with a tweak in recent versions of urlparse.
603         if parsed.fragment:
604             self.channel += "#" + parsed.fragment
605         isnick = self.channel.endswith(",isnick")
606         if isnick:
607             self.channel = self.channel[:-7]
608         if self.channel and not isnick and self.channel[0] not in "#&+":
609             self.channel = "#" + self.channel
610         # support both channel?secret and channel?key=secret
611         self.key = ""
612         if parsed.query:
613             self.key = re.sub("^key=", "", parsed.query)
614         self.port = int(ircport)
615     def valid(self):
616         "Both components must be present for a valid target."
617         return self.servername and self.channel
618     def server(self):
619         "Return a hashable tuple representing the destination server."
620         return (self.servername, self.port)
621
622 class Dispatcher:
623     "Manage connections to a particular server-port combination."
624     def __init__(self, irkerd, servername, port):
625         self.irker = irkerd
626         self.servername = servername
627         self.port = port
628         self.connections = []
629     def dispatch(self, channel, message, key):
630         "Dispatch messages for our server-port combination."
631         # First, check if there is room for another channel
632         # on any of our existing connections.
633         connections = [x for x in self.connections if x.live()]
634         eligibles = [x for x in connections if x.joined_to(channel)] \
635                     or [x for x in connections if x.accepting(channel)]
636         if eligibles:
637             eligibles[0].enqueue(channel, message, key)
638             return
639         # All connections are full up. Look for one old enough to be
640         # scavenged.
641         ancients = []
642         for connection in connections:
643             for (chan, age) in connections.channels_joined.items():
644                 if age < time.time() - CHANNEL_TTL:
645                     ancients.append((connection, chan, age))
646         if ancients:
647             ancients.sort(key=lambda x: x[2]) 
648             (found_connection, drop_channel, _drop_age) = ancients[0]
649             found_connection.part(drop_channel, "scavenged by irkerd")
650             del found_connection.channels_joined[drop_channel]
651             #time.sleep(ANTI_FLOOD_DELAY)
652             found_connection.enqueue(channel, message, key)
653             return
654         # Didn't find any channels with no recent activity
655         newconn = Connection(self.irker,
656                              self.servername,
657                              self.port)
658         self.connections.append(newconn)
659         newconn.enqueue(channel, message, key)
660     def live(self):
661         "Does this server-port combination have any live connections?"
662         self.connections = [x for x in self.connections if x.live()]
663         return len(self.connections) > 0
664     def pending(self):
665         "Return all connections with pending traffic."
666         return [x for x in self.connections if not x.queue.empty()]
667     def last_xmit(self):
668         "Return the time of the most recent transmission."
669         return max(x.last_xmit for x in self.connections)
670
671 class Irker:
672     "Persistent IRC multiplexer."
673     def __init__(self, debuglevel=0):
674         self.debuglevel = debuglevel
675         self.irc = IRCClient(self.debuglevel)
676         self.irc.add_event_handler("ping", self._handle_ping)
677         self.irc.add_event_handler("welcome", self._handle_welcome)
678         self.irc.add_event_handler("erroneusnickname", self._handle_badnick)
679         self.irc.add_event_handler("nicknameinuse", self._handle_badnick)
680         self.irc.add_event_handler("nickcollision", self._handle_badnick)
681         self.irc.add_event_handler("unavailresource", self._handle_badnick)
682         self.irc.add_event_handler("featurelist", self._handle_features)
683         self.irc.add_event_handler("disconnect", self._handle_disconnect)
684         self.irc.add_event_handler("kick", self._handle_kick)
685         self.irc.add_event_handler("every_raw_message", self._handle_every_raw_message)
686         self.servers = {}
687         self.until = None
688     def thread_launch(self):
689         thread = threading.Thread(target=self.irc.spin)
690         thread.setDaemon(True)
691         self.irc._thread = thread
692         thread.start()
693     def logerr(self, errmsg):
694         "Log a processing error."
695         sys.stderr.write("irkerd: " + errmsg + "\n")
696     def _handle_ping(self, connection, _event):
697         "PING arrived, bump the last-received time for the connection."
698         if connection.context:
699             connection.context.handle_ping()
700     def _handle_welcome(self, connection, _event):
701         "Welcome arrived, nick accepted for this connection."
702         if connection.context:
703             connection.context.handle_welcome()
704     def _handle_badnick(self, connection, _event):
705         "Nick not accepted for this connection."
706         if connection.context:
707             connection.context.handle_badnick()
708     def _handle_features(self, connection, event):
709         "Determine if and how we can set deaf mode."
710         if connection.context:
711             cxt = connection.context
712             arguments = event.arguments
713             for lump in arguments:
714                 if self.until is None and lump.startswith("DEAF="):
715                     if not logfile:
716                         connection.mode(cxt.nickname(), "+"+lump[5:])
717                 elif lump.startswith("MAXCHANNELS="):
718                     m = int(lump[12:])
719                     for pref in "#&+":
720                         cxt.channel_limits[pref] = m
721                     self.irc.debug(1, "%s maxchannels is %d"
722                                % (connection.server, m))
723                 elif lump.startswith("CHANLIMIT=#:"):
724                     limits = lump[10:].split(",")
725                     try:
726                         for token in limits:
727                             (prefixes, limit) = token.split(":")
728                             limit = int(limit)
729                             for c in prefixes:
730                                 cxt.channel_limits[c] = limit
731                         self.irc.debug(1, "%s channel limit map is %s"
732                                    % (connection.server, cxt.channel_limits))
733                     except ValueError:
734                         self.logerr("ill-formed CHANLIMIT property")
735     def _handle_disconnect(self, connection, _event):
736         "Server hung up the connection."
737         self.irc.debug(1, "server %s disconnected" % connection.server)
738         connection.close()
739         if connection.context:
740             connection.context.handle_disconnect()
741     def _handle_kick(self, connection, event):
742         "Server hung up the connection."
743         target = event.target
744         self.irc.debug(1, "irker has been kicked from %s on %s" % (target, connection.server))
745         if connection.context:
746             connection.context.handle_kick(target)
747     def _handle_every_raw_message(self, _connection, event):
748         "Log all messages when in watcher mode."
749         if logfile:
750             with open(logfile, "a") as logfp:
751                 logfp.write("%03f|%s|%s\n" % \
752                              (time.time(), event.source, event.arguments[0]))
753         if self.until is not None:
754             if self.until == event.arguments[0]:
755                 raise SystemExit, 1
756     def pending(self):
757         "Do we have any pending message traffic?"
758         return [k for (k, v) in self.servers.items() if v.pending()]
759     def handle(self, line):
760         "Perform a JSON relay request."
761         try:
762             request = json.loads(line.strip())
763             if not isinstance(request, dict):
764                 self.logerr("request is not a JSON dictionary: %r" % request)
765             elif "to" not in request or "privmsg" not in request:
766                 self.logerr("malformed request - 'to' or 'privmsg' missing: %r" % request)
767             else:
768                 channels = request['to']
769                 message = request['privmsg']
770                 if not isinstance(channels, (list, basestring)):
771                     self.logerr("malformed request - unexpected channel type: %r" % channels)
772                 if not isinstance(message, basestring):
773                     self.logerr("malformed request - unexpected message type: %r" % message)
774                 else:
775                     if not isinstance(channels, list):
776                         channels = [channels]
777                     for url in channels:
778                         if not isinstance(url, basestring):
779                             self.logerr("malformed request - URL has unexpected type: %r" % url)
780                         else:
781                             target = Target(url)
782                             if not target.valid():
783                                 return
784                             if target.server() not in self.servers:
785                                 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
786                             self.servers[target.server()].dispatch(target.channel, message, target.key)
787                             # GC dispatchers with no active connections
788                             servernames = self.servers.keys()
789                             for servername in servernames:
790                                 if not self.servers[servername].live():
791                                     del self.servers[servername]
792                             # If we might be pushing a resource limit
793                             # even after garbage collection, remove a
794                             # session.  The goal here is to head off
795                             # DoS attacks that aim at exhausting
796                             # thread space or file descriptors.  The
797                             # cost is that attempts to DoS this
798                             # service will cause lots of join/leave
799                             # spam as we scavenge old channels after
800                             # connecting to new ones. The particular
801                             # method used for selecting a session to
802                             # be terminated doesn't matter much; we
803                             # choose the one longest idle on the
804                             # assumption that message activity is likely
805                             # to be clumpy.
806                             if len(self.servers) >= CONNECTION_MAX:
807                                 oldest = min(self.servers.keys(), key=lambda name: self.servers[name].last_xmit())
808                                 del self.servers[oldest]
809         except ValueError:
810             self.logerr("can't recognize JSON on input: %r" % line)
811         except RuntimeError:
812             self.logerr("wildly malformed JSON blew the parser stack.")
813
814 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
815     def handle(self):
816         while True:
817             line = self.rfile.readline()
818             if not line:
819                 break
820             irker.handle(line.strip())
821
822 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
823     def handle(self):
824         data = self.request[0].strip()
825         #socket = self.request[1]
826         irker.handle(data)
827
828 def usage():
829     sys.stdout.write("""
830 Usage:
831   irkerd [-d debuglevel] [-l logfile] [-n nick] [-p password] [-V] [-h]
832
833 Options
834   -d    set debug level
835   -l    set logfile
836   -n    set nick-style
837   -p    set nickserv password
838   -V    return irkerd version
839   -h    print this help dialog
840 """)
841
842 if __name__ == '__main__':
843     debuglvl = 0
844     immediate = None
845     namestyle = "irker%03d"
846     password = None
847     logfile = None
848     try:
849         (options, arguments) = getopt.getopt(sys.argv[1:], "d:i:l:n:p:Vh")
850     except getopt.GetoptError as e:
851         sys.stderr.write("%s" % e)
852         usage()
853         sys.exit(1)
854     for (opt, val) in options:
855         if opt == '-d':         # Enable debug/progress messages
856             debuglvl = int(val)
857         elif opt == '-i':       # Immediate mode - send one message, then exit. 
858             immediate = val
859         elif opt == '-l':       # Logfile mode - report traffic read in
860             logfile = val
861         elif opt == '-n':       # Force the nick
862             namestyle = val
863         elif opt == '-p':       # Set a nickserv password
864             password = val
865         elif opt == '-V':       # Emit version and exit
866             sys.stdout.write("irkerd version %s\n" % version)
867             sys.exit(0)
868         elif opt == '-h':
869             usage()
870             sys.exit(0)
871     fallback = re.search("%.*d", namestyle)
872     irker = Irker(debuglevel=debuglvl)
873     irker.irc.debug(1, "irkerd version %s" % version)
874     if immediate:
875         (to, privmsg) = val.split(",")
876         irker.handle('{"to":"%s","privmsg":"%s"}' % (to, privmsg))
877         irker.until = privmsg
878         irker.irc.spin()
879     else:
880         irker.thread_launch()
881         try:
882             tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
883             udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
884             for server in [tcpserver, udpserver]:
885                 server = threading.Thread(target=server.serve_forever)
886                 server.setDaemon(True)
887                 server.start()
888             try:
889                 signal.pause()
890             except KeyboardInterrupt:
891                 raise SystemExit(1)
892         except socket.error, e:
893             sys.stderr.write("irkerd: server launch failed: %r\n" % e)
894
895 # end