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