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