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