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