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