chiark / gitweb /
c83a02c0243d3065a6ef1cade828b819d37ead88
[inn-innduct.git] / backends / innduct.c
1 /*
2  * Newsfeeds file entries should look like this:
3  *     host.name.of.site[/exclude,exclude,...]\
4  *             :pattern,pattern...[/distribution,distribution...]\
5  *             :Tf,Wnm
6  *             :
7  * or
8  *     sitename[/exclude,exclude,...]\
9  *             :pattern,pattern...[/distribution,distribution...]\
10  *             :Tf,Wnm
11  *             :host.name.of.site
12  *
13  * Four files full of
14  *    token messageid
15  * or might be blanked out
16  *    <spc><spc><spc><spc>....
17  *
18  *   site.name_duct.lock       lock preventing multiple ducts
19  *                                holder of this lock is "duct"
20  * F site.name                 main feed file
21  *                                opened/created, then written, by innd
22  *                                read by duct
23  *                                unlinked by duct
24  *                                tokens blanked out by duct when processed
25  * D site.name_duct            temporary feed file during flush (or crash)
26  *                                hardlink created by duct
27  *                                unlinked by duct
28  *   site.name_duct.defer      431'd articles, still being written,
29  *                                created, written, used by duct
30  *   site.name_backlog.lock    lock taken out by innxmit wrapper
31  *                                holder and its child are "xmit"
32  *   site.name_backlog_<date>.<inum>
33  *                             431'd articles, ready for innxmit
34  *                                created (link/mv) by duct
35  *                                read by xmit
36  *                                unlinked by xmit
37  *   site.name_backlog_<letters> eg
38  *   site.name_backlog_manual
39  *                             anything the sysadmin likes (eg, feed files
40  *                             from old feeds to be merged into this one)
41  *                                created (link/mv) by admin
42  *                                read by xmit
43  *                                unlinked by xmit
44
45
46    OVERALL STATES:
47
48                                                                 START
49                                                                   |
50                                                              check D, F
51                                                                   |
52                           <--------------------------------------'|
53         Nothing                            F, D both ENOENT       |
54          F: ENOENT                                                |
55          D: ENOENT                                                |
56          duct: not not reading anything                           |
57            |                                                      |
58            |`---------------------.                               |
59            |                      | duct times out waiting for F  |
60            V  innd creates F      | duct exits                    |
61            |                      V                               |
62         Noduct                    GO TO Dropped                   |
63          F: innd writing                                          |
64          D: ENOENT                                                |
65          duct: not running or not reading anything                |
66            |                                                      |
67            |                                                      |
68      ,-->--+                   <---------------------------------'|
69      |     |  duct opens F                         F exists       |
70      |     |                                       D ENOENT       |
71      |     V                                                      |
72      |  Normal                                                    |
73      |   F: innd writing, duct reading                            |
74      |   D: ENOENT                                                |
75      |     |                                                      |
76      |     |  duct decides time to flush                          |
77      |     |  duct makes hardlink                                 |
78      |     |                                                      |
79      |     V                            <------------------------'|
80      |  Hardlinked                                  F==D          |
81      |   F == D: innd writing, duct reading         both exist    |
82      ^     |                                                      |
83      |     |  duct unlinks F                                      |
84      |     V                                                      |
85      |  Moved                               <----+------------<--'|
86      |   F: ENOENT                               |  F ENOENT      |
87      |   D: innd writing, duct reading           |  D exists      |
88      |     |                                     |                |
89      |     |  duct requests flush of feed        |                |
90      |     |   (others can too, harmlessly)      |                |
91      |     V                                     |                |
92      |  Flushing                                 |                |
93      |   F: ENOENT                               |                |
94      |   D: innd flushing, duct reading          |                |
95      |     |                                     |                |
96      |     |   inndcomm flush fails              |                |
97      |     |`-------------------------->---------'                |
98      |     |                                                      |
99      |     |   inndcomm reports no such site                      |
100      |     |`---------------------------------------------------- | -.
101      |     |                                                      |  |
102      |     |  innd finishes writing D, creates F                  |  |
103      |     |  inndcomm reports flush successful                   |  |
104      |     |                                                      |  |
105      |     V                                                      |  |
106      |  Separated                                <----------------'  |
107      |   F: innd writing                            F!=D             /
108      |   D: duct reading                             both exist     /
109      |     |                                                       /
110      |     |  duct gets to the end of D                           /
111      |     |  duct opens F too                                   /
112      |     V                                                    /
113      |  Finishing                                              /
114      |   F: innd writing, duct reading                        |
115      |   D: duct finishing                                    V
116      |     |                                            Dropping
117      |     |  duct finishes processing D                 F: ENOENT
118      |     V  duct unlinks D                             D: duct reading
119      |     |                                                  |
120      `--<--'                                                  | duct finishes
121                                                               |  processing D
122                                                               | duct unlinks D
123                                                               | duct exits
124                                                               V
125                                                         Dropped
126                                                          F: ENOENT
127                                                          D: ENOENT
128                                                          duct not running
129
130    "duct reading" means innduct is reading the file but also
131    overwriting processed tokens.
132
133  *
134  *
135  */
136
137
138 /*----- general definitions, probably best not changed -----*/
139
140 #define PERIOD_SECONDS 60
141
142 #define CONNCHILD_ESTATUS_STREAM   4
143 #define CONNCHILD_ESTATUS_NOSTREAM 5
144
145 #define INNDCOMMCHILD_ESTATUS_FAIL     6
146 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
147
148
149 /*----- configuration options -----*/
150
151 static char *feedname, *feedfile;
152 static int max_connections, max_queue_per_conn;
153 static int connection_setup_timeout, port, try_stream;
154 static int inndcomm_flush_timeout;
155 static const char *remote_host;
156 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
157
158 static double accept_proportion;
159 static double nocheck_thresh= 0.95;
160 static double nocheck_decay= 1-1/100;
161 static int nocheck, nocheck_reported;
162
163
164 /*----- doubly linked lists -----*/
165
166 #define ISNODE(T)    T *next, *back;
167 #define LIST(T)      struct { T *head, *tail, *tailpred; int count; }
168
169 #define NODE(n) ((struct node*)&(n)->head)
170
171 #define LIST_ADDHEAD(l,n)                                               \
172  (list_addhead((struct list*)&(l), NODE((n))), (void)(l).count++)
173 #define LIST_ADDTAIL(l,n)                                               \
174  (list_addtail((struct list*)&(l), NODE((n))), (void)(l).count++)
175
176 #define LIST_REMHEAD(l)                                                   \
177  ((l).count ? ((l).count--, (void*)list_remhead((struct list*)&(l))) : 0)
178 #define LIST_REMTAIL(l)                                                   \
179  ((l).count ? ((l).count--, (void*)list_remtail((struct list*)&(l))) : 0)
180 #define LIST_REMOVE(l,n)                        \
181  (list_remove(NODE((n))), (void)(l).count--)
182 #define LIST_INSERT(l,n,pred) \
183  (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
184
185
186 /*----- statistics -----*/
187
188 #define RESULT_COUNTS                           \
189   RC(offered)                                   \
190   RC(sent)                                      \
191   RC(unwanted)                                  \
192   RC(accepted)                                  \
193   RC(rejected)                                  \
194   RC(deferred)
195
196 typedef enum {
197 #define RC_INDEX(x) RCI_##x
198   RESULT_COUNTS
199   RCI_max
200 } ResultCountIndex;
201
202 typedef struct {
203   int articles[2 /* checked */][RCI_max];
204 } Counts;
205
206
207 /*----- transmission buffers -----*/
208
209 #define CONNIOVS 128
210
211 typedef enum {
212   xk_Malloc, xk_Const, xk_Artdata;
213 } XmitKind;
214
215 typedef struct {
216   XmitKind kind;
217   union {
218     char *malloc_tofree;
219     ARTHANDLE *sm_art;
220   } info;
221 } XmitDetails;
222
223
224 /*----- core operational data structure types -----*/
225
226 struct Article {
227   int midlen;
228   int checked, sentbody;
229   InputFile *ipf;
230   TOKEN token;
231   off_t offset;
232   int blanklen;
233   char messageid[1];
234 };
235
236 typedef struct {
237   /* This is an instance of struct oop_readable */
238   struct oop_readable readable; /* first */
239   oop_readable_call *readable_callback;
240   void *readable_callback_user;
241
242   int fd;
243   const char *path; /* ptr copy of path_<foo> or feedfile */
244   struct Filemon_Perfile *filemon;
245
246   oop_read *rd;
247   long inprogress; /* no. of articles read but not processed */
248   off_t offset;
249 } InputFile;
250
251 typedef enum {
252   sm_WAITING,
253   sm_NORMAL,
254   sm_FLUSHING,
255   sm_FLUSHFAIL,
256   sm_SEPARATED1,
257   sm_SEPARATED2, /* must follow SEPARATED2 - see feedfile_eof */
258   sm_DROPPING1,
259   sm_DROPPING2, /* must follow DROPPING1 - see feedfile_eof */
260 } StateMachineState;
261
262 struct Conn {
263   ISNODE(Conn);
264   int fd, max_queue, stream;
265   LIST(Article) queue; /* not yet told peer, or CHECK said send it */
266   LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
267   struct iovec xmit[CONNIOVS];
268   XmitDetails xmitd[CONNIOVS];
269   int xmitu;
270 };
271
272
273 /*----- operational variables -----*/
274
275 static int since_connect_attempt;
276 static int nconns;
277 static LIST(Conn) idle, working, full;
278 static LIST(Article) *queue;
279
280 static char *path_ductlock, *path_duct, *path_ductdefer;
281
282 static StateMachineState sms;
283 static FILE *defer;
284 static InputFile *main_input_file, *old_input_file;
285 static int sm_period_counter;
286
287
288 /*----- function predeclarations -----*/
289
290 static void conn_check_work(Conn *conn);
291
292 static int filemon_init(void);
293 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
294 static void filemon_callback(void);
295
296
297 /*========== utility functions etc. ==========*/
298
299 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
300
301 static pid_t xfork(const char *what) {
302   pid_t child;
303
304   child= fork();
305   if (child==-1) sysdie("cannot fork for %s",what);
306   if (!child) postfork(what);
307   return child;
308 }
309
310 static void on_fd_read_except(int fd, oop_call_fd callback) {
311   loop->on_fd(loop, fd, OOP_READ,      callback, 0);
312   loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
313 }
314 static void cancel_fd_read_except(int fd) {
315   loop->cancel_fd(loop, fd, OOP_READ);
316   loop->cancel_fd(loop, fd, OOP_EXCEPTION);
317 }
318
319 static void report_child_status(const char *what, int status) {
320   if (WIFEXITED(status)) {
321     int es= WEXITSTATUS(status);
322     if (es)
323       warn("%s: child died with error exit status %d",es);
324   } else if (WIFSIGNALED(status)) {
325     int sig= WTERMSIG(status);
326     const char *sigstr= strsignal(sig);
327     const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
328     if (sigstr)
329       warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
330     else
331       warn("%s: child died due to unknown fatal signal %d%s",
332            what, sig, coredump);
333   } else {
334     warn("%s: child died with unknown wait status %d", status);
335   }
336 }
337
338 static int xwaitpid(pid_t *pid, const char *what) {
339   int status;
340
341   r= kill(*pid, SIGKILL);
342   if (r) sysdie("cannot kill %s child", what);
343
344   pid_t got= waitpid(*pid, &status, WNOHANG);
345   if (got==-1) sysdie("cannot reap %s child", what);
346
347   *pid= 0;
348
349   return status;
350 }
351
352 /*========== making new connections ==========*/
353
354 static int connecting_sockets[2]= {-1,-1};
355 static pid_t connecting_child;
356
357 static void connect_attempt_discard(void) {
358   if (connecting_sockets[0])
359     cancel_fd(connecting_sockets[0]);
360
361   perhaps_close(&connecting_sockets[0]);
362   perhaps_close(&connecting_sockets[1]);
363
364   if (connecting_child) {
365     int status= xwaitpid(&connecting_child, "connect");
366
367     if (!(WIFEXITED(status) ||
368           (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
369       report_child_status("connect", status);
370   }
371 }
372
373 #define PREP_DECL_MSG_CMSG(msg)                 \
374   struct msghdr msg;                            \
375   memset(&msg,0,sizeof(msg));                   \
376   char msg##cbuf[CMSG_SPACE(sizeof(fd))];       \
377   msg.msg_control= msg##cbuf;                   \
378   msg.msg_controllen= sizeof(msg##cbuf);
379
380 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
381   Conn *conn= 0;
382
383   conn= xcalloc(sizeof(*conn));
384
385   DECL_MSG_CMSG(msg);
386   struct cmsghdr *h= 0;
387   ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
388   if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
389   if (!h) {
390     int status;
391     pid_t got= waitpid(connecting_child, &status, WNOHANG);
392     if (got != -1) {
393       assert(got==connecting_child);
394       connecting_child= 0;
395       if (WIFEXITED(status) &&
396           (WEXITSTATUS(status) != 0
397            WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
398            WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
399         /* child already reported the problem */
400       } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
401         warn("connect: connection attempt timed out");
402       } else if (!WIFEXITED(status)) {
403         report_child_status("connect", status);
404         /* that's probably the root cause then */
405       }
406     } else {
407       /* child is still running apparently, report the socket problem */
408       if (rs < 0)
409         syswarn("connect: read from child socket failed");
410       else if (e == OOP_EXCEPTIONN)
411         warn("connect: unexpected exception on child socket");
412       else
413         warn("connect: unexpected EOF on child socket");
414     }
415     goto x;
416   }
417
418 #define CHK(field, val)                                                   \
419   if (h->cmsg_##field != val) {                                           \
420     die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
421     goto x;                                                               \
422   }
423   CHK(level, SOL_SOCKET);
424   CHK(type,  SCM_RIGHTS);
425   CHK(len,   CMSG_LEN(sizeof(conn-b>fd)));
426 #undef CHK
427
428   if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
429
430   memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
431
432   pid_t got= waitpid(connecting_child, &status, 0);
433   if (got==-1) sysdie("connect: real wait for child");
434   assert(got == connecting_child);
435   connecting_child= 0;
436
437   if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
438   int es= WEXITSTATUS(status);
439   switch (es) {
440   case CONNCHILD_ESTATUS_STREAM:    conn->stream= 1;   break;
441   case CONNCHILD_ESTATUS_NOSTREAM:  conn->stream= 0;   break;
442   default:
443     die("connect: child gave unexpected exit status %d", es);
444   }
445
446   set nonblocking;
447
448   /* Phew! */
449   LIST_ADDHEAD(idle, conn);
450   notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
451   connect_attempt_discard();
452   check_master_queue();
453   return 0;
454
455  x:
456   if (conn) {
457     perhaps_close(&conn->fd);
458     free(conn);
459   }
460   connect_attempt_discard();
461 }
462
463 static void connect_start() {
464   assert(!connecting_sockets[0]);
465   assert(!connecting_sockets[1]);
466   assert(!connecting_child);
467
468   notice("starting connection attempt");
469
470   r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
471   if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
472
473   connecting_child= xfork("connection");
474
475   if (!connecting_child) {
476     FILE *cn_from, *cn_to;
477     char buf[NNTP_STRLEN+100];
478     int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
479
480     r= close(connecting_sockets[0]);
481     if (r) sysdie("connect: close parent socket in child");
482
483     alarm(connection_setup_timeout);
484     if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
485       if (buf[0]) {
486         sanitise_inplace(buf);
487         die("connect: rejected: %s", buf);
488       } else {
489         sysdie("connect: connection attempt failed");
490       }
491     }
492     if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
493       sysdie("connect: authentication failed");
494     if (try_stream) {
495       if (fputs("MODE STREAM\r\n", cn_to) ||
496           fflush(cn_to))
497         sysdie("connect: could not send MODE STREAM");
498       buf[sizeof(buf)-1]= 0;
499       if (!fgets(buf, sizeof(buf)-1, cn_from)) {
500         if (ferror(cn_from))
501           sysdie("connect: could not read response to MODE STREAM");
502         else
503           die("connect: connection close in response to MODE STREAM");
504       }
505       int l= strlen(buf);
506       assert(l>=1);
507       if (buf[-1]!='\n') {
508         sanitise_inplace(buf);
509         die("connect: response to MODE STREAM is too long: %.100s...",
510             remote_host, buf);
511       }
512       l--;  if (l>0 && buf[1-]=='\r') l--;
513       buf[l]= 0;
514       char *ep;
515       int rcode= strtoul(buf,&ep,10);
516       if (ep != buf[3]) {
517         sanitise_inplace(buf);
518         die("connect: bad response to MODE STREAM: %.50s", buf);
519       }
520       switch (rcode) {
521       case 203:
522         exitstatus= CONNCHILD_ESTATUS_STREAM;
523         break;
524       case 480:
525       case 500:
526         break;
527       default:
528         sanitise_inplace(buf);
529         warn("connect: unexpected response to MODE STREAM: %.50s", buf);
530         exitstatus= 2;
531         break;
532       }
533     }
534     int fd= fileno(cn_from);
535
536     PREP_DECL_MSG_CMSG(msg);
537     struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
538     cmsg->cmsg_level= SOL_SOCKET;
539     cmsg->cmsg_type=  SCM_RIGHTS;
540     cmsg->cmsg_len=   CMSG_LEN(sizeof(fd));
541     memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
542
543     msg.msg_controllen= cmsg->cmsg_len;
544     r= sendmsg(connecting_sockets[1], &msg, 0);
545     if (r) sysdie("sendmsg failed for new connection");
546
547     _exit(exitstatus);
548   }
549
550   r= close(connecting_sockets[1]);  connecting_sockets[1]= 0;
551   if (r) sysdie("connect: close child socket in parent");
552
553   on_fd_read_except(connecting_sockets[0], connchild_event);
554   return OOP_CONTINUE;
555
556  x:
557   connect_attempt_discard();
558 }
559
560
561 /*========== overall control of article flow ==========*/
562
563 static void check_master_queue(void) {
564   try reading current feed file;
565
566   if (!queue.count)
567     return;
568
569   Conn *last_assigned=0;
570   for (;;) {
571     if (working.head) {
572       conn_assign_one_article(&working, &last_assigned);
573     } else if (idle.head) {
574       conn_assign_one_article(&idle, &last_assigned);
575     } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
576                !connecting_child && !connect_delay) {
577       connect_delay= reconnect_delay_periods;
578       connect_start();
579     } else {
580       break;
581     }
582   }
583   conn_check_work(last_assigned);
584 }
585
586 static void conn_assign_one_article(LIST(Conn) *connlist,
587                                     Conn **last_assigned) {
588   Conn *conn= connlist->head;
589
590   LIST_REMOVE(*connlist, conn);
591   Article *art= LIST_REMHEAD(queue);
592   LIST_ADDTAIL(conn->queue, art);
593   LIST_ADD(*conn_determine_right_list(conn), conn);
594
595   /* This slightly odd arrangement is so that we call conn_check_work
596    * once after filling the queue for a new connection in
597    * check_master_queue, rather than for each article. */
598   if (conn != *last_assigned && *last_assigned)
599     conn_check_work(*last_assigned);
600   *last_assigned= conn;
601 }
602
603 static int conn_total_queued_articles(Conn *conn) {
604   return conn->sent.count + conn->queue.count;
605 }
606
607 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
608   int inqueue= conn_total_queued_articles(conn);
609   assert(inqueue <= max_queue);
610   if (inqueue == 0) return &idle;
611   if (inqueue == conn->max_queue) return &full;
612   return &working;
613 }
614
615 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
616   check_conn_work(u);
617   return OOP_CONTINUE;
618 }
619
620 static void conn_check_work(Conn *conn)  {
621   void *rp= 0;
622   for (;;) {
623     conn_make_some_xmits(conn);
624     if (!conn->xmitu) {
625       loop->cancel_fd(loop, conn->fd, OOP_WRITE);
626       return;
627     }
628
629     void *rp= conn_write_some_xmits(conn);
630     if (rp==OOP_CONTINUE) {
631       loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
632       return;
633     } else if (rp==OOP_HALT) {
634       return;
635     } else if (!rp) {
636       /* transmitted everything */
637     } else {
638       abort();
639     }
640   }
641 }
642
643
644 /*========== article transmission ==========*/
645
646 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
647                   XmitKind kind) { /* caller must then fill in details */
648   struct iovec *v= &conn->xmit[conn->xmitu];
649   XmitDetails *d= &conn->xmitd[conn->xmitu++];
650   v->iov_base= data;
651   v->iov_len= len;
652   d->kind= kind;
653   return d;
654 }
655
656 static void xmit_noalloc(Conn *conn, const char *data, int len) {
657   xmit_core(conn,data,len, xk_Const);
658 }
659 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
660
661 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
662   XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
663   d->info.sm_art= ah;
664 }
665
666 static void xmit_free(XmitDetails *d) {
667   switch (d->kind) {
668   case xk_Malloc:  free(d->info.malloc_tofree);   break;
669   case xk_Artdata: SMfreearticle(d->info.sm_art); break;
670   case xk_Const:                                  break;
671   default: abort();
672   }
673 }
674
675 static void *conn_write_some_xmits(Conn *conn) {
676   /* return values:
677    *      0:            nothing more to write, no need to call us again
678    *      OOP_CONTINUE: more to write but fd not writeable
679    *      OOP_HALT:     disaster, have destroyed conn
680    */
681   for (;;) {
682     int count= conn->xmitu;
683     if (!count) return 0;
684
685     if (count > IOV_MAX) count= IOV_MAX;
686     ssize_t rs= writev(conn->fd, conn->xmit, count);
687     if (rs < 0) {
688       if (errno == EAGAIN) return OOP_CONTINUE;
689       connfail(conn, "write failed: %s", strerror(errno));
690       return OOP_HALT;
691     }
692     assert(rs > 0);
693
694     for (done=0; rs && done<xmitu; done++) {
695       struct iovec *vp= &conn->xmit[done];
696       XmitDetails *dp= &conn->xmitd[done];
697       if (rs > vp->iov_len) {
698         rs -= vp->iov_len;
699         xmit_free(dp);
700       } else {
701         vp->iov_base += rs;
702         vp->iov_len -= rs;
703       }
704     }
705     int newu= conn->xmitu - done;
706     memmove(conn->xmit,  conn->xmit  + done, newu * sizeof(*conn->xmit));
707     memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
708     conn->xmitu= newu;
709   }
710 }
711
712 static void conn_make_some_xmits(Conn *conn) {
713   for (;;) {
714     if (conn->xmitu+5 > CONNIOVS)
715       break;
716
717     Article *art= LIST_REMHEAD(queue);
718     if (!art) break;
719
720     if (art->checked || (conn->stream && nocheck)) {
721       /* actually send it */
722
723       ARTHANDLE *artdata= SMretrieve();
724
725       if (conn->stream) {
726         if (artdata) {
727           XMIT_LITERAL("TAKETHIS ");
728           xmit_noalloc(conn, art->mid, art->midlen);
729           XMIT_LITERAL("\r\n");
730           xmit_artbody(conn, artdata);
731         }
732       } else {
733         /* we got 235 from IHAVE */
734         if (artdata) {
735           xmit_artbody(conn, artdata);
736         } else {
737           XMIT_LITERAL(".\r\n");
738         }
739       }
740
741       art->sent= 1;
742       LIST_ADDTAIL(conn->sent, art);
743
744       counts[art->checked].sent++;
745
746     } else {
747       /* check it */
748
749       if (conn->stream)
750         XMIT_LITERAL("IHAVE ");
751       else
752         XMIT_LITERAL("CHECK ");
753       xmit_noalloc(art->mid, art->midlen);
754       XMIT_LITERAL("\r\n");
755
756       LIST_ADDTAIL(conn->sent, art);
757       counts[art->checked].offered++;
758     }
759   }
760 }
761
762
763 /*========== handling responses from peer ==========*/
764
765 static const oop_rd_style peer_rd_style= {
766   OOP_RD_DELIM_STRIP, '\n',
767   OOP_RD_NUL_FORBID,
768   OOP_RD_SHORTREC_FORBID
769 };
770
771 static Article *article_reply_check(Connection *conn, const char *response,
772                                     int code_indicates_streaming,
773                                     const char *sanitised_response) {
774   Article *art= LIST_REMHEAD(conn->sent);
775
776   if (!art) {
777     connfail(conn,
778              "peer gave unexpected response when no commands outstanding: %s",
779              sanitised_response);
780     return 0;
781   }
782
783   if (code_indicates_streaming) {
784     assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
785     if (!conn->stream) {
786       connfail("peer gave streaming response code "
787                " to IHAVE or subsequent body: %s", sanitised_response);
788       return 0;
789     }
790     const char *got_mid= response+4;
791     int got_midlen= strcspn(got_mid, " \n\r");
792     if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
793       connfail("peer gave streaming response with syntactically invalid"
794                " messageid: %s", sanitised_response);
795       return 0;
796     }
797     if (got_midlen != art->midlen ||
798         memcmp(got_mid, art->messageid, got_midlen)) {
799       connfail("peer gave streaming response code to wrong article -"
800                " probable synchronisation problem; we offered: %s;"
801                " peer said: %s",
802                art->messageid, sanitised_response);
803       return 0;
804     }
805   } else {
806     if (conn->stream) {
807       connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
808                sanitised_response);
809       return 0;
810     }
811   }
812
813   return art;
814 }
815
816 static void update_nocheck(int accepted) {
817   accept_proportion *= accept_decay;
818   accept_proportion += accepted;
819   nocheck= accept_proportion >= nocheck_thresh;
820   if (nocheck && !nocheck_reported) {
821     notice("entering nocheck mode for the first time");
822     nocheck_reported= 1;
823   }
824 }
825
826 static void article_done(Connection *conn, Article *art, int whichcount) {
827   *count++;
828   counts.articles[art->checked][whichcount]++;
829   if (whichcount == RC_accepted) update_nocheck(1);
830   else if (whichcount == RC_unwanted) update_nocheck(0);
831
832   InputFile *ipf= art->ipf;
833   while (art->blanklen) {
834     static const char spaces[]=
835       "                                                                "
836       "                                                                "
837       "                                                                "
838       "                                                                ";
839     int w= art->blanklen;  if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
840     int r= pwrite(ipf->fd, spaces, w, art->offset);
841     if (r==-1) {
842       if (errno==EINTR) continue;
843       sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
844              art->messageid, art->blanklen, art->offset, ipf->path);
845     }
846     assert(r>=0 && r<=w);
847     art->blanklen -= w;
848     art->offset += w;
849   }
850
851   ipf->inprogress--;
852   assert(ipf->inprogress >= 0);
853
854   if (!ipf->inprogress)
855     loop->on_time(loop, OOP_TIME_NOW, statemc_check_oldinput_done, 0);
856
857   free(art);
858 }
859
860 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
861                          const char *errmsg, int errnoval,
862                          const char *data, size_t recsz, void *conn_v) {
863   Conn *conn= conn_v;
864   connfail(conn, "error receiving from peer: %s", errmsg);
865   return OOP_CONTINUE;
866 }
867
868 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
869                         const char *errmsg, int errnoval,
870                         const char *data, size_t recsz, void *conn_v) {
871   Conn *conn= conn_v;
872
873   if (ev == OOP_RD_EOF) {
874     connfail(conn, "unexpected EOF from peer");
875     return OOP_CONTINUE;
876   }
877   assert(ev == OOP_RD_OK);
878
879   char *ep;
880   unsigned long code= strtoul(data, &ep, 10);
881   if (ep != data+3 || *ep != ' ' || data[0]=='0') {
882     char sanibuf[100];
883     const char *p= data;
884     char *q= sanibuf;
885     *q++= '`';
886     for (;;) {
887       if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
888       int c= *p++;
889       if (!c) { *q++= '\''; break; }
890       if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
891       sprintf(q,"\\x%02x",c);
892       q += 4;
893     }
894     connfail(conn, "badly formatted response from peer: %s", sanibuf);
895     return OOP_CONTINUE;
896   }
897
898   if (conn->quitting) {
899     if (code!=205) {
900       connfail(conn, "peer gave failure response to QUIT: %s", sani);
901       return OOP_CONTINUE;
902     }
903     conn close ok;
904     return;
905   }
906
907   Article *art;
908
909 #define GET_ARTICLE                                                         \
910   art= article_reply_check(conn, data, code_streaming, sani);               \
911   if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
912
913 #define ARTICLE_DEALTWITH(streaming,how)                        \
914   code_streaming= (streaming)                                   \
915   GET_ARTICLE;                                                  \
916   article_done(conn, art, RC_##how);  break;
917
918 #define PEERBADMSG(m) connfail(conn, m ": %s", sani);  return OOP_CONTINUE
919
920   int code_streaming= 0;
921
922   switch (code) {
923
924   case 400: PEERBADMSG("peer stopped accepting articles");
925   case 503: PEERBADMSG("peer timed us out");
926   default:  PEERBADMSG("peer sent unexpected message");
927
928   case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
929   case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
930
931   case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
932   case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
933
934   case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
935   case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
936
937   case 238: /* CHECK says send it */
938     code_streaming= 1;
939   case 335: /* IHAVE says send it */
940     GET_ARTICLE;
941     count_checkedwanted++;
942     LIST_ADDTAIL(conn->queue);
943     if (art->checked) {
944       connfail("peer gave %d response to article body: %s",code, sani);
945       return OOP_CONTINUE;
946     }
947     art->checked= 1;
948     break;
949
950   case 431: /* CHECK or TAKETHIS says try later */
951     code_streaming= 1;
952   case 436: /* IHAVE says try later */
953     GET_ARTICLE;
954     if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
955         || fflush(defer))
956       sysdie("write to defer file %s",path_ductdefer);
957     article_done(conn, art, RC_deferred);
958     break;
959
960   }
961
962   check_check_work(conn);
963   return OOP_CONTINUE;
964 }
965
966
967 /*========== monitoring of input files ==========*/
968
969 static void feedfile_eof(InputFile *ipf) {
970   assert(ipf != main_input_file); /* promised by tailing_try_read */
971   assert(ipf == old_input_file);
972   assert(sms==sm_SEPARATED1 || sms==sm_DROPPING1);
973   sms++;
974   inputfile_tailing_stop(ipf);
975   if (main_input_file)
976     inputfile_tailing_start(main_input_file);
977 }
978
979 static InputFile *open_input_file(const char *path) {
980   int fd= open(path, O_RDONLY);
981   if (fd<0) {
982     if (errno==ENOENT) return 0;
983     sysdie("unable to open input file %s", path);
984   }
985
986   InputFile *ipf= xmalloc(sizeof(InputFile));
987   memset(ipf,0,sizeof(*ipf));
988
989   ipf->readable.on_readable= tailing_on_readable;
990   ipf->readable.on_cancel=   tailing_on_cancel;
991   ipf->readable.try_read=    tailing_try_read;
992
993   ipf->fd= fd;
994   ipf->path= path;
995
996   return ipf;
997 }
998
999 static void close_input_file(InputFile *ipf) {
1000   assert(!ipf->readable_callback); /* must have had ->on_cancel */
1001   assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1002   assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1003   assert(!ipf->inprogress); /* no dangling pointers pointing here */
1004
1005   if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1006   free(ipf);
1007 }
1008
1009
1010 /*---------- dealing with articles read in the input file ----------*/
1011
1012 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1013                                    oop_rd_event ev, const char *errmsg,
1014                                    int errnoval,
1015                                    const char *data, size_t recsz,
1016                                    void *ipf_v) {
1017   InputFile *ipf= ipf_v;
1018   Article *art;
1019   char tokentextbuf[sizeof(TOKEN)*2+3];
1020
1021   if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1022
1023   if (data[0] && data[0]!=' ') {
1024     char *space= strchr(data,' ');
1025     int tokenlen= space-data;
1026     int midlen= (int)recsz-tokenlen-1;
1027     if (midlen < 0) goto bad_data;
1028
1029     if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1030     memcpy(tokentextbuf, data, tokenlen);
1031     tokentextbuf[tokenlen]= 0;
1032     if (!IsToken(tokentextbuf)) goto bad_data;
1033
1034     art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1035     art->offset= ipf->offset;
1036     art->blanklen= recsz;
1037     art->midlen= midlen;
1038     art->checked= art->sentbody= 0;
1039     art->ipf= ipf;  ipf->inprogress++;
1040     art->token= TextToToken(tokentextbuf);
1041     strcpy(art->messageid, space+1);
1042     LIST_ADDTAIL(queue, art);
1043   }
1044   ipf->offset += recsz + 1;
1045
1046   if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
1047     notice("starting flush (%lu >= %lu)",
1048            (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1049
1050     int r= link(feedfile, duct_path);
1051     if (r) sysdie("link feedfile %s to ductfile %s", feedfile, dut_path);
1052     /* => Hardlinked */
1053
1054     r= unlink(feedfile);
1055     if (r) sysdie("unlink old feedfile link %s", feedfile);
1056     /* => Moved */
1057
1058     spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1059   }
1060
1061   check_master_queue();
1062 }
1063
1064
1065 /*========== tailing input file ==========*/
1066
1067 static void filemon_start(InputFile *ipf) {
1068   assert(!ipf->filemon);
1069
1070   ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1071   memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1072   filemon_method_startfile(ipf, ipf->filemon);
1073 }
1074
1075 static void filemon_stop(InputFile *ipf) {
1076   if (!ipf->filemon) return;
1077   filemon_method_stopfile(ipf, ipf->filemon);
1078   free(ipf->filemon);
1079   ipf->filemon= 0;
1080 }
1081
1082 static void filemon_callback(InputFile *ipf) {
1083   ipf->readable_callback(ipf->readable_callback_user);
1084 }
1085
1086 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1087                                      void *user) {
1088   InputFile *ipf= user;
1089   return ipf->readable_callback(ipf->readable_callback_user);
1090 }
1091
1092 static void on_cancel(struct oop_readable *rable) {
1093   InputFile *ipf= (void*)rable;
1094
1095   if (ipf->filemon) filemon_stopfile(ipf);
1096   loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1097   ipf->readable_callback= 0;
1098 }
1099
1100 static int tailing_on_readable(struct oop_readable *rable,
1101                                 oop_readable_call *cb, void *user) {
1102   InputFile *ipf= (void*)rable;
1103
1104   tailing_on_cancel(rable);
1105   ipf->readable_callback= cb;
1106   ipf->readable_callback_user= user;
1107   filemon_startfile(ipf);
1108
1109   loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1110   return 0;
1111 }
1112
1113 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1114                                 size_t length) {
1115   InputFile *ipf= (void*)rable;
1116   for (;;) {
1117     ssize_t r= read(ipf->fd, buffer, length);
1118     if (r==-1) {
1119       if (errno==EINTR) continue;
1120       return r;
1121     }
1122     if (!r) {
1123       if (ipf==main_input_file) { errno=EAGAIN; return -1; }
1124       assert(sms==sm_SEPARATED1 || sms==sm_DROPPING1);
1125     }
1126     return r;
1127   }
1128 }
1129
1130 /*---------- filemon implemented with inotify ----------*/
1131
1132 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1133 #define HAVE_FILEMON
1134
1135 #include <linux/inotify.h>
1136
1137 static int filemon_inotify_fd;
1138 static int filemon_inotify_wdmax;
1139 static InputFile **filemon_inotify_wd2ipf;
1140
1141 typedef struct Filemon_Perfile {
1142   int wd;
1143 } Filemon_Inotify_Perfile;
1144
1145 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1146   int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1147   if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1148
1149   if (wd >= filemon_inotify_wdmax) {
1150     int newmax= wd+2;
1151     filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1152                                  sizeof(*filemon_inotify_wd2ipf) * newmax);
1153     memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1154            sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1155     filemon_inotify_wdmax= newmax;
1156   }
1157
1158   assert(!filemon_inotify_wd2ipf[wd]);
1159   filemon_inotify_wd2ipf[wd]= ipf;
1160
1161   pf->wd= wd;
1162 }
1163
1164 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1165   int wd= pf->wd;
1166   int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1167   if (r) sysdie("inotify_rm_watch");
1168   filemon_inotify_wd2ipf[wd]= 0;
1169 }
1170
1171 static void *filemon_inotify_readable(oop_source *lp, int fd,
1172                                       oop_event e, void *u) {
1173   struct inotify_event iev;
1174   for (;;) {
1175     int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1176     if (r==-1) {
1177       if (errno==EAGAIN) break;
1178       sysdie("read from inotify master");
1179     } else if (r==sizeof(iev)) {
1180       assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1181     } else {
1182       die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1183     }
1184     InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1185     filemon_callback(ipf);
1186   }
1187   return OOP_CONTINUE;
1188 }
1189
1190 static int filemon_method_init(void) {
1191   filemon_inotify_fd= inotify_init();
1192   if (filemon_inotify_fd<0) {
1193     syswarn("could not initialise inotify: inotify_init failed");
1194     return 0;
1195   }
1196   set nonblock;
1197   loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1198
1199   return 1;
1200 }
1201
1202 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1203
1204 /*---------- filemon dummy implementation ----------*/
1205
1206 #if !defined(HAVE_FILEMON)
1207
1208 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1209
1210 static int filemon_method_init(void) { return 0; }
1211 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1212 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1213
1214 #endif /* !HAVE_FILEMON */
1215
1216 /*---------- interface to start and stop an input file ----------*/
1217
1218 static const oop_rd_style feedfile_rdstyle= {
1219   OOP_RD_DELIM_STRIP, '\n',
1220   OOP_RD_NUL_FORBID,
1221   OOP_RD_SHORTREC_EOF,
1222 };
1223
1224 static void inputfile_tailing_start(InputFile *ipf) {
1225   assert(!ipf->fd);
1226   ipf->readable->on_readable= tailing_on_readable;
1227   ipf->readable->on_cancel=   tailing_on_cancel;
1228   ipf->readable->try_read=    tailing_try_read;
1229   ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1230   ipf->readable->delete_kill= 0;
1231
1232   ipf->readable_callback= 0;
1233   ipf->readable_callback_user= 0;
1234
1235   ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1236   assert(ipf->fd);
1237
1238   int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1239                      feedfile_got_article,ipf, feedfile_problem,ipf);
1240   if (r) sysdie("unable start reading feedfile %s",ipf->path);
1241 }
1242
1243 static void inputfile_tailing_stop(InputFile *ipf) {
1244   assert(ipf->fd);
1245   oop_rd_delete(ipf->rd);
1246   ipf->rd= 0;
1247   assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1248 }
1249
1250
1251 /*========== interaction with innd ==========*/
1252
1253 /* See official state diagram at top of file.  We implement
1254  * this as follows:
1255
1256            ================
1257             WAITING
1258            [Nothing/Noduct]
1259             poll for F
1260            ================
1261                 |
1262                 |     TIMEOUT
1263                 |`--------------------------.
1264                 |                           | install defer as backlog
1265                 | OPEN F SUCCEEDS           | exit
1266      ,--------->|                           V
1267      |          V                         =========
1268      |     ========                        (ESRCH)
1269      |      NORMAL                        [Dropped]
1270      |     [Normal]                       =========
1271      |      main F tail
1272      |     ========
1273      |          |
1274      |          | F IS SO BIG WE SHOULD FLUSH
1275      ^          | hardlink F to D
1276      |     [Hardlinked]
1277      |          | unlink F
1278      |          | our handle onto F is now onto D
1279      |     [Moved]
1280      |          |
1281      |          |<---------------------------------------------------.
1282      |          |                                                    |
1283      |          | spawn inndcomm flush                               |
1284      |          V                                                    |
1285      |     ==========                                                |
1286      |      FLUSHING                                                 |
1287      |     [Flushing]                                                |
1288      |      main D tail                                              |
1289      |     ==========                                                |
1290      |          |                                                    |
1291      |          |   INNDCOMM FLUSH FAILS                             ^
1292      |          |`----------------------->----------.                |
1293      |          |                                   |                |
1294      |          |   NO SUCH SITE                    V                |
1295      ^          |`--------------->----.          ===========         |
1296      |          |                      \         FLUSHFAIL           |
1297      |          |                       \        [Moved]             |
1298      |          |                        \       main D tail         |
1299      |          |                         \      ===========         |
1300      |          |                          \        |                |
1301      |          |                           \       | TIME TO RETRY  |
1302      |          |                            \      `----------------'
1303      |          | FLUSH OK                    \
1304      |          | open F                       \
1305      |          V                               V
1306      |     =============                     ============
1307      |      SEPARATED1                        DROPPING1
1308      |     [Separated]                       [Dropping]
1309      |      main F idle                       main none
1310      |      old  D tail                       old  D tail
1311      |     =============                     ============
1312      |          |                                 |
1313      ^          | EOF ON D                        | EOF ON D
1314      |          V                                 V
1315      |     =============                     ============
1316      |      SEPARATED2                        DROPPING2
1317      |     [Finishing]                       [Dropping]
1318      |      main F tail                       main none
1319      |      old  D idle                       old  D idle
1320      |     =============                     ============
1321      |          |                                |
1322      |          | ALL D PROCESSED                | ALL D PROCESSED
1323      |          V install defer as backlog       V install defer as backlog
1324      ^          | close D                        | close D
1325      |          | unlink D                       | unlink D
1326      |          | start new defer                | exit
1327      |          |                                V
1328      `----------'                            ==========
1329                                               (ESRCH)
1330                                              [Droppped]
1331                                              ==========
1332  */
1333
1334 static void open_defer(void) {
1335   struct stat stab;
1336
1337   assert(!defer);
1338   defer= fopen(path_ductdefer, "a+");
1339   if (!defer) sysdie("could not open defer file %s", path_ductdefer);
1340
1341   /* truncate away any half-written records */
1342
1343   r= fstat(fileno(defer), &stab);
1344   if (r) sysdie("could not stat newly opened defer file %s", path_ductdefer);
1345
1346   if (stab.st_size > LONG_MAX)
1347     die("defer file %s size is far too large", path_ductdefer);
1348
1349   if (!stab.st_size)
1350     return;
1351
1352   long orgsize= stab.st_size;
1353   long truncto= stab.st_size;
1354   for (;;) {
1355     if (!truncto) break; /* was only (if anything) one half-truncated record */
1356     if (fseek(defer, truncto-1, SEEK_SET) < 0)
1357       sysdie("seek in defer file %s while truncating partial", path_ductdefer);
1358
1359     r= getc(defer);
1360     if (r==EOF) {
1361       if (ferror(defer))
1362         sysdie("failed read from defer file %s", path_ductdefer);
1363       else
1364         die("defer file %s shrank while we were checking it!", path_ductdefer);
1365     }
1366     if (r=='\n') break;
1367     truncto--;
1368   }
1369
1370   if (stab.st_size != truncto) {
1371     warn("truncating half-record at end of defer file %s -"
1372          " shrinking by %ld bytes from %ld to %ld",
1373          path_ductdefer, orgsize - truncto, orgsize, truncto);
1374
1375     if (fflush(defer)) sysdie("could not flush defer file %s", path_ductdefer);
1376     if (ftruncate(fileno(defer), truncto))
1377       sysdie("could not truncate defer file %s", path_ductdefer);
1378
1379   } else {
1380     info("continuing existing defer file %s (%ld bytes)",
1381          path_ductdefer, orgsize);
1382   }
1383   if (fseek(defer, truncto, SEEK_SET))
1384     sysdie("could not seek to new end of defer file %s", path_ductdefer);
1385 }
1386
1387 static void statemc_init(void) {
1388   struct stat stab;
1389
1390   path_ductlock=  xasprintf("%s_duct.lock",  feedfile);
1391   path_duct=      xasprintf("%s_duct",       feedfile);
1392   path_ductdefer= xasprintf("%s_duct.defer", feedfile);
1393
1394   if (lstat(path_ductdefer, &stab)) {
1395     if (errno!=ENOENT) sysdie("could not check defer file %s", path_defer);
1396   } else {
1397     if (!S_ISREG(stab.st_mode))
1398       die("defer file %s not a plain file (mode 0%lo)",
1399           path_defer, (unsigned long)stab.st_mode);
1400     switch (stab.st_nlink==1) {
1401     case 1: /* ok */ break;
1402     case 2:
1403       if (unlink(path_defer))
1404         sysdie("could not unlink stale defer file link %s (presumably"
1405                " hardlink to backlog file)", path_defer);
1406       break;
1407     default:
1408       die("defer file %s has unexpected link count %d",
1409           path_defer, stab.st_nlink);
1410     }
1411   }
1412   open_defer();
1413
1414   int lockfd= open(path_ductlock, O_CREAT|O_RDWR, 0600);
1415   if (lockfd<0) sysdie("open lockfile %s", path_ductlock);
1416
1417   struct flock fl;
1418   memset(&fl,0,sizeof(fl));
1419   fl.l_type= F_WRLCK;
1420   fl.l_whence= SEEK_SET;
1421   r= fcntl(lockfd, F_SETLK, &fl);
1422   if (r==-1) {
1423     if (errno==EACCES || errno==EAGAIN)
1424       die("another duct holds the lockfile");
1425     sysdie("fcntl F_SETLK lockfile %s", path_ductlock);
1426   }
1427
1428   InputFile *file_d= open_input_file(path_duct);
1429
1430   if (file_d) {
1431     struct stat stab_f, stab_d;
1432
1433     r= stat(feedfile, &stab_f);
1434     if (r) {
1435       if (errno!=ENOENT) sysdie("check feed file %s", feedfile);
1436       /* D exists, F ENOENT => Moved */
1437       goto found_moved;
1438     }
1439
1440     /* F and D both exist */
1441
1442     r= fstat(file_d->fd, &stab_d);
1443     if (r) sysdie("check duct file %s", ductfile);
1444
1445     if (stab_d.st_ino == stab_f.st_ino &&
1446         stab_d.st_dev == stab_f.st_dev) {
1447       /* F==D => Hardlinked*/
1448       r= unlink(path_duct);
1449       if (r) sysdie("unlink feed file %s during startup", feedfile);
1450     found_moved:
1451       /* => Moved */
1452       startup_set_input_file(file_d);
1453       spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1454     } else {
1455       /* F!=D => Separated */
1456       sms= sm_SEPARATED;
1457       startup_set_input_file(file_d);
1458     }
1459   } else { /*!file_d*/
1460     sms= sm_WAITING;
1461     sm_period_counter= open_wait_periods;
1462   }
1463 }
1464
1465 static void statemc_poll(void) {
1466   if (sms==sm_WAITING)
1467     statemc_waiting_poll();
1468
1469   if (!sm_period_counter) return;
1470   sm_period_counter--;
1471   assert(sm_period_counter>=0);
1472
1473   if (sm_period_counter) return;
1474   switch (sms) {
1475   case sm_WAITING:
1476     die("timed out waiting for innd to create feed file %s", feedfile);
1477   case sm_FLUSHFAIL:
1478     spawn_inndcomm_flush(void);
1479     break;
1480   default:
1481     abort();
1482   }
1483 }
1484
1485 static void statemc_waiting_poll(void) {
1486   InputFile *file_f= open_input_file(feedfile);
1487   if (!file_f) return;
1488   startup_set_input_file(file_d);
1489   sms= sm_NORMAL;
1490 }
1491
1492 static void startup_set_input_file(InputFile *f) {
1493   assert(!main_input_file);
1494   main_input_file= f;
1495   inputfile_tailing_start(f);
1496 }
1497
1498 static void *statemc_check_oldinput_done(oop_source *lp,
1499                                          struct timeval now, void *u) {
1500   struct stat stab;
1501
1502   int done= (sms==sm_SEPARATED2 || sms==sm_DROPPING2)
1503          && old_input_file->inprogress;
1504   if (!done) return;
1505
1506   r= fstat(fileno(defer), &stab);
1507   if (r) sysdie("check defer file %s", path_defer);
1508
1509   if (fclose(defer)) sysdie("could not close defer file %s", path_defer);
1510   defer= 0;
1511
1512   char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1513                            (unsigned long)now.tv_sec,
1514                            (unsigned long)stab.st_ino);
1515   if (link(path_defer, path_backlog))
1516     sysdie("could not install defer file %s as backlog file %s",
1517            path_defer, backlog);
1518   if (unlink(path_defer))
1519     sysdie("could not unlink old defer link %s to backlog file %s",
1520            path_defer, backlog);
1521
1522   if (unlink(path_duct))
1523     sysdie("could not unlink old duct file %s", path_duct);
1524
1525   if (sms==sm_DROPPING2) {
1526     notice("feed dropped and our work is complete"
1527            " (but check for backlog files)");
1528     exit(0);
1529   }
1530
1531   open_defer();
1532
1533   close_input_file(old_input_file);
1534   old_input_file= 0;
1535
1536   notice("flush complete");
1537
1538   sms= sm_NORMAL;
1539 }
1540
1541 /*========== flushing the feed ==========*/
1542
1543 static pid_t inndcomm_child;
1544
1545 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1546   assert(inndcomm_child);
1547   int status= xwaitpid(&inndcomm_child, "inndcomm");
1548   loop->cancel_fd(fd);
1549   close(fd);
1550
1551   assert(!old_input_file);
1552
1553   if (WIFEXITED(status)) {
1554     switch (WEXITSTATUS(status)) {
1555       
1556     case INNDCOMMCHILD_ESTATUS_FAIL:
1557       goto failed;
1558
1559     case INNDCOMMCHILD_ESTATUS_NONESUCH:
1560       warn("feed has been dropped by innd, finishing up");
1561       old_input_file= main_input_file;
1562       main_input_file= 0;
1563       sms= sm_DROPPING1;
1564       return OOP_CONTINUE;
1565
1566     case 0:
1567       old_input_file= main_input_file;
1568       main_input_file= open_input_file(feedfile);
1569       if (!main_input_file)
1570         die("flush succeeded but feedfile %s does not exist!", feedfile);
1571       sms= sm_SEPARATED1;
1572       return OOP_CONTINUE;
1573
1574     default:
1575       goto unexpected_exitstatus;
1576       
1577     }
1578   } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1579     warn("flush timed out trying to talk to innd");
1580     goto failed;
1581   } else {
1582   unexpected_exitstatus:
1583     report_child_status("inndcomm child", status);
1584   }
1585
1586  failed:
1587   sm_period_counter= flushfail_retry_periods;
1588   sms= sm_FLUSHFAIL;;
1589 }
1590
1591 static void inndcommfail(const char *what) {
1592   syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1593   exit(INNDCOMMCHILD_ESTATUS_FAIL);
1594 }
1595
1596 void spawn_inndcomm_flush(void) {
1597   int pipefds[2];
1598
1599   assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1600   assert(!inndcomm_child);
1601
1602   if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1603
1604   inndcomm_child= xfork();
1605
1606   if (!inndcomm_child) {
1607     static char flushargv[2]= { feedname, 0 };
1608     char *reply;
1609
1610     close(pipefds[0]);
1611
1612     alarm(inndcomm_flush_timeout);
1613     r= ICCopen();                         if (r)   inndcommfail("connect");
1614     r= ICCcommand('f',flushargv,&reply);  if (r<0) inndcommfail("transmit");
1615     if (!r) exit(0); /* yay! */
1616
1617     if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1618     syswarn("innd ctlinnd flush failed: innd said %s", reply);
1619     exit(INNDCOMMCHILD_ESTATUS_FAIL);
1620   }
1621
1622   close(pipefds[1]);
1623   int sentinel_fd= pipefds[0];
1624   on_fd_read_except(sentinel_fd, inndcomm_event);
1625
1626   sms= sm_FLUSHING;
1627 }
1628
1629 /*========== main program ==========*/
1630
1631 static void postfork_inputfile(InputFile *ipf) {
1632   if (!ipf) return;
1633   assert(ipf->fd >= 0);
1634   close(ipf->fd);
1635   ipf->fd= -1;
1636 }
1637
1638 static void postfork_conns(Connection *conn) {
1639   while (conn) {
1640     close(conn->fd);
1641     conn= conn->next;
1642   }
1643 }
1644
1645 static void postfork_stdio(FILE *f) {
1646   /* we have no stdio streams that are buffered long-term */
1647   if (f) fclose(f);
1648 }
1649
1650 static void postfork(const char *what) {
1651   if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1652     sysdie("%s child: failed to reset SIGPIPE");
1653
1654   postfork_inputfile(main_input_file);
1655   postfork_inputfile(old_input_file);
1656   postfork_conns(idle.head);
1657   postfork_conns(working.head);
1658   postfork_conns(full.head);
1659   postfork_stdio(defer);
1660 }
1661
1662
1663 #define EVERY(what, interval, body)                                          \
1664   static const struct timeval what##_timeout = { 5, 0 };                     \
1665   static void what##_schedule(void);                                         \
1666   static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1667     { body }                                                                 \
1668     what##_schedule();                                                       \
1669   }                                                                          \
1670   static void what##_schedule(void) {                                        \
1671     loop->on_time(loop, what##_timeout, what##_timedout, 0);                 \
1672   }
1673
1674 EVERY(filepoll, {5,0}, { check_master_queue(); })
1675
1676 EVERY(period, {PERIOD_SECONDS,0}, {
1677   if (connect_delay) connect_delay--;
1678   statemc_poll();
1679   check_master_queue();
1680 });
1681
1682 main {
1683   if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1684     sysdie("could not ignore SIGPIPE");
1685   if (!filemon_init())
1686     filepoll_schedule();
1687   period_schedule();
1688 };