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