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