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