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