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