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