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