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