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 *head, *tail, *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).head))) /* 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) \
205 ( (typeof((l).head)) \
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_REMOVE(l,n) \
220 ( LIST_CHECKCANHAVENODE(l,n), \
221 list_remove(NODE((n))), \
225 #define LIST_INSERT(l,n,pred) \
226 ( LIST_CHECKCANHAVENODE(l,n), \
227 LIST_CHECKCANHAVENODE(l,pred), \
228 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
232 /*----- type predeclarations -----*/
234 typedef struct Conn Conn;
235 typedef struct Article Article;
236 typedef struct InputFile InputFile;
237 typedef enum StateMachineState StateMachineState;
242 /*----- function predeclarations -----*/
244 static void conn_check_work(Conn *conn);
246 static int filemon_init(void);
247 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
248 static void filemon_callback(void);
250 static void conn_assign_one_article(ConnList *connlist, Conn **last_assigned);
251 static void statemc_setstate(StateMachineState newsms, int periods,
252 const char *forlog, const char *why);
253 static void check_master_queue(void);
255 static void postfork_inputfile(InputFile *ipf);
257 /*----- configuration options -----*/
259 static char *sitename, *feedfile;
260 static const char *remote_host;
261 static int quiet_multiple=0, become_daemon=1;
263 static int max_connections=10, max_queue_per_conn=200;
265 static int connection_setup_timeout=200, port=119, try_stream=1;
266 static int inndcomm_flush_timeout=100;
267 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
268 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
269 static const char *inndconffile;
271 static double accept_proportion;
272 static double nocheck_thresh_pct= 95.0;
273 static double nocheck_thresh; /* computed in main from _pct */
274 static double nocheck_decay_articles= 100; /* converted to _decay */
275 static double nocheck_decay; /* computed in main from _articles */
276 static int nocheck, nocheck_reported;
279 /*----- statistics -----*/
281 typedef enum { /* in queue in conn->sent */
282 art_Unchecked, /* not checked, not sent checking */
283 art_Wanted, /* checked, wanted sent body as requested */
284 art_Unsolicited, /* - sent body without check */
288 #define RESULT_COUNTS(RCS,RCN) \
296 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
297 #define RCI_TRIPLE_VALS_BASE(counts,x) \
298 , counts[art_Unchecked] x \
299 + counts[art_Wanted] x \
300 + counts[art_Unsolicited] x, \
301 counts[art_Unchecked] x \
302 , counts[art_Wanted] x \
303 , counts[art_Unsolicited] x
306 #define RC_INDEX(x) RCI_##x,
307 RESULT_COUNTS(RC_INDEX, RC_INDEX)
312 /*----- transmission buffers -----*/
317 xk_Malloc, xk_Const, xk_Artdata
329 /*----- core operational data structure types -----*/
332 /* This is also an instance of struct oop_readable */
333 struct oop_readable readable; /* first */
334 oop_readable_call *readable_callback;
335 void *readable_callback_user;
338 struct Filemon_Perfile *filemon;
341 long inprogress; /* no. of articles read but not processed */
344 int counts[art_MaxState][RCI_max];
359 #define SMS_LIST(X) \
367 enum StateMachineState {
368 #define SMS_DEF_ENUM(s) sm_##s,
369 SMS_LIST(SMS_DEF_ENUM)
372 static const char *sms_names[]= {
373 #define SMS_DEF_NAME(s) #s ,
374 SMS_LIST(SMS_DEF_NAME)
380 int fd, max_queue, stream;
381 ArticleList queue; /* not yet told peer, or CHECK said send it */
382 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
383 struct iovec xmit[CONNIOVS];
384 XmitDetails xmitd[CONNIOVS];
389 /*----- operational variables -----*/
391 static oop_source *loop;
393 static int nconns, until_connect;
394 static ConnList idle, working, full;
395 static ArticleList queue;
397 static char *path_lock, *path_flushing, *path_defer;
399 #define SMS(newstate, periods, why) \
400 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
402 static StateMachineState sms;
404 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
405 static int sm_period_counter;
408 /*========== logging ==========*/
410 static void logcore(int sysloglevel, const char *fmt, ...)
411 __attribute__((__format__(printf,2,3)));
412 static void logcore(int sysloglevel, const char *fmt, ...) {
416 vsyslog(sysloglevel,fmt,al);
418 vfprintf(stderr,fmt,al);
424 static void logv(int sysloglevel, const char *pfx, int errnoval,
425 int exitstatus, const char *fmt, va_list al)
426 __attribute__((__format__(printf,5,0)));
427 static void logv(int sysloglevel, const char *pfx, int errnoval,
428 int exitstatus, const char *fmt, va_list al) {
430 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
431 msgbuf[sizeof(msgbuf)-1]= 0;
433 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
434 sysloglevel= LOG_ERR; /* run by wrong user, probably */
436 logcore(sysloglevel, "<%s>%s: %s%s%s",
437 sitename, pfx, msgbuf,
438 errnoval>=0 ? ": " : "",
439 errnoval>=0 ? strerror(errnoval) : "");
442 #define logwrap(fn, pfx, sysloglevel, err, estatus) \
443 static void fn(const char *fmt, ...) \
444 __attribute__((__format__(printf,1,2))); \
445 static void fn(const char *fmt, ...) { \
448 logv(sysloglevel, pfx, err, estatus, fmt, al); \
451 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
452 logwrap(die, " critical", LOG_CRIT, -1, 16);
454 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
455 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
457 logwrap(syswarn, " warning", LOG_WARNING, errno, 0);
458 logwrap(warn, " warning", LOG_WARNING, -1, 0);
460 logwrap(notice, "", LOG_NOTICE, -1, 0);
461 logwrap(info, " info", LOG_INFO, -1, 0);
462 logwrap(debug, " debug", LOG_DEBUG, -1, 0);
465 /*========== utility functions etc. ==========*/
467 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
469 static void *xmalloc(size_t sz) {
473 sysdie("malloc (%ld bytes) failed", (unsigned long)sz);
476 static pid_t xfork(const char *what) {
480 if (child==-1) sysdie("cannot fork for %s",what);
481 if (!child) postfork(what);
482 debug("forked %s %ld", what, (unsigned long)child);
486 static void on_fd_read_except(int fd, oop_call_fd callback) {
487 loop->on_fd(loop, fd, OOP_READ, callback, 0);
488 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
490 static void cancel_fd_read_except(int fd) {
491 loop->cancel_fd(loop, fd, OOP_READ);
492 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
495 static void report_child_status(const char *what, int status) {
496 if (WIFEXITED(status)) {
497 int es= WEXITSTATUS(status);
499 warn("%s: child died with error exit status %d",es);
500 } else if (WIFSIGNALED(status)) {
501 int sig= WTERMSIG(status);
502 const char *sigstr= strsignal(sig);
503 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
505 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
507 warn("%s: child died due to unknown fatal signal %d%s",
508 what, sig, coredump);
510 warn("%s: child died with unknown wait status %d", status);
514 static int xwaitpid(pid_t *pid, const char *what) {
517 int r= kill(*pid, SIGKILL);
518 if (r) sysdie("cannot kill %s child", what);
520 pid_t got= waitpid(*pid, &status, WNOHANG);
521 if (got==-1) sysdie("cannot reap %s child", what);
528 static void xunlink(const char *path, const char *what) {
530 if (r) sysdie("can't unlink %s %s", path, what);
533 static void check_isreg(const struct stat *stab, const char *path,
535 if (!S_ISREG(stab->st_mode))
536 die("%s %s not a plain file (mode 0%lo)",
537 what, path, (unsigned long)stab->st_mode);
540 static void xfstat(int fd, struct stat *stab_r, const char *what) {
541 int r= fstat(fd, stab_r);
542 if (r) sysdie("could not fstat %s", what);
545 static void xfstat_isreg(int fd, struct stat *stab_r,
546 const char *path, const char *what) {
547 xfstat(fd, stab_r, what);
548 check_isreg(stab_r, path, what);
551 static void xlstat_isreg(const char *path, struct stat *stab,
552 int *enoent_r /* 0 means ENOENT is fatal */,
554 int r= lstat(path, stab);
556 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
557 sysdie("could not lstat %s %s", what, path);
559 if (enoent_r) *enoent_r= 0;
560 check_isreg(stab, path, what);
563 static void setnonblock(int fd, int nonblocking) {
564 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
565 if (nonblocking) r |= O_NONBLOCK;
566 else r &= ~O_NONBLOCK;
567 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
570 static int samefile(const struct stat *a, const struct stat *b) {
571 assert(S_ISREG(a->st_mode));
572 assert(S_ISREG(b->st_mode));
573 return (a->st_ino == b->st_ino &&
574 a->st_dev == b->st_dev);
577 static char *sanitise(const char *input, int len) {
578 static char sanibuf[100]; /* returns pointer to this buffer! */
580 const char *p= input;
584 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
586 if (len<=0 || !(c= *p++)) { *q++= '\''; *q=0; break; }
587 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
588 sprintf(q,"\\x%02x",c);
594 /*========== making new connections ==========*/
596 static int connecting_sockets[2]= {-1,-1};
597 static pid_t connecting_child;
599 static void connect_attempt_discard(void) {
600 if (connecting_sockets[0])
601 loop->cancel_fd(connecting_sockets[0]);
603 perhaps_close(&connecting_sockets[0]);
604 perhaps_close(&connecting_sockets[1]);
606 if (connecting_child) {
607 int r= kill(connecting_child, SIGTERM);
608 if (r) syswarn("failed to kill connecting child");
609 int status= xwaitpid(&connecting_child, "connect");
611 if (!(WIFEXITED(status) ||
612 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
613 report_child_status("connect", status);
617 #define PREP_DECL_MSG_CMSG(msg) \
619 memset(&msg,0,sizeof(msg)); \
620 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
621 msg.msg_control= msg##cbuf; \
622 msg.msg_controllen= sizeof(msg##cbuf);
624 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
627 conn= xmalloc(sizeof(*conn));
628 memset(conn,0,sizeof(*conn));
630 PREP_DECL_MSG_CMSG(msg);
631 struct cmsghdr *h= 0;
632 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
633 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
636 pid_t got= waitpid(connecting_child, &status, WNOHANG);
638 assert(got==connecting_child);
640 if (WIFEXITED(status) &&
641 (WEXITSTATUS(status) != 0 &&
642 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
643 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
644 /* child already reported the problem */
645 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
646 warn("connect: connection attempt timed out");
647 } else if (!WIFEXITED(status)) {
648 report_child_status("connect", status);
649 /* that's probably the root cause then */
652 /* child is still running apparently, report the socket problem */
654 syswarn("connect: read from child socket failed");
655 else if (e == OOP_EXCEPTION)
656 warn("connect: unexpected exception on child socket");
658 warn("connect: unexpected EOF on child socket");
663 #define CHK(field, val) \
664 if (h->cmsg_##field != val) { \
665 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
668 CHK(level, SOL_SOCKET);
669 CHK(type, SCM_RIGHTS);
670 CHK(len, CMSG_LEN(sizeof(conn->fd)));
673 if (CMSG_NXTHDR(&msg,h)) { die("connect: child sent many cmsgs"); goto x; }
675 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
678 pid_t got= waitpid(connecting_child, &status, 0);
679 if (got==-1) sysdie("connect: real wait for child");
680 assert(got == connecting_child);
683 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
684 int es= WEXITSTATUS(status);
686 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
687 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
689 fatal("connect: child gave unexpected exit status %d", es);
692 setnonblock(conn->fd, 1);
695 LIST_ADDHEAD(idle, conn);
696 notice("#%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
697 connect_attempt_discard();
698 check_master_queue();
703 perhaps_close(&conn->fd);
706 connect_attempt_discard();
709 static void connect_start(void) {
710 assert(!connecting_sockets[0]);
711 assert(!connecting_sockets[1]);
712 assert(!connecting_child);
714 notice("starting connection attempt");
716 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
717 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
719 connecting_child= xfork("connection");
721 if (!connecting_child) {
722 FILE *cn_from, *cn_to;
723 char buf[NNTP_STRLEN+100];
724 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
726 r= close(connecting_sockets[0]);
727 if (r) sysdie("connect: close parent socket in child");
729 alarm(connection_setup_timeout);
730 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
731 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
732 else sysfatal("connect: connection attempt failed");
734 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
735 sysfatal("connect: authentication failed");
737 if (fputs("MODE STREAM\r\n", cn_to) ||
739 sysfatal("connect: could not send MODE STREAM");
740 buf[sizeof(buf)-1]= 0;
741 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
743 sysfatal("connect: could not read response to MODE STREAM");
745 fatal("connect: connection close in response to MODE STREAM");
750 fatal("connect: response to MODE STREAM is too long: %.100s...",
751 remote_host, sanitise(buf));
752 l--; if (l>0 && buf[l-1]=='\r') l--;
755 int rcode= strtoul(buf,&ep,10);
757 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
761 exitstatus= CONNCHILD_ESTATUS_STREAM;
767 warn("connect: unexpected response to MODE STREAM: %.50s",
773 int fd= fileno(cn_from);
775 PREP_DECL_MSG_CMSG(msg);
776 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
777 cmsg->cmsg_level= SOL_SOCKET;
778 cmsg->cmsg_type= SCM_RIGHTS;
779 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
780 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
782 msg.msg_controllen= cmsg->cmsg_len;
783 r= sendmsg(connecting_sockets[1], &msg, 0);
784 if (r) sysdie("sendmsg failed for new connection");
789 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
790 if (r) sysdie("connect: close child socket in parent");
792 on_fd_read_except(connecting_sockets[0], connchild_event);
796 connect_attempt_discard();
800 /*========== overall control of article flow ==========*/
802 static void check_master_queue(void) {
806 Conn *last_assigned=0;
809 conn_assign_one_article(&working, &last_assigned);
810 } else if (idle.head) {
811 conn_assign_one_article(&idle, &last_assigned);
812 } else if (nconns < max_connections && queue.count >= max_queue_per_conn &&
813 !connecting_child && !until_connect) {
814 until_connect= reconnect_delay_periods;
820 conn_check_work(last_assigned);
823 static void conn_assign_one_article(ConnList *connlist, Conn **last_assigned) {
824 Conn *conn= connlist->head;
826 LIST_REMOVE(*connlist, conn);
827 Article *art= LIST_REMHEAD(queue);
828 LIST_ADDTAIL(conn->queue, art);
829 LIST_ADD(*conn_determine_right_list(conn), conn);
831 /* This slightly odd arrangement is so that we call conn_check_work
832 * once after filling the queue for a new connection in
833 * check_master_queue, rather than for each article. */
834 if (conn != *last_assigned && *last_assigned)
835 conn_check_work(*last_assigned);
836 *last_assigned= conn;
839 static int conn_total_queued_articles(Conn *conn) {
840 return conn->sent.count + conn->queue.count;
843 static ConnList *conn_determine_right_list(Conn *conn) {
844 int inqueue= conn_total_queued_articles(conn);
845 assert(inqueue <= max_queue);
846 if (inqueue == 0) return &idle;
847 if (inqueue == conn->max_queue) return &full;
851 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
856 static void conn_check_work(Conn *conn) {
859 conn_make_some_xmits(conn);
861 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
865 void *rp= conn_write_some_xmits(conn);
866 if (rp==OOP_CONTINUE) {
867 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
869 } else if (rp==OOP_HALT) {
872 /* transmitted everything */
879 static void vconnfail(Conn *conn, const char *fmt, va_list al)
880 __attribute__((printf,2,0));
882 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
883 int requeue[art_MaxState];
886 while ((art= LIST_REMHEAD(conn->queue))) LIST_ADDTAIL(queue);
887 while ((art= LIST_REMHEAD(conn->sent))) {
888 counts[art->state]++;
889 if (art->state==art_Unsolicited) art->state= art_Unchecked;
895 for (i=0, dp=&conn->xmitd; i<conn->xmitu; i++, dp++)
898 char *m= xvasprintf(fmt,al);
899 warn("#%d connection failed, requeueing " RCI_TRIPLE_FMT_BASE ": %s",
900 conn->fd, RCI_TRIPLE_FMT_VALS(requeue, /*nothing*/), m);
906 until_connect= reconnect_delay_periods;
907 check_master_queue();
910 static void connfail(Connection *conn, const char *fmt, ...)
911 __attribute__((printf,2,3));
912 static void connfail(Connection *conn, const char *fmt, ...) {
919 /*========== article transmission ==========*/
921 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
922 XmitKind kind) { /* caller must then fill in details */
923 struct iovec *v= &conn->xmit[conn->xmitu];
924 XmitDetails *d= &conn->xmitd[conn->xmitu++];
931 static void xmit_noalloc(Conn *conn, const char *data, int len) {
932 xmit_core(conn,data,len, xk_Const);
934 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
936 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
937 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
941 static void xmit_free(XmitDetails *d) {
943 case xk_Malloc: free(d->info.malloc_tofree); break;
944 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
945 case xk_Const: break;
950 static void *conn_write_some_xmits(Conn *conn) {
952 * 0: nothing more to write, no need to call us again
953 * OOP_CONTINUE: more to write but fd not writeable
954 * OOP_HALT: disaster, have destroyed conn
957 int count= conn->xmitu;
958 if (!count) return 0;
960 if (count > IOV_MAX) count= IOV_MAX;
961 ssize_t rs= writev(conn->fd, conn->xmit, count);
963 if (errno == EAGAIN) return OOP_CONTINUE;
964 connfail(conn, "write failed: %s", strerror(errno));
969 for (done=0; rs && done<xmitu; done++) {
970 struct iovec *vp= &conn->xmit[done];
971 XmitDetails *dp= &conn->xmitd[done];
972 if (rs > vp->iov_len) {
980 int newu= conn->xmitu - done;
981 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
982 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
987 static void conn_make_some_xmits(Conn *conn) {
989 if (conn->xmitu+5 > CONNIOVS)
992 Article *art= LIST_REMHEAD(queue);
995 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
996 /* actually send it */
998 ARTHANDLE *artdata= SMretrieve();
1002 XMIT_LITERAL("TAKETHIS ");
1003 xmit_noalloc(conn, art->mid, art->midlen);
1004 XMIT_LITERAL("\r\n");
1005 xmit_artbody(conn, artdata);
1008 /* we got 235 from IHAVE */
1010 xmit_artbody(conn, artdata);
1012 XMIT_LITERAL(".\r\n");
1017 art->state == art_Unchecked ? art_Unsolicited :
1018 art->state == art_Wanted ? art_Wanted :
1020 art->ipf->counts[art->state].sent++;
1021 LIST_ADDTAIL(conn->sent, art);
1027 XMIT_LITERAL("IHAVE ");
1029 XMIT_LITERAL("CHECK ");
1030 xmit_noalloc(art->mid, art->midlen);
1031 XMIT_LITERAL("\r\n");
1033 assert(art->state == art_Unchecked);
1034 art->ipf->counts[art->state].sent++;
1035 LIST_ADDTAIL(conn->sent, art);
1041 /*========== handling responses from peer ==========*/
1043 static const oop_rd_style peer_rd_style= {
1044 OOP_RD_DELIM_STRIP, '\n',
1046 OOP_RD_SHORTREC_FORBID
1049 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1050 const char *errmsg, int errnoval,
1051 const char *data, size_t recsz, void *conn_v) {
1053 connfail(conn, "error receiving from peer: %s", errmsg);
1054 return OOP_CONTINUE;
1057 static Article *article_reply_check(Connection *conn, const char *response,
1058 int code_indicates_streaming,
1060 /* 1:yes, -1:no, 0:dontcare */,
1061 const char *sanitised_response) {
1062 Article *art= conn->sent.head;
1066 "peer gave unexpected response when no commands outstanding: %s",
1067 sanitised_response);
1071 if (code_indicates_streaming) {
1072 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1073 if (!conn->stream) {
1074 connfail("peer gave streaming response code "
1075 " to IHAVE or subsequent body: %s", sanitised_response);
1078 const char *got_mid= response+4;
1079 int got_midlen= strcspn(got_mid, " \n\r");
1080 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1081 connfail("peer gave streaming response with syntactically invalid"
1082 " messageid: %s", sanitised_response);
1085 if (got_midlen != art->midlen ||
1086 memcmp(got_mid, art->messageid, got_midlen)) {
1087 connfail("peer gave streaming response code to wrong article -"
1088 " probable synchronisation problem; we offered: %s;"
1090 art->messageid, sanitised_response);
1095 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
1096 sanitised_response);
1101 if (must_have_sent>0 && art->state < art_Wanted) {
1102 connfail("peer says article accepted but we had not sent the body: %s",
1103 sanitised_response);
1106 if (must_have_sent<0 && art->state >= art_Wanted) {
1107 connfail("peer says please sent the article but we just did: %s",
1108 sanitised_response);
1112 Article *art_again= LIST_REMHEAD(conn->sent);
1113 assert(art_again == art);
1117 static void update_nocheck(int accepted) {
1118 accept_proportion *= accept_decay;
1119 accept_proportion += accepted;
1120 int new_nocheck= accept_proportion >= nocheck_thresh;
1121 if (new_nocheck && !nocheck_reported) {
1122 notice("entering nocheck mode for the first time");
1123 nocheck_reported= 1;
1124 } else if (new_nocheck != nocheck) {
1125 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1127 nocheck= new_nocheck;
1130 static void article_done(Connection *conn, Article *art, int whichcount) {
1131 art->ipf->counts[art->state][whichcount]++;
1132 if (whichcount == RC_accepted) update_nocheck(1);
1133 else if (whichcount == RC_unwanted) update_nocheck(0);
1135 InputFile *ipf= art->ipf;
1136 while (art->blanklen) {
1137 static const char spaces[]=
1142 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1143 int r= pwrite(ipf->fd, spaces, w, art->offset);
1145 if (errno==EINTR) continue;
1146 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1147 art->messageid, art->blanklen, art->offset, ipf->path);
1149 assert(r>=0 && r<=w);
1155 assert(ipf->inprogress >= 0);
1157 if (!ipf->inprogress && ipf != main_input_file)
1158 queue_check_input_done();
1163 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1164 const char *errmsg, int errnoval,
1165 const char *data, size_t recsz, void *conn_v) {
1168 if (ev == OOP_RD_EOF) {
1169 connfail(conn, "unexpected EOF from peer");
1170 return OOP_CONTINUE;
1172 assert(ev == OOP_RD_OK);
1174 char *sani= sanitise(data, recsz);
1177 unsigned long code= strtoul(data, &ep, 10);
1178 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1179 connfail(conn, "badly formatted response from peer: %s", sani);
1180 return OOP_CONTINUE;
1183 if (conn->quitting) {
1185 connfail(conn, "peer gave failure response to QUIT: %s", sani);
1186 return OOP_CONTINUE;
1194 #define GET_ARTICLE(musthavesent) \
1195 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1196 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1198 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1199 code_streaming= (streaming) \
1200 GET_ARTICLE(musthavesent); \
1201 article_done(conn, art, RC_##how); break;
1203 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1205 int code_streaming= 0;
1209 case 400: PEERBADMSG("peer stopped accepting articles");
1210 case 503: PEERBADMSG("peer timed us out");
1211 default: PEERBADMSG("peer sent unexpected message");
1213 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1214 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1216 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1217 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1219 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1220 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1222 case 238: /* CHECK says send it */
1224 case 335: /* IHAVE says send it */
1226 assert(art->state == art_Unchecked);
1227 art->ipf->counts[art->state].accepted++;
1228 art->state= art_Wanted;
1229 LIST_ADDTAIL(conn->queue);
1232 case 431: /* CHECK or TAKETHIS says try later */
1234 case 436: /* IHAVE says try later */
1237 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1239 sysfatal("write to defer file %s",path_defer);
1240 article_done(conn, art, RC_deferred);
1245 check_check_work(conn);
1246 return OOP_CONTINUE;
1250 /*========== monitoring of input files ==========*/
1252 static void feedfile_eof(InputFile *ipf) {
1253 assert(ipf != main_input_file); /* promised by tailing_try_read */
1255 inputfile_tailing_stop(ipf);
1256 assert(ipf->fd >= 0);
1257 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1260 if (ipf == flushing_input_file) {
1261 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1262 if (main_input_file) inputfile_tailing_start(main_input_file);
1263 statemc_check_flushing_done();
1264 } else if (ipf == backlog_input_file) {
1265 statemc_check_backlog_done();
1267 abort(); /* supposed to wait rather than get EOF on main input file */
1271 static InputFile *open_input_file(const char *path) {
1272 int fd= open(path, O_RDONLY);
1274 if (errno==ENOENT) return 0;
1275 sysfatal("unable to open input file %s", path);
1278 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1279 memset(ipf,0,sizeof(*ipf));
1281 ipf->readable.on_readable= tailing_on_readable;
1282 ipf->readable.on_cancel= tailing_on_cancel;
1283 ipf->readable.try_read= tailing_try_read;
1286 strcpy(ipf->path, path);
1291 static void close_input_file(InputFile *ipf) {
1292 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1293 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1294 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1295 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1298 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1302 /*---------- dealing with articles read in the input file ----------*/
1304 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1305 oop_rd_event ev, const char *errmsg,
1307 const char *data, size_t recsz,
1309 InputFile *ipf= ipf_v;
1311 char tokentextbuf[sizeof(TOKEN)*2+3];
1313 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1315 if (data[0] && data[0]!=' ') {
1316 char *space= strchr(data,' ');
1317 int tokenlen= space-data;
1318 int midlen= (int)recsz-tokenlen-1;
1319 if (midlen < 0) goto bad_data;
1321 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1322 memcpy(tokentextbuf, data, tokenlen);
1323 tokentextbuf[tokenlen]= 0;
1324 if (!IsToken(tokentextbuf)) goto bad_data;
1326 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1327 art->offset= ipf->offset;
1328 art->blanklen= recsz;
1329 art->midlen= midlen;
1330 art->state= art_Unchecked;
1331 art->ipf= ipf; ipf->inprogress++;
1332 art->token= TextToToken(tokentextbuf);
1333 strcpy(art->messageid, space+1);
1334 LIST_ADDTAIL(queue, art);
1336 ipf->offset += recsz + 1;
1338 if (sms==sm_NORMAL && ipf==main_input_file &&
1339 ipf->offset >= flush_threshold)
1340 statemc_start_flush("feed file size");
1342 check_master_queue();
1345 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1346 assert(sms == sm_NORMAL);
1348 debug("starting flush (%s) (%lu >= %lu) (%d)",
1350 (unsigned long)ipf->offset, (unsigned long)flush_threshold,
1353 int r= link(feedfile, duct_path);
1354 if (r) sysdie("link feedfile %s to flushing file %s", feedfile,
1358 xunlink(feedfile, "old feedfile link");
1361 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1364 /*========== tailing input file ==========*/
1366 static void filemon_start(InputFile *ipf) {
1367 assert(!ipf->filemon);
1369 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1370 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1371 filemon_method_startfile(ipf, ipf->filemon);
1374 static void filemon_stop(InputFile *ipf) {
1375 if (!ipf->filemon) return;
1376 filemon_method_stopfile(ipf, ipf->filemon);
1381 static void filemon_callback(InputFile *ipf) {
1382 ipf->readable_callback(ipf->readable_callback_user);
1385 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1387 InputFile *ipf= user;
1388 return ipf->readable_callback(ipf->readable_callback_user);
1391 static void on_cancel(struct oop_readable *rable) {
1392 InputFile *ipf= (void*)rable;
1394 if (ipf->filemon) filemon_stopfile(ipf);
1395 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1396 ipf->readable_callback= 0;
1399 static void tailing_queue_readable(InputFile *ipf) {
1400 /* lifetime of ipf here is OK because destruction will cause
1401 * on_cancel which will cancel this callback */
1402 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1405 static int tailing_on_readable(struct oop_readable *rable,
1406 oop_readable_call *cb, void *user) {
1407 InputFile *ipf= (void*)rable;
1409 tailing_on_cancel(rable);
1410 ipf->readable_callback= cb;
1411 ipf->readable_callback_user= user;
1412 filemon_startfile(ipf);
1414 tailing_queue_readable(ipf);
1418 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1420 InputFile *ipf= (void*)rable;
1422 ssize_t r= read(ipf->fd, buffer, length);
1424 if (errno==EINTR) continue;
1428 if (ipf==main_input_file) {
1431 } else if (ipf==flushing_input_file) {
1433 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1434 } else if (ipf==backlog_input_file) {
1444 /*---------- filemon implemented with inotify ----------*/
1446 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1447 #define HAVE_FILEMON
1449 #include <linux/inotify.h>
1451 static int filemon_inotify_fd;
1452 static int filemon_inotify_wdmax;
1453 static InputFile **filemon_inotify_wd2ipf;
1455 typedef struct Filemon_Perfile {
1457 } Filemon_Inotify_Perfile;
1459 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1460 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1461 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1463 if (wd >= filemon_inotify_wdmax) {
1465 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1466 sizeof(*filemon_inotify_wd2ipf) * newmax);
1467 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1468 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1469 filemon_inotify_wdmax= newmax;
1472 assert(!filemon_inotify_wd2ipf[wd]);
1473 filemon_inotify_wd2ipf[wd]= ipf;
1475 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1476 ipf, wd, filemon_inotify_wdmax);
1481 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1483 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1484 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1485 if (r) sysdie("inotify_rm_watch");
1486 filemon_inotify_wd2ipf[wd]= 0;
1489 static void *filemon_inotify_readable(oop_source *lp, int fd,
1490 oop_event e, void *u) {
1491 struct inotify_event iev;
1493 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1495 if (errno==EAGAIN) break;
1496 sysdie("read from inotify master");
1497 } else if (r==sizeof(iev)) {
1498 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1500 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1502 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1503 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1504 filemon_callback(ipf);
1506 return OOP_CONTINUE;
1509 static int filemon_method_init(void) {
1510 filemon_inotify_fd= inotify_init();
1511 if (filemon_inotify_fd<0) {
1512 syswarn("could not initialise inotify: inotify_init failed");
1516 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1518 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1522 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1524 /*---------- filemon dummy implementation ----------*/
1526 #if !defined(HAVE_FILEMON)
1528 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1530 static int filemon_method_init(void) { return 0; }
1531 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1532 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1534 #endif /* !HAVE_FILEMON */
1536 /*---------- interface to start and stop an input file ----------*/
1538 static const oop_rd_style feedfile_rdstyle= {
1539 OOP_RD_DELIM_STRIP, '\n',
1541 OOP_RD_SHORTREC_EOF,
1544 static void inputfile_tailing_start(InputFile *ipf) {
1546 ipf->readable->on_readable= tailing_on_readable;
1547 ipf->readable->on_cancel= tailing_on_cancel;
1548 ipf->readable->try_read= tailing_try_read;
1549 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1550 ipf->readable->delete_kill= 0;
1552 ipf->readable_callback= 0;
1553 ipf->readable_callback_user= 0;
1555 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1558 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1559 feedfile_got_article,ipf, feedfile_problem,ipf);
1560 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1563 static void inputfile_tailing_stop(InputFile *ipf) {
1565 oop_rd_cancel(ipf->rd);
1566 oop_rd_delete(ipf->rd);
1568 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1572 /*========== interaction with innd - state machine ==========*/
1574 /* See official state diagram at top of file. We implement
1585 |`---------------------------------------------------.
1587 |`---------------- - - - |
1588 D ENOENT | D EXISTS see OVERALL STATES diagram |
1589 | for full startup logic |
1592 | ============ try to |
1598 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1599 ^ | hardlink F to D |
1602 | | our handle onto F is now onto D |
1605 | |<-------------------<---------------------<---------+
1607 | | spawn inndcomm flush |
1609 | ================== |
1610 | FLUSHING[-ABSENT] |
1612 | main D tail/none |
1613 | ================== |
1615 | | INNDCOMM FLUSH FAILS ^
1616 | |`----------------------->----------. |
1618 | | NO SUCH SITE V |
1619 ^ |`--------------->----. ==================== |
1620 | | \ FLUSHFAILED[-ABSENT] |
1622 | | FLUSH OK \ main D tail/none |
1623 | | open F \ ==================== |
1625 | | \ | TIME TO RETRY |
1626 | |`------->----. ,---<---'\ `----------------'
1627 | | D NONE | | D NONE `----.
1629 | ============= V V ============
1630 | SEPARATED-1 | | DROPPING-1
1631 | flsh->fd>=0 | | flsh->fd>=0
1632 | [Separated] | | [Dropping]
1633 | main F idle | | main none
1634 | old D tail | | old D tail
1635 | ============= | | ============
1637 ^ | EOF ON D | | defer | EOF ON D
1639 | =============== | | ===============
1640 | SEPARATED-2 | | DROPPING-2
1641 | flsh->fd==-1 | V flsh->fd==-1
1642 | [Finishing] | | [Dropping]
1643 | main F tail | `. main none
1644 | old D closed | `. old D closed
1645 | =============== V `. ===============
1647 | | ALL D PROCESSED `. | ALL D PROCESSED
1648 | V install defer as backlog `. | install defer
1649 ^ | close D `. | close D
1650 | | unlink D `. | unlink D
1653 `----------' ==============
1673 static void statemc_init(void) {
1674 struct stat stab, stabf;
1676 path_lock= xasprintf("%s_lock", feedfile);
1677 path_flushing= xasprintf("%s_flushing", feedfile);
1678 path_defer= xasprintf("%s_defer", feedfile);
1679 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1682 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1683 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1686 memset(&fl,0,sizeof(fl));
1688 fl.l_whence= SEEK_SET;
1689 r= fcntl(lockfd, F_SETLK, &fl);
1691 if (errno==EACCES || errno==EAGAIN) {
1692 if (quiet_multiple) exit(0);
1693 fatal("another duct holds the lockfile");
1695 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1698 xfstat_isreg(lockfd, &stabf, "lockfile");
1700 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1702 if (!lock_noent && samefile(&stab, &stabf))
1706 sysdie("could not close stale lockfile %s", path_lock);
1708 debug("startup: locked");
1710 search_backlog_file();
1713 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1715 debug("startup: ductdefer ENOENT");
1717 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1718 switch (stab.st_nlink==1) {
1720 open_defer(); /* so that we will later close it and rename it */
1723 xunlink(path_defer, "stale defer file link"
1724 " (presumably hardlink to backlog file)");
1727 die("defer file %s has unexpected link count %d",
1728 path_defer, stab.st_nlink);
1732 struct stat stab_f, stab_d;
1735 InputFile *file_d= open_input_file(path_flushing);
1736 if (file_d) xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1738 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1740 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1741 debug("startup: F==D => Hardlinked");
1742 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1747 debug("startup: F ENOENT => Moved");
1748 if (file_d) startup_set_input_file(file_d);
1749 spawn_inndcomm_flush("feedfile missing at startup");
1750 /* => Flushing, sms:=FLUSHING */
1753 debug("startup: F!=D => Separated");
1754 startup_set_input_file(file_d);
1755 SMS(SEPARATED, 0, "found both old and current feed files");
1757 debug("startup: F exists, D ENOENT => Normal");
1758 FILE *file_f= open_input_file(feedfile);
1759 if (!file_f) die("feed file vanished during startup");
1760 startup_set_input_file(file_f);
1761 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1766 static void statemc_period_poll(void) {
1767 if (!sm_period_counter) return;
1768 sm_period_counter--;
1769 assert(sm_period_counter>=0);
1771 if (sm_period_counter) return;
1774 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1776 case sm_FLUSHFAILED:
1777 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1784 static void startup_set_input_file(InputFile *f) {
1785 assert(!main_input_file);
1787 inputfile_tailing_start(f);
1790 static int inputfile_is_done(InputFile *ipf) {
1792 if (ipf->inprogress) return 0; /* new article in the meantime */
1793 if (ipf->fd >= 0); return 0; /* not had EOF */
1797 static void notice_processed(InputFile *ipf, const char *what,
1799 #define RCI_NOTHING(x) /* nothing */
1800 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
1801 #define RCI_TRIPLE_VALS(x) RCI_TRIPLE_VALS_BASE(ipf->counts, .x)
1803 info("processed %s%s offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
1804 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
1807 ipf->counts[art_Unchecked].sent + ipf->counts[art_Unsolicited].sent
1808 , ipf->counts[art_Unchecked].sent, ipf->counts[art_Unsolicited].sent,
1809 ipf->counts[art_Wanted].accepted + ipf->counts[art_Unsolicited].accepted
1810 ,ipf->counts[art_Wanted].accepted,ipf->counts[art_Unsolicited].accepted
1811 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
1815 static void statemc_check_backlog_done(void) {
1816 InputFile *ipf= backlog_input_file();
1817 if (!inputfile_is_done(ipf)) return;
1819 const char *slash= strrchr(ipf->path, "/");
1820 const char *leaf= slash ? slash+1 : ipf->path;
1821 const char *under= strchr(slash, "_");
1822 const char *rest= under ? under+1 : leaf;
1823 if (!strncmp(rest,"backlog",7)) rest += 7;
1824 notice_processed(ipf,"backlog:",rest);
1826 close_input_file(ipf);
1827 if (unlink(ipf->path)) {
1828 if (errno != ENOENT)
1829 sysdie("could not unlink processed backlog file %s", ipf->path);
1830 warn("backlog file %s vanished while we were reading it"
1831 " so we couldn't remove it (but it's done now, anyway)",
1835 backlog_input_file= 0;
1836 search_backlog_file();
1840 static void statemc_check_flushing_done(void) {
1841 InputFile *ipf= flushing_input_file;
1842 if (!inputfile_is_done(ipf)) return;
1844 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1846 notice_processed(ipf,"feedfile",0);
1850 xunlink(path_flushing, "old flushing file");
1852 close_input_file(flushing_input_file);
1853 free(flushing_input_file);
1854 flushing_input_file= 0;
1856 if (sms==sm_SEPARATED) {
1857 notice("flush complete");
1858 SMS(NORMAL, 0, "flush complete");
1859 } else if (sms==sm_DROPPING) {
1860 SMS(DROPPED, 0, "old flush complete");
1861 search_backlog_file();
1862 notice("feed dropped, but will continue until backlog is finished");
1866 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
1868 assert(!inputfile_is_done(main_input_file));
1869 statemc_check_flushing_done();
1870 statemc_check_backlog_done();
1871 return OOP_CONTINUE;
1874 static void queue_check_input_done(void) {
1875 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
1878 static void statemc_setstate(StateMachineState newsms, int periods,
1879 const char *forlog, const char *why) {
1881 sm_period_counter= periods;
1883 const char *xtra= "";
1885 case sm_FLUSHING: sm_FLUSHFAILED:
1886 if (!main_input_file) xtra= "-ABSENT";
1888 case sm_SEPARATED: case sm_DROPPING:
1889 xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
1895 info("%s%s[%d] %s",forlog,xtra,periods,why);
1897 info("%s%s %s",forlog,xtra,why);
1901 /*---------- defer and backlog files ----------*/
1903 static void open_defer(void) {
1908 defer= fopen(path_defer, "a+");
1909 if (!defer) sysfatal("could not open defer file %s", path_defer);
1911 /* truncate away any half-written records */
1913 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1915 if (stab.st_size > LONG_MAX)
1916 die("defer file %s size is far too large", path_defer);
1921 long orgsize= stab.st_size;
1922 long truncto= stab.st_size;
1924 if (!truncto) break; /* was only (if anything) one half-truncated record */
1925 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1926 sysdie("seek in defer file %s while truncating partial", path_defer);
1931 sysdie("failed read from defer file %s", path_defer);
1933 die("defer file %s shrank while we were checking it!", path_defer);
1939 if (stab.st_size != truncto) {
1940 warn("truncating half-record at end of defer file %s -"
1941 " shrinking by %ld bytes from %ld to %ld",
1942 path_defer, orgsize - truncto, orgsize, truncto);
1945 sysfatal("could not flush defer file %s", path_defer);
1946 if (ftruncate(fileno(defer), truncto))
1947 sysdie("could not truncate defer file %s", path_defer);
1950 info("continuing existing defer file %s (%ld bytes)",
1951 path_defer, orgsize);
1953 if (fseek(defer, truncto, SEEK_SET))
1954 sysdie("could not seek to new end of defer file %s", path_defer);
1957 static void close_defer(void) {
1961 xfstat(fileno(defer), &stab, "defer file");
1963 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1966 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1967 (unsigned long)now.tv_sec,
1968 (unsigned long)stab.st_ino);
1969 if (link(path_defer, path_backlog))
1970 sysfatal("could not install defer file %s as backlog file %s",
1971 path_defer, backlog);
1972 if (unlink(path_defer))
1973 sysdie("could not unlink old defer link %s to backlog file %s",
1974 path_defer, backlog);
1976 if (until_backlog_nextscan < 0 ||
1977 until_backlog_nextscan > backlog_retry_minperiods + 1)
1978 until_backlog_nextscan= backlog_retry_minperiods + 1;
1981 static void poll_backlog_file(void) {
1982 if (until_backlog_nextscan < 0) return;
1983 if (until_backlog_nextscan-- > 0) return;
1984 search_backlog_file();
1987 static void search_backlog_file(void) {
1988 /* returns non-0 iff there are any backlog files */
1993 const char *oldest_path=0;
1994 time_t oldest_mtime, now;
1996 if (backlog_input_file) return 3;
2000 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2004 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2006 die("out of memory expanding backlog pattern %s", globpat_backlog);
2008 for (i=0; i<gl.gl_pathc; i++) {
2009 const char *path= gl.gl_pathv[i];
2011 if (strchr(path,'#') || strchr(path,'~')) {
2012 debug("backlog file search skipping %s", path);
2015 r= stat(path, &stab);
2017 syswarn("failed to stat backlog file %s", path);
2020 if (!S_ISREG(stab.st_mode)) {
2021 warn("backlog file %s is not a plain file (or link to one)", path);
2024 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2026 oldest_mtime= stab.st_mtime;
2029 case GLOB_NOMATCH: /* fall through */
2032 sysdie("glob expansion of backlog pattern %s gave unexpected"
2033 " nonzero (error?) return value %d", globpat_backlog, r);
2039 debug("backlog scan: none");
2041 if (sms==sm_DROPPED) {
2042 notice("feed dropped and our work is complete");
2043 xunlink(path_lock, "lockfile for old feed");
2046 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2050 now= time(); if (now==-1) sysdie("time(2) failed");
2051 double age= difftime(now, oldest_mtime);
2052 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
2054 if (age_deficiency <= 0) {
2055 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2056 age, age_deficiency, oldest_path);
2058 backlog_input_file= open_input_file(oldest_path);
2059 if (!backlog_input_file) {
2060 warn("backlog file %s vanished as we opened it", backlog_input_file);
2063 inputfile_tailing_start(backlog_input_file);
2064 until_backlog_nextscan= -1;
2068 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
2070 if (backlog_spontaneous_rescan_periods >= 0 &&
2071 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2072 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2074 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2075 age, age_deficiency, until_backlog_nextscan, oldest_path);
2079 /*========== flushing the feed ==========*/
2081 static pid_t inndcomm_child;
2083 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2084 assert(inndcomm_child);
2085 int status= xwaitpid(&inndcomm_child, "inndcomm");
2086 loop->cancel_fd(fd);
2089 assert(!flushing_input_file);
2091 if (WIFEXITED(status)) {
2092 switch (WEXITSTATUS(status)) {
2094 case INNDCOMMCHILD_ESTATUS_FAIL:
2097 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2098 warn("feed has been dropped by innd, finishing up");
2099 flushing_input_file= main_input_file;
2100 tailing_queue_readable(flushing_input_file);
2101 /* we probably previously returned EAGAIN from our fake read method
2102 * when in fact we were at EOF, so signal another readable event
2103 * so we actually see the EOF */
2107 if (flushing_input_file) {
2108 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2111 SMS(DROPPED, 0, "feed dropped by innd");
2112 search_backlog_file();
2114 return OOP_CONTINUE;
2118 flushing_input_file= main_input_file;
2119 tailing_queue_readable(flushing_input_file);
2121 main_input_file= open_input_file(feedfile);
2122 if (!main_input_file)
2123 die("flush succeeded but feedfile %s does not exist!", feedfile);
2125 if (flushing_input_file) {
2126 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2129 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2131 return OOP_CONTINUE;
2134 goto unexpected_exitstatus;
2137 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2138 warn("flush timed out trying to talk to innd");
2141 unexpected_exitstatus:
2142 report_child_status("inndcomm child", status);
2146 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2149 static void inndcommfail(const char *what) {
2150 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2151 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2154 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2157 notice("flushing %s",why);
2159 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2160 assert(!inndcomm_child);
2162 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2164 inndcomm_child= xfork();
2166 if (!inndcomm_child) {
2167 static char flushargv[2]= { sitename, 0 };
2172 alarm(inndcomm_flush_timeout);
2173 r= ICCopen(); if (r) inndcommfail("connect");
2174 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2175 if (!r) exit(0); /* yay! */
2177 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2178 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2179 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2183 int sentinel_fd= pipefds[0];
2184 on_fd_read_except(sentinel_fd, inndcomm_event);
2186 SMS(FLUSHING, 0, why);
2189 /*========== main program ==========*/
2191 static void postfork_inputfile(InputFile *ipf) {
2193 assert(ipf->fd >= 0);
2198 static void postfork_conns(Connection *conn) {
2205 static void postfork_stdio(FILE *f) {
2206 /* we have no stdio streams that are buffered long-term */
2210 static void postfork(const char *what) {
2211 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2212 sysdie("%s child: failed to reset SIGPIPE");
2214 postfork_inputfile(main_input_file);
2215 postfork_inputfile(flushing_input_file);
2216 postfork_conns(idle.head);
2217 postfork_conns(working.head);
2218 postfork_conns(full.head);
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] queue=%d until_connect=%d"
2251 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_FMT(flushing)
2252 " conns idle=%d working=%d full=%d"
2253 " children connecting=%ld inndcomm_child"
2255 sms_names[sms], sm_period_counter, queue.count, until_connect,
2256 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2257 idle.count, working.count, full.count,
2258 (long)connecting_child, (long)inndcomm_child
2261 if (until_connect) until_connect--;
2263 poll_backlog_file();
2264 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2265 statemc_period_poll();
2266 check_master_queue();
2270 /*========== option parsing ==========*/
2273 of_seconds= 001000u;
2274 of_boolean= 002000u;
2277 typedef struct Option Option;
2278 typedef void OptionParser(const Option*, const char *val);
2288 void op_integer(const Option *o, const char *val) {
2291 unsigned long ul= strtoul(val,&ep,10);
2292 if (*ep || ep==val || errno || ul>INT_MAX)
2293 badusage("bad integer value for %s",o->long);
2294 int *store= o->store;
2298 void op_double(const Option *o, const char *val) {
2299 int *store= o->store;
2302 *store= strtod(val, &ep);
2303 if (*ep || ep==val || errno)
2304 badusage("bad floating point value for %s",o->long);
2307 void op_string(const Option *o, const char *val) {
2308 char **store= o->store;
2313 void op_seconds(const Option *o, const char *val) {
2314 int *store= o->store;
2317 double v= strtod(val,&ep);
2318 if (ep==val) badusage("bad time/duration value for %s",o->long);
2320 if (!*ep || !strcmp(ep,"s")) unit= 1;
2321 else if (!strcmp(ep,"m")) unit= 60;
2322 else if (!strcmp(ep,"h")) unit= 3600;
2323 else if (!strcmp(ep,"d")) unit= 86400;
2324 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2328 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2332 void op_periods_rndup(const Option *o, const char *val) {
2333 int *store= o->store;
2335 *store += PERIOD_SECONDS-1;
2336 *store /= PERIOD_SECONDS;
2339 void op_periods_booltrue(const Option *o, const char *val) {
2340 int *store= o->store;
2343 void op_periods_boolfalse(const Option *o, const char *val) {
2344 int *store= o->store;
2348 static const Option options[]= {
2349 {'f',"feedfile", &feedfile, op_string },
2350 {'q',"quiet-multiple", &quiet_multiple, op_booltrue, 1 },
2352 { 0, "max-connections", &max_connections op_integer },
2353 { 0, "max-queue-per-conn", &max_queue_per_conn op_integer },
2356 { 0, "streaming", &try_stream, op_booltrue, 1 },
2357 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2358 {'P',"port", &port op_integer },
2359 { 0, "inndconf", &inndconffile, op_string },
2360 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2361 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2363 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2364 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2366 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2367 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2368 { 0, "connection-timeout", &connection_timeout, op_seconds },
2369 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2372 int main(int argc, char **argv) {
2378 if (*arg != '-') break;
2379 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2381 while ((a= *++arg)) {
2385 char *equals= strchr(arg,'=');
2386 int len= equals ? (equals - arg) : strlen(arg);
2387 for (o=options; o->long; o++)
2388 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2390 badusage("unknown long option --%s",arg);
2393 if (equals) badusage("option --%s does not take a value",o->long);
2395 } else if (equals) {
2399 if (!arg) badusage("option --%s needs a value",o->long);
2402 break; /* eaten the whole argument now */
2404 for (o=options; o->long; o++)
2407 badusage("unknown short option -%c",a);
2414 if (!arg) badusage("option -%c needs a value",o->short);
2417 break; /* eaten the whole argument now */
2422 if (!arg) badusage("need site name argument");
2428 if (*++argv) badusage("too many non-option arguments");
2430 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2431 badusage("nocheck threshold percentage must be between 0..100");
2432 nocheck_thresh= nocheck_thresh_pct * 0.01;
2434 if (nocheck_decay_articles < 0.1)
2435 badusage("nocheck decay articles must be at least 0.1");
2436 nocheck_decay= 1 - 1/nocheck_decay_articles;
2439 pathoutgoing= innconf->pathoutgoing;
2440 innconf_read(inndconffile);
2443 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2444 else if (!feedfile[0])
2445 badusage("feed filename must be nonempty");
2446 else if (feedfile[strlen(feedfile)-1]=='/')
2447 feedfile= xasprintf("%s%s",feedfile,sitename);
2449 const char *feedfile_forbidden= "?*[~#";
2451 while ((c= *feedfile_forbidden++))
2452 if (strchr(feedfile, c))
2453 badusage("feed filename may not contain metacharacter %c",c);
2455 loop= oop_sys_new();
2456 if (!loop) sysdie("could not create liboop event loop");
2458 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2459 sysdie("could not ignore SIGPIPE");
2461 if (become_daemon) {
2462 for (i=3; i<255; i++)
2463 /* do this now before we open syslog, etc. */
2465 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2467 int null= open("/dev/null",O_RDWR);
2468 if (null<0) sysdie("failed to open /dev/null");
2474 pid_t child1= xfork("daemonise first fork");
2475 if (child1) _exit(0);
2477 pid_t sid= setsid();
2478 if (sid != child1) sysdie("setsid failed");
2480 pid_t child2= xfork("daemonise second fork");
2481 if (child2) _exit(0);
2486 if (!filemon_init()) {
2487 warn("no file monitoring available, polling");
2488 filepoll_schedule();