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