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