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