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