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