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