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