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