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