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