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 ConnList *conn_determine_right_list(Conn *conn);
260 static void conn_assign_one_article(ConnList *connlist, Conn **last_assigned);
261 static void statemc_setstate(StateMachineState newsms, int periods,
262 const char *forlog, const char *why);
263 static void check_master_queue(void);
265 static void postfork(const char *what);
266 static void postfork_inputfile(InputFile *ipf);
268 /*----- configuration options -----*/
270 static char *sitename, *feedfile;
271 static const char *remote_host;
272 static int quiet_multiple=0, become_daemon=1;
274 static int max_connections=10, max_queue_per_conn=200;
276 static int connection_setup_timeout=200, port=119, try_stream=1;
277 static int inndcomm_flush_timeout=100;
278 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
279 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
280 static const char *inndconffile;
282 static double accept_proportion;
283 static double nocheck_thresh_pct= 95.0;
284 static double nocheck_thresh; /* computed in main from _pct */
285 static double nocheck_decay_articles= 100; /* converted to _decay */
286 static double nocheck_decay; /* computed in main from _articles */
287 static int nocheck, nocheck_reported;
290 /*----- statistics -----*/
292 typedef enum { /* in queue in conn->sent */
293 art_Unchecked, /* not checked, not sent checking */
294 art_Wanted, /* checked, wanted sent body as requested */
295 art_Unsolicited, /* - sent body without check */
299 #define RESULT_COUNTS(RCS,RCN) \
307 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
308 #define RCI_TRIPLE_VALS_BASE(counts,x) \
309 , counts[art_Unchecked] x \
310 + counts[art_Wanted] x \
311 + counts[art_Unsolicited] x, \
312 counts[art_Unchecked] x \
313 , counts[art_Wanted] x \
314 , counts[art_Unsolicited] x
317 #define RC_INDEX(x) RCI_##x,
318 RESULT_COUNTS(RC_INDEX, RC_INDEX)
323 /*----- transmission buffers -----*/
328 xk_Malloc, xk_Const, xk_Artdata
340 /*----- core operational data structure types -----*/
343 /* This is also an instance of struct oop_readable */
344 struct oop_readable readable; /* first */
345 oop_readable_call *readable_callback;
346 void *readable_callback_user;
349 struct Filemon_Perfile *filemon;
352 long inprogress; /* no. of articles read but not processed */
355 int counts[art_MaxState][RCI_max];
370 #define SMS_LIST(X) \
378 enum StateMachineState {
379 #define SMS_DEF_ENUM(s) sm_##s,
380 SMS_LIST(SMS_DEF_ENUM)
383 static const char *sms_names[]= {
384 #define SMS_DEF_NAME(s) #s ,
385 SMS_LIST(SMS_DEF_NAME)
391 int fd, max_queue, stream;
392 ArticleList queue; /* not yet told peer, or CHECK said send it */
393 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
394 struct iovec xmit[CONNIOVS];
395 XmitDetails xmitd[CONNIOVS];
400 /*----- operational variables -----*/
402 static oop_source *loop;
404 static int until_connect;
405 static ConnList conns;
406 static ArticleList queue;
408 static char *path_lock, *path_flushing, *path_defer;
410 #define SMS(newstate, periods, why) \
411 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
413 static StateMachineState sms;
415 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
416 static int sm_period_counter;
419 /*========== logging ==========*/
421 static void logcore(int sysloglevel, const char *fmt, ...)
422 __attribute__((__format__(printf,2,3)));
423 static void logcore(int sysloglevel, const char *fmt, ...) {
427 vsyslog(sysloglevel,fmt,al);
429 vfprintf(stderr,fmt,al);
435 static void logv(int sysloglevel, const char *pfx, int errnoval,
436 int exitstatus, const char *fmt, va_list al)
437 __attribute__((__format__(printf,5,0)));
438 static void logv(int sysloglevel, const char *pfx, int errnoval,
439 int exitstatus, const char *fmt, va_list al) {
440 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
441 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
442 msgbuf[sizeof(msgbuf)-1]= 0;
444 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
445 sysloglevel= LOG_ERR; /* run by wrong user, probably */
447 logcore(sysloglevel, "<%s>%s: %s%s%s",
448 sitename, pfx, msgbuf,
449 errnoval>=0 ? ": " : "",
450 errnoval>=0 ? strerror(errnoval) : "");
453 #define logwrap(fn, pfx, sysloglevel, err, estatus) \
454 static void fn(const char *fmt, ...) \
455 __attribute__((__format__(printf,1,2))); \
456 static void fn(const char *fmt, ...) { \
459 logv(sysloglevel, pfx, err, estatus, fmt, al); \
462 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
463 logwrap(die, " critical", LOG_CRIT, -1, 16);
465 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
466 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
468 logwrap(syswarn, " warning", LOG_WARNING, errno, 0);
469 logwrap(warn, " warning", LOG_WARNING, -1, 0);
471 logwrap(notice, "", LOG_NOTICE, -1, 0);
472 logwrap(info, " info", LOG_INFO, -1, 0);
473 logwrap(debug, " debug", LOG_DEBUG, -1, 0);
476 /*========== utility functions etc. ==========*/
478 static char *xvasprintf(const char *fmt, va_list al)
479 __attribute__((__format__(printf,1,0)));
480 static char *xvasprintf(const char *fmt, va_list al) {
482 int rc= vasprintf(&str,fmt,al);
483 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
486 static char *xasprintf(const char *fmt, ...)
487 __attribute__((__format__(printf,1,2)));
488 static char *xasprintf(const char *fmt, ...) {
491 char *str= xvasprintf(fmt,al);
496 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
498 static pid_t xfork(const char *what) {
502 if (child==-1) sysdie("cannot fork for %s",what);
503 if (!child) postfork(what);
504 debug("forked %s %ld", what, (unsigned long)child);
508 static void on_fd_read_except(int fd, oop_call_fd callback) {
509 loop->on_fd(loop, fd, OOP_READ, callback, 0);
510 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
512 static void cancel_fd_read_except(int fd) {
513 loop->cancel_fd(loop, fd, OOP_READ);
514 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
517 static void report_child_status(const char *what, int status) {
518 if (WIFEXITED(status)) {
519 int es= WEXITSTATUS(status);
521 warn("%s: child died with error exit status %d",es);
522 } else if (WIFSIGNALED(status)) {
523 int sig= WTERMSIG(status);
524 const char *sigstr= strsignal(sig);
525 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
527 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
529 warn("%s: child died due to unknown fatal signal %d%s",
530 what, sig, coredump);
532 warn("%s: child died with unknown wait status %d", status);
536 static int xwaitpid(pid_t *pid, const char *what) {
539 int r= kill(*pid, SIGKILL);
540 if (r) sysdie("cannot kill %s child", what);
542 pid_t got= waitpid(*pid, &status, WNOHANG);
543 if (got==-1) sysdie("cannot reap %s child", what);
550 static void xunlink(const char *path, const char *what) {
552 if (r) sysdie("can't unlink %s %s", path, what);
555 static void check_isreg(const struct stat *stab, const char *path,
557 if (!S_ISREG(stab->st_mode))
558 die("%s %s not a plain file (mode 0%lo)",
559 what, path, (unsigned long)stab->st_mode);
562 static void xfstat(int fd, struct stat *stab_r, const char *what) {
563 int r= fstat(fd, stab_r);
564 if (r) sysdie("could not fstat %s", what);
567 static void xfstat_isreg(int fd, struct stat *stab_r,
568 const char *path, const char *what) {
569 xfstat(fd, stab_r, what);
570 check_isreg(stab_r, path, what);
573 static void xlstat_isreg(const char *path, struct stat *stab,
574 int *enoent_r /* 0 means ENOENT is fatal */,
576 int r= lstat(path, stab);
578 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
579 sysdie("could not lstat %s %s", what, path);
581 if (enoent_r) *enoent_r= 0;
582 check_isreg(stab, path, what);
585 static void setnonblock(int fd, int nonblocking) {
586 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
587 if (nonblocking) r |= O_NONBLOCK;
588 else r &= ~O_NONBLOCK;
589 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
592 static int samefile(const struct stat *a, const struct stat *b) {
593 assert(S_ISREG(a->st_mode));
594 assert(S_ISREG(b->st_mode));
595 return (a->st_ino == b->st_ino &&
596 a->st_dev == b->st_dev);
599 static char *sanitise(const char *input) {
600 static char sanibuf[100]; /* returns pointer to this buffer! */
602 const char *p= input;
606 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
608 if (!c) { *q++= '\''; *q=0; break; }
609 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
610 sprintf(q,"\\x%02x",c);
616 /*========== making new connections ==========*/
618 static int connecting_sockets[2]= {-1,-1};
619 static pid_t connecting_child;
621 static void connect_attempt_discard(void) {
622 if (connecting_sockets[0])
623 cancel_fd_read_except(connecting_sockets[0]);
625 perhaps_close(&connecting_sockets[0]);
626 perhaps_close(&connecting_sockets[1]);
628 if (connecting_child) {
629 int r= kill(connecting_child, SIGTERM);
630 if (r) syswarn("failed to kill connecting child");
631 int status= xwaitpid(&connecting_child, "connect");
633 if (!(WIFEXITED(status) ||
634 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
635 report_child_status("connect", status);
639 #define PREP_DECL_MSG_CMSG(msg) \
641 memset(&msg,0,sizeof(msg)); \
642 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
643 msg.msg_control= msg##cbuf; \
644 msg.msg_controllen= sizeof(msg##cbuf);
646 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
649 conn= xmalloc(sizeof(*conn));
650 memset(conn,0,sizeof(*conn));
652 PREP_DECL_MSG_CMSG(msg);
653 struct cmsghdr *h= 0;
654 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
655 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
658 pid_t got= waitpid(connecting_child, &status, WNOHANG);
660 assert(got==connecting_child);
662 if (WIFEXITED(status) &&
663 (WEXITSTATUS(status) != 0 &&
664 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
665 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
666 /* child already reported the problem */
667 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
668 warn("connect: connection attempt timed out");
669 } else if (!WIFEXITED(status)) {
670 report_child_status("connect", status);
671 /* that's probably the root cause then */
674 /* child is still running apparently, report the socket problem */
676 syswarn("connect: read from child socket failed");
677 else if (e == OOP_EXCEPTION)
678 warn("connect: unexpected exception on child socket");
680 warn("connect: unexpected EOF on child socket");
685 #define CHK(field, val) \
686 if (h->cmsg_##field != val) { \
687 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
690 CHK(level, SOL_SOCKET);
691 CHK(type, SCM_RIGHTS);
692 CHK(len, CMSG_LEN(sizeof(conn->fd)));
695 if (CMSG_NXTHDR(&msg,h)) { die("connect: child sent many cmsgs"); goto x; }
697 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
700 pid_t got= waitpid(connecting_child, &status, 0);
701 if (got==-1) sysdie("connect: real wait for child");
702 assert(got == connecting_child);
705 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
706 int es= WEXITSTATUS(status);
708 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
709 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
711 fatal("connect: child gave unexpected exit status %d", es);
715 setnonblock(conn->fd, 1);
716 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
717 LIST_ADDHEAD(conns, conn);
718 notice("#%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
719 connect_attempt_discard();
720 check_master_queue();
725 perhaps_close(&conn->fd);
728 connect_attempt_discard();
731 static void connect_start(void) {
732 assert(!connecting_sockets[0]);
733 assert(!connecting_sockets[1]);
734 assert(!connecting_child);
736 notice("starting connection attempt");
738 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
739 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
741 connecting_child= xfork("connection");
743 if (!connecting_child) {
744 FILE *cn_from, *cn_to;
745 char buf[NNTP_STRLEN+100];
746 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
748 r= close(connecting_sockets[0]);
749 if (r) sysdie("connect: close parent socket in child");
751 alarm(connection_setup_timeout);
752 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
753 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
754 else sysfatal("connect: connection attempt failed");
756 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
757 sysfatal("connect: authentication failed");
759 if (fputs("MODE STREAM\r\n", cn_to) ||
761 sysfatal("connect: could not send MODE STREAM");
762 buf[sizeof(buf)-1]= 0;
763 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
765 sysfatal("connect: could not read response to MODE STREAM");
767 fatal("connect: connection close in response to MODE STREAM");
772 fatal("connect: response to MODE STREAM is too long: %.100s...",
773 remote_host, sanitise(buf));
774 l--; if (l>0 && buf[l-1]=='\r') l--;
777 int rcode= strtoul(buf,&ep,10);
779 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
783 exitstatus= CONNCHILD_ESTATUS_STREAM;
789 warn("connect: unexpected response to MODE STREAM: %.50s",
795 int fd= fileno(cn_from);
797 PREP_DECL_MSG_CMSG(msg);
798 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
799 cmsg->cmsg_level= SOL_SOCKET;
800 cmsg->cmsg_type= SCM_RIGHTS;
801 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
802 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
804 msg.msg_controllen= cmsg->cmsg_len;
805 r= sendmsg(connecting_sockets[1], &msg, 0);
806 if (r) sysdie("sendmsg failed for new connection");
811 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
812 if (r) sysdie("connect: close child socket in parent");
814 on_fd_read_except(connecting_sockets[0], connchild_event);
818 connect_attempt_discard();
822 /*========== overall control of article flow ==========*/
824 static int conn_owned_articles(Conn *conn) {
825 return conn->sent.count + conn->queue.count;
828 static void check_master_queue(void) {
832 Conn *last_assigned=0;
835 conn_assign_one_article(&working, &last_assigned);
836 } else if (idle.head) {
837 conn_assign_one_article(&idle, &last_assigned);
838 } else if (full.count < max_connections &&
839 !connecting_child && !until_connect) {
840 until_connect= reconnect_delay_periods;
846 conn_check_work(last_assigned);
849 static void conn_assign_one_article(ConnList *connlist, Conn **last_assigned) {
850 Conn *conn= connlist->head;
852 LIST_REMOVE(*connlist, conn);
853 Article *art= LIST_REMHEAD(queue);
854 LIST_ADDTAIL(conn->queue, art);
855 LIST_ADDTAIL(*conn_determine_right_list(conn), conn);
857 /* This slightly odd arrangement is so that we call conn_check_work
858 * once after filling the queue for a new connection in
859 * check_master_queue, rather than for each article. */
860 if (conn != *last_assigned && *last_assigned)
861 conn_check_work(*last_assigned);
862 *last_assigned= conn;
865 static ConnList *conn_determine_right_list(Conn *conn) {
866 int inqueue= conn_owned_articles(conn);
867 assert(inqueue <= max_queue_per_conn);
868 if (inqueue == 0) return &idle;
869 if (inqueue == conn->max_queue) return &full;
873 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
878 static void conn_check_work(Conn *conn) {
881 conn_make_some_xmits(conn);
883 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
887 void *rp= conn_write_some_xmits(conn);
888 if (rp==OOP_CONTINUE) {
889 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
891 } else if (rp==OOP_HALT) {
894 /* transmitted everything */
901 static void vconnfail(Conn *conn, const char *fmt, va_list al)
902 __attribute__((__format__(printf,2,0)));
904 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
905 int requeue[art_MaxState];
908 while ((art= LIST_REMHEAD(conn->queue))) LIST_ADDTAIL(queue, art);
909 while ((art= LIST_REMHEAD(conn->sent))) {
910 requeue[art->state]++;
911 if (art->state==art_Unsolicited) art->state= art_Unchecked;
912 LIST_ADDTAIL(queue,art);
917 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
920 char *m= xvasprintf(fmt,al);
921 warn("#%d connection failed, requeueing " RCI_TRIPLE_FMT_BASE ": %s",
922 conn->fd, RCI_TRIPLE_FMT_VALS(requeue, /*nothing*/), m);
926 fixme remove conn from the appropriate list;
929 until_connect= reconnect_delay_periods;
930 check_master_queue();
933 static void connfail(Connection *conn, const char *fmt, ...)
934 __attribute__((__format__(printf,2,3)));
935 static void connfail(Connection *conn, const char *fmt, ...) {
942 /*========== article transmission ==========*/
944 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
945 XmitKind kind) { /* caller must then fill in details */
946 struct iovec *v= &conn->xmit[conn->xmitu];
947 XmitDetails *d= &conn->xmitd[conn->xmitu++];
954 static void xmit_noalloc(Conn *conn, const char *data, int len) {
955 xmit_core(conn,data,len, xk_Const);
957 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
959 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
960 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
964 static void xmit_free(XmitDetails *d) {
966 case xk_Malloc: free(d->info.malloc_tofree); break;
967 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
968 case xk_Const: break;
973 static void *conn_write_some_xmits(Conn *conn) {
975 * 0: nothing more to write, no need to call us again
976 * OOP_CONTINUE: more to write but fd not writeable
977 * OOP_HALT: disaster, have destroyed conn
980 int count= conn->xmitu;
981 if (!count) return 0;
983 if (count > IOV_MAX) count= IOV_MAX;
984 ssize_t rs= writev(conn->fd, conn->xmit, count);
986 if (errno == EAGAIN) return OOP_CONTINUE;
987 connfail(conn, "write failed: %s", strerror(errno));
992 for (done=0; rs && done<xmitu; done++) {
993 struct iovec *vp= &conn->xmit[done];
994 XmitDetails *dp= &conn->xmitd[done];
995 if (rs > vp->iov_len) {
1003 int newu= conn->xmitu - done;
1004 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1005 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1010 static void conn_make_some_xmits(Conn *conn) {
1012 if (conn->xmitu+5 > CONNIOVS)
1015 Article *art= LIST_REMHEAD(queue);
1018 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1019 /* actually send it */
1021 ARTHANDLE *artdata= SMretrieve();
1025 XMIT_LITERAL("TAKETHIS ");
1026 xmit_noalloc(conn, art->mid, art->midlen);
1027 XMIT_LITERAL("\r\n");
1028 xmit_artbody(conn, artdata);
1031 /* we got 235 from IHAVE */
1033 xmit_artbody(conn, artdata);
1035 XMIT_LITERAL(".\r\n");
1040 art->state == art_Unchecked ? art_Unsolicited :
1041 art->state == art_Wanted ? art_Wanted :
1043 art->ipf->counts[art->state].sent++;
1044 LIST_ADDTAIL(conn->sent, art);
1050 XMIT_LITERAL("IHAVE ");
1052 XMIT_LITERAL("CHECK ");
1053 xmit_noalloc(art->mid, art->midlen);
1054 XMIT_LITERAL("\r\n");
1056 assert(art->state == art_Unchecked);
1057 art->ipf->counts[art->state].sent++;
1058 LIST_ADDTAIL(conn->sent, art);
1064 /*========== handling responses from peer ==========*/
1066 static const oop_rd_style peer_rd_style= {
1067 OOP_RD_DELIM_STRIP, '\n',
1069 OOP_RD_SHORTREC_FORBID
1072 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1073 const char *errmsg, int errnoval,
1074 const char *data, size_t recsz, void *conn_v) {
1076 connfail(conn, "error receiving from peer: %s", errmsg);
1077 return OOP_CONTINUE;
1080 static Article *article_reply_check(Connection *conn, const char *response,
1081 int code_indicates_streaming,
1083 /* 1:yes, -1:no, 0:dontcare */,
1084 const char *sanitised_response) {
1085 Article *art= conn->sent.head;
1089 "peer gave unexpected response when no commands outstanding: %s",
1090 sanitised_response);
1094 if (code_indicates_streaming) {
1095 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1096 if (!conn->stream) {
1097 connfail("peer gave streaming response code "
1098 " to IHAVE or subsequent body: %s", sanitised_response);
1101 const char *got_mid= response+4;
1102 int got_midlen= strcspn(got_mid, " \n\r");
1103 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1104 connfail("peer gave streaming response with syntactically invalid"
1105 " messageid: %s", sanitised_response);
1108 if (got_midlen != art->midlen ||
1109 memcmp(got_mid, art->messageid, got_midlen)) {
1110 connfail("peer gave streaming response code to wrong article -"
1111 " probable synchronisation problem; we offered: %s;"
1113 art->messageid, sanitised_response);
1118 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
1119 sanitised_response);
1124 if (must_have_sent>0 && art->state < art_Wanted) {
1125 connfail("peer says article accepted but we had not sent the body: %s",
1126 sanitised_response);
1129 if (must_have_sent<0 && art->state >= art_Wanted) {
1130 connfail("peer says please sent the article but we just did: %s",
1131 sanitised_response);
1135 Article *art_again= LIST_REMHEAD(conn->sent);
1136 assert(art_again == art);
1140 static void update_nocheck(int accepted) {
1141 accept_proportion *= accept_decay;
1142 accept_proportion += accepted;
1143 int new_nocheck= accept_proportion >= nocheck_thresh;
1144 if (new_nocheck && !nocheck_reported) {
1145 notice("entering nocheck mode for the first time");
1146 nocheck_reported= 1;
1147 } else if (new_nocheck != nocheck) {
1148 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1150 nocheck= new_nocheck;
1153 static void article_done(Connection *conn, Article *art, int whichcount) {
1154 art->ipf->counts[art->state][whichcount]++;
1155 if (whichcount == RC_accepted) update_nocheck(1);
1156 else if (whichcount == RC_unwanted) update_nocheck(0);
1158 InputFile *ipf= art->ipf;
1159 while (art->blanklen) {
1160 static const char spaces[]=
1165 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1166 int r= pwrite(ipf->fd, spaces, w, art->offset);
1168 if (errno==EINTR) continue;
1169 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1170 art->messageid, art->blanklen, art->offset, ipf->path);
1172 assert(r>=0 && r<=w);
1178 assert(ipf->inprogress >= 0);
1180 if (!ipf->inprogress && ipf != main_input_file)
1181 queue_check_input_done();
1186 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1187 const char *errmsg, int errnoval,
1188 const char *data, size_t recsz, void *conn_v) {
1191 if (ev == OOP_RD_EOF) {
1192 connfail(conn, "unexpected EOF from peer");
1193 return OOP_CONTINUE;
1195 assert(ev == OOP_RD_OK);
1197 char *sani= sanitise(data, recsz);
1200 unsigned long code= strtoul(data, &ep, 10);
1201 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1202 connfail(conn, "badly formatted response from peer: %s", sani);
1203 return OOP_CONTINUE;
1206 if (conn->quitting) {
1208 connfail(conn, "peer gave failure response to QUIT: %s", sani);
1209 return OOP_CONTINUE;
1217 #define GET_ARTICLE(musthavesent) \
1218 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1219 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1221 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1222 code_streaming= (streaming) \
1223 GET_ARTICLE(musthavesent); \
1224 article_done(conn, art, RC_##how); break;
1226 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1228 int code_streaming= 0;
1232 case 400: PEERBADMSG("peer stopped accepting articles");
1233 case 503: PEERBADMSG("peer timed us out");
1234 default: PEERBADMSG("peer sent unexpected message");
1236 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1237 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1239 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1240 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1242 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1243 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1245 case 238: /* CHECK says send it */
1247 case 335: /* IHAVE says send it */
1249 assert(art->state == art_Unchecked);
1250 art->ipf->counts[art->state].accepted++;
1251 art->state= art_Wanted;
1252 LIST_ADDTAIL(conn->queue);
1255 case 431: /* CHECK or TAKETHIS says try later */
1257 case 436: /* IHAVE says try later */
1260 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1262 sysfatal("write to defer file %s",path_defer);
1263 article_done(conn, art, RC_deferred);
1268 check_check_work(conn);
1269 return OOP_CONTINUE;
1273 /*========== monitoring of input files ==========*/
1275 static void feedfile_eof(InputFile *ipf) {
1276 assert(ipf != main_input_file); /* promised by tailing_try_read */
1278 inputfile_tailing_stop(ipf);
1279 assert(ipf->fd >= 0);
1280 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1283 if (ipf == flushing_input_file) {
1284 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1285 if (main_input_file) inputfile_tailing_start(main_input_file);
1286 statemc_check_flushing_done();
1287 } else if (ipf == backlog_input_file) {
1288 statemc_check_backlog_done();
1290 abort(); /* supposed to wait rather than get EOF on main input file */
1294 static InputFile *open_input_file(const char *path) {
1295 int fd= open(path, O_RDONLY);
1297 if (errno==ENOENT) return 0;
1298 sysfatal("unable to open input file %s", path);
1301 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1302 memset(ipf,0,sizeof(*ipf));
1304 ipf->readable.on_readable= tailing_on_readable;
1305 ipf->readable.on_cancel= tailing_on_cancel;
1306 ipf->readable.try_read= tailing_try_read;
1309 strcpy(ipf->path, path);
1314 static void close_input_file(InputFile *ipf) {
1315 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1316 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1317 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1318 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1321 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1325 /*---------- dealing with articles read in the input file ----------*/
1327 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1328 oop_rd_event ev, const char *errmsg,
1330 const char *data, size_t recsz,
1332 InputFile *ipf= ipf_v;
1334 char tokentextbuf[sizeof(TOKEN)*2+3];
1336 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1338 if (data[0] && data[0]!=' ') {
1339 char *space= strchr(data,' ');
1340 int tokenlen= space-data;
1341 int midlen= (int)recsz-tokenlen-1;
1342 if (midlen < 0) goto bad_data;
1344 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1345 memcpy(tokentextbuf, data, tokenlen);
1346 tokentextbuf[tokenlen]= 0;
1347 if (!IsToken(tokentextbuf)) goto bad_data;
1349 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1350 art->offset= ipf->offset;
1351 art->blanklen= recsz;
1352 art->midlen= midlen;
1353 art->state= art_Unchecked;
1354 art->ipf= ipf; ipf->inprogress++;
1355 art->token= TextToToken(tokentextbuf);
1356 strcpy(art->messageid, space+1);
1357 LIST_ADDTAIL(queue, art);
1359 ipf->offset += recsz + 1;
1361 if (sms==sm_NORMAL && ipf==main_input_file &&
1362 ipf->offset >= flush_threshold)
1363 statemc_start_flush("feed file size");
1365 check_master_queue();
1368 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1369 assert(sms == sm_NORMAL);
1371 debug("starting flush (%s) (%lu >= %lu) (%d)",
1373 (unsigned long)ipf->offset, (unsigned long)flush_threshold,
1376 int r= link(feedfile, duct_path);
1377 if (r) sysdie("link feedfile %s to flushing file %s", feedfile,
1381 xunlink(feedfile, "old feedfile link");
1384 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1387 /*========== tailing input file ==========*/
1389 static void filemon_start(InputFile *ipf) {
1390 assert(!ipf->filemon);
1392 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1393 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1394 filemon_method_startfile(ipf, ipf->filemon);
1397 static void filemon_stop(InputFile *ipf) {
1398 if (!ipf->filemon) return;
1399 filemon_method_stopfile(ipf, ipf->filemon);
1404 static void filemon_callback(InputFile *ipf) {
1405 ipf->readable_callback(ipf->readable_callback_user);
1408 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1410 InputFile *ipf= user;
1411 return ipf->readable_callback(ipf->readable_callback_user);
1414 static void on_cancel(struct oop_readable *rable) {
1415 InputFile *ipf= (void*)rable;
1417 if (ipf->filemon) filemon_stopfile(ipf);
1418 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1419 ipf->readable_callback= 0;
1422 static void tailing_queue_readable(InputFile *ipf) {
1423 /* lifetime of ipf here is OK because destruction will cause
1424 * on_cancel which will cancel this callback */
1425 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1428 static int tailing_on_readable(struct oop_readable *rable,
1429 oop_readable_call *cb, void *user) {
1430 InputFile *ipf= (void*)rable;
1432 tailing_on_cancel(rable);
1433 ipf->readable_callback= cb;
1434 ipf->readable_callback_user= user;
1435 filemon_startfile(ipf);
1437 tailing_queue_readable(ipf);
1441 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1443 InputFile *ipf= (void*)rable;
1445 ssize_t r= read(ipf->fd, buffer, length);
1447 if (errno==EINTR) continue;
1451 if (ipf==main_input_file) {
1454 } else if (ipf==flushing_input_file) {
1456 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1457 } else if (ipf==backlog_input_file) {
1467 /*---------- filemon implemented with inotify ----------*/
1469 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1470 #define HAVE_FILEMON
1472 #include <linux/inotify.h>
1474 static int filemon_inotify_fd;
1475 static int filemon_inotify_wdmax;
1476 static InputFile **filemon_inotify_wd2ipf;
1478 typedef struct Filemon_Perfile {
1480 } Filemon_Inotify_Perfile;
1482 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1483 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1484 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1486 if (wd >= filemon_inotify_wdmax) {
1488 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1489 sizeof(*filemon_inotify_wd2ipf) * newmax);
1490 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1491 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1492 filemon_inotify_wdmax= newmax;
1495 assert(!filemon_inotify_wd2ipf[wd]);
1496 filemon_inotify_wd2ipf[wd]= ipf;
1498 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1499 ipf, wd, filemon_inotify_wdmax);
1504 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1506 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1507 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1508 if (r) sysdie("inotify_rm_watch");
1509 filemon_inotify_wd2ipf[wd]= 0;
1512 static void *filemon_inotify_readable(oop_source *lp, int fd,
1513 oop_event e, void *u) {
1514 struct inotify_event iev;
1516 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1518 if (errno==EAGAIN) break;
1519 sysdie("read from inotify master");
1520 } else if (r==sizeof(iev)) {
1521 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1523 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1525 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1526 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1527 filemon_callback(ipf);
1529 return OOP_CONTINUE;
1532 static int filemon_method_init(void) {
1533 filemon_inotify_fd= inotify_init();
1534 if (filemon_inotify_fd<0) {
1535 syswarn("could not initialise inotify: inotify_init failed");
1539 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1541 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1545 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1547 /*---------- filemon dummy implementation ----------*/
1549 #if !defined(HAVE_FILEMON)
1551 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1553 static int filemon_method_init(void) { return 0; }
1554 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1555 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1557 #endif /* !HAVE_FILEMON */
1559 /*---------- interface to start and stop an input file ----------*/
1561 static const oop_rd_style feedfile_rdstyle= {
1562 OOP_RD_DELIM_STRIP, '\n',
1564 OOP_RD_SHORTREC_EOF,
1567 static void inputfile_tailing_start(InputFile *ipf) {
1569 ipf->readable->on_readable= tailing_on_readable;
1570 ipf->readable->on_cancel= tailing_on_cancel;
1571 ipf->readable->try_read= tailing_try_read;
1572 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1573 ipf->readable->delete_kill= 0;
1575 ipf->readable_callback= 0;
1576 ipf->readable_callback_user= 0;
1578 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1581 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1582 feedfile_got_article,ipf, feedfile_problem,ipf);
1583 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1586 static void inputfile_tailing_stop(InputFile *ipf) {
1588 oop_rd_cancel(ipf->rd);
1589 oop_rd_delete(ipf->rd);
1591 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1595 /*========== interaction with innd - state machine ==========*/
1597 /* See official state diagram at top of file. We implement
1608 |`---------------------------------------------------.
1610 |`---------------- - - - |
1611 D ENOENT | D EXISTS see OVERALL STATES diagram |
1612 | for full startup logic |
1615 | ============ try to |
1621 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1622 ^ | hardlink F to D |
1625 | | our handle onto F is now onto D |
1628 | |<-------------------<---------------------<---------+
1630 | | spawn inndcomm flush |
1632 | ================== |
1633 | FLUSHING[-ABSENT] |
1635 | main D tail/none |
1636 | ================== |
1638 | | INNDCOMM FLUSH FAILS ^
1639 | |`----------------------->----------. |
1641 | | NO SUCH SITE V |
1642 ^ |`--------------->----. ==================== |
1643 | | \ FLUSHFAILED[-ABSENT] |
1645 | | FLUSH OK \ main D tail/none |
1646 | | open F \ ==================== |
1648 | | \ | TIME TO RETRY |
1649 | |`------->----. ,---<---'\ `----------------'
1650 | | D NONE | | D NONE `----.
1652 | ============= V V ============
1653 | SEPARATED-1 | | DROPPING-1
1654 | flsh->fd>=0 | | flsh->fd>=0
1655 | [Separated] | | [Dropping]
1656 | main F idle | | main none
1657 | old D tail | | old D tail
1658 | ============= | | ============
1660 ^ | EOF ON D | | defer | EOF ON D
1662 | =============== | | ===============
1663 | SEPARATED-2 | | DROPPING-2
1664 | flsh->fd==-1 | V flsh->fd==-1
1665 | [Finishing] | | [Dropping]
1666 | main F tail | `. main none
1667 | old D closed | `. old D closed
1668 | =============== V `. ===============
1670 | | ALL D PROCESSED `. | ALL D PROCESSED
1671 | V install defer as backlog `. | install defer
1672 ^ | close D `. | close D
1673 | | unlink D `. | unlink D
1676 `----------' ==============
1696 static void statemc_init(void) {
1697 struct stat stab, stabf;
1699 path_lock= xasprintf("%s_lock", feedfile);
1700 path_flushing= xasprintf("%s_flushing", feedfile);
1701 path_defer= xasprintf("%s_defer", feedfile);
1702 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1705 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1706 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1709 memset(&fl,0,sizeof(fl));
1711 fl.l_whence= SEEK_SET;
1712 r= fcntl(lockfd, F_SETLK, &fl);
1714 if (errno==EACCES || errno==EAGAIN) {
1715 if (quiet_multiple) exit(0);
1716 fatal("another duct holds the lockfile");
1718 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1721 xfstat_isreg(lockfd, &stabf, "lockfile");
1723 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1725 if (!lock_noent && samefile(&stab, &stabf))
1729 sysdie("could not close stale lockfile %s", path_lock);
1731 debug("startup: locked");
1733 search_backlog_file();
1736 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1738 debug("startup: ductdefer ENOENT");
1740 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1741 switch (stab.st_nlink==1) {
1743 open_defer(); /* so that we will later close it and rename it */
1746 xunlink(path_defer, "stale defer file link"
1747 " (presumably hardlink to backlog file)");
1750 die("defer file %s has unexpected link count %d",
1751 path_defer, stab.st_nlink);
1755 struct stat stab_f, stab_d;
1758 InputFile *file_d= open_input_file(path_flushing);
1759 if (file_d) xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1761 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1763 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1764 debug("startup: F==D => Hardlinked");
1765 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1770 debug("startup: F ENOENT => Moved");
1771 if (file_d) startup_set_input_file(file_d);
1772 spawn_inndcomm_flush("feedfile missing at startup");
1773 /* => Flushing, sms:=FLUSHING */
1776 debug("startup: F!=D => Separated");
1777 startup_set_input_file(file_d);
1778 SMS(SEPARATED, 0, "found both old and current feed files");
1780 debug("startup: F exists, D ENOENT => Normal");
1781 FILE *file_f= open_input_file(feedfile);
1782 if (!file_f) die("feed file vanished during startup");
1783 startup_set_input_file(file_f);
1784 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1789 static void statemc_period_poll(void) {
1790 if (!sm_period_counter) return;
1791 sm_period_counter--;
1792 assert(sm_period_counter>=0);
1794 if (sm_period_counter) return;
1797 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1799 case sm_FLUSHFAILED:
1800 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1807 static void startup_set_input_file(InputFile *f) {
1808 assert(!main_input_file);
1810 inputfile_tailing_start(f);
1813 static int inputfile_is_done(InputFile *ipf) {
1815 if (ipf->inprogress) return 0; /* new article in the meantime */
1816 if (ipf->fd >= 0); return 0; /* not had EOF */
1820 static void notice_processed(InputFile *ipf, const char *what,
1822 #define RCI_NOTHING(x) /* nothing */
1823 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
1824 #define RCI_TRIPLE_VALS(x) RCI_TRIPLE_VALS_BASE(ipf->counts, .x)
1826 info("processed %s%s offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
1827 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
1830 ipf->counts[art_Unchecked].sent + ipf->counts[art_Unsolicited].sent
1831 , ipf->counts[art_Unchecked].sent, ipf->counts[art_Unsolicited].sent,
1832 ipf->counts[art_Wanted].accepted + ipf->counts[art_Unsolicited].accepted
1833 ,ipf->counts[art_Wanted].accepted,ipf->counts[art_Unsolicited].accepted
1834 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
1838 static void statemc_check_backlog_done(void) {
1839 InputFile *ipf= backlog_input_file();
1840 if (!inputfile_is_done(ipf)) return;
1842 const char *slash= strrchr(ipf->path, "/");
1843 const char *leaf= slash ? slash+1 : ipf->path;
1844 const char *under= strchr(slash, "_");
1845 const char *rest= under ? under+1 : leaf;
1846 if (!strncmp(rest,"backlog",7)) rest += 7;
1847 notice_processed(ipf,"backlog:",rest);
1849 close_input_file(ipf);
1850 if (unlink(ipf->path)) {
1851 if (errno != ENOENT)
1852 sysdie("could not unlink processed backlog file %s", ipf->path);
1853 warn("backlog file %s vanished while we were reading it"
1854 " so we couldn't remove it (but it's done now, anyway)",
1858 backlog_input_file= 0;
1859 search_backlog_file();
1863 static void statemc_check_flushing_done(void) {
1864 InputFile *ipf= flushing_input_file;
1865 if (!inputfile_is_done(ipf)) return;
1867 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1869 notice_processed(ipf,"feedfile",0);
1873 xunlink(path_flushing, "old flushing file");
1875 close_input_file(flushing_input_file);
1876 free(flushing_input_file);
1877 flushing_input_file= 0;
1879 if (sms==sm_SEPARATED) {
1880 notice("flush complete");
1881 SMS(NORMAL, 0, "flush complete");
1882 } else if (sms==sm_DROPPING) {
1883 SMS(DROPPED, 0, "old flush complete");
1884 search_backlog_file();
1885 notice("feed dropped, but will continue until backlog is finished");
1889 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
1891 assert(!inputfile_is_done(main_input_file));
1892 statemc_check_flushing_done();
1893 statemc_check_backlog_done();
1894 return OOP_CONTINUE;
1897 static void queue_check_input_done(void) {
1898 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
1901 static void statemc_setstate(StateMachineState newsms, int periods,
1902 const char *forlog, const char *why) {
1904 sm_period_counter= periods;
1906 const char *xtra= "";
1908 case sm_FLUSHING: sm_FLUSHFAILED:
1909 if (!main_input_file) xtra= "-ABSENT";
1911 case sm_SEPARATED: case sm_DROPPING:
1912 xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
1918 info("%s%s[%d] %s",forlog,xtra,periods,why);
1920 info("%s%s %s",forlog,xtra,why);
1924 /*---------- defer and backlog files ----------*/
1926 static void open_defer(void) {
1931 defer= fopen(path_defer, "a+");
1932 if (!defer) sysfatal("could not open defer file %s", path_defer);
1934 /* truncate away any half-written records */
1936 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1938 if (stab.st_size > LONG_MAX)
1939 die("defer file %s size is far too large", path_defer);
1944 long orgsize= stab.st_size;
1945 long truncto= stab.st_size;
1947 if (!truncto) break; /* was only (if anything) one half-truncated record */
1948 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1949 sysdie("seek in defer file %s while truncating partial", path_defer);
1954 sysdie("failed read from defer file %s", path_defer);
1956 die("defer file %s shrank while we were checking it!", path_defer);
1962 if (stab.st_size != truncto) {
1963 warn("truncating half-record at end of defer file %s -"
1964 " shrinking by %ld bytes from %ld to %ld",
1965 path_defer, orgsize - truncto, orgsize, truncto);
1968 sysfatal("could not flush defer file %s", path_defer);
1969 if (ftruncate(fileno(defer), truncto))
1970 sysdie("could not truncate defer file %s", path_defer);
1973 info("continuing existing defer file %s (%ld bytes)",
1974 path_defer, orgsize);
1976 if (fseek(defer, truncto, SEEK_SET))
1977 sysdie("could not seek to new end of defer file %s", path_defer);
1980 static void close_defer(void) {
1984 xfstat(fileno(defer), &stab, "defer file");
1986 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1989 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1990 (unsigned long)now.tv_sec,
1991 (unsigned long)stab.st_ino);
1992 if (link(path_defer, path_backlog))
1993 sysfatal("could not install defer file %s as backlog file %s",
1994 path_defer, backlog);
1995 if (unlink(path_defer))
1996 sysdie("could not unlink old defer link %s to backlog file %s",
1997 path_defer, backlog);
1999 if (until_backlog_nextscan < 0 ||
2000 until_backlog_nextscan > backlog_retry_minperiods + 1)
2001 until_backlog_nextscan= backlog_retry_minperiods + 1;
2004 static void poll_backlog_file(void) {
2005 if (until_backlog_nextscan < 0) return;
2006 if (until_backlog_nextscan-- > 0) return;
2007 search_backlog_file();
2010 static void search_backlog_file(void) {
2011 /* returns non-0 iff there are any backlog files */
2016 const char *oldest_path=0;
2017 time_t oldest_mtime, now;
2019 if (backlog_input_file) return 3;
2023 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2027 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2029 die("out of memory expanding backlog pattern %s", globpat_backlog);
2031 for (i=0; i<gl.gl_pathc; i++) {
2032 const char *path= gl.gl_pathv[i];
2034 if (strchr(path,'#') || strchr(path,'~')) {
2035 debug("backlog file search skipping %s", path);
2038 r= stat(path, &stab);
2040 syswarn("failed to stat backlog file %s", path);
2043 if (!S_ISREG(stab.st_mode)) {
2044 warn("backlog file %s is not a plain file (or link to one)", path);
2047 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2049 oldest_mtime= stab.st_mtime;
2052 case GLOB_NOMATCH: /* fall through */
2055 sysdie("glob expansion of backlog pattern %s gave unexpected"
2056 " nonzero (error?) return value %d", globpat_backlog, r);
2062 debug("backlog scan: none");
2064 if (sms==sm_DROPPED) {
2065 notice("feed dropped and our work is complete");
2066 xunlink(path_lock, "lockfile for old feed");
2069 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2073 now= time(); if (now==-1) sysdie("time(2) failed");
2074 double age= difftime(now, oldest_mtime);
2075 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
2077 if (age_deficiency <= 0) {
2078 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2079 age, age_deficiency, oldest_path);
2081 backlog_input_file= open_input_file(oldest_path);
2082 if (!backlog_input_file) {
2083 warn("backlog file %s vanished as we opened it", backlog_input_file);
2086 inputfile_tailing_start(backlog_input_file);
2087 until_backlog_nextscan= -1;
2091 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
2093 if (backlog_spontaneous_rescan_periods >= 0 &&
2094 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2095 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2097 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2098 age, age_deficiency, until_backlog_nextscan, oldest_path);
2102 /*========== flushing the feed ==========*/
2104 static pid_t inndcomm_child;
2106 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2107 assert(inndcomm_child);
2108 int status= xwaitpid(&inndcomm_child, "inndcomm");
2109 loop->cancel_fd(fd);
2112 assert(!flushing_input_file);
2114 if (WIFEXITED(status)) {
2115 switch (WEXITSTATUS(status)) {
2117 case INNDCOMMCHILD_ESTATUS_FAIL:
2120 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2121 warn("feed has been dropped by innd, finishing up");
2122 flushing_input_file= main_input_file;
2123 tailing_queue_readable(flushing_input_file);
2124 /* we probably previously returned EAGAIN from our fake read method
2125 * when in fact we were at EOF, so signal another readable event
2126 * so we actually see the EOF */
2130 if (flushing_input_file) {
2131 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2134 SMS(DROPPED, 0, "feed dropped by innd");
2135 search_backlog_file();
2137 return OOP_CONTINUE;
2141 flushing_input_file= main_input_file;
2142 tailing_queue_readable(flushing_input_file);
2144 main_input_file= open_input_file(feedfile);
2145 if (!main_input_file)
2146 die("flush succeeded but feedfile %s does not exist!", feedfile);
2148 if (flushing_input_file) {
2149 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2152 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2154 return OOP_CONTINUE;
2157 goto unexpected_exitstatus;
2160 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2161 warn("flush timed out trying to talk to innd");
2164 unexpected_exitstatus:
2165 report_child_status("inndcomm child", status);
2169 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2172 static void inndcommfail(const char *what) {
2173 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2174 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2177 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2180 notice("flushing %s",why);
2182 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2183 assert(!inndcomm_child);
2185 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2187 inndcomm_child= xfork();
2189 if (!inndcomm_child) {
2190 static char flushargv[2]= { sitename, 0 };
2195 alarm(inndcomm_flush_timeout);
2196 r= ICCopen(); if (r) inndcommfail("connect");
2197 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2198 if (!r) exit(0); /* yay! */
2200 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2201 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2202 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2206 int sentinel_fd= pipefds[0];
2207 on_fd_read_except(sentinel_fd, inndcomm_event);
2209 SMS(FLUSHING, 0, why);
2212 /*========== main program ==========*/
2214 static void postfork_inputfile(InputFile *ipf) {
2216 assert(ipf->fd >= 0);
2221 static void postfork_conns(Connection *conn) {
2228 static void postfork_stdio(FILE *f) {
2229 /* we have no stdio streams that are buffered long-term */
2233 static void postfork(const char *what) {
2234 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2235 sysdie("%s child: failed to reset SIGPIPE");
2237 postfork_inputfile(main_input_file);
2238 postfork_inputfile(flushing_input_file);
2239 postfork_conns(idle.head);
2240 postfork_conns(working.head);
2241 postfork_conns(full.head);
2242 postfork_stdio(defer);
2245 #define EVERY(what, interval, body) \
2246 static const struct timeval what##_timeout = { 5, 0 }; \
2247 static void what##_schedule(void); \
2248 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2250 what##_schedule(); \
2252 static void what##_schedule(void) { \
2253 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2256 EVERY(filepoll, {5,0}, {
2257 if (main_input_file && main_input_file->readable_callback)
2258 filemon_callback(main_input_file);
2261 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s" \
2262 #define DEBUG_IPF(sh) \
2263 wh##_input_file, debug_ipf_path(wh##_input_file), \
2264 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2265 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2266 static const char *debug_ipf_path(InputFile *ipf) {
2267 char *slash= strrchr(ipf->path,'/');
2268 return slash ? slash+1 : ipf->path;
2271 EVERY(period, {PERIOD_SECONDS,0}, {
2273 " sms=%s[%d] queue=%d until_connect=%d"
2274 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_FMT(flushing)
2275 " conns idle=%d working=%d full=%d"
2276 " children connecting=%ld inndcomm_child"
2278 sms_names[sms], sm_period_counter, queue.count, until_connect,
2279 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2280 idle.count, working.count, full.count,
2281 (long)connecting_child, (long)inndcomm_child
2284 if (until_connect) until_connect--;
2286 poll_backlog_file();
2287 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2288 statemc_period_poll();
2289 check_master_queue();
2293 /*========== option parsing ==========*/
2296 of_seconds= 001000u;
2297 of_boolean= 002000u;
2300 typedef struct Option Option;
2301 typedef void OptionParser(const Option*, const char *val);
2311 void op_integer(const Option *o, const char *val) {
2314 unsigned long ul= strtoul(val,&ep,10);
2315 if (*ep || ep==val || errno || ul>INT_MAX)
2316 badusage("bad integer value for %s",o->long);
2317 int *store= o->store;
2321 void op_double(const Option *o, const char *val) {
2322 int *store= o->store;
2325 *store= strtod(val, &ep);
2326 if (*ep || ep==val || errno)
2327 badusage("bad floating point value for %s",o->long);
2330 void op_string(const Option *o, const char *val) {
2331 char **store= o->store;
2336 void op_seconds(const Option *o, const char *val) {
2337 int *store= o->store;
2340 double v= strtod(val,&ep);
2341 if (ep==val) badusage("bad time/duration value for %s",o->long);
2343 if (!*ep || !strcmp(ep,"s")) unit= 1;
2344 else if (!strcmp(ep,"m")) unit= 60;
2345 else if (!strcmp(ep,"h")) unit= 3600;
2346 else if (!strcmp(ep,"d")) unit= 86400;
2347 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2351 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2355 void op_periods_rndup(const Option *o, const char *val) {
2356 int *store= o->store;
2358 *store += PERIOD_SECONDS-1;
2359 *store /= PERIOD_SECONDS;
2362 void op_periods_booltrue(const Option *o, const char *val) {
2363 int *store= o->store;
2366 void op_periods_boolfalse(const Option *o, const char *val) {
2367 int *store= o->store;
2371 static const Option options[]= {
2372 {'f',"feedfile", &feedfile, op_string },
2373 {'q',"quiet-multiple", &quiet_multiple, op_booltrue, 1 },
2375 { 0, "max-connections", &max_connections op_integer },
2376 { 0, "max-queue-per-conn", &max_queue_per_conn op_integer },
2379 { 0, "streaming", &try_stream, op_booltrue, 1 },
2380 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2381 {'P',"port", &port op_integer },
2382 { 0, "inndconf", &inndconffile, op_string },
2383 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2384 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2386 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2387 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2389 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2390 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2391 { 0, "connection-timeout", &connection_timeout, op_seconds },
2392 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2395 int main(int argc, char **argv) {
2401 if (*arg != '-') break;
2402 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2404 while ((a= *++arg)) {
2408 char *equals= strchr(arg,'=');
2409 int len= equals ? (equals - arg) : strlen(arg);
2410 for (o=options; o->long; o++)
2411 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2413 badusage("unknown long option --%s",arg);
2416 if (equals) badusage("option --%s does not take a value",o->long);
2418 } else if (equals) {
2422 if (!arg) badusage("option --%s needs a value",o->long);
2425 break; /* eaten the whole argument now */
2427 for (o=options; o->long; o++)
2430 badusage("unknown short option -%c",a);
2437 if (!arg) badusage("option -%c needs a value",o->short);
2440 break; /* eaten the whole argument now */
2445 if (!arg) badusage("need site name argument");
2451 if (*++argv) badusage("too many non-option arguments");
2453 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2454 badusage("nocheck threshold percentage must be between 0..100");
2455 nocheck_thresh= nocheck_thresh_pct * 0.01;
2457 if (nocheck_decay_articles < 0.1)
2458 badusage("nocheck decay articles must be at least 0.1");
2459 nocheck_decay= 1 - 1/nocheck_decay_articles;
2462 pathoutgoing= innconf->pathoutgoing;
2463 innconf_read(inndconffile);
2466 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2467 else if (!feedfile[0])
2468 badusage("feed filename must be nonempty");
2469 else if (feedfile[strlen(feedfile)-1]=='/')
2470 feedfile= xasprintf("%s%s",feedfile,sitename);
2472 const char *feedfile_forbidden= "?*[~#";
2474 while ((c= *feedfile_forbidden++))
2475 if (strchr(feedfile, c))
2476 badusage("feed filename may not contain metacharacter %c",c);
2478 loop= oop_sys_new();
2479 if (!loop) sysdie("could not create liboop event loop");
2481 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2482 sysdie("could not ignore SIGPIPE");
2484 if (become_daemon) {
2485 for (i=3; i<255; i++)
2486 /* do this now before we open syslog, etc. */
2488 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2490 int null= open("/dev/null",O_RDWR);
2491 if (null<0) sysdie("failed to open /dev/null");
2497 pid_t child1= xfork("daemonise first fork");
2498 if (child1) _exit(0);
2500 pid_t sid= setsid();
2501 if (sid != child1) sysdie("setsid failed");
2503 pid_t child2= xfork("daemonise second fork");
2504 if (child2) _exit(0);
2509 if (!filemon_init()) {
2510 warn("no file monitoring available, polling");
2511 filepoll_schedule();