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