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