2 * Newsfeeds file entries should look like this:
3 * host.name.of.site[/exclude,exclude,...]\
4 * :pattern,pattern...[/distribution,distribution...]\
8 * sitename[/exclude,exclude,...]\
9 * :pattern,pattern...[/distribution,distribution...]\
15 * or might be blanked out
16 * <spc><spc><spc><spc>....
18 * F site.name main feed file
19 * opened/created, then written, by innd
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
32 * site.name_defer 431'd articles, still being written,
33 * created, written, used by duct
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
48 * It is safe to remove backlog files manually,
49 * if it's desired to throw away the backlog.
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.
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.
69 | | <----------------<---------------------------------'|
75 | F: innd writing, duct reading |
78 | | duct decides time to flush |
79 | | duct makes hardlink |
81 | V <------------------------'|
83 | F == D: innd writing, duct reading both exist |
86 | | <-----------<-------------<--'|
90 | V <---------------------. |
93 | D: innd writing, duct reading; or ENOENT | |
95 | | duct requests flush of feed | |
96 | | (others can too, harmlessly) | |
100 | D: innd flushing, duct; or ENOENT | |
102 | | inndcomm flush fails | |
103 | |`-------------------------->------------------' |
105 | | inndcomm reports no such site |
106 | |`---------------------------------------------------- | -.
108 | | innd finishes writing D, creates F | |
109 | | inndcomm reports flush successful | |
112 | Separated <----------------' |
113 | F: innd writing F!=D /
114 | D: duct reading; or ENOENT both exist /
116 | | duct gets to the end of D /
117 | | duct opens F too /
120 | F: innd writing, duct reading |
121 | D: duct finishing V
123 | | duct finishes processing D F: ENOENT
124 | V duct unlinks D D: duct reading
126 `--<--' | duct finishes
136 "duct reading" means innduct is reading the file but also
137 overwriting processed tokens.
141 * rune for printing diagrams:
143 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
148 /*============================== PROGRAM ==============================*/
152 #include "inn/list.h"
159 #include <sys/types.h>
160 #include <sys/wait.h>
161 #include <sys/stat.h>
162 #include <sys/socket.h>
175 #include <oop-read.h>
177 /*----- general definitions, probably best not changed -----*/
179 #define PERIOD_SECONDS 60
181 #define CONNCHILD_ESTATUS_STREAM 4
182 #define CONNCHILD_ESTATUS_NOSTREAM 5
184 #define INNDCOMMCHILD_ESTATUS_FAIL 6
185 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
187 /*----- doubly linked lists -----*/
189 #define ISNODE(T) struct { T *succ, *pred; } node /* must be at start */
190 #define DEFLIST(T) typedef struct { T *hd, *tl, *tp; int count; } T##List
192 #define NODE(n) (assert((void*)&(n)->node == &(n)), \
193 (struct node*)&(n)->node)
195 #define LIST_CHECKCANHAVENODE(l,n) \
196 ((void)((n) == ((l).hd))) /* just for the type check */
198 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
199 ( LIST_CHECKCANHAVENODE(l,n), \
200 list_addsomehow((struct list*)&(l), NODE((n))), \
204 #define LIST_REMSOMEHOW(l,list_remsomehow) \
208 list_remsomehow((struct list*)&(l)) ) \
214 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
215 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
216 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
217 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
219 #define LIST_HEAD(l) ((typeof((l).hd))(list_head((struct list*)&(l))))
220 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
221 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
223 #define LIST_REMOVE(l,n) \
224 ( LIST_CHECKCANHAVENODE(l,n), \
225 list_remove(NODE((n))), \
229 #define LIST_INSERT(l,n,pred) \
230 ( LIST_CHECKCANHAVENODE(l,n), \
231 LIST_CHECKCANHAVENODE(l,pred), \
232 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
236 /*----- type predeclarations -----*/
238 typedef struct Conn Conn;
239 typedef struct Article Article;
240 typedef struct InputFile InputFile;
241 typedef struct XmitDetails XmitDetails;
242 typedef enum StateMachineState StateMachineState;
247 /*----- function predeclarations -----*/
249 static void conn_check_work(Conn *conn);
250 static void conn_make_some_xmits(Conn *conn);
251 static void *conn_write_some_xmits(Conn *conn);
253 static void xmit_free(XmitDetails *d);
255 static int filemon_init(void);
256 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
257 static void filemon_callback(void);
259 static void statemc_setstate(StateMachineState newsms, int periods,
260 const char *forlog, const char *why);
261 static void check_master_queue(void);
263 static void postfork(const char *what);
264 static void postfork_inputfile(InputFile *ipf);
266 /*----- configuration options -----*/
268 static char *sitename, *feedfile;
269 static const char *remote_host;
270 static int quiet_multiple=0, become_daemon=1;
272 static int max_connections=10, max_queue_per_conn=200;
274 static int connection_setup_timeout=200, port=119, try_stream=1;
275 static int inndcomm_flush_timeout=100;
276 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
277 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
278 static const char *inndconffile;
280 static double accept_proportion;
281 static double nocheck_thresh_pct= 95.0;
282 static double nocheck_thresh; /* computed in main from _pct */
283 static double nocheck_decay_articles= 100; /* converted to _decay */
284 static double nocheck_decay; /* computed in main from _articles */
285 static int nocheck, nocheck_reported;
288 /*----- statistics -----*/
290 typedef enum { /* in queue in conn->sent */
291 art_Unchecked, /* not checked, not sent checking */
292 art_Wanted, /* checked, wanted sent body as requested */
293 art_Unsolicited, /* - sent body without check */
297 #define RESULT_COUNTS(RCS,RCN) \
305 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
306 #define RCI_TRIPLE_VALS_BASE(counts,x) \
307 , counts[art_Unchecked] x \
308 + counts[art_Wanted] x \
309 + counts[art_Unsolicited] x, \
310 counts[art_Unchecked] x \
311 , counts[art_Wanted] x \
312 , counts[art_Unsolicited] x
315 #define RC_INDEX(x) RCI_##x,
316 RESULT_COUNTS(RC_INDEX, RC_INDEX)
321 /*----- transmission buffers -----*/
326 xk_Malloc, xk_Const, xk_Artdata
338 /*----- core operational data structure types -----*/
341 /* This is also an instance of struct oop_readable */
342 struct oop_readable readable; /* first */
343 oop_readable_call *readable_callback;
344 void *readable_callback_user;
347 struct Filemon_Perfile *filemon;
350 long inprogress; /* no. of articles read but not processed */
353 int counts[art_MaxState][RCI_max];
368 #define SMS_LIST(X) \
376 enum StateMachineState {
377 #define SMS_DEF_ENUM(s) sm_##s,
378 SMS_LIST(SMS_DEF_ENUM)
381 static const char *sms_names[]= {
382 #define SMS_DEF_NAME(s) #s ,
383 SMS_LIST(SMS_DEF_NAME)
389 int fd, max_queue, stream;
390 ArticleList queue; /* not yet told peer, or CHECK said send it */
391 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
392 struct iovec xmit[CONNIOVS];
393 XmitDetails xmitd[CONNIOVS];
398 /*----- operational variables -----*/
400 static oop_source *loop;
402 static int until_connect;
403 static ConnList conns;
404 static ArticleList queue;
406 static char *path_lock, *path_flushing, *path_defer;
408 #define SMS(newstate, periods, why) \
409 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
411 static StateMachineState sms;
413 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
414 static int sm_period_counter;
417 /*========== logging ==========*/
419 static void logcore(int sysloglevel, const char *fmt, ...)
420 __attribute__((__format__(printf,2,3)));
421 static void logcore(int sysloglevel, const char *fmt, ...) {
425 vsyslog(sysloglevel,fmt,al);
427 vfprintf(stderr,fmt,al);
433 static void logv(int sysloglevel, const char *pfx, int errnoval,
434 int exitstatus, const char *fmt, va_list al)
435 __attribute__((__format__(printf,5,0)));
436 static void logv(int sysloglevel, const char *pfx, int errnoval,
437 int exitstatus, const char *fmt, va_list al) {
438 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
439 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
440 msgbuf[sizeof(msgbuf)-1]= 0;
442 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
443 sysloglevel= LOG_ERR; /* run by wrong user, probably */
445 logcore(sysloglevel, "<%s>%s: %s%s%s",
446 sitename, pfx, msgbuf,
447 errnoval>=0 ? ": " : "",
448 errnoval>=0 ? strerror(errnoval) : "");
451 #define logwrap(fn, pfx, sysloglevel, err, estatus) \
452 static void fn(const char *fmt, ...) \
453 __attribute__((__format__(printf,1,2))); \
454 static void fn(const char *fmt, ...) { \
457 logv(sysloglevel, pfx, err, estatus, fmt, al); \
460 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
461 logwrap(die, " critical", LOG_CRIT, -1, 16);
463 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
464 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
466 logwrap(syswarn, " warning", LOG_WARNING, errno, 0);
467 logwrap(warn, " warning", LOG_WARNING, -1, 0);
469 logwrap(notice, "", LOG_NOTICE, -1, 0);
470 logwrap(info, " info", LOG_INFO, -1, 0);
471 logwrap(debug, " debug", LOG_DEBUG, -1, 0);
474 /*========== utility functions etc. ==========*/
476 static char *xvasprintf(const char *fmt, va_list al)
477 __attribute__((__format__(printf,1,0)));
478 static char *xvasprintf(const char *fmt, va_list al) {
480 int rc= vasprintf(&str,fmt,al);
481 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
484 static char *xasprintf(const char *fmt, ...)
485 __attribute__((__format__(printf,1,2)));
486 static char *xasprintf(const char *fmt, ...) {
489 char *str= xvasprintf(fmt,al);
494 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
496 static pid_t xfork(const char *what) {
500 if (child==-1) sysdie("cannot fork for %s",what);
501 if (!child) postfork(what);
502 debug("forked %s %ld", what, (unsigned long)child);
506 static void on_fd_read_except(int fd, oop_call_fd callback) {
507 loop->on_fd(loop, fd, OOP_READ, callback, 0);
508 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
510 static void cancel_fd_read_except(int fd) {
511 loop->cancel_fd(loop, fd, OOP_READ);
512 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
515 static void report_child_status(const char *what, int status) {
516 if (WIFEXITED(status)) {
517 int es= WEXITSTATUS(status);
519 warn("%s: child died with error exit status %d",es);
520 } else if (WIFSIGNALED(status)) {
521 int sig= WTERMSIG(status);
522 const char *sigstr= strsignal(sig);
523 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
525 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
527 warn("%s: child died due to unknown fatal signal %d%s",
528 what, sig, coredump);
530 warn("%s: child died with unknown wait status %d", status);
534 static int xwaitpid(pid_t *pid, const char *what) {
537 int r= kill(*pid, SIGKILL);
538 if (r) sysdie("cannot kill %s child", what);
540 pid_t got= waitpid(*pid, &status, WNOHANG);
541 if (got==-1) sysdie("cannot reap %s child", what);
548 static void xunlink(const char *path, const char *what) {
550 if (r) sysdie("can't unlink %s %s", path, what);
553 static void check_isreg(const struct stat *stab, const char *path,
555 if (!S_ISREG(stab->st_mode))
556 die("%s %s not a plain file (mode 0%lo)",
557 what, path, (unsigned long)stab->st_mode);
560 static void xfstat(int fd, struct stat *stab_r, const char *what) {
561 int r= fstat(fd, stab_r);
562 if (r) sysdie("could not fstat %s", what);
565 static void xfstat_isreg(int fd, struct stat *stab_r,
566 const char *path, const char *what) {
567 xfstat(fd, stab_r, what);
568 check_isreg(stab_r, path, what);
571 static void xlstat_isreg(const char *path, struct stat *stab,
572 int *enoent_r /* 0 means ENOENT is fatal */,
574 int r= lstat(path, stab);
576 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
577 sysdie("could not lstat %s %s", what, path);
579 if (enoent_r) *enoent_r= 0;
580 check_isreg(stab, path, what);
583 static void setnonblock(int fd, int nonblocking) {
584 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
585 if (nonblocking) r |= O_NONBLOCK;
586 else r &= ~O_NONBLOCK;
587 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
590 static int samefile(const struct stat *a, const struct stat *b) {
591 assert(S_ISREG(a->st_mode));
592 assert(S_ISREG(b->st_mode));
593 return (a->st_ino == b->st_ino &&
594 a->st_dev == b->st_dev);
597 static char *sanitise(const char *input) {
598 static char sanibuf[100]; /* returns pointer to this buffer! */
600 const char *p= input;
604 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
606 if (!c) { *q++= '\''; *q=0; break; }
607 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
608 sprintf(q,"\\x%02x",c);
614 /*========== making new connections ==========*/
616 static int connecting_sockets[2]= {-1,-1};
617 static pid_t connecting_child;
619 static void connect_attempt_discard(void) {
620 if (connecting_sockets[0])
621 cancel_fd_read_except(connecting_sockets[0]);
623 perhaps_close(&connecting_sockets[0]);
624 perhaps_close(&connecting_sockets[1]);
626 if (connecting_child) {
627 int r= kill(connecting_child, SIGTERM);
628 if (r) syswarn("failed to kill connecting child");
629 int status= xwaitpid(&connecting_child, "connect");
631 if (!(WIFEXITED(status) ||
632 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
633 report_child_status("connect", status);
637 #define PREP_DECL_MSG_CMSG(msg) \
639 memset(&msg,0,sizeof(msg)); \
640 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
641 msg.msg_control= msg##cbuf; \
642 msg.msg_controllen= sizeof(msg##cbuf);
644 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
647 conn= xmalloc(sizeof(*conn));
648 memset(conn,0,sizeof(*conn));
650 PREP_DECL_MSG_CMSG(msg);
651 struct cmsghdr *h= 0;
652 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
653 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
656 pid_t got= waitpid(connecting_child, &status, WNOHANG);
658 assert(got==connecting_child);
660 if (WIFEXITED(status) &&
661 (WEXITSTATUS(status) != 0 &&
662 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
663 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
664 /* child already reported the problem */
665 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
666 warn("connect: connection attempt timed out");
667 } else if (!WIFEXITED(status)) {
668 report_child_status("connect", status);
669 /* that's probably the root cause then */
672 /* child is still running apparently, report the socket problem */
674 syswarn("connect: read from child socket failed");
675 else if (e == OOP_EXCEPTION)
676 warn("connect: unexpected exception on child socket");
678 warn("connect: unexpected EOF on child socket");
683 #define CHK(field, val) \
684 if (h->cmsg_##field != val) { \
685 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
688 CHK(level, SOL_SOCKET);
689 CHK(type, SCM_RIGHTS);
690 CHK(len, CMSG_LEN(sizeof(conn->fd)));
693 if (CMSG_NXTHDR(&msg,h)) { die("connect: child sent many cmsgs"); goto x; }
695 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
698 pid_t got= waitpid(connecting_child, &status, 0);
699 if (got==-1) sysdie("connect: real wait for child");
700 assert(got == connecting_child);
703 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
704 int es= WEXITSTATUS(status);
706 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
707 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
709 fatal("connect: child gave unexpected exit status %d", es);
713 setnonblock(conn->fd, 1);
714 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
715 LIST_ADDHEAD(conns, conn);
716 notice("#%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
717 connect_attempt_discard();
718 check_master_queue();
723 perhaps_close(&conn->fd);
726 connect_attempt_discard();
729 static void connect_start(void) {
730 assert(!connecting_sockets[0]);
731 assert(!connecting_sockets[1]);
732 assert(!connecting_child);
734 notice("starting connection attempt");
736 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
737 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
739 connecting_child= xfork("connection");
741 if (!connecting_child) {
742 FILE *cn_from, *cn_to;
743 char buf[NNTP_STRLEN+100];
744 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
746 r= close(connecting_sockets[0]);
747 if (r) sysdie("connect: close parent socket in child");
749 alarm(connection_setup_timeout);
750 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
751 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
752 else sysfatal("connect: connection attempt failed");
754 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
755 sysfatal("connect: authentication failed");
757 if (fputs("MODE STREAM\r\n", cn_to) ||
759 sysfatal("connect: could not send MODE STREAM");
760 buf[sizeof(buf)-1]= 0;
761 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
763 sysfatal("connect: could not read response to MODE STREAM");
765 fatal("connect: connection close in response to MODE STREAM");
770 fatal("connect: response to MODE STREAM is too long: %.100s...",
771 remote_host, sanitise(buf));
772 l--; if (l>0 && buf[l-1]=='\r') l--;
775 int rcode= strtoul(buf,&ep,10);
777 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
781 exitstatus= CONNCHILD_ESTATUS_STREAM;
787 warn("connect: unexpected response to MODE STREAM: %.50s",
793 int fd= fileno(cn_from);
795 PREP_DECL_MSG_CMSG(msg);
796 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
797 cmsg->cmsg_level= SOL_SOCKET;
798 cmsg->cmsg_type= SCM_RIGHTS;
799 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
800 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
802 msg.msg_controllen= cmsg->cmsg_len;
803 r= sendmsg(connecting_sockets[1], &msg, 0);
804 if (r) sysdie("sendmsg failed for new connection");
809 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
810 if (r) sysdie("connect: close child socket in parent");
812 on_fd_read_except(connecting_sockets[0], connchild_event);
816 connect_attempt_discard();
820 /*========== overall control of article flow ==========*/
822 static void check_master_queue(void) {
829 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
830 int inqueue= walk->sent.count + walk->queue.count;
831 spare= walk->max_queue - inqueue;
832 assert(inqueue <= max_queue_per_conn);
834 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
835 else if (spare>0) /*working*/ { use= walk; break; }
839 Article *art= LIST_REMHEAD(queue);
840 LIST_ADDTAIL(use->queue, art);
843 conn_check_work(use);
844 } else if (conns.count < max_connections &&
845 !connecting_child && !until_connect) {
846 until_connect= reconnect_delay_periods;
855 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
860 static void conn_check_work(Conn *conn) {
863 conn_make_some_xmits(conn);
865 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
869 void *rp= conn_write_some_xmits(conn);
870 if (rp==OOP_CONTINUE) {
871 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
873 } else if (rp==OOP_HALT) {
876 /* transmitted everything */
883 static void vconnfail(Conn *conn, const char *fmt, va_list al)
884 __attribute__((__format__(printf,2,0)));
886 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
887 int requeue[art_MaxState];
890 while ((art= LIST_REMHEAD(conn->queue))) LIST_ADDTAIL(queue, art);
891 while ((art= LIST_REMHEAD(conn->sent))) {
892 requeue[art->state]++;
893 if (art->state==art_Unsolicited) art->state= art_Unchecked;
894 LIST_ADDTAIL(queue,art);
899 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
902 char *m= xvasprintf(fmt,al);
903 warn("#%d connection failed, requeueing " RCI_TRIPLE_FMT_BASE ": %s",
904 conn->fd, RCI_TRIPLE_FMT_VALS(requeue, /*nothing*/), m);
908 fixme remove conn from the appropriate list;
911 until_connect= reconnect_delay_periods;
912 check_master_queue();
915 static void connfail(Connection *conn, const char *fmt, ...)
916 __attribute__((__format__(printf,2,3)));
917 static void connfail(Connection *conn, const char *fmt, ...) {
924 /*========== article transmission ==========*/
926 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
927 XmitKind kind) { /* caller must then fill in details */
928 struct iovec *v= &conn->xmit[conn->xmitu];
929 XmitDetails *d= &conn->xmitd[conn->xmitu++];
936 static void xmit_noalloc(Conn *conn, const char *data, int len) {
937 xmit_core(conn,data,len, xk_Const);
939 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
941 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
942 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
946 static void xmit_free(XmitDetails *d) {
948 case xk_Malloc: free(d->info.malloc_tofree); break;
949 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
950 case xk_Const: break;
955 static void *conn_write_some_xmits(Conn *conn) {
957 * 0: nothing more to write, no need to call us again
958 * OOP_CONTINUE: more to write but fd not writeable
959 * OOP_HALT: disaster, have destroyed conn
962 int count= conn->xmitu;
963 if (!count) return 0;
965 if (count > IOV_MAX) count= IOV_MAX;
966 ssize_t rs= writev(conn->fd, conn->xmit, count);
968 if (errno == EAGAIN) return OOP_CONTINUE;
969 connfail(conn, "write failed: %s", strerror(errno));
974 for (done=0; rs && done<xmitu; done++) {
975 struct iovec *vp= &conn->xmit[done];
976 XmitDetails *dp= &conn->xmitd[done];
977 if (rs > vp->iov_len) {
985 int newu= conn->xmitu - done;
986 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
987 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
992 static void conn_make_some_xmits(Conn *conn) {
994 if (conn->xmitu+5 > CONNIOVS)
997 Article *art= LIST_REMHEAD(queue);
1000 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1001 /* actually send it */
1003 ARTHANDLE *artdata= SMretrieve();
1007 XMIT_LITERAL("TAKETHIS ");
1008 xmit_noalloc(conn, art->mid, art->midlen);
1009 XMIT_LITERAL("\r\n");
1010 xmit_artbody(conn, artdata);
1013 /* we got 235 from IHAVE */
1015 xmit_artbody(conn, artdata);
1017 XMIT_LITERAL(".\r\n");
1022 art->state == art_Unchecked ? art_Unsolicited :
1023 art->state == art_Wanted ? art_Wanted :
1025 art->ipf->counts[art->state].sent++;
1026 LIST_ADDTAIL(conn->sent, art);
1032 XMIT_LITERAL("IHAVE ");
1034 XMIT_LITERAL("CHECK ");
1035 xmit_noalloc(art->mid, art->midlen);
1036 XMIT_LITERAL("\r\n");
1038 assert(art->state == art_Unchecked);
1039 art->ipf->counts[art->state].sent++;
1040 LIST_ADDTAIL(conn->sent, art);
1046 /*========== handling responses from peer ==========*/
1048 static const oop_rd_style peer_rd_style= {
1049 OOP_RD_DELIM_STRIP, '\n',
1051 OOP_RD_SHORTREC_FORBID
1054 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1055 const char *errmsg, int errnoval,
1056 const char *data, size_t recsz, void *conn_v) {
1058 connfail(conn, "error receiving from peer: %s", errmsg);
1059 return OOP_CONTINUE;
1062 static Article *article_reply_check(Connection *conn, const char *response,
1063 int code_indicates_streaming,
1065 /* 1:yes, -1:no, 0:dontcare */,
1066 const char *sanitised_response) {
1067 Article *art= conn->sent.head;
1071 "peer gave unexpected response when no commands outstanding: %s",
1072 sanitised_response);
1076 if (code_indicates_streaming) {
1077 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1078 if (!conn->stream) {
1079 connfail("peer gave streaming response code "
1080 " to IHAVE or subsequent body: %s", sanitised_response);
1083 const char *got_mid= response+4;
1084 int got_midlen= strcspn(got_mid, " \n\r");
1085 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1086 connfail("peer gave streaming response with syntactically invalid"
1087 " messageid: %s", sanitised_response);
1090 if (got_midlen != art->midlen ||
1091 memcmp(got_mid, art->messageid, got_midlen)) {
1092 connfail("peer gave streaming response code to wrong article -"
1093 " probable synchronisation problem; we offered: %s;"
1095 art->messageid, sanitised_response);
1100 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
1101 sanitised_response);
1106 if (must_have_sent>0 && art->state < art_Wanted) {
1107 connfail("peer says article accepted but we had not sent the body: %s",
1108 sanitised_response);
1111 if (must_have_sent<0 && art->state >= art_Wanted) {
1112 connfail("peer says please sent the article but we just did: %s",
1113 sanitised_response);
1117 Article *art_again= LIST_REMHEAD(conn->sent);
1118 assert(art_again == art);
1122 static void update_nocheck(int accepted) {
1123 accept_proportion *= accept_decay;
1124 accept_proportion += accepted;
1125 int new_nocheck= accept_proportion >= nocheck_thresh;
1126 if (new_nocheck && !nocheck_reported) {
1127 notice("entering nocheck mode for the first time");
1128 nocheck_reported= 1;
1129 } else if (new_nocheck != nocheck) {
1130 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1132 nocheck= new_nocheck;
1135 static void article_done(Connection *conn, Article *art, int whichcount) {
1136 art->ipf->counts[art->state][whichcount]++;
1137 if (whichcount == RC_accepted) update_nocheck(1);
1138 else if (whichcount == RC_unwanted) update_nocheck(0);
1140 InputFile *ipf= art->ipf;
1141 while (art->blanklen) {
1142 static const char spaces[]=
1147 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1148 int r= pwrite(ipf->fd, spaces, w, art->offset);
1150 if (errno==EINTR) continue;
1151 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1152 art->messageid, art->blanklen, art->offset, ipf->path);
1154 assert(r>=0 && r<=w);
1160 assert(ipf->inprogress >= 0);
1162 if (!ipf->inprogress && ipf != main_input_file)
1163 queue_check_input_done();
1168 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1169 const char *errmsg, int errnoval,
1170 const char *data, size_t recsz, void *conn_v) {
1173 if (ev == OOP_RD_EOF) {
1174 connfail(conn, "unexpected EOF from peer");
1175 return OOP_CONTINUE;
1177 assert(ev == OOP_RD_OK);
1179 char *sani= sanitise(data, recsz);
1182 unsigned long code= strtoul(data, &ep, 10);
1183 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1184 connfail(conn, "badly formatted response from peer: %s", sani);
1185 return OOP_CONTINUE;
1188 if (conn->quitting) {
1190 connfail(conn, "peer gave failure response to QUIT: %s", sani);
1191 return OOP_CONTINUE;
1199 #define GET_ARTICLE(musthavesent) \
1200 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1201 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1203 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1204 code_streaming= (streaming) \
1205 GET_ARTICLE(musthavesent); \
1206 article_done(conn, art, RC_##how); break;
1208 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1210 int code_streaming= 0;
1214 case 400: PEERBADMSG("peer stopped accepting articles");
1215 case 503: PEERBADMSG("peer timed us out");
1216 default: PEERBADMSG("peer sent unexpected message");
1218 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1219 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1221 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1222 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1224 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1225 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1227 case 238: /* CHECK says send it */
1229 case 335: /* IHAVE says send it */
1231 assert(art->state == art_Unchecked);
1232 art->ipf->counts[art->state].accepted++;
1233 art->state= art_Wanted;
1234 LIST_ADDTAIL(conn->queue);
1237 case 431: /* CHECK or TAKETHIS says try later */
1239 case 436: /* IHAVE says try later */
1242 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1244 sysfatal("write to defer file %s",path_defer);
1245 article_done(conn, art, RC_deferred);
1250 check_check_work(conn);
1251 return OOP_CONTINUE;
1255 /*========== monitoring of input files ==========*/
1257 static void feedfile_eof(InputFile *ipf) {
1258 assert(ipf != main_input_file); /* promised by tailing_try_read */
1260 inputfile_tailing_stop(ipf);
1261 assert(ipf->fd >= 0);
1262 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1265 if (ipf == flushing_input_file) {
1266 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1267 if (main_input_file) inputfile_tailing_start(main_input_file);
1268 statemc_check_flushing_done();
1269 } else if (ipf == backlog_input_file) {
1270 statemc_check_backlog_done();
1272 abort(); /* supposed to wait rather than get EOF on main input file */
1276 static InputFile *open_input_file(const char *path) {
1277 int fd= open(path, O_RDONLY);
1279 if (errno==ENOENT) return 0;
1280 sysfatal("unable to open input file %s", path);
1283 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1284 memset(ipf,0,sizeof(*ipf));
1286 ipf->readable.on_readable= tailing_on_readable;
1287 ipf->readable.on_cancel= tailing_on_cancel;
1288 ipf->readable.try_read= tailing_try_read;
1291 strcpy(ipf->path, path);
1296 static void close_input_file(InputFile *ipf) {
1297 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1298 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1299 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1300 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1303 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1307 /*---------- dealing with articles read in the input file ----------*/
1309 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1310 oop_rd_event ev, const char *errmsg,
1312 const char *data, size_t recsz,
1314 InputFile *ipf= ipf_v;
1316 char tokentextbuf[sizeof(TOKEN)*2+3];
1318 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1320 if (data[0] && data[0]!=' ') {
1321 char *space= strchr(data,' ');
1322 int tokenlen= space-data;
1323 int midlen= (int)recsz-tokenlen-1;
1324 if (midlen < 0) goto bad_data;
1326 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1327 memcpy(tokentextbuf, data, tokenlen);
1328 tokentextbuf[tokenlen]= 0;
1329 if (!IsToken(tokentextbuf)) goto bad_data;
1331 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1332 art->offset= ipf->offset;
1333 art->blanklen= recsz;
1334 art->midlen= midlen;
1335 art->state= art_Unchecked;
1336 art->ipf= ipf; ipf->inprogress++;
1337 art->token= TextToToken(tokentextbuf);
1338 strcpy(art->messageid, space+1);
1339 LIST_ADDTAIL(queue, art);
1341 ipf->offset += recsz + 1;
1343 if (sms==sm_NORMAL && ipf==main_input_file &&
1344 ipf->offset >= flush_threshold)
1345 statemc_start_flush("feed file size");
1347 check_master_queue();
1350 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1351 assert(sms == sm_NORMAL);
1353 debug("starting flush (%s) (%lu >= %lu) (%d)",
1355 (unsigned long)ipf->offset, (unsigned long)flush_threshold,
1358 int r= link(feedfile, duct_path);
1359 if (r) sysdie("link feedfile %s to flushing file %s", feedfile,
1363 xunlink(feedfile, "old feedfile link");
1366 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1369 /*========== tailing input file ==========*/
1371 static void filemon_start(InputFile *ipf) {
1372 assert(!ipf->filemon);
1374 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1375 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1376 filemon_method_startfile(ipf, ipf->filemon);
1379 static void filemon_stop(InputFile *ipf) {
1380 if (!ipf->filemon) return;
1381 filemon_method_stopfile(ipf, ipf->filemon);
1386 static void filemon_callback(InputFile *ipf) {
1387 ipf->readable_callback(ipf->readable_callback_user);
1390 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1392 InputFile *ipf= user;
1393 return ipf->readable_callback(ipf->readable_callback_user);
1396 static void on_cancel(struct oop_readable *rable) {
1397 InputFile *ipf= (void*)rable;
1399 if (ipf->filemon) filemon_stopfile(ipf);
1400 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1401 ipf->readable_callback= 0;
1404 static void tailing_queue_readable(InputFile *ipf) {
1405 /* lifetime of ipf here is OK because destruction will cause
1406 * on_cancel which will cancel this callback */
1407 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1410 static int tailing_on_readable(struct oop_readable *rable,
1411 oop_readable_call *cb, void *user) {
1412 InputFile *ipf= (void*)rable;
1414 tailing_on_cancel(rable);
1415 ipf->readable_callback= cb;
1416 ipf->readable_callback_user= user;
1417 filemon_startfile(ipf);
1419 tailing_queue_readable(ipf);
1423 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1425 InputFile *ipf= (void*)rable;
1427 ssize_t r= read(ipf->fd, buffer, length);
1429 if (errno==EINTR) continue;
1433 if (ipf==main_input_file) {
1436 } else if (ipf==flushing_input_file) {
1438 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1439 } else if (ipf==backlog_input_file) {
1449 /*---------- filemon implemented with inotify ----------*/
1451 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1452 #define HAVE_FILEMON
1454 #include <linux/inotify.h>
1456 static int filemon_inotify_fd;
1457 static int filemon_inotify_wdmax;
1458 static InputFile **filemon_inotify_wd2ipf;
1460 typedef struct Filemon_Perfile {
1462 } Filemon_Inotify_Perfile;
1464 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1465 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1466 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1468 if (wd >= filemon_inotify_wdmax) {
1470 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1471 sizeof(*filemon_inotify_wd2ipf) * newmax);
1472 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1473 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1474 filemon_inotify_wdmax= newmax;
1477 assert(!filemon_inotify_wd2ipf[wd]);
1478 filemon_inotify_wd2ipf[wd]= ipf;
1480 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1481 ipf, wd, filemon_inotify_wdmax);
1486 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1488 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1489 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1490 if (r) sysdie("inotify_rm_watch");
1491 filemon_inotify_wd2ipf[wd]= 0;
1494 static void *filemon_inotify_readable(oop_source *lp, int fd,
1495 oop_event e, void *u) {
1496 struct inotify_event iev;
1498 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1500 if (errno==EAGAIN) break;
1501 sysdie("read from inotify master");
1502 } else if (r==sizeof(iev)) {
1503 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1505 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1507 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1508 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1509 filemon_callback(ipf);
1511 return OOP_CONTINUE;
1514 static int filemon_method_init(void) {
1515 filemon_inotify_fd= inotify_init();
1516 if (filemon_inotify_fd<0) {
1517 syswarn("could not initialise inotify: inotify_init failed");
1521 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1523 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1527 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1529 /*---------- filemon dummy implementation ----------*/
1531 #if !defined(HAVE_FILEMON)
1533 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1535 static int filemon_method_init(void) { return 0; }
1536 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1537 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1539 #endif /* !HAVE_FILEMON */
1541 /*---------- interface to start and stop an input file ----------*/
1543 static const oop_rd_style feedfile_rdstyle= {
1544 OOP_RD_DELIM_STRIP, '\n',
1546 OOP_RD_SHORTREC_EOF,
1549 static void inputfile_tailing_start(InputFile *ipf) {
1551 ipf->readable->on_readable= tailing_on_readable;
1552 ipf->readable->on_cancel= tailing_on_cancel;
1553 ipf->readable->try_read= tailing_try_read;
1554 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1555 ipf->readable->delete_kill= 0;
1557 ipf->readable_callback= 0;
1558 ipf->readable_callback_user= 0;
1560 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1563 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1564 feedfile_got_article,ipf, feedfile_problem,ipf);
1565 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1568 static void inputfile_tailing_stop(InputFile *ipf) {
1570 oop_rd_cancel(ipf->rd);
1571 oop_rd_delete(ipf->rd);
1573 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1577 /*========== interaction with innd - state machine ==========*/
1579 /* See official state diagram at top of file. We implement
1590 |`---------------------------------------------------.
1592 |`---------------- - - - |
1593 D ENOENT | D EXISTS see OVERALL STATES diagram |
1594 | for full startup logic |
1597 | ============ try to |
1603 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1604 ^ | hardlink F to D |
1607 | | our handle onto F is now onto D |
1610 | |<-------------------<---------------------<---------+
1612 | | spawn inndcomm flush |
1614 | ================== |
1615 | FLUSHING[-ABSENT] |
1617 | main D tail/none |
1618 | ================== |
1620 | | INNDCOMM FLUSH FAILS ^
1621 | |`----------------------->----------. |
1623 | | NO SUCH SITE V |
1624 ^ |`--------------->----. ==================== |
1625 | | \ FLUSHFAILED[-ABSENT] |
1627 | | FLUSH OK \ main D tail/none |
1628 | | open F \ ==================== |
1630 | | \ | TIME TO RETRY |
1631 | |`------->----. ,---<---'\ `----------------'
1632 | | D NONE | | D NONE `----.
1634 | ============= V V ============
1635 | SEPARATED-1 | | DROPPING-1
1636 | flsh->fd>=0 | | flsh->fd>=0
1637 | [Separated] | | [Dropping]
1638 | main F idle | | main none
1639 | old D tail | | old D tail
1640 | ============= | | ============
1642 ^ | EOF ON D | | defer | EOF ON D
1644 | =============== | | ===============
1645 | SEPARATED-2 | | DROPPING-2
1646 | flsh->fd==-1 | V flsh->fd==-1
1647 | [Finishing] | | [Dropping]
1648 | main F tail | `. main none
1649 | old D closed | `. old D closed
1650 | =============== V `. ===============
1652 | | ALL D PROCESSED `. | ALL D PROCESSED
1653 | V install defer as backlog `. | install defer
1654 ^ | close D `. | close D
1655 | | unlink D `. | unlink D
1658 `----------' ==============
1678 static void statemc_init(void) {
1679 struct stat stab, stabf;
1681 path_lock= xasprintf("%s_lock", feedfile);
1682 path_flushing= xasprintf("%s_flushing", feedfile);
1683 path_defer= xasprintf("%s_defer", feedfile);
1684 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1687 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1688 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1691 memset(&fl,0,sizeof(fl));
1693 fl.l_whence= SEEK_SET;
1694 r= fcntl(lockfd, F_SETLK, &fl);
1696 if (errno==EACCES || errno==EAGAIN) {
1697 if (quiet_multiple) exit(0);
1698 fatal("another duct holds the lockfile");
1700 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1703 xfstat_isreg(lockfd, &stabf, "lockfile");
1705 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1707 if (!lock_noent && samefile(&stab, &stabf))
1711 sysdie("could not close stale lockfile %s", path_lock);
1713 debug("startup: locked");
1715 search_backlog_file();
1718 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1720 debug("startup: ductdefer ENOENT");
1722 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1723 switch (stab.st_nlink==1) {
1725 open_defer(); /* so that we will later close it and rename it */
1728 xunlink(path_defer, "stale defer file link"
1729 " (presumably hardlink to backlog file)");
1732 die("defer file %s has unexpected link count %d",
1733 path_defer, stab.st_nlink);
1737 struct stat stab_f, stab_d;
1740 InputFile *file_d= open_input_file(path_flushing);
1741 if (file_d) xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1743 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1745 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1746 debug("startup: F==D => Hardlinked");
1747 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1752 debug("startup: F ENOENT => Moved");
1753 if (file_d) startup_set_input_file(file_d);
1754 spawn_inndcomm_flush("feedfile missing at startup");
1755 /* => Flushing, sms:=FLUSHING */
1758 debug("startup: F!=D => Separated");
1759 startup_set_input_file(file_d);
1760 SMS(SEPARATED, 0, "found both old and current feed files");
1762 debug("startup: F exists, D ENOENT => Normal");
1763 FILE *file_f= open_input_file(feedfile);
1764 if (!file_f) die("feed file vanished during startup");
1765 startup_set_input_file(file_f);
1766 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1771 static void statemc_period_poll(void) {
1772 if (!sm_period_counter) return;
1773 sm_period_counter--;
1774 assert(sm_period_counter>=0);
1776 if (sm_period_counter) return;
1779 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1781 case sm_FLUSHFAILED:
1782 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1789 static void startup_set_input_file(InputFile *f) {
1790 assert(!main_input_file);
1792 inputfile_tailing_start(f);
1795 static int inputfile_is_done(InputFile *ipf) {
1797 if (ipf->inprogress) return 0; /* new article in the meantime */
1798 if (ipf->fd >= 0); return 0; /* not had EOF */
1802 static void notice_processed(InputFile *ipf, const char *what,
1804 #define RCI_NOTHING(x) /* nothing */
1805 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
1806 #define RCI_TRIPLE_VALS(x) RCI_TRIPLE_VALS_BASE(ipf->counts, .x)
1808 info("processed %s%s offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
1809 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
1812 ipf->counts[art_Unchecked].sent + ipf->counts[art_Unsolicited].sent
1813 , ipf->counts[art_Unchecked].sent, ipf->counts[art_Unsolicited].sent,
1814 ipf->counts[art_Wanted].accepted + ipf->counts[art_Unsolicited].accepted
1815 ,ipf->counts[art_Wanted].accepted,ipf->counts[art_Unsolicited].accepted
1816 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
1820 static void statemc_check_backlog_done(void) {
1821 InputFile *ipf= backlog_input_file();
1822 if (!inputfile_is_done(ipf)) return;
1824 const char *slash= strrchr(ipf->path, "/");
1825 const char *leaf= slash ? slash+1 : ipf->path;
1826 const char *under= strchr(slash, "_");
1827 const char *rest= under ? under+1 : leaf;
1828 if (!strncmp(rest,"backlog",7)) rest += 7;
1829 notice_processed(ipf,"backlog:",rest);
1831 close_input_file(ipf);
1832 if (unlink(ipf->path)) {
1833 if (errno != ENOENT)
1834 sysdie("could not unlink processed backlog file %s", ipf->path);
1835 warn("backlog file %s vanished while we were reading it"
1836 " so we couldn't remove it (but it's done now, anyway)",
1840 backlog_input_file= 0;
1841 search_backlog_file();
1845 static void statemc_check_flushing_done(void) {
1846 InputFile *ipf= flushing_input_file;
1847 if (!inputfile_is_done(ipf)) return;
1849 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1851 notice_processed(ipf,"feedfile",0);
1855 xunlink(path_flushing, "old flushing file");
1857 close_input_file(flushing_input_file);
1858 free(flushing_input_file);
1859 flushing_input_file= 0;
1861 if (sms==sm_SEPARATED) {
1862 notice("flush complete");
1863 SMS(NORMAL, 0, "flush complete");
1864 } else if (sms==sm_DROPPING) {
1865 SMS(DROPPED, 0, "old flush complete");
1866 search_backlog_file();
1867 notice("feed dropped, but will continue until backlog is finished");
1871 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
1873 assert(!inputfile_is_done(main_input_file));
1874 statemc_check_flushing_done();
1875 statemc_check_backlog_done();
1876 return OOP_CONTINUE;
1879 static void queue_check_input_done(void) {
1880 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
1883 static void statemc_setstate(StateMachineState newsms, int periods,
1884 const char *forlog, const char *why) {
1886 sm_period_counter= periods;
1888 const char *xtra= "";
1890 case sm_FLUSHING: sm_FLUSHFAILED:
1891 if (!main_input_file) xtra= "-ABSENT";
1893 case sm_SEPARATED: case sm_DROPPING:
1894 xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
1900 info("%s%s[%d] %s",forlog,xtra,periods,why);
1902 info("%s%s %s",forlog,xtra,why);
1906 /*---------- defer and backlog files ----------*/
1908 static void open_defer(void) {
1913 defer= fopen(path_defer, "a+");
1914 if (!defer) sysfatal("could not open defer file %s", path_defer);
1916 /* truncate away any half-written records */
1918 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1920 if (stab.st_size > LONG_MAX)
1921 die("defer file %s size is far too large", path_defer);
1926 long orgsize= stab.st_size;
1927 long truncto= stab.st_size;
1929 if (!truncto) break; /* was only (if anything) one half-truncated record */
1930 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1931 sysdie("seek in defer file %s while truncating partial", path_defer);
1936 sysdie("failed read from defer file %s", path_defer);
1938 die("defer file %s shrank while we were checking it!", path_defer);
1944 if (stab.st_size != truncto) {
1945 warn("truncating half-record at end of defer file %s -"
1946 " shrinking by %ld bytes from %ld to %ld",
1947 path_defer, orgsize - truncto, orgsize, truncto);
1950 sysfatal("could not flush defer file %s", path_defer);
1951 if (ftruncate(fileno(defer), truncto))
1952 sysdie("could not truncate defer file %s", path_defer);
1955 info("continuing existing defer file %s (%ld bytes)",
1956 path_defer, orgsize);
1958 if (fseek(defer, truncto, SEEK_SET))
1959 sysdie("could not seek to new end of defer file %s", path_defer);
1962 static void close_defer(void) {
1966 xfstat(fileno(defer), &stab, "defer file");
1968 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1971 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1972 (unsigned long)now.tv_sec,
1973 (unsigned long)stab.st_ino);
1974 if (link(path_defer, path_backlog))
1975 sysfatal("could not install defer file %s as backlog file %s",
1976 path_defer, backlog);
1977 if (unlink(path_defer))
1978 sysdie("could not unlink old defer link %s to backlog file %s",
1979 path_defer, backlog);
1981 if (until_backlog_nextscan < 0 ||
1982 until_backlog_nextscan > backlog_retry_minperiods + 1)
1983 until_backlog_nextscan= backlog_retry_minperiods + 1;
1986 static void poll_backlog_file(void) {
1987 if (until_backlog_nextscan < 0) return;
1988 if (until_backlog_nextscan-- > 0) return;
1989 search_backlog_file();
1992 static void search_backlog_file(void) {
1993 /* returns non-0 iff there are any backlog files */
1998 const char *oldest_path=0;
1999 time_t oldest_mtime, now;
2001 if (backlog_input_file) return 3;
2005 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2009 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2011 die("out of memory expanding backlog pattern %s", globpat_backlog);
2013 for (i=0; i<gl.gl_pathc; i++) {
2014 const char *path= gl.gl_pathv[i];
2016 if (strchr(path,'#') || strchr(path,'~')) {
2017 debug("backlog file search skipping %s", path);
2020 r= stat(path, &stab);
2022 syswarn("failed to stat backlog file %s", path);
2025 if (!S_ISREG(stab.st_mode)) {
2026 warn("backlog file %s is not a plain file (or link to one)", path);
2029 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2031 oldest_mtime= stab.st_mtime;
2034 case GLOB_NOMATCH: /* fall through */
2037 sysdie("glob expansion of backlog pattern %s gave unexpected"
2038 " nonzero (error?) return value %d", globpat_backlog, r);
2044 debug("backlog scan: none");
2046 if (sms==sm_DROPPED) {
2047 notice("feed dropped and our work is complete");
2048 xunlink(path_lock, "lockfile for old feed");
2051 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2055 now= time(); if (now==-1) sysdie("time(2) failed");
2056 double age= difftime(now, oldest_mtime);
2057 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
2059 if (age_deficiency <= 0) {
2060 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2061 age, age_deficiency, oldest_path);
2063 backlog_input_file= open_input_file(oldest_path);
2064 if (!backlog_input_file) {
2065 warn("backlog file %s vanished as we opened it", backlog_input_file);
2068 inputfile_tailing_start(backlog_input_file);
2069 until_backlog_nextscan= -1;
2073 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
2075 if (backlog_spontaneous_rescan_periods >= 0 &&
2076 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2077 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2079 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2080 age, age_deficiency, until_backlog_nextscan, oldest_path);
2084 /*========== flushing the feed ==========*/
2086 static pid_t inndcomm_child;
2088 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2089 assert(inndcomm_child);
2090 int status= xwaitpid(&inndcomm_child, "inndcomm");
2091 loop->cancel_fd(fd);
2094 assert(!flushing_input_file);
2096 if (WIFEXITED(status)) {
2097 switch (WEXITSTATUS(status)) {
2099 case INNDCOMMCHILD_ESTATUS_FAIL:
2102 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2103 warn("feed has been dropped by innd, finishing up");
2104 flushing_input_file= main_input_file;
2105 tailing_queue_readable(flushing_input_file);
2106 /* we probably previously returned EAGAIN from our fake read method
2107 * when in fact we were at EOF, so signal another readable event
2108 * so we actually see the EOF */
2112 if (flushing_input_file) {
2113 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2116 SMS(DROPPED, 0, "feed dropped by innd");
2117 search_backlog_file();
2119 return OOP_CONTINUE;
2123 flushing_input_file= main_input_file;
2124 tailing_queue_readable(flushing_input_file);
2126 main_input_file= open_input_file(feedfile);
2127 if (!main_input_file)
2128 die("flush succeeded but feedfile %s does not exist!", feedfile);
2130 if (flushing_input_file) {
2131 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2134 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2136 return OOP_CONTINUE;
2139 goto unexpected_exitstatus;
2142 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2143 warn("flush timed out trying to talk to innd");
2146 unexpected_exitstatus:
2147 report_child_status("inndcomm child", status);
2151 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2154 static void inndcommfail(const char *what) {
2155 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2156 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2159 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2162 notice("flushing %s",why);
2164 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2165 assert(!inndcomm_child);
2167 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2169 inndcomm_child= xfork();
2171 if (!inndcomm_child) {
2172 static char flushargv[2]= { sitename, 0 };
2177 alarm(inndcomm_flush_timeout);
2178 r= ICCopen(); if (r) inndcommfail("connect");
2179 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2180 if (!r) exit(0); /* yay! */
2182 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2183 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2184 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2188 int sentinel_fd= pipefds[0];
2189 on_fd_read_except(sentinel_fd, inndcomm_event);
2191 SMS(FLUSHING, 0, why);
2194 /*========== main program ==========*/
2196 static void postfork_inputfile(InputFile *ipf) {
2198 assert(ipf->fd >= 0);
2203 static void postfork_stdio(FILE *f) {
2204 /* we have no stdio streams that are buffered long-term */
2208 static void postfork(const char *what) {
2209 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2210 sysdie("%s child: failed to reset SIGPIPE");
2212 postfork_inputfile(main_input_file);
2213 postfork_inputfile(flushing_input_file);
2216 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2219 postfork_stdio(defer);
2222 #define EVERY(what, interval, body) \
2223 static const struct timeval what##_timeout = { 5, 0 }; \
2224 static void what##_schedule(void); \
2225 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2227 what##_schedule(); \
2229 static void what##_schedule(void) { \
2230 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2233 EVERY(filepoll, {5,0}, {
2234 if (main_input_file && main_input_file->readable_callback)
2235 filemon_callback(main_input_file);
2238 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s" \
2239 #define DEBUG_IPF(sh) \
2240 wh##_input_file, debug_ipf_path(wh##_input_file), \
2241 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2242 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2243 static const char *debug_ipf_path(InputFile *ipf) {
2244 char *slash= strrchr(ipf->path,'/');
2245 return slash ? slash+1 : ipf->path;
2248 EVERY(period, {PERIOD_SECONDS,0}, {
2250 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2251 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_FMT(flushing)
2252 " children connecting=%ld inndcomm_child"
2254 sms_names[sms], sm_period_counter,
2255 queue.count, conns.count, until_connect,
2256 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2257 (long)connecting_child, (long)inndcomm_child
2260 if (until_connect) until_connect--;
2262 poll_backlog_file();
2263 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2264 statemc_period_poll();
2265 check_master_queue();
2269 /*========== option parsing ==========*/
2272 of_seconds= 001000u;
2273 of_boolean= 002000u;
2276 typedef struct Option Option;
2277 typedef void OptionParser(const Option*, const char *val);
2287 void op_integer(const Option *o, const char *val) {
2290 unsigned long ul= strtoul(val,&ep,10);
2291 if (*ep || ep==val || errno || ul>INT_MAX)
2292 badusage("bad integer value for %s",o->long);
2293 int *store= o->store;
2297 void op_double(const Option *o, const char *val) {
2298 int *store= o->store;
2301 *store= strtod(val, &ep);
2302 if (*ep || ep==val || errno)
2303 badusage("bad floating point value for %s",o->long);
2306 void op_string(const Option *o, const char *val) {
2307 char **store= o->store;
2312 void op_seconds(const Option *o, const char *val) {
2313 int *store= o->store;
2316 double v= strtod(val,&ep);
2317 if (ep==val) badusage("bad time/duration value for %s",o->long);
2319 if (!*ep || !strcmp(ep,"s")) unit= 1;
2320 else if (!strcmp(ep,"m")) unit= 60;
2321 else if (!strcmp(ep,"h")) unit= 3600;
2322 else if (!strcmp(ep,"d")) unit= 86400;
2323 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2327 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2331 void op_periods_rndup(const Option *o, const char *val) {
2332 int *store= o->store;
2334 *store += PERIOD_SECONDS-1;
2335 *store /= PERIOD_SECONDS;
2338 void op_periods_booltrue(const Option *o, const char *val) {
2339 int *store= o->store;
2342 void op_periods_boolfalse(const Option *o, const char *val) {
2343 int *store= o->store;
2347 static const Option options[]= {
2348 {'f',"feedfile", &feedfile, op_string },
2349 {'q',"quiet-multiple", &quiet_multiple, op_booltrue, 1 },
2351 { 0, "max-connections", &max_connections op_integer },
2352 { 0, "max-queue-per-conn", &max_queue_per_conn op_integer },
2355 { 0, "streaming", &try_stream, op_booltrue, 1 },
2356 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2357 {'P',"port", &port op_integer },
2358 { 0, "inndconf", &inndconffile, op_string },
2359 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2360 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2362 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2363 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2365 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2366 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2367 { 0, "connection-timeout", &connection_timeout, op_seconds },
2368 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2371 int main(int argc, char **argv) {
2377 if (*arg != '-') break;
2378 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2380 while ((a= *++arg)) {
2384 char *equals= strchr(arg,'=');
2385 int len= equals ? (equals - arg) : strlen(arg);
2386 for (o=options; o->long; o++)
2387 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2389 badusage("unknown long option --%s",arg);
2392 if (equals) badusage("option --%s does not take a value",o->long);
2394 } else if (equals) {
2398 if (!arg) badusage("option --%s needs a value",o->long);
2401 break; /* eaten the whole argument now */
2403 for (o=options; o->long; o++)
2406 badusage("unknown short option -%c",a);
2413 if (!arg) badusage("option -%c needs a value",o->short);
2416 break; /* eaten the whole argument now */
2421 if (!arg) badusage("need site name argument");
2427 if (*++argv) badusage("too many non-option arguments");
2429 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2430 badusage("nocheck threshold percentage must be between 0..100");
2431 nocheck_thresh= nocheck_thresh_pct * 0.01;
2433 if (nocheck_decay_articles < 0.1)
2434 badusage("nocheck decay articles must be at least 0.1");
2435 nocheck_decay= 1 - 1/nocheck_decay_articles;
2438 pathoutgoing= innconf->pathoutgoing;
2439 innconf_read(inndconffile);
2442 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2443 else if (!feedfile[0])
2444 badusage("feed filename must be nonempty");
2445 else if (feedfile[strlen(feedfile)-1]=='/')
2446 feedfile= xasprintf("%s%s",feedfile,sitename);
2448 const char *feedfile_forbidden= "?*[~#";
2450 while ((c= *feedfile_forbidden++))
2451 if (strchr(feedfile, c))
2452 badusage("feed filename may not contain metacharacter %c",c);
2454 loop= oop_sys_new();
2455 if (!loop) sysdie("could not create liboop event loop");
2457 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2458 sysdie("could not ignore SIGPIPE");
2460 if (become_daemon) {
2461 for (i=3; i<255; i++)
2462 /* do this now before we open syslog, etc. */
2464 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2466 int null= open("/dev/null",O_RDWR);
2467 if (null<0) sysdie("failed to open /dev/null");
2473 pid_t child1= xfork("daemonise first fork");
2474 if (child1) _exit(0);
2476 pid_t sid= setsid();
2477 if (sid != child1) sysdie("setsid failed");
2479 pid_t child2= xfork("daemonise second fork");
2480 if (child2) _exit(0);
2485 if (!filemon_init()) {
2486 warn("no file monitoring available, polling");
2487 filepoll_schedule();