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