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