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