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