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