chiark / gitweb /
change messages to pipe
[inn-innduct.git] / backends / innduct.c
index 15541bd2811fc820cde49b3ad6d931fc845a033b..3c746c3ef09cd8632f1a6162e5d474124893e48b 100644 (file)
@@ -182,6 +182,7 @@ perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.
 
 #include "inn/list.h"
 #include "inn/innconf.h"
+#include "inn/messages.h"
 
 #include <sys/uio.h>
 #include <sys/types.h>
@@ -333,7 +334,6 @@ static void close_defer(void);
 static void search_backlog_file(void);
 static void preterminate(void);
 static void raise_default(int signo) NORET;
-static char *debug_report_ipf(InputFile *ipf);
 
 static void inputfile_reading_start(InputFile *ipf);
 static void inputfile_reading_stop(InputFile *ipf);
@@ -343,7 +343,7 @@ static void inputfile_reading_resume(InputFile *ipf);
 
 static void filemon_start(InputFile *ipf);
 static void filemon_stop(InputFile *ipf);
-static void filemon_callback(InputFile *ipf);
+static void tailing_make_readable(InputFile *ipf);
 
 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
 static void connfail(Conn *conn, const char *fmt, ...)         PRINTF(2,3);
@@ -356,9 +356,9 @@ static oop_rd_call peer_rd_err, peer_rd_ok;
 /* when changing defaults, remember to update the manpage */
 
 static const char *sitename, *remote_host;
-static const char *feedfile, *path_cli;
+static const char *feedfile, *path_run, *path_cli, *path_cli_dir;
 static int quiet_multiple=0;
-static int become_daemon=1, try_filemon=1;
+static int interactive=0, try_filemon=1;
 static int try_stream=1;
 static int port=119;
 static const char *inndconffile;
@@ -366,7 +366,7 @@ static const char *inndconffile;
 static int max_connections=10;
 static int max_queue_per_conn=200;
 static int target_max_feedfile_size=100000;
-static int period_seconds=60;
+static int period_seconds=30;
 static int filepoll_seconds=5;
 static int max_queue_per_ipf=-1;
 
@@ -379,11 +379,13 @@ static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
 /* all these are initialised to seconds, and converted to periods in main */
 static int reconnect_delay_periods=1000;
 static int flushfail_retry_periods=1000;
-static int backlog_retry_minperiods=50;
+static int backlog_retry_minperiods=100;
 static int backlog_spontrescan_periods=300;
 static int spontaneous_flush_periods=100000;
 static int max_separated_periods=2000;
 static int need_activity_periods=1000;
+static int lowvol_thresh=3;
+static int lowvol_periods=1000;
 
 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
 static int max_bad_data_initial= 30;
@@ -457,7 +459,7 @@ struct InputFile {
 
   oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
   off_t offset;
-  int skippinglong, paused;
+  int skippinglong, paused, fake_readable;
 
   ArticleList queue;
   long inprogress; /* includes queue.count and also articles in conns */
@@ -502,7 +504,9 @@ struct Conn {
   ISNODE(Conn);
   int fd; /* may be 0, meaning closed (during construction/destruction) */
   oop_read *rd; /* likewise */
-  int max_queue, stream, quitting;
+  int oopwriting; /* since on_fd is not idempotent */
+  int max_queue, stream;
+  const char *quitting;
   int since_activity; /* periods */
   ArticleList waiting; /* not yet told peer */
   ArticleList priority; /* peer says send it now */
@@ -521,6 +525,9 @@ static ConnList conns;
 static char *path_lock, *path_flushing, *path_defer, *path_dump;
 static char *globpat_backlog;
 static pid_t self_pid;
+static int *lowvol_perperiod;
+static int lowvol_circptr;
+static int lowvol_total; /* does not include current period */
 
 /* statemc_init initialises */
 static StateMachineState sms;
@@ -533,15 +540,17 @@ static int until_connect, until_backlog_nextscan;
 static double accept_proportion;
 static int nocheck, nocheck_reported, in_child;
 
-/* for simulation, debugging, etc. */
+/* for logging, simulation, debugging, etc. */
 int simulate_flush= -1;
+int logv_use_syslog;
+static const char *logv_prefix="";
 
 /*========== logging ==========*/
 
 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
 static void logcore(int sysloglevel, const char *fmt, ...) {
   VA;
-  if (become_daemon) {
+  if (logv_use_syslog) {
     vsyslog(sysloglevel,fmt,al);
   } else {
     if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
@@ -562,13 +571,13 @@ static void logv(int sysloglevel, const char *pfx, int errnoval,
   if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
     sysloglevel= LOG_ERR; /* run by wrong user, probably */
 
-  logcore(sysloglevel, "<%s>%s: %s%s%s",
-        sitename, pfx, msgbuf,
-        errnoval>=0 ? ": " : "",
-        errnoval>=0 ? strerror(errnoval) : "");
+  logcore(sysloglevel, "%s%s: %s%s%s",
+         logv_prefix, pfx, msgbuf,
+         errnoval>=0 ? ": " : "",
+         errnoval>=0 ? strerror(errnoval) : "");
 }
 
-#define diewrap(fn, pfx, sysloglevel, err, estatus)            \
+#define DEFFATAL(fn, pfx, sysloglevel, err, estatus)           \
   static void fn(const char *fmt, ...) NORET_PRINTF(1,2);      \
   static void fn(const char *fmt, ...) {                       \
     preterminate();                                            \
@@ -577,7 +586,7 @@ static void logv(int sysloglevel, const char *pfx, int errnoval,
     exit(estatus);                                             \
   }
 
-#define logwrap(fn, pfx, sysloglevel, err)             \
+#define DEFLOG(fn, pfx, sysloglevel, err)              \
   static void fn(const char *fmt, ...) PRINTF(1,2);    \
   static void fn(const char *fmt, ...) {               \
     VA;                                                        \
@@ -585,18 +594,31 @@ static void logv(int sysloglevel, const char *pfx, int errnoval,
     va_end(al);                                                \
   }
 
-diewrap(sysdie,   " critical", LOG_CRIT,    errno, 16);
-diewrap(die,      " critical", LOG_CRIT,    -1,    16);
+#define INNLOGSET_DECLARE(fn, pfx, sysloglevel)                              \
+  static void duct_log_##fn(int l, const char *fmt, va_list al, int errval) { \
+    logv(sysloglevel, pfx, errval ? errval : -1, fmt, al);                   \
+  }
+#define INNLOGSET_CALL(fn, pfx, sysloglevel)   \
+  message_handlers_##fn(1, duct_log_##fn);
+
+
+static int innduct_fatal_cleanup(void) { return 12; } /* used for libinn die */
 
-diewrap(sysfatal, " fatal",    LOG_ERR,     errno, 12);
-diewrap(fatal,    " fatal",    LOG_ERR,     -1,    12);
+/* We want to extend the set of logging functions from inn, and we
+ * want to prepend the site name to all our messages. */
 
-logwrap(syswarn,  " warning",  LOG_WARNING, errno);
-logwrap(warn,     " warning",  LOG_WARNING, -1);
+DEFFATAL(syscrash,    "critical", LOG_CRIT,    errno, 16);
+DEFFATAL(crash,       "critical", LOG_CRIT,    -1,    16);
 
-logwrap(notice,   " notice",   LOG_NOTICE,  -1);
-logwrap(info,     " info",     LOG_INFO,    -1);
-logwrap(debug,    " debug",    LOG_DEBUG,   -1);
+#define INNLOGSETS(INNLOGSET)                  \
+  INNLOGSET(die,      "fatal",    LOG_ERR)     \
+  INNLOGSET(warn,     "warning",  LOG_WARNING) \
+  INNLOGSET(notice,   "notice",   LOG_NOTICE)  \
+  INNLOGSET(trace,    "trace",    LOG_NOTICE)
+INNLOGSETS(INNLOGSET_DECLARE)
+
+DEFLOG(info,          "info",     LOG_INFO,    -1)
+DEFLOG(dbg,           "debug",    LOG_DEBUG,   -1)
 
 
 /*========== utility functions etc. ==========*/
@@ -624,7 +646,7 @@ static int close_perhaps(int *fd) {
 }
 static void xclose(int fd, const char *what, const char *what2) {
   int r= close(fd);
-  if (r) sysdie("close %s%s",what,what2?what2:"");
+  if (r) syscrash("close %s%s",what,what2?what2:"");
 }
 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
   if (*fd <= 0) return;
@@ -636,8 +658,8 @@ static pid_t xfork(const char *what) {
   pid_t child;
 
   child= fork();
-  if (child==-1) sysfatal("cannot fork for %s",what);
-  debug("forked %s %ld", what, (unsigned long)child);
+  if (child==-1) sysdie("cannot fork for %s",what);
+  dbg("forked %s %ld", what, (unsigned long)child);
   if (!child) postfork();
   return child;
 }
@@ -674,11 +696,11 @@ static int xwaitpid(pid_t *pid, const char *what) {
   int status;
 
   int r= kill(*pid, SIGKILL);
-  if (r) sysdie("cannot kill %s child", what);
+  if (r) syscrash("cannot kill %s child", what);
 
   pid_t got= waitpid(*pid, &status, 0);
-  if (got==-1) sysdie("cannot reap %s child", what);
-  if (got==0) die("cannot reap %s child", what);
+  if (got==-1) syscrash("cannot reap %s child", what);
+  if (got==0) crash("cannot reap %s child", what);
 
   *pid= 0;
 
@@ -693,18 +715,18 @@ static void *zxmalloc(size_t sz) {
 
 static void xunlink(const char *path, const char *what) {
   int r= unlink(path);
-  if (r) sysdie("can't unlink %s %s", path, what);
+  if (r) syscrash("can't unlink %s %s", path, what);
 }
 
 static time_t xtime(void) {
   time_t now= time(0);
-  if (now==-1) sysdie("time(2) failed");
+  if (now==-1) syscrash("time(2) failed");
   return now;
 }
 
 static void xsigaction(int signo, const struct sigaction *sa) {
   int r= sigaction(signo,sa,0);
-  if (r) sysdie("sigaction failed for \"%s\"", strsignal(signo));
+  if (r) syscrash("sigaction failed for \"%s\"", strsignal(signo));
 }
 
 static void xsigsetdefault(int signo) {
@@ -716,24 +738,24 @@ static void xsigsetdefault(int signo) {
 
 static void xgettimeofday(struct timeval *tv_r) {
   int r= gettimeofday(tv_r,0);
-  if (r) sysdie("gettimeofday(2) failed");
+  if (r) syscrash("gettimeofday(2) failed");
 }
 
 static void xsetnonblock(int fd, int nonblocking) {
   int errnoval= oop_fd_nonblock(fd, nonblocking);
-  if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
+  if (errnoval) { errno= errnoval; syscrash("setnonblocking"); }
 }
 
 static void check_isreg(const struct stat *stab, const char *path,
                        const char *what) {
   if (!S_ISREG(stab->st_mode))
-    die("%s %s not a plain file (mode 0%lo)",
-       what, path, (unsigned long)stab->st_mode);
+    crash("%s %s not a plain file (mode 0%lo)",
+         what, path, (unsigned long)stab->st_mode);
 }
 
 static void xfstat(int fd, struct stat *stab_r, const char *what) {
   int r= fstat(fd, stab_r);
-  if (r) sysdie("could not fstat %s", what);
+  if (r) syscrash("could not fstat %s", what);
 }
 
 static void xfstat_isreg(int fd, struct stat *stab_r,
@@ -748,7 +770,7 @@ static void xlstat_isreg(const char *path, struct stat *stab,
   int r= lstat(path, stab);
   if (r) {
     if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
-    sysdie("could not lstat %s %s", what, path);
+    syscrash("could not lstat %s %s", what, path);
   }
   if (enoent_r) *enoent_r= 0;
   check_isreg(stab, path, what);
@@ -1008,9 +1030,23 @@ static void cli_init(void) {
   memset(&sa,0,sizeof(sa));
   int maxlen= sizeof(sa.un.sun_path);
 
+  if (!path_cli) {
+    info("control command line disabled");
+    return;
+  }
+
   int pathlen= strlen(path_cli);
-  if (pathlen > maxlen)
-    NOCLI("cli socket path %s too long (%d>%d)", path_cli, pathlen, maxlen);
+  if (pathlen > maxlen) {
+    warn("no cli listener, because cli socket path %s too long (%d>%d)",
+        path_cli, pathlen, maxlen);
+    return;
+  }
+
+  if (path_cli_dir) {
+    int r= mkdir(path_cli_dir, 0700);
+    if (r && errno!=EEXIST)
+      NOCLI("create cli socket directory %s", path_cli_dir);
+  }
 
   int r= unlink(path_cli);
   if (r && errno!=ENOENT)
@@ -1019,7 +1055,7 @@ static void cli_init(void) {
   cli_master= socket(PF_UNIX, SOCK_STREAM, 0);
   if (cli_master<0) NOCLI("create new cli master socket");
 
-  int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
+  int sl= pathlen + offsetof(struct sockaddr_un, sun_path);
   sa.un.sun_family= AF_UNIX;
   memcpy(sa.un.sun_path, path_cli, pathlen);
 
@@ -1043,12 +1079,24 @@ static void cli_init(void) {
 
 /*========== management of connections ==========*/
 
+static void reconnect_blocking_event(void) {
+  until_connect= reconnect_delay_periods;
+}
+
 static void conn_closefd(Conn *conn, const char *msgprefix) {
   int r= close_perhaps(&conn->fd);
   if (r) info("C%d %serror closing socket: %s",
              conn->fd, msgprefix, strerror(errno));
 }
 
+static int conn_busy(Conn *conn) {
+  return
+    conn->waiting.count ||
+    conn->priority.count ||
+    conn->sent.count ||
+    conn->xmitu;
+}
+
 static void conn_dispose(Conn *conn) {
   if (!conn) return;
   if (conn->rd) {
@@ -1062,7 +1110,6 @@ static void conn_dispose(Conn *conn) {
   }
   conn_closefd(conn,"");
   free(conn);
-  until_connect= reconnect_delay_periods;
 }
 
 static void *conn_exception(oop_source *lp, int fd,
@@ -1102,12 +1149,14 @@ static void vconnfail(Conn *conn, const char *fmt, va_list al) {
   for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
     xmit_free(d);
 
+  LIST_REMOVE(conns,conn);
+
   char *m= xvasprintf(fmt,al);
-  warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
-       conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
+  warn("C%d (now %d) connection failed requeueing " RCI_TRIPLE_FMT_BASE ": %s",
+       conn->fd, conns.count, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
   free(m);
 
-  LIST_REMOVE(conns,conn);
+  reconnect_blocking_event();
   conn_dispose(conn);
   check_assign_articles();
 }
@@ -1119,17 +1168,56 @@ static void connfail(Conn *conn, const char *fmt, ...) {
   va_end(al);
 }
 
+static void conn_idle_close(Conn *conn, const char *why) {
+  static const char quitcmd[]= "QUIT\r\n";
+  int todo= sizeof(quitcmd)-1;
+  const char *p= quitcmd;
+  for (;;) {
+    int r= write(conn->fd, p, todo);
+    if (r<0) {
+      if (isewouldblock(errno))
+       connfail(conn, "blocked writing QUIT to idle connection");
+      else
+       connfail(conn, "failed to write QUIT to idle connection: %s",
+                strerror(errno));
+      break;
+    }
+    assert(r<=todo);
+    todo -= r;
+    if (!todo) {
+      conn->quitting= why;
+      conn->since_activity= 0;
+      dbg("C%d is idle (%s), quitting", conn->fd, why);
+      break;
+    }
+  }
+}
+
+/*
+ * For our last connection, we also shut it down if we have had
+ * less than K in the last L
+ */
 static void check_idle_conns(void) {
   Conn *conn;
+
+  int volthisperiod= lowvol_perperiod[lowvol_circptr];
+  lowvol_circptr++;
+  lowvol_circptr %= lowvol_periods;
+  lowvol_total += volthisperiod;
+  lowvol_total -= lowvol_perperiod[lowvol_circptr];
+  lowvol_perperiod[lowvol_circptr]= 0;
+
   FOR_CONN(conn)
     conn->since_activity++;
+
  search_again:
   FOR_CONN(conn) {
     if (conn->since_activity <= need_activity_periods) continue;
 
     /* We need to shut this down */
     if (conn->quitting)
-      connfail(conn,"timed out waiting for response to QUIT");
+      connfail(conn,"timed out waiting for response to QUIT (%s)",
+              conn->quitting);
     else if (conn->sent.count)
       connfail(conn,"timed out waiting for responses");
     else if (conn->waiting.count || conn->priority.count)
@@ -1137,32 +1225,18 @@ static void check_idle_conns(void) {
     else if (conn->xmitu)
       connfail(conn,"peer has been sending responses"
               " before receiving our commands!");
-    else {
-      static const char quitcmd[]= "QUIT\r\n";
-      int todo= sizeof(quitcmd)-1;
-      const char *p= quitcmd;
-      for (;;) {
-       int r= write(conn->fd, p, todo);
-       if (r<0) {
-         if (isewouldblock(errno))
-           connfail(conn, "blocked writing QUIT to idle connection");
-         else
-           connfail(conn, "failed to write QUIT to idle connection: %s",
-                    strerror(errno));
-         break;
-       }
-       assert(r<=todo);
-       todo -= r;
-       if (!todo) {
-         conn->quitting= 1;
-         conn->since_activity= 0;
-         debug("C%d is idle, quitting", conn->fd);
-         break;
-       }
-      }
-    }
+    else
+      conn_idle_close(conn, "no activity");
+    
     goto search_again;
   }
+
+  conn= LIST_HEAD(conns);
+  if (!volthisperiod &&
+      conns.count==1 &&
+      lowvol_total < lowvol_thresh &&
+      !conn_busy(conn))
+    conn_idle_close(conn, "low volume");
 }  
 
 /*---------- making new connections ----------*/
@@ -1243,24 +1317,24 @@ static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
     goto x;
   }
 
-#define CHK(field, val)                                                         \
-  if (h->cmsg_##field != val) {                                                 \
-    die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
-       h->cmsg_##field, val);                                           \
-    goto x;                                                             \
+#define CHK(field, val)                                                           \
+  if (h->cmsg_##field != val) {                                                   \
+    crash("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
+         h->cmsg_##field, val);                                           \
+    goto x;                                                               \
   }
   CHK(level, SOL_SOCKET);
   CHK(type,  SCM_RIGHTS);
   CHK(len,   CMSG_LEN(sizeof(conn->fd)));
 #undef CHK
 
-  if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
+  if (CMSG_NXTHDR(&msg,h)) crash("connect: child sent many cmsgs");
 
   memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
 
   int status;
   pid_t got= waitpid(connecting_child, &status, 0);
-  if (got==-1) sysdie("connect: real wait for child");
+  if (got==-1) syscrash("connect: real wait for child");
   assert(got == connecting_child);
   connecting_child= 0;
 
@@ -1270,7 +1344,7 @@ static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
   case CONNCHILD_ESTATUS_STREAM:    conn->stream= 1;   break;
   case CONNCHILD_ESTATUS_NOSTREAM:  conn->stream= 0;   break;
   default:
-    fatal("connect: child gave unexpected exit status %d", es);
+    die("connect: child gave unexpected exit status %d", es);
   }
 
   /* Phew! */
@@ -1278,14 +1352,15 @@ static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
 
   loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
   conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
-  if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
+  if (!conn->fd) crash("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
   int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
                     &peer_rd_ok, conn,
                     &peer_rd_err, conn);
-  if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
+  if (r) syscrash("oop_rd_read for peer (fd=%d)",conn->fd);
 
-  notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
   LIST_ADDHEAD(conns, conn);
+  notice("C%d (now %d) connected %s",
+        conn->fd, conns.count, conn->stream ? "streaming" : "plain");
 
   connect_attempt_discard();
   check_assign_articles();
@@ -1294,6 +1369,7 @@ static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
  x:
   conn_dispose(conn);
   connect_attempt_discard();
+  reconnect_blocking_event();
   return OOP_CONTINUE;
 }
 
@@ -1308,6 +1384,8 @@ static void connect_start(void) {
   assert(!connecting_fdpass_sock);
 
   info("starting connection attempt");
+  int ok_until_connect= until_connect;
+  reconnect_blocking_event();
 
   int socks[2];
   int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
@@ -1333,37 +1411,37 @@ static void connect_start(void) {
        --l;
       }
       if (!buf[0]) {
-       sysfatal("connect: connection attempt failed");
+       sysdie("connect: connection attempt failed");
       } else {
        buf[l]= 0;
-       fatal("connect: %s: %s", stripped ? "rejected" : "failed",
-             sanitise(buf,-1));
+       die("connect: %s: %s", stripped ? "rejected" : "failed",
+           sanitise(buf,-1));
       }
     }
     if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
-      sysfatal("connect: authentication failed");
+      sysdie("connect: authentication failed");
     if (try_stream) {
       if (fputs("MODE STREAM\r\n", cn_to)==EOF ||
          fflush(cn_to))
-       sysfatal("connect: could not send MODE STREAM");
+       sysdie("connect: could not send MODE STREAM");
       buf[sizeof(buf)-1]= 0;
       if (!fgets(buf, sizeof(buf)-1, cn_from)) {
        if (ferror(cn_from))
-         sysfatal("connect: could not read response to MODE STREAM");
+         sysdie("connect: could not read response to MODE STREAM");
        else
-         fatal("connect: connection close in response to MODE STREAM");
+         die("connect: connection close in response to MODE STREAM");
       }
       int l= strlen(buf);
       assert(l>=1);
       if (buf[l-1]!='\n')
-       fatal("connect: response to MODE STREAM is too long: %.100s...",
-             sanitise(buf,-1));
+       die("connect: response to MODE STREAM is too long: %.100s...",
+           sanitise(buf,-1));
       l--;  if (l>0 && buf[l-1]=='\r') l--;
       buf[l]= 0;
       char *ep;
       int rcode= strtoul(buf,&ep,10);
       if (ep != &buf[3])
-       fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf,-1));
+       die("connect: bad response to MODE STREAM: %.50s", sanitise(buf,-1));
 
       switch (rcode) {
       case 203:
@@ -1390,8 +1468,8 @@ static void connect_start(void) {
 
     msg.msg_controllen= cmsg->cmsg_len;
     r= sendmsg(socks[1], &msg, 0);
-    if (r<0) sysdie("sendmsg failed for new connection");
-    if (r!=1) die("sendmsg for new connection gave wrong result %d",r);
+    if (r<0) syscrash("sendmsg failed for new connection");
+    if (r!=1) crash("sendmsg for new connection gave wrong result %d",r);
 
     _exit(exitstatus);
   }
@@ -1400,6 +1478,9 @@ static void connect_start(void) {
   connecting_fdpass_sock= socks[0];
   xsetnonblock(connecting_fdpass_sock, 1);
   on_fd_read_except(connecting_fdpass_sock, connchild_event);
+
+  if (!conns.count)
+    until_connect= ok_until_connect;
 }
 
 /*---------- assigning articles to conns, and transmitting ----------*/
@@ -1452,11 +1533,11 @@ static void check_assign_articles(void) {
        Article *art= dequeue(0);
        if (!art) break;
        LIST_ADDTAIL(use->waiting, art);
+       lowvol_perperiod[lowvol_circptr]++;
        spare--;
       }
       conn_maybe_write(use);
     } else if (allow_connect_start()) {
-      until_connect= reconnect_delay_periods;
       connect_start();
       break;
     } else {
@@ -1475,12 +1556,16 @@ static void conn_maybe_write(Conn *conn)  {
     conn_make_some_xmits(conn);
     if (!conn->xmitu) {
       loop->cancel_fd(loop, conn->fd, OOP_WRITE);
+      conn->oopwriting= 0;
       return;
     }
 
     void *rp= conn_write_some_xmits(conn);
     if (rp==OOP_CONTINUE) {
-      loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
+      if (!conn->oopwriting) {
+       loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
+       conn->oopwriting= 1;
+      }
       return;
     } else if (rp==OOP_HALT) {
       return;
@@ -1525,7 +1610,7 @@ static void article_defer(Article *art /* not on a queue */, int whichcount) {
   open_defer();
   if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
       || fflush(defer))
-    sysfatal("write to defer file %s",path_defer);
+    sysdie("write to defer file %s",path_defer);
   article_done(art, whichcount);
 }
 
@@ -1570,6 +1655,7 @@ static void autodefer_input_file_articles(InputFile *ipf) {
 }
 
 static void autodefer_input_file(InputFile *ipf) {
+  static const char *const abandon= "stuck";
   ipf->autodefer= 0;
 
   autodefer_input_file_articles(ipf);
@@ -1580,11 +1666,11 @@ static void autodefer_input_file(InputFile *ipf) {
       if (has_article_in(&walk->waiting,  ipf) ||
          has_article_in(&walk->priority, ipf) ||
          has_article_in(&walk->sent,     ipf))
-       walk->quitting= -1;
+       walk->quitting= abandon;
     }
     while (ipf->inprogress) {
       FOR_CONN(walk)
-       if (walk->quitting < 0) goto found;
+       if (walk->quitting == abandon) goto found;
       abort(); /* where are they ?? */
 
     found:
@@ -1647,15 +1733,18 @@ static void *conn_write_some_xmits(Conn *conn) {
     assert(rs > 0);
 
     int done;
-    for (done=0; rs && done<conn->xmitu; done++) {
+    for (done=0; rs; ) {
+      assert(done<conn->xmitu);
       struct iovec *vp= &conn->xmit[done];
       XmitDetails *dp= &conn->xmitd[done];
-      if (rs > vp->iov_len) {
+      if (rs >= vp->iov_len) {
        rs -= vp->iov_len;
-       xmit_free(dp);
+       xmit_free(dp); /* vp->iov_len -= vp->iov_len, etc. */
+       done++;
       } else {
        vp->iov_base= (char*)vp->iov_base + rs;
        vp->iov_len -= rs;
+       break; /* rs -= rs */
       }
     }
     int newu= conn->xmitu - done;
@@ -1809,7 +1898,7 @@ static void update_nocheck(int accepted) {
     notice("entering nocheck mode for the first time");
     nocheck_reported= 1;
   } else if (new_nocheck != nocheck) {
-    debug("nocheck mode %s", new_nocheck ? "start" : "stop");
+    dbg("nocheck mode %s", new_nocheck ? "start" : "stop");
   }
   nocheck= new_nocheck;
 }
@@ -1838,9 +1927,9 @@ static void article_done(Article *art, int whichcount) {
     int r= pwrite(ipf->fd, spaces, w, art->offset);
     if (r==-1) {
       if (errno==EINTR) continue;
-      sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
-            art->messageid, art->blanklen,
-            (unsigned long)art->offset, ipf->path);
+      syscrash("failed to blank entry for %s (length %d at offset %lu) in %s",
+              art->messageid, art->blanklen,
+              (unsigned long)art->offset, ipf->path);
     }
     assert(r>=0 && r<=w);
     art->blanklen -= w;
@@ -1875,19 +1964,17 @@ static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
     return OOP_CONTINUE;
   }
 
-  int conn_busy=
-    conn->waiting.count ||
-    conn->priority.count ||
-    conn->sent.count ||
-    conn->xmitu;
+  int busy= conn_busy(conn);
 
   if (conn->quitting) {
-    if (code!=205 && code!=503) {
-      connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
+    if (code!=205 && code!=400) {
+      connfail(conn, "peer gave unexpected response to QUIT (%s): %s",
+              conn->quitting, sani);
     } else {
-      notice("C%d idle connection closed by us", conn->fd);
-      assert(!conn_busy);
       LIST_REMOVE(conns,conn);
+      notice("C%d (now %d) idle connection closed (%s)",
+            conn->fd, conns.count, conn->quitting);
+      assert(!busy);
       conn_dispose(conn);
     }
     return OOP_CONTINUE;
@@ -1919,11 +2006,12 @@ static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
   default:  PEERBADMSG("peer sent unexpected message");
 
   case 400:
-    if (conn_busy)
+    if (busy)
       PEERBADMSG("peer timed us out or stopped accepting articles");
 
-    notice("C%d idle connection closed by peer", conn->fd);
     LIST_REMOVE(conns,conn);
+    notice("C%d (now %d) idle connection closed by peer",
+          conns.count, conn->fd);
     conn_dispose(conn);
     return OOP_CONTINUE;
 
@@ -1983,7 +2071,7 @@ static InputFile *open_input_file(const char *path) {
   int fd= open(path, O_RDWR);
   if (fd<0) {
     if (errno==ENOENT) return 0;
-    sysfatal("unable to open input file %s", path);
+    sysdie("unable to open input file %s", path);
   }
   assert(fd>0);
 
@@ -2016,8 +2104,8 @@ static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
   ipf->readcount_err++;
   if (ipf->readcount_err > max_bad_data_initial +
       (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
-    die("too much garbage in input file!  (%d errs, %d ok, %d blank)",
-       ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
+    crash("too much garbage in input file!  (%d errs, %d ok, %d blank)",
+         ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
   return OOP_CONTINUE;
 }
 
@@ -2028,8 +2116,8 @@ static void *feedfile_read_err(oop_source *lp, oop_read *rd,
   InputFile *ipf= ipf_v;
   assert(ev == OOP_RD_SYSTEM);
   errno= errnoval;
-  sysdie("error reading input file: %s, offset %lu",
-        ipf->path, (unsigned long)ipf->offset);
+  syscrash("error reading input file: %s, offset %lu",
+          ipf->path, (unsigned long)ipf->offset);
 }
 
 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
@@ -2091,12 +2179,15 @@ static void *feedfile_got_article(oop_source *lp, oop_read *rd,
   art->offset= old_offset;
   art->blanklen= recsz;
   strcpy(art->messageid, space+1);
-  LIST_ADDTAIL(ipf->queue, art);
 
-  if (ipf->autodefer >= 0)
+  if (ipf->autodefer >= 0) {
     article_autodefer(ipf, art);
-  else if (ipf==backlog_input_file)
-    article_check_expired(art);
+  } else {
+    LIST_ADDTAIL(ipf->queue, art);
+
+    if (ipf==backlog_input_file)
+      article_check_expired(art);
+  }
 
   if (sms==sm_NORMAL && ipf==main_input_file &&
       ipf->offset >= target_max_feedfile_size)
@@ -2111,7 +2202,16 @@ static void *feedfile_got_article(oop_source *lp, oop_read *rd,
 
 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
                                     void *user) {
+  /* lifetime of ipf here is OK because destruction will cause
+   * on_cancel which will cancel this callback */
   InputFile *ipf= user;
+
+  if (!ipf->fake_readable) return OOP_CONTINUE;
+
+  /* we just keep calling readable until our caller (oop_rd)
+   * has called try_read, and try_read has found EOF so given EAGAIN */
+  loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
+
   return ipf->readable_callback(loop, &ipf->readable,
                                ipf->readable_callback_user);
 }
@@ -2124,9 +2224,10 @@ static void tailing_on_cancel(struct oop_readable *rable) {
   ipf->readable_callback= 0;
 }
 
-static void tailing_queue_readable(InputFile *ipf) {
-  /* lifetime of ipf here is OK because destruction will cause
-   * on_cancel which will cancel this callback */
+static void tailing_make_readable(InputFile *ipf) {
+  if (!ipf || !ipf->readable_callback) /* so callers can be naive */
+    return;
+  ipf->fake_readable= 1;
   loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
 }
 
@@ -2138,8 +2239,7 @@ static int tailing_on_readable(struct oop_readable *rable,
   ipf->readable_callback= cb;
   ipf->readable_callback_user= user;
   filemon_start(ipf);
-
-  tailing_queue_readable(ipf);
+  tailing_make_readable(ipf);
   return 0;
 }
 
@@ -2150,11 +2250,13 @@ static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
     ssize_t r= read(ipf->fd, buffer, length);
     if (r==-1) {
       if (errno==EINTR) continue;
+      ipf->fake_readable= 0;
       return r;
     }
     if (!r) {
       if (ipf==main_input_file) {
        errno=EAGAIN;
+       ipf->fake_readable= 0;
        return -1;
       } else if (ipf==flushing_input_file) {
        assert(ipf->rd);
@@ -2165,7 +2267,6 @@ static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
        abort();
       }
     }
-    tailing_queue_readable(ipf);
     return r;
   }
 }
@@ -2187,7 +2288,7 @@ struct Filemon_Perfile {
 
 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
   int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
-  if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
+  if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
 
   if (wd >= filemon_inotify_wdmax) {
     int newmax= wd+2;
@@ -2201,17 +2302,17 @@ static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
   assert(!filemon_inotify_wd2ipf[wd]);
   filemon_inotify_wd2ipf[wd]= ipf;
 
-  debug("filemon inotify startfile %p wd=%d wdmax=%d",
-       ipf, wd, filemon_inotify_wdmax);
+  dbg("filemon inotify startfile %p wd=%d wdmax=%d",
+      ipf, wd, filemon_inotify_wdmax);
 
   pf->wd= wd;
 }
 
 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
   int wd= pf->wd;
-  debug("filemon inotify stopfile %p wd=%d", ipf, wd);
+  dbg("filemon inotify stopfile %p wd=%d", ipf, wd);
   int r= inotify_rm_watch(filemon_inotify_fd, wd);
-  if (r) sysdie("inotify_rm_watch");
+  if (r) syscrash("inotify_rm_watch");
   filemon_inotify_wd2ipf[wd]= 0;
 }
 
@@ -2222,15 +2323,15 @@ static void *filemon_inotify_readable(oop_source *lp, int fd,
     int r= read(filemon_inotify_fd, &iev, sizeof(iev));
     if (r==-1) {
       if (isewouldblock(errno)) break;
-      sysdie("read from inotify master");
+      syscrash("read from inotify master");
     } else if (r==sizeof(iev)) {
       assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
     } else {
-      die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
+      crash("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
     }
     InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
-    /*debug("filemon inotify readable read %p wd=%d", ipf, iev.wd);*/
-    filemon_callback(ipf);
+    /*dbg("filemon inotify readable read %p wd=%d", ipf, iev.wd);*/
+    tailing_make_readable(ipf);
   }
   return OOP_CONTINUE;
 }
@@ -2244,7 +2345,7 @@ static int filemon_method_init(void) {
   xsetnonblock(filemon_inotify_fd, 1);
   loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable, 0);
 
-  debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
+  dbg("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
   return 1;
 }
 
@@ -2291,11 +2392,6 @@ static void filemon_stop(InputFile *ipf) {
   ipf->filemon= 0;
 }
 
-static void filemon_callback(InputFile *ipf) {
-  if (ipf && ipf->readable_callback) /* so filepoll() can be naive */
-    ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
-}
-
 /*---------- interface to start and stop an input file ----------*/
 
 static const oop_rd_style feedfile_rdstyle= {
@@ -2310,7 +2406,7 @@ static void inputfile_reading_resume(InputFile *ipf) {
 
   int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
                     feedfile_got_article,ipf, feedfile_read_err, ipf);
-  if (r) sysdie("unable start reading feedfile %s",ipf->path);
+  if (r) syscrash("unable start reading feedfile %s",ipf->path);
 
   ipf->paused= 0;
 }
@@ -2462,7 +2558,7 @@ static void statemc_lock(void) {
   
   for (;;) {
     lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
-    if (lockfd<0) sysfatal("open lockfile %s", path_lock);
+    if (lockfd<0) sysdie("open lockfile %s", path_lock);
 
     struct flock fl;
     memset(&fl,0,sizeof(fl));
@@ -2472,9 +2568,9 @@ static void statemc_lock(void) {
     if (r==-1) {
       if (errno==EACCES || isewouldblock(errno)) {
        if (quiet_multiple) exit(0);
-       fatal("another duct holds the lockfile");
+       die("another duct holds the lockfile");
       }
-      sysfatal("fcntl F_SETLK lockfile %s", path_lock);
+      sysdie("fcntl F_SETLK lockfile %s", path_lock);
     }
 
     xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
@@ -2488,18 +2584,18 @@ static void statemc_lock(void) {
   }
 
   FILE *lockfile= fdopen(lockfd, "w");
-  if (!lockfile) sysdie("fdopen lockfile");
+  if (!lockfile) syscrash("fdopen lockfile");
 
   int r= ftruncate(lockfd, 0);
-  if (r) sysdie("truncate lockfile to write new info");
+  if (r) syscrash("truncate lockfile to write new info");
 
   if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
              (unsigned long)self_pid,
              sitename, feedfile, remote_host) == EOF ||
       fflush(lockfile))
-    sysfatal("write info to lockfile %s", path_lock);
+    sysdie("write info to lockfile %s", path_lock);
 
-  debug("startup: locked");
+  dbg("startup: locked");
 }
 
 static void statemc_init(void) {
@@ -2510,9 +2606,9 @@ static void statemc_init(void) {
   int defer_noent;
   xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
   if (defer_noent) {
-    debug("startup: ductdefer ENOENT");
+    dbg("startup: ductdefer ENOENT");
   } else {
-    debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
+    dbg("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
     switch (stabdefer.st_nlink==1) {
     case 1:
       open_defer(); /* so that we will later close it and rename it */
@@ -2522,8 +2618,8 @@ static void statemc_init(void) {
              " (presumably hardlink to backlog file)");
       break;
     default:
-      die("defer file %s has unexpected link count %d",
-         path_defer, stabdefer.st_nlink);
+      crash("defer file %s has unexpected link count %d",
+           path_defer, stabdefer.st_nlink);
     }
   }
 
@@ -2536,29 +2632,29 @@ static void statemc_init(void) {
   xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
 
   if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
-    debug("startup: F==D => Hardlinked");
+    dbg("startup: F==D => Hardlinked");
     xunlink(feedfile, "feed file (during startup)"); /* => Moved */
     noent_f= 1;
   }
 
   if (noent_f) {
-    debug("startup: F ENOENT => Moved");
+    dbg("startup: F ENOENT => Moved");
     if (file_d) startup_set_input_file(file_d);
     spawn_inndcomm_flush("feedfile missing at startup");
     /* => Flushing, sms:=FLUSHING */
   } else {
     if (file_d) {
-      debug("startup: F!=D => Separated");
+      dbg("startup: F!=D => Separated");
       startup_set_input_file(file_d);
       flushing_input_file= main_input_file;
       main_input_file= open_input_file(feedfile);
-      if (!main_input_file) die("feedfile vanished during startup");
+      if (!main_input_file) crash("feedfile vanished during startup");
       SMS(SEPARATED, max_separated_periods,
          "found both old and current feed files");
     } else {
-      debug("startup: F exists, D ENOENT => Normal");
+      dbg("startup: F exists, D ENOENT => Normal");
       InputFile *file_f= open_input_file(feedfile);
-      if (!file_f) die("feed file vanished during startup");
+      if (!file_f) crash("feed file vanished during startup");
       startup_set_input_file(file_f);
       SMS(NORMAL, spontaneous_flush_periods, "normal startup");
     }
@@ -2568,15 +2664,15 @@ static void statemc_init(void) {
 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
   assert(sms == sm_NORMAL);
 
-  debug("starting flush (%s) (%lu >?= %lu) (%d)",
+  dbg("starting flush (%s) (%lu >?= %lu) (%d)",
        why,
        (unsigned long)(main_input_file ? main_input_file->offset : 0),
        (unsigned long)target_max_feedfile_size,
        until_flush);
 
   int r= link(feedfile, path_flushing);
-  if (r) sysfatal("link feedfile %s to flushing file %s",
-                 feedfile, path_flushing);
+  if (r) sysdie("link feedfile %s to flushing file %s",
+               feedfile, path_flushing);
   /* => Hardlinked */
 
   xunlink(feedfile, "old feedfile link");
@@ -2677,7 +2773,7 @@ static void statemc_check_backlog_done(void) {
   close_input_file(ipf);
   if (unlink(ipf->path)) {
     if (errno != ENOENT)
-      sysdie("could not unlink processed backlog file %s", ipf->path);
+      syscrash("could not unlink processed backlog file %s", ipf->path);
     warn("backlog file %s vanished while we were reading it"
         " so we couldn't remove it (but it's done now, anyway)",
         ipf->path);
@@ -2716,7 +2812,8 @@ static void statemc_check_flushing_done(void) {
 
 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
                                      void *u) {
-  assert(!inputfile_is_done(main_input_file));
+  /* main input file may be idle but if so that's because
+   * we haven't got to it yet, but that doesn't mean it's really done */
   statemc_check_flushing_done();
   statemc_check_backlog_done();
   return OOP_CONTINUE;
@@ -2759,14 +2856,14 @@ static void open_defer(void) {
   if (defer) return;
 
   defer= fopen(path_defer, "a+");
-  if (!defer) sysfatal("could not open defer file %s", path_defer);
+  if (!defer) sysdie("could not open defer file %s", path_defer);
 
   /* truncate away any half-written records */
 
   xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
 
   if (stab.st_size > LONG_MAX)
-    die("defer file %s size is far too large", path_defer);
+    crash("defer file %s size is far too large", path_defer);
 
   if (!stab.st_size)
     return;
@@ -2776,14 +2873,14 @@ static void open_defer(void) {
   for (;;) {
     if (!truncto) break; /* was only (if anything) one half-truncated record */
     if (fseek(defer, truncto-1, SEEK_SET) < 0)
-      sysdie("seek in defer file %s while truncating partial", path_defer);
+      syscrash("seek in defer file %s while truncating partial", path_defer);
 
     int r= getc(defer);
     if (r==EOF) {
       if (ferror(defer))
-       sysdie("failed read from defer file %s", path_defer);
+       syscrash("failed read from defer file %s", path_defer);
       else
-       die("defer file %s shrank while we were checking it!", path_defer);
+       crash("defer file %s shrank while we were checking it!", path_defer);
     }
     if (r=='\n') break;
     truncto--;
@@ -2795,16 +2892,16 @@ static void open_defer(void) {
         path_defer, orgsize - truncto, orgsize, truncto);
 
     if (fflush(defer))
-      sysfatal("could not flush defer file %s", path_defer);
+      sysdie("could not flush defer file %s", path_defer);
     if (ftruncate(fileno(defer), truncto))
-      sysdie("could not truncate defer file %s", path_defer);
+      syscrash("could not truncate defer file %s", path_defer);
 
   } else {
     info("continuing existing defer file %s (%ld bytes)",
         path_defer, orgsize);
   }
   if (fseek(defer, truncto, SEEK_SET))
-    sysdie("could not seek to new end of defer file %s", path_defer);
+    syscrash("could not seek to new end of defer file %s", path_defer);
 }
 
 static void close_defer(void) {
@@ -2814,7 +2911,7 @@ static void close_defer(void) {
   struct stat stab;
   xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
 
-  if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
+  if (fclose(defer)) sysdie("could not close defer file %s", path_defer);
   defer= 0;
 
   time_t now= xtime();
@@ -2823,11 +2920,11 @@ static void close_defer(void) {
                           (unsigned long)now,
                           (unsigned long)stab.st_ino);
   if (link(path_defer, backlog))
-    sysfatal("could not install defer file %s as backlog file %s",
+    sysdie("could not install defer file %s as backlog file %s",
           path_defer, backlog);
   if (unlink(path_defer))
-    sysdie("could not unlink old defer link %s to backlog file %s",
-          path_defer, backlog);
+    syscrash("could not unlink old defer link %s to backlog file %s",
+            path_defer, backlog);
 
   free(backlog);
 
@@ -2859,15 +2956,15 @@ static void search_backlog_file(void) {
 
   switch (r) {
   case GLOB_ABORTED:
-    sysfatal("failed to expand backlog pattern %s", globpat_backlog);
+    sysdie("failed to expand backlog pattern %s", globpat_backlog);
   case GLOB_NOSPACE:
-    fatal("out of memory expanding backlog pattern %s", globpat_backlog);
+    die("out of memory expanding backlog pattern %s", globpat_backlog);
   case 0:
     for (i=0; i<gl.gl_pathc; i++) {
       const char *path= gl.gl_pathv[i];
 
       if (strchr(path,'#') || strchr(path,'~')) {
-       debug("backlog file search skipping %s", path);
+       dbg("backlog file search skipping %s", path);
        continue;
       }
       r= stat(path, &stab);
@@ -2887,12 +2984,12 @@ static void search_backlog_file(void) {
   case GLOB_NOMATCH: /* fall through */
     break;
   default:
-    sysdie("glob expansion of backlog pattern %s gave unexpected"
-          " nonzero (error?) return value %d", globpat_backlog, r);
+    syscrash("glob expansion of backlog pattern %s gave unexpected"
+            " nonzero (error?) return value %d", globpat_backlog, r);
   }
 
   if (!oldest_path) {
-    debug("backlog scan: none");
+    dbg("backlog scan: none");
 
     if (sms==sm_DROPPED) {
       preterminate();
@@ -2914,7 +3011,7 @@ static void search_backlog_file(void) {
   long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
 
   if (age_deficiency <= 0) {
-    debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
+    dbg("backlog scan: found age=%f deficiency=%ld oldest=%s",
          age, age_deficiency, oldest_path);
 
     backlog_input_file= open_input_file(oldest_path);
@@ -2934,7 +3031,7 @@ static void search_backlog_file(void) {
       until_backlog_nextscan > backlog_spontrescan_periods)
     until_backlog_nextscan= backlog_spontrescan_periods;
 
-  debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
+  dbg("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
        age, age_deficiency, until_backlog_nextscan, oldest_path);
 
  xfree:
@@ -2966,8 +3063,9 @@ static void *sigarrived_event(oop_source *lp, int fd, oop_event e, void *u) {
   assert(fd=signal_self_pipe[0]);
   char buf[PIPE_BUF];
   int r= read(signal_self_pipe[0], buf, sizeof(buf));
-  if (r<0 && !isewouldblock(errno)) sysdie("failed to read signal self pipe");
-  if (r==0) die("eof on signal self pipe");
+  if (r<0 && !isewouldblock(errno))
+    syscrash("failed to read signal self pipe");
+  if (r==0) crash("eof on signal self pipe");
   if (terminate_sig_flag) {
     preterminate();
     notice("terminating (%s)", strsignal(terminate_sig_flag));
@@ -2991,9 +3089,9 @@ static void sigarrived_handler(int signum) {
 
 static void init_signals(void) {
   if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
-    sysdie("could not ignore SIGPIPE");
+    syscrash("could not ignore SIGPIPE");
 
-  if (pipe(signal_self_pipe)) sysfatal("create self-pipe for signals");
+  if (pipe(signal_self_pipe)) sysdie("create self-pipe for signals");
 
   xsetnonblock(signal_self_pipe[0],1);
   xsetnonblock(signal_self_pipe[1],1);
@@ -3034,7 +3132,7 @@ static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
     case INNDCOMMCHILD_ESTATUS_NONESUCH:
       notice("feed has been dropped by innd, finishing up");
       flushing_input_file= main_input_file;
-      tailing_queue_readable(flushing_input_file);
+      tailing_make_readable(flushing_input_file);
        /* we probably previously returned EAGAIN from our fake read method
         * when in fact we were at EOF, so signal another readable event
         * so we actually see the EOF */
@@ -3054,17 +3152,19 @@ static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
     case 0:
       /* as above */
       flushing_input_file= main_input_file;
-      tailing_queue_readable(flushing_input_file);
+      tailing_make_readable(flushing_input_file);
 
       main_input_file= open_input_file(feedfile);
       if (!main_input_file)
-       die("flush succeeded but feedfile %s does not exist!", feedfile);
+       crash("flush succeeded but feedfile %s does not exist!"
+             " (this probably means feedfile does not correspond"
+             " to site %s in newsfeeds)", feedfile, sitename);
 
       if (flushing_input_file) {
-       SMS(SEPARATED, max_separated_periods, "recovery flush complete");
+       SMS(SEPARATED, max_separated_periods, "flush complete");
       } else {
        close_defer();
-       SMS(NORMAL, spontaneous_flush_periods, "flush complete");
+       SMS(NORMAL, spontaneous_flush_periods, "recovery flush complete");
       }
       return OOP_CONTINUE;
 
@@ -3099,7 +3199,7 @@ void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
   assert(!inndcomm_child);
   assert(!inndcomm_sentinel_fd);
 
-  if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
+  if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
 
   inndcomm_child= xfork("inndcomm child");
 
@@ -3147,7 +3247,7 @@ static void postfork_inputfile(InputFile *ipf) {
 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
   /* we have no stdio streams that are buffered long-term */
   if (!f) return;
-  if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
+  if (fclose(f)) syscrash("(in child) close %s%s", what, what2?what2:0);
 }
 
 static void postfork(void) {
@@ -3203,11 +3303,11 @@ static void every(int interval, int fixed_rate, void (*f)(void)) {
 }
 
 static void filepoll(void) {
-  filemon_callback(main_input_file);
-  filemon_callback(flushing_input_file);
+  tailing_make_readable(main_input_file);
+  tailing_make_readable(flushing_input_file);
 }
 
-static char *debug_report_ipf(InputFile *ipf) {
+static char *dbg_report_ipf(InputFile *ipf) {
   if (!ipf) return xasprintf("none");
 
   const char *slash= strrchr(ipf->path,'/');
@@ -3223,19 +3323,19 @@ static char *debug_report_ipf(InputFile *ipf) {
 }
 
 static void period(void) {
-  char *dipf_main=     debug_report_ipf(main_input_file);
-  char *dipf_flushing= debug_report_ipf(flushing_input_file);
-  char *dipf_backlog=  debug_report_ipf(backlog_input_file);
-
-  debug("PERIOD"
-       " sms=%s[%d] conns=%d until_connect=%d"
-       " input_files main:%s flushing:%s backlog:%s[%d]"
-       " children connecting=%ld inndcomm=%ld"
-       ,
-       sms_names[sms], until_flush, conns.count, until_connect,
-       dipf_main, dipf_flushing, dipf_backlog, until_backlog_nextscan,
-       (long)connecting_child, (long)inndcomm_child
-       );
+  char *dipf_main=     dbg_report_ipf(main_input_file);
+  char *dipf_flushing= dbg_report_ipf(flushing_input_file);
+  char *dipf_backlog=  dbg_report_ipf(backlog_input_file);
+
+  dbg("PERIOD"
+      " sms=%s[%d] conns=%d until_connect=%d"
+      " input_files main:%s flushing:%s backlog:%s[%d]"
+      " children connecting=%ld inndcomm=%ld lowvol_total=%d"
+      ,
+      sms_names[sms], until_flush, conns.count, until_connect,
+      dipf_main, dipf_flushing, dipf_backlog, until_backlog_nextscan,
+      (long)connecting_child, (long)inndcomm_child, lowvol_total
+      );
 
   free(dipf_main);
   free(dipf_flushing);
@@ -3273,7 +3373,7 @@ static void dump_article_list(FILE *f, const CliCommand *c,
   
 static void dump_input_file(FILE *f, const CliCommand *c,
                            InputFile *ipf, const char *wh) {
-  char *dipf= debug_report_ipf(ipf);
+  char *dipf= dbg_report_ipf(ipf);
   fprintf(f,"input %s %s", wh, dipf);
   free(dipf);
   
@@ -3325,6 +3425,17 @@ CCMD(dump) {
   DUMPV("%d", , cli_master);
   fprintf(f,"\n");
 
+  fprintf(f,"lowvol");
+  DUMPV("%d", , lowvol_circptr);
+  DUMPV("%d", , lowvol_total);
+  fprintf(f,":");
+  for (i=0; i<lowvol_periods; i++) {
+    fprintf(f," ");
+    if (i==lowvol_circptr) fprintf(f,"*");
+    fprintf(f,"%d",lowvol_perperiod[i]);
+  }
+  fprintf(f,"\n");
+
   fprintf(f,"filemon ");
   filemon_method_dump_info(f);
 
@@ -3339,7 +3450,7 @@ CCMD(dump) {
 
     fprintf(f,"C%d",conn->fd);
     DUMPV("%p",conn->,rd);             DUMPV("%d",conn->,max_queue);
-    DUMPV("%d",conn->,stream);         DUMPV("%d",conn->,quitting);
+    DUMPV("%d",conn->,stream);         DUMPV("\"%s\"",conn->,quitting);
     DUMPV("%d",conn->,since_activity);
     fprintf(f,"\n");
 
@@ -3388,8 +3499,8 @@ static void vbadusage(const char *fmt, va_list al) {
   fprintf(stderr, "bad usage: %s\n"
          "say --help for help, or read the manpage\n",
          m);
-  if (become_daemon)
-    syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
+  if (interactive < 2)
+    syslog(LOG_ERR,"innduct: invoked with bad usage: %s",m);
   exit(8);
 }
 
@@ -3548,12 +3659,14 @@ static void help(const Option *o, const char *val);
 static const Option innduct_options[]= {
 {'f',"feedfile",         "F",     &feedfile,                 op_string      },
 {'q',"quiet-multiple",   0,       &quiet_multiple,           op_setint, 1   },
-{0,"no-daemon",          0,       &become_daemon,            op_setint, 0   },
+{0,"no-daemon",          0,       &interactive,              op_setint, 1   },
+{0,"interactive",        0,       &interactive,              op_setint, 2   },
 {0,"no-streaming",       0,       &try_stream,               op_setint, 0   },
 {0,"no-filemon",         0,       &try_filemon,              op_setint, 0   },
 {'C',"inndconf",         "F",     &inndconffile,             op_string      },
 {'P',"port",             "PORT",  &port,                     op_integer     },
-{0,"cli",                0,       &path_cli,                 op_string      },
+{0,"chdir",              "DIR",   &path_run,                 op_string      },
+{0,"cli",            "DIR/|PATH", &path_cli,                 op_string      },
 {0,"help",               0,       0,                         help           },
 
 {0,"max-connections",    "N",     &max_connections,          op_integer     },
@@ -3576,6 +3689,8 @@ static const Option innduct_options[]= {
 {0,"max-flush-interval",     "PERIOD", &spontaneous_flush_periods,op_seconds },
 {0,"flush-finish-timeout",   "PERIOD", &max_separated_periods,    op_seconds },
 {0,"idle-timeout",           "PERIOD", &need_activity_periods,    op_seconds },
+{0,"low-volume-thresh",      "PERIOD", &lowvol_thresh,            op_integer },
+{0,"low-volume-window",      "PERIOD", &lowvol_periods,           op_seconds },
 
 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio,   op_double    },
 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer   },
@@ -3603,15 +3718,18 @@ static void convert_to_periods_rndup(int *store) {
   *store /= period_seconds;
 }
 
-static void assemble_path(const char **path_io, const char *suffix,
-                         const char *what) {
-  const char *const specified= *path_io;
-  if (!specified[0]) badusage("%s, if specified, must be nonempty", what);
-  if (specified[strlen(specified)-1]=='/')
-    *path_io= xasprintf("%s%s%s", specified, sitename, suffix);
+static int path_ends_slash(const char *specified) {
+  int l= strlen(specified);
+  assert(l);
+  return specified[l-1] == '/';
 }
 
 int main(int argc, char **argv) {
+  /* set up libinn logging */
+  message_program_name= "innduct";
+  message_fatal_cleanup= innduct_fatal_cleanup;
+  INNLOGSETS(INNLOGSET_CALL)
+
   if (!argv[1]) {
     printusage(stderr);
     exit(8);
@@ -3623,13 +3741,16 @@ int main(int argc, char **argv) {
 
   sitename= *argv++;
   if (!sitename) badusage("need site name argument");
-  remote_host= *argv++;
+
+  if (*argv) remote_host= *argv++;
+  else remote_host= sitename;
+  
   if (*argv) badusage("too many non-option arguments");
 
   /* defaults */
 
   int r= innconf_read(inndconffile);
-  if (!r) badusage("could not read inn.conf (more info on stderr)");
+  if (!r) badusage("could not read inn.conf");
 
   if (!remote_host) remote_host= sitename;
 
@@ -3648,16 +3769,31 @@ int main(int argc, char **argv) {
   convert_to_periods_rndup(&spontaneous_flush_periods);
   convert_to_periods_rndup(&max_separated_periods);
   convert_to_periods_rndup(&need_activity_periods);
+  convert_to_periods_rndup(&lowvol_periods);
 
   if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
     badusage("bad input data ratio must be between 0..100");
   max_bad_data_ratio *= 0.01;
-  
-  if (!feedfile) feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
-  else assemble_path(&feedfile, "", "feed filename");
 
-  if (!path_cli) path_cli= xasprintf("%s_cli", feedfile);
-  else assemble_path(&path_cli, "%s_cli", "cli socket path");
+  if (!path_run)
+    path_run= innconf->pathrun;
+
+  if (!feedfile) feedfile= sitename;
+  if (!feedfile[0]) badusage("feed filename, if specified, must be nonempty");
+  if (path_ends_slash(feedfile))
+    feedfile= xasprintf("%s%s", feedfile, sitename);
+  if (feedfile[0] != '/')
+    feedfile= xasprintf("%s/%s", innconf->pathoutgoing, feedfile);
+
+  if (!path_cli) {
+    path_cli_dir= "innduct";
+  } else if (!path_cli[0] || !strcmp(path_cli,"none")) {
+    path_cli= 0; /* ok, don't then */
+  } else if (path_ends_slash(path_cli)) {
+    path_cli_dir= xasprintf("%.*s", strlen(path_cli)-1, path_cli);
+  }
+  if (path_cli_dir)
+    path_cli= xasprintf("%s/%s", path_cli_dir, sitename);
 
   if (max_queue_per_ipf<0)
     max_queue_per_ipf= max_queue_per_conn * 2;
@@ -3668,6 +3804,14 @@ int main(int argc, char **argv) {
     if (strchr(feedfile, c))
       badusage("feed filename may not contain metacharacter %c",c);
 
+  int i;
+  lowvol_perperiod= xcalloc(sizeof(*lowvol_perperiod), lowvol_periods);
+  for (i=0; i<lowvol_periods; i++) {
+    lowvol_perperiod[i]= lowvol_thresh;
+    lowvol_total += lowvol_thresh;
+  }
+  lowvol_total -= lowvol_thresh;
+
   /* set things up */
 
   path_lock=        xasprintf("%s_lock",      feedfile);
@@ -3677,20 +3821,27 @@ int main(int argc, char **argv) {
   globpat_backlog=  xasprintf("%s_backlog*",  feedfile);
 
   oop_source_sys *sysloop= oop_sys_new();
-  if (!sysloop) sysdie("could not create liboop event loop");
+  if (!sysloop) syscrash("could not create liboop event loop");
   loop= (oop_source*)sysloop;
 
   LIST_INIT(conns);
 
-  if (become_daemon) {
+  if (interactive < 1) {
     int i;
     for (i=3; i<255; i++)
       /* do this now before we open syslog, etc. */
       close(i);
+  }
+
+  logv_prefix= xasprintf("%s| ", sitename);
+  if (interactive < 2) {
     openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
+    logv_use_syslog= 1;
+  }
 
+  if (interactive < 1) {
     int null= open("/dev/null",O_RDWR);
-    if (null<0) sysfatal("failed to open /dev/null");
+    if (null<0) sysdie("failed to open /dev/null");
     dup2(null,0);
     dup2(null,1);
     dup2(null,2);
@@ -3700,14 +3851,17 @@ int main(int argc, char **argv) {
     if (child1) _exit(0);
 
     pid_t sid= setsid();
-    if (sid == -1) sysfatal("setsid failed");
+    if (sid == -1) sysdie("setsid failed");
 
     pid_t child2= xfork("daemonise second fork");
     if (child2) _exit(0);
   }
 
   self_pid= getpid();
-  if (self_pid==-1) sysdie("getpid");
+  if (self_pid==-1) syscrash("getpid");
+
+  r= chdir(path_run);
+  if (r) sysdie("could not chdir to pathrun %s", path_run);
 
   statemc_lock();
 
@@ -3719,7 +3873,7 @@ int main(int argc, char **argv) {
   r= SMsetup(SM_PREOPEN, &val); if (!r) warn("SMsetup SM_PREOPEN failed");
   r= SMinit(); if (!r) die("storage manager initialisation (SMinit) failed");
 
-  if (!become_daemon)
+  if (interactive >= 2)
     cli_stdio();
 
   cli_init();
@@ -3743,5 +3897,5 @@ int main(int argc, char **argv) {
 
   void *run= oop_sys_run(sysloop);
   assert(run == OOP_ERROR);
-  sysdie("event loop failed");
+  syscrash("event loop failed");
 }