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