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