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