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