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 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(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, username=None, realname=None,
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 " + target.password)
292 self.nick(self.nickname)
294 username=target.username or username or 'irker',
295 realname=realname or 'irker relaying client')
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)
307 incoming = self.socket.recv(16384)
309 # Server hung up on us.
310 self.disconnect("Connection reset by peer")
313 # Dead air also indicates a connection reset.
314 self.disconnect("Connection reset by peer")
317 self.buffer.append(incoming)
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)
330 self.handle_event(Event("every_raw_message",
331 self.real_server_name,
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()
346 arguments.append(a[1])
348 command = IRCServerConnection.codemap.get(command, command)
349 if command in ["privmsg", "notice"]:
350 target = arguments.pop(0)
354 if command == "quit":
355 arguments = [arguments[0]]
356 elif command == "ping":
357 target = arguments[0]
359 target = arguments[0]
360 arguments = arguments[1:]
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))
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]:
372 def is_connected(self):
373 return self.socket is not None
375 def disconnect(self, message=""):
376 if self.socket is None:
378 # Don't send a QUIT here - causes infinite loop!
380 self.socket.shutdown(socket.SHUT_WR)
387 Event("disconnect", self.target.server, "", [message]))
389 def join(self, channel, key=""):
390 self.ship("JOIN %s%s" % (channel, (key and (" " + key))))
392 def mode(self, target, command):
393 self.ship("MODE %s %s" % (target, command))
395 def nick(self, newnick):
396 self.ship("NICK " + newnick)
398 def part(self, channel, message=""):
399 cmd_parts = ['PART', channel]
401 cmd_parts.append(message)
402 self.ship(' '.join(cmd_parts))
404 def privmsg(self, target, text):
405 self.ship("PRIVMSG %s :%s" % (target, text))
407 def quit(self, message=""):
408 self.ship("QUIT" + (message and (" :" + message)))
410 def user(self, username, realname):
411 self.ship("USER %s 0 * :%s" % (username, realname))
413 def ship(self, string):
414 "Ship a command to the server, appending CR/LF"
416 self.socket.send(string.encode('utf-8') + b'\r\n')
417 LOG.debug("TO: %s" % string)
419 self.disconnect("Connection reset by peer.")
422 def __init__(self, evtype, source, target, arguments=None):
426 if arguments is None:
428 self.arguments = arguments
430 def is_channel(string):
431 return string and string[0] in "#&+!"
434 def __init__(self, irker, target, nick_template, nick_needs_number=False,
435 password=None, **kwargs):
438 self.nick_template = nick_template
439 self.nick_needs_number = nick_needs_number
440 self.password = password
442 self.nick_trial = None
443 self.connection = 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()
452 def nickname(self, n=None):
453 "Return a name for the nth server connection."
456 if self.nick_needs_number:
457 return (self.nick_template % n)
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())
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
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):
488 self.status = "handshaking"
490 del self.channels_joined[outof]
492 LOG.error("kicked by %s from %s that's not joined" % (
495 while not self.queue.empty():
496 (channel, message, key) = self.queue.get()
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)
509 self.queue.put((channel, message, key))
511 self.queue.put((channel, None, key))
513 "Try to ship pending messages from the queue."
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.
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"
533 elif xmit_timeout or ping_timeout:
535 "timing out connection to %s at %s "
536 "(ping_timeout=%s, xmit_timeout=%s)") % (
537 self.target, time.asctime(), ping_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"
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
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"
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 = {}
568 # IRCServerConnectionError on failure
569 self.connection.connect(
571 nickname=self.nickname(),
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 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.
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)
702 "Represent this instance as a string"
703 return self.servername or self.url or repr(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)
711 raise InvalidRequest(
712 'target URL missing a channel: %r' % self.url)
714 "Return a hashable tuple representing the destination server."
715 return (self.servername, self.port)
718 "Manage connections to a particular server-port combination."
719 def __init__(self, irker, **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)]
731 eligibles[0].enqueue(channel, message, key, quit_after)
733 # All connections are full up. Look for one old enough to be
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))
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)
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)
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
757 "Return all connections with pending traffic."
758 return [x for x in self.connections if not x.queue.empty()]
760 "Return the time of the most recent transmission."
761 return max(x.last_xmit for x in self.connections)
764 "Persistent IRC multiplexer."
765 def __init__(self, logfile=None, **kwargs):
766 self.logfile = logfile
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)
780 def thread_launch(self):
781 thread = threading.Thread(target=self.irc.spin)
782 thread.setDaemon(True)
783 self.irc._thread = thread
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="):
805 connection.mode(cxt.nickname(), "+"+lump[5:])
806 elif lump.startswith("MAXCHANNELS="):
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(",")
815 (prefixes, limit) = token.split(":")
818 cxt.channel_limits[c] = limit
819 LOG.info("%s channel limit map is %s" % (
820 connection.target, cxt.channel_limits))
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)
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."
839 with open(self.logfile, "a") as logfp:
840 logfp.write("%03f|%s|%s\n" % \
841 (time.time(), event.source, event.arguments[0]))
843 "Do we have any pending message traffic?"
844 return [k for (k, v) in self.servers.items() if v.pending()]
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]
868 if not isinstance(url, UNICODE_TYPE):
869 raise InvalidRequest(
870 "malformed request - URL has unexpected type: %r" %
874 except InvalidRequest as e:
875 LOG.error(UNICODE_TYPE(e))
877 targets.append(target)
878 return (targets, message)
880 def handle(self, line, quit_after=False):
881 "Perform a JSON relay request."
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:
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))
914 self.logerr("can't recognize JSON on input: %r" % line)
916 self.logerr("wildly malformed JSON blew the parser stack.")
918 class IrkerTCPHandler(socketserver.StreamRequestHandler):
921 line = self.rfile.readline()
924 if not isinstance(line, UNICODE_TYPE):
925 line = UNICODE_TYPE(line, 'utf-8')
926 irker.handle(line=line.strip())
928 class IrkerUDPHandler(socketserver.BaseRequestHandler):
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())
937 if __name__ == '__main__':
938 parser = argparse.ArgumentParser(
939 description=__doc__.strip().splitlines()[0])
941 '-c', '--ca-file', metavar='PATH',
942 help='file of trusted certificates for SSL/TLS')
944 '-d', '--log-level', metavar='LEVEL', choices=LOG_LEVELS,
945 help='how much to log to the log file (one of %(choices)s)')
947 '-l', '--log-file', metavar='PATH',
948 help='file for saving captured message traffic')
950 '-n', '--nick', metavar='NAME', default='irker%03d',
951 help="nickname (optionally with a '%%.*d' server connection marker)")
953 '-p', '--password', metavar='PASSWORD',
954 help='NickServ password')
956 '-i', '--immediate', metavar='IRC-URL',
958 'send a single message to IRC-URL and exit. The message is the '
959 'first positional argument.'))
961 '-V', '--version', action='version',
962 version='%(prog)s {0}'.format(version))
964 'message', metavar='MESSAGE', nargs='?',
965 help='message for --immediate mode')
966 args = parser.parse_args()
968 handler = logging.StreamHandler()
969 LOG.addHandler(handler)
971 log_level = getattr(logging, args.log_level.upper())
972 LOG.setLevel(log_level)
975 logfile=args.log_file,
976 nick_template=args.nick,
977 nick_needs_number=re.search('%.*d', args.nick),
978 password=args.password,
981 LOG.info("irkerd version %s" % version)
985 '--immediate set (%r), but message argument not given' % (
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)
995 'message argument given (%r), but --immediate not set' % (
998 irker.thread_launch()
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)
1008 except KeyboardInterrupt:
1010 except socket.error as e:
1011 LOG.error("server launch failed: %r\n" % e)