chiark / gitweb /
WIP make it compile
[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  * F site.name                 main feed file
19  *                                opened/created, then written, by innd
20  *                                read by duct
21  *                                unlinked by duct
22  *                                tokens blanked out by duct when processed
23  *   site.name_lock            lock preventing multiple ducts
24  *                                to hold lock must open,F_SETLK[W]
25  *                                  and then stat to check that locked file
26  *                                  still has name site.name_lock
27  *                                holder of this lock is "duct"
28  *                                (only) lockholder may remove the lockfile
29  * D site.name_flushing        temporary feed file during flush (or crash)
30  *                                hardlink created by duct
31  *                                unlinked by duct
32  *   site.name_defer           431'd articles, still being written,
33  *                                created, written, used by duct
34  *
35  *   site.name_backlog.<date>.<inum>
36  *                             431'd articles, ready for innxmit or duct
37  *                                created (link/mv) by duct
38  *   site.name_backlog<anything-else>  (where <anything-else> does not
39  *                                      contain '#' or '~') eg
40  *   site.name_backlog.manual
41  *                             anything the sysadmin likes (eg, feed files
42  *                             from old feeds to be merged into this one)
43  *                                created (link/mv) by admin
44  *                                may be symlinks (in which case links
45  *                                may be written through, but only links
46  *                                will be removed.
47  *
48  *                             It is safe to remove backlog files manually,
49  *                             if it's desired to throw away the backlog.
50  *
51  * Backlog files are also processed by innduct.  We find the oldest
52  * backlog file which is at least a certain amount old, and feed it
53  * back into our processing.  When every article in it has been read
54  * and processed, we unlink it and look for another backlog file.
55  *
56  * If we don't have a backlog file that we're reading, we close the
57  * defer file that we're writing and make it into a backlog file at
58  * the first convenient opportunity.
59  * -8<-
60
61
62    OVERALL STATES:
63
64                                                                 START
65                                                                   |
66      ,-->--.                                                 check F, D
67      |     |                                                      |
68      |     |                                                      |
69      |     |  <----------------<---------------------------------'|
70      |     |                                       F exists       |
71      |     |                                       D ENOENT       |
72      |     |  duct opens F                                        |
73      |     V                                                      |
74      |  Normal                                                    |
75      |   F: innd writing, duct reading                            |
76      |   D: ENOENT                                                |
77      |     |                                                      |
78      |     |  duct decides time to flush                          |
79      |     |  duct makes hardlink                                 |
80      |     |                                                      |
81      |     V                            <------------------------'|
82      |  Hardlinked                                  F==D          |
83      |   F == D: innd writing, duct reading         both exist    |
84      ^     |                                                      |
85      |     |  duct unlinks F                                      |
86      |     |                        <-----------<-------------<--'|
87      |     |                           open D         F ENOENT    |
88      |     |                           if exists                  |
89      |     |                                                      |
90      |     V                        <---------------------.       |
91      |  Moved                                             |       |
92      |   F: ENOENT                                        |       |
93      |   D: innd writing, duct reading; or ENOENT         |       |
94      |     |                                              |       |
95      |     |  duct requests flush of feed                 |       |
96      |     |   (others can too, harmlessly)               |       |
97      |     V                                              |       |
98      |  Flushing                                          |       |
99      |   F: ENOENT                                        |       |
100      |   D: innd flushing, duct; or ENOENT                |       |
101      |     |                                              |       |
102      |     |   inndcomm flush fails                       |       |
103      |     |`-------------------------->------------------'       |
104      |     |                                                      |
105      |     |   inndcomm reports no such site                      |
106      |     |`---------------------------------------------------- | -.
107      |     |                                                      |  |
108      |     |  innd finishes writing D, creates F                  |  |
109      |     |  inndcomm reports flush successful                   |  |
110      |     |                                                      |  |
111      |     V                                                      |  |
112      |  Separated                                <----------------'  |
113      |   F: innd writing                            F!=D             /
114      |   D: duct reading; or ENOENT                  both exist     /
115      |     |                                                       /
116      |     |  duct gets to the end of D                           /
117      |     |  duct opens F too                                   /
118      |     V                                                    /
119      |  Finishing                                              /
120      |   F: innd writing, duct reading                        |
121      |   D: duct finishing                                    V
122      |     |                                            Dropping
123      |     |  duct finishes processing D                 F: ENOENT
124      |     V  duct unlinks D                             D: duct reading
125      |     |                                                  |
126      `--<--'                                                  | duct finishes
127                                                               |  processing D
128                                                               | duct unlinks D
129                                                               | duct exits
130                                                               V
131                                                         Dropped
132                                                          F: ENOENT
133                                                          D: ENOENT
134                                                          duct not running
135
136    "duct reading" means innduct is reading the file but also
137    overwriting processed tokens.
138
139  * ->8- -^L-
140  *
141  * rune for printing diagrams:
142
143 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
144
145  *
146  */
147
148 #define _GNU_SOURCE
149
150 #include "config.h"
151 #include "storage.h"
152 #include "oop.h"
153 #include "oop-read.h"
154
155 #include <sys/uio.h>
156 #include <sys/types.h>
157 #include <sys/wait.h>
158 #include <sys/stat.h>
159 #include <sys/socket.h>
160 #include <unistd.h>
161 #include <string.h>
162 #include <signal.h>
163 #include <stdio.h>
164 #include <errno.h>
165 #include <syslog.h>
166
167 /*----- general definitions, probably best not changed -----*/
168
169 #define PERIOD_SECONDS 60
170
171 #define CONNCHILD_ESTATUS_STREAM   4
172 #define CONNCHILD_ESTATUS_NOSTREAM 5
173
174 #define INNDCOMMCHILD_ESTATUS_FAIL     6
175 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
176
177 typedef struct Conn Conn;
178 typedef struct Article Article;
179
180 /*----- configuration options -----*/
181
182 static char *sitename, *feedfile;
183 static const char *remote_host;
184 static int quiet_multiple=0, become_daemon=1;
185
186 static int max_connections=10, max_queue_per_conn=200;
187
188 static int connection_setup_timeout=200, port=119, try_stream=1;
189 static int inndcomm_flush_timeout=100;
190 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
191 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
192 static const char *inndconffile;
193
194 static double accept_proportion;
195 static double nocheck_thresh_pct= 95.0;
196 static double nocheck_thresh; /* computed in main from _pct */
197 static double nocheck_decay_articles= 100; /* converted to _decay */
198 static double nocheck_decay; /* computed in main from _articles */
199 static int nocheck, nocheck_reported;
200
201
202 /*----- doubly linked lists -----*/
203
204 #define ISNODE(T)    T *next, *back;
205 #define LIST(T)      struct { T *head, *tail, *tailpred; int count; }
206
207 #define NODE(n) ((struct node*)&(n)->head)
208
209 #define LIST_ADDHEAD(l,n)                                               \
210  (list_addhead((struct list*)&(l), NODE((n))), (void)(l).count++)
211 #define LIST_ADDTAIL(l,n)                                               \
212  (list_addtail((struct list*)&(l), NODE((n))), (void)(l).count++)
213
214 #define LIST_REMHEAD(l)                                                   \
215  ((l).count ? ((l).count--, (void*)list_remhead((struct list*)&(l))) : 0)
216 #define LIST_REMTAIL(l)                                                   \
217  ((l).count ? ((l).count--, (void*)list_remtail((struct list*)&(l))) : 0)
218 #define LIST_REMOVE(l,n)                        \
219  (list_remove(NODE((n))), (void)(l).count--)
220 #define LIST_INSERT(l,n,pred) \
221  (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
222
223
224 /*----- statistics -----*/
225
226 typedef enum {      /* in queue                 in conn->sent             */
227   art_Unchecked,    /*   not checked, not sent    checking                */
228   art_Wanted,       /*   checked, wanted          sent body as requested  */
229   art_Unsolicited,  /*   -                        sent body without check */
230   art_MaxState
231 } ArtState;
232
233 #define RESULT_COUNTS(RCS,RCN)                  \
234   RCS(sent)                                     \
235   RCS(accepted)                                 \
236   RCN(unwanted)                                 \
237   RCN(rejected)                                 \
238   RCN(deferred)                                 \
239   RCN(connretry)
240
241 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
242 #define RCI_TRIPLE_VALS_BASE(counts,x)          \
243        , counts[art_Unchecked] x                \
244        + counts[art_Wanted] x                   \
245        + counts[art_Unsolicited] x,             \
246        counts[art_Unchecked] x                  \
247        , counts[art_Wanted] x                   \
248        , counts[art_Unsolicited] x
249
250 typedef enum {
251 #define RC_INDEX(x) RCI_##x,
252   RESULT_COUNTS(RC_INDEX, RC_INDEX)
253   RCI_max
254 } ResultCountIndex;
255
256
257 /*----- transmission buffers -----*/
258
259 #define CONNIOVS 128
260
261 typedef enum {
262   xk_Malloc, xk_Const, xk_Artdata
263 } XmitKind;
264
265 typedef struct {
266   XmitKind kind;
267   union {
268     char *malloc_tofree;
269     ARTHANDLE *sm_art;
270   } info;
271 } XmitDetails;
272
273
274 /*----- core operational data structure types -----*/
275
276 typedef struct InputFile {
277   /* This is an instance of struct oop_readable */
278   struct oop_readable readable; /* first */
279   oop_readable_call *readable_callback;
280   void *readable_callback_user;
281
282   int fd;
283   struct Filemon_Perfile *filemon;
284
285   oop_read *rd;
286   long inprogress; /* no. of articles read but not processed */
287   off_t offset;
288
289   int counts[art_MaxState][RCI_max];
290   char path[];
291 } InputFile;
292
293 struct Article {
294   ArtState state;
295   int midlen;
296   InputFile *ipf;
297   TOKEN token;
298   off_t offset;
299   int blanklen;
300   char messageid[1];
301 };
302
303 #define SMS_LIST(X)                             \
304   X(NORMAL)                                     \
305   X(FLUSHING)                                   \
306   X(FLUSHFAILED)                                \
307   X(SEPARATED)                                  \
308   X(DROPPING)                                   \
309   X(DROPPED)
310
311 typedef enum {
312 #define SMS_DEF_ENUM(s) sm_##s,
313   SMS_LIST(SMS_DEF_ENUM)
314 } StateMachineState;
315
316 static const char *sms_names[]= {
317 #define SMS_DEF_NAME(s) #s ,
318   SMS_LIST(SMS_DEF_NAME)
319   0
320 };
321
322 struct Conn {
323   ISNODE(Conn);
324   int fd, max_queue, stream;
325   LIST(Article) queue; /* not yet told peer, or CHECK said send it */
326   LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
327   struct iovec xmit[CONNIOVS];
328   XmitDetails xmitd[CONNIOVS];
329   int xmitu;
330 };
331
332
333 /*----- operational variables -----*/
334
335 static oop_source *loop;
336
337 static int nconns;
338 static LIST(Conn) idle, working, full;
339 static LIST(Article) *queue;
340
341 static char *path_lock, *path_flushing, *path_defer;
342
343 #define SMS(newstate, periods, why) \
344    (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
345
346 static StateMachineState sms;
347 static FILE *defer;
348 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
349 static int sm_period_counter;
350
351
352 /*----- function predeclarations -----*/
353
354 static void conn_check_work(Conn *conn);
355
356 static int filemon_init(void);
357 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
358 static void filemon_callback(void);
359
360 static void statemc_setstate(StateMachineState newsms, int periods,
361                              const char *forlog, const char *why);
362
363 /*========== logging ==========*/
364
365 static void logcore(int sysloglevel, const char *fmt, ...)
366      __attribute__((__format__(printf,2,3)));
367 static void logcore(int sysloglevel, const char *fmt, ...) {
368   va_list al;
369   va_start(al,fmt);
370   if (become_daemon) {
371     vsyslog(sysloglevel,fmt,al);
372   } else {
373     vfprintf(stderr,fmt,al);
374     putc('\n',stderr);
375   }
376   va_end(al);
377 }
378
379 static void logv(int sysloglevel, const char *pfx, int errnoval,
380                  int exitstatus, const char *fmt, va_list al)
381      __attribute__((__format__(printf,5,0)));
382 static void logv(int sysloglevel, const char *pfx, int errnoval,
383                  int exitstatus, const char *fmt, va_list al) {
384   char msgbuf[256];
385   vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
386   msgbuf[sizeof(msgbuf)-1]= 0;
387
388   if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
389     sysloglevel= LOG_ERR; /* run by wrong user, probably */
390
391   logcore(sysloglevel, "<%s>%s: %s%s%s",
392          sitename, pfx, msgbuf,
393          errnoval>=0 ? ": " : "",
394          errnoval>=0 ? strerror(errnoval) : "");
395 }
396
397 #define logwrap(fn, pfx, sysloglevel, err, estatus)     \
398   static void fn(const char *fmt, ...)                  \
399       __attribute__((__format__(printf,1,2)));          \
400   static void fn(const char *fmt, ...) {                \
401     va_list al;                                         \
402     va_start(al,fmt);                                   \
403     logv(sysloglevel, pfx, err, estatus, fmt, al);      \
404   }
405
406 logwrap(sysdie,   " critical", LOG_CRIT,    errno, 16);
407 logwrap(die,      " critical", LOG_CRIT,    -1,    16);
408
409 logwrap(sysfatal, " fatal",    LOG_ERR,     errno, 12);
410 logwrap(fatal,    " fatal",    LOG_ERR,     -1,    12);
411
412 logwrap(syswarn,  " warning",  LOG_WARNING, errno, 0);
413 logwrap(warn,     " warning",  LOG_WARNING, -1,    0);
414
415 logwrap(notice,   "",          LOG_NOTICE,  -1,    0);
416 logwrap(info,     " info",     LOG_INFO,    -1,    0);
417 logwrap(debug,    " debug",    LOG_DEBUG,   -1,    0);
418
419
420 /*========== utility functions etc. ==========*/
421
422 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
423
424 static void *xmalloc(size_t sz) {
425   if (!sz) return 0;
426   void *r= malloc(sz);
427   if (r) return r;
428   sysdie("malloc (%ld bytes) failed", (unsigned long)sz);
429 }
430
431 static pid_t xfork(const char *what) {
432   pid_t child;
433
434   child= fork();
435   if (child==-1) sysdie("cannot fork for %s",what);
436   if (!child) postfork(what);
437   debug("forked %s %ld", what, (unsigned long)child);
438   return child;
439 }
440
441 static void on_fd_read_except(int fd, oop_call_fd callback) {
442   loop->on_fd(loop, fd, OOP_READ,      callback, 0);
443   loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
444 }
445 static void cancel_fd_read_except(int fd) {
446   loop->cancel_fd(loop, fd, OOP_READ);
447   loop->cancel_fd(loop, fd, OOP_EXCEPTION);
448 }
449
450 static void report_child_status(const char *what, int status) {
451   if (WIFEXITED(status)) {
452     int es= WEXITSTATUS(status);
453     if (es)
454       warn("%s: child died with error exit status %d",es);
455   } else if (WIFSIGNALED(status)) {
456     int sig= WTERMSIG(status);
457     const char *sigstr= strsignal(sig);
458     const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
459     if (sigstr)
460       warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
461     else
462       warn("%s: child died due to unknown fatal signal %d%s",
463            what, sig, coredump);
464   } else {
465     warn("%s: child died with unknown wait status %d", status);
466   }
467 }
468
469 static int xwaitpid(pid_t *pid, const char *what) {
470   int status;
471
472   int r= kill(*pid, SIGKILL);
473   if (r) sysdie("cannot kill %s child", what);
474
475   pid_t got= waitpid(*pid, &status, WNOHANG);
476   if (got==-1) sysdie("cannot reap %s child", what);
477
478   *pid= 0;
479
480   return status;
481 }
482
483 static void xunlink(const char *path, const char *what) {
484   int r= unlink(path);
485   if (r) sysdie("can't unlink %s %s", path, what);
486 }
487
488 static void check_isreg(const struct stat *stab, const char *path,
489                         const char *what) {
490   if (!S_ISREG(stab->st_mode))
491     die("%s %s not a plain file (mode 0%lo)",
492         what, path, (unsigned long)stab->st_mode);
493 }
494
495 static void xfstat(int fd, struct stat *stab_r, const char *what) {
496   int r= fstab(fd, stab_r);
497   if (r) sysdie("could not fstat %s", what);
498 }
499
500 static void xfstat_isreg(int fd, struct stat *stab_r,
501                          const char *path, const char *what) {
502   xfstat(fd, stab_r, what);
503   check_isreg(stab_r, path, what);
504 }
505
506 static void xlstat_isreg(const char *path, struct stat *stab,
507                          int *enoent_r /* 0 means ENOENT is fatal */,
508                          const char *what) {
509   int r= lstat(path, stab);
510   if (r) {
511     if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
512     sysdie("could not lstat %s %s", what, path);
513   }
514   if (enoent_r) *enoent_r= 0;
515   check_isreg(stab, path, what);
516 }
517
518 static int samefile(const struct stat *a, const struct stat *b) {
519   assert(S_ISREG(a->st_mode));
520   assert(S_ISREG(b->st_mode));
521   return (a->st_ino == b->st_ino &&
522           a->st_dev == b->st_dev);
523 }
524
525 /*========== making new connections ==========*/
526
527 static int connecting_sockets[2]= {-1,-1};
528 static pid_t connecting_child;
529
530 static void connect_attempt_discard(void) {
531   if (connecting_sockets[0])
532     cancel_fd(connecting_sockets[0]);
533
534   perhaps_close(&connecting_sockets[0]);
535   perhaps_close(&connecting_sockets[1]);
536
537   if (connecting_child) {
538     int r= kill(connecting_child, SIGTERM);
539     if (r) syswarn("failed to kill connecting child");
540     int status= xwaitpid(&connecting_child, "connect");
541
542     if (!(WIFEXITED(status) ||
543           (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
544       report_child_status("connect", status);
545   }
546 }
547
548 #define PREP_DECL_MSG_CMSG(msg)                 \
549   struct msghdr msg;                            \
550   memset(&msg,0,sizeof(msg));                   \
551   char msg##cbuf[CMSG_SPACE(sizeof(fd))];       \
552   msg.msg_control= msg##cbuf;                   \
553   msg.msg_controllen= sizeof(msg##cbuf);
554
555 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
556   Conn *conn= 0;
557
558   conn= xmalloc(sizeof(*conn));
559   memset(conn,0,sizeof(*conn));
560
561   PREP_DECL_MSG_CMSG(msg);
562   struct cmsghdr *h= 0;
563   ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
564   if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
565   if (!h) {
566     int status;
567     pid_t got= waitpid(connecting_child, &status, WNOHANG);
568     if (got != -1) {
569       assert(got==connecting_child);
570       connecting_child= 0;
571       if (WIFEXITED(status) &&
572           (WEXITSTATUS(status) != 0
573            WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
574            WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
575         /* child already reported the problem */
576       } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
577         warn("connect: connection attempt timed out");
578       } else if (!WIFEXITED(status)) {
579         report_child_status("connect", status);
580         /* that's probably the root cause then */
581       }
582     } else {
583       /* child is still running apparently, report the socket problem */
584       if (rs < 0)
585         syswarn("connect: read from child socket failed");
586       else if (e == OOP_EXCEPTIONN)
587         warn("connect: unexpected exception on child socket");
588       else
589         warn("connect: unexpected EOF on child socket");
590     }
591     goto x;
592   }
593
594 #define CHK(field, val)                                                   \
595   if (h->cmsg_##field != val) {                                           \
596     die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
597     goto x;                                                               \
598   }
599   CHK(level, SOL_SOCKET);
600   CHK(type,  SCM_RIGHTS);
601   CHK(len,   CMSG_LEN(sizeof(conn-b>fd)));
602 #undef CHK
603
604   if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
605
606   memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
607
608   pid_t got= waitpid(connecting_child, &status, 0);
609   if (got==-1) sysdie("connect: real wait for child");
610   assert(got == connecting_child);
611   connecting_child= 0;
612
613   if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
614   int es= WEXITSTATUS(status);
615   switch (es) {
616   case CONNCHILD_ESTATUS_STREAM:    conn->stream= 1;   break;
617   case CONNCHILD_ESTATUS_NOSTREAM:  conn->stream= 0;   break;
618   default:
619     fatal("connect: child gave unexpected exit status %d", es);
620   }
621
622   set nonblocking;
623
624   /* Phew! */
625   LIST_ADDHEAD(idle, conn);
626   notice("#%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
627   connect_attempt_discard();
628   check_master_queue();
629   return 0;
630
631  x:
632   if (conn) {
633     perhaps_close(&conn->fd);
634     free(conn);
635   }
636   connect_attempt_discard();
637 }
638
639 static void connect_start(void) {
640   assert(!connecting_sockets[0]);
641   assert(!connecting_sockets[1]);
642   assert(!connecting_child);
643
644   notice("starting connection attempt");
645
646   r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
647   if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
648
649   connecting_child= xfork("connection");
650
651   if (!connecting_child) {
652     FILE *cn_from, *cn_to;
653     char buf[NNTP_STRLEN+100];
654     int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
655
656     r= close(connecting_sockets[0]);
657     if (r) sysdie("connect: close parent socket in child");
658
659     alarm(connection_setup_timeout);
660     if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
661       if (buf[0]) {
662         sanitise_inplace(buf);
663         fatal("connect: rejected: %s", buf);
664       } else {
665         sysfatal("connect: connection attempt failed");
666       }
667     }
668     if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
669       sysfatal("connect: authentication failed");
670     if (try_stream) {
671       if (fputs("MODE STREAM\r\n", cn_to) ||
672           fflush(cn_to))
673         sysfatal("connect: could not send MODE STREAM");
674       buf[sizeof(buf)-1]= 0;
675       if (!fgets(buf, sizeof(buf)-1, cn_from)) {
676         if (ferror(cn_from))
677           sysfatal("connect: could not read response to MODE STREAM");
678         else
679           fatal("connect: connection close in response to MODE STREAM");
680       }
681       int l= strlen(buf);
682       assert(l>=1);
683       if (buf[-1]!='\n') {
684         sanitise_inplace(buf);
685         fatal("connect: response to MODE STREAM is too long: %.100s...",
686             remote_host, buf);
687       }
688       l--;  if (l>0 && buf[1-]=='\r') l--;
689       buf[l]= 0;
690       char *ep;
691       int rcode= strtoul(buf,&ep,10);
692       if (ep != buf[3]) {
693         sanitise_inplace(buf);
694         fatal("connect: bad response to MODE STREAM: %.50s", buf);
695       }
696       switch (rcode) {
697       case 203:
698         exitstatus= CONNCHILD_ESTATUS_STREAM;
699         break;
700       case 480:
701       case 500:
702         break;
703       default:
704         sanitise_inplace(buf);
705         warn("connect: unexpected response to MODE STREAM: %.50s", buf);
706         exitstatus= 2;
707         break;
708       }
709     }
710     int fd= fileno(cn_from);
711
712     PREP_DECL_MSG_CMSG(msg);
713     struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
714     cmsg->cmsg_level= SOL_SOCKET;
715     cmsg->cmsg_type=  SCM_RIGHTS;
716     cmsg->cmsg_len=   CMSG_LEN(sizeof(fd));
717     memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
718
719     msg.msg_controllen= cmsg->cmsg_len;
720     r= sendmsg(connecting_sockets[1], &msg, 0);
721     if (r) sysdie("sendmsg failed for new connection");
722
723     _exit(exitstatus);
724   }
725
726   r= close(connecting_sockets[1]);  connecting_sockets[1]= 0;
727   if (r) sysdie("connect: close child socket in parent");
728
729   on_fd_read_except(connecting_sockets[0], connchild_event);
730   return OOP_CONTINUE;
731
732  x:
733   connect_attempt_discard();
734 }
735
736
737 /*========== overall control of article flow ==========*/
738
739 static void check_master_queue(void) {
740   if (!queue.count)
741     return;
742
743   Conn *last_assigned=0;
744   for (;;) {
745     if (working.head) {
746       conn_assign_one_article(&working, &last_assigned);
747     } else if (idle.head) {
748       conn_assign_one_article(&idle, &last_assigned);
749     } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
750                !connecting_child && !connect_delay) {
751       connect_delay= reconnect_delay_periods;
752       connect_start();
753     } else {
754       break;
755     }
756   }
757   conn_check_work(last_assigned);
758 }
759
760 static void conn_assign_one_article(LIST(Conn) *connlist,
761                                     Conn **last_assigned) {
762   Conn *conn= connlist->head;
763
764   LIST_REMOVE(*connlist, conn);
765   Article *art= LIST_REMHEAD(queue);
766   LIST_ADDTAIL(conn->queue, art);
767   LIST_ADD(*conn_determine_right_list(conn), conn);
768
769   /* This slightly odd arrangement is so that we call conn_check_work
770    * once after filling the queue for a new connection in
771    * check_master_queue, rather than for each article. */
772   if (conn != *last_assigned && *last_assigned)
773     conn_check_work(*last_assigned);
774   *last_assigned= conn;
775 }
776
777 static int conn_total_queued_articles(Conn *conn) {
778   return conn->sent.count + conn->queue.count;
779 }
780
781 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
782   int inqueue= conn_total_queued_articles(conn);
783   assert(inqueue <= max_queue);
784   if (inqueue == 0) return &idle;
785   if (inqueue == conn->max_queue) return &full;
786   return &working;
787 }
788
789 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
790   check_conn_work(u);
791   return OOP_CONTINUE;
792 }
793
794 static void conn_check_work(Conn *conn)  {
795   void *rp= 0;
796   for (;;) {
797     conn_make_some_xmits(conn);
798     if (!conn->xmitu) {
799       loop->cancel_fd(loop, conn->fd, OOP_WRITE);
800       return;
801     }
802
803     void *rp= conn_write_some_xmits(conn);
804     if (rp==OOP_CONTINUE) {
805       loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
806       return;
807     } else if (rp==OOP_HALT) {
808       return;
809     } else if (!rp) {
810       /* transmitted everything */
811     } else {
812       abort();
813     }
814   }
815 }
816
817 static void vconnfail(Conn *conn, const char *fmt, va_list al)
818      __attribute__((printf,2,0));
819
820 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
821   int requeue[art_MaxState];
822
823   Article *art;
824   while ((art= LIST_REMHEAD(conn->queue))) LIST_ADDTAIL(queue);
825   while ((art= LIST_REMHEAD(conn->sent))) {
826     counts[art->state]++;
827     if (art->state==art_Unsolicited) art->state= art_Unchecked;
828     LIST_ADDTAIL(queue);
829   }
830
831   int i;
832   XmitDetails *xd;
833   for (i=0, dp=&conn->xmitd; i<conn->xmitu; i++, dp++)
834     xmit_free(dp);
835
836   char *m= xvasprintf(fmt,al);
837   warn("#%d connection failed, requeueing " RCI_TRIPLE_FMT_BASE ": %s",
838        conn->fd, RCI_TRIPLE_FMT_VALS(requeue, /*nothing*/), m);
839   free(m);
840
841   close(conn->fd);
842   free(conn);
843
844   connect_delay= reconnect_delay_periods;
845   check_master_queue();
846 }
847
848 static void connfail(Connection *conn, const char *fmt, ...)
849      __attribute__((printf,2,3));
850 static void connfail(Connection *conn, const char *fmt, ...) {
851   va_list al;
852   va_start(al,fmt);
853   vconnfail(fmt,al);
854   va_end(al);
855 }
856
857 /*========== article transmission ==========*/
858
859 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
860                   XmitKind kind) { /* caller must then fill in details */
861   struct iovec *v= &conn->xmit[conn->xmitu];
862   XmitDetails *d= &conn->xmitd[conn->xmitu++];
863   v->iov_base= data;
864   v->iov_len= len;
865   d->kind= kind;
866   return d;
867 }
868
869 static void xmit_noalloc(Conn *conn, const char *data, int len) {
870   xmit_core(conn,data,len, xk_Const);
871 }
872 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
873
874 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
875   XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
876   d->info.sm_art= ah;
877 }
878
879 static void xmit_free(XmitDetails *d) {
880   switch (d->kind) {
881   case xk_Malloc:  free(d->info.malloc_tofree);   break;
882   case xk_Artdata: SMfreearticle(d->info.sm_art); break;
883   case xk_Const:                                  break;
884   default: abort();
885   }
886 }
887
888 static void *conn_write_some_xmits(Conn *conn) {
889   /* return values:
890    *      0:            nothing more to write, no need to call us again
891    *      OOP_CONTINUE: more to write but fd not writeable
892    *      OOP_HALT:     disaster, have destroyed conn
893    */
894   for (;;) {
895     int count= conn->xmitu;
896     if (!count) return 0;
897
898     if (count > IOV_MAX) count= IOV_MAX;
899     ssize_t rs= writev(conn->fd, conn->xmit, count);
900     if (rs < 0) {
901       if (errno == EAGAIN) return OOP_CONTINUE;
902       connfail(conn, "write failed: %s", strerror(errno));
903       return OOP_HALT;
904     }
905     assert(rs > 0);
906
907     for (done=0; rs && done<xmitu; done++) {
908       struct iovec *vp= &conn->xmit[done];
909       XmitDetails *dp= &conn->xmitd[done];
910       if (rs > vp->iov_len) {
911         rs -= vp->iov_len;
912         xmit_free(dp);
913       } else {
914         vp->iov_base += rs;
915         vp->iov_len -= rs;
916       }
917     }
918     int newu= conn->xmitu - done;
919     memmove(conn->xmit,  conn->xmit  + done, newu * sizeof(*conn->xmit));
920     memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
921     conn->xmitu= newu;
922   }
923 }
924
925 static void conn_make_some_xmits(Conn *conn) {
926   for (;;) {
927     if (conn->xmitu+5 > CONNIOVS)
928       break;
929
930     Article *art= LIST_REMHEAD(queue);
931     if (!art) break;
932
933     if (art->state >= art_Wanted || (conn->stream && nocheck)) {
934       /* actually send it */
935
936       ARTHANDLE *artdata= SMretrieve();
937
938       if (conn->stream) {
939         if (artdata) {
940           XMIT_LITERAL("TAKETHIS ");
941           xmit_noalloc(conn, art->mid, art->midlen);
942           XMIT_LITERAL("\r\n");
943           xmit_artbody(conn, artdata);
944         }
945       } else {
946         /* we got 235 from IHAVE */
947         if (artdata) {
948           xmit_artbody(conn, artdata);
949         } else {
950           XMIT_LITERAL(".\r\n");
951         }
952       }
953
954       art->state=
955         art->state == art_Unchecked ? art_Unsolicited :
956         art->state == art_Wanted    ? art_Wanted      :
957         abort();
958       art->ipf->counts[art->state].sent++;
959       LIST_ADDTAIL(conn->sent, art);
960
961     } else {
962       /* check it */
963
964       if (conn->stream)
965         XMIT_LITERAL("IHAVE ");
966       else
967         XMIT_LITERAL("CHECK ");
968       xmit_noalloc(art->mid, art->midlen);
969       XMIT_LITERAL("\r\n");
970
971       assert(art->state == art_Unchecked);
972       art->ipf->counts[art->state].sent++;
973       LIST_ADDTAIL(conn->sent, art);
974     }
975   }
976 }
977
978
979 /*========== handling responses from peer ==========*/
980
981 static const oop_rd_style peer_rd_style= {
982   OOP_RD_DELIM_STRIP, '\n',
983   OOP_RD_NUL_FORBID,
984   OOP_RD_SHORTREC_FORBID
985 };
986
987 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
988                          const char *errmsg, int errnoval,
989                          const char *data, size_t recsz, void *conn_v) {
990   Conn *conn= conn_v;
991   connfail(conn, "error receiving from peer: %s", errmsg);
992   return OOP_CONTINUE;
993 }
994
995 static Article *article_reply_check(Connection *conn, const char *response,
996                                     int code_indicates_streaming,
997                                     int must_have_sent
998                                         /* 1:yes, -1:no, 0:dontcare */,
999                                     const char *sanitised_response) {
1000   Article *art= conn->sent.head;
1001
1002   if (!art) {
1003     connfail(conn,
1004              "peer gave unexpected response when no commands outstanding: %s",
1005              sanitised_response);
1006     return 0;
1007   }
1008
1009   if (code_indicates_streaming) {
1010     assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1011     if (!conn->stream) {
1012       connfail("peer gave streaming response code "
1013                " to IHAVE or subsequent body: %s", sanitised_response);
1014       return 0;
1015     }
1016     const char *got_mid= response+4;
1017     int got_midlen= strcspn(got_mid, " \n\r");
1018     if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1019       connfail("peer gave streaming response with syntactically invalid"
1020                " messageid: %s", sanitised_response);
1021       return 0;
1022     }
1023     if (got_midlen != art->midlen ||
1024         memcmp(got_mid, art->messageid, got_midlen)) {
1025       connfail("peer gave streaming response code to wrong article -"
1026                " probable synchronisation problem; we offered: %s;"
1027                " peer said: %s",
1028                art->messageid, sanitised_response);
1029       return 0;
1030     }
1031   } else {
1032     if (conn->stream) {
1033       connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
1034                sanitised_response);
1035       return 0;
1036     }
1037   }
1038
1039   if (must_have_sent>0 && art->state < art_Wanted) {
1040     connfail("peer says article accepted but we had not sent the body: %s",
1041              sanitised_response);
1042     return 0;
1043   }
1044   if (must_have_sent<0 && art->state >= art_Wanted) {
1045     connfail("peer says please sent the article but we just did: %s",
1046              sanitised_response);
1047     return 0;
1048   }
1049
1050   Article *art_again= LIST_REMHEAD(conn->sent);
1051   assert(art_again == art);
1052   return art;
1053 }
1054
1055 static void update_nocheck(int accepted) {
1056   accept_proportion *= accept_decay;
1057   accept_proportion += accepted;
1058   int new_nocheck= accept_proportion >= nocheck_thresh;
1059   if (new_nocheck && !nocheck_reported) {
1060     notice("entering nocheck mode for the first time");
1061     nocheck_reported= 1;
1062   } else if (new_nocheck != nocheck) {
1063     debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1064   }
1065   nocheck= new_nocheck;
1066 }
1067
1068 static void article_done(Connection *conn, Article *art, int whichcount) {
1069   art->ipf->counts[art->state][whichcount]++;
1070   if (whichcount == RC_accepted) update_nocheck(1);
1071   else if (whichcount == RC_unwanted) update_nocheck(0);
1072
1073   InputFile *ipf= art->ipf;
1074   while (art->blanklen) {
1075     static const char spaces[]=
1076       "                                                                "
1077       "                                                                "
1078       "                                                                "
1079       "                                                                ";
1080     int w= art->blanklen;  if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1081     int r= pwrite(ipf->fd, spaces, w, art->offset);
1082     if (r==-1) {
1083       if (errno==EINTR) continue;
1084       sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1085              art->messageid, art->blanklen, art->offset, ipf->path);
1086     }
1087     assert(r>=0 && r<=w);
1088     art->blanklen -= w;
1089     art->offset += w;
1090   }
1091
1092   ipf->inprogress--;
1093   assert(ipf->inprogress >= 0);
1094
1095   if (!ipf->inprogress && ipf != main_input_file)
1096     queue_check_input_done();
1097
1098   free(art);
1099 }
1100
1101 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1102                         const char *errmsg, int errnoval,
1103                         const char *data, size_t recsz, void *conn_v) {
1104   Conn *conn= conn_v;
1105
1106   if (ev == OOP_RD_EOF) {
1107     connfail(conn, "unexpected EOF from peer");
1108     return OOP_CONTINUE;
1109   }
1110   assert(ev == OOP_RD_OK);
1111
1112   char *ep;
1113   unsigned long code= strtoul(data, &ep, 10);
1114   if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1115     char sanibuf[100];
1116     const char *p= data;
1117     char *q= sanibuf;
1118     *q++= '`';
1119     for (;;) {
1120       if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
1121       int c= *p++;
1122       if (!c) { *q++= '\''; break; }
1123       if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
1124       sprintf(q,"\\x%02x",c);
1125       q += 4;
1126     }
1127     connfail(conn, "badly formatted response from peer: %s", sanibuf);
1128     return OOP_CONTINUE;
1129   }
1130
1131   if (conn->quitting) {
1132     if (code!=205) {
1133       connfail(conn, "peer gave failure response to QUIT: %s", sani);
1134       return OOP_CONTINUE;
1135     }
1136     conn close ok;
1137     return;
1138   }
1139
1140   Article *art;
1141
1142 #define GET_ARTICLE(musthavesent)                                           \
1143   art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1144   if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1145
1146 #define ARTICLE_DEALTWITH(streaming,musthavesent,how)           \
1147   code_streaming= (streaming)                                   \
1148   GET_ARTICLE(musthavesent);                                    \
1149   article_done(conn, art, RC_##how);  break;
1150
1151 #define PEERBADMSG(m) connfail(conn, m ": %s", sani);  return OOP_CONTINUE
1152
1153   int code_streaming= 0;
1154
1155   switch (code) {
1156
1157   case 400: PEERBADMSG("peer stopped accepting articles");
1158   case 503: PEERBADMSG("peer timed us out");
1159   default:  PEERBADMSG("peer sent unexpected message");
1160
1161   case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1162   case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1163
1164   case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1165   case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1166
1167   case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1168   case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1169
1170   case 238: /* CHECK says send it */
1171     code_streaming= 1;
1172   case 335: /* IHAVE says send it */
1173     GET_ARTICLE(-1);
1174     assert(art->state == art_Unchecked);
1175     art->ipf->counts[art->state].accepted++;
1176     art->state= art_Wanted;
1177     LIST_ADDTAIL(conn->queue);
1178     break;
1179
1180   case 431: /* CHECK or TAKETHIS says try later */
1181     code_streaming= 1;
1182   case 436: /* IHAVE says try later */
1183     GET_ARTICLE(0);
1184     open_defer();
1185     if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1186         || fflush(defer))
1187       sysfatal("write to defer file %s",path_defer);
1188     article_done(conn, art, RC_deferred);
1189     break;
1190
1191   }
1192
1193   check_check_work(conn);
1194   return OOP_CONTINUE;
1195 }
1196
1197
1198 /*========== monitoring of input files ==========*/
1199
1200 static void feedfile_eof(InputFile *ipf) {
1201   assert(ipf != main_input_file); /* promised by tailing_try_read */
1202
1203   inputfile_tailing_stop(ipf);
1204   assert(ipf->fd >= 0);
1205   if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1206   ipf->fd= -1;
1207
1208   if (ipf == flushing_input_file) {
1209     assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1210     if (main_input_file) inputfile_tailing_start(main_input_file);
1211     statemc_check_flushing_done();
1212   } else if (ipf == backlog_input_file) {
1213     statemc_check_backlog_done();
1214   } else {
1215     abort(); /* supposed to wait rather than get EOF on main input file */
1216   }
1217 }
1218
1219 static InputFile *open_input_file(const char *path) {
1220   int fd= open(path, O_RDONLY);
1221   if (fd<0) {
1222     if (errno==ENOENT) return 0;
1223     sysfatal("unable to open input file %s", path);
1224   }
1225
1226   InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1227   memset(ipf,0,sizeof(*ipf));
1228
1229   ipf->readable.on_readable= tailing_on_readable;
1230   ipf->readable.on_cancel=   tailing_on_cancel;
1231   ipf->readable.try_read=    tailing_try_read;
1232
1233   ipf->fd= fd;
1234   strcpy(ipf->path, path);
1235
1236   return ipf;
1237 }
1238
1239 static void close_input_file(InputFile *ipf) {
1240   assert(!ipf->readable_callback); /* must have had ->on_cancel */
1241   assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1242   assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1243   assert(!ipf->inprogress); /* no dangling pointers pointing here */
1244
1245   if (ipf->fd >= 0)
1246     if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1247 }
1248
1249
1250 /*---------- dealing with articles read in the input file ----------*/
1251
1252 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1253                                    oop_rd_event ev, const char *errmsg,
1254                                    int errnoval,
1255                                    const char *data, size_t recsz,
1256                                    void *ipf_v) {
1257   InputFile *ipf= ipf_v;
1258   Article *art;
1259   char tokentextbuf[sizeof(TOKEN)*2+3];
1260
1261   if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1262
1263   if (data[0] && data[0]!=' ') {
1264     char *space= strchr(data,' ');
1265     int tokenlen= space-data;
1266     int midlen= (int)recsz-tokenlen-1;
1267     if (midlen < 0) goto bad_data;
1268
1269     if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1270     memcpy(tokentextbuf, data, tokenlen);
1271     tokentextbuf[tokenlen]= 0;
1272     if (!IsToken(tokentextbuf)) goto bad_data;
1273
1274     art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1275     art->offset= ipf->offset;
1276     art->blanklen= recsz;
1277     art->midlen= midlen;
1278     art->state= art_Unchecked;
1279     art->ipf= ipf;  ipf->inprogress++;
1280     art->token= TextToToken(tokentextbuf);
1281     strcpy(art->messageid, space+1);
1282     LIST_ADDTAIL(queue, art);
1283   }
1284   ipf->offset += recsz + 1;
1285
1286   if (sms==sm_NORMAL && ipf==main_input_file &&
1287       ipf->offset >= flush_threshold)
1288     statemc_start_flush("feed file size");
1289
1290   check_master_queue();
1291 }
1292
1293 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1294   assert(sms == sm_NORMAL);
1295
1296   debug("starting flush (%s) (%lu >= %lu) (%d)",
1297         why,
1298         (unsigned long)ipf->offset, (unsigned long)flush_threshold,
1299         sm_period_counter);
1300
1301   int r= link(feedfile, duct_path);
1302   if (r) sysdie("link feedfile %s to flushing file %s", feedfile,
1303                 path_duct);
1304   /* => Hardlinked */
1305
1306   xunlink(feedfile, "old feedfile link");
1307   /* => Moved */
1308
1309   spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1310 }
1311
1312 /*========== tailing input file ==========*/
1313
1314 static void filemon_start(InputFile *ipf) {
1315   assert(!ipf->filemon);
1316
1317   ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1318   memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1319   filemon_method_startfile(ipf, ipf->filemon);
1320 }
1321
1322 static void filemon_stop(InputFile *ipf) {
1323   if (!ipf->filemon) return;
1324   filemon_method_stopfile(ipf, ipf->filemon);
1325   free(ipf->filemon);
1326   ipf->filemon= 0;
1327 }
1328
1329 static void filemon_callback(InputFile *ipf) {
1330   ipf->readable_callback(ipf->readable_callback_user);
1331 }
1332
1333 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1334                                      void *user) {
1335   InputFile *ipf= user;
1336   return ipf->readable_callback(ipf->readable_callback_user);
1337 }
1338
1339 static void on_cancel(struct oop_readable *rable) {
1340   InputFile *ipf= (void*)rable;
1341
1342   if (ipf->filemon) filemon_stopfile(ipf);
1343   loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1344   ipf->readable_callback= 0;
1345 }
1346
1347 static void tailing_queue_readable(InputFile *ipf) {
1348   /* lifetime of ipf here is OK because destruction will cause
1349    * on_cancel which will cancel this callback */
1350   loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1351 }
1352
1353 static int tailing_on_readable(struct oop_readable *rable,
1354                                 oop_readable_call *cb, void *user) {
1355   InputFile *ipf= (void*)rable;
1356
1357   tailing_on_cancel(rable);
1358   ipf->readable_callback= cb;
1359   ipf->readable_callback_user= user;
1360   filemon_startfile(ipf);
1361
1362   tailing_queue_readable(ipf);
1363   return 0;
1364 }
1365
1366 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1367                                 size_t length) {
1368   InputFile *ipf= (void*)rable;
1369   for (;;) {
1370     ssize_t r= read(ipf->fd, buffer, length);
1371     if (r==-1) {
1372       if (errno==EINTR) continue;
1373       return r;
1374     }
1375     if (!r) {
1376       if (ipf==main_input_file) {
1377         errno=EAGAIN;
1378         return -1;
1379       } else if (ipf==flushing_input_file) {
1380         assert(ipf->fd>=0);
1381         assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1382       } else if (ipf==backlog_input_file) {
1383         assert(ipf->fd>=0);
1384       } else {
1385         abort();
1386       }
1387     }
1388     return r;
1389   }
1390 }
1391
1392 /*---------- filemon implemented with inotify ----------*/
1393
1394 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1395 #define HAVE_FILEMON
1396
1397 #include <linux/inotify.h>
1398
1399 static int filemon_inotify_fd;
1400 static int filemon_inotify_wdmax;
1401 static InputFile **filemon_inotify_wd2ipf;
1402
1403 typedef struct Filemon_Perfile {
1404   int wd;
1405 } Filemon_Inotify_Perfile;
1406
1407 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1408   int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1409   if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1410
1411   if (wd >= filemon_inotify_wdmax) {
1412     int newmax= wd+2;
1413     filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1414                                  sizeof(*filemon_inotify_wd2ipf) * newmax);
1415     memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1416            sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1417     filemon_inotify_wdmax= newmax;
1418   }
1419
1420   assert(!filemon_inotify_wd2ipf[wd]);
1421   filemon_inotify_wd2ipf[wd]= ipf;
1422
1423   debug("filemon inotify startfile %p wd=%d wdmax=%d",
1424         ipf, wd, filemon_inotify_wdmax);
1425
1426   pf->wd= wd;
1427 }
1428
1429 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1430   int wd= pf->wd;
1431   debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1432   int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1433   if (r) sysdie("inotify_rm_watch");
1434   filemon_inotify_wd2ipf[wd]= 0;
1435 }
1436
1437 static void *filemon_inotify_readable(oop_source *lp, int fd,
1438                                       oop_event e, void *u) {
1439   struct inotify_event iev;
1440   for (;;) {
1441     int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1442     if (r==-1) {
1443       if (errno==EAGAIN) break;
1444       sysdie("read from inotify master");
1445     } else if (r==sizeof(iev)) {
1446       assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1447     } else {
1448       die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1449     }
1450     InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1451     debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1452     filemon_callback(ipf);
1453   }
1454   return OOP_CONTINUE;
1455 }
1456
1457 static int filemon_method_init(void) {
1458   filemon_inotify_fd= inotify_init();
1459   if (filemon_inotify_fd<0) {
1460     syswarn("could not initialise inotify: inotify_init failed");
1461     return 0;
1462   }
1463   set nonblock;
1464   loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1465
1466   debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1467   return 1;
1468 }
1469
1470 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1471
1472 /*---------- filemon dummy implementation ----------*/
1473
1474 #if !defined(HAVE_FILEMON)
1475
1476 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1477
1478 static int filemon_method_init(void) { return 0; }
1479 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1480 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1481
1482 #endif /* !HAVE_FILEMON */
1483
1484 /*---------- interface to start and stop an input file ----------*/
1485
1486 static const oop_rd_style feedfile_rdstyle= {
1487   OOP_RD_DELIM_STRIP, '\n',
1488   OOP_RD_NUL_FORBID,
1489   OOP_RD_SHORTREC_EOF,
1490 };
1491
1492 static void inputfile_tailing_start(InputFile *ipf) {
1493   assert(!ipf->fd);
1494   ipf->readable->on_readable= tailing_on_readable;
1495   ipf->readable->on_cancel=   tailing_on_cancel;
1496   ipf->readable->try_read=    tailing_try_read;
1497   ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1498   ipf->readable->delete_kill= 0;
1499
1500   ipf->readable_callback= 0;
1501   ipf->readable_callback_user= 0;
1502
1503   ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1504   assert(ipf->fd);
1505
1506   int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1507                      feedfile_got_article,ipf, feedfile_problem,ipf);
1508   if (r) sysdie("unable start reading feedfile %s",ipf->path);
1509 }
1510
1511 static void inputfile_tailing_stop(InputFile *ipf) {
1512   assert(ipf->fd);
1513   oop_rd_cancel(ipf->rd);
1514   oop_rd_delete(ipf->rd);
1515   ipf->rd= 0;
1516   assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1517 }
1518
1519
1520 /*========== interaction with innd - state machine ==========*/
1521
1522 /* See official state diagram at top of file.  We implement
1523  * this as follows:
1524  * -8<-
1525
1526             .=======.
1527             ||START||
1528             `======='
1529                 |
1530                 | open F
1531                 |
1532                 |    F ENOENT
1533                 |`---------------------------------------------------.
1534       F OPEN OK |                                                    |
1535                 |`---------------- - - -                             |
1536        D ENOENT |       D EXISTS   see OVERALL STATES diagram        |
1537                 |                  for full startup logic            |
1538      ,--------->|                                                    |
1539      |          V                                                    |
1540      |     ============                                       try to |
1541      |      NORMAL                                            open D |
1542      |     [Normal]                                                  |
1543      |      main F tail                                              |
1544      |     ============                                              V
1545      |          |                                                    |
1546      |          | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT            |
1547      ^          | hardlink F to D                                    |
1548      |     [Hardlinked]                                              |
1549      |          | unlink F                                           |
1550      |          | our handle onto F is now onto D                    |
1551      |     [Moved]                                                   |
1552      |          |                                                    |
1553      |          |<-------------------<---------------------<---------+
1554      |          |                                                    |
1555      |          | spawn inndcomm flush                               |
1556      |          V                                                    |
1557      |     ==================                                        |
1558      |      FLUSHING[-ABSENT]                                        |
1559      |     [Flushing]                                                |
1560      |     main D tail/none                                          |
1561      |     ==================                                        |
1562      |          |                                                    |
1563      |          |   INNDCOMM FLUSH FAILS                             ^
1564      |          |`----------------------->----------.                |
1565      |          |                                   |                |
1566      |          |   NO SUCH SITE                    V                |
1567      ^          |`--------------->----.         ==================== |
1568      |          |                      \        FLUSHFAILED[-ABSENT] |
1569      |          |                       \         [Moved]            |
1570      |          | FLUSH OK               \       main D tail/none    |
1571      |          | open F                  \     ==================== |
1572      |          |                          \        |                |
1573      |          |                           \       | TIME TO RETRY  |
1574      |          |`------->----.     ,---<---'\      `----------------'
1575      |          |    D NONE   |     | D NONE  `----.
1576      |          V             |     |              V
1577      |     =============      V     V             ============
1578      |      SEPARATED-1       |     |              DROPPING-1
1579      |      flsh->fd>=0       |     |              flsh->fd>=0
1580      |     [Separated]        |     |             [Dropping]
1581      |      main F idle       |     |              main none
1582      |      old D tail        |     |              old D tail
1583      |     =============      |     |             ============
1584      |          |             |     | install       |
1585      ^          | EOF ON D    |     |  defer        | EOF ON D
1586      |          V             |     |               V
1587      |     ===============    |     |             ===============
1588      |      SEPARATED-2       |     |              DROPPING-2
1589      |      flsh->fd==-1      |     V              flsh->fd==-1
1590      |     [Finishing]        |     |             [Dropping]
1591      |      main F tail       |     `.             main none
1592      |      old D closed      |       `.           old D closed
1593      |     ===============    V         `.        ===============
1594      |          |                         `.          |
1595      |          | ALL D PROCESSED           `.        | ALL D PROCESSED
1596      |          V install defer as backlog    `.      | install defer
1597      ^          | close D                       `.    | close D
1598      |          | unlink D                        `.  | unlink D
1599      |          |                                  |  |
1600      |          |                                  V  V
1601      `----------'                               ==============
1602                                                  DROPPED
1603                                                 [Dropped]
1604                                                  main none
1605                                                  old none
1606                                                  some backlog
1607                                                 ==============
1608                                                       |
1609                                                       | ALL BACKLOG DONE
1610                                                       |
1611                                                       | unlink lock
1612                                                       | exit
1613                                                       V
1614                                                   ==========
1615                                                    (ESRCH)
1616                                                   [Droppped]
1617                                                   ==========
1618  * ->8-
1619  */
1620
1621 static void statemc_init(void) {
1622   struct stat stab, stabf;
1623
1624   path_lock=        xasprintf("%s_lock",      feedfile);
1625   path_flushing=    xasprintf("%s_flushing",  feedfile);
1626   path_defer=       xasprintf("%s_defer",     feedfile);
1627   globpat_backlog=  xasprintf("%s_backlog*",  feedfile);
1628
1629   for (;;) {
1630     int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1631     if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1632
1633     struct flock fl;
1634     memset(&fl,0,sizeof(fl));
1635     fl.l_type= F_WRLCK;
1636     fl.l_whence= SEEK_SET;
1637     r= fcntl(lockfd, F_SETLK, &fl);
1638     if (r==-1) {
1639       if (errno==EACCES || errno==EAGAIN) {
1640         if (quiet_multiple) exit(0);
1641         fatal("another duct holds the lockfile");
1642       }
1643       sysdie("fcntl F_SETLK lockfile %s", path_lock);
1644     }
1645
1646     xfstat_isreg(lockfd, &stabf, "lockfile");
1647     int lock_noent;
1648     xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1649
1650     if (!lock_noent && samefile(&stab, &stabf))
1651       break;
1652
1653     if (close(lockfd))
1654       sysdie("could not close stale lockfile %s", path_lock);
1655   }
1656   debug("startup: locked");
1657
1658   search_backlog_file();
1659
1660   int defer_noent;
1661   xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1662   if (defer_noent) {
1663     debug("startup: ductdefer ENOENT");
1664   } else {
1665     debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1666     switch (stab.st_nlink==1) {
1667     case 1:
1668       open_defer(); /* so that we will later close it and rename it */
1669       break;
1670     case 2:
1671       xunlink(path_defer, "stale defer file link"
1672               " (presumably hardlink to backlog file)");
1673       break;
1674     default:
1675       die("defer file %s has unexpected link count %d",
1676           path_defer, stab.st_nlink);
1677     }
1678   }
1679
1680   struct stat stab_f, stab_d;
1681   int noent_f;
1682
1683   InputFile *file_d= open_input_file(path_flushing);
1684   if (file_d) xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1685
1686   xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1687
1688   if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1689     debug("startup: F==D => Hardlinked");
1690     xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1691     noent_f= 1;
1692   }
1693
1694   if (noent_f) {
1695     debug("startup: F ENOENT => Moved");
1696     if (file_d) startup_set_input_file(file_d);
1697     spawn_inndcomm_flush("feedfile missing at startup");
1698     /* => Flushing, sms:=FLUSHING */
1699   } else {
1700     if (file_d) {
1701       debug("startup: F!=D => Separated");
1702       startup_set_input_file(file_d);
1703       SMS(SEPARATED, 0, "found both old and current feed files");
1704     } else {
1705       debug("startup: F exists, D ENOENT => Normal");
1706       FILE *file_f= open_input_file(feedfile);
1707       if (!file_f) die("feed file vanished during startup");
1708       startup_set_input_file(file_f);
1709       SMS(NORMAL, flushfail_retry_periods, "normal startup");
1710     }
1711   }
1712 }
1713
1714 static void statemc_period_poll(void) {
1715   if (!sm_period_counter) return;
1716   sm_period_counter--;
1717   assert(sm_period_counter>=0);
1718
1719   if (sm_period_counter) return;
1720   switch (sms) {
1721   case sm_NORMAL:
1722     statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1723     break;
1724   case sm_FLUSHFAILED:
1725     spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1726     break;
1727   default:
1728     abort();
1729   }
1730 }
1731
1732 static void startup_set_input_file(InputFile *f) {
1733   assert(!main_input_file);
1734   main_input_file= f;
1735   inputfile_tailing_start(f);
1736 }
1737
1738 static int inputfile_is_done(InputFile *ipf) {
1739   if (!ipf) return 0;
1740   if (ipf->inprogress) return 0; /* new article in the meantime */
1741   if (ipf->fd >= 0); return 0; /* not had EOF */
1742   return 1;
1743 }
1744
1745 static void notice_processed(InputFile *ipf, const char *what,
1746                              const char *spec) {
1747 #define RCI_NOTHING(x) /* nothing */
1748 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
1749 #define RCI_TRIPLE_VALS(x) RCI_TRIPLE_VALS_BASE(ipf->counts, .x)
1750
1751   info("processed %s%s offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
1752        RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
1753        ,
1754        what,spec,
1755        ipf->counts[art_Unchecked].sent + ipf->counts[art_Unsolicited].sent
1756        , ipf->counts[art_Unchecked].sent, ipf->counts[art_Unsolicited].sent,
1757        ipf->counts[art_Wanted].accepted + ipf->counts[art_Unsolicited].accepted
1758        ,ipf->counts[art_Wanted].accepted,ipf->counts[art_Unsolicited].accepted
1759        RESULT_COUNTS(RCI_NOTHING,  RCI_TRIPLE_VALS)
1760        );
1761 }
1762
1763 static void statemc_check_backlog_done(void) {
1764   InputFile *ipf= backlog_input_file();
1765   if (!inputfile_is_done(ipf)) return;
1766
1767   const char *slash= strrchr(ipf->path, "/");
1768   const char *leaf= slash ? slash+1 : ipf->path;
1769   const char *under= strchr(slash, "_");
1770   const char *rest= under ? under+1 : leaf;
1771   if (!strncmp(rest,"backlog",7)) rest += 7;
1772   notice_processed(ipf,"backlog:",rest);
1773   
1774   close_input_file(ipf);
1775   if (unlink(ipf->path)) {
1776     if (errno != ENOENT)
1777       sysdie("could not unlink processed backlog file %s", ipf->path);
1778     warn("backlog file %s vanished while we were reading it"
1779          " so we couldn't remove it (but it's done now, anyway)",
1780          ipf->path);
1781   }
1782   free(ipf);
1783   backlog_input_file= 0;
1784   search_backlog_file();
1785   return;
1786 }
1787
1788 static void statemc_check_flushing_done(void) {
1789   InputFile *ipf= flushing_input_file;
1790   if (!inputfile_is_done(ipf)) return;
1791
1792   assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1793
1794   notice_processed(ipf,"feedfile",0);
1795
1796   close_defer();
1797
1798   xunlink(path_flushing, "old flushing file");
1799
1800   close_input_file(flushing_input_file);
1801   free(flushing_input_file);
1802   flushing_input_file= 0;
1803
1804   if (sms==sm_SEPARATED) {
1805     notice("flush complete");
1806     SMS(NORMAL, 0, "flush complete");
1807   } else if (sms==sm_DROPPING) {
1808     SMS(DROPPED, 0, "old flush complete");
1809     search_backlog_file();
1810     notice("feed dropped, but will continue until backlog is finished");
1811   }
1812 }
1813
1814 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
1815                                       void *u) {
1816   assert(!inputfile_is_done(main_input_file));
1817   statemc_check_flushing_done();
1818   statemc_check_backlog_done();
1819   return OOP_CONTINUE;
1820 }
1821
1822 static void queue_check_input_done(void) {
1823   loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
1824 }
1825
1826 static void statemc_setstate(StateMachineState newsms, int periods,
1827                              const char *forlog, const char *why) {
1828   sms= newsms;
1829   sm_period_counter= periods;
1830
1831   const char *xtra= "";
1832   switch (sms) {
1833   case sm_FLUSHING: sm_FLUSHFAILED:
1834     if (!main_input_file) xtra= "-ABSENT";
1835     break;
1836   case sm_SEPARATED: case sm_DROPPING:
1837     xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
1838     break;
1839   default:;
1840   }
1841
1842   if (periods) {
1843     info("%s%s[%d] %s",forlog,xtra,periods,why);
1844   } else {
1845     info("%s%s %s",forlog,xtra,why);
1846   }
1847 }
1848
1849 /*---------- defer and backlog files ----------*/
1850
1851 static void open_defer(void) {
1852   struct stat stab;
1853
1854   if (defer) return;
1855
1856   defer= fopen(path_defer, "a+");
1857   if (!defer) sysfatal("could not open defer file %s", path_defer);
1858
1859   /* truncate away any half-written records */
1860
1861   xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1862
1863   if (stab.st_size > LONG_MAX)
1864     die("defer file %s size is far too large", path_defer);
1865
1866   if (!stab.st_size)
1867     return;
1868
1869   long orgsize= stab.st_size;
1870   long truncto= stab.st_size;
1871   for (;;) {
1872     if (!truncto) break; /* was only (if anything) one half-truncated record */
1873     if (fseek(defer, truncto-1, SEEK_SET) < 0)
1874       sysdie("seek in defer file %s while truncating partial", path_defer);
1875
1876     r= getc(defer);
1877     if (r==EOF) {
1878       if (ferror(defer))
1879         sysdie("failed read from defer file %s", path_defer);
1880       else
1881         die("defer file %s shrank while we were checking it!", path_defer);
1882     }
1883     if (r=='\n') break;
1884     truncto--;
1885   }
1886
1887   if (stab.st_size != truncto) {
1888     warn("truncating half-record at end of defer file %s -"
1889          " shrinking by %ld bytes from %ld to %ld",
1890          path_defer, orgsize - truncto, orgsize, truncto);
1891
1892     if (fflush(defer))
1893       sysfatal("could not flush defer file %s", path_defer);
1894     if (ftruncate(fileno(defer), truncto))
1895       sysdie("could not truncate defer file %s", path_defer);
1896
1897   } else {
1898     info("continuing existing defer file %s (%ld bytes)",
1899          path_defer, orgsize);
1900   }
1901   if (fseek(defer, truncto, SEEK_SET))
1902     sysdie("could not seek to new end of defer file %s", path_defer);
1903 }
1904
1905 static void close_defer(void) {
1906   if (!defer)
1907     return;
1908
1909   xfstat(fileno(defer), &stab, "defer file");
1910
1911   if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1912   defer= 0;
1913
1914   char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1915                            (unsigned long)now.tv_sec,
1916                            (unsigned long)stab.st_ino);
1917   if (link(path_defer, path_backlog))
1918     sysfatal("could not install defer file %s as backlog file %s",
1919            path_defer, backlog);
1920   if (unlink(path_defer))
1921     sysdie("could not unlink old defer link %s to backlog file %s",
1922            path_defer, backlog);
1923
1924   if (until_backlog_nextscan < 0 ||
1925       until_backlog_nextscan > backlog_retry_minperiods + 1)
1926     until_backlog_nextscan= backlog_retry_minperiods + 1;
1927 }
1928
1929 static void poll_backlog_file(void) {
1930   if (until_backlog_nextscan < 0) return;
1931   if (until_backlog_nextscan-- > 0) return;
1932   search_backlog_file();
1933 }
1934
1935 static void search_backlog_file(void) {
1936   /* returns non-0 iff there are any backlog files */
1937
1938   glob_t gl;
1939   int r;
1940   struct stat stab;
1941   const char *oldest_path=0;
1942   time_t oldest_mtime, now;
1943
1944   if (backlog_input_file) return 3;
1945
1946  try_again:
1947
1948   r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
1949
1950   switch (r) {
1951   case GLOB_ABORTED:
1952     sysdie("failed to expand backlog pattern %s", globpat_backlog);
1953   case GLOB_NOSPACE:
1954     die("out of memory expanding backlog pattern %s", globpat_backlog);
1955   case 0:
1956     for (i=0; i<gl.gl_pathc; i++) {
1957       const char *path= gl.gl_pathv[i];
1958
1959       if (strchr(path,'#') || strchr(path,'~')) {
1960         debug("backlog file search skipping %s", path);
1961         continue;
1962       }
1963       r= stat(path, &stab);
1964       if (r) {
1965         syswarn("failed to stat backlog file %s", path);
1966         continue;
1967       }
1968       if (!S_ISREG(stab.st_mode)) {
1969         warn("backlog file %s is not a plain file (or link to one)", path);
1970         continue;
1971       }
1972       if (!oldest_path || stab.st_mtime < oldest_mtime) {
1973         oldest_path= path;
1974         oldest_mtime= stab.st_mtime;
1975       }
1976     }
1977   case GLOB_NOMATCH: /* fall through */
1978     break;
1979   default:
1980     sysdie("glob expansion of backlog pattern %s gave unexpected"
1981            " nonzero (error?) return value %d", globpat_backlog, r);
1982   }
1983
1984   globfree(&gl);
1985
1986   if (!oldest_path) {
1987     debug("backlog scan: none");
1988
1989     if (sms==sm_DROPPED) {
1990       notice("feed dropped and our work is complete");
1991       xunlink(path_lock, "lockfile for old feed");
1992       exit(0);
1993     }
1994     until_backlog_nextscan= backlog_spontaneous_rescan_periods;
1995     return 0;
1996   }
1997
1998   now= time();  if (now==-1) sysdie("time(2) failed");
1999   double age= difftime(now, oldest_mtime);
2000   long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
2001
2002   if (age_deficiency <= 0) {
2003     debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2004           age, age_deficiency, oldest_path);
2005
2006     backlog_input_file= open_input_file(oldest_path);
2007     if (!backlog_input_file) {
2008       warn("backlog file %s vanished as we opened it", backlog_input_file);
2009       goto try_again;
2010     }
2011     inputfile_tailing_start(backlog_input_file);
2012     until_backlog_nextscan= -1;
2013     return 1;
2014   }
2015
2016   until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
2017
2018   if (backlog_spontaneous_rescan_periods >= 0 &&
2019       until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2020     until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2021
2022   debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2023         age, age_deficiency, until_backlog_nextscan, oldest_path);
2024   return 2;
2025 }
2026
2027 /*========== flushing the feed ==========*/
2028
2029 static pid_t inndcomm_child;
2030
2031 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2032   assert(inndcomm_child);
2033   int status= xwaitpid(&inndcomm_child, "inndcomm");
2034   loop->cancel_fd(fd);
2035   close(fd);
2036
2037   assert(!flushing_input_file);
2038
2039   if (WIFEXITED(status)) {
2040     switch (WEXITSTATUS(status)) {
2041
2042     case INNDCOMMCHILD_ESTATUS_FAIL:
2043       goto failed;
2044
2045     case INNDCOMMCHILD_ESTATUS_NONESUCH:
2046       warn("feed has been dropped by innd, finishing up");
2047       flushing_input_file= main_input_file;
2048       tailing_queue_readable(flushing_input_file);
2049         /* we probably previously returned EAGAIN from our fake read method
2050          * when in fact we were at EOF, so signal another readable event
2051          * so we actually see the EOF */
2052
2053       main_input_file= 0;
2054
2055       if (flushing_input_file) {
2056         SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2057       } else {
2058         close_defer();
2059         SMS(DROPPED, 0, "feed dropped by innd");
2060         search_backlog_file();
2061       }
2062       return OOP_CONTINUE;
2063
2064     case 0:
2065       /* as above */
2066       flushing_input_file= main_input_file;
2067       tailing_queue_readable(flushing_input_file);
2068
2069       main_input_file= open_input_file(feedfile);
2070       if (!main_input_file)
2071         die("flush succeeded but feedfile %s does not exist!", feedfile);
2072
2073       if (flushing_input_file) {
2074         SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2075       } else {
2076         close_defer();
2077         SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2078       }
2079       return OOP_CONTINUE;
2080
2081     default:
2082       goto unexpected_exitstatus;
2083
2084     }
2085   } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2086     warn("flush timed out trying to talk to innd");
2087     goto failed;
2088   } else {
2089   unexpected_exitstatus:
2090     report_child_status("inndcomm child", status);
2091   }
2092
2093  failed:
2094   SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2095 }
2096
2097 static void inndcommfail(const char *what) {
2098   syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2099   exit(INNDCOMMCHILD_ESTATUS_FAIL);
2100 }
2101
2102 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2103   int pipefds[2];
2104
2105   notice("flushing %s",why);
2106
2107   assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2108   assert(!inndcomm_child);
2109
2110   if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2111
2112   inndcomm_child= xfork();
2113
2114   if (!inndcomm_child) {
2115     static char flushargv[2]= { sitename, 0 };
2116     char *reply;
2117
2118     close(pipefds[0]);
2119
2120     alarm(inndcomm_flush_timeout);
2121     r= ICCopen();                         if (r)   inndcommfail("connect");
2122     r= ICCcommand('f',flushargv,&reply);  if (r<0) inndcommfail("transmit");
2123     if (!r) exit(0); /* yay! */
2124
2125     if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2126     syswarn("innd ctlinnd flush failed: innd said %s", reply);
2127     exit(INNDCOMMCHILD_ESTATUS_FAIL);
2128   }
2129
2130   close(pipefds[1]);
2131   int sentinel_fd= pipefds[0];
2132   on_fd_read_except(sentinel_fd, inndcomm_event);
2133
2134   SMS(FLUSHING, 0, why);
2135 }
2136
2137 /*========== main program ==========*/
2138
2139 static void postfork_inputfile(InputFile *ipf) {
2140   if (!ipf) return;
2141   assert(ipf->fd >= 0);
2142   close(ipf->fd);
2143   ipf->fd= -1;
2144 }
2145
2146 static void postfork_conns(Connection *conn) {
2147   while (conn) {
2148     close(conn->fd);
2149     conn= conn->next;
2150   }
2151 }
2152
2153 static void postfork_stdio(FILE *f) {
2154   /* we have no stdio streams that are buffered long-term */
2155   if (f) fclose(f);
2156 }
2157
2158 static void postfork(const char *what) {
2159   if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2160     sysdie("%s child: failed to reset SIGPIPE");
2161
2162   postfork_inputfile(main_input_file);
2163   postfork_inputfile(flushing_input_file);
2164   postfork_conns(idle.head);
2165   postfork_conns(working.head);
2166   postfork_conns(full.head);
2167   postfork_stdio(defer);
2168 }
2169
2170 #define EVERY(what, interval, body)                                          \
2171   static const struct timeval what##_timeout = { 5, 0 };                     \
2172   static void what##_schedule(void);                                         \
2173   static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2174     { body }                                                                 \
2175     what##_schedule();                                                       \
2176   }                                                                          \
2177   static void what##_schedule(void) {                                        \
2178     loop->on_time(loop, what##_timeout, what##_timedout, 0);                 \
2179   }
2180
2181 EVERY(filepoll, {5,0}, {
2182   if (main_input_file && main_input_file->readable_callback)
2183     filemon_callback(main_input_file);
2184 });
2185
2186 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s"  \
2187 #define DEBUG_IPF(sh)                                           \
2188   wh##_input_file, debug_ipf_path(wh##_input_file),             \
2189   wh##_input_file->inprogress, (long)wh##_input_file->offset,   \
2190   wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2191 static const char *debug_ipf_path(InputFile *ipf) {
2192   char *slash= strrchr(ipf->path,'/');
2193   return slash ? slash+1 : ipf->path;
2194 }
2195
2196 EVERY(period, {PERIOD_SECONDS,0}, {
2197   debug("PERIOD"
2198         " sms=%s[%d] queue=%d connect_delay=%d"
2199         " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_FMT(flushing)
2200         " conns idle=%d working=%d full=%d"
2201         " children connecting=%ld inndcomm_child"
2202         ,
2203         sms_names[sms], sm_period_counter, queue.count, connect_delay,
2204         DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2205         idle.count, working.count, full.count,
2206         (long)connecting_child, (long)inndcomm_child
2207         );
2208
2209   if (connect_delay) connect_delay--;
2210
2211   poll_backlog_file();
2212   if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2213   statemc_period_poll();
2214   check_master_queue();
2215 });
2216
2217
2218 /*========== option parsing ==========*/
2219
2220 enum OptFlags {
2221   of_seconds= 001000u;
2222   of_boolean= 002000u;
2223 };
2224
2225 typedef struct Option Option;
2226 typedef void OptionParser(const Option*, const char *val);
2227
2228 struct Option {
2229   int short;
2230   const char *long;
2231   void *store;
2232   OptionParser *fn;
2233   int noarg;
2234 };
2235
2236 void op_integer(const Option *o, const char *val) {
2237   char *ep;
2238   errno= 0;
2239   unsigned long ul= strtoul(val,&ep,10);
2240   if (*ep || ep==val || errno || ul>INT_MAX)
2241     badusage("bad integer value for %s",o->long);
2242   int *store= o->store;
2243   *store= ul;
2244 }
2245
2246 void op_double(const Option *o, const char *val) {
2247   int *store= o->store;
2248   char *ep;
2249   errno= 0;
2250   *store= strtod(val, &ep);
2251   if (*ep || ep==val || errno)
2252     badusage("bad floating point value for %s",o->long);
2253 }
2254
2255 void op_string(const Option *o, const char *val) {
2256   char **store= o->store;
2257   free(*store);
2258   *store= val;
2259 }
2260
2261 void op_seconds(const Option *o, const char *val) {
2262   int *store= o->store;
2263   char *ep;
2264
2265   double v= strtod(val,&ep);
2266   if (ep==val) badusage("bad time/duration value for %s",o->long);
2267
2268   if (!*ep || !strcmp(ep,"s")) unit= 1;
2269   else if (!strcmp(ep,"m")) unit= 60;
2270   else if (!strcmp(ep,"h")) unit= 3600;
2271   else if (!strcmp(ep,"d")) unit= 86400;
2272   else badusage("bad units %s for time/duration value for %s",ep,o->long);
2273
2274   v *= unit;
2275   v= ceil(v);
2276   if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2277   *store= v;
2278 }
2279
2280 void op_periods_rndup(const Option *o, const char *val) {
2281   int *store= o->store;
2282   op_seconds(o,val);
2283   *store += PERIOD_SECONDS-1;
2284   *store /= PERIOD_SECONDS;
2285 }
2286
2287 void op_periods_booltrue(const Option *o, const char *val) {
2288   int *store= o->store;
2289   *store= 1;
2290 }
2291 void op_periods_boolfalse(const Option *o, const char *val) {
2292   int *store= o->store;
2293   *store= 0;
2294 }
2295
2296 static const Option options[]= {
2297 {'f',"feedfile",              &feedfile,                 op_string           },
2298 {'q',"quiet-multiple",        &quiet_multiple,           op_booltrue,  1     },
2299
2300 { 0, "max-connections",       &max_connections           op_integer          },
2301 { 0, "max-queue-per-conn",    &max_queue_per_conn        op_integer          },
2302
2303
2304 { 0, "streaming",             &try_stream,               op_booltrue,  1     },
2305 { 0, "no-streaming",          &try_stream,               op_boolfalse, 1     },
2306 {'P',"port",                  &port                      op_integer          },
2307 { 0, "inndconf",              &inndconffile,             op_string           },
2308 {'d',"daemon",                &become_daemon,            op_booltrue,  1     },
2309 { 0, "no-daemon",             &become_daemon,            op_boolfalse, 1     },
2310
2311 { 0, "no-check-proportion",   &nocheck_thresh_pct,       op_double           },
2312 { 0, "no-check-filter",       &nocheck_decay_articles,   op_double           },
2313
2314 { 0, "reconnect-interval",    &reconnect_delay_periods,  op_periods_rndup    },
2315 { 0, "flush-retry-interval",  &flushfail_retry_periods,  op_periods_rndup    },
2316 { 0, "connection-timeout",    &connection_timeout,       op_seconds          },
2317 { 0, "inndcomm-timeout",      &inndcomm_flush_timeout,   op_seconds          },
2318 };
2319
2320 int main(int argc, char **argv) {
2321   const char *arg;
2322
2323   for (;;) {
2324     arg= *++argv;
2325     if (!arg) break;
2326     if (*arg != '-') break;
2327     if (!strcmp(arg,"--")) { arg= *++argv; break; }
2328     int a;
2329     while ((a= *++arg)) {
2330       const Option *o;
2331       if (a=='-') {
2332         arg++;
2333         char *equals= strchr(arg,'=');
2334         int len= equals ? (equals - arg) : strlen(arg);
2335         for (o=options; o->long; o++)
2336           if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2337             goto found_long;
2338         badusage("unknown long option --%s",arg);
2339       found_long:
2340         if (o->noarg) {
2341           if (equals) badusage("option --%s does not take a value",o->long);
2342           arg= 0;
2343         } else if (equals) {
2344           arg= equals+1;
2345         } else {
2346           arg= *++argv;
2347           if (!arg) badusage("option --%s needs a value",o->long);
2348         }
2349         o->fn(o, arg);
2350         break; /* eaten the whole argument now */
2351       }
2352       for (o=options; o->long; o++)
2353         if (a == o->short)
2354           goto found_short;
2355       badusage("unknown short option -%c",a);
2356     found_short:
2357       if (o->noarg) {
2358         o->fn(o,0);
2359       } else {
2360         if (!*++arg) {
2361           arg= *++argv;
2362           if (!arg) badusage("option -%c needs a value",o->short);
2363         }
2364         o->fn(o,arg);
2365         break; /* eaten the whole argument now */
2366       }
2367     }
2368   }
2369
2370   if (!arg) badusage("need site name argument");
2371   sitename= arg;
2372
2373   if ((arg= *++argv))
2374     remote_host= arg;
2375
2376   if (*++argv) badusage("too many non-option arguments");
2377
2378   if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2379     badusage("nocheck threshold percentage must be between 0..100");
2380   nocheck_thresh= nocheck_thresh_pct * 0.01;
2381
2382   if (nocheck_decay_articles < 0.1)
2383     badusage("nocheck decay articles must be at least 0.1");
2384   nocheck_decay= 1 - 1/nocheck_decay_articles;
2385
2386   if (!pathoutgoing)
2387     pathoutgoing= innconf->pathoutgoing;
2388   innconf_read(inndconffile);
2389
2390   if (!feedfile)
2391     feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2392   else if (!feedfile[0])
2393     badusage("feed filename must be nonempty");
2394   else if (feedfile[strlen(feedfile)-1]=='/')
2395     feedfile= xasprintf("%s%s",feedfile,sitename);
2396
2397   const char *feedfile_forbidden= "?*[~#";
2398   int c;
2399   while ((c= *feedfile_forbidden++))
2400     if (strchr(feedfile, c))
2401       badusage("feed filename may not contain metacharacter %c",c);
2402
2403   loop= oop_sys_new();
2404   if (!loop) sysdie("could not create liboop event loop");
2405
2406   if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2407     sysdie("could not ignore SIGPIPE");
2408
2409   if (become_daemon) {
2410     for (i=3; i<255; i++)
2411       /* do this now before we open syslog, etc. */
2412       close(i);
2413     openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2414
2415     int null= open("/dev/null",O_RDWR);
2416     if (null<0) sysdie("failed to open /dev/null");
2417     dup2(null,0);
2418     dup2(null,1);
2419     dup2(null,2);
2420     close(null);
2421
2422     pid_t child1= xfork("daemonise first fork");
2423     if (child1) _exit(0);
2424
2425     pid_t sid= setsid();
2426     if (sid != child1) sysdie("setsid failed");
2427
2428     pid_t child2= xfork("daemonise second fork");
2429     if (child2) _exit(0);
2430   }
2431
2432   notice("starting");
2433
2434   if (!filemon_init()) {
2435     warn("no file monitoring available, polling");
2436     filepoll_schedule();
2437   }
2438
2439   period_schedule();
2440
2441   statemc_init();
2442
2443   loop->execute.
2444 }