chiark / gitweb /
a1c749196099fd480acaf76c822234139a72d4bd
[inn-innduct.git] / backends / innduct.c
1 /*
2  * todo
3  *  - reset signals TERM and INT (and HUP) in children
4  *
5  *  - manpage: document control master stuff
6  *  - admin-initiated flush
7  *
8  * debugging rune:
9  *  build-lfs/backends/innduct --connection-timeout=30 --no-daemon -C ../inn.conf -f `pwd`/fee sit localhost
10  */
11
12 /*
13  * Newsfeeds file entries should look like this:
14  *     host.name.of.site[/exclude,exclude,...]\
15  *             :pattern,pattern...[/distribution,distribution...]\
16  *             :Tf,Wnm
17  *             :
18  * or
19  *     sitename[/exclude,exclude,...]\
20  *             :pattern,pattern...[/distribution,distribution...]\
21  *             :Tf,Wnm
22  *             :host.name.of.site
23  *
24  * Four files full of
25  *    token messageid
26  * or might be blanked out
27  *    <spc><spc><spc><spc>....
28  *
29  * F site.name                 main feed file
30  *                                opened/created, then written, by innd
31  *                                read by duct
32  *                                unlinked by duct
33  *                                tokens blanked out by duct when processed
34  *   site.name_lock            lock preventing multiple ducts
35  *                                to hold lock must open,F_SETLK[W]
36  *                                  and then stat to check that locked file
37  *                                  still has name site.name_lock
38  *                                holder of this lock is "duct"
39  *                                (only) lockholder may remove the lockfile
40  * D site.name_flushing        temporary feed file during flush (or crash)
41  *                                hardlink created by duct
42  *                                unlinked by duct
43  *   site.name_defer           431'd articles, still being written,
44  *                                created, written, used by duct
45  *
46  *   site.name_backlog.<date>.<inum>
47  *                             431'd articles, ready for innxmit or duct
48  *                                created (link/mv) by duct
49  *   site.name_backlog<anything-else>  (where <anything-else> does not
50  *                                      contain '#' or '~') eg
51  *   site.name_backlog.manual
52  *                             anything the sysadmin likes (eg, feed files
53  *                             from old feeds to be merged into this one)
54  *                                created (link/mv) by admin
55  *                                may be symlinks (in which case links
56  *                                may be written through, but only links
57  *                                will be removed.
58  *
59  *                             It is safe to remove backlog files manually,
60  *                             if it's desired to throw away the backlog.
61  *
62  * Backlog files are also processed by innduct.  We find the oldest
63  * backlog file which is at least a certain amount old, and feed it
64  * back into our processing.  When every article in it has been read
65  * and processed, we unlink it and look for another backlog file.
66  *
67  * If we don't have a backlog file that we're reading, we close the
68  * defer file that we're writing and make it into a backlog file at
69  * the first convenient opportunity.
70  * -8<-
71
72
73    OVERALL STATES:
74
75                                                                 START
76                                                                   |
77      ,-->--.                                                 check F, D
78      |     |                                                      |
79      |     |                                                      |
80      |     |  <----------------<---------------------------------'|
81      |     |                                       F exists       |
82      |     |                                       D ENOENT       |
83      |     |  duct opens F                                        |
84      |     V                                                      |
85      |  Normal                                                    |
86      |   F: innd writing, duct reading                            |
87      |   D: ENOENT                                                |
88      |     |                                                      |
89      |     |  duct decides time to flush                          |
90      |     |  duct makes hardlink                                 |
91      |     |                                                      |
92      |     V                            <------------------------'|
93      |  Hardlinked                                  F==D          |
94      |   F == D: innd writing, duct reading         both exist    |
95      ^     |                                                      |
96      |     |  duct unlinks F                                      |
97      |     |                        <-----------<-------------<--'|
98      |     |                           open D         F ENOENT    |
99      |     |                           if exists                  |
100      |     |                                                      |
101      |     V                        <---------------------.       |
102      |  Moved                                             |       |
103      |   F: ENOENT                                        |       |
104      |   D: innd writing, duct reading; or ENOENT         |       |
105      |     |                                              |       |
106      |     |  duct requests flush of feed                 |       |
107      |     |   (others can too, harmlessly)               |       |
108      |     V                                              |       |
109      |  Flushing                                          |       |
110      |   F: ENOENT                                        |       |
111      |   D: innd flushing, duct; or ENOENT                |       |
112      |     |                                              |       |
113      |     |   inndcomm flush fails                       |       |
114      |     |`-------------------------->------------------'       |
115      |     |                                                      |
116      |     |   inndcomm reports no such site                      |
117      |     |`---------------------------------------------------- | -.
118      |     |                                                      |  |
119      |     |  innd finishes writing D, creates F                  |  |
120      |     |  inndcomm reports flush successful                   |  |
121      |     |                                                      |  |
122      |     V                                                      |  |
123      |  Separated                                <----------------'  |
124      |   F: innd writing                            F!=D             /
125      |   D: duct reading; or ENOENT                  both exist     /
126      |     |                                                       /
127      |     |  duct gets to the end of D                           /
128      |     |  duct opens F too                                   /
129      |     V                                                    /
130      |  Finishing                                              /
131      |   F: innd writing, duct reading                        |
132      |   D: duct finishing                                    V
133      |     |                                            Dropping
134      |     |  duct finishes processing D                 F: ENOENT
135      |     V  duct unlinks D                             D: duct reading
136      |     |                                                  |
137      `--<--'                                                  | duct finishes
138                                                               |  processing D
139                                                               | duct unlinks D
140                                                               | duct exits
141                                                               V
142                                                         Dropped
143                                                          F: ENOENT
144                                                          D: ENOENT
145                                                          duct not running
146
147    "duct reading" means innduct is reading the file but also
148    overwriting processed tokens.
149
150  * ->8- -^L-
151  *
152  * rune for printing diagrams:
153
154 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
155
156  *
157  */
158
159 /*============================== PROGRAM ==============================*/
160
161 #define _GNU_SOURCE 1
162
163 #include "config.h"
164 #include "storage.h"
165 #include "nntp.h"
166 #include "libinn.h"
167 #include "inndcomm.h"
168
169 #include "inn/list.h"
170 #include "inn/innconf.h"
171
172 #include <sys/uio.h>
173 #include <sys/types.h>
174 #include <sys/wait.h>
175 #include <sys/stat.h>
176 #include <sys/socket.h>
177 #include <sys/un.h>
178 #include <unistd.h>
179 #include <string.h>
180 #include <signal.h>
181 #include <stdio.h>
182 #include <errno.h>
183 #include <syslog.h>
184 #include <fcntl.h>
185 #include <stdarg.h>
186 #include <assert.h>
187 #include <stdlib.h>
188 #include <stddef.h>
189 #include <glob.h>
190 #include <time.h>
191 #include <math.h>
192 #include <ctype.h>
193
194 #include <oop.h>
195 #include <oop-read.h>
196
197 /*----- general definitions, probably best not changed -----*/
198
199 #define CONNCHILD_ESTATUS_STREAM   24
200 #define CONNCHILD_ESTATUS_NOSTREAM 25
201
202 #define INNDCOMMCHILD_ESTATUS_FAIL     26
203 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
204
205 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
206 #define MAX_CONTROL_COMMAND 1000
207
208 #define VA                va_list al;  va_start(al,fmt)
209 #define PRINTF(f,a)       __attribute__((__format__(printf,f,a)))
210 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
211
212 #define NEW(ptr)              ((ptr)= zxmalloc(sizeof(*(ptr))))
213 #define NEW_DECL(type,ptr) type ptr = zxmalloc(sizeof(*(ptr)))
214
215 #define DUMPV(fmt,pfx,v) fprintf(f, " " #v "=" fmt, pfx v);
216
217 #define FOR_CONN(conn) \
218   for ((conn)=LIST_HEAD(conns); (conn); (conn)=LIST_NEXT((conn)))
219
220 /*----- doubly linked lists -----*/
221
222 #define ISNODE(T)   struct node list_node
223 #define DEFLIST(T)                              \
224    typedef struct {                             \
225      union { struct list li; T *for_type; } u;  \
226      int count;                                 \
227    } T##List
228
229 #define NODE(n) (assert((void*)&(n)->list_node == (n)), &(n)->list_node)
230
231 #define LIST_CHECKCANHAVENODE(l,n) \
232   ((void)((n) == ((l).u.for_type))) /* just for the type check */
233
234 #define LIST_ADDSOMEHOW(l,n,list_addsomehow)    \
235  ( LIST_CHECKCANHAVENODE(l,n),                  \
236    list_addsomehow(&(l).u.li, NODE((n))),       \
237    (void)(l).count++                            \
238    )
239
240 #define LIST_REMSOMEHOW(l,list_remsomehow)      \
241  ( (typeof((l).u.for_type))                     \
242    ( (l).count                                  \
243      ? ( (l).count--,                           \
244          list_remsomehow(&(l).u.li) )           \
245      : 0                                        \
246      )                                          \
247    )
248
249
250 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
251 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
252 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
253 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
254
255 #define LIST_INIT(l) ((l).count=0, list_new(&(l).u.li))
256 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
257 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
258 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
259
260 #define LIST_REMOVE(l,n)                        \
261  ( LIST_CHECKCANHAVENODE(l,n),                  \
262    list_remove(NODE((n))),                      \
263    (void)(l).count--                            \
264    )
265
266 #define LIST_INSERT(l,n,pred)                                   \
267  ( LIST_CHECKCANHAVENODE(l,n),                                  \
268    LIST_CHECKCANHAVENODE(l,pred),                               \
269    list_insert((struct list*)&(l), NODE((n)), NODE((pred))),    \
270    (void)(l).count++                                            \
271    )
272
273 /*----- type predeclarations -----*/
274
275 typedef struct Conn Conn;
276 typedef struct Article Article;
277 typedef struct InputFile InputFile;
278 typedef struct XmitDetails XmitDetails;
279 typedef struct Filemon_Perfile Filemon_Perfile;
280 typedef enum StateMachineState StateMachineState;
281 typedef struct ControlCommand ControlCommand;
282
283 DEFLIST(Conn);
284 DEFLIST(Article);
285
286 /*----- function predeclarations -----*/
287
288 static void conn_maybe_write(Conn *conn);
289 static void conn_make_some_xmits(Conn *conn);
290 static void *conn_write_some_xmits(Conn *conn);
291
292 static void xmit_free(XmitDetails *d);
293
294 #define SMS(newstate, periods, why) \
295    (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
296 static void statemc_setstate(StateMachineState newsms, int periods,
297                              const char *forlog, const char *why);
298
299 static void statemc_start_flush(const char *why); /* Normal => Flushing */
300 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
301
302 static void article_done(Conn *conn, Article *art, int whichcount);
303
304 static void check_assign_articles(void);
305 static void queue_check_input_done(void);
306
307 static void statemc_check_flushing_done(void);
308 static void statemc_check_backlog_done(void);
309
310 static void postfork(void);
311 static void period(void);
312
313 static void open_defer(void);
314 static void close_defer(void);
315 static void search_backlog_file(void);
316 static void preterminate(void);
317 static void raise_default(int signo);
318 static char *debug_report_ipf(InputFile *ipf);
319
320 static void inputfile_reading_start(InputFile *ipf);
321 static void inputfile_reading_stop(InputFile *ipf);
322
323 static void filemon_start(InputFile *ipf);
324 static void filemon_stop(InputFile *ipf);
325 static void filemon_callback(InputFile *ipf);
326
327 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
328 static void connfail(Conn *conn, const char *fmt, ...)         PRINTF(2,3);
329
330 static const oop_rd_style peer_rd_style;
331 static oop_rd_call peer_rd_err, peer_rd_ok;
332
333 /*----- configuration options -----*/
334 /* when changing defaults, remember to update the manpage */
335
336 static const char *sitename, *remote_host;
337 static const char *feedfile, *realsockdir="/tmp/innduct.control";
338 static int quiet_multiple=0;
339 static int become_daemon=1, try_filemon=1;
340 static int try_stream=1;
341 static int port=119;
342 static const char *inndconffile;
343
344 static int max_connections=10;
345 static int max_queue_per_conn=200;
346 static int target_max_feedfile_size=100000;
347 static int period_seconds=60;
348 static int filepoll_seconds=5;
349
350 static int connection_setup_timeout=200;
351 static int inndcomm_flush_timeout=100;
352
353 static double nocheck_thresh= 95.0; /* converted from percentage by main */
354 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
355
356 /* all these are initialised to seconds, and converted to periods in main */
357 static int reconnect_delay_periods=1000;
358 static int flushfail_retry_periods=1000;
359 static int backlog_retry_minperiods=50;
360 static int backlog_spontrescan_periods=300;
361 static int spontaneous_flush_periods=100000;
362 static int need_activity_periods=1000;
363
364 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
365 static int max_bad_data_initial= 30;
366   /* in one corrupt 4096-byte block the number of newlines has
367    * mean 16 and standard deviation 3.99.  30 corresponds to z=+3.5 */
368
369
370 /*----- statistics -----*/
371
372 typedef enum {      /* in queue                 in conn->sent             */
373   art_Unchecked,    /*   not checked, not sent    checking                */
374   art_Wanted,       /*   checked, wanted          sent body as requested  */
375   art_Unsolicited,  /*   -                        sent body without check */
376   art_MaxState,
377 } ArtState;
378
379 static const char *const artstate_names[]=
380   { "Unchecked", "Wanted", "Unsolicited", 0 };
381
382 #define RESULT_COUNTS(RCS,RCN)                  \
383   RCS(sent)                                     \
384   RCS(accepted)                                 \
385   RCN(unwanted)                                 \
386   RCN(rejected)                                 \
387   RCN(deferred)                                 \
388   RCN(missing)                                  \
389   RCN(connretry)
390
391 #define RCI_TRIPLE_FMT_BASE "%d (id=%d,bod=%d,nc=%d)"
392 #define RCI_TRIPLE_VALS_BASE(counts,x)          \
393        counts[art_Unchecked] x                  \
394        + counts[art_Wanted] x                   \
395        + counts[art_Unsolicited] x,             \
396        counts[art_Unchecked] x                  \
397        , counts[art_Wanted] x                   \
398        , counts[art_Unsolicited] x
399
400 typedef enum {
401 #define RC_INDEX(x) RC_##x,
402   RESULT_COUNTS(RC_INDEX, RC_INDEX)
403   RCI_max
404 } ResultCountIndex;
405
406
407 /*----- transmission buffers -----*/
408
409 #define CONNIOVS 128
410
411 typedef enum {
412   xk_Malloc, xk_Const, xk_Artdata
413 } XmitKind;
414
415 struct XmitDetails {
416   XmitKind kind;
417   union {
418     char *malloc_tofree;
419     ARTHANDLE *sm_art;
420   } info;
421 };
422
423
424 /*----- core operational data structure types -----*/
425
426 struct InputFile {
427   /* This is also an instance of struct oop_readable */
428   struct oop_readable readable; /* first */
429   oop_readable_call *readable_callback;
430   void *readable_callback_user;
431
432   int fd;
433   Filemon_Perfile *filemon;
434
435   oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
436   long inprogress; /* no. of articles read but not processed */
437   off_t offset;
438   int skippinglong;
439
440   int counts[art_MaxState][RCI_max];
441   int readcount_ok, readcount_blank, readcount_err;
442   char path[];
443 };
444
445 struct Article {
446   ISNODE(Article);
447   ArtState state;
448   int midlen, missing;
449   InputFile *ipf;
450   TOKEN token;
451   off_t offset;
452   int blanklen;
453   char messageid[1];
454 };
455
456 #define SMS_LIST(X)                             \
457   X(NORMAL)                                     \
458   X(FLUSHING)                                   \
459   X(FLUSHFAILED)                                \
460   X(SEPARATED)                                  \
461   X(DROPPING)                                   \
462   X(DROPPED)
463
464 enum StateMachineState {
465 #define SMS_DEF_ENUM(s) sm_##s,
466   SMS_LIST(SMS_DEF_ENUM)
467 };
468
469 static const char *sms_names[]= {
470 #define SMS_DEF_NAME(s) #s ,
471   SMS_LIST(SMS_DEF_NAME)
472   0
473 };
474
475 struct Conn {
476   ISNODE(Conn);
477   int fd; /* may be 0, meaning closed (during construction/destruction) */
478   oop_read *rd; /* likewise */
479   int max_queue, stream, quitting;
480   int since_activity; /* periods */
481   ArticleList waiting; /* not yet told peer */
482   ArticleList priority; /* peer says send it now */
483   ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
484   struct iovec xmit[CONNIOVS];
485   XmitDetails xmitd[CONNIOVS];
486   int xmitu;
487 };
488
489
490 /*----- general operational variables -----*/
491
492 /* main initialises */
493 static oop_source *loop;
494 static ConnList conns;
495 static ArticleList queue;
496 static char *path_lock, *path_flushing, *path_defer;
497 static char *path_control, *path_dump;
498 static char *globpat_backlog;
499 static pid_t self_pid;
500
501 /* statemc_init initialises */
502 static StateMachineState sms;
503 static int sm_period_counter;
504 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
505 static FILE *defer;
506
507 /* initialisation to 0 is good */
508 static int until_connect, until_backlog_nextscan;
509 static double accept_proportion;
510 static int nocheck, nocheck_reported, in_child;
511
512 /* for simulation, debugging, etc. */
513 int simulate_flush= -1;
514
515 /*========== logging ==========*/
516
517 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
518 static void logcore(int sysloglevel, const char *fmt, ...) {
519   VA;
520   if (become_daemon) {
521     vsyslog(sysloglevel,fmt,al);
522   } else {
523     if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
524     vfprintf(stderr,fmt,al);
525     putc('\n',stderr);
526   }
527   va_end(al);
528 }
529
530 static void logv(int sysloglevel, const char *pfx, int errnoval,
531                  const char *fmt, va_list al) PRINTF(5,0);
532 static void logv(int sysloglevel, const char *pfx, int errnoval,
533                  const char *fmt, va_list al) {
534   char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
535   vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
536   msgbuf[sizeof(msgbuf)-1]= 0;
537
538   if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
539     sysloglevel= LOG_ERR; /* run by wrong user, probably */
540
541   logcore(sysloglevel, "<%s>%s: %s%s%s",
542          sitename, pfx, msgbuf,
543          errnoval>=0 ? ": " : "",
544          errnoval>=0 ? strerror(errnoval) : "");
545 }
546
547 #define diewrap(fn, pfx, sysloglevel, err, estatus)             \
548   static void fn(const char *fmt, ...) NORET_PRINTF(1,2);       \
549   static void fn(const char *fmt, ...) {                        \
550     preterminate();                                             \
551     VA;                                                         \
552     logv(sysloglevel, pfx, err, fmt, al);                       \
553     exit(estatus);                                              \
554   }
555
556 #define logwrap(fn, pfx, sysloglevel, err)              \
557   static void fn(const char *fmt, ...) PRINTF(1,2);     \
558   static void fn(const char *fmt, ...) {                \
559     VA;                                                 \
560     logv(sysloglevel, pfx, err, fmt, al);               \
561     va_end(al);                                         \
562   }
563
564 diewrap(sysdie,   " critical", LOG_CRIT,    errno, 16);
565 diewrap(die,      " critical", LOG_CRIT,    -1,    16);
566
567 diewrap(sysfatal, " fatal",    LOG_ERR,     errno, 12);
568 diewrap(fatal,    " fatal",    LOG_ERR,     -1,    12);
569
570 logwrap(syswarn,  " warning",  LOG_WARNING, errno);
571 logwrap(warn,     " warning",  LOG_WARNING, -1);
572
573 logwrap(notice,   " notice",   LOG_NOTICE,  -1);
574 logwrap(info,     " info",     LOG_INFO,    -1);
575 logwrap(debug,    " debug",    LOG_DEBUG,   -1);
576
577
578 /*========== utility functions etc. ==========*/
579
580 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
581 static char *xvasprintf(const char *fmt, va_list al) {
582   char *str;
583   int rc= vasprintf(&str,fmt,al);
584   if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
585   return str;
586 }
587 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
588 static char *xasprintf(const char *fmt, ...) {
589   VA;
590   char *str= xvasprintf(fmt,al);
591   va_end(al);
592   return str;
593 }
594
595 static int close_perhaps(int *fd) {
596   if (*fd <= 0) return 0;
597   int r= close(*fd);
598   *fd=0;
599   return r;
600 }
601 static void xclose(int fd, const char *what, const char *what2) {
602   int r= close(fd);
603   if (r) sysdie("close %s%s",what,what2?what2:"");
604 }
605 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
606   if (*fd <= 0) return;
607   xclose(*fd,what,what2);
608   *fd=0;
609 }
610
611 static pid_t xfork(const char *what) {
612   pid_t child;
613
614   child= fork();
615   if (child==-1) sysfatal("cannot fork for %s",what);
616   debug("forked %s %ld", what, (unsigned long)child);
617   if (!child) postfork();
618   return child;
619 }
620
621 static void on_fd_read_except(int fd, oop_call_fd callback) {
622   loop->on_fd(loop, fd, OOP_READ,      callback, 0);
623   loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
624 }
625 static void cancel_fd_read_except(int fd) {
626   loop->cancel_fd(loop, fd, OOP_READ);
627   loop->cancel_fd(loop, fd, OOP_EXCEPTION);
628 }
629
630 static void report_child_status(const char *what, int status) {
631   if (WIFEXITED(status)) {
632     int es= WEXITSTATUS(status);
633     if (es)
634       warn("%s: child died with error exit status %d", what, es);
635   } else if (WIFSIGNALED(status)) {
636     int sig= WTERMSIG(status);
637     const char *sigstr= strsignal(sig);
638     const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
639     if (sigstr)
640       warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
641     else
642       warn("%s: child died due to unknown fatal signal %d%s",
643            what, sig, coredump);
644   } else {
645     warn("%s: child died with unknown wait status %d", what,status);
646   }
647 }
648
649 static int xwaitpid(pid_t *pid, const char *what) {
650   int status;
651
652   int r= kill(*pid, SIGKILL);
653   if (r) sysdie("cannot kill %s child", what);
654
655   pid_t got= waitpid(*pid, &status, 0);
656   if (got==-1) sysdie("cannot reap %s child", what);
657   if (got==0) die("cannot reap %s child", what);
658
659   *pid= 0;
660
661   return status;
662 }
663
664 static void *zxmalloc(size_t sz) {
665   void *p= xmalloc(sz);
666   memset(p,0,sz);
667   return p;
668 }
669
670 static void xunlink(const char *path, const char *what) {
671   int r= unlink(path);
672   if (r) sysdie("can't unlink %s %s", path, what);
673 }
674
675 static time_t xtime(void) {
676   time_t now= time(0);
677   if (now==-1) sysdie("time(2) failed");
678   return now;
679 }
680
681 static void xsigaction(int s, const struct sigaction *sa) {
682   int r= sigaction(s,sa,0);
683   if (r) sysdie("sigaction failed for \"%s\"", strsignal(s));
684 }
685
686 static void xgettimeofday(struct timeval *tv_r) {
687   int r= gettimeofday(tv_r,0);
688   if (r) sysdie("gettimeofday(2) failed");
689 }
690
691 static void xsetnonblock(int fd, int nonblocking) {
692   int errnoval= oop_fd_nonblock(fd, nonblocking);
693   if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
694 }
695
696 static void check_isreg(const struct stat *stab, const char *path,
697                         const char *what) {
698   if (!S_ISREG(stab->st_mode))
699     die("%s %s not a plain file (mode 0%lo)",
700         what, path, (unsigned long)stab->st_mode);
701 }
702
703 static void xfstat(int fd, struct stat *stab_r, const char *what) {
704   int r= fstat(fd, stab_r);
705   if (r) sysdie("could not fstat %s", what);
706 }
707
708 static void xfstat_isreg(int fd, struct stat *stab_r,
709                          const char *path, const char *what) {
710   xfstat(fd, stab_r, what);
711   check_isreg(stab_r, path, what);
712 }
713
714 static void xlstat_isreg(const char *path, struct stat *stab,
715                          int *enoent_r /* 0 means ENOENT is fatal */,
716                          const char *what) {
717   int r= lstat(path, stab);
718   if (r) {
719     if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
720     sysdie("could not lstat %s %s", what, path);
721   }
722   if (enoent_r) *enoent_r= 0;
723   check_isreg(stab, path, what);
724 }
725
726 static int samefile(const struct stat *a, const struct stat *b) {
727   assert(S_ISREG(a->st_mode));
728   assert(S_ISREG(b->st_mode));
729   return (a->st_ino == b->st_ino &&
730           a->st_dev == b->st_dev);
731 }
732
733 static char *sanitise(const char *input, int len) {
734   static char sanibuf[100]; /* returns pointer to this buffer! */
735
736   const char *p= input;
737   const char *endp= len>=0 ? input+len : 0;
738   char *q= sanibuf;
739   *q++= '`';
740   for (;;) {
741     if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
742     int c= (!endp || p<endp) ? *p++ : 0;
743     if (!c) { *q++= '\''; *q=0; break; }
744     if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
745     sprintf(q,"\\x%02x",c);
746     q += 4;
747   }
748   return sanibuf;
749 }
750
751 static int isewouldblock(int errnoval) {
752   return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
753 }
754
755 /*========== command and control connections ==========*/
756
757 static int control_master;
758
759 typedef struct ControlConn ControlConn;
760 struct ControlConn {
761   void (*destroy)(ControlConn*);
762   int fd;
763   oop_read *rd;
764   FILE *out;
765   union {
766     struct sockaddr sa;
767     struct sockaddr_un un;
768   } sa;
769   socklen_t salen;
770 };
771
772 static const oop_rd_style control_rd_style= {
773   OOP_RD_DELIM_STRIP, '\n',
774   OOP_RD_NUL_FORBID,
775   OOP_RD_SHORTREC_FORBID
776 };
777
778 static void control_destroy(ControlConn *cc) {
779   cc->destroy(cc);
780 }
781
782 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
783   if (ferror(cc->out) | fflush(cc->out)) {
784     info("CTRL%d write error %s", cc->fd, strerror(errno));
785     control_destroy(cc);
786   }
787 }
788
789 static void control_prompt(ControlConn *cc /* may destroy*/) {
790   fprintf(cc->out, "%s| ", sitename);
791   control_checkouterr(cc);
792 }
793
794 struct ControlCommand {
795   const char *cmd;
796   void (*f)(ControlConn *cc, const ControlCommand *ccmd,
797             const char *arg, size_t argsz);
798   void *xdata;
799   int xval;
800 };
801
802 static const ControlCommand control_commands[];
803
804 #define CCMD(wh)                                                        \
805   static void ccmd_##wh(ControlConn *cc, const ControlCommand *c,       \
806                         const char *arg, size_t argsz)
807
808 CCMD(help) {
809   fputs("commands:\n", cc->out);
810   const ControlCommand *ccmd;
811   for (ccmd=control_commands; ccmd->cmd; ccmd++)
812     fprintf(cc->out, " %s\n", ccmd->cmd);
813 }
814
815 CCMD(period) { period(); }
816 CCMD(setintarg) { *(int*)c->xdata= atoi(arg); }
817 CCMD(setint) { *(int*)c->xdata= c->xval; }
818 CCMD(setint_period) { *(int*)c->xdata= c->xval; period(); }
819 CCMD(dump);
820
821 CCMD(stop) {
822   preterminate();
823   notice("terminating (CTRL%d)",cc->fd);
824   raise_default(SIGTERM);
825   abort();
826 }
827
828 static const ControlCommand control_commands[]= {
829   { "h",             ccmd_help      },
830   { "p",             ccmd_period    },
831   { "stop",          ccmd_stop      },
832   { "dump q",        ccmd_dump, 0,0 },
833   { "dump a",        ccmd_dump, 0,1 },
834
835 #define POKES(cmd,func)                                                 \
836   { cmd "sm",        func,           &sm_period_counter,       1 },     \
837   { cmd "conn",      func,           &until_connect,           0 },     \
838   { cmd "blscan",    func,           &until_backlog_nextscan,  0 },
839 POKES("prod ", ccmd_setint_period)
840 POKES("next ", ccmd_setint)
841
842   { "pretend flush", ccmd_setintarg, &simulate_flush             },
843   { "wedge blscan",  ccmd_setint,    &until_backlog_nextscan, -1 },
844   { 0 }
845 };
846
847 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
848                            const char *errmsg, int errnoval,
849                            const char *data, size_t recsz, void *cc_v) {
850   ControlConn *cc= cc_v;
851
852   if (!data) {
853     info("CTRL%d closed", cc->fd);
854     cc->destroy(cc);
855     return OOP_CONTINUE;
856   }
857
858   if (recsz == 0) goto prompt;
859
860   const ControlCommand *ccmd;
861   for (ccmd=control_commands; ccmd->cmd; ccmd++) {
862     int l= strlen(ccmd->cmd);
863     if (recsz < l) continue;
864     if (recsz > l && data[l] != ' ') continue;
865     if (memcmp(data, ccmd->cmd, l)) continue;
866
867     int argl= (int)recsz - (l+1); 
868     ccmd->f(cc, ccmd, argl>=0 ? data+l+1 : 0, argl);
869     goto prompt;
870   }
871
872   fputs("unknown command; h for help\n", cc->out);
873
874  prompt:
875   control_prompt(cc);
876   return OOP_CONTINUE;
877 }
878
879 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
880                             const char *errmsg, int errnoval,
881                             const char *data, size_t recsz, void *cc_v) {
882   ControlConn *cc= cc_v;
883   
884   info("CTRL%d read error %s", cc->fd, errmsg);
885   cc->destroy(cc);
886   return OOP_CONTINUE;
887 }
888
889 static int control_conn_startup(ControlConn *cc /* may destroy*/,
890                                 const char *how) {
891   cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
892   if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
893
894   int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
895                       control_rd_ok, cc,
896                       control_rd_err, cc);
897   if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
898
899   info("CTRL%d %s ready", cc->fd, how);
900   control_prompt(cc);
901   return 0;
902 }
903
904 static void control_stdio_destroy(ControlConn *cc) {
905   if (cc->rd) {
906     oop_rd_cancel(cc->rd);
907     errno= oop_rd_delete_tidy(cc->rd);
908     if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
909   }
910   free(cc);
911 }
912
913 static void control_stdio(void) {
914   NEW_DECL(ControlConn *,cc);
915   cc->destroy= control_stdio_destroy;
916
917   cc->fd= 0;
918   cc->out= stdout;
919   int r= control_conn_startup(cc,"stdio");
920   if (r) cc->destroy(cc);
921 }
922
923 static void control_accepted_destroy(ControlConn *cc) {
924   if (cc->rd) {
925     oop_rd_cancel(cc->rd);
926     oop_rd_delete_kill(cc->rd);
927   }
928   if (cc->out) { fclose(cc->out); cc->fd=0; }
929   close_perhaps(&cc->fd);
930   free(cc);
931 }
932
933 static void *control_master_readable(oop_source *lp, int master,
934                                      oop_event ev, void *u) {
935   NEW_DECL(ControlConn *,cc);
936   cc->destroy= control_accepted_destroy;
937
938   cc->salen= sizeof(cc->sa);
939   cc->fd= accept(master, &cc->sa.sa, &cc->salen);
940   if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
941
942   cc->out= fdopen(cc->fd, "w");
943   if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
944
945   int r= control_conn_startup(cc, "accepted");
946   if (r) goto x;
947
948   return OOP_CONTINUE;
949
950  x:
951   cc->destroy(cc);
952   return OOP_CONTINUE;
953 }
954
955 #define NOCONTROL(...) do{                                              \
956     syswarn("no control socket, because failed to " __VA_ARGS__);       \
957     goto nocontrol;                                                     \
958   }while(0)
959
960 static void control_init(void) {
961   char *real=0;
962   
963   union {
964     struct sockaddr sa;
965     struct sockaddr_un un;
966   } sa;
967
968   memset(&sa,0,sizeof(sa));
969   int maxlen= sizeof(sa.un.sun_path);
970
971   int reallen= readlink(path_control, sa.un.sun_path, maxlen);
972   if (reallen<0) {
973     if (errno != ENOENT)
974       NOCONTROL("readlink control socket symlink path %s", path_control);
975   }
976   if (reallen >= maxlen) {
977     debug("control socket symlink path too long (r=%d)",reallen);
978     xunlink(path_control, "old (overlong) control socket symlink");
979     reallen= -1;
980   }
981   
982   if (reallen<0) {
983     struct stat stab;
984     int r= lstat(realsockdir,&stab);
985     if (r) {
986       if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
987
988       r= mkdir(realsockdir, 0700);
989       if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
990
991     } else {
992       uid_t self= geteuid();
993       if (!S_ISDIR(stab.st_mode) ||
994           stab.st_uid != self ||
995           stab.st_mode & 0007) {
996         warn("no control socket, because real socket directory"
997              " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
998              !!S_ISDIR(stab.st_mode),
999              (unsigned long)stab.st_uid, (unsigned long)self,
1000              (unsigned long)stab.st_mode & 0777UL);
1001         goto nocontrol;
1002       }
1003     }
1004
1005     real= xasprintf("%s/s%lx.%lx", realsockdir,
1006                     (unsigned long)xtime(), (unsigned long)self_pid);
1007     int reallen= strlen(real);
1008
1009     if (reallen >= maxlen) {
1010       warn("no control socket, because tmpnam gave overly-long path"
1011            " %s", real);
1012       goto nocontrol;
1013     }
1014     r= symlink(real, path_control);
1015     if (r) NOCONTROL("make control socket path %s a symlink to real"
1016                      " socket path %s", path_control, real);
1017     memcpy(sa.un.sun_path, real, reallen);
1018   }
1019
1020   int r= unlink(sa.un.sun_path);
1021   if (r && errno!=ENOENT)
1022     NOCONTROL("remove old real socket %s", sa.un.sun_path);
1023
1024   control_master= socket(PF_UNIX, SOCK_STREAM, 0);
1025   if (control_master<0) NOCONTROL("create new control socket");
1026
1027   sa.un.sun_family= AF_UNIX;
1028   int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
1029   r= bind(control_master, &sa.sa, sl);
1030   if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
1031
1032   r= listen(control_master, 5);
1033   if (r) NOCONTROL("listen");
1034
1035   xsetnonblock(control_master, 1);
1036
1037   loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
1038   info("control socket ok, real path %s", sa.un.sun_path);
1039
1040   return;
1041
1042  nocontrol:
1043   free(real);
1044   xclose_perhaps(&control_master, "control master",0);
1045   return;
1046 }
1047
1048 /*========== management of connections ==========*/
1049
1050 static void conn_closefd(Conn *conn, const char *msgprefix) {
1051   int r= close_perhaps(&conn->fd);
1052   if (r) info("C%d %serror closing socket: %s",
1053               conn->fd, msgprefix, strerror(errno));
1054 }
1055
1056 static void conn_dispose(Conn *conn) {
1057   if (!conn) return;
1058   if (conn->rd) {
1059     oop_rd_cancel(conn->rd);
1060     oop_rd_delete_kill(conn->rd);
1061     conn->rd= 0;
1062   }
1063   if (conn->fd) {
1064     loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1065     loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
1066   }
1067   conn_closefd(conn,"");
1068   free(conn);
1069   until_connect= reconnect_delay_periods;
1070 }
1071
1072 static void *conn_exception(oop_source *lp, int fd,
1073                             oop_event ev, void *conn_v) {
1074   Conn *conn= conn_v;
1075   unsigned char ch;
1076   assert(fd == conn->fd);
1077   assert(ev == OOP_EXCEPTION);
1078   int r= read(conn->fd, &ch, 1);
1079   if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1080   else connfail(conn,"exceptional condition on socket (peer sent urgent"
1081                 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1082   return OOP_CONTINUE;
1083 }  
1084
1085 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1086   int requeue[art_MaxState];
1087   memset(requeue,0,sizeof(requeue));
1088
1089   Article *art;
1090   while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1091   while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1092   while ((art= LIST_REMHEAD(conn->sent))) {
1093     requeue[art->state]++;
1094     if (art->state==art_Unsolicited) art->state= art_Unchecked;
1095     LIST_ADDTAIL(queue,art);
1096   }
1097
1098   int i;
1099   XmitDetails *d;
1100   for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1101     xmit_free(d);
1102
1103   char *m= xvasprintf(fmt,al);
1104   warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1105        conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1106   free(m);
1107
1108   LIST_REMOVE(conns,conn);
1109   conn_dispose(conn);
1110   check_assign_articles();
1111 }
1112
1113 static void connfail(Conn *conn, const char *fmt, ...) {
1114   va_list al;
1115   va_start(al,fmt);
1116   vconnfail(conn,fmt,al);
1117   va_end(al);
1118 }
1119
1120 static void check_idle_conns(void) {
1121   Conn *conn;
1122   FOR_CONN(conn)
1123     conn->since_activity++;
1124  search_again:
1125   FOR_CONN(conn) {
1126     if (conn->since_activity <= need_activity_periods) continue;
1127
1128     /* We need to shut this down */
1129     if (conn->quitting)
1130       connfail(conn,"timed out waiting for response to QUIT");
1131     else if (conn->sent.count)
1132       connfail(conn,"timed out waiting for responses");
1133     else if (conn->waiting.count || conn->priority.count)
1134       connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1135     else if (conn->xmitu)
1136       connfail(conn,"peer has been sending responses"
1137                " before receiving our commands!");
1138     else {
1139       static const char quitcmd[]= "QUIT\r\n";
1140       int todo= sizeof(quitcmd)-1;
1141       const char *p= quitcmd;
1142       for (;;) {
1143         int r= write(conn->fd, p, todo);
1144         if (r<0) {
1145           if (isewouldblock(errno))
1146             connfail(conn, "blocked writing QUIT to idle connection");
1147           else
1148             connfail(conn, "failed to write QUIT to idle connection: %s",
1149                      strerror(errno));
1150           break;
1151         }
1152         assert(r<=todo);
1153         todo -= r;
1154         if (!todo) {
1155           conn->quitting= 1;
1156           conn->since_activity= 0;
1157           debug("C%d is idle, quitting", conn->fd);
1158           break;
1159         }
1160       }
1161     }
1162     goto search_again;
1163   }
1164 }  
1165
1166 /*---------- making new connections ----------*/
1167
1168 static pid_t connecting_child;
1169 static int connecting_fdpass_sock;
1170
1171 static void connect_attempt_discard(void) {
1172   if (connecting_child) {
1173     int status= xwaitpid(&connecting_child, "connect");
1174     if (!(WIFEXITED(status) ||
1175           (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1176       report_child_status("connect", status);
1177   }
1178   if (connecting_fdpass_sock) {
1179     cancel_fd_read_except(connecting_fdpass_sock);
1180     xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1181   }
1182 }
1183
1184 #define PREP_DECL_MSG_CMSG(msg)                 \
1185   char msgbyte= 0;                              \
1186   struct iovec msgiov;                          \
1187   msgiov.iov_base= &msgbyte;                    \
1188   msgiov.iov_len= 1;                            \
1189   struct msghdr msg;                            \
1190   memset(&msg,0,sizeof(msg));                   \
1191   char msg##cbuf[CMSG_SPACE(sizeof(int))];      \
1192   msg.msg_iov= &msgiov;                         \
1193   msg.msg_iovlen= 1;                            \
1194   msg.msg_control= msg##cbuf;                   \
1195   msg.msg_controllen= sizeof(msg##cbuf);
1196
1197 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1198   Conn *conn= 0;
1199
1200   assert(fd == connecting_fdpass_sock);
1201
1202   PREP_DECL_MSG_CMSG(msg);
1203   
1204   ssize_t rs= recvmsg(fd, &msg, 0);
1205   if (rs<0) {
1206     if (isewouldblock(errno)) return OOP_CONTINUE;
1207     syswarn("failed to read socket from connecting child");
1208     goto x;
1209   }
1210
1211   NEW(conn);
1212   LIST_INIT(conn->waiting);
1213   LIST_INIT(conn->priority);
1214   LIST_INIT(conn->sent);
1215
1216   struct cmsghdr *h= 0;
1217   if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1218   if (!h) {
1219     int status= xwaitpid(&connecting_child, "connect child (broken)");
1220
1221     if (WIFEXITED(status)) {
1222       if (WEXITSTATUS(status) != 0 &&
1223           WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1224           WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1225         /* child already reported the problem */;
1226       else {
1227         if (e == OOP_EXCEPTION)
1228           warn("connect: connection child exited code %d but"
1229                " unexpected exception on fdpass socket",
1230                WEXITSTATUS(status));
1231         else
1232           warn("connect: connection child exited code %d but"
1233                " no cmsg (rs=%d)",
1234                WEXITSTATUS(status), (int)rs);
1235       }
1236     } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1237       warn("connect: connection attempt timed out");
1238     } else {
1239       report_child_status("connect", status);
1240     }
1241     goto x;
1242   }
1243
1244 #define CHK(field, val)                                                  \
1245   if (h->cmsg_##field != val) {                                          \
1246     die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1247         h->cmsg_##field, val);                                           \
1248     goto x;                                                              \
1249   }
1250   CHK(level, SOL_SOCKET);
1251   CHK(type,  SCM_RIGHTS);
1252   CHK(len,   CMSG_LEN(sizeof(conn->fd)));
1253 #undef CHK
1254
1255   if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1256
1257   memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1258
1259   int status;
1260   pid_t got= waitpid(connecting_child, &status, 0);
1261   if (got==-1) sysdie("connect: real wait for child");
1262   assert(got == connecting_child);
1263   connecting_child= 0;
1264
1265   if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1266   int es= WEXITSTATUS(status);
1267   switch (es) {
1268   case CONNCHILD_ESTATUS_STREAM:    conn->stream= 1;   break;
1269   case CONNCHILD_ESTATUS_NOSTREAM:  conn->stream= 0;   break;
1270   default:
1271     fatal("connect: child gave unexpected exit status %d", es);
1272   }
1273
1274   /* Phew! */
1275   conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1276
1277   loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1278   conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1279   if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1280   int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1281                      &peer_rd_ok, conn,
1282                      &peer_rd_err, conn);
1283   if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1284
1285   notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1286   LIST_ADDHEAD(conns, conn);
1287
1288   connect_attempt_discard();
1289   check_assign_articles();
1290   return OOP_CONTINUE;
1291
1292  x:
1293   conn_dispose(conn);
1294   connect_attempt_discard();
1295   return OOP_CONTINUE;
1296 }
1297
1298 static int allow_connect_start(void) {
1299   return conns.count < max_connections
1300     && !connecting_child
1301     && !until_connect;
1302 }
1303
1304 static void connect_start(void) {
1305   assert(!connecting_child);
1306   assert(!connecting_fdpass_sock);
1307
1308   info("starting connection attempt");
1309
1310   int socks[2];
1311   int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1312   if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1313
1314   connecting_child= xfork("connection");
1315
1316   if (!connecting_child) {
1317     FILE *cn_from, *cn_to;
1318     char buf[NNTP_STRLEN+100];
1319     int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1320
1321     xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1322
1323     alarm(connection_setup_timeout);
1324     if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1325       int l= strlen(buf);
1326       int stripped=0;
1327       while (l>0) {
1328         unsigned char c= buf[l-1];
1329         if (!isspace(c)) break;
1330         if (c=='\n' || c=='\r') stripped=1;
1331         --l;
1332       }
1333       if (!buf[0]) {
1334         sysfatal("connect: connection attempt failed");
1335       } else {
1336         buf[l]= 0;
1337         fatal("connect: %s: %s", stripped ? "rejected" : "failed",
1338               sanitise(buf,-1));
1339       }
1340     }
1341     if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1342       sysfatal("connect: authentication failed");
1343     if (try_stream) {
1344       if (fputs("MODE STREAM\r\n", cn_to)==EOF ||
1345           fflush(cn_to))
1346         sysfatal("connect: could not send MODE STREAM");
1347       buf[sizeof(buf)-1]= 0;
1348       if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1349         if (ferror(cn_from))
1350           sysfatal("connect: could not read response to MODE STREAM");
1351         else
1352           fatal("connect: connection close in response to MODE STREAM");
1353       }
1354       int l= strlen(buf);
1355       assert(l>=1);
1356       if (buf[l-1]!='\n')
1357         fatal("connect: response to MODE STREAM is too long: %.100s...",
1358               sanitise(buf,-1));
1359       l--;  if (l>0 && buf[l-1]=='\r') l--;
1360       buf[l]= 0;
1361       char *ep;
1362       int rcode= strtoul(buf,&ep,10);
1363       if (ep != &buf[3])
1364         fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf,-1));
1365
1366       switch (rcode) {
1367       case 203:
1368         exitstatus= CONNCHILD_ESTATUS_STREAM;
1369         break;
1370       case 480:
1371       case 500:
1372         break;
1373       default:
1374         warn("connect: unexpected response to MODE STREAM: %.50s",
1375              sanitise(buf,-1));
1376         exitstatus= 2;
1377         break;
1378       }
1379     }
1380     int fd= fileno(cn_from);
1381
1382     PREP_DECL_MSG_CMSG(msg);
1383     struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1384     cmsg->cmsg_level= SOL_SOCKET;
1385     cmsg->cmsg_type=  SCM_RIGHTS;
1386     cmsg->cmsg_len=   CMSG_LEN(sizeof(fd));
1387     memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1388
1389     msg.msg_controllen= cmsg->cmsg_len;
1390     r= sendmsg(socks[1], &msg, 0);
1391     if (r<0) sysdie("sendmsg failed for new connection");
1392     if (r!=1) die("sendmsg for new connection gave wrong result %d",r);
1393
1394     _exit(exitstatus);
1395   }
1396
1397   xclose(socks[1], "connecting fdpass child's socket",0);
1398   connecting_fdpass_sock= socks[0];
1399   xsetnonblock(connecting_fdpass_sock, 1);
1400   on_fd_read_except(connecting_fdpass_sock, connchild_event);
1401 }
1402
1403 /*---------- assigning articles to conns, and transmitting ----------*/
1404
1405 static void check_assign_articles(void) {
1406   for (;;) {
1407     if (!queue.count)
1408       break;
1409
1410     Conn *walk, *use=0;
1411     int spare=0, inqueue=0;
1412
1413     /* Find a connection to offer this article.  We prefer a busy
1414      * connection to an idle one, provided it's not full.  We take the
1415      * first (oldest) and since that's stable, it will mean we fill up
1416      * connections in order.  That way if we have too many
1417      * connections, the spare ones will go away eventually.
1418      */
1419     FOR_CONN(walk) {
1420       if (walk->quitting) continue;
1421       inqueue= walk->sent.count + walk->priority.count
1422              + walk->waiting.count;
1423       spare= walk->max_queue - inqueue;
1424       assert(inqueue <= max_queue_per_conn);
1425       assert(spare >= 0);
1426       if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1427       else if (spare>0) /*working*/ { use= walk; break; }
1428     }
1429     if (use) {
1430       if (!inqueue) use->since_activity= 0; /* reset idle counter */
1431       while (spare>0) {
1432         Article *art= LIST_REMHEAD(queue);
1433         if (!art) break;
1434         LIST_ADDTAIL(use->waiting, art);
1435         spare--;
1436       }
1437       conn_maybe_write(use);
1438     } else if (allow_connect_start()) {
1439       until_connect= reconnect_delay_periods;
1440       connect_start();
1441       break;
1442     } else {
1443       break;
1444     }
1445   }
1446 }
1447
1448 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1449   conn_maybe_write(u);
1450   return OOP_CONTINUE;
1451 }
1452
1453 static void conn_maybe_write(Conn *conn)  {
1454   for (;;) {
1455     conn_make_some_xmits(conn);
1456     if (!conn->xmitu) {
1457       loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1458       return;
1459     }
1460
1461     void *rp= conn_write_some_xmits(conn);
1462     if (rp==OOP_CONTINUE) {
1463       loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1464       return;
1465     } else if (rp==OOP_HALT) {
1466       return;
1467     } else if (!rp) {
1468       /* transmitted everything */
1469     } else {
1470       abort();
1471     }
1472   }
1473 }
1474
1475 /*========== article transmission ==========*/
1476
1477 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1478                   XmitKind kind) { /* caller must then fill in details */
1479   struct iovec *v= &conn->xmit[conn->xmitu];
1480   XmitDetails *d= &conn->xmitd[conn->xmitu++];
1481   v->iov_base= (char*)data;
1482   v->iov_len= len;
1483   d->kind= kind;
1484   return d;
1485 }
1486
1487 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1488   xmit_core(conn,data,len, xk_Const);
1489 }
1490 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1491
1492 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1493   XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1494   d->info.sm_art= ah;
1495 }
1496
1497 static void xmit_free(XmitDetails *d) {
1498   switch (d->kind) {
1499   case xk_Malloc:  free(d->info.malloc_tofree);   break;
1500   case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1501   case xk_Const:                                  break;
1502   default: abort();
1503   }
1504 }
1505
1506 static void *conn_write_some_xmits(Conn *conn) {
1507   /* return values:
1508    *      0:            nothing more to write, no need to call us again
1509    *      OOP_CONTINUE: more to write but fd not writeable
1510    *      OOP_HALT:     disaster, have destroyed conn
1511    */
1512   for (;;) {
1513     int count= conn->xmitu;
1514     if (!count) return 0;
1515
1516     if (count > IOV_MAX) count= IOV_MAX;
1517     ssize_t rs= writev(conn->fd, conn->xmit, count);
1518     if (rs < 0) {
1519       if (isewouldblock(errno)) return OOP_CONTINUE;
1520       connfail(conn, "write failed: %s", strerror(errno));
1521       return OOP_HALT;
1522     }
1523     assert(rs > 0);
1524
1525     int done;
1526     for (done=0; rs && done<conn->xmitu; done++) {
1527       struct iovec *vp= &conn->xmit[done];
1528       XmitDetails *dp= &conn->xmitd[done];
1529       if (rs > vp->iov_len) {
1530         rs -= vp->iov_len;
1531         xmit_free(dp);
1532       } else {
1533         vp->iov_base= (char*)vp->iov_base + rs;
1534         vp->iov_len -= rs;
1535       }
1536     }
1537     int newu= conn->xmitu - done;
1538     memmove(conn->xmit,  conn->xmit  + done, newu * sizeof(*conn->xmit));
1539     memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1540     conn->xmitu= newu;
1541   }
1542 }
1543
1544 static void conn_make_some_xmits(Conn *conn) {
1545   for (;;) {
1546     if (conn->xmitu+5 > CONNIOVS)
1547       break;
1548
1549     Article *art= LIST_REMHEAD(conn->priority);
1550     if (!art) art= LIST_REMHEAD(conn->waiting);
1551     if (!art) break;
1552
1553     if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1554       /* actually send it */
1555
1556       ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1557
1558       art->state=
1559         art->state == art_Unchecked ? art_Unsolicited :
1560         art->state == art_Wanted    ? art_Wanted      :
1561         (abort(),-1);
1562
1563       if (!artdata) art->missing= 1;
1564       art->ipf->counts[art->state][ artdata ? RC_sent : RC_missing ]++;
1565
1566       if (conn->stream) {
1567         if (artdata) {
1568           XMIT_LITERAL("TAKETHIS ");
1569           xmit_noalloc(conn, art->messageid, art->midlen);
1570           XMIT_LITERAL("\r\n");
1571           xmit_artbody(conn, artdata);
1572         } else {
1573           article_done(conn, art, -1);
1574           continue;
1575         }
1576       } else {
1577         /* we got 235 from IHAVE */
1578         if (artdata) {
1579           xmit_artbody(conn, artdata);
1580         } else {
1581           XMIT_LITERAL(".\r\n");
1582         }
1583       }
1584
1585       LIST_ADDTAIL(conn->sent, art);
1586
1587     } else {
1588       /* check it */
1589
1590       if (conn->stream)
1591         XMIT_LITERAL("CHECK ");
1592       else
1593         XMIT_LITERAL("IHAVE ");
1594       xmit_noalloc(conn, art->messageid, art->midlen);
1595       XMIT_LITERAL("\r\n");
1596
1597       assert(art->state == art_Unchecked);
1598       art->ipf->counts[art->state][RC_sent]++;
1599       LIST_ADDTAIL(conn->sent, art);
1600     }
1601   }
1602 }
1603
1604
1605 /*========== handling responses from peer ==========*/
1606
1607 static const oop_rd_style peer_rd_style= {
1608   OOP_RD_DELIM_STRIP, '\n',
1609   OOP_RD_NUL_FORBID,
1610   OOP_RD_SHORTREC_FORBID
1611 };
1612
1613 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1614                          const char *errmsg, int errnoval,
1615                          const char *data, size_t recsz, void *conn_v) {
1616   Conn *conn= conn_v;
1617   connfail(conn, "error receiving from peer: %s", errmsg);
1618   return OOP_CONTINUE;
1619 }
1620
1621 static Article *article_reply_check(Conn *conn, const char *response,
1622                                     int code_indicates_streaming,
1623                                     int must_have_sent
1624                                         /* 1:yes, -1:no, 0:dontcare */,
1625                                     const char *sanitised_response) {
1626   Article *art= LIST_HEAD(conn->sent);
1627
1628   if (!art) {
1629     connfail(conn,
1630              "peer gave unexpected response when no commands outstanding: %s",
1631              sanitised_response);
1632     return 0;
1633   }
1634
1635   if (code_indicates_streaming) {
1636     assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1637     if (!conn->stream) {
1638       connfail(conn, "peer gave streaming response code "
1639                " to IHAVE or subsequent body: %s", sanitised_response);
1640       return 0;
1641     }
1642     const char *got_mid= response+4;
1643     int got_midlen= strcspn(got_mid, " \n\r");
1644     if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1645       connfail(conn, "peer gave streaming response with syntactically invalid"
1646                " messageid: %s", sanitised_response);
1647       return 0;
1648     }
1649     if (got_midlen != art->midlen ||
1650         memcmp(got_mid, art->messageid, got_midlen)) {
1651       connfail(conn, "peer gave streaming response code to wrong article -"
1652                " probable synchronisation problem; we offered: %s;"
1653                " peer said: %s",
1654                art->messageid, sanitised_response);
1655       return 0;
1656     }
1657   } else {
1658     if (conn->stream) {
1659       connfail(conn, "peer gave non-streaming response code to"
1660                " CHECK/TAKETHIS: %s", sanitised_response);
1661       return 0;
1662     }
1663   }
1664
1665   if (must_have_sent>0 && art->state < art_Wanted) {
1666     connfail(conn, "peer says article accepted but"
1667              " we had not sent the body: %s", sanitised_response);
1668     return 0;
1669   }
1670   if (must_have_sent<0 && art->state >= art_Wanted) {
1671     connfail(conn, "peer says please sent the article but we just did: %s",
1672              sanitised_response);
1673     return 0;
1674   }
1675
1676   Article *art_again= LIST_REMHEAD(conn->sent);
1677   assert(art_again == art);
1678   return art;
1679 }
1680
1681 static void update_nocheck(int accepted) {
1682   accept_proportion *= nocheck_decay;
1683   accept_proportion += accepted * (1.0 - nocheck_decay);
1684   int new_nocheck= accept_proportion >= nocheck_thresh;
1685   if (new_nocheck && !nocheck_reported) {
1686     notice("entering nocheck mode for the first time");
1687     nocheck_reported= 1;
1688   } else if (new_nocheck != nocheck) {
1689     debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1690   }
1691   nocheck= new_nocheck;
1692 }
1693
1694 static void article_done(Conn *conn, Article *art, int whichcount) {
1695   if (!art->missing) art->ipf->counts[art->state][whichcount]++;
1696
1697   if (whichcount == RC_accepted) update_nocheck(1);
1698   else if (whichcount == RC_unwanted) update_nocheck(0);
1699
1700   InputFile *ipf= art->ipf;
1701
1702   while (art->blanklen) {
1703     static const char spaces[]=
1704       "                                                                "
1705       "                                                                "
1706       "                                                                "
1707       "                                                                "
1708       "                                                                "
1709       "                                                                "
1710       "                                                                "
1711       "                                                                "
1712       "                                                                ";
1713     int w= art->blanklen;  if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1714     int r= pwrite(ipf->fd, spaces, w, art->offset);
1715     if (r==-1) {
1716       if (errno==EINTR) continue;
1717       sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1718              art->messageid, art->blanklen,
1719              (unsigned long)art->offset, ipf->path);
1720     }
1721     assert(r>=0 && r<=w);
1722     art->blanklen -= w;
1723     art->offset += w;
1724   }
1725
1726   ipf->inprogress--;
1727   assert(ipf->inprogress >= 0);
1728   free(art);
1729
1730   if (!ipf->inprogress && ipf != main_input_file)
1731     queue_check_input_done();
1732 }
1733
1734 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1735                         const char *errmsg, int errnoval,
1736                         const char *data, size_t recsz, void *conn_v) {
1737   Conn *conn= conn_v;
1738
1739   if (ev == OOP_RD_EOF) {
1740     connfail(conn, "unexpected EOF from peer");
1741     return OOP_CONTINUE;
1742   }
1743   assert(ev == OOP_RD_OK);
1744
1745   char *sani= sanitise(data,-1);
1746
1747   char *ep;
1748   unsigned long code= strtoul(data, &ep, 10);
1749   if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1750     connfail(conn, "badly formatted response from peer: %s", sani);
1751     return OOP_CONTINUE;
1752   }
1753
1754   int conn_busy=
1755     conn->waiting.count ||
1756     conn->priority.count ||
1757     conn->sent.count ||
1758     conn->xmitu;
1759
1760   if (conn->quitting) {
1761     if (code!=205 && code!=503) {
1762       connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1763     } else {
1764       notice("C%d idle connection closed by us", conn->fd);
1765       assert(!conn_busy);
1766       LIST_REMOVE(conns,conn);
1767       conn_dispose(conn);
1768     }
1769     return OOP_CONTINUE;
1770   }
1771
1772   conn->since_activity= 0;
1773   Article *art;
1774
1775 #define GET_ARTICLE(musthavesent) do{                                         \
1776     art= article_reply_check(conn, data, code_streaming, musthavesent, sani); \
1777     if (!art) return OOP_CONTINUE; /* reply_check has failed the conn */      \
1778   }while(0) 
1779
1780 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) do{       \
1781     code_streaming= (streaming);                                \
1782     GET_ARTICLE(musthavesent);                                  \
1783     article_done(conn, art, RC_##how);                          \
1784     goto dealtwith;                                             \
1785   }while(0)
1786
1787 #define PEERBADMSG(m) do {                                      \
1788     connfail(conn, m ": %s", sani);  return OOP_CONTINUE;       \
1789   }while(0)
1790
1791   int code_streaming= 0;
1792
1793   switch (code) {
1794
1795   case 400: PEERBADMSG("peer stopped accepting articles");
1796   default:  PEERBADMSG("peer sent unexpected message");
1797
1798   case 503:
1799     if (conn_busy) PEERBADMSG("peer timed us out");
1800     notice("C%d idle connection closed by peer", conn->fd);
1801     LIST_REMOVE(conns,conn);
1802     conn_dispose(conn);
1803     return OOP_CONTINUE;
1804
1805   case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1806   case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1807
1808   case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1809   case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1810
1811   case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1812   case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1813
1814   case 238: /* CHECK says send it */
1815     code_streaming= 1;
1816   case 335: /* IHAVE says send it */
1817     GET_ARTICLE(-1);
1818     assert(art->state == art_Unchecked);
1819     art->ipf->counts[art->state][RC_accepted]++;
1820     art->state= art_Wanted;
1821     LIST_ADDTAIL(conn->priority, art);
1822     break;
1823
1824   case 431: /* CHECK or TAKETHIS says try later */
1825     code_streaming= 1;
1826   case 436: /* IHAVE says try later */
1827     GET_ARTICLE(0);
1828     open_defer();
1829     if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1830         || fflush(defer))
1831       sysfatal("write to defer file %s",path_defer);
1832     article_done(conn, art, RC_deferred);
1833     break;
1834
1835   }
1836 dealtwith:
1837
1838   conn_maybe_write(conn);
1839   check_assign_articles();
1840   return OOP_CONTINUE;
1841 }
1842
1843
1844 /*========== monitoring of input files ==========*/
1845
1846 static void feedfile_eof(InputFile *ipf) {
1847   assert(ipf != main_input_file); /* promised by tailing_try_read */
1848   inputfile_reading_stop(ipf);
1849
1850   if (ipf == flushing_input_file) {
1851     assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1852     if (main_input_file) inputfile_reading_start(main_input_file);
1853     statemc_check_flushing_done();
1854   } else if (ipf == backlog_input_file) {
1855     statemc_check_backlog_done();
1856   } else {
1857     abort(); /* supposed to wait rather than get EOF on main input file */
1858   }
1859 }
1860
1861 static InputFile *open_input_file(const char *path) {
1862   int fd= open(path, O_RDWR);
1863   if (fd<0) {
1864     if (errno==ENOENT) return 0;
1865     sysfatal("unable to open input file %s", path);
1866   }
1867   assert(fd>0);
1868
1869   InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1870   memset(ipf,0,sizeof(*ipf));
1871
1872   ipf->fd= fd;
1873   strcpy(ipf->path, path);
1874
1875   return ipf;
1876 }
1877
1878 static void close_input_file(InputFile *ipf) { /* does not free */
1879   assert(!ipf->readable_callback); /* must have had ->on_cancel */
1880   assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1881   assert(!ipf->rd); /* must have had inputfile_reading_stop */
1882   assert(!ipf->inprogress); /* no dangling pointers pointing here */
1883   xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1884 }
1885
1886
1887 /*---------- dealing with articles read in the input file ----------*/
1888
1889 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1890                                    const char *data, const char *how) {
1891   warn("corrupted file: %s, offset %lu: %s: in %s",
1892        ipf->path, (unsigned long)offset, how, sanitise(data,-1));
1893   ipf->readcount_err++;
1894   if (ipf->readcount_err > max_bad_data_initial +
1895       (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1896     die("too much garbage in input file!  (%d errs, %d ok, %d blank)",
1897         ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1898   return OOP_CONTINUE;
1899 }
1900
1901 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1902                                oop_rd_event ev, const char *errmsg,
1903                                int errnoval, const char *data, size_t recsz,
1904                                void *ipf_v) {
1905   InputFile *ipf= ipf_v;
1906   assert(ev == OOP_RD_SYSTEM);
1907   errno= errnoval;
1908   sysdie("error reading input file: %s, offset %lu",
1909          ipf->path, (unsigned long)ipf->offset);
1910 }
1911
1912 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1913                                   oop_rd_event ev, const char *errmsg,
1914                                   int errnoval, const char *data, size_t recsz,
1915                                   void *ipf_v) {
1916   InputFile *ipf= ipf_v;
1917   Article *art;
1918   char tokentextbuf[sizeof(TOKEN)*2+3];
1919
1920   if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1921
1922   off_t old_offset= ipf->offset;
1923   ipf->offset += recsz + !!(ev == OOP_RD_OK);
1924
1925 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1926
1927   if (ev==OOP_RD_PARTREC)
1928     feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1929     /* but process it anyway */
1930
1931   if (ipf->skippinglong) {
1932     if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1933     return OOP_CONTINUE;
1934   }
1935   if (ev==OOP_RD_LONG) {
1936     ipf->skippinglong= 1;
1937     X_BAD_DATA("overly long line");
1938   }
1939
1940   if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1941   if (!recsz) X_BAD_DATA("empty line");
1942
1943   if (data[0]==' ') {
1944     if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1945     ipf->readcount_blank++;
1946     return OOP_CONTINUE;
1947   }
1948
1949   char *space= strchr(data,' ');
1950   int tokenlen= space-data;
1951   int midlen= (int)recsz-tokenlen-1;
1952   if (midlen <= 2) X_BAD_DATA("no room for messageid");
1953   if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1954
1955   if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1956   memcpy(tokentextbuf, data, tokenlen);
1957   tokentextbuf[tokenlen]= 0;
1958   if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1959
1960   ipf->readcount_ok++;
1961
1962   art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1963   memset(art,0,sizeof(art));
1964   art->state= art_Unchecked;
1965   art->midlen= midlen;
1966   art->ipf= ipf;  ipf->inprogress++;
1967   art->token= TextToToken(tokentextbuf);
1968   art->offset= old_offset;
1969   art->blanklen= recsz;
1970   strcpy(art->messageid, space+1);
1971   LIST_ADDTAIL(queue, art);
1972
1973   if (sms==sm_NORMAL && ipf==main_input_file &&
1974       ipf->offset >= target_max_feedfile_size)
1975     statemc_start_flush("feed file size");
1976
1977   check_assign_articles();
1978   return OOP_CONTINUE;
1979 }
1980
1981 /*========== tailing input file ==========*/
1982
1983 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1984                                      void *user) {
1985   InputFile *ipf= user;
1986   return ipf->readable_callback(loop, &ipf->readable,
1987                                 ipf->readable_callback_user);
1988 }
1989
1990 static void tailing_on_cancel(struct oop_readable *rable) {
1991   InputFile *ipf= (void*)rable;
1992
1993   if (ipf->filemon) filemon_stop(ipf);
1994   loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1995   ipf->readable_callback= 0;
1996 }
1997
1998 static void tailing_queue_readable(InputFile *ipf) {
1999   /* lifetime of ipf here is OK because destruction will cause
2000    * on_cancel which will cancel this callback */
2001   loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
2002 }
2003
2004 static int tailing_on_readable(struct oop_readable *rable,
2005                                 oop_readable_call *cb, void *user) {
2006   InputFile *ipf= (void*)rable;
2007
2008   tailing_on_cancel(rable);
2009   ipf->readable_callback= cb;
2010   ipf->readable_callback_user= user;
2011   filemon_start(ipf);
2012
2013   tailing_queue_readable(ipf);
2014   return 0;
2015 }
2016
2017 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
2018                                 size_t length) {
2019   InputFile *ipf= (void*)rable;
2020   for (;;) {
2021     ssize_t r= read(ipf->fd, buffer, length);
2022     if (r==-1) {
2023       if (errno==EINTR) continue;
2024       return r;
2025     }
2026     if (!r) {
2027       if (ipf==main_input_file) {
2028         errno=EAGAIN;
2029         return -1;
2030       } else if (ipf==flushing_input_file) {
2031         assert(ipf->rd);
2032         assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2033       } else if (ipf==backlog_input_file) {
2034         assert(ipf->rd);
2035       } else {
2036         abort();
2037       }
2038     }
2039     tailing_queue_readable(ipf);
2040     return r;
2041   }
2042 }
2043
2044 /*---------- filemon implemented with inotify ----------*/
2045
2046 #if defined(HAVE_SYS_INOTIFY_H) && !defined(HAVE_FILEMON)
2047 #define HAVE_FILEMON
2048
2049 #include <sys/inotify.h>
2050
2051 static int filemon_inotify_fd;
2052 static int filemon_inotify_wdmax;
2053 static InputFile **filemon_inotify_wd2ipf;
2054
2055 struct Filemon_Perfile {
2056   int wd;
2057 };
2058
2059 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
2060   int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
2061   if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
2062
2063   if (wd >= filemon_inotify_wdmax) {
2064     int newmax= wd+2;
2065     filemon_inotify_wd2ipf= xrealloc(filemon_inotify_wd2ipf,
2066                                  sizeof(*filemon_inotify_wd2ipf) * newmax);
2067     memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
2068            sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
2069     filemon_inotify_wdmax= newmax;
2070   }
2071
2072   assert(!filemon_inotify_wd2ipf[wd]);
2073   filemon_inotify_wd2ipf[wd]= ipf;
2074
2075   debug("filemon inotify startfile %p wd=%d wdmax=%d",
2076         ipf, wd, filemon_inotify_wdmax);
2077
2078   pf->wd= wd;
2079 }
2080
2081 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
2082   int wd= pf->wd;
2083   debug("filemon inotify stopfile %p wd=%d", ipf, wd);
2084   int r= inotify_rm_watch(filemon_inotify_fd, wd);
2085   if (r) sysdie("inotify_rm_watch");
2086   filemon_inotify_wd2ipf[wd]= 0;
2087 }
2088
2089 static void *filemon_inotify_readable(oop_source *lp, int fd,
2090                                       oop_event e, void *u) {
2091   struct inotify_event iev;
2092   for (;;) {
2093     int r= read(filemon_inotify_fd, &iev, sizeof(iev));
2094     if (r==-1) {
2095       if (isewouldblock(errno)) break;
2096       sysdie("read from inotify master");
2097     } else if (r==sizeof(iev)) {
2098       assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
2099     } else {
2100       die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
2101     }
2102     InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
2103     debug("filemon inotify readable read %p wd=%d", ipf, iev.wd);
2104     filemon_callback(ipf);
2105   }
2106   return OOP_CONTINUE;
2107 }
2108
2109 static int filemon_method_init(void) {
2110   filemon_inotify_fd= inotify_init();
2111   if (filemon_inotify_fd<0) {
2112     syswarn("filemon/inotify: inotify_init failed");
2113     return 0;
2114   }
2115   xsetnonblock(filemon_inotify_fd, 1);
2116   loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable, 0);
2117
2118   debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2119   return 1;
2120 }
2121
2122 static void filemon_method_dump_info(FILE *f) {
2123   int i;
2124   fprintf(f,"inotify");
2125   DUMPV("%d",,filemon_inotify_fd);
2126   DUMPV("%d",,filemon_inotify_wdmax);
2127   for (i=0; i<filemon_inotify_wdmax; i++)
2128     fprintf(f," wd2ipf[%d]=%p\n", i, filemon_inotify_wd2ipf[i],);
2129 }
2130
2131 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2132
2133 /*---------- filemon dummy implementation ----------*/
2134
2135 #if !defined(HAVE_FILEMON)
2136
2137 struct Filemon_Perfile { int dummy; };
2138
2139 static int filemon_method_init(void) {
2140   warn("filemon/dummy: no filemon method compiled in");
2141   return 0;
2142 }
2143 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2144 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2145 static void filemon_method_dump_info(FILE *f) { fprintf(f,"dummy\n"); }
2146
2147 #endif /* !HAVE_FILEMON */
2148
2149 /*---------- filemon generic interface ----------*/
2150
2151 static void filemon_start(InputFile *ipf) {
2152   assert(!ipf->filemon);
2153
2154   NEW(ipf->filemon);
2155   filemon_method_startfile(ipf, ipf->filemon);
2156 }
2157
2158 static void filemon_stop(InputFile *ipf) {
2159   if (!ipf->filemon) return;
2160   filemon_method_stopfile(ipf, ipf->filemon);
2161   free(ipf->filemon);
2162   ipf->filemon= 0;
2163 }
2164
2165 static void filemon_callback(InputFile *ipf) {
2166   if (ipf && ipf->readable_callback) /* so filepoll() can be naive */
2167     ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2168 }
2169
2170 /*---------- interface to start and stop an input file ----------*/
2171
2172 static const oop_rd_style feedfile_rdstyle= {
2173   OOP_RD_DELIM_STRIP, '\n',
2174   OOP_RD_NUL_PERMIT,
2175   OOP_RD_SHORTREC_LONG,
2176 };
2177
2178 static void inputfile_reading_start(InputFile *ipf) {
2179   assert(!ipf->rd);
2180   ipf->readable.on_readable= tailing_on_readable;
2181   ipf->readable.on_cancel=   tailing_on_cancel;
2182   ipf->readable.try_read=    tailing_try_read;
2183   ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2184   ipf->readable.delete_kill= 0;
2185
2186   ipf->readable_callback= 0;
2187   ipf->readable_callback_user= 0;
2188
2189   ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2190   assert(ipf->rd);
2191
2192   int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2193                      feedfile_got_article,ipf, feedfile_read_err, ipf);
2194   if (r) sysdie("unable start reading feedfile %s",ipf->path);
2195 }
2196
2197 static void inputfile_reading_stop(InputFile *ipf) {
2198   assert(ipf->rd);
2199   oop_rd_cancel(ipf->rd);
2200   oop_rd_delete(ipf->rd);
2201   ipf->rd= 0;
2202   assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2203 }
2204
2205
2206 /*========== interaction with innd - state machine ==========*/
2207
2208 /* See official state diagram at top of file.  We implement
2209  * this as follows:
2210  * -8<-
2211
2212             .=======.
2213             ||START||
2214             `======='
2215                 |
2216                 | open F
2217                 |
2218                 |    F ENOENT
2219                 |`---------------------------------------------------.
2220       F OPEN OK |                                                    |
2221                 |`---------------- - - -                             |
2222        D ENOENT |       D EXISTS   see OVERALL STATES diagram        |
2223                 |                  for full startup logic            |
2224      ,--------->|                                                    |
2225      |          V                                                    |
2226      |     ============                                       try to |
2227      |      NORMAL                                            open D |
2228      |     [Normal]                                                  |
2229      |      main F tail                                              |
2230      |     ============                                              V
2231      |          |                                                    |
2232      |          | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT            |
2233      ^          | hardlink F to D                                    |
2234      |     [Hardlinked]                                              |
2235      |          | unlink F                                           |
2236      |          | our handle onto F is now onto D                    |
2237      |     [Moved]                                                   |
2238      |          |                                                    |
2239      |          |<-------------------<---------------------<---------+
2240      |          |                                                    |
2241      |          | spawn inndcomm flush                               |
2242      |          V                                                    |
2243      |     ==================                                        |
2244      |      FLUSHING[-ABSENT]                                        |
2245      |     [Flushing]                                                |
2246      |     main D tail/none                                          |
2247      |     ==================                                        |
2248      |          |                                                    |
2249      |          |   INNDCOMM FLUSH FAILS                             ^
2250      |          |`----------------------->----------.                |
2251      |          |                                   |                |
2252      |          |   NO SUCH SITE                    V                |
2253      ^          |`--------------->----.         ==================== |
2254      |          |                      \        FLUSHFAILED[-ABSENT] |
2255      |          |                       \         [Moved]            |
2256      |          | FLUSH OK               \       main D tail/none    |
2257      |          | open F                  \     ==================== |
2258      |          |                          \        |                |
2259      |          |                           \       | TIME TO RETRY  |
2260      |          |`------->----.     ,---<---'\      `----------------'
2261      |          |    D NONE   |     | D NONE  `----.
2262      |          V             |     |              V
2263      |     =============      V     V             ============
2264      |      SEPARATED-1       |     |              DROPPING-1
2265      |      flsh->rd!=0       |     |              flsh->rd!=0
2266      |     [Separated]        |     |             [Dropping]
2267      |      main F idle       |     |              main none
2268      |      old D tail        |     |              old D tail
2269      |     =============      |     |             ============
2270      |          |             |     | install       |
2271      ^          | EOF ON D    |     |  defer        | EOF ON D
2272      |          V             |     |               V
2273      |     ===============    |     |             ===============
2274      |      SEPARATED-2       |     |              DROPPING-2
2275      |      flsh->rd==0       |     V              flsh->rd==0
2276      |     [Finishing]        |     |             [Dropping]
2277      |      main F tail       |     `.             main none
2278      |      old D closed      |       `.           old D closed
2279      |     ===============    V         `.        ===============
2280      |          |                         `.          |
2281      |          | ALL D PROCESSED           `.        | ALL D PROCESSED
2282      |          V install defer as backlog    `.      | install defer
2283      ^          | close D                       `.    | close D
2284      |          | unlink D                        `.  | unlink D
2285      |          |                                  |  |
2286      |          |                                  V  V
2287      `----------'                               ==============
2288                                                  DROPPED
2289                                                 [Dropped]
2290                                                  main none
2291                                                  old none
2292                                                  some backlog
2293                                                 ==============
2294                                                       |
2295                                                       | ALL BACKLOG DONE
2296                                                       |
2297                                                       | unlink lock
2298                                                       | exit
2299                                                       V
2300                                                   ==========
2301                                                    (ESRCH)
2302                                                   [Droppped]
2303                                                   ==========
2304  * ->8-
2305  */
2306
2307 static void startup_set_input_file(InputFile *f) {
2308   assert(!main_input_file);
2309   main_input_file= f;
2310   inputfile_reading_start(f);
2311 }
2312
2313 static void statemc_lock(void) {
2314   int lockfd;
2315   struct stat stab, stabf;
2316   
2317   for (;;) {
2318     lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2319     if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2320
2321     struct flock fl;
2322     memset(&fl,0,sizeof(fl));
2323     fl.l_type= F_WRLCK;
2324     fl.l_whence= SEEK_SET;
2325     int r= fcntl(lockfd, F_SETLK, &fl);
2326     if (r==-1) {
2327       if (errno==EACCES || isewouldblock(errno)) {
2328         if (quiet_multiple) exit(0);
2329         fatal("another duct holds the lockfile");
2330       }
2331       sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2332     }
2333
2334     xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2335     int lock_noent;
2336     xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2337
2338     if (!lock_noent && samefile(&stab, &stabf))
2339       break;
2340
2341     xclose(lockfd, "stale lockfile ", path_lock);
2342   }
2343
2344   FILE *lockfile= fdopen(lockfd, "w");
2345   if (!lockfile) sysdie("fdopen lockfile");
2346
2347   int r= ftruncate(lockfd, 0);
2348   if (r) sysdie("truncate lockfile to write new info");
2349
2350   if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2351               (unsigned long)self_pid,
2352               sitename, feedfile, remote_host) == EOF ||
2353       fflush(lockfile))
2354     sysfatal("write info to lockfile %s", path_lock);
2355
2356   debug("startup: locked");
2357 }
2358
2359 static void statemc_init(void) {
2360   struct stat stabdefer;
2361
2362   search_backlog_file();
2363
2364   int defer_noent;
2365   xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2366   if (defer_noent) {
2367     debug("startup: ductdefer ENOENT");
2368   } else {
2369     debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2370     switch (stabdefer.st_nlink==1) {
2371     case 1:
2372       open_defer(); /* so that we will later close it and rename it */
2373       break;
2374     case 2:
2375       xunlink(path_defer, "stale defer file link"
2376               " (presumably hardlink to backlog file)");
2377       break;
2378     default:
2379       die("defer file %s has unexpected link count %d",
2380           path_defer, stabdefer.st_nlink);
2381     }
2382   }
2383
2384   struct stat stab_f, stab_d;
2385   int noent_f;
2386
2387   InputFile *file_d= open_input_file(path_flushing);
2388   if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2389
2390   xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2391
2392   if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2393     debug("startup: F==D => Hardlinked");
2394     xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2395     noent_f= 1;
2396   }
2397
2398   if (noent_f) {
2399     debug("startup: F ENOENT => Moved");
2400     if (file_d) startup_set_input_file(file_d);
2401     spawn_inndcomm_flush("feedfile missing at startup");
2402     /* => Flushing, sms:=FLUSHING */
2403   } else {
2404     if (file_d) {
2405       debug("startup: F!=D => Separated");
2406       startup_set_input_file(file_d);
2407       SMS(SEPARATED, 0, "found both old and current feed files");
2408     } else {
2409       debug("startup: F exists, D ENOENT => Normal");
2410       InputFile *file_f= open_input_file(feedfile);
2411       if (!file_f) die("feed file vanished during startup");
2412       startup_set_input_file(file_f);
2413       SMS(NORMAL, spontaneous_flush_periods, "normal startup");
2414     }
2415   }
2416 }
2417
2418 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2419   assert(sms == sm_NORMAL);
2420
2421   debug("starting flush (%s) (%lu >?= %lu) (%d)",
2422         why,
2423         (unsigned long)(main_input_file ? main_input_file->offset : 0),
2424         (unsigned long)target_max_feedfile_size,
2425         sm_period_counter);
2426
2427   int r= link(feedfile, path_flushing);
2428   if (r) sysfatal("link feedfile %s to flushing file %s",
2429                   feedfile, path_flushing);
2430   /* => Hardlinked */
2431
2432   xunlink(feedfile, "old feedfile link");
2433   /* => Moved */
2434
2435   spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2436 }
2437
2438 static void statemc_period_poll(void) {
2439   if (!sm_period_counter) return;
2440   sm_period_counter--;
2441   assert(sm_period_counter>=0);
2442
2443   if (sm_period_counter) return;
2444   switch (sms) {
2445   case sm_NORMAL:
2446     statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2447     break;
2448   case sm_FLUSHFAILED:
2449     spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2450     break;
2451   default:
2452     abort();
2453   }
2454 }
2455
2456 static int inputfile_is_done(InputFile *ipf) {
2457   if (!ipf) return 0;
2458   if (ipf->inprogress) return 0; /* new article in the meantime */
2459   if (ipf->rd) return 0; /* not had EOF */
2460   return 1;
2461 }
2462
2463 static void notice_processed(InputFile *ipf, int completed,
2464                              const char *what, const char *spec) {
2465   if (!ipf) return; /* allows preterminate to be lazy */
2466
2467 #define RCI_NOTHING(x) /* nothing */
2468 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2469 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2470
2471 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2472
2473   char *inprog= completed
2474     ? xasprintf("%s","") /* GCC produces a stupid warning for printf("") ! */
2475     : xasprintf(" inprogress=%ld", ipf->inprogress);
2476
2477   info("%s %s%s read=%d (+bl=%d,+err=%d)%s"
2478        " offered=%d (ch=%d,nc=%d) accepted=%d (ch=%d,nc=%d)"
2479        RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2480        ,
2481        completed?"completed":"processed", what, spec,
2482        ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err, inprog,
2483        CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2484        , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2485        CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2486        , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2487        RESULT_COUNTS(RCI_NOTHING,  RCI_TRIPLE_VALS)
2488        );
2489
2490   free(inprog);
2491
2492 #undef CNT
2493 }
2494
2495 static void statemc_check_backlog_done(void) {
2496   InputFile *ipf= backlog_input_file;
2497   if (!inputfile_is_done(ipf)) return;
2498
2499   const char *slash= strrchr(ipf->path, '/');
2500   const char *leaf= slash ? slash+1 : ipf->path;
2501   const char *under= strchr(slash, '_');
2502   const char *rest= under ? under+1 : leaf;
2503   if (!strncmp(rest,"backlog",7)) rest += 7;
2504   notice_processed(ipf,1,"backlog ",rest);
2505
2506   close_input_file(ipf);
2507   if (unlink(ipf->path)) {
2508     if (errno != ENOENT)
2509       sysdie("could not unlink processed backlog file %s", ipf->path);
2510     warn("backlog file %s vanished while we were reading it"
2511          " so we couldn't remove it (but it's done now, anyway)",
2512          ipf->path);
2513   }
2514   free(ipf);
2515   backlog_input_file= 0;
2516   search_backlog_file();
2517   return;
2518 }
2519
2520 static void statemc_check_flushing_done(void) {
2521   InputFile *ipf= flushing_input_file;
2522   if (!inputfile_is_done(ipf)) return;
2523
2524   assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2525
2526   notice_processed(ipf,1,"feedfile","");
2527
2528   close_defer();
2529
2530   xunlink(path_flushing, "old flushing file");
2531
2532   close_input_file(flushing_input_file);
2533   free(flushing_input_file);
2534   flushing_input_file= 0;
2535
2536   if (sms==sm_SEPARATED) {
2537     notice("flush complete");
2538     SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2539   } else if (sms==sm_DROPPING) {
2540     SMS(DROPPED, 0, "old flush complete");
2541     search_backlog_file();
2542     notice("feed dropped, but will continue until backlog is finished");
2543   }
2544 }
2545
2546 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2547                                       void *u) {
2548   assert(!inputfile_is_done(main_input_file));
2549   statemc_check_flushing_done();
2550   statemc_check_backlog_done();
2551   return OOP_CONTINUE;
2552 }
2553
2554 static void queue_check_input_done(void) {
2555   loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2556 }
2557
2558 static void statemc_setstate(StateMachineState newsms, int periods,
2559                              const char *forlog, const char *why) {
2560   sms= newsms;
2561   sm_period_counter= periods;
2562
2563   const char *xtra= "";
2564   switch (sms) {
2565   case sm_FLUSHING:
2566   case sm_FLUSHFAILED:
2567     if (!main_input_file) xtra= "-ABSENT";
2568     break;
2569   case sm_SEPARATED:
2570   case sm_DROPPING:
2571     xtra= flushing_input_file->rd ? "-1" : "-2";
2572     break;
2573   default:;
2574   }
2575
2576   if (periods) {
2577     info("state %s%s[%d] %s",forlog,xtra,periods,why);
2578   } else {
2579     info("state %s%s %s",forlog,xtra,why);
2580   }
2581 }
2582
2583 /*---------- defer and backlog files ----------*/
2584
2585 static void open_defer(void) {
2586   struct stat stab;
2587
2588   if (defer) return;
2589
2590   defer= fopen(path_defer, "a+");
2591   if (!defer) sysfatal("could not open defer file %s", path_defer);
2592
2593   /* truncate away any half-written records */
2594
2595   xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2596
2597   if (stab.st_size > LONG_MAX)
2598     die("defer file %s size is far too large", path_defer);
2599
2600   if (!stab.st_size)
2601     return;
2602
2603   long orgsize= stab.st_size;
2604   long truncto= stab.st_size;
2605   for (;;) {
2606     if (!truncto) break; /* was only (if anything) one half-truncated record */
2607     if (fseek(defer, truncto-1, SEEK_SET) < 0)
2608       sysdie("seek in defer file %s while truncating partial", path_defer);
2609
2610     int r= getc(defer);
2611     if (r==EOF) {
2612       if (ferror(defer))
2613         sysdie("failed read from defer file %s", path_defer);
2614       else
2615         die("defer file %s shrank while we were checking it!", path_defer);
2616     }
2617     if (r=='\n') break;
2618     truncto--;
2619   }
2620
2621   if (stab.st_size != truncto) {
2622     warn("truncating half-record at end of defer file %s -"
2623          " shrinking by %ld bytes from %ld to %ld",
2624          path_defer, orgsize - truncto, orgsize, truncto);
2625
2626     if (fflush(defer))
2627       sysfatal("could not flush defer file %s", path_defer);
2628     if (ftruncate(fileno(defer), truncto))
2629       sysdie("could not truncate defer file %s", path_defer);
2630
2631   } else {
2632     info("continuing existing defer file %s (%ld bytes)",
2633          path_defer, orgsize);
2634   }
2635   if (fseek(defer, truncto, SEEK_SET))
2636     sysdie("could not seek to new end of defer file %s", path_defer);
2637 }
2638
2639 static void close_defer(void) {
2640   if (!defer)
2641     return;
2642
2643   struct stat stab;
2644   xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2645
2646   if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2647   defer= 0;
2648
2649   time_t now= xtime();
2650
2651   char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2652                            (unsigned long)now,
2653                            (unsigned long)stab.st_ino);
2654   if (link(path_defer, backlog))
2655     sysfatal("could not install defer file %s as backlog file %s",
2656            path_defer, backlog);
2657   if (unlink(path_defer))
2658     sysdie("could not unlink old defer link %s to backlog file %s",
2659            path_defer, backlog);
2660
2661   free(backlog);
2662
2663   if (until_backlog_nextscan < 0 ||
2664       until_backlog_nextscan > backlog_retry_minperiods + 1)
2665     until_backlog_nextscan= backlog_retry_minperiods + 1;
2666 }
2667
2668 static void poll_backlog_file(void) {
2669   if (until_backlog_nextscan < 0) return;
2670   if (until_backlog_nextscan-- > 0) return;
2671   search_backlog_file();
2672 }
2673
2674 static void search_backlog_file(void) {
2675   /* returns non-0 iff there are any backlog files */
2676
2677   glob_t gl;
2678   int r, i;
2679   struct stat stab;
2680   const char *oldest_path=0;
2681   time_t oldest_mtime=0, now;
2682
2683   if (backlog_input_file) return;
2684
2685  try_again:
2686
2687   r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2688
2689   switch (r) {
2690   case GLOB_ABORTED:
2691     sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2692   case GLOB_NOSPACE:
2693     fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2694   case 0:
2695     for (i=0; i<gl.gl_pathc; i++) {
2696       const char *path= gl.gl_pathv[i];
2697
2698       if (strchr(path,'#') || strchr(path,'~')) {
2699         debug("backlog file search skipping %s", path);
2700         continue;
2701       }
2702       r= stat(path, &stab);
2703       if (r) {
2704         syswarn("failed to stat backlog file %s", path);
2705         continue;
2706       }
2707       if (!S_ISREG(stab.st_mode)) {
2708         warn("backlog file %s is not a plain file (or link to one)", path);
2709         continue;
2710       }
2711       if (!oldest_path || stab.st_mtime < oldest_mtime) {
2712         oldest_path= path;
2713         oldest_mtime= stab.st_mtime;
2714       }
2715     }
2716   case GLOB_NOMATCH: /* fall through */
2717     break;
2718   default:
2719     sysdie("glob expansion of backlog pattern %s gave unexpected"
2720            " nonzero (error?) return value %d", globpat_backlog, r);
2721   }
2722
2723   if (!oldest_path) {
2724     debug("backlog scan: none");
2725
2726     if (sms==sm_DROPPED) {
2727       preterminate();
2728       notice("feed dropped and our work is complete");
2729
2730       int r= unlink(path_control);
2731       if (r && errno!=ENOENT)
2732         syswarn("failed to remove control symlink for old feed");
2733
2734       xunlink(path_lock,    "lockfile for old feed");
2735       exit(4);
2736     }
2737     until_backlog_nextscan= backlog_spontrescan_periods;
2738     goto xfree;
2739   }
2740
2741   now= xtime();
2742   double age= difftime(now, oldest_mtime);
2743   long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2744
2745   if (age_deficiency <= 0) {
2746     debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2747           age, age_deficiency, oldest_path);
2748
2749     backlog_input_file= open_input_file(oldest_path);
2750     if (!backlog_input_file) {
2751       warn("backlog file %s vanished as we opened it", oldest_path);
2752       globfree(&gl);
2753       goto try_again;
2754     }
2755     inputfile_reading_start(backlog_input_file);
2756     until_backlog_nextscan= -1;
2757     goto xfree;
2758   }
2759
2760   until_backlog_nextscan= age_deficiency / period_seconds;
2761
2762   if (backlog_spontrescan_periods >= 0 &&
2763       until_backlog_nextscan > backlog_spontrescan_periods)
2764     until_backlog_nextscan= backlog_spontrescan_periods;
2765
2766   debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2767         age, age_deficiency, until_backlog_nextscan, oldest_path);
2768
2769  xfree:
2770   globfree(&gl);
2771   return;
2772 }
2773
2774 /*---------- shutdown and signal handling ----------*/
2775
2776 static void preterminate(void) {
2777   if (in_child) return;
2778   notice_processed(main_input_file,0,"feedfile","");
2779   notice_processed(flushing_input_file,0,"flushing file","");
2780   if (backlog_input_file)
2781     notice_processed(backlog_input_file,0, "backlog file ",
2782                      backlog_input_file->path);
2783 }
2784
2785 static int signal_self_pipe[2];
2786 static sig_atomic_t terminate_sig_flag;
2787
2788 static void raise_default(int signo) {
2789   struct sigaction sa;
2790   memset(&sa,0,sizeof(sa));
2791   sa.sa_handler= SIG_DFL;
2792   xsigaction(signo,&sa);
2793   raise(signo);
2794 }
2795
2796 static void *sigarrived_event(oop_source *lp, int fd, oop_event e, void *u) {
2797   assert(fd=signal_self_pipe[0]);
2798   char buf[PIPE_BUF];
2799   int r= read(signal_self_pipe[0], buf, sizeof(buf));
2800   if (r<0 && !isewouldblock(errno)) sysdie("failed to read signal self pipe");
2801   if (r==0) die("eof on signal self pipe");
2802   if (terminate_sig_flag) {
2803     preterminate();
2804     notice("terminating (%s)", strsignal(terminate_sig_flag));
2805     raise_default(terminate_sig_flag);
2806     abort();
2807   }
2808   return OOP_CONTINUE;
2809 }
2810
2811 static void sigarrived_handler(int signum) {
2812   static char x;
2813   switch (signum) {
2814   case SIGINT: case SIGTERM:
2815     if (!terminate_sig_flag) terminate_sig_flag= signum;
2816     break;
2817   default:
2818     abort();
2819   }
2820   write(signal_self_pipe[1],&x,1);
2821 }
2822
2823 static void init_signals(void) {
2824   if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2825     sysdie("could not ignore SIGPIPE");
2826
2827   if (pipe(signal_self_pipe)) sysfatal("create self-pipe for signals");
2828
2829   xsetnonblock(signal_self_pipe[0],1);
2830   xsetnonblock(signal_self_pipe[1],1);
2831
2832   struct sigaction sa;
2833   memset(&sa,0,sizeof(sa));
2834   sa.sa_handler= sigarrived_handler;
2835   sa.sa_flags= SA_RESTART;
2836   xsigaction(SIGTERM,&sa);
2837   xsigaction(SIGINT,&sa);
2838
2839   on_fd_read_except(signal_self_pipe[0], sigarrived_event);
2840 }
2841
2842 /*========== flushing the feed ==========*/
2843
2844 static pid_t inndcomm_child;
2845 static int inndcomm_sentinel_fd;
2846
2847 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2848   assert(inndcomm_child);
2849   assert(fd == inndcomm_sentinel_fd);
2850   int status= xwaitpid(&inndcomm_child, "inndcomm");
2851   inndcomm_child= 0;
2852   
2853   cancel_fd_read_except(fd);
2854   xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2855   inndcomm_sentinel_fd= 0;
2856
2857   assert(!flushing_input_file);
2858
2859   if (WIFEXITED(status)) {
2860     switch (WEXITSTATUS(status)) {
2861
2862     case INNDCOMMCHILD_ESTATUS_FAIL:
2863       goto failed;
2864
2865     case INNDCOMMCHILD_ESTATUS_NONESUCH:
2866       notice("feed has been dropped by innd, finishing up");
2867       flushing_input_file= main_input_file;
2868       tailing_queue_readable(flushing_input_file);
2869         /* we probably previously returned EAGAIN from our fake read method
2870          * when in fact we were at EOF, so signal another readable event
2871          * so we actually see the EOF */
2872
2873       main_input_file= 0;
2874
2875       if (flushing_input_file) {
2876         SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2877       } else {
2878         close_defer();
2879         SMS(DROPPED, 0, "feed dropped by innd");
2880         search_backlog_file();
2881       }
2882       return OOP_CONTINUE;
2883
2884     case 0:
2885       /* as above */
2886       flushing_input_file= main_input_file;
2887       tailing_queue_readable(flushing_input_file);
2888
2889       main_input_file= open_input_file(feedfile);
2890       if (!main_input_file)
2891         die("flush succeeded but feedfile %s does not exist!", feedfile);
2892
2893       if (flushing_input_file) {
2894         SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2895       } else {
2896         close_defer();
2897         SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2898       }
2899       return OOP_CONTINUE;
2900
2901     default:
2902       goto unexpected_exitstatus;
2903
2904     }
2905   } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2906     warn("flush timed out trying to talk to innd");
2907     goto failed;
2908   } else {
2909   unexpected_exitstatus:
2910     report_child_status("inndcomm child", status);
2911   }
2912
2913  failed:
2914   SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2915   return OOP_CONTINUE;
2916 }
2917
2918 static void inndcommfail(const char *what) {
2919   syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2920   exit(INNDCOMMCHILD_ESTATUS_FAIL);
2921 }
2922
2923 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2924   int pipefds[2];
2925
2926   notice("flushing %s",why);
2927
2928   assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2929   assert(!inndcomm_child);
2930   assert(!inndcomm_sentinel_fd);
2931
2932   if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2933
2934   inndcomm_child= xfork("inndcomm child");
2935
2936   if (!inndcomm_child) {
2937     const char *flushargv[2]= { sitename, 0 };
2938     char *reply;
2939     int r;
2940
2941     xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2942     /* parent spots the autoclose of pipefds[1] when we die or exit */
2943
2944     if (simulate_flush>=0) {
2945       warn("SIMULATING flush child status %d", simulate_flush);
2946       if (simulate_flush>128) raise(simulate_flush-128);
2947       else exit(simulate_flush);
2948     }
2949
2950     alarm(inndcomm_flush_timeout);
2951     r= ICCopen();                         if (r)   inndcommfail("connect");
2952     r= ICCcommand('f',flushargv,&reply);  if (r<0) inndcommfail("transmit");
2953     if (!r) exit(0); /* yay! */
2954
2955     if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2956     syswarn("innd ctlinnd flush failed: innd said %s", reply);
2957     exit(INNDCOMMCHILD_ESTATUS_FAIL);
2958   }
2959
2960   simulate_flush= -1;
2961
2962   xclose(pipefds[1], "inndcomm sentinel child's end",0);
2963   inndcomm_sentinel_fd= pipefds[0];
2964   assert(inndcomm_sentinel_fd);
2965   on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2966
2967   SMS(FLUSHING, 0, why);
2968 }
2969
2970 /*========== main program ==========*/
2971
2972 static void postfork_inputfile(InputFile *ipf) {
2973   if (!ipf) return;
2974   xclose(ipf->fd, "(in child) input file ", ipf->path);
2975 }
2976
2977 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2978   /* we have no stdio streams that are buffered long-term */
2979   if (!f) return;
2980   if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2981 }
2982
2983 static void postfork(void) {
2984   in_child= 1;
2985
2986   if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2987     sysdie("(in child) failed to reset SIGPIPE");
2988
2989   postfork_inputfile(main_input_file);
2990   postfork_inputfile(flushing_input_file);
2991
2992   Conn *conn;
2993   FOR_CONN(conn)
2994     conn_closefd(conn,"(in child) ");
2995
2996   postfork_stdio(defer, "defer file ", path_defer);
2997 }
2998
2999 typedef struct Every Every;
3000 struct Every {
3001   struct timeval interval;
3002   int fixed_rate;
3003   void (*f)(void);
3004 };
3005
3006 static void every_schedule(Every *e, struct timeval base);
3007
3008 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
3009   Every *e= e_v;
3010   e->f();
3011   if (!e->fixed_rate) xgettimeofday(&base);
3012   every_schedule(e, base);
3013   return OOP_CONTINUE;
3014 }
3015
3016 static void every_schedule(Every *e, struct timeval base) {
3017   struct timeval when;
3018   timeradd(&base, &e->interval, &when);
3019   loop->on_time(loop, when, every_happens, e);
3020 }
3021
3022 static void every(int interval, int fixed_rate, void (*f)(void)) {
3023   NEW_DECL(Every *,e);
3024   e->interval.tv_sec= interval;
3025   e->interval.tv_usec= 0;
3026   e->fixed_rate= fixed_rate;
3027   e->f= f;
3028   struct timeval now;
3029   xgettimeofday(&now);
3030   every_schedule(e, now);
3031 }
3032
3033 static void filepoll(void) {
3034   filemon_callback(main_input_file);
3035   filemon_callback(flushing_input_file);
3036 }
3037
3038 static char *debug_report_ipf(InputFile *ipf) {
3039   if (!ipf) return xasprintf("none");
3040
3041   const char *slash= strrchr(ipf->path,'/');
3042   const char *path= slash ? slash+1 : ipf->path;
3043
3044   return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s%s",
3045                    ipf, path,
3046                    ipf->inprogress, (long)ipf->offset,
3047                    ipf->fd,
3048                    ipf->rd ? "" : ",!rd",
3049                    ipf->skippinglong ? "*skiplong" : "");
3050 }
3051
3052 static void period(void) {
3053   char *dipf_main=     debug_report_ipf(main_input_file);
3054   char *dipf_flushing= debug_report_ipf(flushing_input_file);
3055   char *dipf_backlog=  debug_report_ipf(backlog_input_file);
3056
3057   debug("PERIOD"
3058         " sms=%s[%d] conns=%d queue=%d until_connect=%d"
3059         " input_files main:%s flushing:%s backlog:%s"
3060         " children connecting=%ld inndcomm=%ld"
3061         ,
3062         sms_names[sms], sm_period_counter,
3063           conns.count, queue.count, until_connect,
3064         dipf_main, dipf_flushing, dipf_backlog,
3065         (long)connecting_child, (long)inndcomm_child
3066         );
3067
3068   free(dipf_main);
3069   free(dipf_flushing);
3070   free(dipf_backlog);
3071
3072   if (until_connect) until_connect--;
3073
3074   poll_backlog_file();
3075   if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
3076   statemc_period_poll();
3077   check_assign_articles();
3078   check_idle_conns();
3079 }
3080
3081
3082 /*========== dumping state ==========*/
3083
3084 static void dump_article_list(FILE *f, const ControlCommand *c,
3085                               const ArticleList *al) {
3086   fprintf(f, " count=%d\n", al->count);
3087   if (!c->xval) return;
3088   
3089   int i; Article *art;
3090   for (i=0, art=LIST_HEAD(*al); art; i++, art=LIST_NEXT(art)) {
3091     fprintf(f," #%05d %-11s", i, artstate_names[art->state]);
3092     DUMPV("%p", art->,ipf);
3093     DUMPV("%d", art->,missing);
3094     DUMPV("%lu", (unsigned long)art->,offset);
3095     DUMPV("%d", art->,blanklen);
3096     DUMPV("%d", art->,midlen);
3097     fprintf(f, " %s %s\n", TokenToText(art->token), art->messageid);
3098   }
3099 }
3100   
3101 static void dump_input_file(FILE *f, InputFile *ipf, const char *wh) {
3102   char *dipf= debug_report_ipf(ipf);
3103   fprintf(f,"input %s %s", wh, dipf);
3104   free(dipf);
3105   
3106   if (ipf) {
3107     DUMPV("%d", ipf->,readcount_ok);
3108     DUMPV("%d", ipf->,readcount_blank);
3109     DUMPV("%d", ipf->,readcount_err);
3110   }
3111   fprintf(f,"\n");
3112   if (ipf) {
3113     ArtState state; const char *const *statename; 
3114     for (state=0, statename=artstate_names; *statename; state++,statename++) {
3115 #define RC_DUMP_FMT(x) " " #x "=%d"
3116 #define RC_DUMP_VAL(x) ,ipf->counts[state][RC_##x]
3117       fprintf(f,"input %s counts %-11s"
3118               RESULT_COUNTS(RC_DUMP_FMT,RC_DUMP_FMT) "\n",
3119               wh, *statename
3120               RESULT_COUNTS(RC_DUMP_VAL,RC_DUMP_VAL));
3121     }
3122   }
3123 }
3124
3125 CCMD(dump) {
3126   int i;
3127   fprintf(cc->out, "dumping state to %s\n", path_dump);
3128   FILE *f= fopen(path_dump, "w");
3129   if (!f) { fprintf(cc->out, "failed: open: %s\n", strerror(errno)); return; }
3130
3131   fprintf(f,"general");
3132   DUMPV("%s", sms_names,[sms]);
3133   DUMPV("%d", ,sm_period_counter);
3134   DUMPV("%ld", (long),self_pid);
3135   DUMPV("%p", , defer);
3136   DUMPV("%d", , until_connect);
3137   DUMPV("%d", , until_backlog_nextscan);
3138   DUMPV("%d", , simulate_flush);
3139   fprintf(f,"\nnocheck");
3140   DUMPV("%#.10f", , accept_proportion);
3141   DUMPV("%d", , nocheck);
3142   DUMPV("%d", , nocheck_reported);
3143   fprintf(f,"\n");
3144
3145   fprintf(f,"special");
3146   DUMPV("%ld", (long),connecting_child);
3147   DUMPV("%d", , connecting_fdpass_sock);
3148   DUMPV("%d", , control_master);
3149   fprintf(f,"\n");
3150
3151   fprintf(f,"filemon ");
3152   filemon_method_dump_info(f);
3153
3154   dump_input_file(f, main_input_file,     "main"    );
3155   dump_input_file(f, flushing_input_file, "flushing");
3156   dump_input_file(f, backlog_input_file,  "backlog" );
3157
3158   fprintf(f,"conns count=%d\n", conns.count);
3159
3160   Conn *conn;
3161   FOR_CONN(conn) {
3162
3163     fprintf(f,"C%d",conn->fd);
3164     DUMPV("%p",conn->,rd);             DUMPV("%d",conn->,max_queue);
3165     DUMPV("%d",conn->,stream);         DUMPV("%d",conn->,quitting);
3166     DUMPV("%d",conn->,since_activity);
3167     fprintf(f,"\n");
3168
3169     fprintf(f,"C%d waiting", conn->fd); dump_article_list(f,c,&conn->waiting);
3170     fprintf(f,"C%d priority",conn->fd); dump_article_list(f,c,&conn->priority);
3171     fprintf(f,"C%d sent",    conn->fd); dump_article_list(f,c,&conn->sent);
3172
3173     fprintf(f,"C%d xmit xmitu=%d\n", conn->fd, conn->xmitu);
3174     for (i=0; i<conn->xmitu; i++) {
3175       const struct iovec *iv= &conn->xmit[i];
3176       const XmitDetails *xd= &conn->xmitd[i];
3177       char *dinfo;
3178       long diff;
3179       switch (xd->kind) {
3180       case xk_Malloc:
3181         diff= xd->info.malloc_tofree - (char*)iv->iov_base;
3182         dinfo= xasprintf("M%5ld", diff);
3183         break;
3184       case xk_Const:
3185         dinfo= xasprintf("Const");
3186         break;
3187       case xk_Artdata:
3188         dinfo= xasprintf("A%p", xd->info.sm_art);
3189         break;
3190       default:
3191         abort();
3192       }
3193       fprintf(f," #%03d %-11s l=%d %s\n", i, dinfo, iv->iov_len,
3194               sanitise(iv->iov_base, iv->iov_len));
3195       free(dinfo);
3196     }
3197   }
3198
3199   fprintf(f,"queue"); dump_article_list(f,c,&queue);
3200
3201   fprintf(f,"paths");
3202   DUMPV("%s", , path_lock);
3203   DUMPV("%s", , path_flushing);
3204   DUMPV("%s", , path_defer);
3205   DUMPV("%s", , path_control);
3206   DUMPV("%s", , path_dump);
3207   DUMPV("%s", , globpat_backlog);
3208   fprintf(f,"\n");
3209
3210   if (!!ferror(f) + !!fclose(f)) {
3211     fprintf(cc->out, "failed: write: %s\n", strerror(errno));
3212     return;
3213   }
3214 }
3215
3216 /*========== option parsing ==========*/
3217
3218 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
3219 static void vbadusage(const char *fmt, va_list al) {
3220   char *m= xvasprintf(fmt,al);
3221   fprintf(stderr, "bad usage: %s\n"
3222           "say --help for help, or read the manpage\n",
3223           m);
3224   if (become_daemon)
3225     syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
3226   exit(8);
3227 }
3228
3229 /*---------- generic option parser ----------*/
3230
3231 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
3232 static void badusage(const char *fmt, ...) {
3233   va_list al;
3234   va_start(al,fmt);
3235   vbadusage(fmt,al);
3236 }
3237
3238 enum OptFlags {
3239   of_seconds= 001000u,
3240   of_boolean= 002000u,
3241 };
3242
3243 typedef struct Option Option;
3244 typedef void OptionParser(const Option*, const char *val);
3245
3246 struct Option {
3247   int shrt;
3248   const char *lng, *formarg;
3249   void *store;
3250   OptionParser *fn;
3251   int intval;
3252 };
3253
3254 static void parse_options(const Option *options, char ***argvp) {
3255   /* on return *argvp is first non-option arg; argc is not updated */
3256
3257   for (;;) {
3258     const char *arg= *++(*argvp);
3259     if (!arg) break;
3260     if (*arg != '-') break;
3261     if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
3262     int a;
3263     while ((a= *++arg)) {
3264       const Option *o;
3265       if (a=='-') {
3266         arg++;
3267         char *equals= strchr(arg,'=');
3268         int len= equals ? (equals - arg) : strlen(arg);
3269         for (o=options; o->shrt || o->lng; o++)
3270           if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
3271             goto found_long;
3272         badusage("unknown long option --%s",arg);
3273       found_long:
3274         if (!o->formarg) {
3275           if (equals) badusage("option --%s does not take a value",o->lng);
3276           arg= 0;
3277         } else if (equals) {
3278           arg= equals+1;
3279         } else {
3280           arg= *++(*argvp);
3281           if (!arg) badusage("option --%s needs a value for %s",
3282                              o->lng, o->formarg);
3283         }
3284         o->fn(o, arg);
3285         break; /* eaten the whole argument now */
3286       }
3287       for (o=options; o->shrt || o->lng; o++)
3288         if (a == o->shrt)
3289           goto found_short;
3290       badusage("unknown short option -%c",a);
3291     found_short:
3292       if (!o->formarg) {
3293         o->fn(o,0);
3294       } else {
3295         if (!*++arg) {
3296           arg= *++(*argvp);
3297           if (!arg) badusage("option -%c needs a value for %s",
3298                              o->shrt, o->formarg);
3299         }
3300         o->fn(o,arg);
3301         break; /* eaten the whole argument now */
3302       }
3303     }
3304   }
3305 }
3306
3307 #define DELIMPERHAPS(delim,str)  (str) ? (delim) : "", (str) ? (str) : ""
3308
3309 static void print_options(const Option *options, FILE *f) {
3310   const Option *o;
3311   for (o=options; o->shrt || o->lng; o++) {
3312     char shrt[2] = { o->shrt, 0 };
3313     char *optspec= xasprintf("%s%s%s%s%s",
3314                              o->shrt ? "-" : "", shrt,
3315                              o->shrt && o->lng ? "|" : "",
3316                              DELIMPERHAPS("--", o->lng));
3317     fprintf(f, "  %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
3318     free(optspec);
3319   }
3320 }
3321
3322 /*---------- specific option types ----------*/
3323
3324 static void op_integer(const Option *o, const char *val) {
3325   char *ep;
3326   errno= 0;
3327   unsigned long ul= strtoul(val,&ep,10);
3328   if (*ep || ep==val || errno || ul>INT_MAX)
3329     badusage("bad integer value for %s",o->lng);
3330   int *store= o->store;
3331   *store= ul;
3332 }
3333
3334 static void op_double(const Option *o, const char *val) {
3335   int *store= o->store;
3336   char *ep;
3337   errno= 0;
3338   *store= strtod(val, &ep);
3339   if (*ep || ep==val || errno)
3340     badusage("bad floating point value for %s",o->lng);
3341 }
3342
3343 static void op_string(const Option *o, const char *val) {
3344   const char **store= o->store;
3345   *store= val;
3346 }
3347
3348 static void op_seconds(const Option *o, const char *val) {
3349   int *store= o->store;
3350   char *ep;
3351   int unit;
3352
3353   double v= strtod(val,&ep);
3354   if (ep==val) badusage("bad time/duration value for %s",o->lng);
3355
3356   if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
3357   else if (!strcmp(ep,"m") || !strcmp(ep,"min"))    unit= 60;
3358   else if (!strcmp(ep,"h") || !strcmp(ep,"hour"))   unit= 3600;
3359   else if (!strcmp(ep,"d") || !strcmp(ep,"day"))    unit= 86400;
3360   else if (!strcmp(ep,"das")) unit= 10;
3361   else if (!strcmp(ep,"hs"))  unit= 100;
3362   else if (!strcmp(ep,"ks"))  unit= 1000;
3363   else if (!strcmp(ep,"Ms"))  unit= 1000000;
3364   else badusage("bad units %s for time/duration value for %s",ep,o->lng);
3365
3366   v *= unit;
3367   v= ceil(v);
3368   if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
3369   *store= v;
3370 }
3371
3372 static void op_setint(const Option *o, const char *val) {
3373   int *store= o->store;
3374   *store= o->intval;
3375 }
3376
3377 /*---------- specific options ----------*/
3378
3379 static void help(const Option *o, const char *val);
3380
3381 static const Option innduct_options[]= {
3382 {'f',"feedfile",         "F",     &feedfile,                 op_string      },
3383 {'q',"quiet-multiple",   0,       &quiet_multiple,           op_setint, 1   },
3384 {0,"no-daemon",          0,       &become_daemon,            op_setint, 0   },
3385 {0,"no-streaming",       0,       &try_stream,               op_setint, 0   },
3386 {0,"no-filemon",         0,       &try_filemon,              op_setint, 0   },
3387 {'C',"inndconf",         "F",     &inndconffile,             op_string      },
3388 {'P',"port",             "PORT",  &port,                     op_integer     },
3389 {0,"ctrl-sock-dir",      0,       &realsockdir,              op_string      },
3390 {0,"help",               0,       0,                         help           },
3391
3392 {0,"max-connections",    "N",     &max_connections,          op_integer     },
3393 {0,"max-queue-per-conn", "N",     &max_queue_per_conn,       op_integer     },
3394 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer     },
3395 {0,"period-interval",    "TIME",  &period_seconds,           op_seconds     },
3396
3397 {0,"connection-timeout",   "TIME",  &connection_setup_timeout, op_seconds   },
3398 {0,"stuck-flush-timeout",  "TIME",  &inndcomm_flush_timeout,   op_seconds   },
3399 {0,"feedfile-poll",        "TIME",  &filepoll_seconds,         op_seconds   },
3400
3401 {0,"no-check-proportion",   "PERCENT",   &nocheck_thresh,       op_double   },
3402 {0,"no-check-response-time","ARTICLES",  &nocheck_decay,        op_double   },
3403
3404 {0,"reconnect-interval",     "PERIOD", &reconnect_delay_periods,  op_seconds },
3405 {0,"flush-retry-interval",   "PERIOD", &flushfail_retry_periods,  op_seconds },
3406 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3407 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3408 {0,"max-flush-interval",     "PERIOD", &spontaneous_flush_periods,op_seconds },
3409 {0,"idle-timeout",           "PERIOD", &need_activity_periods,    op_seconds },
3410
3411 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio,   op_double    },
3412 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer   },
3413
3414 {0,0}
3415 };
3416
3417 static void printusage(FILE *f) {
3418   fputs("usage: innduct [options] site [fqdn]\n"
3419         "available options are:\n", f);
3420   print_options(innduct_options, f);
3421 }
3422
3423 static void help(const Option *o, const char *val) {
3424   printusage(stdout);
3425   if (ferror(stdout) || fflush(stdout)) {
3426     perror("innduct: writing help");
3427     exit(12);
3428   }
3429   exit(0);
3430 }
3431
3432 static void convert_to_periods_rndup(int *store) {
3433   *store += period_seconds-1;
3434   *store /= period_seconds;
3435 }
3436
3437 int main(int argc, char **argv) {
3438   if (!argv[1]) {
3439     printusage(stderr);
3440     exit(8);
3441   }
3442
3443   parse_options(innduct_options, &argv);
3444
3445   /* arguments */
3446
3447   sitename= *argv++;
3448   if (!sitename) badusage("need site name argument");
3449   remote_host= *argv++;
3450   if (*argv) badusage("too many non-option arguments");
3451
3452   /* defaults */
3453
3454   int r= innconf_read(inndconffile);
3455   if (!r) badusage("could not read inn.conf (more info on stderr)");
3456
3457   if (!remote_host) remote_host= sitename;
3458
3459   if (nocheck_thresh < 0 || nocheck_thresh > 100)
3460     badusage("nocheck threshold percentage must be between 0..100");
3461   nocheck_thresh *= 0.01;
3462
3463   if (nocheck_decay < 0.1)
3464     badusage("nocheck decay articles must be at least 0.1");
3465   nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3466
3467   convert_to_periods_rndup(&reconnect_delay_periods);
3468   convert_to_periods_rndup(&flushfail_retry_periods);
3469   convert_to_periods_rndup(&backlog_retry_minperiods);
3470   convert_to_periods_rndup(&backlog_spontrescan_periods);
3471   convert_to_periods_rndup(&spontaneous_flush_periods);
3472   convert_to_periods_rndup(&need_activity_periods);
3473
3474   if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3475     badusage("bad input data ratio must be between 0..100");
3476   max_bad_data_ratio *= 0.01;
3477
3478   if (!feedfile) {
3479     feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3480   } else if (!feedfile[0]) {
3481     badusage("feed filename must be nonempty");
3482   } else if (feedfile[strlen(feedfile)-1]=='/') {
3483     feedfile= xasprintf("%s%s",feedfile,sitename);
3484   }
3485
3486   const char *feedfile_forbidden= "?*[~#";
3487   int c;
3488   while ((c= *feedfile_forbidden++))
3489     if (strchr(feedfile, c))
3490       badusage("feed filename may not contain metacharacter %c",c);
3491
3492   /* set things up */
3493
3494   path_lock=        xasprintf("%s_lock",      feedfile);
3495   path_flushing=    xasprintf("%s_flushing",  feedfile);
3496   path_defer=       xasprintf("%s_defer",     feedfile);
3497   path_control=     xasprintf("%s_control",   feedfile);
3498   path_dump=        xasprintf("%s_dump",      feedfile);
3499   globpat_backlog=  xasprintf("%s_backlog*",  feedfile);
3500
3501   oop_source_sys *sysloop= oop_sys_new();
3502   if (!sysloop) sysdie("could not create liboop event loop");
3503   loop= (oop_source*)sysloop;
3504
3505   LIST_INIT(conns);
3506   LIST_INIT(queue);
3507
3508   if (become_daemon) {
3509     int i;
3510     for (i=3; i<255; i++)
3511       /* do this now before we open syslog, etc. */
3512       close(i);
3513     openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3514
3515     int null= open("/dev/null",O_RDWR);
3516     if (null<0) sysfatal("failed to open /dev/null");
3517     dup2(null,0);
3518     dup2(null,1);
3519     dup2(null,2);
3520     xclose(null, "/dev/null original fd",0);
3521
3522     pid_t child1= xfork("daemonise first fork");
3523     if (child1) _exit(0);
3524
3525     pid_t sid= setsid();
3526     if (sid != child1) sysfatal("setsid failed");
3527
3528     pid_t child2= xfork("daemonise second fork");
3529     if (child2) _exit(0);
3530   }
3531
3532   self_pid= getpid();
3533   if (self_pid==-1) sysdie("getpid");
3534
3535   statemc_lock();
3536
3537   init_signals();
3538
3539   notice("starting");
3540
3541   if (!become_daemon)
3542     control_stdio();
3543
3544   control_init();
3545
3546   int filemon_ok= 0;
3547   if (!try_filemon) {
3548     notice("filemon: suppressed by command line option, polling");
3549   } else {
3550     filemon_ok= filemon_method_init();
3551     if (!filemon_ok)
3552       warn("filemon: no file monitoring available, polling");
3553   }
3554   if (!filemon_ok)
3555     every(filepoll_seconds,0,filepoll);
3556
3557   every(period_seconds,1,period);
3558
3559   statemc_init();
3560
3561   /* let's go */
3562
3563   void *run= oop_sys_run(sysloop);
3564   assert(run == OOP_ERROR);
3565   sysdie("event loop failed");
3566 }