chiark / gitweb /
fixes
[innduct.git] / backends / innduct.c
1 /*
2  * todo
3  *  - actually do something with readable on control master
4  *  - option for realsockdir
5  *  - manpage: document control master stuff
6  *  - manpage: innconf is used for communicating with innd
7  *  - debug this:
8  *      build-lfs/backends/innduct --no-daemon -f `pwd`/fee sit dom
9  */
10
11 /*
12  * Newsfeeds file entries should look like this:
13  *     host.name.of.site[/exclude,exclude,...]\
14  *             :pattern,pattern...[/distribution,distribution...]\
15  *             :Tf,Wnm
16  *             :
17  * or
18  *     sitename[/exclude,exclude,...]\
19  *             :pattern,pattern...[/distribution,distribution...]\
20  *             :Tf,Wnm
21  *             :host.name.of.site
22  *
23  * Four files full of
24  *    token messageid
25  * or might be blanked out
26  *    <spc><spc><spc><spc>....
27  *
28  * F site.name                 main feed file
29  *                                opened/created, then written, by innd
30  *                                read by duct
31  *                                unlinked by duct
32  *                                tokens blanked out by duct when processed
33  *   site.name_lock            lock preventing multiple ducts
34  *                                to hold lock must open,F_SETLK[W]
35  *                                  and then stat to check that locked file
36  *                                  still has name site.name_lock
37  *                                holder of this lock is "duct"
38  *                                (only) lockholder may remove the lockfile
39  * D site.name_flushing        temporary feed file during flush (or crash)
40  *                                hardlink created by duct
41  *                                unlinked by duct
42  *   site.name_defer           431'd articles, still being written,
43  *                                created, written, used by duct
44  *
45  *   site.name_backlog.<date>.<inum>
46  *                             431'd articles, ready for innxmit or duct
47  *                                created (link/mv) by duct
48  *   site.name_backlog<anything-else>  (where <anything-else> does not
49  *                                      contain '#' or '~') eg
50  *   site.name_backlog.manual
51  *                             anything the sysadmin likes (eg, feed files
52  *                             from old feeds to be merged into this one)
53  *                                created (link/mv) by admin
54  *                                may be symlinks (in which case links
55  *                                may be written through, but only links
56  *                                will be removed.
57  *
58  *                             It is safe to remove backlog files manually,
59  *                             if it's desired to throw away the backlog.
60  *
61  * Backlog files are also processed by innduct.  We find the oldest
62  * backlog file which is at least a certain amount old, and feed it
63  * back into our processing.  When every article in it has been read
64  * and processed, we unlink it and look for another backlog file.
65  *
66  * If we don't have a backlog file that we're reading, we close the
67  * defer file that we're writing and make it into a backlog file at
68  * the first convenient opportunity.
69  * -8<-
70
71
72    OVERALL STATES:
73
74                                                                 START
75                                                                   |
76      ,-->--.                                                 check F, D
77      |     |                                                      |
78      |     |                                                      |
79      |     |  <----------------<---------------------------------'|
80      |     |                                       F exists       |
81      |     |                                       D ENOENT       |
82      |     |  duct opens F                                        |
83      |     V                                                      |
84      |  Normal                                                    |
85      |   F: innd writing, duct reading                            |
86      |   D: ENOENT                                                |
87      |     |                                                      |
88      |     |  duct decides time to flush                          |
89      |     |  duct makes hardlink                                 |
90      |     |                                                      |
91      |     V                            <------------------------'|
92      |  Hardlinked                                  F==D          |
93      |   F == D: innd writing, duct reading         both exist    |
94      ^     |                                                      |
95      |     |  duct unlinks F                                      |
96      |     |                        <-----------<-------------<--'|
97      |     |                           open D         F ENOENT    |
98      |     |                           if exists                  |
99      |     |                                                      |
100      |     V                        <---------------------.       |
101      |  Moved                                             |       |
102      |   F: ENOENT                                        |       |
103      |   D: innd writing, duct reading; or ENOENT         |       |
104      |     |                                              |       |
105      |     |  duct requests flush of feed                 |       |
106      |     |   (others can too, harmlessly)               |       |
107      |     V                                              |       |
108      |  Flushing                                          |       |
109      |   F: ENOENT                                        |       |
110      |   D: innd flushing, duct; or ENOENT                |       |
111      |     |                                              |       |
112      |     |   inndcomm flush fails                       |       |
113      |     |`-------------------------->------------------'       |
114      |     |                                                      |
115      |     |   inndcomm reports no such site                      |
116      |     |`---------------------------------------------------- | -.
117      |     |                                                      |  |
118      |     |  innd finishes writing D, creates F                  |  |
119      |     |  inndcomm reports flush successful                   |  |
120      |     |                                                      |  |
121      |     V                                                      |  |
122      |  Separated                                <----------------'  |
123      |   F: innd writing                            F!=D             /
124      |   D: duct reading; or ENOENT                  both exist     /
125      |     |                                                       /
126      |     |  duct gets to the end of D                           /
127      |     |  duct opens F too                                   /
128      |     V                                                    /
129      |  Finishing                                              /
130      |   F: innd writing, duct reading                        |
131      |   D: duct finishing                                    V
132      |     |                                            Dropping
133      |     |  duct finishes processing D                 F: ENOENT
134      |     V  duct unlinks D                             D: duct reading
135      |     |                                                  |
136      `--<--'                                                  | duct finishes
137                                                               |  processing D
138                                                               | duct unlinks D
139                                                               | duct exits
140                                                               V
141                                                         Dropped
142                                                          F: ENOENT
143                                                          D: ENOENT
144                                                          duct not running
145
146    "duct reading" means innduct is reading the file but also
147    overwriting processed tokens.
148
149  * ->8- -^L-
150  *
151  * rune for printing diagrams:
152
153 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
154
155  *
156  */
157
158 /*============================== PROGRAM ==============================*/
159
160 #define _GNU_SOURCE 1
161
162 #include "config.h"
163 #include "storage.h"
164 #include "nntp.h"
165 #include "libinn.h"
166 #include "inndcomm.h"
167
168 #include "inn/list.h"
169 #include "inn/innconf.h"
170
171 #include <sys/uio.h>
172 #include <sys/types.h>
173 #include <sys/wait.h>
174 #include <sys/stat.h>
175 #include <sys/socket.h>
176 #include <sys/un.h>
177 #include <unistd.h>
178 #include <string.h>
179 #include <signal.h>
180 #include <stdio.h>
181 #include <errno.h>
182 #include <syslog.h>
183 #include <fcntl.h>
184 #include <stdarg.h>
185 #include <assert.h>
186 #include <stdlib.h>
187 #include <stddef.h>
188 #include <glob.h>
189 #include <time.h>
190 #include <math.h>
191
192 #include <oop.h>
193 #include <oop-read.h>
194
195 /*----- general definitions, probably best not changed -----*/
196
197 #define CONNCHILD_ESTATUS_STREAM   24
198 #define CONNCHILD_ESTATUS_NOSTREAM 25
199
200 #define INNDCOMMCHILD_ESTATUS_FAIL     26
201 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
202
203 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
204 #define MAX_CONTROL_COMMAND 1000
205
206 #define VA                va_list al;  va_start(al,fmt)
207 #define PRINTF(f,a)       __attribute__((__format__(printf,f,a)))
208 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
209
210 /*----- doubly linked lists -----*/
211
212 #define ISNODE(T)   struct node list_node
213 #define DEFLIST(T)                              \
214    typedef struct {                             \
215      union { struct list li; T *for_type; } u;  \
216      int count;                                 \
217    } T##List
218
219 #define NODE(n) (assert((void*)&(n)->list_node == &(n)), &(n)->list_node)
220
221 #define LIST_CHECKCANHAVENODE(l,n) \
222   ((void)((n) == ((l).u.for_type))) /* just for the type check */
223
224 #define LIST_ADDSOMEHOW(l,n,list_addsomehow)    \
225  ( LIST_CHECKCANHAVENODE(l,n),                  \
226    list_addsomehow(&(l).u.li, NODE((n))),       \
227    (void)(l).count++                            \
228    )
229
230 #define LIST_REMSOMEHOW(l,list_remsomehow)      \
231  ( (typeof((l).u.for_type))                     \
232    ( (l).count                                  \
233      ? ( (l).count--,                           \
234          list_remsomehow(&(l).u.li) )           \
235      : 0                                        \
236      )                                          \
237    )
238
239
240 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
241 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
242 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
243 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
244
245 #define LIST_INIT(l) (list_new(&(l).u.li))
246 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
247 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
248 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
249
250 #define LIST_REMOVE(l,n)                        \
251  ( LIST_CHECKCANHAVENODE(l,n),                  \
252    list_remove(NODE((n))),                      \
253    (void)(l).count--                            \
254    )
255
256 #define LIST_INSERT(l,n,pred)                                   \
257  ( LIST_CHECKCANHAVENODE(l,n),                                  \
258    LIST_CHECKCANHAVENODE(l,pred),                               \
259    list_insert((struct list*)&(l), NODE((n)), NODE((pred))),    \
260    (void)(l).count++                                            \
261    )
262
263 /*----- type predeclarations -----*/
264
265 typedef struct Conn Conn;
266 typedef struct Article Article;
267 typedef struct InputFile InputFile;
268 typedef struct XmitDetails XmitDetails;
269 typedef struct Filemon_Perfile Filemon_Perfile;
270 typedef enum StateMachineState StateMachineState;
271
272 DEFLIST(Conn);
273 DEFLIST(Article);
274
275 /*----- function predeclarations -----*/
276
277 static void conn_maybe_write(Conn *conn);
278 static void conn_make_some_xmits(Conn *conn);
279 static void *conn_write_some_xmits(Conn *conn);
280
281 static void xmit_free(XmitDetails *d);
282
283 #define SMS(newstate, periods, why) \
284    (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
285 static void statemc_setstate(StateMachineState newsms, int periods,
286                              const char *forlog, const char *why);
287
288 static void statemc_start_flush(const char *why); /* Normal => Flushing */
289 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
290
291 static void check_assign_articles(void);
292 static void queue_check_input_done(void);
293
294 static void statemc_check_flushing_done(void);
295 static void statemc_check_backlog_done(void);
296
297 static void postfork(void);
298
299 static void open_defer(void);
300 static void close_defer(void);
301 static void search_backlog_file(void);
302
303 static void inputfile_reading_start(InputFile *ipf);
304 static void inputfile_reading_stop(InputFile *ipf);
305
306 static void filemon_start(InputFile *ipf);
307 static void filemon_stop(InputFile *ipf);
308 static void filemon_callback(InputFile *ipf);
309
310 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
311 static void connfail(Conn *conn, const char *fmt, ...)         PRINTF(2,3);
312
313 static const oop_rd_style peer_rd_style;
314 static oop_rd_call peer_rd_err, peer_rd_ok;
315
316 /*----- configuration options -----*/
317 /* when changing defaults, remember to update the manpage */
318
319 static const char *sitename, *remote_host;
320 static const char *feedfile, *realsockdir="/tmp/innduct.control";
321 static int quiet_multiple=0;
322 static int become_daemon=1;
323 static int try_stream=1;
324 static int port=119;
325 static const char *inndconffile;
326
327 static int max_connections=10;
328 static int max_queue_per_conn=200;
329 static int target_max_feedfile_size=100000;
330 static int period_seconds=60;
331
332 static int connection_setup_timeout=200;
333 static int inndcomm_flush_timeout=100;
334
335 static double nocheck_thresh= 95.0; /* converted from percentage by main */
336 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
337
338 /* all these are initialised to seconds, and converted to periods in main */
339 static int reconnect_delay_periods=1000;
340 static int flushfail_retry_periods=1000;
341 static int backlog_retry_minperiods=50;
342 static int backlog_spontrescan_periods=300;
343 static int spontaneous_flush_periods=100000;
344 static int need_activity_periods=1000;
345
346 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
347 static int max_bad_data_initial= 30;
348   /* in one corrupt 4096-byte block the number of newlines has
349    * mean 16 and standard deviation 3.99.  30 corresponds to z=+3.5 */
350
351
352 /*----- statistics -----*/
353
354 typedef enum {      /* in queue                 in conn->sent             */
355   art_Unchecked,    /*   not checked, not sent    checking                */
356   art_Wanted,       /*   checked, wanted          sent body as requested  */
357   art_Unsolicited,  /*   -                        sent body without check */
358   art_MaxState
359 } ArtState;
360
361 #define RESULT_COUNTS(RCS,RCN)                  \
362   RCS(sent)                                     \
363   RCS(accepted)                                 \
364   RCN(unwanted)                                 \
365   RCN(rejected)                                 \
366   RCN(deferred)                                 \
367   RCN(connretry)
368
369 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
370 #define RCI_TRIPLE_VALS_BASE(counts,x)          \
371        counts[art_Unchecked] x                  \
372        + counts[art_Wanted] x                   \
373        + counts[art_Unsolicited] x,             \
374        counts[art_Unchecked] x                  \
375        , counts[art_Wanted] x                   \
376        , counts[art_Unsolicited] x
377
378 typedef enum {
379 #define RC_INDEX(x) RC_##x,
380   RESULT_COUNTS(RC_INDEX, RC_INDEX)
381   RCI_max
382 } ResultCountIndex;
383
384
385 /*----- transmission buffers -----*/
386
387 #define CONNIOVS 128
388
389 typedef enum {
390   xk_Malloc, xk_Const, xk_Artdata
391 } XmitKind;
392
393 struct XmitDetails {
394   XmitKind kind;
395   union {
396     char *malloc_tofree;
397     ARTHANDLE *sm_art;
398   } info;
399 };
400
401
402 /*----- core operational data structure types -----*/
403
404 struct InputFile {
405   /* This is also an instance of struct oop_readable */
406   struct oop_readable readable; /* first */
407   oop_readable_call *readable_callback;
408   void *readable_callback_user;
409
410   int fd;
411   Filemon_Perfile *filemon;
412
413   oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
414   long inprogress; /* no. of articles read but not processed */
415   off_t offset;
416   int skippinglong;
417
418   int counts[art_MaxState][RCI_max];
419   int readcount_ok, readcount_blank, readcount_err;
420   char path[];
421 };
422
423 struct Article {
424   ISNODE(Article);
425   ArtState state;
426   int midlen;
427   InputFile *ipf;
428   TOKEN token;
429   off_t offset;
430   int blanklen;
431   char messageid[1];
432 };
433
434 #define SMS_LIST(X)                             \
435   X(NORMAL)                                     \
436   X(FLUSHING)                                   \
437   X(FLUSHFAILED)                                \
438   X(SEPARATED)                                  \
439   X(DROPPING)                                   \
440   X(DROPPED)
441
442 enum StateMachineState {
443 #define SMS_DEF_ENUM(s) sm_##s,
444   SMS_LIST(SMS_DEF_ENUM)
445 };
446
447 static const char *sms_names[]= {
448 #define SMS_DEF_NAME(s) #s ,
449   SMS_LIST(SMS_DEF_NAME)
450   0
451 };
452
453 struct Conn {
454   ISNODE(Conn);
455   int fd; /* may be 0, meaning closed (during construction/destruction) */
456   oop_read *rd; /* likewise */
457   int max_queue, stream, quitting;
458   int since_activity; /* periods */
459   ArticleList waiting; /* not yet told peer */
460   ArticleList priority; /* peer says send it now */
461   ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
462   struct iovec xmit[CONNIOVS];
463   XmitDetails xmitd[CONNIOVS];
464   int xmitu;
465 };
466
467
468 /*----- general operational variables -----*/
469
470 /* main initialises */
471 static oop_source *loop;
472 static ConnList conns;
473 static ArticleList queue;
474 static char *path_lock, *path_flushing, *path_defer, *path_control;
475 static char *globpat_backlog;
476 static pid_t self_pid;
477
478 /* statemc_init initialises */
479 static StateMachineState sms;
480 static FILE *defer;
481 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
482 static int sm_period_counter;
483
484 /* initialisation to 0 is good */
485 static int until_connect, until_backlog_nextscan;
486 static double accept_proportion;
487 static int nocheck, nocheck_reported;
488
489 /*========== logging ==========*/
490
491 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
492 static void logcore(int sysloglevel, const char *fmt, ...) {
493   VA;
494   if (become_daemon) {
495     vsyslog(sysloglevel,fmt,al);
496   } else {
497     if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
498     vfprintf(stderr,fmt,al);
499     putc('\n',stderr);
500   }
501   va_end(al);
502 }
503
504 static void logv(int sysloglevel, const char *pfx, int errnoval,
505                  const char *fmt, va_list al) PRINTF(5,0);
506 static void logv(int sysloglevel, const char *pfx, int errnoval,
507                  const char *fmt, va_list al) {
508   char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
509   vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
510   msgbuf[sizeof(msgbuf)-1]= 0;
511
512   if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
513     sysloglevel= LOG_ERR; /* run by wrong user, probably */
514
515   logcore(sysloglevel, "<%s>%s: %s%s%s",
516          sitename, pfx, msgbuf,
517          errnoval>=0 ? ": " : "",
518          errnoval>=0 ? strerror(errnoval) : "");
519 }
520
521 #define diewrap(fn, pfx, sysloglevel, err, estatus)             \
522   static void fn(const char *fmt, ...) NORET_PRINTF(1,2);       \
523   static void fn(const char *fmt, ...) {                        \
524     VA;                                                         \
525     logv(sysloglevel, pfx, err, fmt, al);                       \
526     exit(estatus);                                              \
527   }
528
529 #define logwrap(fn, pfx, sysloglevel, err)              \
530   static void fn(const char *fmt, ...) PRINTF(1,2);     \
531   static void fn(const char *fmt, ...) {                \
532     VA;                                                 \
533     logv(sysloglevel, pfx, err, fmt, al);               \
534     va_end(al);                                         \
535   }
536
537 diewrap(sysdie,   " critical", LOG_CRIT,    errno, 16);
538 diewrap(die,      " critical", LOG_CRIT,    -1,    16);
539
540 diewrap(sysfatal, " fatal",    LOG_ERR,     errno, 12);
541 diewrap(fatal,    " fatal",    LOG_ERR,     -1,    12);
542
543 logwrap(syswarn,  " warning",  LOG_WARNING, errno);
544 logwrap(warn,     " warning",  LOG_WARNING, -1);
545
546 logwrap(notice,   " notice",   LOG_NOTICE,  -1);
547 logwrap(info,     " info",     LOG_INFO,    -1);
548 logwrap(debug,    " debug",    LOG_DEBUG,   -1);
549
550
551 /*========== utility functions etc. ==========*/
552
553 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
554 static char *xvasprintf(const char *fmt, va_list al) {
555   char *str;
556   int rc= vasprintf(&str,fmt,al);
557   if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
558   return str;
559 }
560 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
561 static char *xasprintf(const char *fmt, ...) {
562   VA;
563   char *str= xvasprintf(fmt,al);
564   va_end(al);
565   return str;
566 }
567
568 static int close_perhaps(int *fd) {
569   if (*fd <= 0) return 0;
570   int r= close(*fd);
571   *fd=0;
572   return r;
573 }
574 static void xclose(int fd, const char *what, const char *what2) {
575   int r= close(fd);
576   if (r) sysdie("close %s%s",what,what2?what2:"");
577 }
578 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
579   if (*fd <= 0) return;
580   xclose(*fd,what,what2);
581   *fd=0;
582 }
583
584 static pid_t xfork(const char *what) {
585   pid_t child;
586
587   child= fork();
588   if (child==-1) sysfatal("cannot fork for %s",what);
589   debug("forked %s %ld", what, (unsigned long)child);
590   if (!child) postfork();
591   return child;
592 }
593
594 static void on_fd_read_except(int fd, oop_call_fd callback) {
595   loop->on_fd(loop, fd, OOP_READ,      callback, 0);
596   loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
597 }
598 static void cancel_fd_read_except(int fd) {
599   loop->cancel_fd(loop, fd, OOP_READ);
600   loop->cancel_fd(loop, fd, OOP_EXCEPTION);
601 }
602
603 static void report_child_status(const char *what, int status) {
604   if (WIFEXITED(status)) {
605     int es= WEXITSTATUS(status);
606     if (es)
607       warn("%s: child died with error exit status %d", what, es);
608   } else if (WIFSIGNALED(status)) {
609     int sig= WTERMSIG(status);
610     const char *sigstr= strsignal(sig);
611     const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
612     if (sigstr)
613       warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
614     else
615       warn("%s: child died due to unknown fatal signal %d%s",
616            what, sig, coredump);
617   } else {
618     warn("%s: child died with unknown wait status %d", what,status);
619   }
620 }
621
622 static int xwaitpid(pid_t *pid, const char *what) {
623   int status;
624
625   int r= kill(*pid, SIGKILL);
626   if (r) sysdie("cannot kill %s child", what);
627
628   pid_t got= waitpid(*pid, &status, WNOHANG);
629   if (got==-1) sysdie("cannot reap %s child", what);
630
631   *pid= 0;
632
633   return status;
634 }
635
636 static void xunlink(const char *path, const char *what) {
637   int r= unlink(path);
638   if (r) sysdie("can't unlink %s %s", path, what);
639 }
640
641 static time_t xtime(void) {
642   time_t now= time(0);
643   if (now==-1) sysdie("time(2) failed");
644   return now;
645 }
646
647 static void xsetnonblock(int fd, int nonblocking) {
648   int errnoval= oop_fd_nonblock(fd, nonblocking);
649   if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
650 }
651
652 static void check_isreg(const struct stat *stab, const char *path,
653                         const char *what) {
654   if (!S_ISREG(stab->st_mode))
655     die("%s %s not a plain file (mode 0%lo)",
656         what, path, (unsigned long)stab->st_mode);
657 }
658
659 static void xfstat(int fd, struct stat *stab_r, const char *what) {
660   int r= fstat(fd, stab_r);
661   if (r) sysdie("could not fstat %s", what);
662 }
663
664 static void xfstat_isreg(int fd, struct stat *stab_r,
665                          const char *path, const char *what) {
666   xfstat(fd, stab_r, what);
667   check_isreg(stab_r, path, what);
668 }
669
670 static void xlstat_isreg(const char *path, struct stat *stab,
671                          int *enoent_r /* 0 means ENOENT is fatal */,
672                          const char *what) {
673   int r= lstat(path, stab);
674   if (r) {
675     if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
676     sysdie("could not lstat %s %s", what, path);
677   }
678   if (enoent_r) *enoent_r= 0;
679   check_isreg(stab, path, what);
680 }
681
682 static int samefile(const struct stat *a, const struct stat *b) {
683   assert(S_ISREG(a->st_mode));
684   assert(S_ISREG(b->st_mode));
685   return (a->st_ino == b->st_ino &&
686           a->st_dev == b->st_dev);
687 }
688
689 static char *sanitise(const char *input) {
690   static char sanibuf[100]; /* returns pointer to this buffer! */
691
692   const char *p= input;
693   char *q= sanibuf;
694   *q++= '`';
695   for (;;) {
696     if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
697     int c= *p++;
698     if (!c) { *q++= '\''; *q=0; break; }
699     if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
700     sprintf(q,"\\x%02x",c);
701     q += 4;
702   }
703   return sanibuf;
704 }
705
706 static int isewouldblock(int errnoval) {
707   return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
708 }
709
710
711 /*========== command and control connections ==========*/
712
713 static int control_master;
714
715 typedef struct ControlConn ControlConn;
716 struct ControlConn {
717   void (*destroy)(ControlConn*);
718   int fd;
719   oop_read *rd;
720   FILE *out;
721   union {
722     struct sockaddr sa;
723     struct sockaddr_un un;
724   } sa;
725   socklen_t salen;
726 };
727
728 static const oop_rd_style control_rd_style= {
729   OOP_RD_DELIM_STRIP, '\n',
730   OOP_RD_NUL_FORBID,
731   OOP_RD_SHORTREC_FORBID
732 };
733
734 static void control_destroy(ControlConn *cc) {
735   cc->destroy(cc);
736 }
737
738 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
739   if (ferror(cc->out) | fflush(cc->out)) {
740     info("CTRL%d write error %s", cc->fd, strerror(errno));
741     control_destroy(cc);
742   }
743 }
744
745 static void control_prompt(ControlConn *cc /* may destroy*/) {
746   fprintf(cc->out, "%s|", sitename);
747   control_checkouterr(cc);
748 }
749
750 typedef struct ControlCommand ControlCommand;
751 struct ControlCommand {
752   const char *cmd;
753   void (*f)(ControlConn *cc, const ControlCommand *ccmd,
754             const char *arg, size_t argsz);
755 };
756
757 static const ControlCommand control_commands[];
758
759 static void ccmd_help(ControlConn *cc, const ControlCommand *thisccmd,
760                       const char *arg, size_t argsz) {
761   fputs("commands:\n", cc->out);
762   const ControlCommand *ccmd;
763   for (ccmd=control_commands; ccmd->cmd; ccmd++)
764     fprintf(cc->out, " %s\n", ccmd->cmd);
765 }
766
767 static const ControlCommand control_commands[]= {
768   { "h", ccmd_help },
769   { 0 }
770 };
771
772 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
773                            const char *errmsg, int errnoval,
774                            const char *data, size_t recsz, void *cc_v) {
775   ControlConn *cc= cc_v;
776
777   if (!data) {
778     info("CTRL%d closed", cc->fd);
779     cc->destroy(cc);
780     return OOP_CONTINUE;
781   }
782
783   if (recsz == 0) goto prompt;
784
785   const ControlCommand *ccmd;
786   for (ccmd=control_commands; ccmd->cmd; ccmd++) {
787     int l= strlen(ccmd->cmd);
788     if (recsz < l) continue;
789     if (recsz > l && data[l] != ' ') continue;
790     if (memcmp(data, ccmd->cmd, l)) continue;
791
792     int argl= (int)recsz - (l+1); 
793     ccmd->f(cc, ccmd, argl>=0 ? data : 0, argl);
794     goto prompt;
795   }
796
797   fputs("unknown command; h for help\n", cc->out);
798
799  prompt:
800   control_prompt(cc);
801   return OOP_CONTINUE;
802 }
803
804 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
805                             const char *errmsg, int errnoval,
806                             const char *data, size_t recsz, void *cc_v) {
807   ControlConn *cc= cc_v;
808   
809   info("CTRL%d read error %s", cc->fd, errmsg);
810   cc->destroy(cc);
811   return OOP_CONTINUE;
812 }
813
814 static int control_conn_startup(ControlConn *cc /* may destroy*/,
815                                 const char *how) {
816   cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
817   if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
818
819   int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
820                       control_rd_ok, cc,
821                       control_rd_err, cc);
822   if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
823
824   info("CTRL%d %s ready", cc->fd, how);
825   control_prompt(cc);
826   return 0;
827 }
828
829 static void control_stdio_destroy(ControlConn *cc) {
830   if (cc->rd) {
831     oop_rd_cancel(cc->rd);
832     errno= oop_rd_delete_tidy(cc->rd);
833     if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
834   }
835   free(cc);
836 }
837
838 static void control_stdio(void) {
839   ControlConn *cc= xmalloc(sizeof(*cc));
840   memset(cc,0,sizeof(*cc));
841   cc->destroy= control_stdio_destroy;
842
843   cc->fd= 0;
844   cc->out= stdout;
845   int r= control_conn_startup(cc,"stdio");
846   if (r) cc->destroy(cc);
847 }
848
849 static void control_accepted_destroy(ControlConn *cc) {
850   if (cc->rd) {
851     oop_rd_cancel(cc->rd);
852     oop_rd_delete_kill(cc->rd);
853   }
854   if (cc->out) { fclose(cc->out); cc->fd=0; }
855   close_perhaps(&cc->fd);
856   free(cc);
857 }
858
859 static void *control_master_readable(oop_source *lp, int master,
860                                      oop_event ev, void *u) {
861   ControlConn *cc= xmalloc(sizeof(*cc));
862   memset(cc,0,sizeof(*cc));
863   cc->destroy= control_accepted_destroy;
864
865   cc->salen= sizeof(cc->sa);
866   cc->fd= accept(master, &cc->sa.sa, &cc->salen);
867   if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
868
869   cc->out= fdopen(cc->fd, "w");
870   if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
871
872   int r= control_conn_startup(cc, "accepted");
873   if (r) goto x;
874
875   return OOP_CONTINUE;
876
877  x:
878   cc->destroy(cc);
879   return OOP_CONTINUE;
880 }
881
882 #define NOCONTROL(...) do{                                              \
883     syswarn("no control socket, because failed to " __VA_ARGS__);       \
884     goto nocontrol;                                                     \
885   }while(0)
886
887 static void control_init(void) {
888   char *real=0;
889   
890   union {
891     struct sockaddr sa;
892     struct sockaddr_un un;
893   } sa;
894
895   memset(&sa,0,sizeof(sa));
896   int maxlen= sizeof(sa.un.sun_path);
897
898   int reallen= readlink(path_control, sa.un.sun_path, maxlen);
899   if (reallen<0) {
900     if (errno != ENOENT)
901       NOCONTROL("readlink control socket symlink path %s", path_control);
902   }
903   if (reallen >= maxlen) {
904     debug("control socket symlink path too long (r=%d)",reallen);
905     xunlink(path_control, "old (overlong) control socket symlink");
906     reallen= -1;
907   }
908   
909   if (reallen<0) {
910     struct stat stab;
911     int r= lstat(realsockdir,&stab);
912     if (r) {
913       if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
914
915       r= mkdir(realsockdir, 0700);
916       if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
917
918     } else {
919       uid_t self= geteuid();
920       if (!S_ISDIR(stab.st_mode) ||
921           stab.st_uid != self ||
922           stab.st_mode & 0077) {
923         warn("no control socket, because real socket directory"
924              " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
925              !!S_ISDIR(stab.st_mode),
926              (unsigned long)stab.st_uid, (unsigned long)self,
927              (unsigned long)stab.st_mode & 0777UL);
928         goto nocontrol;
929       }
930     }
931
932     real= xasprintf("%s/s%lx.%lx", realsockdir,
933                     (unsigned long)xtime(), (unsigned long)self_pid);
934     int reallen= strlen(real);
935
936     if (reallen >= maxlen) {
937       warn("no control socket, because tmpnam gave overly-long path"
938            " %s", real);
939       goto nocontrol;
940     }
941     r= symlink(real, path_control);
942     if (r) NOCONTROL("make control socket path %s a symlink to real"
943                      " socket path %s", path_control, real);
944     memcpy(sa.un.sun_path, real, reallen);
945   }
946
947   int r= unlink(sa.un.sun_path);
948   if (r && errno!=ENOENT)
949     NOCONTROL("remove old real socket %s", sa.un.sun_path);
950
951   control_master= socket(PF_UNIX, SOCK_STREAM, 0);
952   if (control_master<0) NOCONTROL("create new control socket");
953
954   sa.un.sun_family= AF_UNIX;
955   int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
956   r= bind(control_master, &sa.sa, sl);
957   if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
958
959   r= listen(control_master, 5);
960   if (r) NOCONTROL("listen");
961
962   xsetnonblock(control_master, 1);
963
964   loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
965   info("control socket ok, real path %s", sa.un.sun_path);
966
967   return;
968
969  nocontrol:
970   free(real);
971   xclose_perhaps(&control_master, "control master",0);
972   return;
973 }
974
975 /*========== management of connections ==========*/
976
977 static void conn_closefd(Conn *conn, const char *msgprefix) {
978   int r= close_perhaps(&conn->fd);
979   if (r) info("C%d %serror closing socket: %s",
980               conn->fd, msgprefix, strerror(errno));
981 }
982
983 static void conn_dispose(Conn *conn) {
984   if (!conn) return;
985   if (conn->rd) {
986     oop_rd_cancel(conn->rd);
987     oop_rd_delete_kill(conn->rd);
988     conn->rd= 0;
989   }
990   if (conn->fd) {
991     loop->cancel_fd(loop, conn->fd, OOP_WRITE);
992     loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
993   }
994   conn_closefd(conn,"");
995   free(conn);
996   until_connect= reconnect_delay_periods;
997 }
998
999 static void *conn_exception(oop_source *lp, int fd,
1000                             oop_event ev, void *conn_v) {
1001   Conn *conn= conn_v;
1002   unsigned char ch;
1003   assert(fd == conn->fd);
1004   assert(ev == OOP_EXCEPTION);
1005   int r= read(conn->fd, &ch, 1);
1006   if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1007   else connfail(conn,"exceptional condition on socket (peer sent urgent"
1008                 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1009   return OOP_CONTINUE;
1010 }  
1011
1012 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1013   int requeue[art_MaxState];
1014
1015   Article *art;
1016   while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1017   while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1018   while ((art= LIST_REMHEAD(conn->sent))) {
1019     requeue[art->state]++;
1020     if (art->state==art_Unsolicited) art->state= art_Unchecked;
1021     LIST_ADDTAIL(queue,art);
1022   }
1023
1024   int i;
1025   XmitDetails *d;
1026   for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1027     xmit_free(d);
1028
1029   char *m= xvasprintf(fmt,al);
1030   warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1031        conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1032   free(m);
1033
1034   LIST_REMOVE(conns,conn);
1035   conn_dispose(conn);
1036   check_assign_articles();
1037 }
1038
1039 static void connfail(Conn *conn, const char *fmt, ...) {
1040   va_list al;
1041   va_start(al,fmt);
1042   vconnfail(conn,fmt,al);
1043   va_end(al);
1044 }
1045
1046 static void check_idle_conns(void) {
1047   Conn *conn;
1048   for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
1049     conn->since_activity++;
1050  search_again:
1051   for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
1052     if (conn->since_activity <= need_activity_periods) continue;
1053
1054     /* We need to shut this down */
1055     if (conn->quitting)
1056       connfail(conn,"timed out waiting for response to QUIT");
1057     else if (conn->sent.count)
1058       connfail(conn,"timed out waiting for responses");
1059     else if (conn->waiting.count || conn->priority.count)
1060       connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1061     else if (conn->xmitu)
1062       connfail(conn,"peer has been sending responses"
1063                " before receiving our commands!");
1064     else {
1065       static const char quitcmd[]= "QUIT\r\n";
1066       int todo= sizeof(quitcmd)-1;
1067       const char *p= quitcmd;
1068       for (;;) {
1069         int r= write(conn->fd, p, todo);
1070         if (r<0) {
1071           if (isewouldblock(errno))
1072             connfail(conn, "blocked writing QUIT to idle connection");
1073           else
1074             connfail(conn, "failed to write QUIT to idle connection: %s",
1075                      strerror(errno));
1076           break;
1077         }
1078         assert(r<=todo);
1079         todo -= r;
1080         if (!todo) {
1081           conn->quitting= 1;
1082           conn->since_activity= 0;
1083           debug("C%d is idle, quitting", conn->fd);
1084           break;
1085         }
1086       }
1087     }
1088     goto search_again;
1089   }
1090 }  
1091
1092 /*---------- making new connections ----------*/
1093
1094 static pid_t connecting_child;
1095 static int connecting_fdpass_sock;
1096
1097 static void connect_attempt_discard(void) {
1098   if (connecting_child) {
1099     int r= kill(connecting_child, SIGTERM);
1100     if (r) syswarn("failed to kill connecting child");
1101     int status= xwaitpid(&connecting_child, "connect");
1102
1103     if (!(WIFEXITED(status) ||
1104           (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1105       report_child_status("connect", status);
1106   }
1107   if (connecting_fdpass_sock) {
1108     cancel_fd_read_except(connecting_fdpass_sock);
1109     xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1110   }
1111 }
1112
1113 #define PREP_DECL_MSG_CMSG(msg)                 \
1114   struct msghdr msg;                            \
1115   memset(&msg,0,sizeof(msg));                   \
1116   char msg##cbuf[CMSG_SPACE(sizeof(fd))];       \
1117   msg.msg_control= msg##cbuf;                   \
1118   msg.msg_controllen= sizeof(msg##cbuf);
1119
1120 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1121   Conn *conn= 0;
1122
1123   assert(fd == connecting_fdpass_sock);
1124
1125   conn= xmalloc(sizeof(*conn));
1126   memset(conn,0,sizeof(*conn));
1127
1128   PREP_DECL_MSG_CMSG(msg);
1129   struct cmsghdr *h= 0;
1130   ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
1131   if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1132   if (!h) {
1133     int status;
1134     pid_t got= waitpid(connecting_child, &status, WNOHANG);
1135     if (got != -1) {
1136       assert(got==connecting_child);
1137       connecting_child= 0;
1138       if (WIFEXITED(status)) {
1139         if (WEXITSTATUS(status) != 0 &&
1140             WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1141             WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1142           /* child already reported the problem */;
1143         else
1144           warn("connect: connection child exited code %d but no cmsg",
1145                WEXITSTATUS(status));
1146       } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1147         warn("connect: connection attempt timed out");
1148       } else {
1149         report_child_status("connect", status);
1150       }
1151     } else {
1152       /* child is still running apparently, report the socket problem */
1153       if (rs < 0)
1154         syswarn("connect: read from fdpass socket failed");
1155       else if (e == OOP_EXCEPTION)
1156         warn("connect: unexpected exception on fdpass socket");
1157       else if (!rs)
1158         warn("connect: unexpected EOF on fdpass socket");
1159       else
1160         fatal("connect: unexpected lack of cmsg from child");
1161     }
1162     goto x;
1163   }
1164
1165 #define CHK(field, val)                                                  \
1166   if (h->cmsg_##field != val) {                                          \
1167     die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1168         h->cmsg_##field, val);                                           \
1169     goto x;                                                              \
1170   }
1171   CHK(level, SOL_SOCKET);
1172   CHK(type,  SCM_RIGHTS);
1173   CHK(len,   CMSG_LEN(sizeof(conn->fd)));
1174 #undef CHK
1175
1176   if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1177
1178   memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1179
1180   int status;
1181   pid_t got= waitpid(connecting_child, &status, 0);
1182   if (got==-1) sysdie("connect: real wait for child");
1183   assert(got == connecting_child);
1184   connecting_child= 0;
1185
1186   if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1187   int es= WEXITSTATUS(status);
1188   switch (es) {
1189   case CONNCHILD_ESTATUS_STREAM:    conn->stream= 1;   break;
1190   case CONNCHILD_ESTATUS_NOSTREAM:  conn->stream= 0;   break;
1191   default:
1192     fatal("connect: child gave unexpected exit status %d", es);
1193   }
1194
1195   /* Phew! */
1196   LIST_INIT(conn->waiting);
1197   LIST_INIT(conn->priority);
1198   LIST_INIT(conn->sent);
1199   conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1200
1201   loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1202   conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1203   if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1204   int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1205                      &peer_rd_ok, conn,
1206                      &peer_rd_err, conn);
1207   if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1208
1209   notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1210   LIST_ADDHEAD(conns, conn);
1211
1212   connect_attempt_discard();
1213   check_assign_articles();
1214   return 0;
1215
1216  x:
1217   conn_dispose(conn);
1218   connect_attempt_discard();
1219   return OOP_CONTINUE;
1220 }
1221
1222 static int allow_connect_start(void) {
1223   return conns.count < max_connections
1224     && !connecting_child
1225     && !until_connect;
1226 }
1227
1228 static void connect_start(void) {
1229   assert(!connecting_child);
1230   assert(!connecting_fdpass_sock);
1231
1232   notice("starting connection attempt");
1233
1234   int socks[2];
1235   int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1236   if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1237
1238   connecting_child= xfork("connection");
1239
1240   if (!connecting_child) {
1241     FILE *cn_from, *cn_to;
1242     char buf[NNTP_STRLEN+100];
1243     int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1244
1245     xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1246
1247     alarm(connection_setup_timeout);
1248     if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1249       if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
1250       else sysfatal("connect: connection attempt failed");
1251     }
1252     if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1253       sysfatal("connect: authentication failed");
1254     if (try_stream) {
1255       if (fputs("MODE STREAM\r\n", cn_to) ||
1256           fflush(cn_to))
1257         sysfatal("connect: could not send MODE STREAM");
1258       buf[sizeof(buf)-1]= 0;
1259       if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1260         if (ferror(cn_from))
1261           sysfatal("connect: could not read response to MODE STREAM");
1262         else
1263           fatal("connect: connection close in response to MODE STREAM");
1264       }
1265       int l= strlen(buf);
1266       assert(l>=1);
1267       if (buf[-1]!='\n')
1268         fatal("connect: response to MODE STREAM is too long: %.100s...",
1269               sanitise(buf));
1270       l--;  if (l>0 && buf[l-1]=='\r') l--;
1271       buf[l]= 0;
1272       char *ep;
1273       int rcode= strtoul(buf,&ep,10);
1274       if (ep != &buf[3])
1275         fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
1276
1277       switch (rcode) {
1278       case 203:
1279         exitstatus= CONNCHILD_ESTATUS_STREAM;
1280         break;
1281       case 480:
1282       case 500:
1283         break;
1284       default:
1285         warn("connect: unexpected response to MODE STREAM: %.50s",
1286              sanitise(buf));
1287         exitstatus= 2;
1288         break;
1289       }
1290     }
1291     int fd= fileno(cn_from);
1292
1293     PREP_DECL_MSG_CMSG(msg);
1294     struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1295     cmsg->cmsg_level= SOL_SOCKET;
1296     cmsg->cmsg_type=  SCM_RIGHTS;
1297     cmsg->cmsg_len=   CMSG_LEN(sizeof(fd));
1298     memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1299
1300     msg.msg_controllen= cmsg->cmsg_len;
1301     r= sendmsg(socks[1], &msg, 0);
1302     if (r) sysdie("sendmsg failed for new connection");
1303
1304     _exit(exitstatus);
1305   }
1306
1307   xclose(socks[1], "connecting fdpass child's socket",0);
1308   connecting_fdpass_sock= socks[0];
1309   on_fd_read_except(connecting_fdpass_sock, connchild_event);
1310 }
1311
1312 /*---------- assigning articles to conns, and transmitting ----------*/
1313
1314 static void check_assign_articles(void) {
1315   for (;;) {
1316     if (!queue.count)
1317       break;
1318
1319     Conn *walk, *use=0;
1320     int spare=0, inqueue=0;
1321
1322     /* Find a connection to offer this article.  We prefer a busy
1323      * connection to an idle one, provided it's not full.  We take the
1324      * first (oldest) and since that's stable, it will mean we fill up
1325      * connections in order.  That way if we have too many
1326      * connections, the spare ones will go away eventually.
1327      */
1328     for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1329       if (walk->quitting) continue;
1330       inqueue= walk->sent.count + walk->priority.count
1331              + walk->waiting.count;
1332       spare= walk->max_queue - inqueue;
1333       assert(inqueue <= max_queue_per_conn);
1334       assert(spare >= 0);
1335       if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1336       else if (spare>0) /*working*/ { use= walk; break; }
1337     }
1338     if (use) {
1339       if (!inqueue) use->since_activity= 0; /* reset idle counter */
1340       while (spare>0) {
1341         Article *art= LIST_REMHEAD(queue);
1342         LIST_ADDTAIL(use->waiting, art);
1343         spare--;
1344       }
1345       conn_maybe_write(use);
1346     } else if (allow_connect_start()) {
1347       until_connect= reconnect_delay_periods;
1348       connect_start();
1349       break;
1350     } else {
1351       break;
1352     }
1353   }
1354 }
1355
1356 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1357   conn_maybe_write(u);
1358   return OOP_CONTINUE;
1359 }
1360
1361 static void conn_maybe_write(Conn *conn)  {
1362   for (;;) {
1363     conn_make_some_xmits(conn);
1364     if (!conn->xmitu) {
1365       loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1366       return;
1367     }
1368
1369     void *rp= conn_write_some_xmits(conn);
1370     if (rp==OOP_CONTINUE) {
1371       loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1372       return;
1373     } else if (rp==OOP_HALT) {
1374       return;
1375     } else if (!rp) {
1376       /* transmitted everything */
1377     } else {
1378       abort();
1379     }
1380   }
1381 }
1382
1383 /*========== article transmission ==========*/
1384
1385 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1386                   XmitKind kind) { /* caller must then fill in details */
1387   struct iovec *v= &conn->xmit[conn->xmitu];
1388   XmitDetails *d= &conn->xmitd[conn->xmitu++];
1389   v->iov_base= (char*)data;
1390   v->iov_len= len;
1391   d->kind= kind;
1392   return d;
1393 }
1394
1395 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1396   xmit_core(conn,data,len, xk_Const);
1397 }
1398 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1399
1400 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1401   XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1402   d->info.sm_art= ah;
1403 }
1404
1405 static void xmit_free(XmitDetails *d) {
1406   switch (d->kind) {
1407   case xk_Malloc:  free(d->info.malloc_tofree);   break;
1408   case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1409   case xk_Const:                                  break;
1410   default: abort();
1411   }
1412 }
1413
1414 static void *conn_write_some_xmits(Conn *conn) {
1415   /* return values:
1416    *      0:            nothing more to write, no need to call us again
1417    *      OOP_CONTINUE: more to write but fd not writeable
1418    *      OOP_HALT:     disaster, have destroyed conn
1419    */
1420   for (;;) {
1421     int count= conn->xmitu;
1422     if (!count) return 0;
1423
1424     if (count > IOV_MAX) count= IOV_MAX;
1425     ssize_t rs= writev(conn->fd, conn->xmit, count);
1426     if (rs < 0) {
1427       if (isewouldblock(errno)) return OOP_CONTINUE;
1428       connfail(conn, "write failed: %s", strerror(errno));
1429       return OOP_HALT;
1430     }
1431     assert(rs > 0);
1432
1433     int done;
1434     for (done=0; rs && done<conn->xmitu; done++) {
1435       struct iovec *vp= &conn->xmit[done];
1436       XmitDetails *dp= &conn->xmitd[done];
1437       if (rs > vp->iov_len) {
1438         rs -= vp->iov_len;
1439         xmit_free(dp);
1440       } else {
1441         vp->iov_base= (char*)vp->iov_base + rs;
1442         vp->iov_len -= rs;
1443       }
1444     }
1445     int newu= conn->xmitu - done;
1446     memmove(conn->xmit,  conn->xmit  + done, newu * sizeof(*conn->xmit));
1447     memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1448     conn->xmitu= newu;
1449   }
1450 }
1451
1452 static void conn_make_some_xmits(Conn *conn) {
1453   for (;;) {
1454     if (conn->xmitu+5 > CONNIOVS)
1455       break;
1456
1457     Article *art= LIST_REMHEAD(conn->priority);
1458     if (!art) art= LIST_REMHEAD(conn->waiting);
1459     if (!art) break;
1460
1461     if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1462       /* actually send it */
1463
1464       ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1465
1466       if (conn->stream) {
1467         if (artdata) {
1468           XMIT_LITERAL("TAKETHIS ");
1469           xmit_noalloc(conn, art->messageid, art->midlen);
1470           XMIT_LITERAL("\r\n");
1471           xmit_artbody(conn, artdata);
1472         }
1473       } else {
1474         /* we got 235 from IHAVE */
1475         if (artdata) {
1476           xmit_artbody(conn, artdata);
1477         } else {
1478           XMIT_LITERAL(".\r\n");
1479         }
1480       }
1481
1482       art->state=
1483         art->state == art_Unchecked ? art_Unsolicited :
1484         art->state == art_Wanted    ? art_Wanted      :
1485         (abort(),-1);
1486       art->ipf->counts[art->state][RC_sent]++;
1487       LIST_ADDTAIL(conn->sent, art);
1488
1489     } else {
1490       /* check it */
1491
1492       if (conn->stream)
1493         XMIT_LITERAL("IHAVE ");
1494       else
1495         XMIT_LITERAL("CHECK ");
1496       xmit_noalloc(conn, art->messageid, art->midlen);
1497       XMIT_LITERAL("\r\n");
1498
1499       assert(art->state == art_Unchecked);
1500       art->ipf->counts[art->state][RC_sent]++;
1501       LIST_ADDTAIL(conn->sent, art);
1502     }
1503   }
1504 }
1505
1506
1507 /*========== handling responses from peer ==========*/
1508
1509 static const oop_rd_style peer_rd_style= {
1510   OOP_RD_DELIM_STRIP, '\n',
1511   OOP_RD_NUL_FORBID,
1512   OOP_RD_SHORTREC_FORBID
1513 };
1514
1515 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1516                          const char *errmsg, int errnoval,
1517                          const char *data, size_t recsz, void *conn_v) {
1518   Conn *conn= conn_v;
1519   connfail(conn, "error receiving from peer: %s", errmsg);
1520   return OOP_CONTINUE;
1521 }
1522
1523 static Article *article_reply_check(Conn *conn, const char *response,
1524                                     int code_indicates_streaming,
1525                                     int must_have_sent
1526                                         /* 1:yes, -1:no, 0:dontcare */,
1527                                     const char *sanitised_response) {
1528   Article *art= LIST_HEAD(conn->sent);
1529
1530   if (!art) {
1531     connfail(conn,
1532              "peer gave unexpected response when no commands outstanding: %s",
1533              sanitised_response);
1534     return 0;
1535   }
1536
1537   if (code_indicates_streaming) {
1538     assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1539     if (!conn->stream) {
1540       connfail(conn, "peer gave streaming response code "
1541                " to IHAVE or subsequent body: %s", sanitised_response);
1542       return 0;
1543     }
1544     const char *got_mid= response+4;
1545     int got_midlen= strcspn(got_mid, " \n\r");
1546     if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1547       connfail(conn, "peer gave streaming response with syntactically invalid"
1548                " messageid: %s", sanitised_response);
1549       return 0;
1550     }
1551     if (got_midlen != art->midlen ||
1552         memcmp(got_mid, art->messageid, got_midlen)) {
1553       connfail(conn, "peer gave streaming response code to wrong article -"
1554                " probable synchronisation problem; we offered: %s;"
1555                " peer said: %s",
1556                art->messageid, sanitised_response);
1557       return 0;
1558     }
1559   } else {
1560     if (conn->stream) {
1561       connfail(conn, "peer gave non-streaming response code to"
1562                " CHECK/TAKETHIS: %s", sanitised_response);
1563       return 0;
1564     }
1565   }
1566
1567   if (must_have_sent>0 && art->state < art_Wanted) {
1568     connfail(conn, "peer says article accepted but"
1569              " we had not sent the body: %s", sanitised_response);
1570     return 0;
1571   }
1572   if (must_have_sent<0 && art->state >= art_Wanted) {
1573     connfail(conn, "peer says please sent the article but we just did: %s",
1574              sanitised_response);
1575     return 0;
1576   }
1577
1578   Article *art_again= LIST_REMHEAD(conn->sent);
1579   assert(art_again == art);
1580   return art;
1581 }
1582
1583 static void update_nocheck(int accepted) {
1584   accept_proportion *= nocheck_decay;
1585   accept_proportion += accepted * (1.0 - nocheck_decay);
1586   int new_nocheck= accept_proportion >= nocheck_thresh;
1587   if (new_nocheck && !nocheck_reported) {
1588     notice("entering nocheck mode for the first time");
1589     nocheck_reported= 1;
1590   } else if (new_nocheck != nocheck) {
1591     debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1592   }
1593   nocheck= new_nocheck;
1594 }
1595
1596 static void article_done(Conn *conn, Article *art, int whichcount) {
1597   art->ipf->counts[art->state][whichcount]++;
1598   if (whichcount == RC_accepted) update_nocheck(1);
1599   else if (whichcount == RC_unwanted) update_nocheck(0);
1600
1601   InputFile *ipf= art->ipf;
1602
1603   while (art->blanklen) {
1604     static const char spaces[]=
1605       "                                                                "
1606       "                                                                "
1607       "                                                                "
1608       "                                                                ";
1609     int w= art->blanklen;  if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1610     int r= pwrite(ipf->fd, spaces, w, art->offset);
1611     if (r==-1) {
1612       if (errno==EINTR) continue;
1613       sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1614              art->messageid, art->blanklen,
1615              (unsigned long)art->offset, ipf->path);
1616     }
1617     assert(r>=0 && r<=w);
1618     art->blanklen -= w;
1619     art->offset += w;
1620   }
1621
1622   ipf->inprogress--;
1623   assert(ipf->inprogress >= 0);
1624   free(art);
1625
1626   if (!ipf->inprogress && ipf != main_input_file)
1627     queue_check_input_done();
1628 }
1629
1630 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1631                         const char *errmsg, int errnoval,
1632                         const char *data, size_t recsz, void *conn_v) {
1633   Conn *conn= conn_v;
1634
1635   if (ev == OOP_RD_EOF) {
1636     connfail(conn, "unexpected EOF from peer");
1637     return OOP_CONTINUE;
1638   }
1639   assert(ev == OOP_RD_OK);
1640
1641   char *sani= sanitise(data);
1642
1643   char *ep;
1644   unsigned long code= strtoul(data, &ep, 10);
1645   if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1646     connfail(conn, "badly formatted response from peer: %s", sani);
1647     return OOP_CONTINUE;
1648   }
1649
1650   if (conn->quitting) {
1651     if (code!=205 && code!=503) {
1652       connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1653     } else {
1654       notice("C%d idle connection closed", conn->fd);
1655       assert(!conn->waiting.count);
1656       assert(!conn->priority.count);
1657       assert(!conn->sent.count);
1658       assert(!conn->xmitu);
1659       LIST_REMOVE(conns,conn);
1660       conn_dispose(conn);
1661     }
1662     return OOP_CONTINUE;
1663   }
1664
1665   conn->since_activity= 0;
1666   Article *art;
1667
1668 #define GET_ARTICLE(musthavesent)                                           \
1669   art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1670   if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1671
1672 #define ARTICLE_DEALTWITH(streaming,musthavesent,how)           \
1673   code_streaming= (streaming);                                  \
1674   GET_ARTICLE(musthavesent);                                    \
1675   article_done(conn, art, RC_##how);  break;
1676
1677 #define PEERBADMSG(m) connfail(conn, m ": %s", sani);  return OOP_CONTINUE
1678
1679   int code_streaming= 0;
1680
1681   switch (code) {
1682
1683   case 400: PEERBADMSG("peer stopped accepting articles");
1684   case 503: PEERBADMSG("peer timed us out");
1685   default:  PEERBADMSG("peer sent unexpected message");
1686
1687   case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1688   case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1689
1690   case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1691   case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1692
1693   case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1694   case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1695
1696   case 238: /* CHECK says send it */
1697     code_streaming= 1;
1698   case 335: /* IHAVE says send it */
1699     GET_ARTICLE(-1);
1700     assert(art->state == art_Unchecked);
1701     art->ipf->counts[art->state][RC_accepted]++;
1702     art->state= art_Wanted;
1703     LIST_ADDTAIL(conn->priority, art);
1704     break;
1705
1706   case 431: /* CHECK or TAKETHIS says try later */
1707     code_streaming= 1;
1708   case 436: /* IHAVE says try later */
1709     GET_ARTICLE(0);
1710     open_defer();
1711     if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1712         || fflush(defer))
1713       sysfatal("write to defer file %s",path_defer);
1714     article_done(conn, art, RC_deferred);
1715     break;
1716
1717   }
1718
1719   conn_maybe_write(conn);
1720   check_assign_articles();
1721   return OOP_CONTINUE;
1722 }
1723
1724
1725 /*========== monitoring of input files ==========*/
1726
1727 static void feedfile_eof(InputFile *ipf) {
1728   assert(ipf != main_input_file); /* promised by tailing_try_read */
1729   inputfile_reading_stop(ipf);
1730
1731   if (ipf == flushing_input_file) {
1732     assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1733     if (main_input_file) inputfile_reading_start(main_input_file);
1734     statemc_check_flushing_done();
1735   } else if (ipf == backlog_input_file) {
1736     statemc_check_backlog_done();
1737   } else {
1738     abort(); /* supposed to wait rather than get EOF on main input file */
1739   }
1740 }
1741
1742 static InputFile *open_input_file(const char *path) {
1743   int fd= open(path, O_RDONLY);
1744   if (fd<0) {
1745     if (errno==ENOENT) return 0;
1746     sysfatal("unable to open input file %s", path);
1747   }
1748   assert(fd>0);
1749
1750   InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1751   memset(ipf,0,sizeof(*ipf));
1752
1753   ipf->fd= fd;
1754   strcpy(ipf->path, path);
1755
1756   return ipf;
1757 }
1758
1759 static void close_input_file(InputFile *ipf) { /* does not free */
1760   assert(!ipf->readable_callback); /* must have had ->on_cancel */
1761   assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1762   assert(!ipf->rd); /* must have had inputfile_reading_stop */
1763   assert(!ipf->inprogress); /* no dangling pointers pointing here */
1764   xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1765 }
1766
1767
1768 /*---------- dealing with articles read in the input file ----------*/
1769
1770 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1771                                    const char *data, const char *how) {
1772   warn("corrupted file: %s, offset %lu: %s: %s",
1773        ipf->path, (unsigned long)offset, how, sanitise(data));
1774   ipf->readcount_err++;
1775   if (ipf->readcount_err > max_bad_data_initial +
1776       (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1777     die("too much garbage in input file!  (%d errs, %d ok, %d blank)",
1778         ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1779   return OOP_CONTINUE;
1780 }
1781
1782 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1783                                oop_rd_event ev, const char *errmsg,
1784                                int errnoval, const char *data, size_t recsz,
1785                                void *ipf_v) {
1786   InputFile *ipf= ipf_v;
1787   assert(ev == OOP_RD_SYSTEM);
1788   errno= errnoval;
1789   sysdie("error reading input file: %s, offset %lu",
1790          ipf->path, (unsigned long)ipf->offset);
1791 }
1792
1793 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1794                                   oop_rd_event ev, const char *errmsg,
1795                                   int errnoval, const char *data, size_t recsz,
1796                                   void *ipf_v) {
1797   InputFile *ipf= ipf_v;
1798   Article *art;
1799   char tokentextbuf[sizeof(TOKEN)*2+3];
1800
1801   if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1802
1803   off_t old_offset= ipf->offset;
1804   ipf->offset += recsz + 1;
1805
1806 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1807
1808   if (ev==OOP_RD_PARTREC)
1809     feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1810     /* but process it anyway */
1811
1812   if (ipf->skippinglong) {
1813     if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1814     return OOP_CONTINUE;
1815   }
1816   if (ev==OOP_RD_LONG) {
1817     ipf->skippinglong= 1;
1818     X_BAD_DATA("overly long line");
1819   }
1820
1821   if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1822   if (!recsz) X_BAD_DATA("empty line");
1823
1824   if (data[0]==' ') {
1825     if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1826     ipf->readcount_blank++;
1827     return OOP_CONTINUE;
1828   }
1829
1830   char *space= strchr(data,' ');
1831   int tokenlen= space-data;
1832   int midlen= (int)recsz-tokenlen-1;
1833   if (midlen <= 2) X_BAD_DATA("no room for messageid");
1834   if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1835
1836   if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1837   memcpy(tokentextbuf, data, tokenlen);
1838   tokentextbuf[tokenlen]= 0;
1839   if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1840
1841   ipf->readcount_ok++;
1842
1843   art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1844   art->state= art_Unchecked;
1845   art->midlen= midlen;
1846   art->ipf= ipf;  ipf->inprogress++;
1847   art->token= TextToToken(tokentextbuf);
1848   art->offset= ipf->offset;
1849   art->blanklen= recsz;
1850   strcpy(art->messageid, space+1);
1851   LIST_ADDTAIL(queue, art);
1852
1853   if (sms==sm_NORMAL && ipf==main_input_file &&
1854       ipf->offset >= target_max_feedfile_size)
1855     statemc_start_flush("feed file size");
1856
1857   check_assign_articles();
1858   return OOP_CONTINUE;
1859 }
1860
1861 /*========== tailing input file ==========*/
1862
1863 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1864                                      void *user) {
1865   InputFile *ipf= user;
1866   return ipf->readable_callback(loop, &ipf->readable,
1867                                 ipf->readable_callback_user);
1868 }
1869
1870 static void tailing_on_cancel(struct oop_readable *rable) {
1871   InputFile *ipf= (void*)rable;
1872
1873   if (ipf->filemon) filemon_stop(ipf);
1874   loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1875   ipf->readable_callback= 0;
1876 }
1877
1878 static void tailing_queue_readable(InputFile *ipf) {
1879   /* lifetime of ipf here is OK because destruction will cause
1880    * on_cancel which will cancel this callback */
1881   loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1882 }
1883
1884 static int tailing_on_readable(struct oop_readable *rable,
1885                                 oop_readable_call *cb, void *user) {
1886   InputFile *ipf= (void*)rable;
1887
1888   tailing_on_cancel(rable);
1889   ipf->readable_callback= cb;
1890   ipf->readable_callback_user= user;
1891   filemon_start(ipf);
1892
1893   tailing_queue_readable(ipf);
1894   return 0;
1895 }
1896
1897 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1898                                 size_t length) {
1899   InputFile *ipf= (void*)rable;
1900   for (;;) {
1901     ssize_t r= read(ipf->fd, buffer, length);
1902     if (r==-1) {
1903       if (errno==EINTR) continue;
1904       return r;
1905     }
1906     if (!r) {
1907       if (ipf==main_input_file) {
1908         errno=EAGAIN;
1909         return -1;
1910       } else if (ipf==flushing_input_file) {
1911         assert(ipf->rd);
1912         assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1913       } else if (ipf==backlog_input_file) {
1914         assert(ipf->rd);
1915       } else {
1916         abort();
1917       }
1918     }
1919     return r;
1920   }
1921 }
1922
1923 /*---------- filemon implemented with inotify ----------*/
1924
1925 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1926 #define HAVE_FILEMON
1927
1928 #include <linux/inotify.h>
1929
1930 static int filemon_inotify_fd;
1931 static int filemon_inotify_wdmax;
1932 static InputFile **filemon_inotify_wd2ipf;
1933
1934 struct Filemon_Perfile {
1935   int wd;
1936 };
1937
1938 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1939   int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1940   if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
1941
1942   if (wd >= filemon_inotify_wdmax) {
1943     int newmax= wd+2;
1944     filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1945                                  sizeof(*filemon_inotify_wd2ipf) * newmax);
1946     memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1947            sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1948     filemon_inotify_wdmax= newmax;
1949   }
1950
1951   assert(!filemon_inotify_wd2ipf[wd]);
1952   filemon_inotify_wd2ipf[wd]= ipf;
1953
1954   debug("filemon inotify startfile %p wd=%d wdmax=%d",
1955         ipf, wd, filemon_inotify_wdmax);
1956
1957   pf->wd= wd;
1958 }
1959
1960 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1961   int wd= pf->wd;
1962   debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1963   int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1964   if (r) sysdie("inotify_rm_watch");
1965   filemon_inotify_wd2ipf[wd]= 0;
1966 }
1967
1968 static void *filemon_inotify_readable(oop_source *lp, int fd,
1969                                       oop_event e, void *u) {
1970   struct inotify_event iev;
1971   for (;;) {
1972     int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1973     if (r==-1) {
1974       if (isewouldblock(errno)) break;
1975       sysdie("read from inotify master");
1976     } else if (r==sizeof(iev)) {
1977       assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1978     } else {
1979       die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1980     }
1981     InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1982     debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1983     filemon_callback(ipf);
1984   }
1985   return OOP_CONTINUE;
1986 }
1987
1988 static int filemon_method_init(void) {
1989   filemon_inotify_fd= inotify_init();
1990   if (filemon_inotify_fd<0) {
1991     syswarn("could not initialise inotify: inotify_init failed");
1992     return 0;
1993   }
1994   set nonblock;
1995   loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1996
1997   debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1998   return 1;
1999 }
2000
2001 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2002
2003 /*---------- filemon dummy implementation ----------*/
2004
2005 #if !defined(HAVE_FILEMON)
2006
2007 struct Filemon_Perfile { int dummy; };
2008
2009 static int filemon_method_init(void) { return 0; }
2010 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2011 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2012
2013 #endif /* !HAVE_FILEMON */
2014
2015 /*---------- filemon generic interface ----------*/
2016
2017 static void filemon_start(InputFile *ipf) {
2018   assert(!ipf->filemon);
2019
2020   ipf->filemon= xmalloc(sizeof(*ipf->filemon));
2021   memset(ipf->filemon, 0, sizeof(*ipf->filemon));
2022   filemon_method_startfile(ipf, ipf->filemon);
2023 }
2024
2025 static void filemon_stop(InputFile *ipf) {
2026   if (!ipf->filemon) return;
2027   filemon_method_stopfile(ipf, ipf->filemon);
2028   free(ipf->filemon);
2029   ipf->filemon= 0;
2030 }
2031
2032 static void filemon_callback(InputFile *ipf) {
2033   ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2034 }
2035
2036 /*---------- interface to start and stop an input file ----------*/
2037
2038 static const oop_rd_style feedfile_rdstyle= {
2039   OOP_RD_DELIM_STRIP, '\n',
2040   OOP_RD_NUL_PERMIT,
2041   OOP_RD_SHORTREC_LONG,
2042 };
2043
2044 static void inputfile_reading_start(InputFile *ipf) {
2045   assert(!ipf->rd);
2046   ipf->readable.on_readable= tailing_on_readable;
2047   ipf->readable.on_cancel=   tailing_on_cancel;
2048   ipf->readable.try_read=    tailing_try_read;
2049   ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2050   ipf->readable.delete_kill= 0;
2051
2052   ipf->readable_callback= 0;
2053   ipf->readable_callback_user= 0;
2054
2055   ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2056   assert(ipf->rd);
2057
2058   int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2059                      feedfile_got_article,ipf, feedfile_read_err, ipf);
2060   if (r) sysdie("unable start reading feedfile %s",ipf->path);
2061 }
2062
2063 static void inputfile_reading_stop(InputFile *ipf) {
2064   assert(ipf->rd);
2065   oop_rd_cancel(ipf->rd);
2066   oop_rd_delete(ipf->rd);
2067   ipf->rd= 0;
2068   assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2069 }
2070
2071
2072 /*========== interaction with innd - state machine ==========*/
2073
2074 /* See official state diagram at top of file.  We implement
2075  * this as follows:
2076  * -8<-
2077
2078             .=======.
2079             ||START||
2080             `======='
2081                 |
2082                 | open F
2083                 |
2084                 |    F ENOENT
2085                 |`---------------------------------------------------.
2086       F OPEN OK |                                                    |
2087                 |`---------------- - - -                             |
2088        D ENOENT |       D EXISTS   see OVERALL STATES diagram        |
2089                 |                  for full startup logic            |
2090      ,--------->|                                                    |
2091      |          V                                                    |
2092      |     ============                                       try to |
2093      |      NORMAL                                            open D |
2094      |     [Normal]                                                  |
2095      |      main F tail                                              |
2096      |     ============                                              V
2097      |          |                                                    |
2098      |          | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT            |
2099      ^          | hardlink F to D                                    |
2100      |     [Hardlinked]                                              |
2101      |          | unlink F                                           |
2102      |          | our handle onto F is now onto D                    |
2103      |     [Moved]                                                   |
2104      |          |                                                    |
2105      |          |<-------------------<---------------------<---------+
2106      |          |                                                    |
2107      |          | spawn inndcomm flush                               |
2108      |          V                                                    |
2109      |     ==================                                        |
2110      |      FLUSHING[-ABSENT]                                        |
2111      |     [Flushing]                                                |
2112      |     main D tail/none                                          |
2113      |     ==================                                        |
2114      |          |                                                    |
2115      |          |   INNDCOMM FLUSH FAILS                             ^
2116      |          |`----------------------->----------.                |
2117      |          |                                   |                |
2118      |          |   NO SUCH SITE                    V                |
2119      ^          |`--------------->----.         ==================== |
2120      |          |                      \        FLUSHFAILED[-ABSENT] |
2121      |          |                       \         [Moved]            |
2122      |          | FLUSH OK               \       main D tail/none    |
2123      |          | open F                  \     ==================== |
2124      |          |                          \        |                |
2125      |          |                           \       | TIME TO RETRY  |
2126      |          |`------->----.     ,---<---'\      `----------------'
2127      |          |    D NONE   |     | D NONE  `----.
2128      |          V             |     |              V
2129      |     =============      V     V             ============
2130      |      SEPARATED-1       |     |              DROPPING-1
2131      |      flsh->rd!=0       |     |              flsh->rd!=0
2132      |     [Separated]        |     |             [Dropping]
2133      |      main F idle       |     |              main none
2134      |      old D tail        |     |              old D tail
2135      |     =============      |     |             ============
2136      |          |             |     | install       |
2137      ^          | EOF ON D    |     |  defer        | EOF ON D
2138      |          V             |     |               V
2139      |     ===============    |     |             ===============
2140      |      SEPARATED-2       |     |              DROPPING-2
2141      |      flsh->rd==0       |     V              flsh->rd==0
2142      |     [Finishing]        |     |             [Dropping]
2143      |      main F tail       |     `.             main none
2144      |      old D closed      |       `.           old D closed
2145      |     ===============    V         `.        ===============
2146      |          |                         `.          |
2147      |          | ALL D PROCESSED           `.        | ALL D PROCESSED
2148      |          V install defer as backlog    `.      | install defer
2149      ^          | close D                       `.    | close D
2150      |          | unlink D                        `.  | unlink D
2151      |          |                                  |  |
2152      |          |                                  V  V
2153      `----------'                               ==============
2154                                                  DROPPED
2155                                                 [Dropped]
2156                                                  main none
2157                                                  old none
2158                                                  some backlog
2159                                                 ==============
2160                                                       |
2161                                                       | ALL BACKLOG DONE
2162                                                       |
2163                                                       | unlink lock
2164                                                       | exit
2165                                                       V
2166                                                   ==========
2167                                                    (ESRCH)
2168                                                   [Droppped]
2169                                                   ==========
2170  * ->8-
2171  */
2172
2173 static void startup_set_input_file(InputFile *f) {
2174   assert(!main_input_file);
2175   main_input_file= f;
2176   inputfile_reading_start(f);
2177 }
2178
2179 static void statemc_lock(void) {
2180   int lockfd;
2181   struct stat stab, stabf;
2182   
2183   for (;;) {
2184     lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2185     if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2186
2187     struct flock fl;
2188     memset(&fl,0,sizeof(fl));
2189     fl.l_type= F_WRLCK;
2190     fl.l_whence= SEEK_SET;
2191     int r= fcntl(lockfd, F_SETLK, &fl);
2192     if (r==-1) {
2193       if (errno==EACCES || isewouldblock(errno)) {
2194         if (quiet_multiple) exit(0);
2195         fatal("another duct holds the lockfile");
2196       }
2197       sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2198     }
2199
2200     xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2201     int lock_noent;
2202     xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2203
2204     if (!lock_noent && samefile(&stab, &stabf))
2205       break;
2206
2207     xclose(lockfd, "stale lockfile ", path_lock);
2208   }
2209
2210   FILE *lockfile= fdopen(lockfd, "w");
2211   if (!lockfile) sysdie("fdopen lockfile");
2212
2213   int r= ftruncate(lockfd, 0);
2214   if (r) sysdie("truncate lockfile to write new info");
2215
2216   if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2217               (unsigned long)self_pid,
2218               sitename, feedfile, remote_host) == EOF ||
2219       fflush(lockfile))
2220     sysfatal("write info to lockfile %s", path_lock);
2221
2222   debug("startup: locked");
2223 }
2224
2225 static void statemc_init(void) {
2226   struct stat stabdefer;
2227
2228   search_backlog_file();
2229
2230   int defer_noent;
2231   xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2232   if (defer_noent) {
2233     debug("startup: ductdefer ENOENT");
2234   } else {
2235     debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2236     switch (stabdefer.st_nlink==1) {
2237     case 1:
2238       open_defer(); /* so that we will later close it and rename it */
2239       break;
2240     case 2:
2241       xunlink(path_defer, "stale defer file link"
2242               " (presumably hardlink to backlog file)");
2243       break;
2244     default:
2245       die("defer file %s has unexpected link count %d",
2246           path_defer, stabdefer.st_nlink);
2247     }
2248   }
2249
2250   struct stat stab_f, stab_d;
2251   int noent_f;
2252
2253   InputFile *file_d= open_input_file(path_flushing);
2254   if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2255
2256   xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2257
2258   if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2259     debug("startup: F==D => Hardlinked");
2260     xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2261     noent_f= 1;
2262   }
2263
2264   if (noent_f) {
2265     debug("startup: F ENOENT => Moved");
2266     if (file_d) startup_set_input_file(file_d);
2267     spawn_inndcomm_flush("feedfile missing at startup");
2268     /* => Flushing, sms:=FLUSHING */
2269   } else {
2270     if (file_d) {
2271       debug("startup: F!=D => Separated");
2272       startup_set_input_file(file_d);
2273       SMS(SEPARATED, 0, "found both old and current feed files");
2274     } else {
2275       debug("startup: F exists, D ENOENT => Normal");
2276       InputFile *file_f= open_input_file(feedfile);
2277       if (!file_f) die("feed file vanished during startup");
2278       startup_set_input_file(file_f);
2279       SMS(NORMAL, flushfail_retry_periods, "normal startup");
2280     }
2281   }
2282 }
2283
2284 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2285   assert(sms == sm_NORMAL);
2286
2287   debug("starting flush (%s) (%lu >?= %lu) (%d)",
2288         why,
2289         (unsigned long)(main_input_file ? main_input_file->offset : 0),
2290         (unsigned long)target_max_feedfile_size,
2291         sm_period_counter);
2292
2293   int r= link(feedfile, path_flushing);
2294   if (r) sysfatal("link feedfile %s to flushing file %s",
2295                   feedfile, path_flushing);
2296   /* => Hardlinked */
2297
2298   xunlink(feedfile, "old feedfile link");
2299   /* => Moved */
2300
2301   spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2302 }
2303
2304 static void statemc_period_poll(void) {
2305   if (!sm_period_counter) return;
2306   sm_period_counter--;
2307   assert(sm_period_counter>=0);
2308
2309   if (sm_period_counter) return;
2310   switch (sms) {
2311   case sm_NORMAL:
2312     statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2313     break;
2314   case sm_FLUSHFAILED:
2315     spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2316     break;
2317   default:
2318     abort();
2319   }
2320 }
2321
2322 static int inputfile_is_done(InputFile *ipf) {
2323   if (!ipf) return 0;
2324   if (ipf->inprogress) return 0; /* new article in the meantime */
2325   if (ipf->rd) return 0; /* not had EOF */
2326   return 1;
2327 }
2328
2329 static void notice_processed(InputFile *ipf, const char *what,
2330                              const char *spec) {
2331 #define RCI_NOTHING(x) /* nothing */
2332 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2333 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2334
2335 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2336
2337   info("processed %s%s read=%d(+%dbl,+%derr)"
2338        " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2339        RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2340        ,
2341        what, spec,
2342        ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2343        CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2344        , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2345        CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2346        , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2347        RESULT_COUNTS(RCI_NOTHING,  RCI_TRIPLE_VALS)
2348        );
2349
2350 #undef CNT
2351 }
2352
2353 static void statemc_check_backlog_done(void) {
2354   InputFile *ipf= backlog_input_file;
2355   if (!inputfile_is_done(ipf)) return;
2356
2357   const char *slash= strrchr(ipf->path, '/');
2358   const char *leaf= slash ? slash+1 : ipf->path;
2359   const char *under= strchr(slash, '_');
2360   const char *rest= under ? under+1 : leaf;
2361   if (!strncmp(rest,"backlog",7)) rest += 7;
2362   notice_processed(ipf,"backlog:",rest);
2363
2364   close_input_file(ipf);
2365   if (unlink(ipf->path)) {
2366     if (errno != ENOENT)
2367       sysdie("could not unlink processed backlog file %s", ipf->path);
2368     warn("backlog file %s vanished while we were reading it"
2369          " so we couldn't remove it (but it's done now, anyway)",
2370          ipf->path);
2371   }
2372   free(ipf);
2373   backlog_input_file= 0;
2374   search_backlog_file();
2375   return;
2376 }
2377
2378 static void statemc_check_flushing_done(void) {
2379   InputFile *ipf= flushing_input_file;
2380   if (!inputfile_is_done(ipf)) return;
2381
2382   assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2383
2384   notice_processed(ipf,"feedfile",0);
2385
2386   close_defer();
2387
2388   xunlink(path_flushing, "old flushing file");
2389
2390   close_input_file(flushing_input_file);
2391   free(flushing_input_file);
2392   flushing_input_file= 0;
2393
2394   if (sms==sm_SEPARATED) {
2395     notice("flush complete");
2396     SMS(NORMAL, 0, "flush complete");
2397   } else if (sms==sm_DROPPING) {
2398     SMS(DROPPED, 0, "old flush complete");
2399     search_backlog_file();
2400     notice("feed dropped, but will continue until backlog is finished");
2401   }
2402 }
2403
2404 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2405                                       void *u) {
2406   assert(!inputfile_is_done(main_input_file));
2407   statemc_check_flushing_done();
2408   statemc_check_backlog_done();
2409   return OOP_CONTINUE;
2410 }
2411
2412 static void queue_check_input_done(void) {
2413   loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2414 }
2415
2416 static void statemc_setstate(StateMachineState newsms, int periods,
2417                              const char *forlog, const char *why) {
2418   sms= newsms;
2419   sm_period_counter= periods;
2420
2421   const char *xtra= "";
2422   switch (sms) {
2423   case sm_FLUSHING:
2424   case sm_FLUSHFAILED:
2425     if (!main_input_file) xtra= "-ABSENT";
2426     break;
2427   case sm_SEPARATED:
2428   case sm_DROPPING:
2429     xtra= flushing_input_file->rd ? "-1" : "-2";
2430     break;
2431   default:;
2432   }
2433
2434   if (periods) {
2435     info("%s%s[%d] %s",forlog,xtra,periods,why);
2436   } else {
2437     info("%s%s %s",forlog,xtra,why);
2438   }
2439 }
2440
2441 /*---------- defer and backlog files ----------*/
2442
2443 static void open_defer(void) {
2444   struct stat stab;
2445
2446   if (defer) return;
2447
2448   defer= fopen(path_defer, "a+");
2449   if (!defer) sysfatal("could not open defer file %s", path_defer);
2450
2451   /* truncate away any half-written records */
2452
2453   xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2454
2455   if (stab.st_size > LONG_MAX)
2456     die("defer file %s size is far too large", path_defer);
2457
2458   if (!stab.st_size)
2459     return;
2460
2461   long orgsize= stab.st_size;
2462   long truncto= stab.st_size;
2463   for (;;) {
2464     if (!truncto) break; /* was only (if anything) one half-truncated record */
2465     if (fseek(defer, truncto-1, SEEK_SET) < 0)
2466       sysdie("seek in defer file %s while truncating partial", path_defer);
2467
2468     int r= getc(defer);
2469     if (r==EOF) {
2470       if (ferror(defer))
2471         sysdie("failed read from defer file %s", path_defer);
2472       else
2473         die("defer file %s shrank while we were checking it!", path_defer);
2474     }
2475     if (r=='\n') break;
2476     truncto--;
2477   }
2478
2479   if (stab.st_size != truncto) {
2480     warn("truncating half-record at end of defer file %s -"
2481          " shrinking by %ld bytes from %ld to %ld",
2482          path_defer, orgsize - truncto, orgsize, truncto);
2483
2484     if (fflush(defer))
2485       sysfatal("could not flush defer file %s", path_defer);
2486     if (ftruncate(fileno(defer), truncto))
2487       sysdie("could not truncate defer file %s", path_defer);
2488
2489   } else {
2490     info("continuing existing defer file %s (%ld bytes)",
2491          path_defer, orgsize);
2492   }
2493   if (fseek(defer, truncto, SEEK_SET))
2494     sysdie("could not seek to new end of defer file %s", path_defer);
2495 }
2496
2497 static void close_defer(void) {
2498   if (!defer)
2499     return;
2500
2501   struct stat stab;
2502   xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2503
2504   if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2505   defer= 0;
2506
2507   time_t now= xtime();
2508
2509   char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2510                            (unsigned long)now,
2511                            (unsigned long)stab.st_ino);
2512   if (link(path_defer, backlog))
2513     sysfatal("could not install defer file %s as backlog file %s",
2514            path_defer, backlog);
2515   if (unlink(path_defer))
2516     sysdie("could not unlink old defer link %s to backlog file %s",
2517            path_defer, backlog);
2518
2519   free(backlog);
2520
2521   if (until_backlog_nextscan < 0 ||
2522       until_backlog_nextscan > backlog_retry_minperiods + 1)
2523     until_backlog_nextscan= backlog_retry_minperiods + 1;
2524 }
2525
2526 static void poll_backlog_file(void) {
2527   if (until_backlog_nextscan < 0) return;
2528   if (until_backlog_nextscan-- > 0) return;
2529   search_backlog_file();
2530 }
2531
2532 static void search_backlog_file(void) {
2533   /* returns non-0 iff there are any backlog files */
2534
2535   glob_t gl;
2536   int r, i;
2537   struct stat stab;
2538   const char *oldest_path=0;
2539   time_t oldest_mtime=0, now;
2540
2541   if (backlog_input_file) return;
2542
2543  try_again:
2544
2545   r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2546
2547   switch (r) {
2548   case GLOB_ABORTED:
2549     sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2550   case GLOB_NOSPACE:
2551     fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2552   case 0:
2553     for (i=0; i<gl.gl_pathc; i++) {
2554       const char *path= gl.gl_pathv[i];
2555
2556       if (strchr(path,'#') || strchr(path,'~')) {
2557         debug("backlog file search skipping %s", path);
2558         continue;
2559       }
2560       r= stat(path, &stab);
2561       if (r) {
2562         syswarn("failed to stat backlog file %s", path);
2563         continue;
2564       }
2565       if (!S_ISREG(stab.st_mode)) {
2566         warn("backlog file %s is not a plain file (or link to one)", path);
2567         continue;
2568       }
2569       if (!oldest_path || stab.st_mtime < oldest_mtime) {
2570         oldest_path= path;
2571         oldest_mtime= stab.st_mtime;
2572       }
2573     }
2574   case GLOB_NOMATCH: /* fall through */
2575     break;
2576   default:
2577     sysdie("glob expansion of backlog pattern %s gave unexpected"
2578            " nonzero (error?) return value %d", globpat_backlog, r);
2579   }
2580
2581   if (!oldest_path) {
2582     debug("backlog scan: none");
2583
2584     if (sms==sm_DROPPED) {
2585       notice("feed dropped and our work is complete");
2586       xunlink(path_lock, "lockfile for old feed");
2587       exit(4);
2588     }
2589     until_backlog_nextscan= backlog_spontrescan_periods;
2590     goto xfree;
2591   }
2592
2593   now= xtime();
2594   double age= difftime(now, oldest_mtime);
2595   long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2596
2597   if (age_deficiency <= 0) {
2598     debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2599           age, age_deficiency, oldest_path);
2600
2601     backlog_input_file= open_input_file(oldest_path);
2602     if (!backlog_input_file) {
2603       warn("backlog file %s vanished as we opened it", oldest_path);
2604       globfree(&gl);
2605       goto try_again;
2606     }
2607     inputfile_reading_start(backlog_input_file);
2608     until_backlog_nextscan= -1;
2609     goto xfree;
2610   }
2611
2612   until_backlog_nextscan= age_deficiency / period_seconds;
2613
2614   if (backlog_spontrescan_periods >= 0 &&
2615       until_backlog_nextscan > backlog_spontrescan_periods)
2616     until_backlog_nextscan= backlog_spontrescan_periods;
2617
2618   debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2619         age, age_deficiency, until_backlog_nextscan, oldest_path);
2620
2621  xfree:
2622   globfree(&gl);
2623   return;
2624 }
2625
2626 /*========== flushing the feed ==========*/
2627
2628 static pid_t inndcomm_child;
2629 static int inndcomm_sentinel_fd;
2630
2631 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2632   assert(inndcomm_child);
2633   assert(fd == inndcomm_sentinel_fd);
2634   int status= xwaitpid(&inndcomm_child, "inndcomm");
2635   inndcomm_child= 0;
2636   
2637   cancel_fd_read_except(fd);
2638   xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2639   inndcomm_sentinel_fd= 0;
2640
2641   assert(!flushing_input_file);
2642
2643   if (WIFEXITED(status)) {
2644     switch (WEXITSTATUS(status)) {
2645
2646     case INNDCOMMCHILD_ESTATUS_FAIL:
2647       goto failed;
2648
2649     case INNDCOMMCHILD_ESTATUS_NONESUCH:
2650       warn("feed has been dropped by innd, finishing up");
2651       flushing_input_file= main_input_file;
2652       tailing_queue_readable(flushing_input_file);
2653         /* we probably previously returned EAGAIN from our fake read method
2654          * when in fact we were at EOF, so signal another readable event
2655          * so we actually see the EOF */
2656
2657       main_input_file= 0;
2658
2659       if (flushing_input_file) {
2660         SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2661       } else {
2662         close_defer();
2663         SMS(DROPPED, 0, "feed dropped by innd");
2664         search_backlog_file();
2665       }
2666       return OOP_CONTINUE;
2667
2668     case 0:
2669       /* as above */
2670       flushing_input_file= main_input_file;
2671       tailing_queue_readable(flushing_input_file);
2672
2673       main_input_file= open_input_file(feedfile);
2674       if (!main_input_file)
2675         die("flush succeeded but feedfile %s does not exist!", feedfile);
2676
2677       if (flushing_input_file) {
2678         SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2679       } else {
2680         close_defer();
2681         SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2682       }
2683       return OOP_CONTINUE;
2684
2685     default:
2686       goto unexpected_exitstatus;
2687
2688     }
2689   } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2690     warn("flush timed out trying to talk to innd");
2691     goto failed;
2692   } else {
2693   unexpected_exitstatus:
2694     report_child_status("inndcomm child", status);
2695   }
2696
2697  failed:
2698   SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2699   return OOP_CONTINUE;
2700 }
2701
2702 static void inndcommfail(const char *what) {
2703   syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2704   exit(INNDCOMMCHILD_ESTATUS_FAIL);
2705 }
2706
2707 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2708   int pipefds[2];
2709
2710   notice("flushing %s",why);
2711
2712   assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2713   assert(!inndcomm_child);
2714   assert(!inndcomm_sentinel_fd);
2715
2716   if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2717
2718   inndcomm_child= xfork("inndcomm child");
2719
2720   if (!inndcomm_child) {
2721     const char *flushargv[2]= { sitename, 0 };
2722     char *reply;
2723     int r;
2724
2725     xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2726     /* parent spots the autoclose of pipefds[1] when we die or exit */
2727
2728     alarm(inndcomm_flush_timeout);
2729     r= ICCopen();                         if (r)   inndcommfail("connect");
2730     r= ICCcommand('f',flushargv,&reply);  if (r<0) inndcommfail("transmit");
2731     if (!r) exit(0); /* yay! */
2732
2733     if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2734     syswarn("innd ctlinnd flush failed: innd said %s", reply);
2735     exit(INNDCOMMCHILD_ESTATUS_FAIL);
2736   }
2737
2738   xclose(pipefds[1], "inndcomm sentinel child's end",0);
2739   inndcomm_sentinel_fd= pipefds[0];
2740   assert(inndcomm_sentinel_fd);
2741   on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2742
2743   SMS(FLUSHING, 0, why);
2744 }
2745
2746 /*========== main program ==========*/
2747
2748 static void postfork_inputfile(InputFile *ipf) {
2749   if (!ipf) return;
2750   xclose(ipf->fd, "(in child) input file ", ipf->path);
2751 }
2752
2753 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2754   /* we have no stdio streams that are buffered long-term */
2755   if (!f) return;
2756   if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2757 }
2758
2759 static void postfork(void) {
2760   if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2761     sysdie("(in child) failed to reset SIGPIPE");
2762
2763   postfork_inputfile(main_input_file);
2764   postfork_inputfile(flushing_input_file);
2765
2766   Conn *conn;
2767   for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2768     conn_closefd(conn,"(in child) ");
2769
2770   postfork_stdio(defer, "defer file ", path_defer);
2771 }
2772
2773 #define EVERY(what, interval_sec, interval_usec, body)                       \
2774   static struct timeval what##_timeout = { interval_sec, interval_usec };    \
2775   static void what##_schedule(void);                                         \
2776   static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2777     body;                                                                    \
2778     what##_schedule();                                                       \
2779     return OOP_CONTINUE;                                                     \
2780   }                                                                          \
2781   static void what##_schedule(void) {                                        \
2782     loop->on_time(loop, what##_timeout, what##_timedout, 0);                 \
2783   }
2784
2785 EVERY(filepoll, 5,0, ({
2786   if (main_input_file && main_input_file->readable_callback)
2787     filemon_callback(main_input_file);
2788 }));
2789
2790 static char *debug_report_ipf(InputFile *ipf) {
2791   if (!ipf) return xasprintf("none");
2792
2793   const char *slash= strrchr(ipf->path,'/');
2794   const char *path= slash ? slash+1 : ipf->path;
2795
2796   return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2797                    ipf, path,
2798                    ipf->inprogress, (long)ipf->offset,
2799                    ipf->fd, ipf->rd ? "+" : "");
2800 }
2801
2802 EVERY(period, -1,0, ({
2803   char *dipf_main=     debug_report_ipf(main_input_file);
2804   char *dipf_flushing= debug_report_ipf(flushing_input_file);
2805   char *dipf_backlog=  debug_report_ipf(backlog_input_file);
2806
2807   debug("PERIOD"
2808         " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2809         " input_files main:%s old:%s flushing:%s"
2810         " children connecting=%ld inndcomm=%ld"
2811         ,
2812         sms_names[sms], sm_period_counter,
2813           conns.count, queue.count, until_connect,
2814         dipf_main, dipf_flushing, dipf_backlog,
2815         (long)connecting_child, (long)inndcomm_child
2816         );
2817
2818   free(dipf_main);
2819   free(dipf_flushing);
2820   free(dipf_backlog);
2821
2822   if (until_connect) until_connect--;
2823
2824   poll_backlog_file();
2825   if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2826   statemc_period_poll();
2827   check_assign_articles();
2828   check_idle_conns();
2829 }));
2830
2831
2832 /*========== option parsing ==========*/
2833
2834 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2835 static void vbadusage(const char *fmt, va_list al) {
2836   char *m= xvasprintf(fmt,al);
2837   fprintf(stderr, "bad usage: %s\n"
2838           "say --help for help, or read the manpage\n",
2839           m);
2840   if (become_daemon)
2841     syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2842   exit(8);
2843 }
2844
2845 /*---------- generic option parser ----------*/
2846
2847 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2848 static void badusage(const char *fmt, ...) {
2849   va_list al;
2850   va_start(al,fmt);
2851   vbadusage(fmt,al);
2852 }
2853
2854 enum OptFlags {
2855   of_seconds= 001000u,
2856   of_boolean= 002000u,
2857 };
2858
2859 typedef struct Option Option;
2860 typedef void OptionParser(const Option*, const char *val);
2861
2862 struct Option {
2863   int shrt;
2864   const char *lng, *formarg;
2865   void *store;
2866   OptionParser *fn;
2867   int intval;
2868 };
2869
2870 static void parse_options(const Option *options, char ***argvp) {
2871   /* on return *argvp is first non-option arg; argc is not updated */
2872
2873   for (;;) {
2874     const char *arg= *++(*argvp);
2875     if (!arg) break;
2876     if (*arg != '-') break;
2877     if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2878     int a;
2879     while ((a= *++arg)) {
2880       const Option *o;
2881       if (a=='-') {
2882         arg++;
2883         char *equals= strchr(arg,'=');
2884         int len= equals ? (equals - arg) : strlen(arg);
2885         for (o=options; o->shrt || o->lng; o++)
2886           if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2887             goto found_long;
2888         badusage("unknown long option --%s",arg);
2889       found_long:
2890         if (!o->formarg) {
2891           if (equals) badusage("option --%s does not take a value",o->lng);
2892           arg= 0;
2893         } else if (equals) {
2894           arg= equals+1;
2895         } else {
2896           arg= *++(*argvp);
2897           if (!arg) badusage("option --%s needs a value for %s",
2898                              o->lng, o->formarg);
2899         }
2900         o->fn(o, arg);
2901         break; /* eaten the whole argument now */
2902       }
2903       for (o=options; o->shrt || o->lng; o++)
2904         if (a == o->shrt)
2905           goto found_short;
2906       badusage("unknown short option -%c",a);
2907     found_short:
2908       if (!o->formarg) {
2909         o->fn(o,0);
2910       } else {
2911         if (!*++arg) {
2912           arg= *++(*argvp);
2913           if (!arg) badusage("option -%c needs a value for %s",
2914                              o->shrt, o->formarg);
2915         }
2916         o->fn(o,arg);
2917         break; /* eaten the whole argument now */
2918       }
2919     }
2920   }
2921 }
2922
2923 #define DELIMPERHAPS(delim,str)  (str) ? (delim) : "", (str) ? (str) : ""
2924
2925 static void print_options(const Option *options, FILE *f) {
2926   const Option *o;
2927   for (o=options; o->shrt || o->lng; o++) {
2928     char shrt[2] = { o->shrt, 0 };
2929     char *optspec= xasprintf("%s%s%s%s%s",
2930                              o->shrt ? "-" : "", shrt,
2931                              o->shrt && o->lng ? "|" : "",
2932                              DELIMPERHAPS("--", o->lng));
2933     fprintf(f, "  %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
2934     free(optspec);
2935   }
2936 }
2937
2938 /*---------- specific option types ----------*/
2939
2940 static void op_integer(const Option *o, const char *val) {
2941   char *ep;
2942   errno= 0;
2943   unsigned long ul= strtoul(val,&ep,10);
2944   if (*ep || ep==val || errno || ul>INT_MAX)
2945     badusage("bad integer value for %s",o->lng);
2946   int *store= o->store;
2947   *store= ul;
2948 }
2949
2950 static void op_double(const Option *o, const char *val) {
2951   int *store= o->store;
2952   char *ep;
2953   errno= 0;
2954   *store= strtod(val, &ep);
2955   if (*ep || ep==val || errno)
2956     badusage("bad floating point value for %s",o->lng);
2957 }
2958
2959 static void op_string(const Option *o, const char *val) {
2960   const char **store= o->store;
2961   *store= val;
2962 }
2963
2964 static void op_seconds(const Option *o, const char *val) {
2965   int *store= o->store;
2966   char *ep;
2967   int unit;
2968
2969   double v= strtod(val,&ep);
2970   if (ep==val) badusage("bad time/duration value for %s",o->lng);
2971
2972   if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
2973   else if (!strcmp(ep,"m") || !strcmp(ep,"min"))    unit= 60;
2974   else if (!strcmp(ep,"h") || !strcmp(ep,"hour"))   unit= 3600;
2975   else if (!strcmp(ep,"d") || !strcmp(ep,"day"))    unit= 86400;
2976   else if (!strcmp(ep,"das")) unit= 10;
2977   else if (!strcmp(ep,"hs"))  unit= 100;
2978   else if (!strcmp(ep,"ks"))  unit= 1000;
2979   else if (!strcmp(ep,"Ms"))  unit= 1000000;
2980   else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2981
2982   v *= unit;
2983   v= ceil(v);
2984   if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2985   *store= v;
2986 }
2987
2988 static void op_setint(const Option *o, const char *val) {
2989   int *store= o->store;
2990   *store= o->intval;
2991 }
2992
2993 /*---------- specific options ----------*/
2994
2995 static void help(const Option *o, const char *val);
2996
2997 static const Option innduct_options[]= {
2998 {'f',"feedfile",         "F",     &feedfile,                 op_string      },
2999 {'q',"quiet-multiple",   0,       &quiet_multiple,           op_setint, 1   },
3000 {0,"no-daemon",          0,       &become_daemon,            op_setint, 0   },
3001 {0,"no-streaming",       0,       &try_stream,               op_setint, 0   },
3002 {0,"inndconf",           "F",     &inndconffile,             op_string      },
3003 {'P',"port",             "PORT",  &port,                     op_integer     },
3004 {0,"help",               0,       0,                         help           },
3005
3006 {0,"max-connections",    "N",     &max_connections,          op_integer     },
3007 {0,"max-queue-per-conn", "N",     &max_queue_per_conn,       op_integer     },
3008 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer     },
3009 {0,"period-interval",    "TIME",  &period_seconds,           op_seconds     },
3010
3011 {0,"connection-timeout", "TIME",  &connection_setup_timeout, op_seconds     },
3012 {0,"stuck-flush-timeout","TIME",  &inndcomm_flush_timeout,   op_seconds     },
3013
3014 {0,"no-check-proportion",   "PERCENT",   &nocheck_thresh,       op_double   },
3015 {0,"no-check-response-time","ARTICLES",  &nocheck_decay,        op_double   },
3016
3017 {0,"reconnect-interval",     "PERIOD", &reconnect_delay_periods,  op_seconds },
3018 {0,"flush-retry-interval",   "PERIOD", &flushfail_retry_periods,  op_seconds },
3019 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3020 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3021 {0,"max-flush-interval",     "PERIOD", &spontaneous_flush_periods,op_seconds },
3022 {0,"idle-timeout",           "PERIOD", &need_activity_periods,    op_seconds },
3023
3024 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio,   op_double    },
3025 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer   },
3026
3027 {0,0}
3028 };
3029
3030 static void printusage(FILE *f) {
3031   fputs("usage: innduct [options] site [fqdn]\n"
3032         "available options are:\n", f);
3033   print_options(innduct_options, f);
3034 }
3035
3036 static void help(const Option *o, const char *val) {
3037   printusage(stdout);
3038   if (ferror(stdout) || fflush(stdout)) {
3039     perror("innduct: writing help");
3040     exit(12);
3041   }
3042   exit(0);
3043 }
3044
3045 static void convert_to_periods_rndup(int *store) {
3046   *store += period_seconds-1;
3047   *store /= period_seconds;
3048 }
3049
3050 int main(int argc, char **argv) {
3051   if (!argv[1]) {
3052     printusage(stderr);
3053     exit(8);
3054   }
3055
3056   parse_options(innduct_options, &argv);
3057
3058   /* arguments */
3059
3060   sitename= *argv++;
3061   if (!sitename) badusage("need site name argument");
3062   remote_host= *argv++;
3063   if (*argv) badusage("too many non-option arguments");
3064
3065   /* defaults */
3066
3067   if (!remote_host) remote_host= sitename;
3068
3069   if (nocheck_thresh < 0 || nocheck_thresh > 100)
3070     badusage("nocheck threshold percentage must be between 0..100");
3071   nocheck_thresh *= 0.01;
3072
3073   if (nocheck_decay < 0.1)
3074     badusage("nocheck decay articles must be at least 0.1");
3075   nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3076
3077   convert_to_periods_rndup(&reconnect_delay_periods);
3078   convert_to_periods_rndup(&flushfail_retry_periods);
3079   convert_to_periods_rndup(&backlog_retry_minperiods);
3080   convert_to_periods_rndup(&backlog_spontrescan_periods);
3081   convert_to_periods_rndup(&spontaneous_flush_periods);
3082   convert_to_periods_rndup(&need_activity_periods);
3083
3084   if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3085     badusage("bad input data ratio must be between 0..100");
3086   max_bad_data_ratio *= 0.01;
3087
3088   if (!feedfile) {
3089     innconf_read(inndconffile);
3090     feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3091   } else if (!feedfile[0]) {
3092     badusage("feed filename must be nonempty");
3093   } else if (feedfile[strlen(feedfile)-1]=='/') {
3094     feedfile= xasprintf("%s%s",feedfile,sitename);
3095   }
3096
3097   const char *feedfile_forbidden= "?*[~#";
3098   int c;
3099   while ((c= *feedfile_forbidden++))
3100     if (strchr(feedfile, c))
3101       badusage("feed filename may not contain metacharacter %c",c);
3102
3103   /* set things up */
3104
3105   path_lock=        xasprintf("%s_lock",      feedfile);
3106   path_flushing=    xasprintf("%s_flushing",  feedfile);
3107   path_defer=       xasprintf("%s_defer",     feedfile);
3108   path_control=     xasprintf("%s_control",   feedfile);
3109   globpat_backlog=  xasprintf("%s_backlog*",  feedfile);
3110
3111   oop_source_sys *sysloop= oop_sys_new();
3112   if (!sysloop) sysdie("could not create liboop event loop");
3113   loop= (oop_source*)sysloop;
3114
3115   if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3116     sysdie("could not ignore SIGPIPE");
3117
3118   LIST_INIT(conns);
3119   LIST_INIT(queue);
3120
3121   if (become_daemon) {
3122     int i;
3123     for (i=3; i<255; i++)
3124       /* do this now before we open syslog, etc. */
3125       close(i);
3126     openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3127
3128     int null= open("/dev/null",O_RDWR);
3129     if (null<0) sysfatal("failed to open /dev/null");
3130     dup2(null,0);
3131     dup2(null,1);
3132     dup2(null,2);
3133     xclose(null, "/dev/null original fd",0);
3134
3135     pid_t child1= xfork("daemonise first fork");
3136     if (child1) _exit(0);
3137
3138     pid_t sid= setsid();
3139     if (sid != child1) sysfatal("setsid failed");
3140
3141     pid_t child2= xfork("daemonise second fork");
3142     if (child2) _exit(0);
3143   }
3144
3145   self_pid= getpid();
3146   if (self_pid==-1) sysdie("getpid");
3147
3148   statemc_lock();
3149
3150   notice("starting");
3151
3152   if (!become_daemon)
3153     control_stdio();
3154
3155   control_init();
3156
3157   if (!filemon_method_init()) {
3158     warn("no file monitoring available, polling");
3159     filepoll_schedule();
3160   }
3161
3162   period_timeout.tv_sec= period_seconds;
3163   period_schedule();
3164
3165   statemc_init();
3166
3167   /* let's go */
3168
3169   void *r= oop_sys_run(sysloop);
3170   assert(r == OOP_ERROR);
3171   sysdie("event loop failed");
3172 }