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