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