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