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