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