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