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 ==============================*/
157 #include <sys/types.h>
158 #include <sys/wait.h>
159 #include <sys/stat.h>
160 #include <sys/socket.h>
170 #include <oop-read.h>
172 /*----- general definitions, probably best not changed -----*/
174 #define PERIOD_SECONDS 60
176 #define CONNCHILD_ESTATUS_STREAM 4
177 #define CONNCHILD_ESTATUS_NOSTREAM 5
179 #define INNDCOMMCHILD_ESTATUS_FAIL 6
180 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
182 /*----- doubly linked lists -----*/
184 #define ISNODE(T) struct { T *succ, *pred; } node
185 #define DEFLIST(T) typedef struct { T *head, *tail, *tp; int count; } T##List
187 #define NODE(n) ((struct node*)&(n)->node)
189 #define LIST_ADDHEAD(l,n) \
190 (list_addhead((struct list*)&(l), NODE((n))), (void)(l).count++)
191 #define LIST_ADDTAIL(l,n) \
192 (list_addtail((struct list*)&(l), NODE((n))), (void)(l).count++)
194 #define LIST_REMHEAD(l) \
195 ((l).count ? ((l).count--, (void*)list_remhead((struct list*)&(l))) : 0)
196 #define LIST_REMTAIL(l) \
197 ((l).count ? ((l).count--, (void*)list_remtail((struct list*)&(l))) : 0)
198 #define LIST_REMOVE(l,n) \
199 (list_remove(NODE((n))), (void)(l).count--)
200 #define LIST_INSERT(l,n,pred) \
201 (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
203 /*----- type predeclarations -----*/
205 typedef struct Conn Conn;
206 typedef struct Article Article;
207 typedef enum StateMachineState StateMachineState;
212 /*----- function predeclarations -----*/
214 static void conn_check_work(Conn *conn);
216 static int filemon_init(void);
217 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
218 static void filemon_callback(void);
220 static void conn_assign_one_article(ConnList *connlist, Conn **last_assigned);
221 static void statemc_setstate(StateMachineState newsms, int periods,
222 const char *forlog, const char *why);
223 static void check_master_queue(void);
225 /*----- configuration options -----*/
227 static char *sitename, *feedfile;
228 static const char *remote_host;
229 static int quiet_multiple=0, become_daemon=1;
231 static int max_connections=10, max_queue_per_conn=200;
233 static int connection_setup_timeout=200, port=119, try_stream=1;
234 static int inndcomm_flush_timeout=100;
235 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
236 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
237 static const char *inndconffile;
239 static double accept_proportion;
240 static double nocheck_thresh_pct= 95.0;
241 static double nocheck_thresh; /* computed in main from _pct */
242 static double nocheck_decay_articles= 100; /* converted to _decay */
243 static double nocheck_decay; /* computed in main from _articles */
244 static int nocheck, nocheck_reported;
247 /*----- statistics -----*/
249 typedef enum { /* in queue in conn->sent */
250 art_Unchecked, /* not checked, not sent checking */
251 art_Wanted, /* checked, wanted sent body as requested */
252 art_Unsolicited, /* - sent body without check */
256 #define RESULT_COUNTS(RCS,RCN) \
264 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
265 #define RCI_TRIPLE_VALS_BASE(counts,x) \
266 , counts[art_Unchecked] x \
267 + counts[art_Wanted] x \
268 + counts[art_Unsolicited] x, \
269 counts[art_Unchecked] x \
270 , counts[art_Wanted] x \
271 , counts[art_Unsolicited] x
274 #define RC_INDEX(x) RCI_##x,
275 RESULT_COUNTS(RC_INDEX, RC_INDEX)
280 /*----- transmission buffers -----*/
285 xk_Malloc, xk_Const, xk_Artdata
297 /*----- core operational data structure types -----*/
299 typedef struct InputFile {
300 /* This is an instance of struct oop_readable */
301 struct oop_readable readable; /* first */
302 oop_readable_call *readable_callback;
303 void *readable_callback_user;
306 struct Filemon_Perfile *filemon;
309 long inprogress; /* no. of articles read but not processed */
312 int counts[art_MaxState][RCI_max];
327 #define SMS_LIST(X) \
335 enum StateMachineState {
336 #define SMS_DEF_ENUM(s) sm_##s,
337 SMS_LIST(SMS_DEF_ENUM)
340 static const char *sms_names[]= {
341 #define SMS_DEF_NAME(s) #s ,
342 SMS_LIST(SMS_DEF_NAME)
348 int fd, max_queue, stream;
349 ArticleList queue; /* not yet told peer, or CHECK said send it */
350 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
351 struct iovec xmit[CONNIOVS];
352 XmitDetails xmitd[CONNIOVS];
357 /*----- operational variables -----*/
359 static oop_source *loop;
361 static int nconns, until_connect;
362 static ConnList idle, working, full;
363 static ArticleList queue;
365 static char *path_lock, *path_flushing, *path_defer;
367 #define SMS(newstate, periods, why) \
368 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
370 static StateMachineState sms;
372 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
373 static int sm_period_counter;
376 /*========== logging ==========*/
378 static void logcore(int sysloglevel, const char *fmt, ...)
379 __attribute__((__format__(printf,2,3)));
380 static void logcore(int sysloglevel, const char *fmt, ...) {
384 vsyslog(sysloglevel,fmt,al);
386 vfprintf(stderr,fmt,al);
392 static void logv(int sysloglevel, const char *pfx, int errnoval,
393 int exitstatus, const char *fmt, va_list al)
394 __attribute__((__format__(printf,5,0)));
395 static void logv(int sysloglevel, const char *pfx, int errnoval,
396 int exitstatus, const char *fmt, va_list al) {
398 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
399 msgbuf[sizeof(msgbuf)-1]= 0;
401 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
402 sysloglevel= LOG_ERR; /* run by wrong user, probably */
404 logcore(sysloglevel, "<%s>%s: %s%s%s",
405 sitename, pfx, msgbuf,
406 errnoval>=0 ? ": " : "",
407 errnoval>=0 ? strerror(errnoval) : "");
410 #define logwrap(fn, pfx, sysloglevel, err, estatus) \
411 static void fn(const char *fmt, ...) \
412 __attribute__((__format__(printf,1,2))); \
413 static void fn(const char *fmt, ...) { \
416 logv(sysloglevel, pfx, err, estatus, fmt, al); \
419 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
420 logwrap(die, " critical", LOG_CRIT, -1, 16);
422 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
423 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
425 logwrap(syswarn, " warning", LOG_WARNING, errno, 0);
426 logwrap(warn, " warning", LOG_WARNING, -1, 0);
428 logwrap(notice, "", LOG_NOTICE, -1, 0);
429 logwrap(info, " info", LOG_INFO, -1, 0);
430 logwrap(debug, " debug", LOG_DEBUG, -1, 0);
433 /*========== utility functions etc. ==========*/
435 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
437 static void *xmalloc(size_t sz) {
441 sysdie("malloc (%ld bytes) failed", (unsigned long)sz);
444 static pid_t xfork(const char *what) {
448 if (child==-1) sysdie("cannot fork for %s",what);
449 if (!child) postfork(what);
450 debug("forked %s %ld", what, (unsigned long)child);
454 static void on_fd_read_except(int fd, oop_call_fd callback) {
455 loop->on_fd(loop, fd, OOP_READ, callback, 0);
456 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
458 static void cancel_fd_read_except(int fd) {
459 loop->cancel_fd(loop, fd, OOP_READ);
460 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
463 static void report_child_status(const char *what, int status) {
464 if (WIFEXITED(status)) {
465 int es= WEXITSTATUS(status);
467 warn("%s: child died with error exit status %d",es);
468 } else if (WIFSIGNALED(status)) {
469 int sig= WTERMSIG(status);
470 const char *sigstr= strsignal(sig);
471 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
473 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
475 warn("%s: child died due to unknown fatal signal %d%s",
476 what, sig, coredump);
478 warn("%s: child died with unknown wait status %d", status);
482 static int xwaitpid(pid_t *pid, const char *what) {
485 int r= kill(*pid, SIGKILL);
486 if (r) sysdie("cannot kill %s child", what);
488 pid_t got= waitpid(*pid, &status, WNOHANG);
489 if (got==-1) sysdie("cannot reap %s child", what);
496 static void xunlink(const char *path, const char *what) {
498 if (r) sysdie("can't unlink %s %s", path, what);
501 static void check_isreg(const struct stat *stab, const char *path,
503 if (!S_ISREG(stab->st_mode))
504 die("%s %s not a plain file (mode 0%lo)",
505 what, path, (unsigned long)stab->st_mode);
508 static void xfstat(int fd, struct stat *stab_r, const char *what) {
509 int r= fstab(fd, stab_r);
510 if (r) sysdie("could not fstat %s", what);
513 static void xfstat_isreg(int fd, struct stat *stab_r,
514 const char *path, const char *what) {
515 xfstat(fd, stab_r, what);
516 check_isreg(stab_r, path, what);
519 static void xlstat_isreg(const char *path, struct stat *stab,
520 int *enoent_r /* 0 means ENOENT is fatal */,
522 int r= lstat(path, stab);
524 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
525 sysdie("could not lstat %s %s", what, path);
527 if (enoent_r) *enoent_r= 0;
528 check_isreg(stab, path, what);
531 static void setnonblock(int fd, int nonblocking) {
532 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
533 if (nonblocking) r |= O_NONBLOCK;
534 else r &= ~O_NONBLOCK;
535 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
538 static int samefile(const struct stat *a, const struct stat *b) {
539 assert(S_ISREG(a->st_mode));
540 assert(S_ISREG(b->st_mode));
541 return (a->st_ino == b->st_ino &&
542 a->st_dev == b->st_dev);
545 /*========== making new connections ==========*/
547 static int connecting_sockets[2]= {-1,-1};
548 static pid_t connecting_child;
550 static void connect_attempt_discard(void) {
551 if (connecting_sockets[0])
552 cancel_fd(connecting_sockets[0]);
554 perhaps_close(&connecting_sockets[0]);
555 perhaps_close(&connecting_sockets[1]);
557 if (connecting_child) {
558 int r= kill(connecting_child, SIGTERM);
559 if (r) syswarn("failed to kill connecting child");
560 int status= xwaitpid(&connecting_child, "connect");
562 if (!(WIFEXITED(status) ||
563 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
564 report_child_status("connect", status);
568 #define PREP_DECL_MSG_CMSG(msg) \
570 memset(&msg,0,sizeof(msg)); \
571 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
572 msg.msg_control= msg##cbuf; \
573 msg.msg_controllen= sizeof(msg##cbuf);
575 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
578 conn= xmalloc(sizeof(*conn));
579 memset(conn,0,sizeof(*conn));
581 PREP_DECL_MSG_CMSG(msg);
582 struct cmsghdr *h= 0;
583 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
584 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
587 pid_t got= waitpid(connecting_child, &status, WNOHANG);
589 assert(got==connecting_child);
591 if (WIFEXITED(status) &&
592 (WEXITSTATUS(status) != 0 &&
593 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
594 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
595 /* child already reported the problem */
596 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
597 warn("connect: connection attempt timed out");
598 } else if (!WIFEXITED(status)) {
599 report_child_status("connect", status);
600 /* that's probably the root cause then */
603 /* child is still running apparently, report the socket problem */
605 syswarn("connect: read from child socket failed");
606 else if (e == OOP_EXCEPTION)
607 warn("connect: unexpected exception on child socket");
609 warn("connect: unexpected EOF on child socket");
614 #define CHK(field, val) \
615 if (h->cmsg_##field != val) { \
616 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
619 CHK(level, SOL_SOCKET);
620 CHK(type, SCM_RIGHTS);
621 CHK(len, CMSG_LEN(sizeof(conn->fd)));
624 if (CMSG_NXTHDR(&msg,h)) { die("connect: child sent many cmsgs"); goto x; }
626 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
629 pid_t got= waitpid(connecting_child, &status, 0);
630 if (got==-1) sysdie("connect: real wait for child");
631 assert(got == connecting_child);
634 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
635 int es= WEXITSTATUS(status);
637 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
638 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
640 fatal("connect: child gave unexpected exit status %d", es);
643 setnonblocking(conn->fd, 1);
646 LIST_ADDHEAD(idle, conn);
647 notice("#%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
648 connect_attempt_discard();
649 check_master_queue();
654 perhaps_close(&conn->fd);
657 connect_attempt_discard();
660 static void connect_start(void) {
661 assert(!connecting_sockets[0]);
662 assert(!connecting_sockets[1]);
663 assert(!connecting_child);
665 notice("starting connection attempt");
667 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
668 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
670 connecting_child= xfork("connection");
672 if (!connecting_child) {
673 FILE *cn_from, *cn_to;
674 char buf[NNTP_STRLEN+100];
675 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
677 r= close(connecting_sockets[0]);
678 if (r) sysdie("connect: close parent socket in child");
680 alarm(connection_setup_timeout);
681 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
683 sanitise_inplace(buf);
684 fatal("connect: rejected: %s", buf);
686 sysfatal("connect: connection attempt failed");
689 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
690 sysfatal("connect: authentication failed");
692 if (fputs("MODE STREAM\r\n", cn_to) ||
694 sysfatal("connect: could not send MODE STREAM");
695 buf[sizeof(buf)-1]= 0;
696 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
698 sysfatal("connect: could not read response to MODE STREAM");
700 fatal("connect: connection close in response to MODE STREAM");
705 sanitise_inplace(buf);
706 fatal("connect: response to MODE STREAM is too long: %.100s...",
709 l--; if (l>0 && buf[l-1]=='\r') l--;
712 int rcode= strtoul(buf,&ep,10);
714 sanitise_inplace(buf);
715 fatal("connect: bad response to MODE STREAM: %.50s", buf);
719 exitstatus= CONNCHILD_ESTATUS_STREAM;
725 sanitise_inplace(buf);
726 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
731 int fd= fileno(cn_from);
733 PREP_DECL_MSG_CMSG(msg);
734 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
735 cmsg->cmsg_level= SOL_SOCKET;
736 cmsg->cmsg_type= SCM_RIGHTS;
737 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
738 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
740 msg.msg_controllen= cmsg->cmsg_len;
741 r= sendmsg(connecting_sockets[1], &msg, 0);
742 if (r) sysdie("sendmsg failed for new connection");
747 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
748 if (r) sysdie("connect: close child socket in parent");
750 on_fd_read_except(connecting_sockets[0], connchild_event);
754 connect_attempt_discard();
758 /*========== overall control of article flow ==========*/
760 static void check_master_queue(void) {
764 Conn *last_assigned=0;
767 conn_assign_one_article(&working, &last_assigned);
768 } else if (idle.head) {
769 conn_assign_one_article(&idle, &last_assigned);
770 } else if (nconns < max_connections && queue.count >= max_queue_per_conn &&
771 !connecting_child && !until_connect) {
772 until_connect= reconnect_delay_periods;
778 conn_check_work(last_assigned);
781 static void conn_assign_one_article(ConnList *connlist, Conn **last_assigned) {
782 Conn *conn= connlist->head;
784 LIST_REMOVE(*connlist, conn);
785 Article *art= LIST_REMHEAD(queue);
786 LIST_ADDTAIL(conn->queue, art);
787 LIST_ADD(*conn_determine_right_list(conn), conn);
789 /* This slightly odd arrangement is so that we call conn_check_work
790 * once after filling the queue for a new connection in
791 * check_master_queue, rather than for each article. */
792 if (conn != *last_assigned && *last_assigned)
793 conn_check_work(*last_assigned);
794 *last_assigned= conn;
797 static int conn_total_queued_articles(Conn *conn) {
798 return conn->sent.count + conn->queue.count;
801 static ConnList *conn_determine_right_list(Conn *conn) {
802 int inqueue= conn_total_queued_articles(conn);
803 assert(inqueue <= max_queue);
804 if (inqueue == 0) return &idle;
805 if (inqueue == conn->max_queue) return &full;
809 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
814 static void conn_check_work(Conn *conn) {
817 conn_make_some_xmits(conn);
819 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
823 void *rp= conn_write_some_xmits(conn);
824 if (rp==OOP_CONTINUE) {
825 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
827 } else if (rp==OOP_HALT) {
830 /* transmitted everything */
837 static void vconnfail(Conn *conn, const char *fmt, va_list al)
838 __attribute__((printf,2,0));
840 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
841 int requeue[art_MaxState];
844 while ((art= LIST_REMHEAD(conn->queue))) LIST_ADDTAIL(queue);
845 while ((art= LIST_REMHEAD(conn->sent))) {
846 counts[art->state]++;
847 if (art->state==art_Unsolicited) art->state= art_Unchecked;
853 for (i=0, dp=&conn->xmitd; i<conn->xmitu; i++, dp++)
856 char *m= xvasprintf(fmt,al);
857 warn("#%d connection failed, requeueing " RCI_TRIPLE_FMT_BASE ": %s",
858 conn->fd, RCI_TRIPLE_FMT_VALS(requeue, /*nothing*/), m);
864 until_connect= reconnect_delay_periods;
865 check_master_queue();
868 static void connfail(Connection *conn, const char *fmt, ...)
869 __attribute__((printf,2,3));
870 static void connfail(Connection *conn, const char *fmt, ...) {
877 /*========== article transmission ==========*/
879 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
880 XmitKind kind) { /* caller must then fill in details */
881 struct iovec *v= &conn->xmit[conn->xmitu];
882 XmitDetails *d= &conn->xmitd[conn->xmitu++];
889 static void xmit_noalloc(Conn *conn, const char *data, int len) {
890 xmit_core(conn,data,len, xk_Const);
892 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
894 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
895 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
899 static void xmit_free(XmitDetails *d) {
901 case xk_Malloc: free(d->info.malloc_tofree); break;
902 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
903 case xk_Const: break;
908 static void *conn_write_some_xmits(Conn *conn) {
910 * 0: nothing more to write, no need to call us again
911 * OOP_CONTINUE: more to write but fd not writeable
912 * OOP_HALT: disaster, have destroyed conn
915 int count= conn->xmitu;
916 if (!count) return 0;
918 if (count > IOV_MAX) count= IOV_MAX;
919 ssize_t rs= writev(conn->fd, conn->xmit, count);
921 if (errno == EAGAIN) return OOP_CONTINUE;
922 connfail(conn, "write failed: %s", strerror(errno));
927 for (done=0; rs && done<xmitu; done++) {
928 struct iovec *vp= &conn->xmit[done];
929 XmitDetails *dp= &conn->xmitd[done];
930 if (rs > vp->iov_len) {
938 int newu= conn->xmitu - done;
939 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
940 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
945 static void conn_make_some_xmits(Conn *conn) {
947 if (conn->xmitu+5 > CONNIOVS)
950 Article *art= LIST_REMHEAD(queue);
953 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
954 /* actually send it */
956 ARTHANDLE *artdata= SMretrieve();
960 XMIT_LITERAL("TAKETHIS ");
961 xmit_noalloc(conn, art->mid, art->midlen);
962 XMIT_LITERAL("\r\n");
963 xmit_artbody(conn, artdata);
966 /* we got 235 from IHAVE */
968 xmit_artbody(conn, artdata);
970 XMIT_LITERAL(".\r\n");
975 art->state == art_Unchecked ? art_Unsolicited :
976 art->state == art_Wanted ? art_Wanted :
978 art->ipf->counts[art->state].sent++;
979 LIST_ADDTAIL(conn->sent, art);
985 XMIT_LITERAL("IHAVE ");
987 XMIT_LITERAL("CHECK ");
988 xmit_noalloc(art->mid, art->midlen);
989 XMIT_LITERAL("\r\n");
991 assert(art->state == art_Unchecked);
992 art->ipf->counts[art->state].sent++;
993 LIST_ADDTAIL(conn->sent, art);
999 /*========== handling responses from peer ==========*/
1001 static const oop_rd_style peer_rd_style= {
1002 OOP_RD_DELIM_STRIP, '\n',
1004 OOP_RD_SHORTREC_FORBID
1007 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1008 const char *errmsg, int errnoval,
1009 const char *data, size_t recsz, void *conn_v) {
1011 connfail(conn, "error receiving from peer: %s", errmsg);
1012 return OOP_CONTINUE;
1015 static Article *article_reply_check(Connection *conn, const char *response,
1016 int code_indicates_streaming,
1018 /* 1:yes, -1:no, 0:dontcare */,
1019 const char *sanitised_response) {
1020 Article *art= conn->sent.head;
1024 "peer gave unexpected response when no commands outstanding: %s",
1025 sanitised_response);
1029 if (code_indicates_streaming) {
1030 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1031 if (!conn->stream) {
1032 connfail("peer gave streaming response code "
1033 " to IHAVE or subsequent body: %s", sanitised_response);
1036 const char *got_mid= response+4;
1037 int got_midlen= strcspn(got_mid, " \n\r");
1038 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1039 connfail("peer gave streaming response with syntactically invalid"
1040 " messageid: %s", sanitised_response);
1043 if (got_midlen != art->midlen ||
1044 memcmp(got_mid, art->messageid, got_midlen)) {
1045 connfail("peer gave streaming response code to wrong article -"
1046 " probable synchronisation problem; we offered: %s;"
1048 art->messageid, sanitised_response);
1053 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
1054 sanitised_response);
1059 if (must_have_sent>0 && art->state < art_Wanted) {
1060 connfail("peer says article accepted but we had not sent the body: %s",
1061 sanitised_response);
1064 if (must_have_sent<0 && art->state >= art_Wanted) {
1065 connfail("peer says please sent the article but we just did: %s",
1066 sanitised_response);
1070 Article *art_again= LIST_REMHEAD(conn->sent);
1071 assert(art_again == art);
1075 static void update_nocheck(int accepted) {
1076 accept_proportion *= accept_decay;
1077 accept_proportion += accepted;
1078 int new_nocheck= accept_proportion >= nocheck_thresh;
1079 if (new_nocheck && !nocheck_reported) {
1080 notice("entering nocheck mode for the first time");
1081 nocheck_reported= 1;
1082 } else if (new_nocheck != nocheck) {
1083 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1085 nocheck= new_nocheck;
1088 static void article_done(Connection *conn, Article *art, int whichcount) {
1089 art->ipf->counts[art->state][whichcount]++;
1090 if (whichcount == RC_accepted) update_nocheck(1);
1091 else if (whichcount == RC_unwanted) update_nocheck(0);
1093 InputFile *ipf= art->ipf;
1094 while (art->blanklen) {
1095 static const char spaces[]=
1100 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1101 int r= pwrite(ipf->fd, spaces, w, art->offset);
1103 if (errno==EINTR) continue;
1104 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1105 art->messageid, art->blanklen, art->offset, ipf->path);
1107 assert(r>=0 && r<=w);
1113 assert(ipf->inprogress >= 0);
1115 if (!ipf->inprogress && ipf != main_input_file)
1116 queue_check_input_done();
1121 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1122 const char *errmsg, int errnoval,
1123 const char *data, size_t recsz, void *conn_v) {
1126 if (ev == OOP_RD_EOF) {
1127 connfail(conn, "unexpected EOF from peer");
1128 return OOP_CONTINUE;
1130 assert(ev == OOP_RD_OK);
1133 unsigned long code= strtoul(data, &ep, 10);
1134 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1136 const char *p= data;
1140 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
1142 if (!c) { *q++= '\''; break; }
1143 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
1144 sprintf(q,"\\x%02x",c);
1147 connfail(conn, "badly formatted response from peer: %s", sanibuf);
1148 return OOP_CONTINUE;
1151 if (conn->quitting) {
1153 connfail(conn, "peer gave failure response to QUIT: %s", sani);
1154 return OOP_CONTINUE;
1162 #define GET_ARTICLE(musthavesent) \
1163 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1164 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1166 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1167 code_streaming= (streaming) \
1168 GET_ARTICLE(musthavesent); \
1169 article_done(conn, art, RC_##how); break;
1171 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1173 int code_streaming= 0;
1177 case 400: PEERBADMSG("peer stopped accepting articles");
1178 case 503: PEERBADMSG("peer timed us out");
1179 default: PEERBADMSG("peer sent unexpected message");
1181 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1182 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1184 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1185 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1187 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1188 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1190 case 238: /* CHECK says send it */
1192 case 335: /* IHAVE says send it */
1194 assert(art->state == art_Unchecked);
1195 art->ipf->counts[art->state].accepted++;
1196 art->state= art_Wanted;
1197 LIST_ADDTAIL(conn->queue);
1200 case 431: /* CHECK or TAKETHIS says try later */
1202 case 436: /* IHAVE says try later */
1205 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1207 sysfatal("write to defer file %s",path_defer);
1208 article_done(conn, art, RC_deferred);
1213 check_check_work(conn);
1214 return OOP_CONTINUE;
1218 /*========== monitoring of input files ==========*/
1220 static void feedfile_eof(InputFile *ipf) {
1221 assert(ipf != main_input_file); /* promised by tailing_try_read */
1223 inputfile_tailing_stop(ipf);
1224 assert(ipf->fd >= 0);
1225 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1228 if (ipf == flushing_input_file) {
1229 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1230 if (main_input_file) inputfile_tailing_start(main_input_file);
1231 statemc_check_flushing_done();
1232 } else if (ipf == backlog_input_file) {
1233 statemc_check_backlog_done();
1235 abort(); /* supposed to wait rather than get EOF on main input file */
1239 static InputFile *open_input_file(const char *path) {
1240 int fd= open(path, O_RDONLY);
1242 if (errno==ENOENT) return 0;
1243 sysfatal("unable to open input file %s", path);
1246 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1247 memset(ipf,0,sizeof(*ipf));
1249 ipf->readable.on_readable= tailing_on_readable;
1250 ipf->readable.on_cancel= tailing_on_cancel;
1251 ipf->readable.try_read= tailing_try_read;
1254 strcpy(ipf->path, path);
1259 static void close_input_file(InputFile *ipf) {
1260 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1261 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1262 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1263 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1266 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1270 /*---------- dealing with articles read in the input file ----------*/
1272 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1273 oop_rd_event ev, const char *errmsg,
1275 const char *data, size_t recsz,
1277 InputFile *ipf= ipf_v;
1279 char tokentextbuf[sizeof(TOKEN)*2+3];
1281 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1283 if (data[0] && data[0]!=' ') {
1284 char *space= strchr(data,' ');
1285 int tokenlen= space-data;
1286 int midlen= (int)recsz-tokenlen-1;
1287 if (midlen < 0) goto bad_data;
1289 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1290 memcpy(tokentextbuf, data, tokenlen);
1291 tokentextbuf[tokenlen]= 0;
1292 if (!IsToken(tokentextbuf)) goto bad_data;
1294 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1295 art->offset= ipf->offset;
1296 art->blanklen= recsz;
1297 art->midlen= midlen;
1298 art->state= art_Unchecked;
1299 art->ipf= ipf; ipf->inprogress++;
1300 art->token= TextToToken(tokentextbuf);
1301 strcpy(art->messageid, space+1);
1302 LIST_ADDTAIL(queue, art);
1304 ipf->offset += recsz + 1;
1306 if (sms==sm_NORMAL && ipf==main_input_file &&
1307 ipf->offset >= flush_threshold)
1308 statemc_start_flush("feed file size");
1310 check_master_queue();
1313 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1314 assert(sms == sm_NORMAL);
1316 debug("starting flush (%s) (%lu >= %lu) (%d)",
1318 (unsigned long)ipf->offset, (unsigned long)flush_threshold,
1321 int r= link(feedfile, duct_path);
1322 if (r) sysdie("link feedfile %s to flushing file %s", feedfile,
1326 xunlink(feedfile, "old feedfile link");
1329 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1332 /*========== tailing input file ==========*/
1334 static void filemon_start(InputFile *ipf) {
1335 assert(!ipf->filemon);
1337 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1338 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1339 filemon_method_startfile(ipf, ipf->filemon);
1342 static void filemon_stop(InputFile *ipf) {
1343 if (!ipf->filemon) return;
1344 filemon_method_stopfile(ipf, ipf->filemon);
1349 static void filemon_callback(InputFile *ipf) {
1350 ipf->readable_callback(ipf->readable_callback_user);
1353 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1355 InputFile *ipf= user;
1356 return ipf->readable_callback(ipf->readable_callback_user);
1359 static void on_cancel(struct oop_readable *rable) {
1360 InputFile *ipf= (void*)rable;
1362 if (ipf->filemon) filemon_stopfile(ipf);
1363 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1364 ipf->readable_callback= 0;
1367 static void tailing_queue_readable(InputFile *ipf) {
1368 /* lifetime of ipf here is OK because destruction will cause
1369 * on_cancel which will cancel this callback */
1370 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1373 static int tailing_on_readable(struct oop_readable *rable,
1374 oop_readable_call *cb, void *user) {
1375 InputFile *ipf= (void*)rable;
1377 tailing_on_cancel(rable);
1378 ipf->readable_callback= cb;
1379 ipf->readable_callback_user= user;
1380 filemon_startfile(ipf);
1382 tailing_queue_readable(ipf);
1386 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1388 InputFile *ipf= (void*)rable;
1390 ssize_t r= read(ipf->fd, buffer, length);
1392 if (errno==EINTR) continue;
1396 if (ipf==main_input_file) {
1399 } else if (ipf==flushing_input_file) {
1401 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1402 } else if (ipf==backlog_input_file) {
1412 /*---------- filemon implemented with inotify ----------*/
1414 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1415 #define HAVE_FILEMON
1417 #include <linux/inotify.h>
1419 static int filemon_inotify_fd;
1420 static int filemon_inotify_wdmax;
1421 static InputFile **filemon_inotify_wd2ipf;
1423 typedef struct Filemon_Perfile {
1425 } Filemon_Inotify_Perfile;
1427 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1428 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1429 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1431 if (wd >= filemon_inotify_wdmax) {
1433 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1434 sizeof(*filemon_inotify_wd2ipf) * newmax);
1435 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1436 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1437 filemon_inotify_wdmax= newmax;
1440 assert(!filemon_inotify_wd2ipf[wd]);
1441 filemon_inotify_wd2ipf[wd]= ipf;
1443 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1444 ipf, wd, filemon_inotify_wdmax);
1449 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1451 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1452 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1453 if (r) sysdie("inotify_rm_watch");
1454 filemon_inotify_wd2ipf[wd]= 0;
1457 static void *filemon_inotify_readable(oop_source *lp, int fd,
1458 oop_event e, void *u) {
1459 struct inotify_event iev;
1461 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1463 if (errno==EAGAIN) break;
1464 sysdie("read from inotify master");
1465 } else if (r==sizeof(iev)) {
1466 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1468 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1470 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1471 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1472 filemon_callback(ipf);
1474 return OOP_CONTINUE;
1477 static int filemon_method_init(void) {
1478 filemon_inotify_fd= inotify_init();
1479 if (filemon_inotify_fd<0) {
1480 syswarn("could not initialise inotify: inotify_init failed");
1484 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1486 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1490 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1492 /*---------- filemon dummy implementation ----------*/
1494 #if !defined(HAVE_FILEMON)
1496 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1498 static int filemon_method_init(void) { return 0; }
1499 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1500 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1502 #endif /* !HAVE_FILEMON */
1504 /*---------- interface to start and stop an input file ----------*/
1506 static const oop_rd_style feedfile_rdstyle= {
1507 OOP_RD_DELIM_STRIP, '\n',
1509 OOP_RD_SHORTREC_EOF,
1512 static void inputfile_tailing_start(InputFile *ipf) {
1514 ipf->readable->on_readable= tailing_on_readable;
1515 ipf->readable->on_cancel= tailing_on_cancel;
1516 ipf->readable->try_read= tailing_try_read;
1517 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1518 ipf->readable->delete_kill= 0;
1520 ipf->readable_callback= 0;
1521 ipf->readable_callback_user= 0;
1523 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1526 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1527 feedfile_got_article,ipf, feedfile_problem,ipf);
1528 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1531 static void inputfile_tailing_stop(InputFile *ipf) {
1533 oop_rd_cancel(ipf->rd);
1534 oop_rd_delete(ipf->rd);
1536 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1540 /*========== interaction with innd - state machine ==========*/
1542 /* See official state diagram at top of file. We implement
1553 |`---------------------------------------------------.
1555 |`---------------- - - - |
1556 D ENOENT | D EXISTS see OVERALL STATES diagram |
1557 | for full startup logic |
1560 | ============ try to |
1566 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1567 ^ | hardlink F to D |
1570 | | our handle onto F is now onto D |
1573 | |<-------------------<---------------------<---------+
1575 | | spawn inndcomm flush |
1577 | ================== |
1578 | FLUSHING[-ABSENT] |
1580 | main D tail/none |
1581 | ================== |
1583 | | INNDCOMM FLUSH FAILS ^
1584 | |`----------------------->----------. |
1586 | | NO SUCH SITE V |
1587 ^ |`--------------->----. ==================== |
1588 | | \ FLUSHFAILED[-ABSENT] |
1590 | | FLUSH OK \ main D tail/none |
1591 | | open F \ ==================== |
1593 | | \ | TIME TO RETRY |
1594 | |`------->----. ,---<---'\ `----------------'
1595 | | D NONE | | D NONE `----.
1597 | ============= V V ============
1598 | SEPARATED-1 | | DROPPING-1
1599 | flsh->fd>=0 | | flsh->fd>=0
1600 | [Separated] | | [Dropping]
1601 | main F idle | | main none
1602 | old D tail | | old D tail
1603 | ============= | | ============
1605 ^ | EOF ON D | | defer | EOF ON D
1607 | =============== | | ===============
1608 | SEPARATED-2 | | DROPPING-2
1609 | flsh->fd==-1 | V flsh->fd==-1
1610 | [Finishing] | | [Dropping]
1611 | main F tail | `. main none
1612 | old D closed | `. old D closed
1613 | =============== V `. ===============
1615 | | ALL D PROCESSED `. | ALL D PROCESSED
1616 | V install defer as backlog `. | install defer
1617 ^ | close D `. | close D
1618 | | unlink D `. | unlink D
1621 `----------' ==============
1641 static void statemc_init(void) {
1642 struct stat stab, stabf;
1644 path_lock= xasprintf("%s_lock", feedfile);
1645 path_flushing= xasprintf("%s_flushing", feedfile);
1646 path_defer= xasprintf("%s_defer", feedfile);
1647 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1650 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1651 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1654 memset(&fl,0,sizeof(fl));
1656 fl.l_whence= SEEK_SET;
1657 r= fcntl(lockfd, F_SETLK, &fl);
1659 if (errno==EACCES || errno==EAGAIN) {
1660 if (quiet_multiple) exit(0);
1661 fatal("another duct holds the lockfile");
1663 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1666 xfstat_isreg(lockfd, &stabf, "lockfile");
1668 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1670 if (!lock_noent && samefile(&stab, &stabf))
1674 sysdie("could not close stale lockfile %s", path_lock);
1676 debug("startup: locked");
1678 search_backlog_file();
1681 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1683 debug("startup: ductdefer ENOENT");
1685 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1686 switch (stab.st_nlink==1) {
1688 open_defer(); /* so that we will later close it and rename it */
1691 xunlink(path_defer, "stale defer file link"
1692 " (presumably hardlink to backlog file)");
1695 die("defer file %s has unexpected link count %d",
1696 path_defer, stab.st_nlink);
1700 struct stat stab_f, stab_d;
1703 InputFile *file_d= open_input_file(path_flushing);
1704 if (file_d) xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1706 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1708 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1709 debug("startup: F==D => Hardlinked");
1710 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1715 debug("startup: F ENOENT => Moved");
1716 if (file_d) startup_set_input_file(file_d);
1717 spawn_inndcomm_flush("feedfile missing at startup");
1718 /* => Flushing, sms:=FLUSHING */
1721 debug("startup: F!=D => Separated");
1722 startup_set_input_file(file_d);
1723 SMS(SEPARATED, 0, "found both old and current feed files");
1725 debug("startup: F exists, D ENOENT => Normal");
1726 FILE *file_f= open_input_file(feedfile);
1727 if (!file_f) die("feed file vanished during startup");
1728 startup_set_input_file(file_f);
1729 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1734 static void statemc_period_poll(void) {
1735 if (!sm_period_counter) return;
1736 sm_period_counter--;
1737 assert(sm_period_counter>=0);
1739 if (sm_period_counter) return;
1742 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1744 case sm_FLUSHFAILED:
1745 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1752 static void startup_set_input_file(InputFile *f) {
1753 assert(!main_input_file);
1755 inputfile_tailing_start(f);
1758 static int inputfile_is_done(InputFile *ipf) {
1760 if (ipf->inprogress) return 0; /* new article in the meantime */
1761 if (ipf->fd >= 0); return 0; /* not had EOF */
1765 static void notice_processed(InputFile *ipf, const char *what,
1767 #define RCI_NOTHING(x) /* nothing */
1768 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
1769 #define RCI_TRIPLE_VALS(x) RCI_TRIPLE_VALS_BASE(ipf->counts, .x)
1771 info("processed %s%s offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
1772 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
1775 ipf->counts[art_Unchecked].sent + ipf->counts[art_Unsolicited].sent
1776 , ipf->counts[art_Unchecked].sent, ipf->counts[art_Unsolicited].sent,
1777 ipf->counts[art_Wanted].accepted + ipf->counts[art_Unsolicited].accepted
1778 ,ipf->counts[art_Wanted].accepted,ipf->counts[art_Unsolicited].accepted
1779 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
1783 static void statemc_check_backlog_done(void) {
1784 InputFile *ipf= backlog_input_file();
1785 if (!inputfile_is_done(ipf)) return;
1787 const char *slash= strrchr(ipf->path, "/");
1788 const char *leaf= slash ? slash+1 : ipf->path;
1789 const char *under= strchr(slash, "_");
1790 const char *rest= under ? under+1 : leaf;
1791 if (!strncmp(rest,"backlog",7)) rest += 7;
1792 notice_processed(ipf,"backlog:",rest);
1794 close_input_file(ipf);
1795 if (unlink(ipf->path)) {
1796 if (errno != ENOENT)
1797 sysdie("could not unlink processed backlog file %s", ipf->path);
1798 warn("backlog file %s vanished while we were reading it"
1799 " so we couldn't remove it (but it's done now, anyway)",
1803 backlog_input_file= 0;
1804 search_backlog_file();
1808 static void statemc_check_flushing_done(void) {
1809 InputFile *ipf= flushing_input_file;
1810 if (!inputfile_is_done(ipf)) return;
1812 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1814 notice_processed(ipf,"feedfile",0);
1818 xunlink(path_flushing, "old flushing file");
1820 close_input_file(flushing_input_file);
1821 free(flushing_input_file);
1822 flushing_input_file= 0;
1824 if (sms==sm_SEPARATED) {
1825 notice("flush complete");
1826 SMS(NORMAL, 0, "flush complete");
1827 } else if (sms==sm_DROPPING) {
1828 SMS(DROPPED, 0, "old flush complete");
1829 search_backlog_file();
1830 notice("feed dropped, but will continue until backlog is finished");
1834 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
1836 assert(!inputfile_is_done(main_input_file));
1837 statemc_check_flushing_done();
1838 statemc_check_backlog_done();
1839 return OOP_CONTINUE;
1842 static void queue_check_input_done(void) {
1843 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
1846 static void statemc_setstate(StateMachineState newsms, int periods,
1847 const char *forlog, const char *why) {
1849 sm_period_counter= periods;
1851 const char *xtra= "";
1853 case sm_FLUSHING: sm_FLUSHFAILED:
1854 if (!main_input_file) xtra= "-ABSENT";
1856 case sm_SEPARATED: case sm_DROPPING:
1857 xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
1863 info("%s%s[%d] %s",forlog,xtra,periods,why);
1865 info("%s%s %s",forlog,xtra,why);
1869 /*---------- defer and backlog files ----------*/
1871 static void open_defer(void) {
1876 defer= fopen(path_defer, "a+");
1877 if (!defer) sysfatal("could not open defer file %s", path_defer);
1879 /* truncate away any half-written records */
1881 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1883 if (stab.st_size > LONG_MAX)
1884 die("defer file %s size is far too large", path_defer);
1889 long orgsize= stab.st_size;
1890 long truncto= stab.st_size;
1892 if (!truncto) break; /* was only (if anything) one half-truncated record */
1893 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1894 sysdie("seek in defer file %s while truncating partial", path_defer);
1899 sysdie("failed read from defer file %s", path_defer);
1901 die("defer file %s shrank while we were checking it!", path_defer);
1907 if (stab.st_size != truncto) {
1908 warn("truncating half-record at end of defer file %s -"
1909 " shrinking by %ld bytes from %ld to %ld",
1910 path_defer, orgsize - truncto, orgsize, truncto);
1913 sysfatal("could not flush defer file %s", path_defer);
1914 if (ftruncate(fileno(defer), truncto))
1915 sysdie("could not truncate defer file %s", path_defer);
1918 info("continuing existing defer file %s (%ld bytes)",
1919 path_defer, orgsize);
1921 if (fseek(defer, truncto, SEEK_SET))
1922 sysdie("could not seek to new end of defer file %s", path_defer);
1925 static void close_defer(void) {
1929 xfstat(fileno(defer), &stab, "defer file");
1931 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1934 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1935 (unsigned long)now.tv_sec,
1936 (unsigned long)stab.st_ino);
1937 if (link(path_defer, path_backlog))
1938 sysfatal("could not install defer file %s as backlog file %s",
1939 path_defer, backlog);
1940 if (unlink(path_defer))
1941 sysdie("could not unlink old defer link %s to backlog file %s",
1942 path_defer, backlog);
1944 if (until_backlog_nextscan < 0 ||
1945 until_backlog_nextscan > backlog_retry_minperiods + 1)
1946 until_backlog_nextscan= backlog_retry_minperiods + 1;
1949 static void poll_backlog_file(void) {
1950 if (until_backlog_nextscan < 0) return;
1951 if (until_backlog_nextscan-- > 0) return;
1952 search_backlog_file();
1955 static void search_backlog_file(void) {
1956 /* returns non-0 iff there are any backlog files */
1961 const char *oldest_path=0;
1962 time_t oldest_mtime, now;
1964 if (backlog_input_file) return 3;
1968 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
1972 sysdie("failed to expand backlog pattern %s", globpat_backlog);
1974 die("out of memory expanding backlog pattern %s", globpat_backlog);
1976 for (i=0; i<gl.gl_pathc; i++) {
1977 const char *path= gl.gl_pathv[i];
1979 if (strchr(path,'#') || strchr(path,'~')) {
1980 debug("backlog file search skipping %s", path);
1983 r= stat(path, &stab);
1985 syswarn("failed to stat backlog file %s", path);
1988 if (!S_ISREG(stab.st_mode)) {
1989 warn("backlog file %s is not a plain file (or link to one)", path);
1992 if (!oldest_path || stab.st_mtime < oldest_mtime) {
1994 oldest_mtime= stab.st_mtime;
1997 case GLOB_NOMATCH: /* fall through */
2000 sysdie("glob expansion of backlog pattern %s gave unexpected"
2001 " nonzero (error?) return value %d", globpat_backlog, r);
2007 debug("backlog scan: none");
2009 if (sms==sm_DROPPED) {
2010 notice("feed dropped and our work is complete");
2011 xunlink(path_lock, "lockfile for old feed");
2014 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2018 now= time(); if (now==-1) sysdie("time(2) failed");
2019 double age= difftime(now, oldest_mtime);
2020 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
2022 if (age_deficiency <= 0) {
2023 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2024 age, age_deficiency, oldest_path);
2026 backlog_input_file= open_input_file(oldest_path);
2027 if (!backlog_input_file) {
2028 warn("backlog file %s vanished as we opened it", backlog_input_file);
2031 inputfile_tailing_start(backlog_input_file);
2032 until_backlog_nextscan= -1;
2036 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
2038 if (backlog_spontaneous_rescan_periods >= 0 &&
2039 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2040 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2042 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2043 age, age_deficiency, until_backlog_nextscan, oldest_path);
2047 /*========== flushing the feed ==========*/
2049 static pid_t inndcomm_child;
2051 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2052 assert(inndcomm_child);
2053 int status= xwaitpid(&inndcomm_child, "inndcomm");
2054 loop->cancel_fd(fd);
2057 assert(!flushing_input_file);
2059 if (WIFEXITED(status)) {
2060 switch (WEXITSTATUS(status)) {
2062 case INNDCOMMCHILD_ESTATUS_FAIL:
2065 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2066 warn("feed has been dropped by innd, finishing up");
2067 flushing_input_file= main_input_file;
2068 tailing_queue_readable(flushing_input_file);
2069 /* we probably previously returned EAGAIN from our fake read method
2070 * when in fact we were at EOF, so signal another readable event
2071 * so we actually see the EOF */
2075 if (flushing_input_file) {
2076 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2079 SMS(DROPPED, 0, "feed dropped by innd");
2080 search_backlog_file();
2082 return OOP_CONTINUE;
2086 flushing_input_file= main_input_file;
2087 tailing_queue_readable(flushing_input_file);
2089 main_input_file= open_input_file(feedfile);
2090 if (!main_input_file)
2091 die("flush succeeded but feedfile %s does not exist!", feedfile);
2093 if (flushing_input_file) {
2094 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2097 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2099 return OOP_CONTINUE;
2102 goto unexpected_exitstatus;
2105 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2106 warn("flush timed out trying to talk to innd");
2109 unexpected_exitstatus:
2110 report_child_status("inndcomm child", status);
2114 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2117 static void inndcommfail(const char *what) {
2118 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2119 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2122 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2125 notice("flushing %s",why);
2127 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2128 assert(!inndcomm_child);
2130 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2132 inndcomm_child= xfork();
2134 if (!inndcomm_child) {
2135 static char flushargv[2]= { sitename, 0 };
2140 alarm(inndcomm_flush_timeout);
2141 r= ICCopen(); if (r) inndcommfail("connect");
2142 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2143 if (!r) exit(0); /* yay! */
2145 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2146 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2147 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2151 int sentinel_fd= pipefds[0];
2152 on_fd_read_except(sentinel_fd, inndcomm_event);
2154 SMS(FLUSHING, 0, why);
2157 /*========== main program ==========*/
2159 static void postfork_inputfile(InputFile *ipf) {
2161 assert(ipf->fd >= 0);
2166 static void postfork_conns(Connection *conn) {
2173 static void postfork_stdio(FILE *f) {
2174 /* we have no stdio streams that are buffered long-term */
2178 static void postfork(const char *what) {
2179 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2180 sysdie("%s child: failed to reset SIGPIPE");
2182 postfork_inputfile(main_input_file);
2183 postfork_inputfile(flushing_input_file);
2184 postfork_conns(idle.head);
2185 postfork_conns(working.head);
2186 postfork_conns(full.head);
2187 postfork_stdio(defer);
2190 #define EVERY(what, interval, body) \
2191 static const struct timeval what##_timeout = { 5, 0 }; \
2192 static void what##_schedule(void); \
2193 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2195 what##_schedule(); \
2197 static void what##_schedule(void) { \
2198 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2201 EVERY(filepoll, {5,0}, {
2202 if (main_input_file && main_input_file->readable_callback)
2203 filemon_callback(main_input_file);
2206 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s" \
2207 #define DEBUG_IPF(sh) \
2208 wh##_input_file, debug_ipf_path(wh##_input_file), \
2209 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2210 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2211 static const char *debug_ipf_path(InputFile *ipf) {
2212 char *slash= strrchr(ipf->path,'/');
2213 return slash ? slash+1 : ipf->path;
2216 EVERY(period, {PERIOD_SECONDS,0}, {
2218 " sms=%s[%d] queue=%d until_connect=%d"
2219 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_FMT(flushing)
2220 " conns idle=%d working=%d full=%d"
2221 " children connecting=%ld inndcomm_child"
2223 sms_names[sms], sm_period_counter, queue.count, until_connect,
2224 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2225 idle.count, working.count, full.count,
2226 (long)connecting_child, (long)inndcomm_child
2229 if (until_connect) until_connect--;
2231 poll_backlog_file();
2232 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2233 statemc_period_poll();
2234 check_master_queue();
2238 /*========== option parsing ==========*/
2241 of_seconds= 001000u;
2242 of_boolean= 002000u;
2245 typedef struct Option Option;
2246 typedef void OptionParser(const Option*, const char *val);
2256 void op_integer(const Option *o, const char *val) {
2259 unsigned long ul= strtoul(val,&ep,10);
2260 if (*ep || ep==val || errno || ul>INT_MAX)
2261 badusage("bad integer value for %s",o->long);
2262 int *store= o->store;
2266 void op_double(const Option *o, const char *val) {
2267 int *store= o->store;
2270 *store= strtod(val, &ep);
2271 if (*ep || ep==val || errno)
2272 badusage("bad floating point value for %s",o->long);
2275 void op_string(const Option *o, const char *val) {
2276 char **store= o->store;
2281 void op_seconds(const Option *o, const char *val) {
2282 int *store= o->store;
2285 double v= strtod(val,&ep);
2286 if (ep==val) badusage("bad time/duration value for %s",o->long);
2288 if (!*ep || !strcmp(ep,"s")) unit= 1;
2289 else if (!strcmp(ep,"m")) unit= 60;
2290 else if (!strcmp(ep,"h")) unit= 3600;
2291 else if (!strcmp(ep,"d")) unit= 86400;
2292 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2296 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2300 void op_periods_rndup(const Option *o, const char *val) {
2301 int *store= o->store;
2303 *store += PERIOD_SECONDS-1;
2304 *store /= PERIOD_SECONDS;
2307 void op_periods_booltrue(const Option *o, const char *val) {
2308 int *store= o->store;
2311 void op_periods_boolfalse(const Option *o, const char *val) {
2312 int *store= o->store;
2316 static const Option options[]= {
2317 {'f',"feedfile", &feedfile, op_string },
2318 {'q',"quiet-multiple", &quiet_multiple, op_booltrue, 1 },
2320 { 0, "max-connections", &max_connections op_integer },
2321 { 0, "max-queue-per-conn", &max_queue_per_conn op_integer },
2324 { 0, "streaming", &try_stream, op_booltrue, 1 },
2325 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2326 {'P',"port", &port op_integer },
2327 { 0, "inndconf", &inndconffile, op_string },
2328 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2329 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2331 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2332 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2334 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2335 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2336 { 0, "connection-timeout", &connection_timeout, op_seconds },
2337 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2340 int main(int argc, char **argv) {
2346 if (*arg != '-') break;
2347 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2349 while ((a= *++arg)) {
2353 char *equals= strchr(arg,'=');
2354 int len= equals ? (equals - arg) : strlen(arg);
2355 for (o=options; o->long; o++)
2356 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2358 badusage("unknown long option --%s",arg);
2361 if (equals) badusage("option --%s does not take a value",o->long);
2363 } else if (equals) {
2367 if (!arg) badusage("option --%s needs a value",o->long);
2370 break; /* eaten the whole argument now */
2372 for (o=options; o->long; o++)
2375 badusage("unknown short option -%c",a);
2382 if (!arg) badusage("option -%c needs a value",o->short);
2385 break; /* eaten the whole argument now */
2390 if (!arg) badusage("need site name argument");
2396 if (*++argv) badusage("too many non-option arguments");
2398 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2399 badusage("nocheck threshold percentage must be between 0..100");
2400 nocheck_thresh= nocheck_thresh_pct * 0.01;
2402 if (nocheck_decay_articles < 0.1)
2403 badusage("nocheck decay articles must be at least 0.1");
2404 nocheck_decay= 1 - 1/nocheck_decay_articles;
2407 pathoutgoing= innconf->pathoutgoing;
2408 innconf_read(inndconffile);
2411 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2412 else if (!feedfile[0])
2413 badusage("feed filename must be nonempty");
2414 else if (feedfile[strlen(feedfile)-1]=='/')
2415 feedfile= xasprintf("%s%s",feedfile,sitename);
2417 const char *feedfile_forbidden= "?*[~#";
2419 while ((c= *feedfile_forbidden++))
2420 if (strchr(feedfile, c))
2421 badusage("feed filename may not contain metacharacter %c",c);
2423 loop= oop_sys_new();
2424 if (!loop) sysdie("could not create liboop event loop");
2426 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2427 sysdie("could not ignore SIGPIPE");
2429 if (become_daemon) {
2430 for (i=3; i<255; i++)
2431 /* do this now before we open syslog, etc. */
2433 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2435 int null= open("/dev/null",O_RDWR);
2436 if (null<0) sysdie("failed to open /dev/null");
2442 pid_t child1= xfork("daemonise first fork");
2443 if (child1) _exit(0);
2445 pid_t sid= setsid();
2446 if (sid != child1) sysdie("setsid failed");
2448 pid_t child2= xfork("daemonise second fork");
2449 if (child2) _exit(0);
2454 if (!filemon_init()) {
2455 warn("no file monitoring available, polling");
2456 filepoll_schedule();