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 with_statement
24 # These things might need tuning
29 XMIT_TTL = (3 * 60 * 60) # Time to live, seconds from last transmit
30 PING_TTL = (15 * 60) # Time to live, seconds from last PING
31 HANDSHAKE_TTL = 60 # Time to live, seconds from nick transmit
32 CHANNEL_TTL = (3 * 60 * 60) # Time to live, seconds from last transmit
33 DISCONNECT_TTL = (24 * 60 * 60) # Time to live, seconds from last connect
34 UNSEEN_TTL = 60 # Time to live, seconds since first request
35 CHANNEL_MAX = 18 # Max channels open per socket (default)
36 ANTI_FLOOD_DELAY = 1.0 # Anti-flood delay after transmissions, seconds
37 ANTI_BUZZ_DELAY = 0.09 # Anti-buzz delay after queue-empty check
38 CONNECTION_MAX = 200 # To avoid hitting a thread limit
40 # No user-serviceable parts below this line
49 except ImportError: # Python 2
58 except ImportError: # Python 2
59 import SocketServer as socketserver
64 import urllib.parse as urllib_parse
65 except ImportError: # Python 2
66 import urlparse as urllib_parse
69 LOG = logging.getLogger(__name__)
70 LOG.setLevel(logging.ERROR)
71 LOG_LEVELS = ['critical', 'error', 'warning', 'info', 'debug']
74 # Sketch of implementation:
76 # One Irker object manages multiple IRC sessions. It holds a map of
77 # Dispatcher objects, one per (server, port) combination, which are
78 # responsible for routing messages to one of any number of Connection
79 # objects that do the actual socket conversations. The reason for the
80 # Dispatcher layer is that IRC daemons limit the number of channels a
81 # client (that is, from the daemon's point of view, a socket) can be
82 # joined to, so each session to a server needs a flock of Connection
83 # instances each with its own socket.
85 # Connections are timed out and removed when either they haven't seen a
86 # PING for a while (indicating that the server may be stalled or down)
87 # or there has been no message traffic to them for a while, or
88 # even if the queue is nonempty but efforts to connect have failed for
91 # There are multiple threads. One accepts incoming traffic from all
92 # servers. Each Connection also has a consumer thread and a
93 # thread-safe message queue. The program main appends messages to
94 # queues as JSON requests are received; the consumer threads try to
95 # ship them to servers. When a socket write stalls, it only blocks an
96 # individual consumer thread; if it stalls long enough, the session
97 # will be timed out. This solves the biggest problem with a
98 # single-threaded implementation, which is that you can't count on a
99 # single stalled write not hanging all other traffic - you're at the
100 # mercy of the length of the buffers in the TCP/IP layer.
102 # Message delivery is thus not reliable in the face of network stalls,
103 # but this was considered acceptable because IRC (notoriously) has the
104 # same problem - there is little point in reliable delivery to a relay
105 # that is down or unreliable.
107 # This code uses only NICK, JOIN, PART, MODE, PRIVMSG, USER, and QUIT.
108 # It is strictly compliant to RFC1459, except for the interpretation and
109 # use of the DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features.
111 # CHANLIMIT is as described in the Internet RFC draft
112 # draft-brocklesby-irc-isupport-03 at <http://www.mirc.com/isupport.html>.
113 # The ",isnick" feature is as described in
114 # <http://ftp.ics.uci.edu/pub/ietf/uri/draft-mirashi-url-irc-01.txt>.
116 # Historical note: the IRCClient and IRCServerConnection classes
117 # (~270LOC) replace the overweight, overcomplicated 3KLOC mass of
118 # irclib code that irker formerly used as a service library. They
119 # still look similar to parts of irclib because I contributed to that
120 # code before giving up on it.
122 class IRCError(Exception):
127 class InvalidRequest (ValueError):
128 "An invalid JSON request"
133 "An IRC client session to one or more servers."
135 self.mutex = threading.RLock()
136 self.server_connections = []
137 self.event_handlers = {}
138 self.add_event_handler("ping",
139 lambda c, e: c.ship("PONG %s" % e.target))
142 "Initialize a new server-connection object."
143 conn = IRCServerConnection(self)
145 self.server_connections.append(conn)
148 def spin(self, timeout=0.2):
149 "Spin processing data from connections forever."
150 # Outer loop should specifically *not* be mutex-locked.
151 # Otherwise no other thread would ever be able to change
152 # the shared state of an IRC object running this function.
156 connected = [x for x in self.server_connections
157 if x is not None and x.socket is not None]
158 sockets = [x.socket for x in connected]
160 connmap = dict([(c.socket.fileno(), c) for c in connected])
161 (insocks, _o, _e) = select.select(sockets, [], [], timeout)
163 connmap[s.fileno()].consume()
166 time.sleep(nextsleep)
168 def add_event_handler(self, event, handler):
169 "Set a handler to be called later."
171 event_handlers = self.event_handlers.setdefault(event, [])
172 event_handlers.append(handler)
174 def handle_event(self, connection, event):
176 h = self.event_handlers
177 th = sorted(h.get("all_events", []) + h.get(event.type, []))
179 handler(connection, event)
181 def drop_connection(self, connection):
183 self.server_connections.remove(connection)
186 class LineBufferedStream():
187 "Line-buffer a read stream."
188 _crlf_re = re.compile(b'\r?\n')
193 def append(self, newbytes):
194 self.buffer += newbytes
197 "Iterate over lines in the buffer."
198 lines = self._crlf_re.split(self.buffer)
199 self.buffer = lines.pop()
205 class IRCServerConnectionError(IRCError):
208 class IRCServerConnection():
209 command_re = re.compile("^(:(?P<prefix>[^ ]+) +)?(?P<command>[^ ]+)( *(?P<argument> .+))?")
210 # The full list of numeric-to-event mappings is in Perl's Net::IRC.
211 # We only need to ensure that if some ancient server throws numerics
212 # for the ones we actually want to catch, they're mapped.
215 "005": "featurelist",
216 "432": "erroneusnickname",
217 "433": "nicknameinuse",
218 "436": "nickcollision",
219 "437": "unavailresource",
222 def __init__(self, master):
226 def connect(self, target, nickname,
227 password=None, username=None, ircname=None):
228 LOG.debug("connect(server=%r, port=%r, nickname=%r, ...)" % (
229 target.servername, target.port, nickname))
230 if self.socket is not None:
231 self.disconnect("Changing servers")
233 self.buffer = LineBufferedStream()
234 self.event_handlers = {}
235 self.real_server_name = ""
237 self.nickname = nickname
239 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
240 self.socket.bind(('', 0))
241 self.socket.connect((target.servername, target.port))
242 except socket.error as err:
243 raise IRCServerConnectionError("Couldn't connect to socket: %s" % err)
246 self.ship("PASS " + password)
247 self.nick(self.nickname)
248 self.user(username=username or ircname, realname=ircname or nickname)
252 # Without this thread lock, there is a window during which
253 # select() can find a closed socket, leading to an EBADF error.
254 with self.master.mutex:
255 self.disconnect("Closing object")
256 self.master.drop_connection(self)
260 incoming = self.socket.recv(16384)
262 # Server hung up on us.
263 self.disconnect("Connection reset by peer")
266 # Dead air also indicates a connection reset.
267 self.disconnect("Connection reset by peer")
270 self.buffer.append(incoming)
272 for line in self.buffer:
273 LOG.debug("FROM: %s" % line)
281 self.handle_event(Event("every_raw_message",
282 self.real_server_name,
286 m = IRCServerConnection.command_re.match(line)
287 if m.group("prefix"):
288 prefix = m.group("prefix")
289 if not self.real_server_name:
290 self.real_server_name = prefix
291 if m.group("command"):
292 command = m.group("command").lower()
293 if m.group("argument"):
294 a = m.group("argument").split(" :", 1)
295 arguments = a[0].split()
297 arguments.append(a[1])
299 command = IRCServerConnection.codemap.get(command, command)
300 if command in ["privmsg", "notice"]:
301 target = arguments.pop(0)
305 if command == "quit":
306 arguments = [arguments[0]]
307 elif command == "ping":
308 target = arguments[0]
310 target = arguments[0]
311 arguments = arguments[1:]
313 LOG.debug("command: %s, source: %s, target: %s, arguments: %s" % (
314 command, prefix, target, arguments))
315 self.handle_event(Event(command, prefix, target, arguments))
317 def handle_event(self, event):
318 self.master.handle_event(self, event)
319 if event.type in self.event_handlers:
320 for fn in self.event_handlers[event.type]:
323 def is_connected(self):
324 return self.socket is not None
326 def disconnect(self, message=""):
327 if self.socket is None:
329 # Don't send a QUIT here - causes infinite loop!
331 self.socket.shutdown(socket.SHUT_WR)
338 Event("disconnect", self.target.server, "", [message]))
340 def join(self, channel, key=""):
341 self.ship("JOIN %s%s" % (channel, (key and (" " + key))))
343 def mode(self, target, command):
344 self.ship("MODE %s %s" % (target, command))
346 def nick(self, newnick):
347 self.ship("NICK " + newnick)
349 def part(self, channel, message=""):
350 cmd_parts = ['PART', channel]
352 cmd_parts.append(message)
353 self.ship(' '.join(cmd_parts))
355 def privmsg(self, target, text):
356 self.ship("PRIVMSG %s :%s" % (target, text))
358 def quit(self, message=""):
359 self.ship("QUIT" + (message and (" :" + message)))
361 def user(self, username, realname):
362 self.ship("USER %s 0 * :%s" % (username, realname))
364 def ship(self, string):
365 "Ship a command to the server, appending CR/LF"
367 self.socket.send(string.encode('utf-8') + b'\r\n')
368 LOG.debug("TO: %s" % string)
370 self.disconnect("Connection reset by peer.")
373 def __init__(self, evtype, source, target, arguments=None):
377 if arguments is None:
379 self.arguments = arguments
381 def is_channel(string):
382 return string and string[0] in "#&+!"
385 def __init__(self, irker, target, nick_template, nick_needs_number=False,
386 password=None, **kwargs):
389 self.nick_template = nick_template
390 self.nick_needs_number = nick_needs_number
391 self.password = password
393 self.nick_trial = None
394 self.connection = None
396 self.last_xmit = time.time()
397 self.last_ping = time.time()
398 self.channels_joined = {}
399 self.channel_limits = {}
400 # The consumer thread
401 self.queue = queue.Queue()
403 def nickname(self, n=None):
404 "Return a name for the nth server connection."
407 if self.nick_needs_number:
408 return (self.nick_template % n)
410 return self.nick_template
411 def handle_ping(self):
412 "Register the fact that the server has pinged this connection."
413 self.last_ping = time.time()
414 def handle_welcome(self):
415 "The server says we're OK, with a non-conflicting nick."
416 self.status = "ready"
417 LOG.info("nick %s accepted" % self.nickname())
419 self.connection.privmsg("nickserv", "identify %s" % self.password)
420 def handle_badnick(self):
421 "The server says our nick is ill-formed or has a conflict."
422 LOG.info("nick %s rejected" % self.nickname())
423 if self.nick_needs_number:
424 # Randomness prevents a malicious user or bot from
425 # anticipating the next trial name in order to block us
426 # from completing the handshake.
427 self.nick_trial += random.randint(1, 3)
428 self.last_xmit = time.time()
429 self.connection.nick(self.nickname())
430 # Otherwise fall through, it might be possible to
432 def handle_disconnect(self):
433 "Server disconnected us for flooding or some other reason."
434 self.connection = None
435 if self.status != "expired":
436 self.status = "disconnected"
437 def handle_kick(self, outof):
439 self.status = "handshaking"
441 del self.channels_joined[outof]
443 LOG.error("kicked by %s from %s that's not joined" % (
446 while not self.queue.empty():
447 (channel, message, key) = self.queue.get()
449 qcopy.append((channel, message, key))
450 for (channel, message, key) in qcopy:
451 self.queue.put((channel, message, key))
452 self.status = "ready"
453 def enqueue(self, channel, message, key, quit_after=False):
454 "Enque a message for transmission."
455 if self.thread is None or not self.thread.is_alive():
456 self.status = "unseen"
457 self.thread = threading.Thread(target=self.dequeue)
458 self.thread.setDaemon(True)
460 self.queue.put((channel, message, key))
462 self.queue.put((channel, None, key))
464 "Try to ship pending messages from the queue."
467 # We want to be kind to the IRC servers and not hold unused
468 # sockets open forever, so they have a time-to-live. The
469 # loop is coded this particular way so that we can drop
470 # the actual server connection when its time-to-live
471 # expires, then reconnect and resume transmission if the
472 # queue fills up again.
473 if self.queue.empty():
474 # Queue is empty, at some point we want to time out
475 # the connection rather than holding a socket open in
476 # the server forever.
478 xmit_timeout = now > self.last_xmit + XMIT_TTL
479 ping_timeout = now > self.last_ping + PING_TTL
480 if self.status == "disconnected":
481 # If the queue is empty, we can drop this connection.
482 self.status = "expired"
484 elif xmit_timeout or ping_timeout:
486 "timing out connection to %s at %s "
487 "(ping_timeout=%s, xmit_timeout=%s)") % (
488 self.target, time.asctime(), ping_timeout,
490 with self.irker.irc.mutex:
491 self.connection.context = None
492 self.connection.quit("transmission timeout")
493 self.connection = None
494 self.status = "disconnected"
496 # Prevent this thread from hogging the CPU by pausing
497 # for just a little bit after the queue-empty check.
498 # As long as this is less that the duration of a human
499 # reflex arc it is highly unlikely any human will ever
501 time.sleep(ANTI_BUZZ_DELAY)
502 elif self.status == "disconnected" \
503 and time.time() > self.last_xmit + DISCONNECT_TTL:
504 # Queue is nonempty, but the IRC server might be
505 # down. Letting failed connections retain queue
506 # space forever would be a memory leak.
507 self.status = "expired"
509 elif not self.connection and self.status != "expired":
510 # Queue is nonempty but server isn't connected.
511 with self.irker.irc.mutex:
512 self.connection = self.irker.irc.newserver()
513 self.connection.context = self
514 # Try to avoid colliding with other instances
515 self.nick_trial = random.randint(1, 990)
516 self.channels_joined = {}
519 # IRCServerConnectionError on failure
520 self.connection.connect(
522 nickname=self.nickname(),
524 ircname="irker relaying client",
526 self.status = "handshaking"
527 LOG.info("XMIT_TTL bump (%s connection) at %s" % (
528 self.target, time.asctime()))
529 self.last_xmit = time.time()
530 self.last_ping = time.time()
531 except IRCServerConnectionError:
532 self.status = "expired"
534 elif self.status == "handshaking":
535 if time.time() > self.last_xmit + HANDSHAKE_TTL:
536 self.status = "expired"
539 # Don't buzz on the empty-queue test while we're
541 time.sleep(ANTI_BUZZ_DELAY)
542 elif self.status == "unseen" \
543 and time.time() > self.last_xmit + UNSEEN_TTL:
544 # Nasty people could attempt a denial-of-service
545 # attack by flooding us with requests with invalid
546 # servernames. We guard against this by rapidly
547 # expiring connections that have a nonempty queue but
548 # have never had a successful open.
549 self.status = "expired"
551 elif self.status == "ready":
552 (channel, message, key) = self.queue.get()
553 if channel not in self.channels_joined:
554 self.connection.join(channel, key=key)
555 LOG.info("joining %s on %s." % (channel, self.target))
556 # None is magic - it's a request to quit the server
558 self.connection.quit()
559 # An empty message might be used as a keepalive or
560 # to join a channel for logging, so suppress the
561 # privmsg send unless there is actual traffic.
563 for segment in message.split("\n"):
564 # Truncate the message if it's too long,
565 # but we're working with characters here,
566 # not bytes, so we could be off.
567 # 500 = 512 - CRLF - 'PRIVMSG ' - ' :'
568 maxlength = 500 - len(channel)
569 if len(segment) > maxlength:
570 segment = segment[:maxlength]
572 self.connection.privmsg(channel, segment)
573 except ValueError as err:
575 "irclib rejected a message to %s on %s "
577 channel, self.target, str(err)))
578 LOG.debug(err.format_exc())
579 time.sleep(ANTI_FLOOD_DELAY)
580 self.last_xmit = self.channels_joined[channel] = time.time()
581 LOG.info("XMIT_TTL bump (%s transmission) at %s" % (
582 self.target, time.asctime()))
583 self.queue.task_done()
584 elif self.status == "expired":
586 "We're expired but still running! This is a bug.")
588 except Exception as e:
589 LOG.error("exception %s in thread for %s" % (e, self.target))
590 # Maybe this should have its own status?
591 self.status = "expired"
592 LOG.debug(e.format_exc())
595 # Make sure we don't leave any zombies behind
596 self.connection.close()
598 # Irclib has a habit of throwing fresh exceptions here. Ignore that
601 "Should this connection not be scavenged?"
602 return self.status != "expired"
603 def joined_to(self, channel):
604 "Is this connection joined to the specified channel?"
605 return channel in self.channels_joined
606 def accepting(self, channel):
607 "Can this connection accept a join of this channel?"
608 if self.channel_limits:
610 for already in self.channels_joined:
611 # This obscure code is because the RFCs allow separate limits
612 # by channel type (indicated by the first character of the name)
613 # a feature that is almost never actually used.
614 if already[0] == channel[0]:
616 return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
618 return len(self.channels_joined) < CHANNEL_MAX
621 "Represent a transmission target."
622 def __init__(self, url):
624 parsed = urllib_parse.urlparse(url)
625 irchost, _, ircport = parsed.netloc.partition(':')
628 self.servername = irchost
629 # IRC channel names are case-insensitive. If we don't smash
630 # case here we may run into problems later. There was a bug
631 # observed on irc.rizon.net where an irkerd user specified #Channel,
632 # got kicked, and irkerd crashed because the server returned
633 # "#channel" in the notification that our kick handler saw.
634 self.channel = parsed.path.lstrip('/').lower()
635 # This deals with a tweak in recent versions of urlparse.
637 self.channel += "#" + parsed.fragment
638 isnick = self.channel.endswith(",isnick")
640 self.channel = self.channel[:-7]
641 if self.channel and not isnick and self.channel[0] not in "#&+":
642 self.channel = "#" + self.channel
643 # support both channel?secret and channel?key=secret
646 self.key = re.sub("^key=", "", parsed.query)
647 self.port = int(ircport)
650 "Represent this instance as a string"
651 return self.servername or self.url or repr(self)
654 "Raise InvalidRequest if the URL is missing a critical component"
655 if not self.servername:
656 raise InvalidRequest(
657 'target URL missing a servername: %r' % self.url)
659 raise InvalidRequest(
660 'target URL missing a channel: %r' % self.url)
662 "Return a hashable tuple representing the destination server."
663 return (self.servername, self.port)
666 "Manage connections to a particular server-port combination."
667 def __init__(self, irker, **kwargs):
670 self.connections = []
671 def dispatch(self, channel, message, key, quit_after=False):
672 "Dispatch messages for our server-port combination."
673 # First, check if there is room for another channel
674 # on any of our existing connections.
675 connections = [x for x in self.connections if x.live()]
676 eligibles = [x for x in connections if x.joined_to(channel)] \
677 or [x for x in connections if x.accepting(channel)]
679 eligibles[0].enqueue(channel, message, key, quit_after)
681 # All connections are full up. Look for one old enough to be
684 for connection in connections:
685 for (chan, age) in connections.channels_joined.items():
686 if age < time.time() - CHANNEL_TTL:
687 ancients.append((connection, chan, age))
689 ancients.sort(key=lambda x: x[2])
690 (found_connection, drop_channel, _drop_age) = ancients[0]
691 found_connection.part(drop_channel, "scavenged by irkerd")
692 del found_connection.channels_joined[drop_channel]
693 #time.sleep(ANTI_FLOOD_DELAY)
694 found_connection.enqueue(channel, message, key, quit_after)
696 # All existing channels had recent activity
697 newconn = Connection(self.irker, **self.kwargs)
698 self.connections.append(newconn)
699 newconn.enqueue(channel, message, key, quit_after)
701 "Does this server-port combination have any live connections?"
702 self.connections = [x for x in self.connections if x.live()]
703 return len(self.connections) > 0
705 "Return all connections with pending traffic."
706 return [x for x in self.connections if not x.queue.empty()]
708 "Return the time of the most recent transmission."
709 return max(x.last_xmit for x in self.connections)
712 "Persistent IRC multiplexer."
713 def __init__(self, logfile=None, **kwargs):
714 self.logfile = logfile
716 self.irc = IRCClient()
717 self.irc.add_event_handler("ping", self._handle_ping)
718 self.irc.add_event_handler("welcome", self._handle_welcome)
719 self.irc.add_event_handler("erroneusnickname", self._handle_badnick)
720 self.irc.add_event_handler("nicknameinuse", self._handle_badnick)
721 self.irc.add_event_handler("nickcollision", self._handle_badnick)
722 self.irc.add_event_handler("unavailresource", self._handle_badnick)
723 self.irc.add_event_handler("featurelist", self._handle_features)
724 self.irc.add_event_handler("disconnect", self._handle_disconnect)
725 self.irc.add_event_handler("kick", self._handle_kick)
726 self.irc.add_event_handler("every_raw_message", self._handle_every_raw_message)
728 def thread_launch(self):
729 thread = threading.Thread(target=self.irc.spin)
730 thread.setDaemon(True)
731 self.irc._thread = thread
733 def _handle_ping(self, connection, _event):
734 "PING arrived, bump the last-received time for the connection."
735 if connection.context:
736 connection.context.handle_ping()
737 def _handle_welcome(self, connection, _event):
738 "Welcome arrived, nick accepted for this connection."
739 if connection.context:
740 connection.context.handle_welcome()
741 def _handle_badnick(self, connection, _event):
742 "Nick not accepted for this connection."
743 if connection.context:
744 connection.context.handle_badnick()
745 def _handle_features(self, connection, event):
746 "Determine if and how we can set deaf mode."
747 if connection.context:
748 cxt = connection.context
749 arguments = event.arguments
750 for lump in arguments:
751 if lump.startswith("DEAF="):
753 connection.mode(cxt.nickname(), "+"+lump[5:])
754 elif lump.startswith("MAXCHANNELS="):
757 cxt.channel_limits[pref] = m
758 LOG.info("%s maxchannels is %d" % (connection.server, m))
759 elif lump.startswith("CHANLIMIT=#:"):
760 limits = lump[10:].split(",")
763 (prefixes, limit) = token.split(":")
766 cxt.channel_limits[c] = limit
767 LOG.info("%s channel limit map is %s" % (
768 connection.target, cxt.channel_limits))
770 LOG.error("ill-formed CHANLIMIT property")
771 def _handle_disconnect(self, connection, _event):
772 "Server hung up the connection."
773 LOG.info("server %s disconnected" % connection.target)
775 if connection.context:
776 connection.context.handle_disconnect()
777 def _handle_kick(self, connection, event):
778 "Server hung up the connection."
779 target = event.target
780 LOG.info("irker has been kicked from %s on %s" % (
781 target, connection.target))
782 if connection.context:
783 connection.context.handle_kick(target)
784 def _handle_every_raw_message(self, _connection, event):
785 "Log all messages when in watcher mode."
787 with open(self.logfile, "a") as logfp:
788 logfp.write("%03f|%s|%s\n" % \
789 (time.time(), event.source, event.arguments[0]))
791 "Do we have any pending message traffic?"
792 return [k for (k, v) in self.servers.items() if v.pending()]
794 def _parse_request(self, line):
795 "Request-parsing helper for the handle() method"
796 request = json.loads(line.strip())
797 if not isinstance(request, dict):
798 raise InvalidRequest(
799 "request is not a JSON dictionary: %r" % request)
800 if "to" not in request or "privmsg" not in request:
801 raise InvalidRequest(
802 "malformed request - 'to' or 'privmsg' missing: %r" % request)
803 channels = request['to']
804 message = request['privmsg']
805 if not isinstance(channels, (list, basestring)):
806 raise InvalidRequest(
807 "malformed request - unexpected channel type: %r" % channels)
808 if not isinstance(message, basestring):
809 raise InvalidRequest(
810 "malformed request - unexpected message type: %r" % message)
811 if not isinstance(channels, list):
812 channels = [channels]
816 if not isinstance(url, basestring):
817 raise InvalidRequest(
818 "malformed request - URL has unexpected type: %r" %
822 except InvalidRequest as e:
825 targets.append(target)
826 return (targets, message)
828 def handle(self, line, quit_after=False):
829 "Perform a JSON relay request."
831 targets, message = self._parse_request(line=line)
832 for target in targets:
833 if target.server() not in self.servers:
834 self.servers[target.server()] = Dispatcher(
835 self, target=target, **self.kwargs)
836 self.servers[target.server()].dispatch(
837 target.channel, message, target.key, quit_after=quit_after)
838 # GC dispatchers with no active connections
839 servernames = self.servers.keys()
840 for servername in servernames:
841 if not self.servers[servername].live():
842 del self.servers[servername]
843 # If we might be pushing a resource limit even
844 # after garbage collection, remove a session. The
845 # goal here is to head off DoS attacks that aim at
846 # exhausting thread space or file descriptors.
847 # The cost is that attempts to DoS this service
848 # will cause lots of join/leave spam as we
849 # scavenge old channels after connecting to new
850 # ones. The particular method used for selecting a
851 # session to be terminated doesn't matter much; we
852 # choose the one longest idle on the assumption
853 # that message activity is likely to be clumpy.
854 if len(self.servers) >= CONNECTION_MAX:
857 key=lambda name: self.servers[name].last_xmit())
858 del self.servers[oldest]
859 except InvalidRequest as e:
862 self.logerr("can't recognize JSON on input: %r" % line)
864 self.logerr("wildly malformed JSON blew the parser stack.")
866 class IrkerTCPHandler(socketserver.StreamRequestHandler):
869 line = self.rfile.readline()
872 irker.handle(line.strip())
874 class IrkerUDPHandler(socketserver.BaseRequestHandler):
876 data = self.request[0].strip()
877 #socket = self.request[1]
881 if __name__ == '__main__':
882 parser = argparse.ArgumentParser(
883 description=__doc__.strip().splitlines()[0])
885 '-d', '--log-level', metavar='LEVEL', choices=LOG_LEVELS,
886 help='file of trusted certificates for SSL/TLS')
888 '-l', '--log-file', metavar='PATH',
889 help='file for saving captured message traffic')
891 '-n', '--nick', metavar='NAME', default='irker%03d',
892 help="nickname (optionally with a '%%.*d' server connection marker)")
894 '-p', '--password', metavar='PASSWORD',
895 help='NickServ password')
897 '-i', '--immediate', action='store_const', const=True,
898 help='disconnect after sending each message')
900 '-V', '--version', action='version',
901 version='%(prog)s {0}'.format(version))
902 args = parser.parse_args()
904 handler = logging.StreamHandler()
905 LOG.addHandler(handler)
907 log_level = getattr(logging, args.log_level.upper())
908 LOG.setLevel(log_level)
911 logfile=args.log_file,
912 nick_template=args.nick,
913 nick_needs_number=re.search('%.*d', args.nick),
914 password=args.password,
916 LOG.info("irkerd version %s" % version)
918 irker.irc.add_event_handler("quit", lambda _c, _e: sys.exit(0))
919 irker.handle('{"to":"%s","privmsg":"%s"}' % (immediate, arguments[0]), quit_after=True)
922 irker.thread_launch()
924 tcpserver = socketserver.TCPServer((HOST, PORT), IrkerTCPHandler)
925 udpserver = socketserver.UDPServer((HOST, PORT), IrkerUDPHandler)
926 for server in [tcpserver, udpserver]:
927 server = threading.Thread(target=server.serve_forever)
928 server.setDaemon(True)
932 except KeyboardInterrupt:
934 except socket.error as e:
935 LOG.error("server launch failed: %r\n" % e)