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