Remove .git from guessed project name
[irker.git] / irkerd
diff --git a/irkerd b/irkerd
index 2a73835097674e03378bdcbc72cd4063e235ec3d..e51924f4e9691a9cfa89f601cc2a7b59cb4bccae 100755 (executable)
--- a/irkerd
+++ b/irkerd
@@ -18,7 +18,8 @@ developers). The -V option prints the program version and exits.
 Design and code by Eric S. Raymond <esr@thyrsus.com>. See the project
 resource page at <http://www.catb.org/~esr/irker/>.
 
-Requires Python 2.6 and the irc client library at version >= 2.0.2: see
+Requires Python 2.6 or 2.5 with the simplejson library installed, and
+the irc client library at version >= 2.0.2: see
 
 http://pypi.python.org/pypi/irc/
 """
@@ -37,32 +38,13 @@ UNSEEN_TTL = 60                     # Time to live, seconds since first request
 CHANNEL_MAX = 18               # Max channels open per socket (default)
 ANTI_FLOOD_DELAY = 0.5         # Anti-flood delay after transmissions, seconds
 ANTI_BUZZ_DELAY = 0.09         # Anti-buzz delay after queue-empty check
+CONNECTION_MAX = 200           # To avoid hitting a thread limit
 
 # No user-serviceable parts below this line
 
-version = "1.8"
+version = "1.10"
 
-# This black magic imports support for green threads (coroutines),
-# then has kinky sex with the import library internals, replacing
-# "threading" with a coroutine-using imposter.  Threads then become
-# ultra-light-weight and cooperatively scheduled.
-try:
-    import eventlet
-    eventlet.monkey_patch()
-    green_threads = True
-    # With greenlets we don't worry about thread exhaustion, only the
-    # file descriptor limit (typically 1024 on modern Unixes). Thus we
-    # can handle a lot more concurrent sessions and generate less
-    # join/leave spam under heavy load.
-    CONNECTION_MAX = 1000
-except ImportError:
-    # Threads are more expensive if we have to use OS-level ones
-    # rather than greenlets.  We need to avoid pushing thread limits
-    # as well as fd limits.  See security.txt for discussion.
-    CONNECTION_MAX = 200
-    green_threads = False
-
-import sys, getopt, urlparse, time, random, socket
+import sys, getopt, urlparse, time, random, socket, signal
 import threading, Queue, SocketServer
 import irc.client, logging
 try:
@@ -87,19 +69,23 @@ except ImportError:
 # even if the queue is nonempty but efforts to connect have failed for
 # a long time.
 #
-# There are multiple threads. One accepts incoming traffic from all servers.
-# Each Connection also has a consumer thread and a thread-safe message queue.
-# The program main appends messages to queues as JSON requests are received;
-# the consumer threads try to ship them to servers.  When a socket write
-# stalls, it only blocks an individual consumer thread; if it stalls long
-# enough, the session will be timed out.
+# There are multiple threads. One accepts incoming traffic from all
+# servers.  Each Connection also has a consumer thread and a
+# thread-safe message queue.  The program main appends messages to
+# queues as JSON requests are received; the consumer threads try to
+# ship them to servers.  When a socket write stalls, it only blocks an
+# individual consumer thread; if it stalls long enough, the session
+# will be timed out. This solves the biggest problem with a
+# single-threaded implementation, which is that you can't count on a
+# single stalled write not hanging all other traffic - you're at the
+# mercy of the length of the buffers in the TCP/IP layer.
 #
 # Message delivery is thus not reliable in the face of network stalls,
 # but this was considered acceptable because IRC (notoriously) has the
 # same problem - there is little point in reliable delivery to a relay
 # that is down or unreliable.
 #
-# This code uses only NICK, JOIN, MODE, and PRIVMSG. It is strictly
+# This code uses only NICK, JOIN, PART, MODE, and PRIVMSG. It is strictly
 # compliant to RFC1459, except for the interpretation and use of the
 # DEAF and CHANLIMIT and (obsolete) MAXCHANNELS features.  CHANLIMIT
 # is as described in the Internet RFC draft
@@ -187,12 +173,16 @@ class Connection:
                     now = time.time()
                     xmit_timeout = now > self.last_xmit + XMIT_TTL
                     ping_timeout = now > self.last_ping + PING_TTL
-                    if (xmit_timeout or ping_timeout) and self.status != "disconnected":
+                    if self.status == "disconnected":
+                        # If the queue is empty, we can drop this connection.
+                        self.status = "expired"
+                        break
+                    elif xmit_timeout or ping_timeout:
                         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))
-                        self.connection.context = None
-                        self.connection.quit("transmission timeout")
-                        self.connection.close()
-                        self.connection = None
+                        with self.irker.library_lock:
+                            self.connection.context = None
+                            self.connection.quit("transmission timeout")
+                            self.connection = None
                         self.status = "disconnected"
                     else:
                         # Prevent this thread from hogging the CPU by pausing
@@ -201,25 +191,35 @@ class Connection:
                         # reflex arc it is highly unlikely any human will ever
                         # notice.
                         time.sleep(ANTI_BUZZ_DELAY)
+                elif self.status == "disconnected" \
+                         and time.time() > self.last_xmit + DISCONNECT_TTL:
+                    # Queue is nonempty, but the IRC server might be
+                    # down. Letting failed connections retain queue
+                    # space forever would be a memory leak.
+                    self.status = "expired"
+                    break
                 elif not self.connection:
                     # Queue is nonempty but server isn't connected.
-                    self.connection = self.irker.irc.server()
-                    self.connection.context = self
-                    # Try to avoid colliding with other instances
-                    self.nick_trial = random.randint(1, 990)
-                    self.channels_joined = {}
-                    # This will throw irc.client.ServerConnectionError on failure
-                    try:
-                        self.connection.connect(self.servername,
-                                            self.port,
-                                            nickname=self.nickname(),
-                                            username="irker",
-                                            ircname="irker relaying client")
-                        self.status = "handshaking"
-                        self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
-                        self.last_xmit = time.time()
-                    except irc.client.ServerConnectionError:
-                        self.status = "disconnected"
+                    with self.irker.library_lock:
+                        self.connection = self.irker.irc.server()
+                        self.connection.context = self
+                        # Try to avoid colliding with other instances
+                        self.nick_trial = random.randint(1, 990)
+                        self.channels_joined = {}
+                        try:
+                            # This will throw
+                            # irc.client.ServerConnectionError on failure
+                            self.connection.connect(self.servername,
+                                                self.port,
+                                                nickname=self.nickname(),
+                                                username="irker",
+                                                ircname="irker relaying client")
+                            self.status = "handshaking"
+                            self.irker.debug(1, "XMIT_TTL bump (%s connection) at %s" % (self.servername, time.asctime()))
+                            self.last_xmit = time.time()
+                            self.last_ping = time.time()
+                        except irc.client.ServerConnectionError:
+                            self.status = "disconnected"
                 elif self.status == "handshaking":
                     if time.time() > self.last_xmit + HANDSHAKE_TTL:
                         self.status = "expired"
@@ -228,13 +228,6 @@ class Connection:
                         # Don't buzz on the empty-queue test while we're
                         # handshaking
                         time.sleep(ANTI_BUZZ_DELAY)
-                elif self.status == "disconnected" \
-                         and time.time() > self.last_xmit + DISCONNECT_TTL:
-                    # Queue is nonempty, but the IRC server might be
-                    # down. Letting failed connections retain queue
-                    # space forever would be a memory leak.
-                    self.status = "expired"
-                    break
                 elif self.status == "unseen" \
                          and time.time() > self.last_xmit + UNSEEN_TTL:
                     # Nasty people could attempt a denial-of-service
@@ -245,16 +238,17 @@ class Connection:
                     self.status = "expired"
                     break
                 elif self.status == "ready":
-                    (channel, message) = self.queue.get()
-                    if channel not in self.channels_joined:
-                        self.connection.join(channel)
-                        self.irker.debug(1, "joining %s on %s." % (channel, self.servername))
-                    for segment in message.split("\n"):
-                        self.connection.privmsg(channel, segment)
-                        time.sleep(ANTI_FLOOD_DELAY)
-                    self.last_xmit = self.channels_joined[channel] = time.time()
-                    self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
-                    self.queue.task_done()
+                    with self.irker.library_lock:
+                        (channel, message) = self.queue.get()
+                        if channel not in self.channels_joined:
+                            self.connection.join(channel)
+                            self.irker.debug(1, "joining %s on %s." % (channel, self.servername))
+                        for segment in message.split("\n"):
+                            self.connection.privmsg(channel, segment)
+                            time.sleep(ANTI_FLOOD_DELAY)
+                        self.last_xmit = self.channels_joined[channel] = time.time()
+                        self.irker.debug(1, "XMIT_TTL bump (%s transmission) at %s" % (self.servername, time.asctime()))
+                        self.queue.task_done()
         except:
             (exc_type, _exc_value, exc_traceback) = sys.exc_info()
             self.irker.logerr("exception %s in thread for %s" % \
@@ -274,6 +268,9 @@ class Connection:
         if self.channel_limits:
             match_count = 0
             for already in self.channels_joined:
+                # This obscure code is because the RFCs allow separate limits
+                # by channel type (indicated by the first character of the name)
+                # a feature that is almost never actually used.
                 if already[0] == channel[0]:
                     match_count += 1
             return match_count < self.channel_limits.get(channel[0], CHANNEL_MAX)
@@ -351,7 +348,7 @@ class Dispatcher:
         return len(self.connections) > 0
     def last_xmit(self):
         "Return the time of the most recent transmission."
-        return max([x.last_xmit for x in self.connections])
+        return max(x.last_xmit for x in self.connections)
 
 class Irker:
     "Persistent IRC multiplexer."
@@ -367,7 +364,8 @@ class Irker:
         self.irc.add_global_handler("featurelist", self._handle_features)
         self.irc.add_global_handler("disconnect", self._handle_disconnect)
         self.irc.add_global_handler("kick", self._handle_kick)
-        thread = threading.Thread(target=self.irc.process_forever)
+        self.library_lock = threading.Lock()
+        thread = threading.Thread(target=self._process_forever)
         thread.setDaemon(True)
         self.irc._thread = thread
         thread.start()
@@ -379,6 +377,12 @@ class Irker:
         "Debugging information."
         if self.debuglevel >= level:
             sys.stderr.write("irkerd: %s\n" % errmsg)
+    def _process_forever(self):
+        "IRC library process_forever with mutex."
+        self.debug(1, "process_forever()")
+        while True:
+            with self.library_lock:
+                self.irc.process_once(ANTI_BUZZ_DELAY)
     def _handle_ping(self, connection, _event):
         "PING arrived, bump the last-received time for the connection."
         if connection.context:
@@ -474,13 +478,8 @@ class Irker:
                             # choose the one longest idle on the
                             # assumption that message activity is likely
                             # to be clumpy.
-                            oldest = None
-                            oldtime = float("inf")
                             if len(self.servers) >= CONNECTION_MAX:
-                                for (name, server) in self.servers.items():
-                                    if server.last_xmit() < oldtime:
-                                        oldest = name
-                                        oldtime = server.last_xmit()
+                                oldest = min(self.servers.keys(), key=lambda name: self.servers[name].last_xmit())
                                 del self.servers[oldest]
         except ValueError:
             self.logerr("can't recognize JSON on input: %r" % line)
@@ -522,8 +521,7 @@ if __name__ == '__main__':
             server.setDaemon(True)
             server.start()
         try:
-            while True:
-                time.sleep(10)
+            signal.pause()
         except KeyboardInterrupt:
             raise SystemExit(1)
     except socket.error, e: