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.
132 connected = [x for x in self.server_connections
133 if x is not None and x.socket is not None]
134 sockets = [x.socket for x in connected]
136 connmap = dict([(c.socket.fileno(), c) for c in connected])
137 (insocks, _o, _e) = select.select(sockets, [], [], timeout)
139 connmap[s.fileno()].consume()
142 time.sleep(nextsleep)
144 def add_event_handler(self, event, handler):
145 "Set a handler to be called later."
147 event_handlers = self.event_handlers.setdefault(event, [])
148 event_handlers.append(handler)
150 def handle_event(self, connection, event):
152 h = self.event_handlers
153 th = sorted(h.get("all_events", []) + h.get(event.type, []))
155 handler(connection, event)
157 def drop_connection(self, connection):
159 self.server_connections.remove(connection)
161 def debug(self, level, errmsg):
162 "Debugging information."
163 if self.debuglevel >= level:
164 sys.stderr.write("irkerd: %s\n" % errmsg)
166 class LineBufferedStream():
167 "Line-buffer a read stream."
168 crlf_re = re.compile(b'\r?\n')
173 def append(self, newbytes):
174 self.buffer += newbytes
177 "Iterate over lines in the buffer."
178 lines = LineBufferedStream.crlf_re.split(self.buffer)
179 self.buffer = lines.pop()
185 class IRCServerConnectionError(IRCError):
188 class IRCServerConnection():
189 command_re = re.compile("^(:(?P<prefix>[^ ]+) +)?(?P<command>[^ ]+)( *(?P<argument> .+))?")
190 # The full list of numeric-to-event mappings is in Perl's Net::IRC.
191 # We only need to ensure that if some ancient server throws numerics
192 # for the ones we actually want to catch, they're mapped.
195 "005": "featurelist",
196 "432": "erroneusnickname",
197 "433": "nicknameinuse",
198 "436": "nickcollision",
199 "437": "unavailresource",
202 def __init__(self, master):
206 def connect(self, server, port, nickname,
207 password=None, username=None, ircname=None):
208 self.master.debug(2, "connect(server=%r, port=%r, nickname=%r, ...)" %
209 (server, port, nickname))
210 if self.socket is not None:
211 self.disconnect("Changing servers")
213 self.buffer = LineBufferedStream()
214 self.event_handlers = {}
215 self.real_server_name = ""
218 self.server_address = (server, port)
219 self.nickname = nickname
220 self.username = username or nickname
221 self.ircname = ircname or nickname
222 self.password = password
224 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
225 self.socket.bind(('', 0))
226 self.socket.connect(self.server_address)
227 except socket.error as err:
228 raise IRCServerConnectionError("Couldn't connect to socket: %s" % err)
231 self.ship("PASS " + self.password)
232 self.nick(self.nickname)
233 self.user(self.username, self.ircname)
237 # Without this thread lock, there is a window during which
238 # select() can find a closed socket, leading to an EBADF error.
239 with self.master.mutex:
240 self.disconnect("Closing object")
241 self.master.drop_connection(self)
245 incoming = self.socket.recv(16384)
247 # Server hung up on us.
248 self.disconnect("Connection reset by peer")
251 # Dead air also indicates a connection reset.
252 self.disconnect("Connection reset by peer")
255 self.buffer.append(incoming)
257 for line in self.buffer:
258 self.master.debug(2, "FROM: %s" % line)
266 self.handle_event(Event("every_raw_message",
267 self.real_server_name,
271 m = IRCServerConnection.command_re.match(line)
272 if m.group("prefix"):
273 prefix = m.group("prefix")
274 if not self.real_server_name:
275 self.real_server_name = prefix
276 if m.group("command"):
277 command = m.group("command").lower()
278 if m.group("argument"):
279 a = m.group("argument").split(" :", 1)
280 arguments = a[0].split()
282 arguments.append(a[1])
284 command = IRCServerConnection.codemap.get(command, command)
285 if command in ["privmsg", "notice"]:
286 target = arguments.pop(0)
290 if command == "quit":
291 arguments = [arguments[0]]
292 elif command == "ping":
293 target = arguments[0]
295 target = arguments[0]
296 arguments = arguments[1:]
299 "command: %s, source: %s, target: %s, arguments: %s" % (command, prefix, target, arguments))
300 self.handle_event(Event(command, prefix, target, arguments))
302 def handle_event(self, event):
303 self.master.handle_event(self, event)
304 if event.type in self.event_handlers:
305 for fn in self.event_handlers[event.type]:
308 def is_connected(self):
309 return self.socket is not None
311 def disconnect(self, message=""):
312 if self.socket is None:
314 # Don't send a QUIT here - causes infinite loop!
316 self.socket.shutdown(socket.SHUT_WR)
322 self.handle_event(Event("disconnect", self.server, "", [message]))
324 def join(self, channel, key=""):
325 self.ship("JOIN %s%s" % (channel, (key and (" " + key))))
327 def mode(self, target, command):
328 self.ship("MODE %s %s" % (target, command))
330 def nick(self, newnick):
331 self.ship("NICK " + newnick)
333 def part(self, channel, message=""):
334 cmd_parts = ['PART', channel]
336 cmd_parts.append(message)
337 self.ship(' '.join(cmd_parts))
339 def privmsg(self, target, text):
340 self.ship("PRIVMSG %s :%s" % (target, text))
342 def quit(self, message=""):
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, quit_after=False):
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 self.queue.put((channel, None, key))
444 "Try to ship pending messages from the queue."
447 # We want to be kind to the IRC servers and not hold unused
448 # sockets open forever, so they have a time-to-live. The
449 # loop is coded this particular way so that we can drop
450 # the actual server connection when its time-to-live
451 # expires, then reconnect and resume transmission if the
452 # queue fills up again.
453 if self.queue.empty():
454 # Queue is empty, at some point we want to time out
455 # the connection rather than holding a socket open in
456 # the server forever.
458 xmit_timeout = now > self.last_xmit + XMIT_TTL
459 ping_timeout = now > self.last_ping + PING_TTL
460 if self.status == "disconnected":
461 # If the queue is empty, we can drop this connection.
462 self.status = "expired"
464 elif xmit_timeout or ping_timeout:
465 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))
466 with self.irker.irc.mutex:
467 self.connection.context = None
468 self.connection.quit("transmission timeout")
469 self.connection = None
470 self.status = "disconnected"
472 # Prevent this thread from hogging the CPU by pausing
473 # for just a little bit after the queue-empty check.
474 # As long as this is less that the duration of a human
475 # reflex arc it is highly unlikely any human will ever
477 time.sleep(ANTI_BUZZ_DELAY)
478 elif self.status == "disconnected" \
479 and time.time() > self.last_xmit + DISCONNECT_TTL:
480 # Queue is nonempty, but the IRC server might be
481 # down. Letting failed connections retain queue
482 # space forever would be a memory leak.
483 self.status = "expired"
485 elif not self.connection and self.status != "expired":
486 # Queue is nonempty but server isn't connected.
487 with self.irker.irc.mutex:
488 self.connection = self.irker.irc.newserver()
489 self.connection.context = self
490 # Try to avoid colliding with other instances
491 self.nick_trial = random.randint(1, 990)
492 self.channels_joined = {}
495 # IRCServerConnectionError on failure
496 self.connection.connect(self.servername,
498 nickname=self.nickname(),
500 ircname="irker relaying client")
501 self.status = "handshaking"
502 self.irker.irc.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
503 self.last_xmit = time.time()
504 self.last_ping = time.time()
505 except IRCServerConnectionError:
506 self.status = "expired"
507 elif self.status == "handshaking":
508 if time.time() > self.last_xmit + HANDSHAKE_TTL:
509 self.status = "expired"
512 # Don't buzz on the empty-queue test while we're
514 time.sleep(ANTI_BUZZ_DELAY)
515 elif self.status == "unseen" \
516 and time.time() > self.last_xmit + UNSEEN_TTL:
517 # Nasty people could attempt a denial-of-service
518 # attack by flooding us with requests with invalid
519 # servernames. We guard against this by rapidly
520 # expiring connections that have a nonempty queue but
521 # have never had a successful open.
522 self.status = "expired"
524 elif self.status == "ready":
525 (channel, message, key) = self.queue.get()
526 if channel not in self.channels_joined:
527 self.connection.join(channel, key=key)
528 self.irker.irc.debug(1, "joining %s on %s." % (channel, self.servername))
529 # None is magic - it's a request to quit the server
531 self.connection.quit()
532 # An empty message might be used as a keepalive or
533 # to join a channel for logging, so suppress the
534 # privmsg send unless there is actual traffic.
536 for segment in message.split("\n"):
537 # Truncate the message if it's too long,
538 # but we're working with characters here,
539 # not bytes, so we could be off.
540 # 500 = 512 - CRLF - 'PRIVMSG ' - ' :'
541 maxlength = 500 - len(channel)
542 if len(segment) > maxlength:
543 segment = segment[:maxlength]
545 self.connection.privmsg(channel, segment)
546 except ValueError as err:
547 self.irker.irc.debug(1, "irclib rejected a message to %s on %s because: %s" % (channel, self.servername, str(err)))
548 self.irker.irc.debug(50, err.format_exc())
549 time.sleep(ANTI_FLOOD_DELAY)
550 self.last_xmit = self.channels_joined[channel] = time.time()
551 self.irker.irc.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
552 self.queue.task_done()
554 (exc_type, _exc_value, exc_traceback) = sys.exc_info()
555 self.irker.logerr("exception %s in thread for %s" % \
556 (exc_type, self.servername))
558 # Maybe this should have its own status?
559 self.status = "expired"
561 # This is so we can see tracebacks for errors inside the thread
562 # when we need to be able to for debugging purposes.
564 raise exc_type, _exc_value, exc_traceback
567 # Make sure we don't leave any zombies behind
568 self.connection.close()
570 # Irclib has a habit of throwing fresh exceptions here. Ignore that
573 "Should this connection not be scavenged?"
574 return self.status != "expired"
575 def joined_to(self, channel):
576 "Is this connection joined to the specified channel?"
577 return channel in self.channels_joined
578 def accepting(self, channel):
579 "Can this connection accept a join of this channel?"
580 if self.channel_limits:
582 for already in self.channels_joined:
583 # This obscure code is because the RFCs allow separate limits
584 # by channel type (indicated by the first character of the name)
585 # a feature that is almost never actually used.
586 if already[0] == channel[0]:
588 return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
590 return len(self.channels_joined) < CHANNEL_MAX
593 "Represent a transmission target."
594 def __init__(self, url):
595 # Pre-2.6 Pythons don't recognize irc: as a valid URL prefix.
596 url = url.replace("irc://", "http://")
597 parsed = urlparse.urlparse(url)
598 irchost, _, ircport = parsed.netloc.partition(':')
601 self.servername = irchost
602 # IRC channel names are case-insensitive. If we don't smash
603 # case here we may run into problems later. There was a bug
604 # observed on irc.rizon.net where an irkerd user specified #Channel,
605 # got kicked, and irkerd crashed because the server returned
606 # "#channel" in the notification that our kick handler saw.
607 self.channel = parsed.path.lstrip('/').lower()
608 # This deals with a tweak in recent versions of urlparse.
610 self.channel += "#" + parsed.fragment
611 isnick = self.channel.endswith(",isnick")
613 self.channel = self.channel[:-7]
614 if self.channel and not isnick and self.channel[0] not in "#&+":
615 self.channel = "#" + self.channel
616 # support both channel?secret and channel?key=secret
619 self.key = re.sub("^key=", "", parsed.query)
620 self.port = int(ircport)
622 "Both components must be present for a valid target."
623 return self.servername and self.channel
625 "Return a hashable tuple representing the destination server."
626 return (self.servername, self.port)
629 "Manage connections to a particular server-port combination."
630 def __init__(self, irkerd, servername, port):
632 self.servername = servername
634 self.connections = []
635 def dispatch(self, channel, message, key, quit_after=False):
636 "Dispatch messages for our server-port combination."
637 # First, check if there is room for another channel
638 # on any of our existing connections.
639 connections = [x for x in self.connections if x.live()]
640 eligibles = [x for x in connections if x.joined_to(channel)] \
641 or [x for x in connections if x.accepting(channel)]
643 eligibles[0].enqueue(channel, message, key, quit_after)
645 # All connections are full up. Look for one old enough to be
648 for connection in connections:
649 for (chan, age) in connections.channels_joined.items():
650 if age < time.time() - CHANNEL_TTL:
651 ancients.append((connection, chan, age))
653 ancients.sort(key=lambda x: x[2])
654 (found_connection, drop_channel, _drop_age) = ancients[0]
655 found_connection.part(drop_channel, "scavenged by irkerd")
656 del found_connection.channels_joined[drop_channel]
657 #time.sleep(ANTI_FLOOD_DELAY)
658 found_connection.enqueue(channel, message, key, quit_after)
660 # Didn't find any channels with no recent activity
661 newconn = Connection(self.irker,
664 self.connections.append(newconn)
665 newconn.enqueue(channel, message, key, quit_after)
667 "Does this server-port combination have any live connections?"
668 self.connections = [x for x in self.connections if x.live()]
669 return len(self.connections) > 0
671 "Return all connections with pending traffic."
672 return [x for x in self.connections if not x.queue.empty()]
674 "Return the time of the most recent transmission."
675 return max(x.last_xmit for x in self.connections)
678 "Persistent IRC multiplexer."
679 def __init__(self, debuglevel=0):
680 self.debuglevel = debuglevel
681 self.irc = IRCClient(self.debuglevel)
682 self.irc.add_event_handler("ping", self._handle_ping)
683 self.irc.add_event_handler("welcome", self._handle_welcome)
684 self.irc.add_event_handler("erroneusnickname", self._handle_badnick)
685 self.irc.add_event_handler("nicknameinuse", self._handle_badnick)
686 self.irc.add_event_handler("nickcollision", self._handle_badnick)
687 self.irc.add_event_handler("unavailresource", self._handle_badnick)
688 self.irc.add_event_handler("featurelist", self._handle_features)
689 self.irc.add_event_handler("disconnect", self._handle_disconnect)
690 self.irc.add_event_handler("kick", self._handle_kick)
691 self.irc.add_event_handler("every_raw_message", self._handle_every_raw_message)
693 def thread_launch(self):
694 thread = threading.Thread(target=self.irc.spin)
695 thread.setDaemon(True)
696 self.irc._thread = thread
698 def logerr(self, errmsg):
699 "Log a processing error."
700 sys.stderr.write("irkerd: " + errmsg + "\n")
701 def _handle_ping(self, connection, _event):
702 "PING arrived, bump the last-received time for the connection."
703 if connection.context:
704 connection.context.handle_ping()
705 def _handle_welcome(self, connection, _event):
706 "Welcome arrived, nick accepted for this connection."
707 if connection.context:
708 connection.context.handle_welcome()
709 def _handle_badnick(self, connection, _event):
710 "Nick not accepted for this connection."
711 if connection.context:
712 connection.context.handle_badnick()
713 def _handle_features(self, connection, event):
714 "Determine if and how we can set deaf mode."
715 if connection.context:
716 cxt = connection.context
717 arguments = event.arguments
718 for lump in arguments:
719 if lump.startswith("DEAF="):
721 connection.mode(cxt.nickname(), "+"+lump[5:])
722 elif lump.startswith("MAXCHANNELS="):
725 cxt.channel_limits[pref] = m
726 self.irc.debug(1, "%s maxchannels is %d"
727 % (connection.server, m))
728 elif lump.startswith("CHANLIMIT=#:"):
729 limits = lump[10:].split(",")
732 (prefixes, limit) = token.split(":")
735 cxt.channel_limits[c] = limit
736 self.irc.debug(1, "%s channel limit map is %s"
737 % (connection.server, cxt.channel_limits))
739 self.logerr("ill-formed CHANLIMIT property")
740 def _handle_disconnect(self, connection, _event):
741 "Server hung up the connection."
742 self.irc.debug(1, "server %s disconnected" % connection.server)
744 if connection.context:
745 connection.context.handle_disconnect()
746 def _handle_kick(self, connection, event):
747 "Server hung up the connection."
748 target = event.target
749 self.irc.debug(1, "irker has been kicked from %s on %s" % (target, connection.server))
750 if connection.context:
751 connection.context.handle_kick(target)
752 def _handle_every_raw_message(self, _connection, event):
753 "Log all messages when in watcher mode."
755 with open(logfile, "a") as logfp:
756 logfp.write("%03f|%s|%s\n" % \
757 (time.time(), event.source, event.arguments[0]))
759 "Do we have any pending message traffic?"
760 return [k for (k, v) in self.servers.items() if v.pending()]
761 def handle(self, line, quit_after=False):
762 "Perform a JSON relay request."
764 request = json.loads(line.strip())
765 if not isinstance(request, dict):
766 self.logerr("request is not a JSON dictionary: %r" % request)
767 elif "to" not in request or "privmsg" not in request:
768 self.logerr("malformed request - 'to' or 'privmsg' missing: %r" % request)
770 channels = request['to']
771 message = request['privmsg']
772 if not isinstance(channels, (list, basestring)):
773 self.logerr("malformed request - unexpected channel type: %r" % channels)
774 if not isinstance(message, basestring):
775 self.logerr("malformed request - unexpected message type: %r" % message)
777 if not isinstance(channels, list):
778 channels = [channels]
780 if not isinstance(url, basestring):
781 self.logerr("malformed request - URL has unexpected type: %r" % url)
784 if not target.valid():
786 if target.server() not in self.servers:
787 self.servers[target.server()] = Dispatcher(self, target.servername, target.port)
788 self.servers[target.server()].dispatch(target.channel, message, target.key, quit_after=quit_after)
789 # GC dispatchers with no active connections
790 servernames = self.servers.keys()
791 for servername in servernames:
792 if not self.servers[servername].live():
793 del self.servers[servername]
794 # If we might be pushing a resource limit
795 # even after garbage collection, remove a
796 # session. The goal here is to head off
797 # DoS attacks that aim at exhausting
798 # thread space or file descriptors. The
799 # cost is that attempts to DoS this
800 # service will cause lots of join/leave
801 # spam as we scavenge old channels after
802 # connecting to new ones. The particular
803 # method used for selecting a session to
804 # be terminated doesn't matter much; we
805 # choose the one longest idle on the
806 # assumption that message activity is likely
808 if len(self.servers) >= CONNECTION_MAX:
809 oldest = min(self.servers.keys(), key=lambda name: self.servers[name].last_xmit())
810 del self.servers[oldest]
812 self.logerr("can't recognize JSON on input: %r" % line)
814 self.logerr("wildly malformed JSON blew the parser stack.")
816 class IrkerTCPHandler(SocketServer.StreamRequestHandler):
819 line = self.rfile.readline()
822 irker.handle(line.strip())
824 class IrkerUDPHandler(SocketServer.BaseRequestHandler):
826 data = self.request[0].strip()
827 #socket = self.request[1]
833 irkerd [-d debuglevel] [-l logfile] [-n nick] [-p password] [-i channel message] [-V] [-h]
839 -p set nickserv password
841 -V return irkerd version
842 -h print this help dialog
845 if __name__ == '__main__':
848 namestyle = "irker%03d"
852 (options, arguments) = getopt.getopt(sys.argv[1:], "d:i:l:n:p:Vh")
853 except getopt.GetoptError as e:
854 sys.stderr.write("%s" % e)
857 for (opt, val) in options:
858 if opt == '-d': # Enable debug/progress messages
860 elif opt == '-i': # Immediate mode - send one message, then exit.
862 elif opt == '-l': # Logfile mode - report traffic read in
864 elif opt == '-n': # Force the nick
866 elif opt == '-p': # Set a nickserv password
868 elif opt == '-V': # Emit version and exit
869 sys.stdout.write("irkerd version %s\n" % version)
874 fallback = re.search("%.*d", namestyle)
875 irker = Irker(debuglevel=debuglvl)
876 irker.irc.debug(1, "irkerd version %s" % version)
878 irker.irc.add_event_handler("quit", lambda _c, _e: sys.exit(0))
879 irker.handle('{"to":"%s","privmsg":"%s"}' % (immediate, arguments[0]), quit_after=True)
882 irker.thread_launch()
884 tcpserver = SocketServer.TCPServer((HOST, PORT), IrkerTCPHandler)
885 udpserver = SocketServer.UDPServer((HOST, PORT), IrkerUDPHandler)
886 for server in [tcpserver, udpserver]:
887 server = threading.Thread(target=server.serve_forever)
888 server.setDaemon(True)
892 except KeyboardInterrupt:
894 except socket.error, e:
895 sys.stderr.write("irkerd: server launch failed: %r\n" % e)