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