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