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