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 Options: -d sets the debug-message level (probably only of interest to
16 developers). -l sets a logfile to capture message traffic from
17 channels. -n sets the nick and -p the nickserv password. The -V
18 option prints the program version and exits.
20 Design and code by Eric S. Raymond <esr@thyrsus.com>. See the project
21 resource page at <http://www.catb.org/~esr/irker/>.
23 Requires Python 2.6 or 2.5 with the simplejson library installed.
26 from __future__ import with_statement
28 # These things might need tuning
33 XMIT_TTL = (3 * 60 * 60) # Time to live, seconds from last transmit
34 PING_TTL = (15 * 60) # Time to live, seconds from last PING
35 HANDSHAKE_TTL = 60 # Time to live, seconds from nick transmit
36 CHANNEL_TTL = (3 * 60 * 60) # Time to live, seconds from last transmit
37 DISCONNECT_TTL = (24 * 60 * 60) # Time to live, seconds from last connect
38 UNSEEN_TTL = 60 # Time to live, seconds since first request
39 CHANNEL_MAX = 18 # Max channels open per socket (default)
40 ANTI_FLOOD_DELAY = 1.0 # Anti-flood delay after transmissions, seconds
41 ANTI_BUZZ_DELAY = 0.09 # Anti-buzz delay after queue-empty check
42 CONNECTION_MAX = 200 # To avoid hitting a thread limit
44 # No user-serviceable parts below this line
48 import sys, getopt, urlparse, time, random, socket, signal, re
49 import threading, Queue, SocketServer, select, itertools
52 import simplejson as json # Faster, also makes us Python-2.4-compatible
56 # Sketch of implementation:
58 # One Irker object manages multiple IRC sessions. It holds a map of
59 # Dispatcher objects, one per (server, port) combination, which are
60 # responsible for routing messages to one of any number of Connection
61 # objects that do the actual socket conversations. The reason for the
62 # Dispatcher layer is that IRC daemons limit the number of channels a
63 # client (that is, from the daemon's point of view, a socket) can be
64 # joined to, so each session to a server needs a flock of Connection
65 # instances each with its own socket.
67 # Connections are timed out and removed when either they haven't seen a
68 # PING for a while (indicating that the server may be stalled or down)
69 # or there has been no message traffic to them for a while, or
70 # even if the queue is nonempty but efforts to connect have failed for
73 # There are multiple threads. One accepts incoming traffic from all
74 # servers. Each Connection also has a consumer thread and a
75 # thread-safe message queue. The program main appends messages to
76 # queues as JSON requests are received; the consumer threads try to
77 # ship them to servers. When a socket write stalls, it only blocks an
78 # individual consumer thread; if it stalls long enough, the session
79 # will be timed out. This solves the biggest problem with a
80 # single-threaded implementation, which is that you can't count on a
81 # single stalled write not hanging all other traffic - you're at the
82 # mercy of the length of the buffers in the TCP/IP layer.
84 # Message delivery is thus not reliable in the face of network stalls,
85 # but this was considered acceptable because IRC (notoriously) has the
86 # same problem - there is little point in reliable delivery to a relay
87 # that is down or unreliable.
89 # This code uses only NICK, JOIN, PART, MODE, PRIVMSG, USER, and QUIT.
90 # It is strictly compliant to RFC1459, except for the interpretation and
91 # use of the DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features.
93 # CHANLIMIT is as described in the Internet RFC draft
94 # draft-brocklesby-irc-isupport-03 at <http://www.mirc.com/isupport.html>.
95 # The ",isnick" feature is as described in
96 # <http://ftp.ics.uci.edu/pub/ietf/uri/draft-mirashi-url-irc-01.txt>.
98 # Historical note: the IRCClient and IRCServerConnection classes
99 # (~270LOC) replace the overweight, overcomplicated 3KLOC mass of
100 # irclib code that irker formerly used as a service library. They
101 # still look similar to parts of irclib because I contributed to that
102 # code before giving up on it.
104 class IRCError(Exception):
109 "An IRC client session to one or more servers."
111 self.mutex = threading.RLock()
112 self.server_connections = []
113 self.event_handlers = {}
114 self.add_event_handler("ping",
115 lambda c, e: c.ship("PONG %s" % e.target))
118 "Initialize a new server-connection object."
119 conn = IRCServerConnection(self)
121 self.server_connections.append(conn)
124 def spin(self, timeout=0.2):
125 "Spin processing data from connections forever."
126 # Outer loop should specifically *not* be mutex-locked.
127 # Otherwise no other thread would ever be able to change
128 # the shared state of an IRC object running this function.
131 connected = [x for x in self.server_connections
132 if x is not None and x.socket is not None]
133 sockets = [x.socket for x in connected]
135 (insocks, _o, _e) = select.select(sockets, [], [], timeout)
136 for s, c in itertools.product(insocks, self.server_connections):
143 def add_event_handler(self, event, handler):
144 "Set a handler to be called later."
146 event_handlers = self.event_handlers.setdefault(event, [])
147 event_handlers.append(handler)
149 def handle_event(self, connection, event):
151 h = self.event_handlers
152 th = sorted(h.get("all_events", []) + h.get(event.type, []))
154 handler(connection, event)
156 def drop_connection(self, connection):
158 self.server_connections.remove(connection)
160 class LineBufferedStream():
161 "Line-buffer a read stream."
162 crlf_re = re.compile(b'\r?\n')
167 def append(self, newbytes):
168 self.buffer += newbytes
171 "Iterate over lines in the buffer."
172 lines = LineBufferedStream.crlf_re.split(self.buffer)
173 self.buffer = lines.pop()
179 class IRCServerConnectionError(IRCError):
182 class IRCServerConnection():
183 command_re = re.compile("^(:(?P<prefix>[^ ]+) +)?(?P<command>[^ ]+)( *(?P<argument> .+))?")
184 # The full list of numeric-to-event mappings is in Perl's Net::IRC.
185 # We only need to ensure that if some ancient server throws numerics
186 # for the ones we actually want to catch, they're mapped.
189 "005": "featurelist",
190 "432": "erroneusnickname",
191 "433": "nicknameinuse",
192 "436": "nickcollision",
193 "437": "unavailresource",
196 def __init__(self, master):
200 def connect(self, server, port, nickname,
201 password=None, username=None, ircname=None):
202 log.debug("connect(server=%r, port=%r, nickname=%r, ...)",
203 server, port, nickname)
204 if self.socket is not None:
205 self.disconnect("Changing servers")
207 self.buffer = LineBufferedStream()
208 self.event_handlers = {}
209 self.real_server_name = ""
212 self.server_address = (server, port)
213 self.nickname = nickname
214 self.username = username or nickname
215 self.ircname = ircname or nickname
216 self.password = password
218 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
219 self.socket.bind(('', 0))
220 self.socket.connect(self.server_address)
221 except socket.error as err:
222 raise IRCServerConnectionError("Couldn't connect to socket: %s" % err)
225 self.ship("PASS " + self.password)
226 self.nick(self.nickname)
227 self.user(self.username, self.ircname)
231 # Without this thread lock, there is a window during which
232 # select() can find a closed socket, leading to an EBADF error.
233 with self.master.mutex:
234 self.disconnect("Closing object")
235 self.master.drop_connection(self)
239 incoming = self.socket.recv(16384)
241 # Server hung up on us.
242 self.disconnect("Connection reset by peer")
245 # Dead air also indicates a connection reset.
246 self.disconnect("Connection reset by peer")
249 self.buffer.append(incoming)
251 for line in self.buffer:
252 log.debug("FROM: %s", line)
260 self.handle_event(Event("every_raw_message",
261 self.real_server_name,
265 m = IRCServerConnection.command_re.match(line)
266 if m.group("prefix"):
267 prefix = m.group("prefix")
268 if not self.real_server_name:
269 self.real_server_name = prefix
270 if m.group("command"):
271 command = m.group("command").lower()
272 if m.group("argument"):
273 a = m.group("argument").split(" :", 1)
274 arguments = a[0].split()
276 arguments.append(a[1])
278 command = IRCServerConnection.codemap.get(command, command)
279 if command in ["privmsg", "notice"]:
280 target = arguments.pop(0)
284 if command == "quit":
285 arguments = [arguments[0]]
286 elif command == "ping":
287 target = arguments[0]
289 target = arguments[0]
290 arguments = arguments[1:]
292 log.debug("command: %s, source: %s, target: %s, "
293 "arguments: %s", command, prefix, target, arguments)
294 self.handle_event(Event(command, prefix, target, arguments))
296 def handle_event(self, event):
297 self.master.handle_event(self, event)
298 if event.type in self.event_handlers:
299 for fn in self.event_handlers[event.type]:
302 def is_connected(self):
303 return self.socket is not None
305 def disconnect(self, message=""):
306 if self.socket is None:
310 self.socket.shutdown(socket.SHUT_WR)
316 self.handle_event(Event("disconnect", self.server, "", [message]))
318 def join(self, channel, key=""):
319 self.ship("JOIN %s%s" % (channel, (key and (" " + key))))
321 def mode(self, target, command):
322 self.ship("MODE %s %s" % (target, command))
324 def nick(self, newnick):
325 self.ship("NICK " + newnick)
327 def part(self, channel, message=""):
328 cmd_parts = ['PART', channel]
330 cmd_parts.append(message)
331 self.ship(' '.join(cmd_parts))
333 def privmsg(self, target, text):
334 self.ship("PRIVMSG %s :%s" % (target, text))
336 def quit(self, message=""):
337 # Triggers an error that forces a disconnect.
338 self.ship("QUIT" + (message and (" :" + message)))
340 def user(self, username, realname):
341 self.ship("USER %s 0 * :%s" % (username, realname))
343 def ship(self, string):
344 "Ship a command to the server, appending CR/LF"
346 self.socket.send(string + b'\r\n')
347 log.debug("TO: %s", string)
349 self.disconnect("Connection reset by peer.")
352 def __init__(self, evtype, source, target, arguments=None):
356 if arguments is None:
358 self.arguments = arguments
360 def is_channel(string):
361 return string and string[0] in "#&+!"
364 def __init__(self, irkerd, servername, port):
366 self.servername = servername
368 self.nick_trial = None
369 self.connection = None
371 self.last_xmit = time.time()
372 self.last_ping = time.time()
373 self.channels_joined = {}
374 self.channel_limits = {}
375 # The consumer thread
376 self.queue = Queue.Queue()
378 def nickname(self, n=None):
379 "Return a name for the nth server connection."
383 return (namestyle % n)
386 def handle_ping(self):
387 "Register the fact that the server has pinged this connection."
388 self.last_ping = time.time()
389 def handle_welcome(self):
390 "The server says we're OK, with a non-conflicting nick."
391 self.status = "ready"
392 self.irker.debug(1, "nick %s accepted" % self.nickname())
394 self.connection.privmsg("nickserv", "identify %s" % password)
395 def handle_badnick(self):
396 "The server says our nick is ill-formed or has a conflict."
397 self.irker.debug(1, "nick %s rejected" % self.nickname())
399 # Randomness prevents a malicious user or bot from
400 # anticipating the next trial name in order to block us
401 # from completing the handshake.
402 self.nick_trial += random.randint(1, 3)
403 self.last_xmit = time.time()
404 self.connection.nick(self.nickname())
405 # Otherwise fall through, it might be possible to
407 def handle_disconnect(self):
408 "Server disconnected us for flooding or some other reason."
409 self.connection = None
410 self.status = "disconnected"
411 def handle_kick(self, outof):
413 self.status = "handshaking"
415 del self.channels_joined[outof]
417 self.irker.logerr("kicked by %s from %s that's not joined"
418 % (self.servername, outof))
420 while not self.queue.empty():
421 (channel, message, key) = self.queue.get()
423 qcopy.append((channel, message, key))
424 for (channel, message, key) in qcopy:
425 self.queue.put((channel, message, key))
426 self.status = "ready"
427 def enqueue(self, channel, message, key):
428 "Enque a message for transmission."
429 if self.thread is None or not self.thread.is_alive():
430 self.status = "unseen"
431 self.thread = threading.Thread(target=self.dequeue)
432 self.thread.setDaemon(True)
434 self.queue.put((channel, message, key))
436 "Try to ship pending messages from the queue."
439 # We want to be kind to the IRC servers and not hold unused
440 # sockets open forever, so they have a time-to-live. The
441 # loop is coded this particular way so that we can drop
442 # the actual server connection when its time-to-live
443 # expires, then reconnect and resume transmission if the
444 # queue fills up again.
445 if self.queue.empty():
446 # Queue is empty, at some point we want to time out
447 # the connection rather than holding a socket open in
448 # the server forever.
450 xmit_timeout = now > self.last_xmit + XMIT_TTL
451 ping_timeout = now > self.last_ping + PING_TTL
452 if self.status == "disconnected":
453 # If the queue is empty, we can drop this connection.
454 self.status = "expired"
456 elif xmit_timeout or ping_timeout:
457 self.irker.debug(1, "timing out connection to %s at %s (ping_timeout=%s, xmit_timeout=%s)" % (self.servername, time.asctime(), ping_timeout, xmit_timeout))
458 with self.irker.irc.mutex:
459 self.connection.context = None
460 self.connection.quit("transmission timeout")
461 self.connection = None
462 self.status = "disconnected"
464 # Prevent this thread from hogging the CPU by pausing
465 # for just a little bit after the queue-empty check.
466 # As long as this is less that the duration of a human
467 # reflex arc it is highly unlikely any human will ever
469 time.sleep(ANTI_BUZZ_DELAY)
470 elif self.status == "disconnected" \
471 and time.time() > self.last_xmit + DISCONNECT_TTL:
472 # Queue is nonempty, but the IRC server might be
473 # down. Letting failed connections retain queue
474 # space forever would be a memory leak.
475 self.status = "expired"
477 elif not self.connection:
478 # Queue is nonempty but server isn't connected.
479 with self.irker.irc.mutex:
480 self.connection = self.irker.irc.newserver()
481 self.connection.context = self
482 # Try to avoid colliding with other instances
483 self.nick_trial = random.randint(1, 990)
484 self.channels_joined = {}
487 # IRCServerConnectionError on failure
488 self.connection.connect(self.servername,
490 nickname=self.nickname(),
492 ircname="irker relaying client")
493 if hasattr(self.connection, "buffer"):
494 self.connection.buffer.errors = 'replace'
495 self.status = "handshaking"
496 self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
497 self.last_xmit = time.time()
498 self.last_ping = time.time()
499 except IRCServerConnectionError:
500 self.status = "disconnected"
501 elif self.status == "handshaking":
502 if time.time() > self.last_xmit + HANDSHAKE_TTL:
503 self.status = "expired"
506 # Don't buzz on the empty-queue test while we're
508 time.sleep(ANTI_BUZZ_DELAY)
509 elif self.status == "unseen" \
510 and time.time() > self.last_xmit + UNSEEN_TTL:
511 # Nasty people could attempt a denial-of-service
512 # attack by flooding us with requests with invalid
513 # servernames. We guard against this by rapidly
514 # expiring connections that have a nonempty queue but
515 # have never had a successful open.
516 self.status = "expired"
518 elif self.status == "ready":
519 (channel, message, key) = self.queue.get()
520 if channel not in self.channels_joined:
521 self.connection.join(channel, key=key)
522 self.irker.debug(1, "joining %s on %s." % (channel, self.servername))
523 # An empty message might be used as a keepalive or
524 # to join a channel for logging, so suppress the
525 # privmsg send unless there is actual traffic.
527 for segment in message.split("\n"):
528 # Truncate the message if it's too long,
529 # but we're working with characters here,
530 # not bytes, so we could be off.
531 # 500 = 512 - CRLF - 'PRIVMSG ' - ' :'
532 maxlength = 500 - len(channel)
533 if len(segment) > maxlength:
534 segment = segment[:maxlength]
536 self.connection.privmsg(channel, segment)
537 except ValueError as err:
538 self.irker.debug(1, "irclib rejected a message to %s on %s because: %s" % (channel, self.servername, str(err)))
539 time.sleep(ANTI_FLOOD_DELAY)
540 self.last_xmit = self.channels_joined[channel] = time.time()
541 self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
542 self.queue.task_done()
544 (exc_type, _exc_value, exc_traceback) = sys.exc_info()
545 self.irker.logerr("exception %s in thread for %s" % \
546 (exc_type, self.servername))
548 # Maybe this should have its own status?
549 self.status = "expired"
551 # This is so we can see tracebacks for errors inside the thread
552 # when we need to be able to for debugging purposes.
554 raise exc_type, _exc_value, exc_traceback
557 # Make sure we don't leave any zombies behind
558 self.connection.close()
560 # Irclib has a habit of throwing fresh exceptions here. Ignore that
563 "Should this connection not be scavenged?"
564 return self.status != "expired"
565 def joined_to(self, channel):
566 "Is this connection joined to the specified channel?"
567 return channel in self.channels_joined
568 def accepting(self, channel):
569 "Can this connection accept a join of this channel?"
570 if self.channel_limits:
572 for already in self.channels_joined:
573 # This obscure code is because the RFCs allow separate limits
574 # by channel type (indicated by the first character of the name)
575 # a feature that is almost never actually used.
576 if already[0] == channel[0]:
578 return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
580 return len(self.channels_joined) < CHANNEL_MAX
583 "Represent a transmission target."
584 def __init__(self, url):
585 # Pre-2.6 Pythons don't recognize irc: as a valid URL prefix.
586 url = url.replace("irc://", "http://")
587 parsed = urlparse.urlparse(url)
588 irchost, _, ircport = parsed.netloc.partition(':')
591 self.servername = irchost
592 # IRC channel names are case-insensitive. If we don't smash
593 # case here we may run into problems later. There was a bug
594 # observed on irc.rizon.net where an irkerd user specified #Channel,
595 # got kicked, and irkerd crashed because the server returned
596 # "#channel" in the notification that our kick handler saw.
597 self.channel = parsed.path.lstrip('/').lower()
598 # This deals with a tweak in recent versions of urlparse.
600 self.channel += "#" + parsed.fragment
601 isnick = self.channel.endswith(",isnick")
603 self.channel = self.channel[:-7]
604 if self.channel and not isnick and self.channel[0] not in "#&+":
605 self.channel = "#" + self.channel
606 # support both channel?secret and channel?key=secret
609 self.key = re.sub("^key=", "", parsed.query)
610 self.port = int(ircport)
612 "Both components must be present for a valid target."
613 return self.servername and self.channel
615 "Return a hashable tuple representing the destination server."
616 return (self.servername, self.port)
619 "Manage connections to a particular server-port combination."
620 def __init__(self, irkerd, servername, port):
622 self.servername = servername
624 self.connections = []
625 def dispatch(self, channel, message, key):
626 "Dispatch messages for our server-port combination."
627 # First, check if there is room for another channel
628 # on any of our existing connections.
629 connections = [x for x in self.connections if x.live()]
630 eligibles = [x for x in connections if x.joined_to(channel)] \
631 or [x for x in connections if x.accepting(channel)]
633 eligibles[0].enqueue(channel, message, key)
635 # All connections are full up. Look for one old enough to be
638 for connection in connections:
639 for (chan, age) in connections.channels_joined.items():
640 if age < time.time() - CHANNEL_TTL:
641 ancients.append((connection, chan, age))
643 ancients.sort(key=lambda x: x[2])
644 (found_connection, drop_channel, _drop_age) = ancients[0]
645 found_connection.part(drop_channel, "scavenged by irkerd")
646 del found_connection.channels_joined[drop_channel]
647 #time.sleep(ANTI_FLOOD_DELAY)
648 found_connection.enqueue(channel, message, key)
650 # Didn't find any channels with no recent activity
651 newconn = Connection(self.irker,
654 self.connections.append(newconn)
655 newconn.enqueue(channel, message, key)
657 "Does this server-port combination have any live connections?"
658 self.connections = [x for x in self.connections if x.live()]
659 return len(self.connections) > 0
661 "Return the time of the most recent transmission."
662 return max(x.last_xmit for x in self.connections)
665 "Persistent IRC multiplexer."
666 def __init__(self, debuglevel=0):
667 self.debuglevel = debuglevel
668 self.irc = IRCClient()
669 self.irc.add_event_handler("ping", self._handle_ping)
670 self.irc.add_event_handler("welcome", self._handle_welcome)
671 self.irc.add_event_handler("erroneusnickname", self._handle_badnick)
672 self.irc.add_event_handler("nicknameinuse", self._handle_badnick)
673 self.irc.add_event_handler("nickcollision", self._handle_badnick)
674 self.irc.add_event_handler("unavailresource", self._handle_badnick)
675 self.irc.add_event_handler("featurelist", self._handle_features)
676 self.irc.add_event_handler("disconnect", self._handle_disconnect)
677 self.irc.add_event_handler("kick", self._handle_kick)
678 self.irc.add_event_handler("every_raw_message", self._handle_every_raw_message)
679 thread = threading.Thread(target=self.irc.spin)
680 thread.setDaemon(True)
681 self.irc._thread = thread
684 def logerr(self, errmsg):
685 "Log a processing error."
686 sys.stderr.write("irkerd: " + errmsg + "\n")
687 def debug(self, level, errmsg):
688 "Debugging information."
689 if self.debuglevel >= level:
690 sys.stderr.write("irkerd: %s\n" % errmsg)
691 def _handle_ping(self, connection, _event):
692 "PING arrived, bump the last-received time for the connection."
693 if connection.context:
694 connection.context.handle_ping()
695 def _handle_welcome(self, connection, _event):
696 "Welcome arrived, nick accepted for this connection."
697 if connection.context:
698 connection.context.handle_welcome()
699 def _handle_badnick(self, connection, _event):
700 "Nick not accepted for this connection."
701 if connection.context:
702 connection.context.handle_badnick()
703 def _handle_features(self, connection, event):
704 "Determine if and how we can set deaf mode."
705 if connection.context:
706 cxt = connection.context
707 arguments = event.arguments
708 # irclib 5.0 compatibility, because the maintainer is a fool
709 if callable(arguments):
710 arguments = arguments()
711 for lump in arguments:
712 if lump.startswith("DEAF="):
714 connection.mode(cxt.nickname(), "+"+lump[5:])
715 elif lump.startswith("MAXCHANNELS="):
718 cxt.channel_limits[pref] = m
719 self.debug(1, "%s maxchannels is %d"
720 % (connection.server, m))
721 elif lump.startswith("CHANLIMIT=#:"):
722 limits = lump[10:].split(",")
725 (prefixes, limit) = token.split(":")
728 cxt.channel_limits[c] = limit
729 self.debug(1, "%s channel limit map is %s"
730 % (connection.server, cxt.channel_limits))
732 self.logerr("ill-formed CHANLIMIT property")
733 def _handle_disconnect(self, connection, _event):
734 "Server hung up the connection."
735 self.debug(1, "server %s disconnected" % connection.server)
737 if connection.context:
738 connection.context.handle_disconnect()
739 def _handle_kick(self, connection, event):
740 "Server hung up the connection."
741 target = event.target
742 # irclib 5.0 compatibility, because the maintainer continues
746 self.debug(1, "irker has been kicked from %s on %s" % (target, connection.server))
747 if connection.context:
748 connection.context.handle_kick(target)
749 def _handle_every_raw_message(self, _connection, event):
750 "Log all messages when in watcher mode."
752 with open(logfile, "a") as logfp:
753 logfp.write("%03f|%s|%s\n" % \
754 (time.time(), event.source, event.arguments[0]))
755 def handle(self, line):
756 "Perform a JSON relay request."
758 request = json.loads(line.strip())
759 if not isinstance(request, dict):
760 self.logerr("request is not a JSON dictionary: %r" % request)
761 elif "to" not in request or "privmsg" not in request:
762 self.logerr("malformed request - 'to' or 'privmsg' missing: %r" % request)
764 channels = request['to']
765 message = request['privmsg']
766 if not isinstance(channels, (list, basestring)):
767 self.logerr("malformed request - unexpected channel type: %r" % channels)
768 if not isinstance(message, basestring):
769 self.logerr("malformed request - unexpected message type: %r" % message)
771 if not isinstance(channels, list):
772 channels = [channels]
774 if not isinstance(url, basestring):
775 self.logerr("malformed request - URL has unexpected type: %r" % url)
778 if not target.valid():
780 if target.server() not in self.servers:
781 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
782 self.servers[target.server()].dispatch(target.channel, message, target.key)
783 # GC dispatchers with no active connections
784 servernames = self.servers.keys()
785 for servername in servernames:
786 if not self.servers[servername].live():
787 del self.servers[servername]
788 # If we might be pushing a resource limit
789 # even after garbage collection, remove a
790 # session. The goal here is to head off
791 # DoS attacks that aim at exhausting
792 # thread space or file descriptors. The
793 # cost is that attempts to DoS this
794 # service will cause lots of join/leave
795 # spam as we scavenge old channels after
796 # connecting to new ones. The particular
797 # method used for selecting a session to
798 # be terminated doesn't matter much; we
799 # choose the one longest idle on the
800 # assumption that message activity is likely
802 if len(self.servers) >= CONNECTION_MAX:
803 oldest = min(self.servers.keys(), key=lambda name: self.servers[name].last_xmit())
804 del self.servers[oldest]
806 self.logerr("can't recognize JSON on input: %r" % line)
808 self.logerr("wildly malformed JSON blew the parser stack.")
810 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
813 line = self.rfile.readline()
816 irker.handle(line.strip())
818 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
820 data = self.request[0].strip()
821 #socket = self.request[1]
827 irkerd [-d debuglevel] [-l logfile] [-n nick] [-p password] [-V] [-h]
833 -p set nickserv password
834 -V return irkerd version
835 -h print this help dialog
838 if __name__ == '__main__':
839 log = logging.getLogger(__name__)
841 namestyle = "irker%03d"
845 (options, arguments) = getopt.getopt(sys.argv[1:], "d:l:n:p:Vh")
846 except getopt.GetoptError as e:
847 sys.stderr.write("%s" % e)
850 for (opt, val) in options:
851 if opt == '-d': # Enable debug/progress messages
854 logging.basicConfig(level=logging.DEBUG)
855 elif opt == '-l': # Logfile mode - report traffic read in
857 elif opt == '-n': # Force the nick
859 elif opt == '-p': # Set a nickserv password
861 elif opt == '-V': # Emit version and exit
862 sys.stdout.write("irkerd version %s\n" % version)
867 fallback = re.search("%.*d", namestyle)
868 irker = Irker(debuglevel=debuglvl)
869 irker.debug(1, "irkerd version %s" % version)
871 tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
872 udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
873 for server in [tcpserver, udpserver]:
874 server = threading.Thread(target=server.serve_forever)
875 server.setDaemon(True)
879 except KeyboardInterrupt:
881 except socket.error, e:
882 sys.stderr.write("irkerd: server launch failed: %r\n" % e)