chiark / gitweb /
WIP, before change sm timeout machinery to count down and general counter
[innduct.git] / backends / innduct.c
index 51b423303fb4023f3008554e64db0a6965d2afb1..54e61969863931b532961eb1822e5dd7895b1412 100644 (file)
@@ -1,6 +1,19 @@
 /*
+ * Newsfeeds file entries should look like this:
+ *     host.name.of.site[/exclude,exclude,...]\
+ *             :pattern,pattern...[/distribution,distribution...]\
+ *             :Tf,Wnm
+ *             :
+ * or
+ *     sitename[/exclude,exclude,...]\
+ *             :pattern,pattern...[/distribution,distribution...]\
+ *             :Tf,Wnm
+ *             :host.name.of.site
+ *
  * Four files full of
- *    token article
+ *    token messageid
+ * or might be blanked out
+ *    <spc><spc><spc><spc>....
  *
  *   site.name_duct.lock       lock preventing multiple ducts
  *                                holder of this lock is "duct"
@@ -16,7 +29,8 @@
  *                                created, written, used by duct
  *   site.name_backlog.lock    lock taken out by innxmit wrapper
  *                                holder and its child are "xmit"
- *   site.name_backlog_<inum>  431'd articles, ready for innxmit
+ *   site.name_backlog_<date>.<inum>
+ *                             431'd articles, ready for innxmit
  *                                created (link/mv) by duct
  *                                read by xmit
  *                                unlinked by xmit
  *
  */
 
+
+/*----- general definitions, probably best not changed -----*/
+
 #define PERIOD_SECONDS 60
 
-static char *feedfile;
+#define CONNCHILD_ESTATUS_STREAM   4
+#define CONNCHILD_ESTATUS_NOSTREAM 5
+
+#define INNDCOMMCHILD_ESTATUS_FAIL     6
+#define INNDCOMMCHILD_ESTATUS_NONESUCH 7
+
+
+/*----- configuration options -----*/
+
+static char *feedname, *feedfile;
 static int max_connections, max_queue_per_conn;
 static int connection_setup_timeout, port, try_stream;
+static int inndcomm_flush_timeout;
 static const char *remote_host;
 
+static double accept_proportion;
+static double nocheck_thresh= 0.95;
+static double nocheck_decay= 1-1/100;
+static int nocheck, nocheck_reported;
+
+
+/*----- doubly linked lists -----*/
+
 #define ISNODE(T)    T *next, *back;
 #define LIST(T)      struct { T *head, *tail, *tailpred; int count; }
 
@@ -146,21 +181,34 @@ static const char *remote_host;
 #define LIST_INSERT(l,n,pred) \
  (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
 
-struct Article {
-  char *mid;
-  int midlen;
-  int checked, sentbody;
-  fd and offset for blanking token or mid;
-};
 
-#define CONNIOVS 128
+/*----- statistics -----*/
+
+#define RESULT_COUNTS                          \
+  RC(offered)                                  \
+  RC(sent)                                     \
+  RC(unwanted)                                 \
+  RC(accepted)                                 \
+  RC(rejected)                                 \
+  RC(deferred)
 
-#define CN "<%d> "
+typedef enum {
+#define RC_INDEX(x) RCI_##x
+  RESULT_COUNTS
+  RCI_max
+} ResultCountIndex;
 
-typedef struct Conn Conn;
+typedef struct {
+  int articles[2 /* checked */][RCI_max];
+} Counts;
+
+
+/*----- transmission buffers -----*/
+
+#define CONNIOVS 128
 
 typedef enum {
-  Malloc, Const, Artdata;
+  xk_Malloc, xk_Const, xk_Artdata;
 } XmitKind;
 
 typedef struct {
@@ -171,6 +219,45 @@ typedef struct {
   } info;
 } XmitDetails;
 
+
+/*----- core operational data structure types -----*/
+
+struct Article {
+  int midlen;
+  int checked, sentbody;
+  InputFile *ipf;
+  TOKEN token;
+  off_t offset;
+  int blanklen;
+  char messageid[1];
+};
+
+typedef struct {
+  /* This is an instance of struct oop_readable */
+  struct oop_readable readable; /* first */
+  oop_readable_call *readable_callback;
+  void *readable_callback_user;
+
+  int fd;
+  const char *path; /* ptr copy of path_<foo> or feedfile */
+  struct Filemon_Perfile *filemon;
+
+  oop_read *rd;
+  long inprogress; /* no. of articles read but not processed */
+  off_t offset;
+} InputFile;
+
+typedef enum {
+  sm_WAITING,
+  sm_NORMAL,
+  sm_FLUSHING,
+  sm_FLUSHFAIL,
+  sm_SEPARATED1,
+  sm_SEPARATED2, /* must follow SEPARATED2 - see feedfile_eof */
+  sm_DROPPING1,
+  sm_DROPPING2, /* must follow DROPPING1 - see feedfile_eof */
+} StateMachineState;
+
 struct Conn {
   ISNODE(Conn);
   int fd, max_queue, stream;
@@ -181,26 +268,52 @@ struct Conn {
   int xmitu;
 };
 
-static int filemon_init(void);
-static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
-static void filemon_callback(void);
-
 
-#define CHILD_ESTATUS_STREAM   4
-#define CHILD_ESTATUS_NOSTREAM 5
+/*----- operational variables -----*/
 
 static int since_connect_attempt;
 static int nconns;
 static LIST(Conn) idle, working, full;
-
 static LIST(Article) *queue;
 
+static char *path_ductlock, *path_duct, *path_ductdefer;
+
+static StateMachineState sms;
+static FILE *defer;
+static InputFile *main_input_file, *old_input_file;
+static int waiting_periods_sofar;
+
+
+/*----- function predeclarations -----*/
+
+static void conn_check_work(Conn *conn);
+
+static int filemon_init(void);
+static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
+static void filemon_callback(void);
+
+
+/*========== utility functions etc. ==========*/
+
 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
 
-/*========== making new connections ==========*/
+static pid_t xfork(const char *what) {
+  pid_t child;
 
-static int connecting_sockets[2]= {-1,-1};
-static pid_t connecting_child;
+  child= fork();
+  if (child==-1) sysdie("cannot fork for %s",what);
+  if (!child) postfork(what);
+  return child;
+}
+
+static void on_fd_read_except(int fd, oop_call_fd callback) {
+  loop->on_fd(loop, fd, OOP_READ,      callback, 0);
+  loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
+}
+static void cancel_fd_read_except(int fd) {
+  loop->cancel_fd(loop, fd, OOP_READ);
+  loop->cancel_fd(loop, fd, OOP_EXCEPTION);
+}
 
 static void report_child_status(const char *what, int status) {
   if (WIFEXITED(status)) {
@@ -221,27 +334,38 @@ static void report_child_status(const char *what, int status) {
   }
 }
 
+static int xwaitpid(pid_t *pid, const char *what) {
+  int status;
+
+  r= kill(*pid, SIGKILL);
+  if (r) sysdie("cannot kill %s child", what);
+
+  pid_t got= waitpid(*pid, &status, WNOHANG);
+  if (got==-1) sysdie("cannot reap %s child", what);
+
+  *pid= 0;
+
+  return status;
+}
+
+/*========== making new connections ==========*/
+
+static int connecting_sockets[2]= {-1,-1};
+static pid_t connecting_child;
+
 static void connect_attempt_discard(void) {
-  if (connecting_sockets[0]) {
-    cancel_fd(loop, connecting_sockets[0], OOP_READ);
-    cancel_fd(loop, connecting_sockets[0], OOP_EXCEPTION);
-  }
+  if (connecting_sockets[0])
+    cancel_fd(connecting_sockets[0]);
+
   perhaps_close(&connecting_sockets[0]);
   perhaps_close(&connecting_sockets[1]);
 
   if (connecting_child) {
-    int status;
-    r= kill(connecting_child, SIGKILL);
-    if (r) sysdie("cannot kill connect child");
-
-    pid_t got= waitpid(connecting_child, &status, WNOHANG);
-    if (got==-1) sysdie("cannot reap connect child");
+    int status= xwaitpid(&connecting_child, "connect");
 
     if (!(WIFEXITED(status) ||
-         (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL))) {
-      report_child_status("connect"
-    }
-    connecting_child= 0;
+         (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
+      report_child_status("connect", status);
   }
 }
 
@@ -269,8 +393,8 @@ static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
       connecting_child= 0;
       if (WIFEXITED(status) &&
          (WEXITSTATUS(status) != 0
-          WEXITSTATUS(status) != CHILD_ESTATUS_STREAM &&
-          WEXITSTATUS(status) != CHILD_ESTATUS_NOSTREAM)) {
+          WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
+          WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
        /* child already reported the problem */
       } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
        warn("connect: connection attempt timed out");
@@ -312,8 +436,8 @@ static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
   if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
   int es= WEXITSTATUS(status);
   switch (es) {
-  case CHILD_ESTATUS_STREAM:    conn->stream= 1;   break;
-  case CHILD_ESTATUS_NOSTREAM:  conn->stream= 0;   break;
+  case CONNCHILD_ESTATUS_STREAM:    conn->stream= 1;   break;
+  case CONNCHILD_ESTATUS_NOSTREAM:  conn->stream= 0;   break;
   default:
     die("connect: child gave unexpected exit status %d", es);
   }
@@ -345,16 +469,12 @@ static void connect_start() {
   r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
   if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
 
-  connecting_child= fork();
-  if (connecting_child==-1) { syswarn("connect: cannot fork"); goto x; }
+  connecting_child= xfork("connection");
 
   if (!connecting_child) {
     FILE *cn_from, *cn_to;
     char buf[NNTP_STRLEN+100];
-    int exitstatus= CHILD_ESTATUS_NOSTREAM;
-
-    put sigpipe back;
-    close unwanted fds;
+    int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
 
     r= close(connecting_sockets[0]);
     if (r) sysdie("connect: close parent socket in child");
@@ -398,7 +518,7 @@ static void connect_start() {
       }
       switch (rcode) {
       case 203:
-       exitstatus= CHILD_ESTATUS_STREAM;
+       exitstatus= CONNCHILD_ESTATUS_STREAM;
        break;
       case 480:
       case 500:
@@ -429,17 +549,15 @@ static void connect_start() {
   r= close(connecting_sockets[1]);  connecting_sockets[1]= 0;
   if (r) sysdie("connect: close child socket in parent");
 
-  loop->on_fd(loop, connecting_sockets[0], OOP_READ,      connchild_event, 0);
-  loop->on_fd(loop, connecting_sockets[0], OOP_EXCEPTION, connchild_event, 0);
+  on_fd_read_except(connecting_sockets[0], connchild_event);
   return OOP_CONTINUE;
 
  x:
   connect_attempt_discard();
 }
 
-/*========== overall control of article flow ==========*/
 
-static void conn_check_work(Conn *conn);
+/*========== overall control of article flow ==========*/
 
 static void check_master_queue(void) {
   try reading current feed file;
@@ -521,8 +639,38 @@ static void conn_check_work(Conn *conn)  {
   }
 }
 
+
 /*========== article transmission ==========*/
 
+static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
+                  XmitKind kind) { /* caller must then fill in details */
+  struct iovec *v= &conn->xmit[conn->xmitu];
+  XmitDetails *d= &conn->xmitd[conn->xmitu++];
+  v->iov_base= data;
+  v->iov_len= len;
+  d->kind= kind;
+  return d;
+}
+
+static void xmit_noalloc(Conn *conn, const char *data, int len) {
+  xmit_core(conn,data,len, xk_Const);
+}
+#define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
+
+static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
+  XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
+  d->info.sm_art= ah;
+}
+
+static void xmit_free(XmitDetails *d) {
+  switch (d->kind) {
+  case xk_Malloc:  free(d->info.malloc_tofree);   break;
+  case xk_Artdata: SMfreearticle(d->info.sm_art); break;
+  case xk_Const:                                  break;
+  default: abort();
+  }
+}
+
 static void *conn_write_some_xmits(Conn *conn) {
   /* return values:
    *      0:            nothing more to write, no need to call us again
@@ -537,8 +685,7 @@ static void *conn_write_some_xmits(Conn *conn) {
     ssize_t rs= writev(conn->fd, conn->xmit, count);
     if (rs < 0) {
       if (errno == EAGAIN) return OOP_CONTINUE;
-      syswarn(CN "write failed", conn->fd);
-      conn_failed(conn);
+      connfail(conn, "write failed: %s", strerror(errno));
       return OOP_HALT;
     }
     assert(rs > 0);
@@ -569,29 +716,32 @@ static void conn_make_some_xmits(Conn *conn) {
     Article *art= LIST_REMHEAD(queue);
     if (!art) break;
 
-    if (art->checked || conn->nocheck) {
+    if (art->checked || (conn->stream && nocheck)) {
       /* actually send it */
 
-      ARTHANDLE *artdata= SMretrieve(somehow);
+      ARTHANDLE *artdata= SMretrieve();
 
       if (conn->stream) {
        if (artdata) {
          XMIT_LITERAL("TAKETHIS ");
-         xmit_noalloc(art->mid, art->midlen);
+         xmit_noalloc(conn, art->mid, art->midlen);
          XMIT_LITERAL("\r\n");
-         xmit_artbody(artdata);
+         xmit_artbody(conn, artdata);
        }
       } else {
        /* we got 235 from IHAVE */
        if (artdata) {
-         xmit_artbody(artdata);
+         xmit_artbody(conn, artdata);
        } else {
          XMIT_LITERAL(".\r\n");
        }
       }
+
       art->sent= 1;
       LIST_ADDTAIL(conn->sent, art);
 
+      counts[art->checked].sent++;
+
     } else {
       /* check it */
 
@@ -603,11 +753,13 @@ static void conn_make_some_xmits(Conn *conn) {
       XMIT_LITERAL("\r\n");
 
       LIST_ADDTAIL(conn->sent, art);
+      counts[art->checked].offered++;
     }
   }
 }
 
-/*========== responses from peer ==========*/
+
+/*========== handling responses from peer ==========*/
 
 static const oop_rd_style peer_rd_style= {
   OOP_RD_DELIM_STRIP, '\n',
@@ -615,15 +767,111 @@ static const oop_rd_style peer_rd_style= {
   OOP_RD_SHORTREC_FORBID
 };
 
+static Article *article_reply_check(Connection *conn, const char *response,
+                                   int code_indicates_streaming,
+                                   const char *sanitised_response) {
+  Article *art= LIST_REMHEAD(conn->sent);
+
+  if (!art) {
+    connfail(conn,
+            "peer gave unexpected response when no commands outstanding: %s",
+            sanitised_response);
+    return 0;
+  }
+
+  if (code_indicates_streaming) {
+    assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
+    if (!conn->stream) {
+      connfail("peer gave streaming response code "
+              " to IHAVE or subsequent body: %s", sanitised_response);
+      return 0;
+    }
+    const char *got_mid= response+4;
+    int got_midlen= strcspn(got_mid, " \n\r");
+    if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
+      connfail("peer gave streaming response with syntactically invalid"
+              " messageid: %s", sanitised_response);
+      return 0;
+    }
+    if (got_midlen != art->midlen ||
+       memcmp(got_mid, art->messageid, got_midlen)) {
+      connfail("peer gave streaming response code to wrong article -"
+              " probable synchronisation problem; we offered: %s;"
+              " peer said: %s",
+              art->messageid, sanitised_response);
+      return 0;
+    }
+  } else {
+    if (conn->stream) {
+      connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
+              sanitised_response);
+      return 0;
+    }
+  }
+
+  return art;
+}
+
+static void update_nocheck(int accepted) {
+  accept_proportion *= accept_decay;
+  accept_proportion += accepted;
+  nocheck= accept_proportion >= nocheck_thresh;
+  if (nocheck && !nocheck_reported) {
+    notice("entering nocheck mode for the first time");
+    nocheck_reported= 1;
+  }
+}
+
+static void article_done(Connection *conn, Article *art, int whichcount) {
+  *count++;
+  counts.articles[art->checked][whichcount]++;
+  if (whichcount == RC_accepted) update_nocheck(1);
+  else if (whichcount == RC_unwanted) update_nocheck(0);
+
+  InputFile *ipf= art->ipf;
+  while (art->blanklen) {
+    static const char spaces[]=
+      "                                                                "
+      "                                                                "
+      "                                                                "
+      "                                                                ";
+    int w= art->blanklen;  if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
+    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, art->offset, ipf->path);
+    }
+    assert(r>=0 && r<=w);
+    art->blanklen -= w;
+    art->offset += w;
+  }
+
+  ipf->inprogress--;
+  assert(ipf->inprogress >= 0);
+
+  if (!ipf->inprogress)
+    loop->on_time(loop, OOP_TIME_NOW, statemc_check_oldinput_done, 0);
+
+  free(art);
+}
+
+static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
+                        const char *errmsg, int errnoval,
+                        const char *data, size_t recsz, void *conn_v) {
+  Conn *conn= conn_v;
+  connfail(conn, "error receiving from peer: %s", errmsg);
+  return OOP_CONTINUE;
+}
+
 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
                        const char *errmsg, int errnoval,
                        const char *data, size_t recsz, void *conn_v) {
   Conn *conn= conn_v;
 
   if (ev == OOP_RD_EOF) {
-    warn("unexpected EOF from peer");
-    conn_failed(conn);
-    return;
+    connfail(conn, "unexpected EOF from peer");
+    return OOP_CONTINUE;
   }
   assert(ev == OOP_RD_OK);
 
@@ -642,64 +890,178 @@ static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
       sprintf(q,"\\x%02x",c);
       q += 4;
     }
-    warn("badly formatted response from peer: %s", sanibuf);
-    conn_failed(conn);
-    return;
+    connfail(conn, "badly formatted response from peer: %s", sanibuf);
+    return OOP_CONTINUE;
   }
 
   if (conn->quitting) {
     if (code!=205) {
-      warn("peer gave failure response to QUIT: %s", sani);
-      conn_failed(conn);
-      return;
+      connfail(conn, "peer gave failure response to QUIT: %s", sani);
+      return OOP_CONTINUE;
     }
     conn close ok;
     return;
   }
 
+  Article *art;
+
+#define GET_ARTICLE                                                        \
+  art= article_reply_check(conn, data, code_streaming, sani);              \
+  if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
+
+#define ARTICLE_DEALTWITH(streaming,how)                       \
+  code_streaming= (streaming)                                  \
+  GET_ARTICLE;                                                 \
+  article_done(conn, art, RC_##how);  break;
+
+#define PEERBADMSG(m) connfail(conn, m ": %s", sani);  return OOP_CONTINUE
+
+  int code_streaming= 0;
+
   switch (code) {
-  case 438: /* CHECK says they have it */
-  case 435: /* IHAVE says they have it */
-    ARTICLE_DEALTWITH(1,unwanted);
-    break;
+
+  case 400: PEERBADMSG("peer stopped accepting articles");
+  case 503: PEERBADMSG("peer timed us out");
+  default:  PEERBADMSG("peer sent unexpected message");
+
+  case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
+  case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
+
+  case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
+  case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
+
+  case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
+  case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
 
   case 238: /* CHECK says send it */
+    code_streaming= 1;
   case 335: /* IHAVE says send it */
+    GET_ARTICLE;
     count_checkedwanted++;
-    Article *art= LIST_REMHEAD(conn->sent);
-    art->checked= 1;
     LIST_ADDTAIL(conn->queue);
-    break;
-
-  case 235: /* IHAVE says thanks */
-  case 239: /* TAKETHIS says thanks */
-    ARTICLE_DEALTWITH(1,accepted);
-    break;
-
-  case 439: /* TAKETHIS says rejected */
-  case 437: /* IHAVE says rejected */
-    ARTICLE_DEALTWITH(1,rejected);
+    if (art->checked) {
+      connfail("peer gave %d response to article body: %s",code, sani);
+      return OOP_CONTINUE;
+    }
+    art->checked= 1;
     break;
 
   case 431: /* CHECK or TAKETHIS says try later */
+    code_streaming= 1;
   case 436: /* IHAVE says try later */
-    ARTICLE_DEALTWITH(0,deferred);
+    GET_ARTICLE;
+    if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
+       || fflush(defer))
+      sysdie("write to defer file %s",path_ductdefer);
+    article_done(conn, art, RC_deferred);
     break;
 
-  case 400: warn("peer has stopped accepting articles: %s", sani); goto failed;
-  case 503: warn("peer timed us out: %s", sani);                   goto failed;
-  default:  warn("peer sent unexpected message: %s", sani);
-  failed:
-    conn_failed(conn);
-    return OOP_CONTINUE;;
   }
 
+  check_check_work(conn);
   return OOP_CONTINUE;
 }
 
-/*========== monitoring of input file ==========*/
 
-/*---------- tailing input file ----------*/
+/*========== monitoring of input files ==========*/
+
+static void feedfile_eof(InputFile *ipf) {
+  assert(ipf != main_input_file); /* promised by tailing_try_read */
+  assert(ipf == old_input_file);
+  assert(sms==sm_SEPARATED1 || sms==sm_DROPPING1);
+  sms++;
+  inputfile_tailing_stop(ipf);
+  if (main_input_file)
+    inputfile_tailing_start(main_input_file);
+}
+
+static InputFile *open_input_file(const char *path) {
+  int fd= open(path, O_RDONLY);
+  if (fd<0) {
+    if (errno==ENOENT) return 0;
+    sysdie("unable to open input file %s", path);
+  }
+
+  InputFile *ipf= xmalloc(sizeof(InputFile));
+  memset(ipf,0,sizeof(*ipf));
+
+  ipf->readable.on_readable= tailing_on_readable;
+  ipf->readable.on_cancel=   tailing_on_cancel;
+  ipf->readable.try_read=    tailing_try_read;
+
+  ipf->fd= fd;
+  ipf->path= path;
+
+  return ipf;
+}
+
+static void close_input_file(InputFile *ipf) {
+  assert(!ipf->readable_callback); /* must have had ->on_cancel */
+  assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
+  assert(!ipf->rd); /* must have had inputfile_tailing_stop */
+  assert(!ipf->inprogress); /* no dangling pointers pointing here */
+
+  if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
+  free(ipf);
+}
+
+
+/*---------- dealing with articles read in the input file ----------*/
+
+typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
+                                  oop_rd_event ev, const char *errmsg,
+                                  int errnoval,
+                                  const char *data, size_t recsz,
+                                  void *ipf_v) {
+  InputFile *ipf= ipf_v;
+  Article *art;
+  char tokentextbuf[sizeof(TOKEN)*2+3];
+
+  if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
+
+  if (data[0] && data[0]!=' ') {
+    char *space= strchr(data,' ');
+    int tokenlen= space-data;
+    int midlen= (int)recsz-tokenlen-1;
+    if (midlen < 0) goto bad_data;
+
+    if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
+    memcpy(tokentextbuf, data, tokenlen);
+    tokentextbuf[tokenlen]= 0;
+    if (!IsToken(tokentextbuf)) goto bad_data;
+
+    art= xmalloc(sizeof(*art) - 1 + midlen + 1);
+    art->offset= ipf->offset;
+    art->blanklen= recsz;
+    art->midlen= midlen;
+    art->checked= art->sentbody= 0;
+    art->ipf= ipf;  ipf->inprogress++;
+    art->token= TextToToken(tokentextbuf);
+    strcpy(art->messageid, space+1);
+    LIST_ADDTAIL(queue, art);
+  }
+  ipf->offset += recsz + 1;
+
+  if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
+    notice("starting flush (%lu >= %lu)",
+          (unsigned long)ipf->offset, (unsigned long)flush_threshold);
+
+    int r= link(feedfile, duct_path);
+    if (r) sysdie("link feedfile %s to ductfile %s", feedfile, dut_path);
+    /* => Hardlinked */
+
+    r= unlink(feedfile);
+    if (r) sysdie("unlink old feedfile link %s", feedfile);
+    /* => Moved */
+
+    spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
+  }
+
+  check_master_queue();
+}
+
+
+/*========== tailing input file ==========*/
 
 static void filemon_start(InputFile *ipf) {
   assert(!ipf->filemon);
@@ -708,7 +1070,7 @@ static void filemon_start(InputFile *ipf) {
   memset(ipf->filemon, 0, sizeof(*ipf->filemon));
   filemon_method_startfile(ipf, ipf->filemon);
 }
+
 static void filemon_stop(InputFile *ipf) {
   if (!ipf->filemon) return;
   filemon_method_stopfile(ipf, ipf->filemon);
@@ -719,7 +1081,7 @@ static void filemon_stop(InputFile *ipf) {
 static void filemon_callback(InputFile *ipf) {
   ipf->readable_callback(ipf->readable_callback_user);
 }
+
 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
                                     void *user) {
   InputFile *ipf= user;
@@ -731,6 +1093,7 @@ static void on_cancel(struct oop_readable *rable) {
 
   if (ipf->filemon) filemon_stopfile(ipf);
   loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
+  ipf->readable_callback= 0;
 }
 
 static int tailing_on_readable(struct oop_readable *rable,
@@ -751,12 +1114,18 @@ static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
   InputFile *ipf= (void*)rable;
   for (;;) {
     ssize_t r= read(ipf->fd, buffer, length);
-    if (!r && ipf==main_input_file) { errno=EAGAIN; return -1; }
-    if (r==-1 && errno==EINTR) continue;
+    if (r==-1) {
+      if (errno==EINTR) continue;
+      return r;
+    }
+    if (!r) {
+      if (ipf==main_input_file) { errno=EAGAIN; return -1; }
+      assert(sms==sm_SEPARATED1 || sms==sm_DROPPING1);
+    }
     return r;
   }
 }
+
 /*---------- filemon implemented with inotify ----------*/
 
 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
@@ -850,7 +1219,7 @@ static const oop_rd_style feedfile_rdstyle= {
   OOP_RD_NUL_FORBID,
   OOP_RD_SHORTREC_EOF,
 };
+
 static void inputfile_tailing_start(InputFile *ipf) {
   assert(!ipf->fd);
   ipf->readable->on_readable= tailing_on_readable;
@@ -877,11 +1246,12 @@ static void inputfile_tailing_stop(InputFile *ipf) {
   assert(!ipf->filemon); /* we shouldn't be monitoring it now */
 }
 
+
 /*========== interaction with innd ==========*/
 
 /* See official state diagram at top of file.  We implement
  * this as follows:
- *
+
           ================
            WAITING
           [Nothing/Noduct]
@@ -891,13 +1261,13 @@ static void inputfile_tailing_stop(InputFile *ipf) {
                |     TIMEOUT
                |`--------------------------.
                |                           | install defer as backlog
-     ,--------->|                           | exit
-     |          | OPEN F SUCCEEDS           V
+                | OPEN F SUCCEEDS           | exit
+     ,--------->|                           V
      |          V                         =========
      |     ========                        (ESRCH)
      |      NORMAL                        [Dropped]
      |     [Normal]                       =========
-     |      read F
+     |      main F tail
      |     ========
      |          |
      |          | F IS SO BIG WE SHOULD FLUSH
@@ -914,73 +1284,132 @@ static void inputfile_tailing_stop(InputFile *ipf) {
      |     ==========                                                |
      |      FLUSHING                                                 |
      |     [Flushing]                                                |
-     |      read D                                                   |
+     |      main D tail                                              |
      |     ==========                                                |
      |          |                                                    |
      |          |   INNDCOMM FLUSH FAILS                             ^
-     |          |`----------------------->--------.                  |
-     |          |                                 |                  |
-     |          |   NO SUCH SITE                  V                  |
-     ^          |`----------------.            =========             |
-     |          |                 |            FLUSHFAIL             |
-     |          |                 V            [Moved]               |
-     |          |            ==========        read D                |
-     |          |             DROPPING         =========             |
-     |          |            [Dropping]           |                  |
-     |          |             read D              | TIME TO RETRY    |
-     |          |            ==========           `------------------'
-     |          | FLUSH OK        |
-     |          | open F          | AT EOF OF D AND ALL PROCESSED
-     |          V                 | install defer as backlog
-     |     ===========            | unlink D
-     |      SEPARATED             | exit
-     |     [Separated]            V
-     |      read D            ==========
-     |     ===========         (ESRCH)
-     |          |             [Droppped]
-     |          |             ==========
-     |          V
-     |          | AT EOF OF D
-     ^          |
-     |     ===========
-     |      FINISHING
-     |     [Finishing]
-     |      read F
-     |      write D
-     |     ===========
-     |          |
-     |          | ALL D PROCESSED
-     |          | install defer as backlog
-     |          | start new defer
-     ^          V unlink D
-     |          | close D
-     |          |
-     `----------'
-
- *
+     |          |`----------------------->----------.                |
+     |          |                                   |                |
+     |          |   NO SUCH SITE                    V                |
+     ^          |`--------------->----.          ===========         |
+     |          |                      \         FLUSHFAIL           |
+     |          |                       \        [Moved]             |
+     |          |                        \       main D tail         |
+     |          |                         \      ===========         |
+     |          |                          \        |                |
+     |          |                           \       | TIME TO RETRY  |
+     |          |                            \      `----------------'
+     |          | FLUSH OK                    \
+     |          | open F                       \
+     |          V                               V
+     |     =============                     ============
+     |      SEPARATED1                        DROPPING1
+     |     [Separated]                       [Dropping]
+     |      main F idle                       main none
+     |      old  D tail                       old  D tail
+     |     =============                     ============
+     |          |                                 |
+     ^          | EOF ON D                        | EOF ON D
+     |          V                                 V
+     |     =============                     ============
+     |      SEPARATED2                        DROPPING2
+     |     [Finishing]                       [Dropping]
+     |      main F tail                              main none
+     |      old  D idle                       old  D idle
+     |     =============                            ============
+     |          |                               |
+     |          | ALL D PROCESSED                | ALL D PROCESSED
+     |          V install defer as backlog       V install defer as backlog
+     ^          | close D                        | close D
+     |          | unlink D                       | unlink D
+     |          | start new defer                | exit
+     |          |                                V
+     `----------'                            ==========
+                                              (ESRCH)
+                                             [Droppped]
+                                             ==========
  */
 
-static char *path_ductlock, *path_duct, *path_ductdefer;
+static void open_defer(void) {
+  struct stat stab;
 
-typedef struct {
-  /* This is an instance of struct oop_readable */
-  struct oop_readable readable; /* first */
-  oop_readable_call *readable_callback;
-  void *readable_callback_user;
+  assert(!defer);
+  defer= fopen(path_ductdefer, "a+");
+  if (!defer) sysdie("could not open defer file %s", path_ductdefer);
 
-  int fd;
-  const char *path; /* ptr copy of path_<foo> or feedfile */
-  struct Filemon_Perfile *filemon;
+  /* truncate away any half-written records */
 
-  oop_read *rd;
-  long inprogress; /* no. of articles read but not processed */
-} InputFile;
+  r= fstat(fileno(defer), &stab);
+  if (r) sysdie("could not stat newly opened defer file %s", path_ductdefer);
+
+  if (stab.st_size > LONG_MAX)
+    die("defer file %s size is far too large", path_ductdefer);
+
+  if (!stab.st_size)
+    return;
+
+  long orgsize= stab.st_size;
+  long truncto= stab.st_size;
+  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_ductdefer);
+
+    r= getc(defer);
+    if (r==EOF) {
+      if (ferror(defer))
+       sysdie("failed read from defer file %s", path_ductdefer);
+      else
+       die("defer file %s shrank while we were checking it!", path_ductdefer);
+    }
+    if (r=='\n') break;
+    truncto--;
+  }
+
+  if (stab.st_size != truncto) {
+    warn("truncating half-record at end of defer file %s -"
+        " shrinking by %ld bytes from %ld to %ld",
+        path_ductdefer, orgsize - truncto, orgsize, truncto);
+
+    if (fflush(defer)) sysdie("could not flush defer file %s", path_ductdefer);
+    if (ftruncate(fileno(defer), truncto))
+      sysdie("could not truncate defer file %s", path_ductdefer);
+
+  } else {
+    info("continuing existing defer file %s (%ld bytes)",
+        path_ductdefer, orgsize);
+  }
+  if (fseek(defer, truncto, SEEK_SET))
+    sysdie("could not seek to new end of defer file %s", path_ductdefer);
+}
 
 static void statemc_init(void) {
+  struct stat stab;
+
   path_ductlock=  xasprintf("%s_duct.lock",  feedfile);
   path_duct=      xasprintf("%s_duct",       feedfile);
   path_ductdefer= xasprintf("%s_duct.defer", feedfile);
 
+  if (lstat(path_ductdefer, &stab)) {
+    if (errno!=ENOENT) sysdie("could not check defer file %s", path_defer);
+  } else {
+    if (!S_ISREG(stab.st_mode))
+      die("defer file %s not a plain file (mode 0%lo)",
+         path_defer, (unsigned long)stab.st_mode);
+    switch (stab.st_nlink==1) {
+    case 1: /* ok */ break;
+    case 2:
+      if (unlink(path_defer))
+       sysdie("could not unlink stale defer file link %s (presumably"
+              " hardlink to backlog file)", path_defer);
+      break;
+    default:
+      die("defer file %s has unexpected link count %d",
+         path_defer, stab.st_nlink);
+    }
+  }
+  open_defer();
+
   int lockfd= open(path_ductlock, O_CREAT|O_RDWR, 0600);
   if (lockfd<0) sysdie("open lockfile %s", path_ductlock);
 
@@ -994,29 +1423,226 @@ static void statemc_init(void) {
       die("another duct holds the lockfile");
     sysdie("fcntl F_SETLK lockfile %s", path_ductlock);
   }
+
+  InputFile *file_d= open_input_file(path_duct);
+
+  if (file_d) {
+    struct stat stab_f, stab_d;
+
+    r= stat(feedfile, &stab_f);
+    if (r) {
+      if (errno!=ENOENT) sysdie("check feed file %s", feedfile);
+      /* D exists, F ENOENT => Moved */
+      goto found_moved;
+    }
+
+    /* F and D both exist */
+
+    r= fstat(file_d->fd, &stab_d);
+    if (r) sysdie("check duct file %s", ductfile);
+
+    if (stab_d.st_ino == stab_f.st_ino &&
+       stab_d.st_dev == stab_f.st_dev) {
+      /* F==D => Hardlinked*/
+      r= unlink(path_duct);
+      if (r) sysdie("unlink feed file %s during startup", feedfile);
+    found_moved:
+      /* => Moved */
+      startup_set_input_file(file_d);
+      spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
+    } else {
+      /* F!=D => Separated */
+      sms= sm_SEPARATED;
+      startup_set_input_file(file_d);
+    }
+  } else { /*!file_d*/
+    sms= sm_WAITING;
+    statemc_waiting_poll();
+  }
 }
 
 static void statemc_poll(void) {
-  if (tailing_fd>=0) return;
+  if (sms==sm_WAITING) statemc_waiting_poll();
+}
 
-  int d_fd= open(path_duct, O_RDWR);
-  if (d_fd<0)
-    if (errno!=ENOENT) sysdie("open duct file %s", path_duct);
+static void statemc_waiting_poll(void) {
+  InputFile *file_f= open_input_file(feedfile);
+  if (!file_f) {
+    if (waiting_periods_sofar++ > waiting_timeout_periods)
+      die("timed out waiting for innd to create feed file %s", feedfile);
+    return;
+  }
+  startup_set_input_file(file_d);
+  sms= sm_NORMAL;
+}
 
-  int f_fd= open(feedfile, O_RDWR);
-  if (f_fd<0)
-    if (errno!=ENOENT) sysdie("open feed file %s", feedfile);
+static void startup_set_input_file(InputFile *f) {
+  assert(!main_input_file);
+  main_input_file= f;
+  inputfile_tailing_start(f);
+}
 
-  if (d_fd<0) {
-    if (f_fd>=0)
-      start_tailing(f_fd);
-    return;
+static void *statemc_check_oldinput_done(oop_source *lp,
+                                        struct timeval now, void *u) {
+  struct stat stab;
+
+  int done= (sms==sm_SEPARATED2 || sms==sm_DROPPING2)
+         && old_input_file->inprogress;
+  if (!done) return;
+
+  r= fstat(fileno(defer), &stab);
+  if (r) sysdie("check defer file %s", path_defer);
+
+  if (fclose(defer)) sysdie("could not close defer file %s", path_defer);
+  defer= 0;
+
+  char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
+                          (unsigned long)now.tv_sec,
+                          (unsigned long)stab.st_ino);
+  if (link(path_defer, path_backlog))
+    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);
+
+  if (unlink(path_duct))
+    sysdie("could not unlink old duct file %s", path_duct);
+
+  if (sms==sm_DROPPING2) {
+    notice("feed dropped and our work is complete"
+          " (but check for backlog files)");
+    exit(0);
   }
 
+  open_defer();
+
+  close_input_file(old_input_file);
+  old_input_file= 0;
+
+  sms= sm_NORMAL;
+}
 
+/*========== flushing the feed ==========*/
+
+static pid_t inndcomm_child;
+
+static void inndcommfail(const char *what) {
+  syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
+  exit(INNDCOMMCHILD_ESTATUS_FAIL);
+}
+
+static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
+  assert(inndcomm_child);
+  int status= xwaitpid(&inndcomm_child, "inndcomm");
+  loop->cancel_fd(fd);
+  close(fd);
+
+  assert(!old_input_file);
+
+  if (WIFEXITED(status)) {
+    switch (WEXITSTATUS(status)) {
+      
+    case INNDCOMMCHILD_ESTATUS_FAIL:
+      goto failed;
+
+    case INNDCOMMCHILD_ESTATUS_NONESUCH:
+      warn("feed has been dropped by innd, finishing up");
+      old_input_file= main_input_file;
+      main_input_file= 0;
+      sms= sm_DROPPING1;
+      return OOP_CONTINUE;
+
+    case 0:
+      old_input_file= main_input_file;
+      main_input_file= open_input_file(feedfile);
+      if (!main_input_file)
+       die("flush succeeded but feedfile %s does not exist!", feedfile);
+      sms= sm_SEPARATED1;
+      return OOP_CONTINUE;
+
+    default:
+      goto unexpected_exitstatus;
+      
+    }
+  } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
+    warn("flush of %s timed out trying to talk to innd", feedname);
+    goto failed;
+  } else {
+  unexpected_exitstatus:
+    report_child_status("inndcomm child", status);
+  }
+
+ failed:
+  
+
+void spawn_inndcomm_flush(void) {
+  int pipefds[2];
+
+  assert(sms == sm_NORMAL);
+  assert(!inndcomm_child);
+
+  if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
+
+  inndcomm_child= xfork();
+
+  if (!inndcomm_child) {
+    static char flushargv[2]= { feedname, 0 };
+    char *reply;
+
+    close(pipefds[0]);
+
+    alarm(inndcomm_flush_timeout);
+    r= ICCopen();                         if (r)   inndcommfail("connect");
+    r= ICCcommand('f',flushargv,&reply);  if (r<0) inndcommfail("transmit");
+    if (!r) exit(0); /* yay! */
+
+    if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
+    syswarn("innd ctlinnd flush %s failed: innd said %s", feedname, reply);
+    exit(INNDCOMMCHILD_ESTATUS_FAIL);
+  }
+
+  close(pipefds[1]);
+  int sentinel_fd= pipefds[0];
+  on_fd_read_except(sentinel_fd, inndcomm_event);
+
+  sms= sm_FLUSHING;
+}
 
 /*========== main program ==========*/
 
+static void postfork_inputfile(InputFile *ipf) {
+  if (!ipf) return;
+  assert(ipf->fd >= 0);
+  close(ipf->fd);
+  ipf->fd= -1;
+}
+
+static void postfork_conns(Connection *conn) {
+  while (conn) {
+    close(conn->fd);
+    conn= conn->next;
+  }
+}
+
+static void postfork_stdio(FILE *f) {
+  /* we have no stdio streams that are buffered long-term */
+  if (f) fclose(f);
+}
+
+static void postfork(const char *what) {
+  if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
+    sysdie("%s child: failed to reset SIGPIPE");
+
+  postfork_inputfile(main_input_file);
+  postfork_inputfile(old_input_file);
+  postfork_conns(idle.head);
+  postfork_conns(working.head);
+  postfork_conns(full.head);
+  postfork_stdio(defer);
+}
+
+
 #define EVERY(what, interval, body)                                         \
   static const struct timeval what##_timeout = { 5, 0 };                    \
   static void what##_schedule(void);                                        \