Version bump for 2.8 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.8"
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                 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(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, username=None, realname=None,
267                 **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 target.password:
291             self.ship("PASS " + target.password)
292         self.nick(self.nickname)
293         self.user(
294             username=target.username or username or 'irker',
295             realname=realname or 'irker relaying client')
296         return self
297
298     def close(self):
299         # Without this thread lock, there is a window during which
300         # select() can find a closed socket, leading to an EBADF error.
301         with self.master.mutex:
302             self.disconnect("Closing object")
303             self.master.drop_connection(self)
304
305     def consume(self):
306         try:
307             incoming = self.socket.recv(16384)
308         except socket.error:
309             # Server hung up on us.
310             self.disconnect("Connection reset by peer")
311             return
312         if not incoming:
313             # Dead air also indicates a connection reset.
314             self.disconnect("Connection reset by peer")
315             return
316
317         self.buffer.append(incoming)
318
319         for line in self.buffer:
320             if not isinstance(line, UNICODE_TYPE):
321                 line = UNICODE_TYPE(line, 'utf-8')
322             LOG.debug("FROM: %s" % line)
323
324             if not line:
325                 continue
326
327             prefix = None
328             command = None
329             arguments = None
330             self.handle_event(Event("every_raw_message",
331                                      self.real_server_name,
332                                      None,
333                                      [line]))
334
335             m = IRCServerConnection.command_re.match(line)
336             if m.group("prefix"):
337                 prefix = m.group("prefix")
338                 if not self.real_server_name:
339                     self.real_server_name = prefix
340             if m.group("command"):
341                 command = m.group("command").lower()
342             if m.group("argument"):
343                 a = m.group("argument").split(" :", 1)
344                 arguments = a[0].split()
345                 if len(a) == 2:
346                     arguments.append(a[1])
347
348             command = IRCServerConnection.codemap.get(command, command)
349             if command in ["privmsg", "notice"]:
350                 target = arguments.pop(0)
351             else:
352                 target = None
353
354                 if command == "quit":
355                     arguments = [arguments[0]]
356                 elif command == "ping":
357                     target = arguments[0]
358                 else:
359                     target = arguments[0]
360                     arguments = arguments[1:]
361
362             LOG.debug("command: %s, source: %s, target: %s, arguments: %s" % (
363                 command, prefix, target, arguments))
364             self.handle_event(Event(command, prefix, target, arguments))
365
366     def handle_event(self, event):
367         self.master.handle_event(self, event)
368         if event.type in self.event_handlers:
369             for fn in self.event_handlers[event.type]:
370                 fn(self, event)
371
372     def is_connected(self):
373         return self.socket is not None
374
375     def disconnect(self, message=""):
376         if self.socket is None:
377             return
378         # Don't send a QUIT here - causes infinite loop!
379         try:
380             self.socket.shutdown(socket.SHUT_WR)
381             self.socket.close()
382         except socket.error:
383             pass
384         del self.socket
385         self.socket = None
386         self.handle_event(
387             Event("disconnect", self.target.server, "", [message]))
388
389     def join(self, channel, key=""):
390         self.ship("JOIN %s%s" % (channel, (key and (" " + key))))
391
392     def mode(self, target, command):
393         self.ship("MODE %s %s" % (target, command))
394
395     def nick(self, newnick):
396         self.ship("NICK " + newnick)
397
398     def part(self, channel, message=""):
399         cmd_parts = ['PART', channel]
400         if message:
401             cmd_parts.append(message)
402         self.ship(' '.join(cmd_parts))
403
404     def privmsg(self, target, text):
405         self.ship("PRIVMSG %s :%s" % (target, text))
406
407     def quit(self, message=""):
408         self.ship("QUIT" + (message and (" :" + message)))
409
410     def user(self, username, realname):
411         self.ship("USER %s 0 * :%s" % (username, realname))
412
413     def ship(self, string):
414         "Ship a command to the server, appending CR/LF"
415         try:
416             self.socket.send(string.encode('utf-8') + b'\r\n')
417             LOG.debug("TO: %s" % string)
418         except socket.error:
419             self.disconnect("Connection reset by peer.")
420
421 class Event(object):
422     def __init__(self, evtype, source, target, arguments=None):
423         self.type = evtype
424         self.source = source
425         self.target = target
426         if arguments is None:
427             arguments = []
428         self.arguments = arguments
429
430 def is_channel(string):
431     return string and string[0] in "#&+!"
432
433 class Connection:
434     def __init__(self, irker, target, nick_template, nick_needs_number=False,
435                  password=None, **kwargs):
436         self.irker = irker
437         self.target = target
438         self.nick_template = nick_template
439         self.nick_needs_number = nick_needs_number
440         self.password = password
441         self.kwargs = kwargs
442         self.nick_trial = None
443         self.connection = None
444         self.status = None
445         self.last_xmit = time.time()
446         self.last_ping = time.time()
447         self.channels_joined = {}
448         self.channel_limits = {}
449         # The consumer thread
450         self.queue = queue.Queue()
451         self.thread = None
452     def nickname(self, n=None):
453         "Return a name for the nth server connection."
454         if n is None:
455             n = self.nick_trial
456         if self.nick_needs_number:
457             return (self.nick_template % n)
458         else:
459             return self.nick_template
460     def handle_ping(self):
461         "Register the fact that the server has pinged this connection."
462         self.last_ping = time.time()
463     def handle_welcome(self):
464         "The server says we're OK, with a non-conflicting nick."
465         self.status = "ready"
466         LOG.info("nick %s accepted" % self.nickname())
467         if self.password:
468             self.connection.privmsg("nickserv", "identify %s" % self.password)
469     def handle_badnick(self):
470         "The server says our nick is ill-formed or has a conflict."
471         LOG.info("nick %s rejected" % self.nickname())
472         if self.nick_needs_number:
473             # Randomness prevents a malicious user or bot from
474             # anticipating the next trial name in order to block us
475             # from completing the handshake.
476             self.nick_trial += random.randint(1, 3)
477             self.last_xmit = time.time()
478             self.connection.nick(self.nickname())
479         # Otherwise fall through, it might be possible to
480         # recover manually.
481     def handle_disconnect(self):
482         "Server disconnected us for flooding or some other reason."
483         self.connection = None
484         if self.status != "expired":
485             self.status = "disconnected"
486     def handle_kick(self, outof):
487         "We've been kicked."
488         self.status = "handshaking"
489         try:
490             del self.channels_joined[outof]
491         except KeyError:
492             LOG.error("kicked by %s from %s that's not joined" % (
493                 self.target, outof))
494         qcopy = []
495         while not self.queue.empty():
496             (channel, message, key) = self.queue.get()
497             if channel != outof:
498                 qcopy.append((channel, message, key))
499         for (channel, message, key) in qcopy:
500             self.queue.put((channel, message, key))
501         self.status = "ready"
502     def enqueue(self, channel, message, key, quit_after=False):
503         "Enque a message for transmission."
504         if self.thread is None or not self.thread.is_alive():
505             self.status = "unseen"
506             self.thread = threading.Thread(target=self.dequeue)
507             self.thread.setDaemon(True)
508             self.thread.start()
509         self.queue.put((channel, message, key))
510         if quit_after:
511             self.queue.put((channel, None, key))
512     def dequeue(self):
513         "Try to ship pending messages from the queue."
514         try:
515             while True:
516                 # We want to be kind to the IRC servers and not hold unused
517                 # sockets open forever, so they have a time-to-live.  The
518                 # loop is coded this particular way so that we can drop
519                 # the actual server connection when its time-to-live
520                 # expires, then reconnect and resume transmission if the
521                 # queue fills up again.
522                 if self.queue.empty():
523                     # Queue is empty, at some point we want to time out
524                     # the connection rather than holding a socket open in
525                     # the server forever.
526                     now = time.time()
527                     xmit_timeout = now > self.last_xmit + XMIT_TTL
528                     ping_timeout = now > self.last_ping + PING_TTL
529                     if self.status == "disconnected":
530                         # If the queue is empty, we can drop this connection.
531                         self.status = "expired"
532                         break
533                     elif xmit_timeout or ping_timeout:
534                         LOG.info((
535                             "timing out connection to %s at %s "
536                             "(ping_timeout=%s, xmit_timeout=%s)") % (
537                             self.target, time.asctime(), ping_timeout,
538                             xmit_timeout))
539                         with self.irker.irc.mutex:
540                             self.connection.context = None
541                             self.connection.quit("transmission timeout")
542                             self.connection = None
543                         self.status = "disconnected"
544                     else:
545                         # Prevent this thread from hogging the CPU by pausing
546                         # for just a little bit after the queue-empty check.
547                         # As long as this is less that the duration of a human
548                         # reflex arc it is highly unlikely any human will ever
549                         # notice.
550                         time.sleep(ANTI_BUZZ_DELAY)
551                 elif self.status == "disconnected" \
552                          and time.time() > self.last_xmit + DISCONNECT_TTL:
553                     # Queue is nonempty, but the IRC server might be
554                     # down. Letting failed connections retain queue
555                     # space forever would be a memory leak.
556                     self.status = "expired"
557                     break
558                 elif not self.connection and self.status != "expired":
559                     # Queue is nonempty but server isn't connected.
560                     with self.irker.irc.mutex:
561                         self.connection = self.irker.irc.newserver()
562                         self.connection.context = self
563                         # Try to avoid colliding with other instances
564                         self.nick_trial = random.randint(1, 990)
565                         self.channels_joined = {}
566                         try:
567                             # This will throw
568                             # IRCServerConnectionError on failure
569                             self.connection.connect(
570                                 target=self.target,
571                                 nickname=self.nickname(),
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         self.username = parsed.username
679         self.password = parsed.password
680         self.servername = parsed.hostname
681         self.port = parsed.port or default_ircport
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
701     def __str__(self):
702         "Represent this instance as a string"
703         return self.servername or self.url or repr(self)
704
705     def validate(self):
706         "Raise InvalidRequest if the URL is missing a critical component"
707         if not self.servername:
708             raise InvalidRequest(
709                 'target URL missing a servername: %r' % self.url)
710         if not self.channel:
711             raise InvalidRequest(
712                 'target URL missing a channel: %r' % self.url)
713     def server(self):
714         "Return a hashable tuple representing the destination server."
715         return (self.servername, self.port)
716
717 class Dispatcher:
718     "Manage connections to a particular server-port combination."
719     def __init__(self, irker, **kwargs):
720         self.irker = irker
721         self.kwargs = kwargs
722         self.connections = []
723     def dispatch(self, channel, message, key, quit_after=False):
724         "Dispatch messages for our server-port combination."
725         # First, check if there is room for another channel
726         # on any of our existing connections.
727         connections = [x for x in self.connections if x.live()]
728         eligibles = [x for x in connections if x.joined_to(channel)] \
729                     or [x for x in connections if x.accepting(channel)]
730         if eligibles:
731             eligibles[0].enqueue(channel, message, key, quit_after)
732             return
733         # All connections are full up. Look for one old enough to be
734         # scavenged.
735         ancients = []
736         for connection in connections:
737             for (chan, age) in connections.channels_joined.items():
738                 if age < time.time() - CHANNEL_TTL:
739                     ancients.append((connection, chan, age))
740         if ancients:
741             ancients.sort(key=lambda x: x[2]) 
742             (found_connection, drop_channel, _drop_age) = ancients[0]
743             found_connection.part(drop_channel, "scavenged by irkerd")
744             del found_connection.channels_joined[drop_channel]
745             #time.sleep(ANTI_FLOOD_DELAY)
746             found_connection.enqueue(channel, message, key, quit_after)
747             return
748         # All existing channels had recent activity
749         newconn = Connection(self.irker, **self.kwargs)
750         self.connections.append(newconn)
751         newconn.enqueue(channel, message, key, quit_after)
752     def live(self):
753         "Does this server-port combination have any live connections?"
754         self.connections = [x for x in self.connections if x.live()]
755         return len(self.connections) > 0
756     def pending(self):
757         "Return all connections with pending traffic."
758         return [x for x in self.connections if not x.queue.empty()]
759     def last_xmit(self):
760         "Return the time of the most recent transmission."
761         return max(x.last_xmit for x in self.connections)
762
763 class Irker:
764     "Persistent IRC multiplexer."
765     def __init__(self, logfile=None, **kwargs):
766         self.logfile = logfile
767         self.kwargs = kwargs
768         self.irc = IRCClient()
769         self.irc.add_event_handler("ping", self._handle_ping)
770         self.irc.add_event_handler("welcome", self._handle_welcome)
771         self.irc.add_event_handler("erroneusnickname", self._handle_badnick)
772         self.irc.add_event_handler("nicknameinuse", self._handle_badnick)
773         self.irc.add_event_handler("nickcollision", self._handle_badnick)
774         self.irc.add_event_handler("unavailresource", self._handle_badnick)
775         self.irc.add_event_handler("featurelist", self._handle_features)
776         self.irc.add_event_handler("disconnect", self._handle_disconnect)
777         self.irc.add_event_handler("kick", self._handle_kick)
778         self.irc.add_event_handler("every_raw_message", self._handle_every_raw_message)
779         self.servers = {}
780     def thread_launch(self):
781         thread = threading.Thread(target=self.irc.spin)
782         thread.setDaemon(True)
783         self.irc._thread = thread
784         thread.start()
785     def _handle_ping(self, connection, _event):
786         "PING arrived, bump the last-received time for the connection."
787         if connection.context:
788             connection.context.handle_ping()
789     def _handle_welcome(self, connection, _event):
790         "Welcome arrived, nick accepted for this connection."
791         if connection.context:
792             connection.context.handle_welcome()
793     def _handle_badnick(self, connection, _event):
794         "Nick not accepted for this connection."
795         if connection.context:
796             connection.context.handle_badnick()
797     def _handle_features(self, connection, event):
798         "Determine if and how we can set deaf mode."
799         if connection.context:
800             cxt = connection.context
801             arguments = event.arguments
802             for lump in arguments:
803                 if lump.startswith("DEAF="):
804                     if not self.logfile:
805                         connection.mode(cxt.nickname(), "+"+lump[5:])
806                 elif lump.startswith("MAXCHANNELS="):
807                     m = int(lump[12:])
808                     for pref in "#&+":
809                         cxt.channel_limits[pref] = m
810                     LOG.info("%s maxchannels is %d" % (connection.server, m))
811                 elif lump.startswith("CHANLIMIT=#:"):
812                     limits = lump[10:].split(",")
813                     try:
814                         for token in limits:
815                             (prefixes, limit) = token.split(":")
816                             limit = int(limit)
817                             for c in prefixes:
818                                 cxt.channel_limits[c] = limit
819                         LOG.info("%s channel limit map is %s" % (
820                             connection.target, cxt.channel_limits))
821                     except ValueError:
822                         LOG.error("ill-formed CHANLIMIT property")
823     def _handle_disconnect(self, connection, _event):
824         "Server hung up the connection."
825         LOG.info("server %s disconnected" % connection.target)
826         connection.close()
827         if connection.context:
828             connection.context.handle_disconnect()
829     def _handle_kick(self, connection, event):
830         "Server hung up the connection."
831         target = event.target
832         LOG.info("irker has been kicked from %s on %s" % (
833             target, connection.target))
834         if connection.context:
835             connection.context.handle_kick(target)
836     def _handle_every_raw_message(self, _connection, event):
837         "Log all messages when in watcher mode."
838         if self.logfile:
839             with open(self.logfile, "a") as logfp:
840                 logfp.write("%03f|%s|%s\n" % \
841                              (time.time(), event.source, event.arguments[0]))
842     def pending(self):
843         "Do we have any pending message traffic?"
844         return [k for (k, v) in self.servers.items() if v.pending()]
845
846     def _parse_request(self, line):
847         "Request-parsing helper for the handle() method"
848         request = json.loads(line.strip())
849         if not isinstance(request, dict):
850             raise InvalidRequest(
851                 "request is not a JSON dictionary: %r" % request)
852         if "to" not in request or "privmsg" not in request:
853             raise InvalidRequest(
854                 "malformed request - 'to' or 'privmsg' missing: %r" % request)
855         channels = request['to']
856         message = request['privmsg']
857         if not isinstance(channels, (list, UNICODE_TYPE)):
858             raise InvalidRequest(
859                 "malformed request - unexpected channel type: %r" % channels)
860         if not isinstance(message, UNICODE_TYPE):
861             raise InvalidRequest(
862                 "malformed request - unexpected message type: %r" % message)
863         if not isinstance(channels, list):
864             channels = [channels]
865         targets = []
866         for url in channels:
867             try:
868                 if not isinstance(url, UNICODE_TYPE):
869                     raise InvalidRequest(
870                         "malformed request - URL has unexpected type: %r" %
871                         url)
872                 target = Target(url)
873                 target.validate()
874             except InvalidRequest as e:
875                 LOG.error(UNICODE_TYPE(e))
876             else:
877                 targets.append(target)
878         return (targets, message)
879
880     def handle(self, line, quit_after=False):
881         "Perform a JSON relay request."
882         try:
883             targets, message = self._parse_request(line=line)
884             for target in targets:
885                 if target.server() not in self.servers:
886                     self.servers[target.server()] = Dispatcher(
887                         self, target=target, **self.kwargs)
888                 self.servers[target.server()].dispatch(
889                     target.channel, message, target.key, quit_after=quit_after)
890                 # GC dispatchers with no active connections
891                 servernames = self.servers.keys()
892                 for servername in servernames:
893                     if not self.servers[servername].live():
894                         del self.servers[servername]
895                     # If we might be pushing a resource limit even
896                     # after garbage collection, remove a session.  The
897                     # goal here is to head off DoS attacks that aim at
898                     # exhausting thread space or file descriptors.
899                     # The cost is that attempts to DoS this service
900                     # will cause lots of join/leave spam as we
901                     # scavenge old channels after connecting to new
902                     # ones. The particular method used for selecting a
903                     # session to be terminated doesn't matter much; we
904                     # choose the one longest idle on the assumption
905                     # that message activity is likely to be clumpy.
906                     if len(self.servers) >= CONNECTION_MAX:
907                         oldest = min(
908                             self.servers.keys(),
909                             key=lambda name: self.servers[name].last_xmit())
910                         del self.servers[oldest]
911         except InvalidRequest as e:
912             LOG.error(UNICODE_TYPE(e))
913         except ValueError:
914             self.logerr("can't recognize JSON on input: %r" % line)
915         except RuntimeError:
916             self.logerr("wildly malformed JSON blew the parser stack.")
917
918 class IrkerTCPHandler(socketserver.StreamRequestHandler):
919     def handle(self):
920         while True:
921             line = self.rfile.readline()
922             if not line:
923                 break
924             if not isinstance(line, UNICODE_TYPE):
925                 line = UNICODE_TYPE(line, 'utf-8')
926             irker.handle(line=line.strip())
927
928 class IrkerUDPHandler(socketserver.BaseRequestHandler):
929     def handle(self):
930         line = self.request[0].strip()
931         #socket = self.request[1]
932         if not isinstance(line, UNICODE_TYPE):
933             line = UNICODE_TYPE(line, 'utf-8')
934         irker.handle(line=line.strip())
935
936
937 if __name__ == '__main__':
938     parser = argparse.ArgumentParser(
939         description=__doc__.strip().splitlines()[0])
940     parser.add_argument(
941         '-c', '--ca-file', metavar='PATH',
942         help='file of trusted certificates for SSL/TLS')
943     parser.add_argument(
944         '-d', '--log-level', metavar='LEVEL', choices=LOG_LEVELS,
945         help='how much to log to the log file (one of %(choices)s)')
946     parser.add_argument(
947         '-l', '--log-file', metavar='PATH',
948         help='file for saving captured message traffic')
949     parser.add_argument(
950         '-n', '--nick', metavar='NAME', default='irker%03d',
951         help="nickname (optionally with a '%%.*d' server connection marker)")
952     parser.add_argument(
953         '-p', '--password', metavar='PASSWORD',
954         help='NickServ password')
955     parser.add_argument(
956         '-i', '--immediate', metavar='IRC-URL',
957         help=(
958             'send a single message to IRC-URL and exit.  The message is the '
959             'first positional argument.'))
960     parser.add_argument(
961         '-V', '--version', action='version',
962         version='%(prog)s {0}'.format(version))
963     parser.add_argument(
964         'message', metavar='MESSAGE', nargs='?',
965         help='message for --immediate mode')
966     args = parser.parse_args()
967
968     handler = logging.StreamHandler()
969     LOG.addHandler(handler)
970     if args.log_level:
971         log_level = getattr(logging, args.log_level.upper())
972         LOG.setLevel(log_level)
973
974     irker = Irker(
975         logfile=args.log_file,
976         nick_template=args.nick,
977         nick_needs_number=re.search('%.*d', args.nick),
978         password=args.password,
979         cafile=args.ca_file,
980         )
981     LOG.info("irkerd version %s" % version)
982     if args.immediate:
983         if not args.message:
984             LOG.error(
985                 '--immediate set (%r), but message argument not given' % (
986                 args.immediate))
987             raise SystemExit(1)
988         irker.irc.add_event_handler("quit", lambda _c, _e: sys.exit(0))
989         irker.handle('{"to":"%s","privmsg":"%s"}' % (
990             args.immediate, args.message), quit_after=True)
991         irker.irc.spin()
992     else:
993         if args.message:
994             LOG.error(
995                 'message argument given (%r), but --immediate not set' % (
996                 args.message))
997             raise SystemExit(1)
998         irker.thread_launch()
999         try:
1000             tcpserver = socketserver.TCPServer((HOST, PORT), IrkerTCPHandler)
1001             udpserver = socketserver.UDPServer((HOST, PORT), IrkerUDPHandler)
1002             for server in [tcpserver, udpserver]:
1003                 server = threading.Thread(target=server.serve_forever)
1004                 server.setDaemon(True)
1005                 server.start()
1006             try:
1007                 signal.pause()
1008             except KeyboardInterrupt:
1009                 raise SystemExit(1)
1010         except socket.error as e:
1011             LOG.error("server launch failed: %r\n" % e)
1012
1013 # end