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