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