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