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