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