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