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