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
51 import simplejson as json # Faster, also makes us Python-2.4-compatible
55 # Sketch of implementation:
57 # One Irker object manages multiple IRC sessions. It holds a map of
58 # Dispatcher objects, one per (server, port) combination, which are
59 # responsible for routing messages to one of any number of Connection
60 # objects that do the actual socket conversations. The reason for the
61 # Dispatcher layer is that IRC daemons limit the number of channels a
62 # client (that is, from the daemon's point of view, a socket) can be
63 # joined to, so each session to a server needs a flock of Connection
64 # instances each with its own socket.
66 # Connections are timed out and removed when either they haven't seen a
67 # PING for a while (indicating that the server may be stalled or down)
68 # or there has been no message traffic to them for a while, or
69 # even if the queue is nonempty but efforts to connect have failed for
72 # There are multiple threads. One accepts incoming traffic from all
73 # servers. Each Connection also has a consumer thread and a
74 # thread-safe message queue. The program main appends messages to
75 # queues as JSON requests are received; the consumer threads try to
76 # ship them to servers. When a socket write stalls, it only blocks an
77 # individual consumer thread; if it stalls long enough, the session
78 # will be timed out. This solves the biggest problem with a
79 # single-threaded implementation, which is that you can't count on a
80 # single stalled write not hanging all other traffic - you're at the
81 # mercy of the length of the buffers in the TCP/IP layer.
83 # Message delivery is thus not reliable in the face of network stalls,
84 # but this was considered acceptable because IRC (notoriously) has the
85 # same problem - there is little point in reliable delivery to a relay
86 # that is down or unreliable.
88 # This code uses only NICK, JOIN, PART, MODE, PRIVMSG, USER, and QUIT.
89 # It is strictly compliant to RFC1459, except for the interpretation and
90 # use of the DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features.
92 # CHANLIMIT is as described in the Internet RFC draft
93 # draft-brocklesby-irc-isupport-03 at <http://www.mirc.com/isupport.html>.
94 # The ",isnick" feature is as described in
95 # <http://ftp.ics.uci.edu/pub/ietf/uri/draft-mirashi-url-irc-01.txt>.
97 # Historical note: the IRCClient and IRCServerConnection classes
98 # (~270LOC) replace the overweight, overcomplicated 3KLOC mass of
99 # irclib code that irker formerly used as a service library. They
100 # still look similar to parts of irclib because I contributed to that
101 # code before giving up on it.
103 class IRCError(Exception):
108 "An IRC client session to one or more servers."
109 def __init__(self, debuglevel):
110 self.mutex = threading.RLock()
111 self.server_connections = []
112 self.event_handlers = {}
113 self.add_event_handler("ping",
114 lambda c, e: c.ship("PONG %s" % e.target))
115 self.debuglevel = debuglevel
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 connmap = dict([(c.socket.fileno(), c) for c in connected])
136 (insocks, _o, _e) = select.select(sockets, [], [], timeout)
138 connmap[s.fileno()].consume()
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 def debug(self, level, errmsg):
161 "Debugging information."
162 if self.debuglevel >= level:
163 sys.stderr.write("irkerd: %s\n" % errmsg)
165 class LineBufferedStream():
166 "Line-buffer a read stream."
167 crlf_re = re.compile(b'\r?\n')
172 def append(self, newbytes):
173 self.buffer += newbytes
176 "Iterate over lines in the buffer."
177 lines = LineBufferedStream.crlf_re.split(self.buffer)
178 self.buffer = lines.pop()
184 class IRCServerConnectionError(IRCError):
187 class IRCServerConnection():
188 command_re = re.compile("^(:(?P<prefix>[^ ]+) +)?(?P<command>[^ ]+)( *(?P<argument> .+))?")
189 # The full list of numeric-to-event mappings is in Perl's Net::IRC.
190 # We only need to ensure that if some ancient server throws numerics
191 # for the ones we actually want to catch, they're mapped.
194 "005": "featurelist",
195 "432": "erroneusnickname",
196 "433": "nicknameinuse",
197 "436": "nickcollision",
198 "437": "unavailresource",
201 def __init__(self, master):
205 def connect(self, server, port, nickname,
206 password=None, username=None, ircname=None):
207 self.master.debug(2, "connect(server=%r, port=%r, nickname=%r, ...)" %
208 (server, port, nickname))
209 if self.socket is not None:
210 self.disconnect("Changing servers")
212 self.buffer = LineBufferedStream()
213 self.event_handlers = {}
214 self.real_server_name = ""
217 self.server_address = (server, port)
218 self.nickname = nickname
219 self.username = username or nickname
220 self.ircname = ircname or nickname
221 self.password = password
223 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
224 self.socket.bind(('', 0))
225 self.socket.connect(self.server_address)
226 except socket.error as err:
227 raise IRCServerConnectionError("Couldn't connect to socket: %s" % err)
230 self.ship("PASS " + self.password)
231 self.nick(self.nickname)
232 self.user(self.username, self.ircname)
236 # Without this thread lock, there is a window during which
237 # select() can find a closed socket, leading to an EBADF error.
238 with self.master.mutex:
239 self.disconnect("Closing object")
240 self.master.drop_connection(self)
244 incoming = self.socket.recv(16384)
246 # Server hung up on us.
247 self.disconnect("Connection reset by peer")
250 # Dead air also indicates a connection reset.
251 self.disconnect("Connection reset by peer")
254 self.buffer.append(incoming)
256 for line in self.buffer:
257 self.master.debug(2, "FROM: %s" % line)
265 self.handle_event(Event("every_raw_message",
266 self.real_server_name,
270 m = IRCServerConnection.command_re.match(line)
271 if m.group("prefix"):
272 prefix = m.group("prefix")
273 if not self.real_server_name:
274 self.real_server_name = prefix
275 if m.group("command"):
276 command = m.group("command").lower()
277 if m.group("argument"):
278 a = m.group("argument").split(" :", 1)
279 arguments = a[0].split()
281 arguments.append(a[1])
283 command = IRCServerConnection.codemap.get(command, command)
284 if command in ["privmsg", "notice"]:
285 target = arguments.pop(0)
289 if command == "quit":
290 arguments = [arguments[0]]
291 elif command == "ping":
292 target = arguments[0]
294 target = arguments[0]
295 arguments = arguments[1:]
298 "command: %s, source: %s, target: %s, arguments: %s" % (command, prefix, target, arguments))
299 self.handle_event(Event(command, prefix, target, arguments))
301 def handle_event(self, event):
302 self.master.handle_event(self, event)
303 if event.type in self.event_handlers:
304 for fn in self.event_handlers[event.type]:
307 def is_connected(self):
308 return self.socket is not None
310 def disconnect(self, message=""):
311 if self.socket is None:
313 # Don't send a QUIT here - causes infinite loop!
315 self.socket.shutdown(socket.SHUT_WR)
321 self.handle_event(Event("disconnect", self.server, "", [message]))
323 def join(self, channel, key=""):
324 self.ship("JOIN %s%s" % (channel, (key and (" " + key))))
326 def mode(self, target, command):
327 self.ship("MODE %s %s" % (target, command))
329 def nick(self, newnick):
330 self.ship("NICK " + newnick)
332 def part(self, channel, message=""):
333 cmd_parts = ['PART', channel]
335 cmd_parts.append(message)
336 self.ship(' '.join(cmd_parts))
338 def privmsg(self, target, text):
339 self.ship("PRIVMSG %s :%s" % (target, text))
341 def quit(self, message=""):
342 # Triggers an error that forces a disconnect.
343 self.ship("QUIT" + (message and (" :" + message)))
345 def user(self, username, realname):
346 self.ship("USER %s 0 * :%s" % (username, realname))
348 def ship(self, string):
349 "Ship a command to the server, appending CR/LF"
351 self.socket.send(string.encode('utf-8') + b'\r\n')
352 self.master.debug(2, "TO: %s" % string)
354 self.disconnect("Connection reset by peer.")
357 def __init__(self, evtype, source, target, arguments=None):
361 if arguments is None:
363 self.arguments = arguments
365 def is_channel(string):
366 return string and string[0] in "#&+!"
369 def __init__(self, irkerd, servername, port):
371 self.servername = servername
373 self.nick_trial = None
374 self.connection = None
376 self.last_xmit = time.time()
377 self.last_ping = time.time()
378 self.channels_joined = {}
379 self.channel_limits = {}
380 # The consumer thread
381 self.queue = Queue.Queue()
383 def nickname(self, n=None):
384 "Return a name for the nth server connection."
388 return (namestyle % n)
391 def handle_ping(self):
392 "Register the fact that the server has pinged this connection."
393 self.last_ping = time.time()
394 def handle_welcome(self):
395 "The server says we're OK, with a non-conflicting nick."
396 self.status = "ready"
397 self.irker.irc.debug(1, "nick %s accepted" % self.nickname())
399 self.connection.privmsg("nickserv", "identify %s" % password)
400 def handle_badnick(self):
401 "The server says our nick is ill-formed or has a conflict."
402 self.irker.irc.debug(1, "nick %s rejected" % self.nickname())
404 # Randomness prevents a malicious user or bot from
405 # anticipating the next trial name in order to block us
406 # from completing the handshake.
407 self.nick_trial += random.randint(1, 3)
408 self.last_xmit = time.time()
409 self.connection.nick(self.nickname())
410 # Otherwise fall through, it might be possible to
412 def handle_disconnect(self):
413 "Server disconnected us for flooding or some other reason."
414 self.connection = None
415 if self.status != "expired":
416 self.status = "disconnected"
417 def handle_kick(self, outof):
419 self.status = "handshaking"
421 del self.channels_joined[outof]
423 self.irker.logerr("kicked by %s from %s that's not joined"
424 % (self.servername, outof))
426 while not self.queue.empty():
427 (channel, message, key) = self.queue.get()
429 qcopy.append((channel, message, key))
430 for (channel, message, key) in qcopy:
431 self.queue.put((channel, message, key))
432 self.status = "ready"
433 def enqueue(self, channel, message, key):
434 "Enque a message for transmission."
435 if self.thread is None or not self.thread.is_alive():
436 self.status = "unseen"
437 self.thread = threading.Thread(target=self.dequeue)
438 self.thread.setDaemon(True)
440 self.queue.put((channel, message, key))
442 "Try to ship pending messages from the queue."
445 # We want to be kind to the IRC servers and not hold unused
446 # sockets open forever, so they have a time-to-live. The
447 # loop is coded this particular way so that we can drop
448 # the actual server connection when its time-to-live
449 # expires, then reconnect and resume transmission if the
450 # queue fills up again.
451 if self.queue.empty():
452 # Queue is empty, at some point we want to time out
453 # the connection rather than holding a socket open in
454 # the server forever.
456 xmit_timeout = now > self.last_xmit + XMIT_TTL
457 ping_timeout = now > self.last_ping + PING_TTL
458 if self.status == "disconnected":
459 # If the queue is empty, we can drop this connection.
460 self.status = "expired"
462 elif xmit_timeout or ping_timeout:
463 self.irker.irc.debug(1, "timing out connection to %s at %s (ping_timeout=%s, xmit_timeout=%s)" % (self.servername, time.asctime(), ping_timeout, xmit_timeout))
464 with self.irker.irc.mutex:
465 self.connection.context = None
466 self.connection.quit("transmission timeout")
467 self.connection = None
468 self.status = "disconnected"
470 # Prevent this thread from hogging the CPU by pausing
471 # for just a little bit after the queue-empty check.
472 # As long as this is less that the duration of a human
473 # reflex arc it is highly unlikely any human will ever
475 time.sleep(ANTI_BUZZ_DELAY)
476 elif self.status == "disconnected" \
477 and time.time() > self.last_xmit + DISCONNECT_TTL:
478 # Queue is nonempty, but the IRC server might be
479 # down. Letting failed connections retain queue
480 # space forever would be a memory leak.
481 self.status = "expired"
483 elif not self.connection and self.status != "expired":
484 # Queue is nonempty but server isn't connected.
485 with self.irker.irc.mutex:
486 self.connection = self.irker.irc.newserver()
487 self.connection.context = self
488 # Try to avoid colliding with other instances
489 self.nick_trial = random.randint(1, 990)
490 self.channels_joined = {}
493 # IRCServerConnectionError on failure
494 self.connection.connect(self.servername,
496 nickname=self.nickname(),
498 ircname="irker relaying client")
499 self.status = "handshaking"
500 self.irker.irc.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
501 self.last_xmit = time.time()
502 self.last_ping = time.time()
503 except IRCServerConnectionError:
504 self.status = "expired"
505 elif self.status == "handshaking":
506 if time.time() > self.last_xmit + HANDSHAKE_TTL:
507 self.status = "expired"
510 # Don't buzz on the empty-queue test while we're
512 time.sleep(ANTI_BUZZ_DELAY)
513 elif self.status == "unseen" \
514 and time.time() > self.last_xmit + UNSEEN_TTL:
515 # Nasty people could attempt a denial-of-service
516 # attack by flooding us with requests with invalid
517 # servernames. We guard against this by rapidly
518 # expiring connections that have a nonempty queue but
519 # have never had a successful open.
520 self.status = "expired"
522 elif self.status == "ready":
523 (channel, message, key) = self.queue.get()
524 if channel not in self.channels_joined:
525 self.connection.join(channel, key=key)
526 self.irker.irc.debug(1, "joining %s on %s." % (channel, self.servername))
527 # An empty message might be used as a keepalive or
528 # to join a channel for logging, so suppress the
529 # privmsg send unless there is actual traffic.
531 for segment in message.split("\n"):
532 # Truncate the message if it's too long,
533 # but we're working with characters here,
534 # not bytes, so we could be off.
535 # 500 = 512 - CRLF - 'PRIVMSG ' - ' :'
536 maxlength = 500 - len(channel)
537 if len(segment) > maxlength:
538 segment = segment[:maxlength]
540 self.connection.privmsg(channel, segment)
541 except ValueError as err:
542 self.irker.irc.debug(1, "irclib rejected a message to %s on %s because: %s" % (channel, self.servername, str(err)))
543 self.irker.irc.debug(50, err.format_exc())
544 time.sleep(ANTI_FLOOD_DELAY)
545 self.last_xmit = self.channels_joined[channel] = time.time()
546 self.irker.irc.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
547 self.queue.task_done()
549 (exc_type, _exc_value, exc_traceback) = sys.exc_info()
550 self.irker.logerr("exception %s in thread for %s" % \
551 (exc_type, self.servername))
553 # Maybe this should have its own status?
554 self.status = "expired"
556 # This is so we can see tracebacks for errors inside the thread
557 # when we need to be able to for debugging purposes.
559 raise exc_type, _exc_value, exc_traceback
562 # Make sure we don't leave any zombies behind
563 self.connection.close()
565 # Irclib has a habit of throwing fresh exceptions here. Ignore that
568 "Should this connection not be scavenged?"
569 return self.status != "expired"
570 def joined_to(self, channel):
571 "Is this connection joined to the specified channel?"
572 return channel in self.channels_joined
573 def accepting(self, channel):
574 "Can this connection accept a join of this channel?"
575 if self.channel_limits:
577 for already in self.channels_joined:
578 # This obscure code is because the RFCs allow separate limits
579 # by channel type (indicated by the first character of the name)
580 # a feature that is almost never actually used.
581 if already[0] == channel[0]:
583 return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
585 return len(self.channels_joined) < CHANNEL_MAX
588 "Represent a transmission target."
589 def __init__(self, url):
590 # Pre-2.6 Pythons don't recognize irc: as a valid URL prefix.
591 url = url.replace("irc://", "http://")
592 parsed = urlparse.urlparse(url)
593 irchost, _, ircport = parsed.netloc.partition(':')
596 self.servername = irchost
597 # IRC channel names are case-insensitive. If we don't smash
598 # case here we may run into problems later. There was a bug
599 # observed on irc.rizon.net where an irkerd user specified #Channel,
600 # got kicked, and irkerd crashed because the server returned
601 # "#channel" in the notification that our kick handler saw.
602 self.channel = parsed.path.lstrip('/').lower()
603 # This deals with a tweak in recent versions of urlparse.
605 self.channel += "#" + parsed.fragment
606 isnick = self.channel.endswith(",isnick")
608 self.channel = self.channel[:-7]
609 if self.channel and not isnick and self.channel[0] not in "#&+":
610 self.channel = "#" + self.channel
611 # support both channel?secret and channel?key=secret
614 self.key = re.sub("^key=", "", parsed.query)
615 self.port = int(ircport)
617 "Both components must be present for a valid target."
618 return self.servername and self.channel
620 "Return a hashable tuple representing the destination server."
621 return (self.servername, self.port)
624 "Manage connections to a particular server-port combination."
625 def __init__(self, irkerd, servername, port):
627 self.servername = servername
629 self.connections = []
630 def dispatch(self, channel, message, key):
631 "Dispatch messages for our server-port combination."
632 # First, check if there is room for another channel
633 # on any of our existing connections.
634 connections = [x for x in self.connections if x.live()]
635 eligibles = [x for x in connections if x.joined_to(channel)] \
636 or [x for x in connections if x.accepting(channel)]
638 eligibles[0].enqueue(channel, message, key)
640 # All connections are full up. Look for one old enough to be
643 for connection in connections:
644 for (chan, age) in connections.channels_joined.items():
645 if age < time.time() - CHANNEL_TTL:
646 ancients.append((connection, chan, age))
648 ancients.sort(key=lambda x: x[2])
649 (found_connection, drop_channel, _drop_age) = ancients[0]
650 found_connection.part(drop_channel, "scavenged by irkerd")
651 del found_connection.channels_joined[drop_channel]
652 #time.sleep(ANTI_FLOOD_DELAY)
653 found_connection.enqueue(channel, message, key)
655 # Didn't find any channels with no recent activity
656 newconn = Connection(self.irker,
659 self.connections.append(newconn)
660 newconn.enqueue(channel, message, key)
662 "Does this server-port combination have any live connections?"
663 self.connections = [x for x in self.connections if x.live()]
664 return len(self.connections) > 0
666 "Return the time of the most recent transmission."
667 return max(x.last_xmit for x in self.connections)
670 "Persistent IRC multiplexer."
671 def __init__(self, debuglevel=0):
672 self.debuglevel = debuglevel
673 self.irc = IRCClient(self.debuglevel)
674 self.irc.add_event_handler("ping", self._handle_ping)
675 self.irc.add_event_handler("welcome", self._handle_welcome)
676 self.irc.add_event_handler("erroneusnickname", self._handle_badnick)
677 self.irc.add_event_handler("nicknameinuse", self._handle_badnick)
678 self.irc.add_event_handler("nickcollision", self._handle_badnick)
679 self.irc.add_event_handler("unavailresource", self._handle_badnick)
680 self.irc.add_event_handler("featurelist", self._handle_features)
681 self.irc.add_event_handler("disconnect", self._handle_disconnect)
682 self.irc.add_event_handler("kick", self._handle_kick)
683 self.irc.add_event_handler("every_raw_message", self._handle_every_raw_message)
684 thread = threading.Thread(target=self.irc.spin)
685 thread.setDaemon(True)
686 self.irc._thread = thread
689 def logerr(self, errmsg):
690 "Log a processing error."
691 sys.stderr.write("irkerd: " + errmsg + "\n")
692 def _handle_ping(self, connection, _event):
693 "PING arrived, bump the last-received time for the connection."
694 if connection.context:
695 connection.context.handle_ping()
696 def _handle_welcome(self, connection, _event):
697 "Welcome arrived, nick accepted for this connection."
698 if connection.context:
699 connection.context.handle_welcome()
700 def _handle_badnick(self, connection, _event):
701 "Nick not accepted for this connection."
702 if connection.context:
703 connection.context.handle_badnick()
704 def _handle_features(self, connection, event):
705 "Determine if and how we can set deaf mode."
706 if connection.context:
707 cxt = connection.context
708 arguments = event.arguments
709 for lump in arguments:
710 if lump.startswith("DEAF="):
712 connection.mode(cxt.nickname(), "+"+lump[5:])
713 elif lump.startswith("MAXCHANNELS="):
716 cxt.channel_limits[pref] = m
717 self.irc.debug(1, "%s maxchannels is %d"
718 % (connection.server, m))
719 elif lump.startswith("CHANLIMIT=#:"):
720 limits = lump[10:].split(",")
723 (prefixes, limit) = token.split(":")
726 cxt.channel_limits[c] = limit
727 self.irc.debug(1, "%s channel limit map is %s"
728 % (connection.server, cxt.channel_limits))
730 self.logerr("ill-formed CHANLIMIT property")
731 def _handle_disconnect(self, connection, _event):
732 "Server hung up the connection."
733 self.irc.debug(1, "server %s disconnected" % connection.server)
735 if connection.context:
736 connection.context.handle_disconnect()
737 def _handle_kick(self, connection, event):
738 "Server hung up the connection."
739 target = event.target
740 self.irc.debug(1, "irker has been kicked from %s on %s" % (target, connection.server))
741 if connection.context:
742 connection.context.handle_kick(target)
743 def _handle_every_raw_message(self, _connection, event):
744 "Log all messages when in watcher mode."
746 with open(logfile, "a") as logfp:
747 logfp.write("%03f|%s|%s\n" % \
748 (time.time(), event.source, event.arguments[0]))
749 def handle(self, line):
750 "Perform a JSON relay request."
752 request = json.loads(line.strip())
753 if not isinstance(request, dict):
754 self.logerr("request is not a JSON dictionary: %r" % request)
755 elif "to" not in request or "privmsg" not in request:
756 self.logerr("malformed request - 'to' or 'privmsg' missing: %r" % request)
758 channels = request['to']
759 message = request['privmsg']
760 if not isinstance(channels, (list, basestring)):
761 self.logerr("malformed request - unexpected channel type: %r" % channels)
762 if not isinstance(message, basestring):
763 self.logerr("malformed request - unexpected message type: %r" % message)
765 if not isinstance(channels, list):
766 channels = [channels]
768 if not isinstance(url, basestring):
769 self.logerr("malformed request - URL has unexpected type: %r" % url)
772 if not target.valid():
774 if target.server() not in self.servers:
775 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
776 self.servers[target.server()].dispatch(target.channel, message, target.key)
777 # GC dispatchers with no active connections
778 servernames = self.servers.keys()
779 for servername in servernames:
780 if not self.servers[servername].live():
781 del self.servers[servername]
782 # If we might be pushing a resource limit
783 # even after garbage collection, remove a
784 # session. The goal here is to head off
785 # DoS attacks that aim at exhausting
786 # thread space or file descriptors. The
787 # cost is that attempts to DoS this
788 # service will cause lots of join/leave
789 # spam as we scavenge old channels after
790 # connecting to new ones. The particular
791 # method used for selecting a session to
792 # be terminated doesn't matter much; we
793 # choose the one longest idle on the
794 # assumption that message activity is likely
796 if len(self.servers) >= CONNECTION_MAX:
797 oldest = min(self.servers.keys(), key=lambda name: self.servers[name].last_xmit())
798 del self.servers[oldest]
800 self.logerr("can't recognize JSON on input: %r" % line)
802 self.logerr("wildly malformed JSON blew the parser stack.")
804 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
807 line = self.rfile.readline()
810 irker.handle(line.strip())
812 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
814 data = self.request[0].strip()
815 #socket = self.request[1]
821 irkerd [-d debuglevel] [-l logfile] [-n nick] [-p password] [-V] [-h]
827 -p set nickserv password
828 -V return irkerd version
829 -h print this help dialog
832 if __name__ == '__main__':
834 namestyle = "irker%03d"
838 (options, arguments) = getopt.getopt(sys.argv[1:], "d:l:n:p:Vh")
839 except getopt.GetoptError as e:
840 sys.stderr.write("%s" % e)
843 for (opt, val) in options:
844 if opt == '-d': # Enable debug/progress messages
846 elif opt == '-l': # Logfile mode - report traffic read in
848 elif opt == '-n': # Force the nick
850 elif opt == '-p': # Set a nickserv password
852 elif opt == '-V': # Emit version and exit
853 sys.stdout.write("irkerd version %s\n" % version)
858 fallback = re.search("%.*d", namestyle)
859 irker = Irker(debuglevel=debuglvl)
860 irker.irc.debug(1, "irkerd version %s" % version)
862 tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
863 udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
864 for server in [tcpserver, udpserver]:
865 server = threading.Thread(target=server.serve_forever)
866 server.setDaemon(True)
870 except KeyboardInterrupt:
872 except socket.error, e:
873 sys.stderr.write("irkerd: server launch failed: %r\n" % e)