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