chiark / gitweb /
b9460ed598a62a205ef865608cbab2151815bc49
[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, sentbody;
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   *count++;
964   art->ipf->counts.articles[art->checked][whichcount]++;
965   if (whichcount == RC_accepted) update_nocheck(1);
966   else if (whichcount == RC_unwanted) update_nocheck(0);
967
968   InputFile *ipf= art->ipf;
969   while (art->blanklen) {
970     static const char spaces[]=
971       "                                                                "
972       "                                                                "
973       "                                                                "
974       "                                                                ";
975     int w= art->blanklen;  if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
976     int r= pwrite(ipf->fd, spaces, w, art->offset);
977     if (r==-1) {
978       if (errno==EINTR) continue;
979       sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
980              art->messageid, art->blanklen, art->offset, ipf->path);
981     }
982     assert(r>=0 && r<=w);
983     art->blanklen -= w;
984     art->offset += w;
985   }
986
987   ipf->inprogress--;
988   assert(ipf->inprogress >= 0);
989
990   if (!ipf->inprogress && ipf != main_input_file)
991     queue_check_input_done();
992
993   free(art);
994 }
995
996 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
997                         const char *errmsg, int errnoval,
998                         const char *data, size_t recsz, void *conn_v) {
999   Conn *conn= conn_v;
1000
1001   if (ev == OOP_RD_EOF) {
1002     connfail(conn, "unexpected EOF from peer");
1003     return OOP_CONTINUE;
1004   }
1005   assert(ev == OOP_RD_OK);
1006
1007   char *ep;
1008   unsigned long code= strtoul(data, &ep, 10);
1009   if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1010     char sanibuf[100];
1011     const char *p= data;
1012     char *q= sanibuf;
1013     *q++= '`';
1014     for (;;) {
1015       if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
1016       int c= *p++;
1017       if (!c) { *q++= '\''; break; }
1018       if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
1019       sprintf(q,"\\x%02x",c);
1020       q += 4;
1021     }
1022     connfail(conn, "badly formatted response from peer: %s", sanibuf);
1023     return OOP_CONTINUE;
1024   }
1025
1026   if (conn->quitting) {
1027     if (code!=205) {
1028       connfail(conn, "peer gave failure response to QUIT: %s", sani);
1029       return OOP_CONTINUE;
1030     }
1031     conn close ok;
1032     return;
1033   }
1034
1035   Article *art;
1036
1037 #define GET_ARTICLE                                                         \
1038   art= article_reply_check(conn, data, code_streaming, sani);               \
1039   if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1040
1041 #define ARTICLE_DEALTWITH(streaming,how)                        \
1042   code_streaming= (streaming)                                   \
1043   GET_ARTICLE;                                                  \
1044   article_done(conn, art, RC_##how);  break;
1045
1046 #define PEERBADMSG(m) connfail(conn, m ": %s", sani);  return OOP_CONTINUE
1047
1048   int code_streaming= 0;
1049
1050   switch (code) {
1051
1052   case 400: PEERBADMSG("peer stopped accepting articles");
1053   case 503: PEERBADMSG("peer timed us out");
1054   default:  PEERBADMSG("peer sent unexpected message");
1055
1056   case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
1057   case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
1058
1059   case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
1060   case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
1061
1062   case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
1063   case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
1064
1065   case 238: /* CHECK says send it */
1066     code_streaming= 1;
1067   case 335: /* IHAVE says send it */
1068     GET_ARTICLE;
1069     count_checkedwanted++;
1070     LIST_ADDTAIL(conn->queue);
1071     if (art->checked) {
1072       connfail("peer gave %d response to article body: %s",code, sani);
1073       return OOP_CONTINUE;
1074     }
1075     art->checked= 1;
1076     break;
1077
1078   case 431: /* CHECK or TAKETHIS says try later */
1079     code_streaming= 1;
1080   case 436: /* IHAVE says try later */
1081     GET_ARTICLE;
1082     open_defer();
1083     if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1084         || fflush(defer))
1085       sysfatal("write to defer file %s",path_defer);
1086     article_done(conn, art, RC_deferred);
1087     break;
1088
1089   }
1090
1091   check_check_work(conn);
1092   return OOP_CONTINUE;
1093 }
1094
1095
1096 /*========== monitoring of input files ==========*/
1097
1098 static void feedfile_eof(InputFile *ipf) {
1099   assert(ipf != main_input_file); /* promised by tailing_try_read */
1100
1101   inputfile_tailing_stop(ipf);
1102   assert(ipf->fd >= 0);
1103   if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1104   ipf->fd= -1;
1105
1106   if (ipf == flushing_input_file) {
1107     assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1108     if (main_input_file) inputfile_tailing_start(main_input_file);
1109     statemc_check_flushing_done();
1110   } else if (ipf == backlog_input_file) {
1111     statemc_check_backlog_done();
1112   } else {
1113     abort(); /* supposed to wait rather than get EOF on main input file */
1114   }
1115 }
1116
1117 static InputFile *open_input_file(const char *path) {
1118   int fd= open(path, O_RDONLY);
1119   if (fd<0) {
1120     if (errno==ENOENT) return 0;
1121     sysfatal("unable to open input file %s", path);
1122   }
1123
1124   InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1125   memset(ipf,0,sizeof(*ipf));
1126
1127   ipf->readable.on_readable= tailing_on_readable;
1128   ipf->readable.on_cancel=   tailing_on_cancel;
1129   ipf->readable.try_read=    tailing_try_read;
1130
1131   ipf->fd= fd;
1132   strcpy(ipf->path, path);
1133
1134   return ipf;
1135 }
1136
1137 static void close_input_file(InputFile *ipf) {
1138   assert(!ipf->readable_callback); /* must have had ->on_cancel */
1139   assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1140   assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1141   assert(!ipf->inprogress); /* no dangling pointers pointing here */
1142
1143   if (ipf->fd >= 0)
1144     if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1145 }
1146
1147
1148 /*---------- dealing with articles read in the input file ----------*/
1149
1150 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1151                                    oop_rd_event ev, const char *errmsg,
1152                                    int errnoval,
1153                                    const char *data, size_t recsz,
1154                                    void *ipf_v) {
1155   InputFile *ipf= ipf_v;
1156   Article *art;
1157   char tokentextbuf[sizeof(TOKEN)*2+3];
1158
1159   if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1160
1161   if (data[0] && data[0]!=' ') {
1162     char *space= strchr(data,' ');
1163     int tokenlen= space-data;
1164     int midlen= (int)recsz-tokenlen-1;
1165     if (midlen < 0) goto bad_data;
1166
1167     if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1168     memcpy(tokentextbuf, data, tokenlen);
1169     tokentextbuf[tokenlen]= 0;
1170     if (!IsToken(tokentextbuf)) goto bad_data;
1171
1172     art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1173     art->offset= ipf->offset;
1174     art->blanklen= recsz;
1175     art->midlen= midlen;
1176     art->checked= art->sentbody= 0;
1177     art->ipf= ipf;  ipf->inprogress++;
1178     art->token= TextToToken(tokentextbuf);
1179     strcpy(art->messageid, space+1);
1180     LIST_ADDTAIL(queue, art);
1181   }
1182   ipf->offset += recsz + 1;
1183
1184   if (sms==sm_NORMAL && ipf==main_input_file &&
1185       ipf->offset >= flush_threshold)
1186     statemc_start_flush("feed file size");
1187
1188   check_master_queue();
1189 }
1190
1191 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1192   assert(sms == sm_NORMAL);
1193
1194   debug("starting flush (%s) (%lu >= %lu) (%d)",
1195         why,
1196         (unsigned long)ipf->offset, (unsigned long)flush_threshold,
1197         sm_period_counter);
1198
1199   int r= link(feedfile, duct_path);
1200   if (r) sysdie("link feedfile %s to flushing file %s", feedfile,
1201                 path_duct);
1202   /* => Hardlinked */
1203
1204   xunlink(feedfile, "old feedfile link");
1205   /* => Moved */
1206
1207   spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1208 }
1209
1210 /*========== tailing input file ==========*/
1211
1212 static void filemon_start(InputFile *ipf) {
1213   assert(!ipf->filemon);
1214
1215   ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1216   memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1217   filemon_method_startfile(ipf, ipf->filemon);
1218 }
1219
1220 static void filemon_stop(InputFile *ipf) {
1221   if (!ipf->filemon) return;
1222   filemon_method_stopfile(ipf, ipf->filemon);
1223   free(ipf->filemon);
1224   ipf->filemon= 0;
1225 }
1226
1227 static void filemon_callback(InputFile *ipf) {
1228   ipf->readable_callback(ipf->readable_callback_user);
1229 }
1230
1231 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1232                                      void *user) {
1233   InputFile *ipf= user;
1234   return ipf->readable_callback(ipf->readable_callback_user);
1235 }
1236
1237 static void on_cancel(struct oop_readable *rable) {
1238   InputFile *ipf= (void*)rable;
1239
1240   if (ipf->filemon) filemon_stopfile(ipf);
1241   loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1242   ipf->readable_callback= 0;
1243 }
1244
1245 static void tailing_queue_readable(InputFile *ipf) {
1246   /* lifetime of ipf here is OK because destruction will cause
1247    * on_cancel which will cancel this callback */
1248   loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1249 }
1250
1251 static int tailing_on_readable(struct oop_readable *rable,
1252                                 oop_readable_call *cb, void *user) {
1253   InputFile *ipf= (void*)rable;
1254
1255   tailing_on_cancel(rable);
1256   ipf->readable_callback= cb;
1257   ipf->readable_callback_user= user;
1258   filemon_startfile(ipf);
1259
1260   tailing_queue_readable(ipf);
1261   return 0;
1262 }
1263
1264 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1265                                 size_t length) {
1266   InputFile *ipf= (void*)rable;
1267   for (;;) {
1268     ssize_t r= read(ipf->fd, buffer, length);
1269     if (r==-1) {
1270       if (errno==EINTR) continue;
1271       return r;
1272     }
1273     if (!r) {
1274       if (ipf==main_input_file) {
1275         errno=EAGAIN;
1276         return -1;
1277       } else if (ipf==flushing_input_file) {
1278         assert(ipf->fd>=0);
1279         assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1280       } else if (ipf==backlog_input_file) {
1281         assert(ipf->fd>=0);
1282       } else {
1283         abort();
1284       }
1285     }
1286     return r;
1287   }
1288 }
1289
1290 /*---------- filemon implemented with inotify ----------*/
1291
1292 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1293 #define HAVE_FILEMON
1294
1295 #include <linux/inotify.h>
1296
1297 static int filemon_inotify_fd;
1298 static int filemon_inotify_wdmax;
1299 static InputFile **filemon_inotify_wd2ipf;
1300
1301 typedef struct Filemon_Perfile {
1302   int wd;
1303 } Filemon_Inotify_Perfile;
1304
1305 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1306   int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1307   if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1308
1309   if (wd >= filemon_inotify_wdmax) {
1310     int newmax= wd+2;
1311     filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1312                                  sizeof(*filemon_inotify_wd2ipf) * newmax);
1313     memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1314            sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1315     filemon_inotify_wdmax= newmax;
1316   }
1317
1318   assert(!filemon_inotify_wd2ipf[wd]);
1319   filemon_inotify_wd2ipf[wd]= ipf;
1320
1321   debug("filemon inotify startfile %p wd=%d wdmax=%d",
1322         ipf, wd, filemon_inotify_wdmax);
1323
1324   pf->wd= wd;
1325 }
1326
1327 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1328   int wd= pf->wd;
1329   debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1330   int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1331   if (r) sysdie("inotify_rm_watch");
1332   filemon_inotify_wd2ipf[wd]= 0;
1333 }
1334
1335 static void *filemon_inotify_readable(oop_source *lp, int fd,
1336                                       oop_event e, void *u) {
1337   struct inotify_event iev;
1338   for (;;) {
1339     int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1340     if (r==-1) {
1341       if (errno==EAGAIN) break;
1342       sysdie("read from inotify master");
1343     } else if (r==sizeof(iev)) {
1344       assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1345     } else {
1346       die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1347     }
1348     InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1349     debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1350     filemon_callback(ipf);
1351   }
1352   return OOP_CONTINUE;
1353 }
1354
1355 static int filemon_method_init(void) {
1356   filemon_inotify_fd= inotify_init();
1357   if (filemon_inotify_fd<0) {
1358     syswarn("could not initialise inotify: inotify_init failed");
1359     return 0;
1360   }
1361   set nonblock;
1362   loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1363
1364   debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1365   return 1;
1366 }
1367
1368 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1369
1370 /*---------- filemon dummy implementation ----------*/
1371
1372 #if !defined(HAVE_FILEMON)
1373
1374 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1375
1376 static int filemon_method_init(void) { return 0; }
1377 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1378 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1379
1380 #endif /* !HAVE_FILEMON */
1381
1382 /*---------- interface to start and stop an input file ----------*/
1383
1384 static const oop_rd_style feedfile_rdstyle= {
1385   OOP_RD_DELIM_STRIP, '\n',
1386   OOP_RD_NUL_FORBID,
1387   OOP_RD_SHORTREC_EOF,
1388 };
1389
1390 static void inputfile_tailing_start(InputFile *ipf) {
1391   assert(!ipf->fd);
1392   ipf->readable->on_readable= tailing_on_readable;
1393   ipf->readable->on_cancel=   tailing_on_cancel;
1394   ipf->readable->try_read=    tailing_try_read;
1395   ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1396   ipf->readable->delete_kill= 0;
1397
1398   ipf->readable_callback= 0;
1399   ipf->readable_callback_user= 0;
1400
1401   ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1402   assert(ipf->fd);
1403
1404   int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1405                      feedfile_got_article,ipf, feedfile_problem,ipf);
1406   if (r) sysdie("unable start reading feedfile %s",ipf->path);
1407 }
1408
1409 static void inputfile_tailing_stop(InputFile *ipf) {
1410   assert(ipf->fd);
1411   oop_rd_cancel(ipf->rd);
1412   oop_rd_delete(ipf->rd);
1413   ipf->rd= 0;
1414   assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1415 }
1416
1417
1418 /*========== interaction with innd - state machine ==========*/
1419
1420 /* See official state diagram at top of file.  We implement
1421  * this as follows:
1422  * -8<-
1423
1424             .=======.
1425             ||START||
1426             `======='
1427                 |
1428                 | open F
1429                 |
1430                 |    F ENOENT
1431                 |`---------------------------------------------------.
1432       F OPEN OK |                                                    |
1433                 |`---------------- - - -                             |
1434        D ENOENT |       D EXISTS   see OVERALL STATES diagram        |
1435                 |                  for full startup logic            |
1436      ,--------->|                                                    |
1437      |          V                                                    |
1438      |     ============                                       try to |
1439      |      NORMAL                                            open D |
1440      |     [Normal]                                                  |
1441      |      main F tail                                              |
1442      |     ============                                              V
1443      |          |                                                    |
1444      |          | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT            |
1445      ^          | hardlink F to D                                    |
1446      |     [Hardlinked]                                              |
1447      |          | unlink F                                           |
1448      |          | our handle onto F is now onto D                    |
1449      |     [Moved]                                                   |
1450      |          |                                                    |
1451      |          |<-------------------<---------------------<---------+
1452      |          |                                                    |
1453      |          | spawn inndcomm flush                               |
1454      |          V                                                    |
1455      |     ==================                                        |
1456      |      FLUSHING[-ABSENT]                                        |
1457      |     [Flushing]                                                |
1458      |     main D tail/none                                          |
1459      |     ==================                                        |
1460      |          |                                                    |
1461      |          |   INNDCOMM FLUSH FAILS                             ^
1462      |          |`----------------------->----------.                |
1463      |          |                                   |                |
1464      |          |   NO SUCH SITE                    V                |
1465      ^          |`--------------->----.         ==================== |
1466      |          |                      \        FLUSHFAILED[-ABSENT] |
1467      |          |                       \         [Moved]            |
1468      |          | FLUSH OK               \       main D tail/none    |
1469      |          | open F                  \     ==================== |
1470      |          |                          \        |                |
1471      |          |                           \       | TIME TO RETRY  |
1472      |          |`------->----.     ,---<---'\      `----------------'
1473      |          |    D NONE   |     | D NONE  `----.
1474      |          V             |     |              V
1475      |     =============      V     V             ============
1476      |      SEPARATED-1       |     |              DROPPING-1
1477      |      flsh->fd>=0       |     |              flsh->fd>=0
1478      |     [Separated]        |     |             [Dropping]
1479      |      main F idle       |     |              main none
1480      |      old D tail        |     |              old D tail
1481      |     =============      |     |             ============
1482      |          |             |     | install       |
1483      ^          | EOF ON D    |     |  defer        | EOF ON D
1484      |          V             |     |               V
1485      |     ===============    |     |             ===============
1486      |      SEPARATED-2       |     |              DROPPING-2
1487      |      flsh->fd==-1      |     V              flsh->fd==-1
1488      |     [Finishing]        |     |             [Dropping]
1489      |      main F tail       |     `.             main none
1490      |      old D closed      |       `.           old D closed
1491      |     ===============    V         `.        ===============
1492      |          |                         `.          |
1493      |          | ALL D PROCESSED           `.        | ALL D PROCESSED
1494      |          V install defer as backlog    `.      | install defer
1495      ^          | close D                       `.    | close D
1496      |          | unlink D                        `.  | unlink D
1497      |          |                                  |  |
1498      |          |                                  V  V
1499      `----------'                               ==============
1500                                                  DROPPED
1501                                                 [Dropped]
1502                                                  main none
1503                                                  old none
1504                                                  some backlog
1505                                                 ==============
1506                                                       |
1507                                                       | ALL BACKLOG DONE
1508                                                       |
1509                                                       | unlink lock
1510                                                       | exit
1511                                                       V
1512                                                   ==========
1513                                                    (ESRCH)
1514                                                   [Droppped]
1515                                                   ==========
1516  * ->8-
1517  */
1518
1519 static void statemc_init(void) {
1520   struct stat stab, stabf;
1521
1522   path_lock=        xasprintf("%s_lock",      feedfile);
1523   path_flushing=    xasprintf("%s_flushing",  feedfile);
1524   path_defer=       xasprintf("%s_defer",     feedfile);
1525   globpat_backlog=  xasprintf("%s_backlog*",  feedfile);
1526
1527   for (;;) {
1528     int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1529     if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1530
1531     struct flock fl;
1532     memset(&fl,0,sizeof(fl));
1533     fl.l_type= F_WRLCK;
1534     fl.l_whence= SEEK_SET;
1535     r= fcntl(lockfd, F_SETLK, &fl);
1536     if (r==-1) {
1537       if (errno==EACCES || errno==EAGAIN) {
1538         if (quiet_if_locked) exit(0);
1539         fatal("another duct holds the lockfile");
1540       }
1541       sysdie("fcntl F_SETLK lockfile %s", path_lock);
1542     }
1543
1544     xfstat_isreg(lockfd, &stabf, "lockfile");
1545     int lock_noent;
1546     xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1547
1548     if (!lock_noent && samefile(&stab, &stabf))
1549       break;
1550
1551     if (close(lockfd))
1552       sysdie("could not close stale lockfile %s", path_lock);
1553   }
1554   debug("startup: locked");
1555
1556   search_backlog_file();
1557
1558   int defer_noent;
1559   xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1560   if (defer_noent) {
1561     debug("startup: ductdefer ENOENT");
1562   } else {
1563     debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1564     switch (stab.st_nlink==1) {
1565     case 1:
1566       open_defer(); /* so that we will later close it and rename it */
1567       break;
1568     case 2:
1569       xunlink(path_defer, "stale defer file link"
1570               " (presumably hardlink to backlog file)");
1571       break;
1572     default:
1573       die("defer file %s has unexpected link count %d",
1574           path_defer, stab.st_nlink);
1575     }
1576   }
1577
1578   struct stat stab_f, stab_d;
1579   int noent_f;
1580
1581   InputFile *file_d= open_input_file(path_flushing);
1582   if (file_d) xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1583
1584   xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1585
1586   if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1587     debug("startup: F==D => Hardlinked");
1588     xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1589     noent_f= 1;
1590   }
1591
1592   if (noent_f) {
1593     debug("startup: F ENOENT => Moved");
1594     if (file_d) startup_set_input_file(file_d);
1595     spawn_inndcomm_flush("feedfile missing at startup");
1596     /* => Flushing, sms:=FLUSHING */
1597   } else {
1598     if (file_d) {
1599       debug("startup: F!=D => Separated");
1600       startup_set_input_file(file_d);
1601       SMS(SEPARATED, 0, "found both old and current feed files");
1602     } else {
1603       debug("startup: F exists, D ENOENT => Normal");
1604       FILE *file_f= open_input_file(feedfile);
1605       if (!file_f) die("feed file vanished during startup");
1606       startup_set_input_file(file_f);
1607       SMS(NORMAL, flushfail_retry_periods, "normal startup");
1608     }
1609   }
1610 }
1611
1612 static void statemc_period_poll(void) {
1613   if (!sm_period_counter) return;
1614   sm_period_counter--;
1615   assert(sm_period_counter>=0);
1616
1617   if (sm_period_counter) return;
1618   switch (sms) {
1619   case sm_NORMAL:
1620     statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1621     break;
1622   case sm_FLUSHFAILED:
1623     spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1624     break;
1625   default:
1626     abort();
1627   }
1628 }
1629
1630 static void startup_set_input_file(InputFile *f) {
1631   assert(!main_input_file);
1632   main_input_file= f;
1633   inputfile_tailing_start(f);
1634 }
1635
1636 static int inputfile_is_done(InputFile *ipf) {
1637   if (!ipf) return 0;
1638   if (ipf->inprogress) return 0; /* new article in the meantime */
1639   if (ipf->fd >= 0); return 0; /* not had EOF */
1640   return 1;
1641 }
1642  
1643 static void statemc_check_backlog_done(void) {
1644   InputFile *ipf= backlog_input_file();
1645   if (!inputfile_is_done(ipf)) return;
1646
1647   notice_processed(ipf,"backlog file",ipf->path);
1648   close_input_file(ipf);
1649   if (unlink(ipf->path)) {
1650     if (errno != ENOENT)
1651       sysdie("could not unlink processed backlog file %s", ipf->path);
1652     warn("backlog file %s vanished while we were reading it"
1653          " so we couldn't remove it (but it's done now, anyway)",
1654          ipf->path);
1655   }
1656   free(ipf);
1657   backlog_input_file= 0;
1658   search_backlog_file();
1659   return;
1660 }
1661
1662 static void statemc_check_flushing_done(void) {
1663   InputFile *ipf= flushing_input_file;
1664   if (!inputfile_is_done(ipf)) return;
1665
1666   assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1667
1668   notice_processed(ipf,"feed file",0);
1669
1670   close_defer();
1671
1672   xunlink(path_flushing, "old flushing file");
1673
1674   close_input_file(flushing_input_file);
1675   free(flushing_input_file);
1676   flushing_input_file= 0;
1677
1678   if (sms==sm_SEPARATED) {
1679     notice("flush complete");
1680     SMS(NORMAL, 0, "flush complete");
1681   } else if (sms==sm_DROPPING) {
1682     SMS(DROPPED, 0, "old flush complete");
1683     search_backlog_file();
1684     notice("feed dropped, but will continue until backlog is finished");
1685   }
1686 }
1687
1688 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
1689                                       void *u) {
1690   assert(!inputfile_is_done(main_input_file));
1691   statemc_check_flushing_done();
1692   statemc_check_backlog_done();
1693   return OOP_CONTINUE;
1694 }
1695
1696 static void queue_check_input_done(void) {
1697   loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
1698 }
1699
1700 static void statemc_setstate(StateMachineState newsms, int periods,
1701                              const char *forlog, const char *why) {
1702   sms= newsms;
1703   sm_period_counter= periods;
1704
1705   const char *xtra= "";
1706   switch (sms) {
1707   case sm_FLUSHING: sm_FLUSHFAILED:
1708     if (!main_input_file) xtra= "-ABSENT";
1709     break;
1710   case sm_SEPARATED: case sm_DROPPING:
1711     xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
1712     break;
1713   default:;
1714   }
1715
1716   if (periods) {
1717     info("%s%s[%d] %s",forlog,xtra,periods,why);
1718   } else {
1719     info("%s%s %s",forlog,xtra,why);
1720   }
1721 }
1722
1723 /*---------- defer and backlog files ----------*/
1724
1725 static void open_defer(void) {
1726   struct stat stab;
1727
1728   if (defer) return;
1729
1730   defer= fopen(path_defer, "a+");
1731   if (!defer) sysfatal("could not open defer file %s", path_defer);
1732
1733   /* truncate away any half-written records */
1734
1735   xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1736
1737   if (stab.st_size > LONG_MAX)
1738     die("defer file %s size is far too large", path_defer);
1739
1740   if (!stab.st_size)
1741     return;
1742
1743   long orgsize= stab.st_size;
1744   long truncto= stab.st_size;
1745   for (;;) {
1746     if (!truncto) break; /* was only (if anything) one half-truncated record */
1747     if (fseek(defer, truncto-1, SEEK_SET) < 0)
1748       sysdie("seek in defer file %s while truncating partial", path_defer);
1749
1750     r= getc(defer);
1751     if (r==EOF) {
1752       if (ferror(defer))
1753         sysdie("failed read from defer file %s", path_defer);
1754       else
1755         die("defer file %s shrank while we were checking it!", path_defer);
1756     }
1757     if (r=='\n') break;
1758     truncto--;
1759   }
1760
1761   if (stab.st_size != truncto) {
1762     warn("truncating half-record at end of defer file %s -"
1763          " shrinking by %ld bytes from %ld to %ld",
1764          path_defer, orgsize - truncto, orgsize, truncto);
1765
1766     if (fflush(defer))
1767       sysfatal("could not flush defer file %s", path_defer);
1768     if (ftruncate(fileno(defer), truncto))
1769       sysdie("could not truncate defer file %s", path_defer);
1770
1771   } else {
1772     info("continuing existing defer file %s (%ld bytes)",
1773          path_defer, orgsize);
1774   }
1775   if (fseek(defer, truncto, SEEK_SET))
1776     sysdie("could not seek to new end of defer file %s", path_defer);
1777 }
1778
1779 static void close_defer(void) {
1780   if (!defer)
1781     return;
1782
1783   xfstat(fileno(defer), &stab, "defer file");
1784
1785   if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1786   defer= 0;
1787
1788   char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1789                            (unsigned long)now.tv_sec,
1790                            (unsigned long)stab.st_ino);
1791   if (link(path_defer, path_backlog))
1792     sysfatal("could not install defer file %s as backlog file %s",
1793            path_defer, backlog);
1794   if (unlink(path_defer))
1795     sysdie("could not unlink old defer link %s to backlog file %s",
1796            path_defer, backlog);
1797
1798   if (until_backlog_nextscan < 0 ||
1799       until_backlog_nextscan > backlog_retry_minperiods + 1)
1800     until_backlog_nextscan= backlog_retry_minperiods + 1;
1801 }
1802
1803 static void poll_backlog_file(void) {
1804   if (until_backlog_nextscan < 0) return;
1805   if (until_backlog_nextscan-- > 0) return;
1806   search_backlog_file();
1807 }
1808
1809 static void search_backlog_file(void) {
1810   /* returns non-0 iff there are any backlog files */
1811
1812   glob_t gl;
1813   int r;
1814   struct stat stab;
1815   const char *oldest_path=0;
1816   time_t oldest_mtime, now;
1817
1818   if (backlog_input_file) return 3;
1819
1820  try_again:
1821
1822   r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
1823
1824   switch (r) {
1825   case GLOB_ABORTED:
1826     sysdie("failed to expand backlog pattern %s", globpat_backlog);
1827   case GLOB_NOSPACE:
1828     die("out of memory expanding backlog pattern %s", globpat_backlog);
1829   case 0:
1830     for (i=0; i<gl.gl_pathc; i++) {
1831       const char *path= gl.gl_pathv[i];
1832
1833       if (strchr(path,'#') || strchr(path,'~')) {
1834         debug("backlog file search skipping %s", path);
1835         continue;
1836       }
1837       r= stat(path, &stab);
1838       if (r) {
1839         syswarn("failed to stat backlog file %s", path);
1840         continue;
1841       }
1842       if (!S_ISREG(stab.st_mode)) {
1843         warn("backlog file %s is not a plain file (or link to one)", path);
1844         continue;
1845       }
1846       if (!oldest_path || stab.st_mtime < oldest_mtime) {
1847         oldest_path= path;
1848         oldest_mtime= stab.st_mtime;
1849       }
1850     }
1851   case GLOB_NOMATCH: /* fall through */
1852     break;
1853   default:
1854     sysdie("glob expansion of backlog pattern %s gave unexpected"
1855            " nonzero (error?) return value %d", globpat_backlog, r);
1856   }
1857
1858   globfree(&gl);
1859
1860   if (!oldest_path) {
1861     debug("backlog scan: none");
1862
1863     if (sms==sm_DROPPED) {
1864       notice("feed dropped and our work is complete");
1865       xunlink(path_lock, "lockfile for old feed");
1866       exit(0);
1867     }
1868     until_backlog_nextscan= backlog_spontaneous_rescan_periods;
1869     return 0;
1870   }
1871
1872   now= time();  if (now==-1) sysdie("time(2) failed");
1873   double age= difftime(now, oldest_mtime);
1874   long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
1875
1876   if (age_deficiency <= 0) {
1877     debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
1878           age, age_deficiency, oldest_path);
1879
1880     backlog_input_file= open_input_file(oldest_path);
1881     if (!backlog_input_file) {
1882       warn("backlog file %s vanished as we opened it", backlog_input_file);
1883       goto try_again;
1884     }
1885     inputfile_tailing_start(backlog_input_file);
1886     until_backlog_nextscan= -1;
1887     return 1;
1888   }
1889
1890   until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
1891
1892   if (backlog_spontaneous_rescan_periods >= 0 &&
1893       until_backlog_nextscan > backlog_spontaneous_rescan_periods)
1894     until_backlog_nextscan= backlog_spontaneous_rescan_periods;
1895
1896   debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
1897         age, age_deficiency, until_backlog_nextscan, oldest_path);
1898   return 2;
1899 }
1900
1901 /*========== flushing the feed ==========*/
1902
1903 static pid_t inndcomm_child;
1904
1905 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1906   assert(inndcomm_child);
1907   int status= xwaitpid(&inndcomm_child, "inndcomm");
1908   loop->cancel_fd(fd);
1909   close(fd);
1910
1911   assert(!flushing_input_file);
1912
1913   if (WIFEXITED(status)) {
1914     switch (WEXITSTATUS(status)) {
1915
1916     case INNDCOMMCHILD_ESTATUS_FAIL:
1917       goto failed;
1918
1919     case INNDCOMMCHILD_ESTATUS_NONESUCH:
1920       warn("feed has been dropped by innd, finishing up");
1921       flushing_input_file= main_input_file;
1922       tailing_queue_readable(flushing_input_file);
1923         /* we probably previously returned EAGAIN from our fake read method
1924          * when in fact we were at EOF, so signal another readable event
1925          * so we actually see the EOF */
1926
1927       main_input_file= 0;
1928
1929       if (flushing_input_file) {
1930         SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
1931       } else {
1932         close_defer();
1933         SMS(DROPPED, 0, "feed dropped by innd");
1934         search_backlog_file();
1935       }
1936       return OOP_CONTINUE;
1937
1938     case 0:
1939       /* as above */
1940       flushing_input_file= main_input_file;
1941       tailing_queue_readable(flushing_input_file);
1942
1943       main_input_file= open_input_file(feedfile);
1944       if (!main_input_file)
1945         die("flush succeeded but feedfile %s does not exist!", feedfile);
1946
1947       if (flushing_input_file) {
1948         SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
1949       } else {
1950         close_defer();
1951         SMS(NORMAL, spontaneous_flush_periods, "flush complete");
1952       }
1953       return OOP_CONTINUE;
1954
1955     default:
1956       goto unexpected_exitstatus;
1957
1958     }
1959   } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1960     warn("flush timed out trying to talk to innd");
1961     goto failed;
1962   } else {
1963   unexpected_exitstatus:
1964     report_child_status("inndcomm child", status);
1965   }
1966
1967  failed:
1968   SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
1969 }
1970
1971 static void inndcommfail(const char *what) {
1972   syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1973   exit(INNDCOMMCHILD_ESTATUS_FAIL);
1974 }
1975
1976 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
1977   int pipefds[2];
1978
1979   notice("flushing %s",why);
1980
1981   assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
1982   assert(!inndcomm_child);
1983
1984   if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1985
1986   inndcomm_child= xfork();
1987
1988   if (!inndcomm_child) {
1989     static char flushargv[2]= { sitename, 0 };
1990     char *reply;
1991
1992     close(pipefds[0]);
1993
1994     alarm(inndcomm_flush_timeout);
1995     r= ICCopen();                         if (r)   inndcommfail("connect");
1996     r= ICCcommand('f',flushargv,&reply);  if (r<0) inndcommfail("transmit");
1997     if (!r) exit(0); /* yay! */
1998
1999     if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2000     syswarn("innd ctlinnd flush failed: innd said %s", reply);
2001     exit(INNDCOMMCHILD_ESTATUS_FAIL);
2002   }
2003
2004   close(pipefds[1]);
2005   int sentinel_fd= pipefds[0];
2006   on_fd_read_except(sentinel_fd, inndcomm_event);
2007
2008   SMS(FLUSHING, 0, why);
2009 }
2010
2011 /*========== main program ==========*/
2012
2013 static void postfork_inputfile(InputFile *ipf) {
2014   if (!ipf) return;
2015   assert(ipf->fd >= 0);
2016   close(ipf->fd);
2017   ipf->fd= -1;
2018 }
2019
2020 static void postfork_conns(Connection *conn) {
2021   while (conn) {
2022     close(conn->fd);
2023     conn= conn->next;
2024   }
2025 }
2026
2027 static void postfork_stdio(FILE *f) {
2028   /* we have no stdio streams that are buffered long-term */
2029   if (f) fclose(f);
2030 }
2031
2032 static void postfork(const char *what) {
2033   if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2034     sysdie("%s child: failed to reset SIGPIPE");
2035
2036   postfork_inputfile(main_input_file);
2037   postfork_inputfile(flushing_input_file);
2038   postfork_conns(idle.head);
2039   postfork_conns(working.head);
2040   postfork_conns(full.head);
2041   postfork_stdio(defer);
2042 }
2043
2044 #define EVERY(what, interval, body)                                          \
2045   static const struct timeval what##_timeout = { 5, 0 };                     \
2046   static void what##_schedule(void);                                         \
2047   static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2048     { body }                                                                 \
2049     what##_schedule();                                                       \
2050   }                                                                          \
2051   static void what##_schedule(void) {                                        \
2052     loop->on_time(loop, what##_timeout, what##_timedout, 0);                 \
2053   }
2054
2055 EVERY(filepoll, {5,0}, {
2056   if (main_input_file && main_input_file->readable_callback)
2057     filemon_callback(main_input_file);
2058 });
2059
2060 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s"  \
2061 #define DEBUG_IPF(sh)                                           \
2062   wh##_input_file, debug_ipf_path(wh##_input_file),             \
2063   wh##_input_file->inprogress, (long)wh##_input_file->offset,   \
2064   wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2065 static const char *debug_ipf_path(InputFile *ipf) {
2066   char *slash= strrchr(ipf->path,'/');
2067   return slash ? slash+1 : ipf->path;
2068 }
2069
2070 EVERY(period, {PERIOD_SECONDS,0}, {
2071   debug("PERIOD"
2072         " sms=%s[%d] queue=%d connect_delay=%d"
2073         " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_FMT(flushing)
2074         " conns idle=%d working=%d full=%d"
2075         " children connecting=%ld inndcomm_child"
2076         ,
2077         sms_names[sms], sm_period_counter, queue.count, connect_delay,
2078         DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2079         idle.count, working.count, full.count,
2080         (long)connecting_child, (long)inndcomm_child
2081         );
2082
2083   if (connect_delay) connect_delay--;
2084
2085   poll_backlog_file();
2086   if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2087   statemc_period_poll();
2088   check_master_queue();
2089 });
2090
2091
2092 /*========== option parsing ==========*/
2093
2094 enum OptFlags {
2095   of_seconds= 001000u;
2096   of_boolean= 002000u;
2097 };
2098
2099 typedef struct Option Option;
2100 typedef void OptionParser(const Option*, const char *val);
2101
2102 struct Option {
2103   int short;
2104   const char *long;
2105   void *store;
2106   OptionParser *fn;
2107   int noarg;
2108 };
2109
2110 void op_integer(const Option *o, const char *val) {
2111   char *ep;
2112   errno= 0;
2113   unsigned long ul= strtoul(val,&ep,10);
2114   if (*ep || ep==val || errno || ul>INT_MAX)
2115     badusage("bad integer value for %s",o->long);
2116   int *store= o->store;
2117   *store= ul;
2118 }
2119
2120 void op_double(const Option *o, const char *val) {
2121   int *store= o->store;
2122   char *ep;
2123   errno= 0;
2124   *store= strtod(val, &ep);
2125   if (*ep || ep==val || errno)
2126     badusage("bad floating point value for %s",o->long);
2127 }
2128
2129 void op_string(const Option *o, const char *val) {
2130   char **store= o->store;
2131   free(*store);
2132   *store= val;
2133 }
2134
2135 void op_seconds(const Option *o, const char *val) {
2136   int *store= o->store;
2137   char *ep;
2138
2139   double v= strtod(val,&ep);
2140   if (ep==val) badusage("bad time/duration value for %s",o->long);
2141
2142   if (!*ep || !strcmp(ep,"s")) unit= 1;
2143   else if (!strcmp(ep,"m")) unit= 60;
2144   else if (!strcmp(ep,"h")) unit= 3600;
2145   else if (!strcmp(ep,"d")) unit= 86400;
2146   else badusage("bad units %s for time/duration value for %s",ep,o->long);
2147
2148   v *= unit;
2149   v= ceil(v);
2150   if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2151   *store= v;
2152 }
2153
2154 void op_periods_rndup(const Option *o, const char *val) {
2155   int *store= o->store;
2156   op_seconds(o,val);
2157   *store += PERIOD_SECONDS-1;
2158   *store /= PERIOD_SECONDS;
2159 }
2160
2161 void op_periods_booltrue(const Option *o, const char *val) {
2162   int *store= o->store;
2163   *store= 1;
2164 }
2165 void op_periods_boolfalse(const Option *o, const char *val) {
2166   int *store= o->store;
2167   *store= 0;
2168 }
2169
2170 static const Option options[]= {
2171 { 0, "max-connections",       &max_connections           op_integer          },
2172 { 0, "streaming",             &try_stream,               op_booltrue,  1     },
2173 { 0, "no-streaming",          &try_stream,               op_boolfalse, 1     },
2174 {'h',"host",                  &remote_host,              op_string           },
2175 {'P',"port",                  &port                      op_integer          },
2176 { 0, "inndconf",              &inndconffile,             op_string           },
2177 {'f',"feedfile",              &feedfile,                 op_string           },
2178 {'q',"quiet-multiple",        &quiet_if_locked,          op_booltrue,  1     },
2179 { 0, "no-quiet-multiple",     &quiet_if_locked,          op_boolfalse, 1     },
2180 {'d',"daemon",                &become_daemon,            op_booltrue,  1     },
2181 { 0, "no-daemon",             &become_daemon,            op_boolfalse, 1     },
2182
2183 { 0, "no-check-proportion",   &nocheck_thresh_pct,       op_double           },
2184 { 0, "no-check-filter",       &nocheck_decay_articles,   op_double           },
2185
2186 { 0, "max-queue-size",        &max_queue_per_conn        op_integer          },
2187 { 0, "reconnect-interval",    &reconnect_delay_periods,  op_periods_rndup    },
2188 { 0, "flush-retry-interval",  &flushfail_retry_periods,  op_periods_rndup    },
2189 { 0, "connection-timeout",    &connection_timeout,       op_seconds          },
2190 { 0, "inndcomm-timeout",      &inndcomm_flush_timeout,   op_seconds          },
2191 };
2192
2193 int main(int argc, char **argv) {
2194   const char *arg;
2195
2196   for (;;) {
2197     arg= *++argv;
2198     if (!arg) break;
2199     if (*arg != '-') break;
2200     if (!strcmp(arg,"--")) { arg= *++argv; break; }
2201     int a;
2202     while ((a= *++arg)) {
2203       const Option *o;
2204       if (a=='-') {
2205         arg++;
2206         char *equals= strchr(arg,'=');
2207         int len= equals ? (equals - arg) : strlen(arg);
2208         for (o=options; o->long; o++)
2209           if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2210             goto found_long;
2211         badusage("unknown long option --%s",arg);
2212       found_long:
2213         if (o->noarg) {
2214           if (equals) badusage("option --%s does not take a value",o->long);
2215           arg= 0;
2216         } else if (equals) {
2217           arg= equals+1;
2218         } else {
2219           arg= *++argv;
2220           if (!arg) badusage("option --%s needs a value",o->long);
2221         }
2222         o->fn(o, arg);
2223         break; /* eaten the whole argument now */
2224       }
2225       for (o=options; o->long; o++)
2226         if (a == o->short)
2227           goto found_short;
2228       badusage("unknown short option -%c",a);
2229     found_short:
2230       if (o->noarg) {
2231         o->fn(o,0);
2232       } else {
2233         if (!*++arg) {
2234           arg= *++argv;
2235           if (!arg) badusage("option -%c needs a value",o->short);
2236         }
2237         o->fn(o,arg);
2238         break; /* eaten the whole argument now */
2239       }
2240     }
2241   }
2242
2243   if (!arg) badusage("need site name argument");
2244   sitename= arg;
2245
2246   if ((arg= *++argv)) {
2247     if (remote_host) badusage("must not specify -h and also host as argument");
2248     remote_host= arg;
2249   }
2250
2251   if (*++argv) badusage("too many non-option arguments");
2252
2253   if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2254     badusage("nocheck threshold percentage must be between 0..100");
2255   nocheck_thresh= nocheck_thresh_pct * 0.01;
2256
2257   if (nocheck_decay_articles < 0.1)
2258     badusage("nocheck decay articles must be at least 0.1");
2259   nocheck_decay= 1 - 1/nocheck_decay_articles;
2260
2261   innconf_read(inndconffile);
2262
2263   if (!feedfile)
2264     feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2265   else if (!feedfile[0])
2266     badusage("feed filename must be nonempty");
2267   else if (feedfile[strlen(feedfile)-1]=='/')
2268     feedfile= xasprintf("%s%s",feedfile,sitename);
2269
2270   const char *feedfile_forbidden= "?*[~#";
2271   int c;
2272   while ((c= *feedfile_forbidden++))
2273     if (strchr(feedfile, c))
2274       badusage("feed filename may not contain metacharacter %c",c);
2275
2276   if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2277     sysdie("could not ignore SIGPIPE");
2278
2279   if (become_daemon) {
2280     for (i=3; i<255; i++)
2281       /* do this now before we open syslog, etc. */
2282       close(i);
2283     openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2284
2285     int null= open("/dev/null",O_RDWR);
2286     if (null<0) sysdie("failed to open /dev/null");
2287     dup2(null,0);
2288     dup2(null,1);
2289     dup2(null,2);
2290     close(null);
2291
2292     pid_t child1= xfork("daemonise first fork");
2293     if (child1) _exit(0);
2294
2295     pid_t sid= setsid();
2296     if (sid != child1) sysdie("setsid failed");
2297
2298     pid_t child2= xfork("daemonise second fork");
2299     if (child2) _exit(0);
2300   }
2301
2302   notice("starting");
2303
2304   if (!filemon_init()) {
2305     warn("no file monitoring available, polling");
2306     filepoll_schedule();
2307   }
2308
2309   period_schedule();
2310
2311   statemc_init();
2312
2313   loop->execute.
2314 }