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