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