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