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