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