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