3 irkerd - a simple IRC multiplexer daemon
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
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.
15 Design and code by Eric S. Raymond <esr@thyrsus.com>. See the project
16 resource page at <http://www.catb.org/~esr/irker/>.
18 Requires Python 2.7, or:
19 * 2.6 with the argparse package installed.
22 from __future__ import unicode_literals
23 from __future__ import with_statement
25 # These things might need tuning
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
41 # No user-serviceable parts below this line
50 except ImportError: # Python 2
59 except ImportError: # Python 2
60 import SocketServer as socketserver
67 import urllib.parse as urllib_parse
68 except ImportError: # Python 2
69 import urlparse as urllib_parse
72 LOG = logging.getLogger(__name__)
73 LOG.setLevel(logging.ERROR)
74 LOG_LEVELS = ['critical', 'error', 'warning', 'info', 'debug']
77 UNICODE_TYPE = unicode
78 except NameError: # Python 3
82 # Sketch of implementation:
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.
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
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.
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.
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.
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>.
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.
130 class IRCError(Exception):
135 class InvalidRequest (ValueError):
136 "An invalid JSON request"
141 "An IRC client session to one or more servers."
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))
150 "Initialize a new server-connection object."
151 conn = IRCServerConnection(self)
153 self.server_connections.append(conn)
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.
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]
168 connmap = dict([(c.socket.fileno(), c) for c in connected])
169 (insocks, _o, _e) = select.select(sockets, [], [], timeout)
171 connmap[s.fileno()].consume()
174 time.sleep(nextsleep)
176 def add_event_handler(self, event, handler):
177 "Set a handler to be called later."
179 event_handlers = self.event_handlers.setdefault(event, [])
180 event_handlers.append(handler)
182 def handle_event(self, connection, event):
184 h = self.event_handlers
185 th = sorted(h.get("all_events", []) + h.get(event.type, []))
187 handler(connection, event)
189 def drop_connection(self, connection):
191 self.server_connections.remove(connection)
194 class LineBufferedStream():
195 "Line-buffer a read stream."
196 _crlf_re = re.compile(b'\r?\n')
201 def append(self, newbytes):
202 self.buffer += newbytes
205 "Iterate over lines in the buffer."
206 lines = self._crlf_re.split(self.buffer)
207 self.buffer = lines.pop()
213 class IRCServerConnectionError(IRCError):
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.
223 "005": "featurelist",
224 "432": "erroneusnickname",
225 "433": "nicknameinuse",
226 "436": "nickcollision",
227 "437": "unavailresource",
230 def __init__(self, master):
234 def _wrap_socket(self, socket, target, cafile=None,
235 protocol=ssl.PROTOCOL_TLSv1):
236 try: # Python 3.2 and greater
237 ssl_context = ssl.SSLContext(protocol)
238 except AttributeError: # Python < 3.2
239 self.socket = ssl.wrap_socket(
240 self.socket, cert_reqs=ssl.CERT_REQUIRED,
241 ssl_version=protocol, ca_certs=cafile)
243 ssl_context.verify_mode = ssl.CERT_REQUIRED
245 ssl_context.load_verify_locations(cafile=cafile)
247 ssl_context.set_default_verify_paths()
250 kwargs['server_hostname'] = target.servername
251 self.socket = ssl_context.wrap_socket(self.socket, **kwargs)
254 def _check_hostname(self, target):
255 if hasattr(ssl, 'match_hostname'): # Python >= 3.2
256 cert = self.socket.getpeercert()
258 ssl.match_hostname(cert, target.servername)
259 except ssl.CertificateError as e:
260 raise IRCServerConnectionError(
261 'Invalid SSL/TLS certificate: %s' % e)
264 'cannot check SSL/TLS hostname with Python %s' % sys.version)
266 def connect(self, target, nickname,
267 password=None, username=None, ircname=None, **kwargs):
268 LOG.debug("connect(server=%r, port=%r, nickname=%r, ...)" % (
269 target.servername, target.port, nickname))
270 if self.socket is not None:
271 self.disconnect("Changing servers")
273 self.buffer = LineBufferedStream()
274 self.event_handlers = {}
275 self.real_server_name = ""
277 self.nickname = nickname
279 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
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)
289 self._check_hostname(target=target)
291 self.ship("PASS " + password)
292 self.nick(self.nickname)
293 self.user(username=username or ircname, realname=ircname or nickname)
297 # Without this thread lock, there is a window during which
298 # select() can find a closed socket, leading to an EBADF error.
299 with self.master.mutex:
300 self.disconnect("Closing object")
301 self.master.drop_connection(self)
305 incoming = self.socket.recv(16384)
307 # Server hung up on us.
308 self.disconnect("Connection reset by peer")
311 # Dead air also indicates a connection reset.
312 self.disconnect("Connection reset by peer")
315 self.buffer.append(incoming)
317 for line in self.buffer:
318 if not isinstance(line, UNICODE_TYPE):
319 line = UNICODE_TYPE(line, 'utf-8')
320 LOG.debug("FROM: %s" % line)
328 self.handle_event(Event("every_raw_message",
329 self.real_server_name,
333 m = IRCServerConnection.command_re.match(line)
334 if m.group("prefix"):
335 prefix = m.group("prefix")
336 if not self.real_server_name:
337 self.real_server_name = prefix
338 if m.group("command"):
339 command = m.group("command").lower()
340 if m.group("argument"):
341 a = m.group("argument").split(" :", 1)
342 arguments = a[0].split()
344 arguments.append(a[1])
346 command = IRCServerConnection.codemap.get(command, command)
347 if command in ["privmsg", "notice"]:
348 target = arguments.pop(0)
352 if command == "quit":
353 arguments = [arguments[0]]
354 elif command == "ping":
355 target = arguments[0]
357 target = arguments[0]
358 arguments = arguments[1:]
360 LOG.debug("command: %s, source: %s, target: %s, arguments: %s" % (
361 command, prefix, target, arguments))
362 self.handle_event(Event(command, prefix, target, arguments))
364 def handle_event(self, event):
365 self.master.handle_event(self, event)
366 if event.type in self.event_handlers:
367 for fn in self.event_handlers[event.type]:
370 def is_connected(self):
371 return self.socket is not None
373 def disconnect(self, message=""):
374 if self.socket is None:
376 # Don't send a QUIT here - causes infinite loop!
378 self.socket.shutdown(socket.SHUT_WR)
385 Event("disconnect", self.target.server, "", [message]))
387 def join(self, channel, key=""):
388 self.ship("JOIN %s%s" % (channel, (key and (" " + key))))
390 def mode(self, target, command):
391 self.ship("MODE %s %s" % (target, command))
393 def nick(self, newnick):
394 self.ship("NICK " + newnick)
396 def part(self, channel, message=""):
397 cmd_parts = ['PART', channel]
399 cmd_parts.append(message)
400 self.ship(' '.join(cmd_parts))
402 def privmsg(self, target, text):
403 self.ship("PRIVMSG %s :%s" % (target, text))
405 def quit(self, message=""):
406 self.ship("QUIT" + (message and (" :" + message)))
408 def user(self, username, realname):
409 self.ship("USER %s 0 * :%s" % (username, realname))
411 def ship(self, string):
412 "Ship a command to the server, appending CR/LF"
414 self.socket.send(string.encode('utf-8') + b'\r\n')
415 LOG.debug("TO: %s" % string)
417 self.disconnect("Connection reset by peer.")
420 def __init__(self, evtype, source, target, arguments=None):
424 if arguments is None:
426 self.arguments = arguments
428 def is_channel(string):
429 return string and string[0] in "#&+!"
432 def __init__(self, irker, target, nick_template, nick_needs_number=False,
433 password=None, **kwargs):
436 self.nick_template = nick_template
437 self.nick_needs_number = nick_needs_number
438 self.password = password
440 self.nick_trial = None
441 self.connection = None
443 self.last_xmit = time.time()
444 self.last_ping = time.time()
445 self.channels_joined = {}
446 self.channel_limits = {}
447 # The consumer thread
448 self.queue = queue.Queue()
450 def nickname(self, n=None):
451 "Return a name for the nth server connection."
454 if self.nick_needs_number:
455 return (self.nick_template % n)
457 return self.nick_template
458 def handle_ping(self):
459 "Register the fact that the server has pinged this connection."
460 self.last_ping = time.time()
461 def handle_welcome(self):
462 "The server says we're OK, with a non-conflicting nick."
463 self.status = "ready"
464 LOG.info("nick %s accepted" % self.nickname())
466 self.connection.privmsg("nickserv", "identify %s" % self.password)
467 def handle_badnick(self):
468 "The server says our nick is ill-formed or has a conflict."
469 LOG.info("nick %s rejected" % self.nickname())
470 if self.nick_needs_number:
471 # Randomness prevents a malicious user or bot from
472 # anticipating the next trial name in order to block us
473 # from completing the handshake.
474 self.nick_trial += random.randint(1, 3)
475 self.last_xmit = time.time()
476 self.connection.nick(self.nickname())
477 # Otherwise fall through, it might be possible to
479 def handle_disconnect(self):
480 "Server disconnected us for flooding or some other reason."
481 self.connection = None
482 if self.status != "expired":
483 self.status = "disconnected"
484 def handle_kick(self, outof):
486 self.status = "handshaking"
488 del self.channels_joined[outof]
490 LOG.error("kicked by %s from %s that's not joined" % (
493 while not self.queue.empty():
494 (channel, message, key) = self.queue.get()
496 qcopy.append((channel, message, key))
497 for (channel, message, key) in qcopy:
498 self.queue.put((channel, message, key))
499 self.status = "ready"
500 def enqueue(self, channel, message, key, quit_after=False):
501 "Enque a message for transmission."
502 if self.thread is None or not self.thread.is_alive():
503 self.status = "unseen"
504 self.thread = threading.Thread(target=self.dequeue)
505 self.thread.setDaemon(True)
507 self.queue.put((channel, message, key))
509 self.queue.put((channel, None, key))
511 "Try to ship pending messages from the queue."
514 # We want to be kind to the IRC servers and not hold unused
515 # sockets open forever, so they have a time-to-live. The
516 # loop is coded this particular way so that we can drop
517 # the actual server connection when its time-to-live
518 # expires, then reconnect and resume transmission if the
519 # queue fills up again.
520 if self.queue.empty():
521 # Queue is empty, at some point we want to time out
522 # the connection rather than holding a socket open in
523 # the server forever.
525 xmit_timeout = now > self.last_xmit + XMIT_TTL
526 ping_timeout = now > self.last_ping + PING_TTL
527 if self.status == "disconnected":
528 # If the queue is empty, we can drop this connection.
529 self.status = "expired"
531 elif xmit_timeout or ping_timeout:
533 "timing out connection to %s at %s "
534 "(ping_timeout=%s, xmit_timeout=%s)") % (
535 self.target, time.asctime(), ping_timeout,
537 with self.irker.irc.mutex:
538 self.connection.context = None
539 self.connection.quit("transmission timeout")
540 self.connection = None
541 self.status = "disconnected"
543 # Prevent this thread from hogging the CPU by pausing
544 # for just a little bit after the queue-empty check.
545 # As long as this is less that the duration of a human
546 # reflex arc it is highly unlikely any human will ever
548 time.sleep(ANTI_BUZZ_DELAY)
549 elif self.status == "disconnected" \
550 and time.time() > self.last_xmit + DISCONNECT_TTL:
551 # Queue is nonempty, but the IRC server might be
552 # down. Letting failed connections retain queue
553 # space forever would be a memory leak.
554 self.status = "expired"
556 elif not self.connection and self.status != "expired":
557 # Queue is nonempty but server isn't connected.
558 with self.irker.irc.mutex:
559 self.connection = self.irker.irc.newserver()
560 self.connection.context = self
561 # Try to avoid colliding with other instances
562 self.nick_trial = random.randint(1, 990)
563 self.channels_joined = {}
566 # IRCServerConnectionError on failure
567 self.connection.connect(
569 nickname=self.nickname(),
571 ircname="irker relaying client",
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:
580 self.status = "expired"
582 elif self.status == "handshaking":
583 if time.time() > self.last_xmit + HANDSHAKE_TTL:
584 self.status = "expired"
587 # Don't buzz on the empty-queue test while we're
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"
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
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.
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]
620 self.connection.privmsg(channel, segment)
621 except ValueError as err:
623 "irclib rejected a message to %s on %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":
634 "We're expired but still running! This is a bug.")
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())
643 # Make sure we don't leave any zombies behind
644 self.connection.close()
646 # Irclib has a habit of throwing fresh exceptions here. Ignore that
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:
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]:
664 return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
666 return len(self.channels_joined) < CHANNEL_MAX
669 "Represent a transmission target."
670 def __init__(self, url):
672 parsed = urllib_parse.urlparse(url)
673 self.ssl = parsed.scheme == 'ircs'
675 default_ircport = 6697
677 default_ircport = 6667
678 irchost, _, ircport = parsed.netloc.partition(':')
680 ircport = default_ircport
681 self.servername = irchost
682 # IRC channel names are case-insensitive. If we don't smash
683 # case here we may run into problems later. There was a bug
684 # observed on irc.rizon.net where an irkerd user specified #Channel,
685 # got kicked, and irkerd crashed because the server returned
686 # "#channel" in the notification that our kick handler saw.
687 self.channel = parsed.path.lstrip('/').lower()
688 # This deals with a tweak in recent versions of urlparse.
690 self.channel += "#" + parsed.fragment
691 isnick = self.channel.endswith(",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
699 self.key = re.sub("^key=", "", parsed.query)
700 self.port = int(ircport)
703 "Represent this instance as a string"
704 return self.servername or self.url or repr(self)
707 "Raise InvalidRequest if the URL is missing a critical component"
708 if not self.servername:
709 raise InvalidRequest(
710 'target URL missing a servername: %r' % self.url)
712 raise InvalidRequest(
713 'target URL missing a channel: %r' % self.url)
715 "Return a hashable tuple representing the destination server."
716 return (self.servername, self.port)
719 "Manage connections to a particular server-port combination."
720 def __init__(self, irker, **kwargs):
723 self.connections = []
724 def dispatch(self, channel, message, key, quit_after=False):
725 "Dispatch messages for our server-port combination."
726 # First, check if there is room for another channel
727 # on any of our existing connections.
728 connections = [x for x in self.connections if x.live()]
729 eligibles = [x for x in connections if x.joined_to(channel)] \
730 or [x for x in connections if x.accepting(channel)]
732 eligibles[0].enqueue(channel, message, key, quit_after)
734 # All connections are full up. Look for one old enough to be
737 for connection in connections:
738 for (chan, age) in connections.channels_joined.items():
739 if age < time.time() - CHANNEL_TTL:
740 ancients.append((connection, chan, age))
742 ancients.sort(key=lambda x: x[2])
743 (found_connection, drop_channel, _drop_age) = ancients[0]
744 found_connection.part(drop_channel, "scavenged by irkerd")
745 del found_connection.channels_joined[drop_channel]
746 #time.sleep(ANTI_FLOOD_DELAY)
747 found_connection.enqueue(channel, message, key, quit_after)
749 # All existing channels had recent activity
750 newconn = Connection(self.irker, **self.kwargs)
751 self.connections.append(newconn)
752 newconn.enqueue(channel, message, key, quit_after)
754 "Does this server-port combination have any live connections?"
755 self.connections = [x for x in self.connections if x.live()]
756 return len(self.connections) > 0
758 "Return all connections with pending traffic."
759 return [x for x in self.connections if not x.queue.empty()]
761 "Return the time of the most recent transmission."
762 return max(x.last_xmit for x in self.connections)
765 "Persistent IRC multiplexer."
766 def __init__(self, logfile=None, **kwargs):
767 self.logfile = logfile
769 self.irc = IRCClient()
770 self.irc.add_event_handler("ping", self._handle_ping)
771 self.irc.add_event_handler("welcome", self._handle_welcome)
772 self.irc.add_event_handler("erroneusnickname", self._handle_badnick)
773 self.irc.add_event_handler("nicknameinuse", self._handle_badnick)
774 self.irc.add_event_handler("nickcollision", self._handle_badnick)
775 self.irc.add_event_handler("unavailresource", self._handle_badnick)
776 self.irc.add_event_handler("featurelist", self._handle_features)
777 self.irc.add_event_handler("disconnect", self._handle_disconnect)
778 self.irc.add_event_handler("kick", self._handle_kick)
779 self.irc.add_event_handler("every_raw_message", self._handle_every_raw_message)
781 def thread_launch(self):
782 thread = threading.Thread(target=self.irc.spin)
783 thread.setDaemon(True)
784 self.irc._thread = thread
786 def _handle_ping(self, connection, _event):
787 "PING arrived, bump the last-received time for the connection."
788 if connection.context:
789 connection.context.handle_ping()
790 def _handle_welcome(self, connection, _event):
791 "Welcome arrived, nick accepted for this connection."
792 if connection.context:
793 connection.context.handle_welcome()
794 def _handle_badnick(self, connection, _event):
795 "Nick not accepted for this connection."
796 if connection.context:
797 connection.context.handle_badnick()
798 def _handle_features(self, connection, event):
799 "Determine if and how we can set deaf mode."
800 if connection.context:
801 cxt = connection.context
802 arguments = event.arguments
803 for lump in arguments:
804 if lump.startswith("DEAF="):
806 connection.mode(cxt.nickname(), "+"+lump[5:])
807 elif lump.startswith("MAXCHANNELS="):
810 cxt.channel_limits[pref] = m
811 LOG.info("%s maxchannels is %d" % (connection.server, m))
812 elif lump.startswith("CHANLIMIT=#:"):
813 limits = lump[10:].split(",")
816 (prefixes, limit) = token.split(":")
819 cxt.channel_limits[c] = limit
820 LOG.info("%s channel limit map is %s" % (
821 connection.target, cxt.channel_limits))
823 LOG.error("ill-formed CHANLIMIT property")
824 def _handle_disconnect(self, connection, _event):
825 "Server hung up the connection."
826 LOG.info("server %s disconnected" % connection.target)
828 if connection.context:
829 connection.context.handle_disconnect()
830 def _handle_kick(self, connection, event):
831 "Server hung up the connection."
832 target = event.target
833 LOG.info("irker has been kicked from %s on %s" % (
834 target, connection.target))
835 if connection.context:
836 connection.context.handle_kick(target)
837 def _handle_every_raw_message(self, _connection, event):
838 "Log all messages when in watcher mode."
840 with open(self.logfile, "a") as logfp:
841 logfp.write("%03f|%s|%s\n" % \
842 (time.time(), event.source, event.arguments[0]))
844 "Do we have any pending message traffic?"
845 return [k for (k, v) in self.servers.items() if v.pending()]
847 def _parse_request(self, line):
848 "Request-parsing helper for the handle() method"
849 request = json.loads(line.strip())
850 if not isinstance(request, dict):
851 raise InvalidRequest(
852 "request is not a JSON dictionary: %r" % request)
853 if "to" not in request or "privmsg" not in request:
854 raise InvalidRequest(
855 "malformed request - 'to' or 'privmsg' missing: %r" % request)
856 channels = request['to']
857 message = request['privmsg']
858 if not isinstance(channels, (list, UNICODE_TYPE)):
859 raise InvalidRequest(
860 "malformed request - unexpected channel type: %r" % channels)
861 if not isinstance(message, UNICODE_TYPE):
862 raise InvalidRequest(
863 "malformed request - unexpected message type: %r" % message)
864 if not isinstance(channels, list):
865 channels = [channels]
869 if not isinstance(url, UNICODE_TYPE):
870 raise InvalidRequest(
871 "malformed request - URL has unexpected type: %r" %
875 except InvalidRequest as e:
876 LOG.error(UNICODE_TYPE(e))
878 targets.append(target)
879 return (targets, message)
881 def handle(self, line, quit_after=False):
882 "Perform a JSON relay request."
884 targets, message = self._parse_request(line=line)
885 for target in targets:
886 if target.server() not in self.servers:
887 self.servers[target.server()] = Dispatcher(
888 self, target=target, **self.kwargs)
889 self.servers[target.server()].dispatch(
890 target.channel, message, target.key, quit_after=quit_after)
891 # GC dispatchers with no active connections
892 servernames = self.servers.keys()
893 for servername in servernames:
894 if not self.servers[servername].live():
895 del self.servers[servername]
896 # If we might be pushing a resource limit even
897 # after garbage collection, remove a session. The
898 # goal here is to head off DoS attacks that aim at
899 # exhausting thread space or file descriptors.
900 # The cost is that attempts to DoS this service
901 # will cause lots of join/leave spam as we
902 # scavenge old channels after connecting to new
903 # ones. The particular method used for selecting a
904 # session to be terminated doesn't matter much; we
905 # choose the one longest idle on the assumption
906 # that message activity is likely to be clumpy.
907 if len(self.servers) >= CONNECTION_MAX:
910 key=lambda name: self.servers[name].last_xmit())
911 del self.servers[oldest]
912 except InvalidRequest as e:
913 LOG.error(UNICODE_TYPE(e))
915 self.logerr("can't recognize JSON on input: %r" % line)
917 self.logerr("wildly malformed JSON blew the parser stack.")
919 class IrkerTCPHandler(socketserver.StreamRequestHandler):
922 line = self.rfile.readline()
925 if not isinstance(line, UNICODE_TYPE):
926 line = UNICODE_TYPE(line, 'utf-8')
927 irker.handle(line=line.strip())
929 class IrkerUDPHandler(socketserver.BaseRequestHandler):
931 line = self.request[0].strip()
932 #socket = self.request[1]
933 if not isinstance(line, UNICODE_TYPE):
934 line = UNICODE_TYPE(line, 'utf-8')
935 irker.handle(line=line.strip())
938 if __name__ == '__main__':
939 parser = argparse.ArgumentParser(
940 description=__doc__.strip().splitlines()[0])
942 '-c', '--ca-file', metavar='PATH',
943 help='file of trusted certificates for SSL/TLS')
945 '-d', '--log-level', metavar='LEVEL', choices=LOG_LEVELS,
946 help='file of trusted certificates for SSL/TLS')
948 '-l', '--log-file', metavar='PATH',
949 help='file for saving captured message traffic')
951 '-n', '--nick', metavar='NAME', default='irker%03d',
952 help="nickname (optionally with a '%%.*d' server connection marker)")
954 '-p', '--password', metavar='PASSWORD',
955 help='NickServ password')
957 '-i', '--immediate', action='store_const', const=True,
958 help='disconnect after sending each message')
960 '-V', '--version', action='version',
961 version='%(prog)s {0}'.format(version))
962 args = parser.parse_args()
964 handler = logging.StreamHandler()
965 LOG.addHandler(handler)
967 log_level = getattr(logging, args.log_level.upper())
968 LOG.setLevel(log_level)
971 logfile=args.log_file,
972 nick_template=args.nick,
973 nick_needs_number=re.search('%.*d', args.nick),
974 password=args.password,
977 LOG.info("irkerd version %s" % version)
979 irker.irc.add_event_handler("quit", lambda _c, _e: sys.exit(0))
980 irker.handle('{"to":"%s","privmsg":"%s"}' % (immediate, arguments[0]), quit_after=True)
983 irker.thread_launch()
985 tcpserver = socketserver.TCPServer((HOST, PORT), IrkerTCPHandler)
986 udpserver = socketserver.UDPServer((HOST, PORT), IrkerUDPHandler)
987 for server in [tcpserver, udpserver]:
988 server = threading.Thread(target=server.serve_forever)
989 server.setDaemon(True)
993 except KeyboardInterrupt:
995 except socket.error as e:
996 LOG.error("server launch failed: %r\n" % e)