3 * - close idle connections
8 * Newsfeeds file entries should look like this:
9 * host.name.of.site[/exclude,exclude,...]\
10 * :pattern,pattern...[/distribution,distribution...]\
14 * sitename[/exclude,exclude,...]\
15 * :pattern,pattern...[/distribution,distribution...]\
21 * or might be blanked out
22 * <spc><spc><spc><spc>....
24 * F site.name main feed file
25 * opened/created, then written, by innd
28 * tokens blanked out by duct when processed
29 * site.name_lock lock preventing multiple ducts
30 * to hold lock must open,F_SETLK[W]
31 * and then stat to check that locked file
32 * still has name site.name_lock
33 * holder of this lock is "duct"
34 * (only) lockholder may remove the lockfile
35 * D site.name_flushing temporary feed file during flush (or crash)
36 * hardlink created by duct
38 * site.name_defer 431'd articles, still being written,
39 * created, written, used by duct
41 * site.name_backlog.<date>.<inum>
42 * 431'd articles, ready for innxmit or duct
43 * created (link/mv) by duct
44 * site.name_backlog<anything-else> (where <anything-else> does not
45 * contain '#' or '~') eg
46 * site.name_backlog.manual
47 * anything the sysadmin likes (eg, feed files
48 * from old feeds to be merged into this one)
49 * created (link/mv) by admin
50 * may be symlinks (in which case links
51 * may be written through, but only links
54 * It is safe to remove backlog files manually,
55 * if it's desired to throw away the backlog.
57 * Backlog files are also processed by innduct. We find the oldest
58 * backlog file which is at least a certain amount old, and feed it
59 * back into our processing. When every article in it has been read
60 * and processed, we unlink it and look for another backlog file.
62 * If we don't have a backlog file that we're reading, we close the
63 * defer file that we're writing and make it into a backlog file at
64 * the first convenient opportunity.
75 | | <----------------<---------------------------------'|
81 | F: innd writing, duct reading |
84 | | duct decides time to flush |
85 | | duct makes hardlink |
87 | V <------------------------'|
89 | F == D: innd writing, duct reading both exist |
92 | | <-----------<-------------<--'|
96 | V <---------------------. |
99 | D: innd writing, duct reading; or ENOENT | |
101 | | duct requests flush of feed | |
102 | | (others can too, harmlessly) | |
106 | D: innd flushing, duct; or ENOENT | |
108 | | inndcomm flush fails | |
109 | |`-------------------------->------------------' |
111 | | inndcomm reports no such site |
112 | |`---------------------------------------------------- | -.
114 | | innd finishes writing D, creates F | |
115 | | inndcomm reports flush successful | |
118 | Separated <----------------' |
119 | F: innd writing F!=D /
120 | D: duct reading; or ENOENT both exist /
122 | | duct gets to the end of D /
123 | | duct opens F too /
126 | F: innd writing, duct reading |
127 | D: duct finishing V
129 | | duct finishes processing D F: ENOENT
130 | V duct unlinks D D: duct reading
132 `--<--' | duct finishes
142 "duct reading" means innduct is reading the file but also
143 overwriting processed tokens.
147 * rune for printing diagrams:
149 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
154 /*============================== PROGRAM ==============================*/
158 #include "inn/list.h"
165 #include <sys/types.h>
166 #include <sys/wait.h>
167 #include <sys/stat.h>
168 #include <sys/socket.h>
181 #include <oop-read.h>
183 /*----- general definitions, probably best not changed -----*/
185 #define PERIOD_SECONDS 60
187 #define CONNCHILD_ESTATUS_STREAM 4
188 #define CONNCHILD_ESTATUS_NOSTREAM 5
190 #define INNDCOMMCHILD_ESTATUS_FAIL 6
191 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
193 /*----- doubly linked lists -----*/
195 #define ISNODE(T) struct { T *succ, *pred; } node /* must be at start */
196 #define DEFLIST(T) typedef struct { T *hd, *tl, *tp; int count; } T##List
198 #define NODE(n) (assert((void*)&(n)->node == &(n)), \
199 (struct node*)&(n)->node)
201 #define LIST_CHECKCANHAVENODE(l,n) \
202 ((void)((n) == ((l).hd))) /* just for the type check */
204 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
205 ( LIST_CHECKCANHAVENODE(l,n), \
206 list_addsomehow((struct list*)&(l), NODE((n))), \
210 #define LIST_REMSOMEHOW(l,list_remsomehow) \
214 list_remsomehow((struct list*)&(l)) ) \
220 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
221 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
222 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
223 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
225 #define LIST_HEAD(l) ((typeof((l).hd))(list_head((struct list*)&(l))))
226 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
227 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
229 #define LIST_REMOVE(l,n) \
230 ( LIST_CHECKCANHAVENODE(l,n), \
231 list_remove(NODE((n))), \
235 #define LIST_INSERT(l,n,pred) \
236 ( LIST_CHECKCANHAVENODE(l,n), \
237 LIST_CHECKCANHAVENODE(l,pred), \
238 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
242 /*----- type predeclarations -----*/
244 typedef struct Conn Conn;
245 typedef struct Article Article;
246 typedef struct InputFile InputFile;
247 typedef struct XmitDetails XmitDetails;
248 typedef enum StateMachineState StateMachineState;
253 /*----- function predeclarations -----*/
255 static void conn_check_work(Conn *conn);
256 static void conn_make_some_xmits(Conn *conn);
257 static void *conn_write_some_xmits(Conn *conn);
259 static void xmit_free(XmitDetails *d);
261 static int filemon_init(void);
262 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
263 static void filemon_callback(void);
265 static void statemc_setstate(StateMachineState newsms, int periods,
266 const char *forlog, const char *why);
267 static void check_master_queue(void);
268 static void queue_check_input_done(void);
270 static void postfork(const char *what);
271 static void postfork_inputfile(InputFile *ipf);
273 /*----- configuration options -----*/
275 static char *sitename, *feedfile;
276 static const char *remote_host;
277 static int quiet_multiple=0, become_daemon=1;
279 static int max_connections=10, max_queue_per_conn=200;
281 static int connection_setup_timeout=200, port=119, try_stream=1;
282 static int inndcomm_flush_timeout=100;
283 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
284 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
285 static const char *inndconffile;
287 static double accept_proportion;
288 static double nocheck_thresh_pct= 95.0;
289 static double nocheck_thresh; /* computed in main from _pct */
290 static double nocheck_decay_articles= 100; /* converted to _decay */
291 static double nocheck_decay; /* computed in main from _articles */
292 static int nocheck, nocheck_reported;
295 /*----- statistics -----*/
297 typedef enum { /* in queue in conn->sent */
298 art_Unchecked, /* not checked, not sent checking */
299 art_Wanted, /* checked, wanted sent body as requested */
300 art_Unsolicited, /* - sent body without check */
304 #define RESULT_COUNTS(RCS,RCN) \
312 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
313 #define RCI_TRIPLE_VALS_BASE(counts,x) \
314 counts[art_Unchecked] x \
315 + counts[art_Wanted] x \
316 + counts[art_Unsolicited] x, \
317 counts[art_Unchecked] x \
318 , counts[art_Wanted] x \
319 , counts[art_Unsolicited] x
322 #define RC_INDEX(x) RC_##x,
323 RESULT_COUNTS(RC_INDEX, RC_INDEX)
328 /*----- transmission buffers -----*/
333 xk_Malloc, xk_Const, xk_Artdata
345 /*----- core operational data structure types -----*/
348 /* This is also an instance of struct oop_readable */
349 struct oop_readable readable; /* first */
350 oop_readable_call *readable_callback;
351 void *readable_callback_user;
354 struct Filemon_Perfile *filemon;
357 long inprogress; /* no. of articles read but not processed */
360 int counts[art_MaxState][RCI_max];
375 #define SMS_LIST(X) \
383 enum StateMachineState {
384 #define SMS_DEF_ENUM(s) sm_##s,
385 SMS_LIST(SMS_DEF_ENUM)
388 static const char *sms_names[]= {
389 #define SMS_DEF_NAME(s) #s ,
390 SMS_LIST(SMS_DEF_NAME)
396 int fd, max_queue, stream, quitting;
397 ArticleList queue; /* not yet told peer, or CHECK said send it */
398 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
399 struct iovec xmit[CONNIOVS];
400 XmitDetails xmitd[CONNIOVS];
405 /*----- operational variables -----*/
407 static oop_source *loop;
409 static int until_connect;
410 static ConnList conns;
411 static ArticleList queue;
413 static char *path_lock, *path_flushing, *path_defer;
415 #define SMS(newstate, periods, why) \
416 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
418 static StateMachineState sms;
420 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
421 static int sm_period_counter;
424 /*========== logging ==========*/
426 static void logcore(int sysloglevel, const char *fmt, ...)
427 __attribute__((__format__(printf,2,3)));
428 static void logcore(int sysloglevel, const char *fmt, ...) {
432 vsyslog(sysloglevel,fmt,al);
434 vfprintf(stderr,fmt,al);
440 static void logv(int sysloglevel, const char *pfx, int errnoval,
441 int exitstatus, const char *fmt, va_list al)
442 __attribute__((__format__(printf,5,0)));
443 static void logv(int sysloglevel, const char *pfx, int errnoval,
444 int exitstatus, const char *fmt, va_list al) {
445 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
446 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
447 msgbuf[sizeof(msgbuf)-1]= 0;
449 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
450 sysloglevel= LOG_ERR; /* run by wrong user, probably */
452 logcore(sysloglevel, "<%s>%s: %s%s%s",
453 sitename, pfx, msgbuf,
454 errnoval>=0 ? ": " : "",
455 errnoval>=0 ? strerror(errnoval) : "");
458 #define logwrap(fn, pfx, sysloglevel, err, estatus) \
459 static void fn(const char *fmt, ...) \
460 __attribute__((__format__(printf,1,2))); \
461 static void fn(const char *fmt, ...) { \
464 logv(sysloglevel, pfx, err, estatus, fmt, al); \
467 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
468 logwrap(die, " critical", LOG_CRIT, -1, 16);
470 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
471 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
473 logwrap(syswarn, " warning", LOG_WARNING, errno, 0);
474 logwrap(warn, " warning", LOG_WARNING, -1, 0);
476 logwrap(notice, "", LOG_NOTICE, -1, 0);
477 logwrap(info, " info", LOG_INFO, -1, 0);
478 logwrap(debug, " debug", LOG_DEBUG, -1, 0);
481 /*========== utility functions etc. ==========*/
483 static char *xvasprintf(const char *fmt, va_list al)
484 __attribute__((__format__(printf,1,0)));
485 static char *xvasprintf(const char *fmt, va_list al) {
487 int rc= vasprintf(&str,fmt,al);
488 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
491 static char *xasprintf(const char *fmt, ...)
492 __attribute__((__format__(printf,1,2)));
493 static char *xasprintf(const char *fmt, ...) {
496 char *str= xvasprintf(fmt,al);
501 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
503 static pid_t xfork(const char *what) {
507 if (child==-1) sysdie("cannot fork for %s",what);
508 if (!child) postfork(what);
509 debug("forked %s %ld", what, (unsigned long)child);
513 static void on_fd_read_except(int fd, oop_call_fd callback) {
514 loop->on_fd(loop, fd, OOP_READ, callback, 0);
515 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
517 static void cancel_fd_read_except(int fd) {
518 loop->cancel_fd(loop, fd, OOP_READ);
519 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
522 static void report_child_status(const char *what, int status) {
523 if (WIFEXITED(status)) {
524 int es= WEXITSTATUS(status);
526 warn("%s: child died with error exit status %d",es);
527 } else if (WIFSIGNALED(status)) {
528 int sig= WTERMSIG(status);
529 const char *sigstr= strsignal(sig);
530 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
532 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
534 warn("%s: child died due to unknown fatal signal %d%s",
535 what, sig, coredump);
537 warn("%s: child died with unknown wait status %d", status);
541 static int xwaitpid(pid_t *pid, const char *what) {
544 int r= kill(*pid, SIGKILL);
545 if (r) sysdie("cannot kill %s child", what);
547 pid_t got= waitpid(*pid, &status, WNOHANG);
548 if (got==-1) sysdie("cannot reap %s child", what);
555 static void xunlink(const char *path, const char *what) {
557 if (r) sysdie("can't unlink %s %s", path, what);
560 static void check_isreg(const struct stat *stab, const char *path,
562 if (!S_ISREG(stab->st_mode))
563 die("%s %s not a plain file (mode 0%lo)",
564 what, path, (unsigned long)stab->st_mode);
567 static void xfstat(int fd, struct stat *stab_r, const char *what) {
568 int r= fstat(fd, stab_r);
569 if (r) sysdie("could not fstat %s", what);
572 static void xfstat_isreg(int fd, struct stat *stab_r,
573 const char *path, const char *what) {
574 xfstat(fd, stab_r, what);
575 check_isreg(stab_r, path, what);
578 static void xlstat_isreg(const char *path, struct stat *stab,
579 int *enoent_r /* 0 means ENOENT is fatal */,
581 int r= lstat(path, stab);
583 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
584 sysdie("could not lstat %s %s", what, path);
586 if (enoent_r) *enoent_r= 0;
587 check_isreg(stab, path, what);
590 static void setnonblock(int fd, int nonblocking) {
591 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
592 if (nonblocking) r |= O_NONBLOCK;
593 else r &= ~O_NONBLOCK;
594 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
597 static int samefile(const struct stat *a, const struct stat *b) {
598 assert(S_ISREG(a->st_mode));
599 assert(S_ISREG(b->st_mode));
600 return (a->st_ino == b->st_ino &&
601 a->st_dev == b->st_dev);
604 static char *sanitise(const char *input) {
605 static char sanibuf[100]; /* returns pointer to this buffer! */
607 const char *p= input;
611 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
613 if (!c) { *q++= '\''; *q=0; break; }
614 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
615 sprintf(q,"\\x%02x",c);
621 /*========== making new connections ==========*/
623 static void conn_dispose(Conn *conn) {
625 perhaps_close(&conn->fd);
627 until_connect= reconnect_delay_periods;
630 static int connecting_sockets[2]= {-1,-1};
631 static pid_t connecting_child;
633 static void connect_attempt_discard(void) {
634 if (connecting_sockets[0])
635 cancel_fd_read_except(connecting_sockets[0]);
637 perhaps_close(&connecting_sockets[0]);
638 perhaps_close(&connecting_sockets[1]);
640 if (connecting_child) {
641 int r= kill(connecting_child, SIGTERM);
642 if (r) syswarn("failed to kill connecting child");
643 int status= xwaitpid(&connecting_child, "connect");
645 if (!(WIFEXITED(status) ||
646 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
647 report_child_status("connect", status);
651 #define PREP_DECL_MSG_CMSG(msg) \
653 memset(&msg,0,sizeof(msg)); \
654 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
655 msg.msg_control= msg##cbuf; \
656 msg.msg_controllen= sizeof(msg##cbuf);
658 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
661 conn= xmalloc(sizeof(*conn));
662 memset(conn,0,sizeof(*conn));
664 PREP_DECL_MSG_CMSG(msg);
665 struct cmsghdr *h= 0;
666 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
667 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
670 pid_t got= waitpid(connecting_child, &status, WNOHANG);
672 assert(got==connecting_child);
674 if (WIFEXITED(status) &&
675 (WEXITSTATUS(status) != 0 &&
676 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
677 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
678 /* child already reported the problem */
679 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
680 warn("connect: connection attempt timed out");
681 } else if (!WIFEXITED(status)) {
682 report_child_status("connect", status);
683 /* that's probably the root cause then */
686 /* child is still running apparently, report the socket problem */
688 syswarn("connect: read from child socket failed");
689 else if (e == OOP_EXCEPTION)
690 warn("connect: unexpected exception on child socket");
692 warn("connect: unexpected EOF on child socket");
697 #define CHK(field, val) \
698 if (h->cmsg_##field != val) { \
699 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
702 CHK(level, SOL_SOCKET);
703 CHK(type, SCM_RIGHTS);
704 CHK(len, CMSG_LEN(sizeof(conn->fd)));
707 if (CMSG_NXTHDR(&msg,h)) { die("connect: child sent many cmsgs"); goto x; }
709 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
712 pid_t got= waitpid(connecting_child, &status, 0);
713 if (got==-1) sysdie("connect: real wait for child");
714 assert(got == connecting_child);
717 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
718 int es= WEXITSTATUS(status);
720 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
721 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
723 fatal("connect: child gave unexpected exit status %d", es);
727 setnonblock(conn->fd, 1);
728 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
729 LIST_ADDHEAD(conns, conn);
730 notice("#%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
731 connect_attempt_discard();
732 check_master_queue();
737 connect_attempt_discard();
740 static void connect_start(void) {
741 assert(!connecting_sockets[0]);
742 assert(!connecting_sockets[1]);
743 assert(!connecting_child);
745 notice("starting connection attempt");
747 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
748 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
750 connecting_child= xfork("connection");
752 if (!connecting_child) {
753 FILE *cn_from, *cn_to;
754 char buf[NNTP_STRLEN+100];
755 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
757 r= close(connecting_sockets[0]);
758 if (r) sysdie("connect: close parent socket in child");
760 alarm(connection_setup_timeout);
761 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
762 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
763 else sysfatal("connect: connection attempt failed");
765 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
766 sysfatal("connect: authentication failed");
768 if (fputs("MODE STREAM\r\n", cn_to) ||
770 sysfatal("connect: could not send MODE STREAM");
771 buf[sizeof(buf)-1]= 0;
772 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
774 sysfatal("connect: could not read response to MODE STREAM");
776 fatal("connect: connection close in response to MODE STREAM");
781 fatal("connect: response to MODE STREAM is too long: %.100s...",
782 remote_host, sanitise(buf));
783 l--; if (l>0 && buf[l-1]=='\r') l--;
786 int rcode= strtoul(buf,&ep,10);
788 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
792 exitstatus= CONNCHILD_ESTATUS_STREAM;
798 warn("connect: unexpected response to MODE STREAM: %.50s",
804 int fd= fileno(cn_from);
806 PREP_DECL_MSG_CMSG(msg);
807 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
808 cmsg->cmsg_level= SOL_SOCKET;
809 cmsg->cmsg_type= SCM_RIGHTS;
810 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
811 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
813 msg.msg_controllen= cmsg->cmsg_len;
814 r= sendmsg(connecting_sockets[1], &msg, 0);
815 if (r) sysdie("sendmsg failed for new connection");
820 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
821 if (r) sysdie("connect: close child socket in parent");
823 on_fd_read_except(connecting_sockets[0], connchild_event);
827 connect_attempt_discard();
831 /*========== overall control of article flow ==========*/
833 static void check_master_queue(void) {
840 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
841 int inqueue= walk->sent.count + walk->queue.count;
842 spare= walk->max_queue - inqueue;
843 assert(inqueue <= max_queue_per_conn);
845 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
846 else if (spare>0) /*working*/ { use= walk; break; }
850 Article *art= LIST_REMHEAD(queue);
851 LIST_ADDTAIL(use->queue, art);
854 conn_check_work(use);
855 } else if (conns.count < max_connections &&
856 !connecting_child && !until_connect) {
857 until_connect= reconnect_delay_periods;
866 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
871 static void conn_check_work(Conn *conn) {
874 conn_make_some_xmits(conn);
876 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
880 void *rp= conn_write_some_xmits(conn);
881 if (rp==OOP_CONTINUE) {
882 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
884 } else if (rp==OOP_HALT) {
887 /* transmitted everything */
894 static void vconnfail(Conn *conn, const char *fmt, va_list al)
895 __attribute__((__format__(printf,2,0)));
897 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
898 int requeue[art_MaxState];
901 while ((art= LIST_REMHEAD(conn->queue))) LIST_ADDTAIL(queue, art);
902 while ((art= LIST_REMHEAD(conn->sent))) {
903 requeue[art->state]++;
904 if (art->state==art_Unsolicited) art->state= art_Unchecked;
905 LIST_ADDTAIL(queue,art);
910 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
913 char *m= xvasprintf(fmt,al);
914 warn("#%d connection failed, requeueing " RCI_TRIPLE_FMT_BASE ": %s",
915 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
918 LIST_REMOVE(conns,conn);
920 check_master_queue();
923 static void connfail(Conn *conn, const char *fmt, ...)
924 __attribute__((__format__(printf,2,3)));
925 static void connfail(Conn *conn, const char *fmt, ...) {
928 vconnfail(conn,fmt,al);
932 /*========== article transmission ==========*/
934 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
935 XmitKind kind) { /* caller must then fill in details */
936 struct iovec *v= &conn->xmit[conn->xmitu];
937 XmitDetails *d= &conn->xmitd[conn->xmitu++];
938 v->iov_base= (char*)data;
944 static void xmit_noalloc(Conn *conn, const char *data, int len) {
945 xmit_core(conn,data,len, xk_Const);
947 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
949 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
950 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
954 static void xmit_free(XmitDetails *d) {
956 case xk_Malloc: free(d->info.malloc_tofree); break;
957 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
958 case xk_Const: break;
963 static void *conn_write_some_xmits(Conn *conn) {
965 * 0: nothing more to write, no need to call us again
966 * OOP_CONTINUE: more to write but fd not writeable
967 * OOP_HALT: disaster, have destroyed conn
970 int count= conn->xmitu;
971 if (!count) return 0;
973 if (count > IOV_MAX) count= IOV_MAX;
974 ssize_t rs= writev(conn->fd, conn->xmit, count);
976 if (errno == EAGAIN) return OOP_CONTINUE;
977 connfail(conn, "write failed: %s", strerror(errno));
983 for (done=0; rs && done<conn->xmitu; done++) {
984 struct iovec *vp= &conn->xmit[done];
985 XmitDetails *dp= &conn->xmitd[done];
986 if (rs > vp->iov_len) {
994 int newu= conn->xmitu - done;
995 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
996 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1001 static void conn_make_some_xmits(Conn *conn) {
1003 if (conn->xmitu+5 > CONNIOVS)
1006 Article *art= LIST_REMHEAD(queue);
1009 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1010 /* actually send it */
1012 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1016 XMIT_LITERAL("TAKETHIS ");
1017 xmit_noalloc(conn, art->messageid, art->midlen);
1018 XMIT_LITERAL("\r\n");
1019 xmit_artbody(conn, artdata);
1022 /* we got 235 from IHAVE */
1024 xmit_artbody(conn, artdata);
1026 XMIT_LITERAL(".\r\n");
1031 art->state == art_Unchecked ? art_Unsolicited :
1032 art->state == art_Wanted ? art_Wanted :
1034 art->ipf->counts[art->state][RC_sent]++;
1035 LIST_ADDTAIL(conn->sent, art);
1041 XMIT_LITERAL("IHAVE ");
1043 XMIT_LITERAL("CHECK ");
1044 xmit_noalloc(conn, art->messageid, art->midlen);
1045 XMIT_LITERAL("\r\n");
1047 assert(art->state == art_Unchecked);
1048 art->ipf->counts[art->state][RCI_sent]++;
1049 LIST_ADDTAIL(conn->sent, art);
1055 /*========== handling responses from peer ==========*/
1057 static const oop_rd_style peer_rd_style= {
1058 OOP_RD_DELIM_STRIP, '\n',
1060 OOP_RD_SHORTREC_FORBID
1063 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1064 const char *errmsg, int errnoval,
1065 const char *data, size_t recsz, void *conn_v) {
1067 connfail(conn, "error receiving from peer: %s", errmsg);
1068 return OOP_CONTINUE;
1071 static Article *article_reply_check(Conn *conn, const char *response,
1072 int code_indicates_streaming,
1074 /* 1:yes, -1:no, 0:dontcare */,
1075 const char *sanitised_response) {
1076 Article *art= LIST_HEAD(conn->sent);
1080 "peer gave unexpected response when no commands outstanding: %s",
1081 sanitised_response);
1085 if (code_indicates_streaming) {
1086 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1087 if (!conn->stream) {
1088 connfail(conn, "peer gave streaming response code "
1089 " to IHAVE or subsequent body: %s", sanitised_response);
1092 const char *got_mid= response+4;
1093 int got_midlen= strcspn(got_mid, " \n\r");
1094 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1095 connfail(conn, "peer gave streaming response with syntactically invalid"
1096 " messageid: %s", sanitised_response);
1099 if (got_midlen != art->midlen ||
1100 memcmp(got_mid, art->messageid, got_midlen)) {
1101 connfail(conn, "peer gave streaming response code to wrong article -"
1102 " probable synchronisation problem; we offered: %s;"
1104 art->messageid, sanitised_response);
1109 connfail(conn, "peer gave non-streaming response code to"
1110 " CHECK/TAKETHIS: %s", sanitised_response);
1115 if (must_have_sent>0 && art->state < art_Wanted) {
1116 connfail(conn, "peer says article accepted but"
1117 " we had not sent the body: %s", sanitised_response);
1120 if (must_have_sent<0 && art->state >= art_Wanted) {
1121 connfail(conn, "peer says please sent the article but we just did: %s",
1122 sanitised_response);
1126 Article *art_again= LIST_REMHEAD(conn->sent);
1127 assert(art_again == art);
1131 static void update_nocheck(int accepted) {
1132 accept_proportion *= nocheck_decay;
1133 accept_proportion += accepted * (1.0 - nocheck_decay);
1134 int new_nocheck= accept_proportion >= nocheck_thresh;
1135 if (new_nocheck && !nocheck_reported) {
1136 notice("entering nocheck mode for the first time");
1137 nocheck_reported= 1;
1138 } else if (new_nocheck != nocheck) {
1139 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1141 nocheck= new_nocheck;
1144 static void article_done(Conn *conn, Article *art, int whichcount) {
1145 art->ipf->counts[art->state][whichcount]++;
1146 if (whichcount == RC_accepted) update_nocheck(1);
1147 else if (whichcount == RC_unwanted) update_nocheck(0);
1149 InputFile *ipf= art->ipf;
1150 while (art->blanklen) {
1151 static const char spaces[]=
1156 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1157 int r= pwrite(ipf->fd, spaces, w, art->offset);
1159 if (errno==EINTR) continue;
1160 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1161 art->messageid, art->blanklen, art->offset, ipf->path);
1163 assert(r>=0 && r<=w);
1169 assert(ipf->inprogress >= 0);
1171 if (!ipf->inprogress && ipf != main_input_file)
1172 queue_check_input_done();
1177 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1178 const char *errmsg, int errnoval,
1179 const char *data, size_t recsz, void *conn_v) {
1182 if (ev == OOP_RD_EOF) {
1183 connfail(conn, "unexpected EOF from peer");
1184 return OOP_CONTINUE;
1186 assert(ev == OOP_RD_OK);
1188 char *sani= sanitise(data);
1191 unsigned long code= strtoul(data, &ep, 10);
1192 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1193 connfail(conn, "badly formatted response from peer: %s", sani);
1194 return OOP_CONTINUE;
1197 if (conn->quitting) {
1198 if (code!=205 && code!=503) {
1199 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1201 notice("#%d idle connection closed\n");
1202 assert(!conn->queue.count);
1203 assert(!conn->sent.count);
1204 assert(!conn->xmitu);
1205 LIST_REMOVE(conns,conn);
1208 return OOP_CONTINUE;
1213 #define GET_ARTICLE(musthavesent) \
1214 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1215 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1217 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1218 code_streaming= (streaming); \
1219 GET_ARTICLE(musthavesent); \
1220 article_done(conn, art, RC_##how); break;
1222 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1224 int code_streaming= 0;
1228 case 400: PEERBADMSG("peer stopped accepting articles");
1229 case 503: PEERBADMSG("peer timed us out");
1230 default: PEERBADMSG("peer sent unexpected message");
1232 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1233 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1235 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1236 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1238 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1239 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1241 case 238: /* CHECK says send it */
1243 case 335: /* IHAVE says send it */
1245 assert(art->state == art_Unchecked);
1246 art->ipf->counts[art->state][RC_accepted]++;
1247 art->state= art_Wanted;
1248 LIST_ADDTAIL(conn->queue, art);
1251 case 431: /* CHECK or TAKETHIS says try later */
1253 case 436: /* IHAVE says try later */
1256 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1258 sysfatal("write to defer file %s",path_defer);
1259 article_done(conn, art, RC_deferred);
1264 check_check_work(conn);
1265 return OOP_CONTINUE;
1269 /*========== monitoring of input files ==========*/
1271 static void feedfile_eof(InputFile *ipf) {
1272 assert(ipf != main_input_file); /* promised by tailing_try_read */
1274 inputfile_tailing_stop(ipf);
1275 assert(ipf->fd >= 0);
1276 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1279 if (ipf == flushing_input_file) {
1280 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1281 if (main_input_file) inputfile_tailing_start(main_input_file);
1282 statemc_check_flushing_done();
1283 } else if (ipf == backlog_input_file) {
1284 statemc_check_backlog_done();
1286 abort(); /* supposed to wait rather than get EOF on main input file */
1290 static InputFile *open_input_file(const char *path) {
1291 int fd= open(path, O_RDONLY);
1293 if (errno==ENOENT) return 0;
1294 sysfatal("unable to open input file %s", path);
1297 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1298 memset(ipf,0,sizeof(*ipf));
1300 ipf->readable.on_readable= tailing_on_readable;
1301 ipf->readable.on_cancel= tailing_on_cancel;
1302 ipf->readable.try_read= tailing_try_read;
1305 strcpy(ipf->path, path);
1310 static void close_input_file(InputFile *ipf) {
1311 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1312 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1313 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1314 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1317 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1321 /*---------- dealing with articles read in the input file ----------*/
1323 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1324 oop_rd_event ev, const char *errmsg,
1326 const char *data, size_t recsz,
1328 InputFile *ipf= ipf_v;
1330 char tokentextbuf[sizeof(TOKEN)*2+3];
1332 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1334 if (data[0] && data[0]!=' ') {
1335 char *space= strchr(data,' ');
1336 int tokenlen= space-data;
1337 int midlen= (int)recsz-tokenlen-1;
1338 if (midlen < 0) goto bad_data;
1340 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1341 memcpy(tokentextbuf, data, tokenlen);
1342 tokentextbuf[tokenlen]= 0;
1343 if (!IsToken(tokentextbuf)) goto bad_data;
1345 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1346 art->offset= ipf->offset;
1347 art->blanklen= recsz;
1348 art->midlen= midlen;
1349 art->state= art_Unchecked;
1350 art->ipf= ipf; ipf->inprogress++;
1351 art->token= TextToToken(tokentextbuf);
1352 strcpy(art->messageid, space+1);
1353 LIST_ADDTAIL(queue, art);
1355 ipf->offset += recsz + 1;
1357 if (sms==sm_NORMAL && ipf==main_input_file &&
1358 ipf->offset >= flush_threshold)
1359 statemc_start_flush("feed file size");
1361 check_master_queue();
1364 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1365 assert(sms == sm_NORMAL);
1367 debug("starting flush (%s) (%lu >= %lu) (%d)",
1369 (unsigned long)ipf->offset, (unsigned long)flush_threshold,
1372 int r= link(feedfile, duct_path);
1373 if (r) sysdie("link feedfile %s to flushing file %s", feedfile,
1377 xunlink(feedfile, "old feedfile link");
1380 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1383 /*========== tailing input file ==========*/
1385 static void filemon_start(InputFile *ipf) {
1386 assert(!ipf->filemon);
1388 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1389 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1390 filemon_method_startfile(ipf, ipf->filemon);
1393 static void filemon_stop(InputFile *ipf) {
1394 if (!ipf->filemon) return;
1395 filemon_method_stopfile(ipf, ipf->filemon);
1400 static void filemon_callback(InputFile *ipf) {
1401 ipf->readable_callback(ipf->readable_callback_user);
1404 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1406 InputFile *ipf= user;
1407 return ipf->readable_callback(ipf->readable_callback_user);
1410 static void on_cancel(struct oop_readable *rable) {
1411 InputFile *ipf= (void*)rable;
1413 if (ipf->filemon) filemon_stopfile(ipf);
1414 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1415 ipf->readable_callback= 0;
1418 static void tailing_queue_readable(InputFile *ipf) {
1419 /* lifetime of ipf here is OK because destruction will cause
1420 * on_cancel which will cancel this callback */
1421 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1424 static int tailing_on_readable(struct oop_readable *rable,
1425 oop_readable_call *cb, void *user) {
1426 InputFile *ipf= (void*)rable;
1428 tailing_on_cancel(rable);
1429 ipf->readable_callback= cb;
1430 ipf->readable_callback_user= user;
1431 filemon_startfile(ipf);
1433 tailing_queue_readable(ipf);
1437 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1439 InputFile *ipf= (void*)rable;
1441 ssize_t r= read(ipf->fd, buffer, length);
1443 if (errno==EINTR) continue;
1447 if (ipf==main_input_file) {
1450 } else if (ipf==flushing_input_file) {
1452 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1453 } else if (ipf==backlog_input_file) {
1463 /*---------- filemon implemented with inotify ----------*/
1465 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1466 #define HAVE_FILEMON
1468 #include <linux/inotify.h>
1470 static int filemon_inotify_fd;
1471 static int filemon_inotify_wdmax;
1472 static InputFile **filemon_inotify_wd2ipf;
1474 typedef struct Filemon_Perfile {
1476 } Filemon_Inotify_Perfile;
1478 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1479 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1480 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1482 if (wd >= filemon_inotify_wdmax) {
1484 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1485 sizeof(*filemon_inotify_wd2ipf) * newmax);
1486 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1487 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1488 filemon_inotify_wdmax= newmax;
1491 assert(!filemon_inotify_wd2ipf[wd]);
1492 filemon_inotify_wd2ipf[wd]= ipf;
1494 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1495 ipf, wd, filemon_inotify_wdmax);
1500 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1502 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1503 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1504 if (r) sysdie("inotify_rm_watch");
1505 filemon_inotify_wd2ipf[wd]= 0;
1508 static void *filemon_inotify_readable(oop_source *lp, int fd,
1509 oop_event e, void *u) {
1510 struct inotify_event iev;
1512 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1514 if (errno==EAGAIN) break;
1515 sysdie("read from inotify master");
1516 } else if (r==sizeof(iev)) {
1517 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1519 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1521 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1522 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1523 filemon_callback(ipf);
1525 return OOP_CONTINUE;
1528 static int filemon_method_init(void) {
1529 filemon_inotify_fd= inotify_init();
1530 if (filemon_inotify_fd<0) {
1531 syswarn("could not initialise inotify: inotify_init failed");
1535 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1537 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1541 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1543 /*---------- filemon dummy implementation ----------*/
1545 #if !defined(HAVE_FILEMON)
1547 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1549 static int filemon_method_init(void) { return 0; }
1550 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1551 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1553 #endif /* !HAVE_FILEMON */
1555 /*---------- interface to start and stop an input file ----------*/
1557 static const oop_rd_style feedfile_rdstyle= {
1558 OOP_RD_DELIM_STRIP, '\n',
1560 OOP_RD_SHORTREC_EOF,
1563 static void inputfile_tailing_start(InputFile *ipf) {
1565 ipf->readable->on_readable= tailing_on_readable;
1566 ipf->readable->on_cancel= tailing_on_cancel;
1567 ipf->readable->try_read= tailing_try_read;
1568 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1569 ipf->readable->delete_kill= 0;
1571 ipf->readable_callback= 0;
1572 ipf->readable_callback_user= 0;
1574 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1577 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1578 feedfile_got_article,ipf, feedfile_problem,ipf);
1579 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1582 static void inputfile_tailing_stop(InputFile *ipf) {
1584 oop_rd_cancel(ipf->rd);
1585 oop_rd_delete(ipf->rd);
1587 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1591 /*========== interaction with innd - state machine ==========*/
1593 /* See official state diagram at top of file. We implement
1604 |`---------------------------------------------------.
1606 |`---------------- - - - |
1607 D ENOENT | D EXISTS see OVERALL STATES diagram |
1608 | for full startup logic |
1611 | ============ try to |
1617 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1618 ^ | hardlink F to D |
1621 | | our handle onto F is now onto D |
1624 | |<-------------------<---------------------<---------+
1626 | | spawn inndcomm flush |
1628 | ================== |
1629 | FLUSHING[-ABSENT] |
1631 | main D tail/none |
1632 | ================== |
1634 | | INNDCOMM FLUSH FAILS ^
1635 | |`----------------------->----------. |
1637 | | NO SUCH SITE V |
1638 ^ |`--------------->----. ==================== |
1639 | | \ FLUSHFAILED[-ABSENT] |
1641 | | FLUSH OK \ main D tail/none |
1642 | | open F \ ==================== |
1644 | | \ | TIME TO RETRY |
1645 | |`------->----. ,---<---'\ `----------------'
1646 | | D NONE | | D NONE `----.
1648 | ============= V V ============
1649 | SEPARATED-1 | | DROPPING-1
1650 | flsh->fd>=0 | | flsh->fd>=0
1651 | [Separated] | | [Dropping]
1652 | main F idle | | main none
1653 | old D tail | | old D tail
1654 | ============= | | ============
1656 ^ | EOF ON D | | defer | EOF ON D
1658 | =============== | | ===============
1659 | SEPARATED-2 | | DROPPING-2
1660 | flsh->fd==-1 | V flsh->fd==-1
1661 | [Finishing] | | [Dropping]
1662 | main F tail | `. main none
1663 | old D closed | `. old D closed
1664 | =============== V `. ===============
1666 | | ALL D PROCESSED `. | ALL D PROCESSED
1667 | V install defer as backlog `. | install defer
1668 ^ | close D `. | close D
1669 | | unlink D `. | unlink D
1672 `----------' ==============
1692 static void statemc_init(void) {
1693 struct stat stab, stabf;
1695 path_lock= xasprintf("%s_lock", feedfile);
1696 path_flushing= xasprintf("%s_flushing", feedfile);
1697 path_defer= xasprintf("%s_defer", feedfile);
1698 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1701 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1702 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1705 memset(&fl,0,sizeof(fl));
1707 fl.l_whence= SEEK_SET;
1708 r= fcntl(lockfd, F_SETLK, &fl);
1710 if (errno==EACCES || errno==EAGAIN) {
1711 if (quiet_multiple) exit(0);
1712 fatal("another duct holds the lockfile");
1714 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1717 xfstat_isreg(lockfd, &stabf, "lockfile");
1719 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1721 if (!lock_noent && samefile(&stab, &stabf))
1725 sysdie("could not close stale lockfile %s", path_lock);
1727 debug("startup: locked");
1729 search_backlog_file();
1732 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1734 debug("startup: ductdefer ENOENT");
1736 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1737 switch (stab.st_nlink==1) {
1739 open_defer(); /* so that we will later close it and rename it */
1742 xunlink(path_defer, "stale defer file link"
1743 " (presumably hardlink to backlog file)");
1746 die("defer file %s has unexpected link count %d",
1747 path_defer, stab.st_nlink);
1751 struct stat stab_f, stab_d;
1754 InputFile *file_d= open_input_file(path_flushing);
1755 if (file_d) xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1757 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1759 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1760 debug("startup: F==D => Hardlinked");
1761 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1766 debug("startup: F ENOENT => Moved");
1767 if (file_d) startup_set_input_file(file_d);
1768 spawn_inndcomm_flush("feedfile missing at startup");
1769 /* => Flushing, sms:=FLUSHING */
1772 debug("startup: F!=D => Separated");
1773 startup_set_input_file(file_d);
1774 SMS(SEPARATED, 0, "found both old and current feed files");
1776 debug("startup: F exists, D ENOENT => Normal");
1777 FILE *file_f= open_input_file(feedfile);
1778 if (!file_f) die("feed file vanished during startup");
1779 startup_set_input_file(file_f);
1780 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1785 static void statemc_period_poll(void) {
1786 if (!sm_period_counter) return;
1787 sm_period_counter--;
1788 assert(sm_period_counter>=0);
1790 if (sm_period_counter) return;
1793 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1795 case sm_FLUSHFAILED:
1796 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1803 static void startup_set_input_file(InputFile *f) {
1804 assert(!main_input_file);
1806 inputfile_tailing_start(f);
1809 static int inputfile_is_done(InputFile *ipf) {
1811 if (ipf->inprogress) return 0; /* new article in the meantime */
1812 if (ipf->fd >= 0); return 0; /* not had EOF */
1816 static void notice_processed(InputFile *ipf, const char *what,
1818 #define RCI_NOTHING(x) /* nothing */
1819 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
1820 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, .x)
1822 info("processed %s%s offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
1823 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
1826 ipf->counts[art_Unchecked].sent + ipf->counts[art_Unsolicited].sent
1827 , ipf->counts[art_Unchecked].sent, ipf->counts[art_Unsolicited].sent,
1828 ipf->counts[art_Wanted].accepted + ipf->counts[art_Unsolicited].accepted
1829 ,ipf->counts[art_Wanted].accepted,ipf->counts[art_Unsolicited].accepted
1830 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
1834 static void statemc_check_backlog_done(void) {
1835 InputFile *ipf= backlog_input_file();
1836 if (!inputfile_is_done(ipf)) return;
1838 const char *slash= strrchr(ipf->path, "/");
1839 const char *leaf= slash ? slash+1 : ipf->path;
1840 const char *under= strchr(slash, "_");
1841 const char *rest= under ? under+1 : leaf;
1842 if (!strncmp(rest,"backlog",7)) rest += 7;
1843 notice_processed(ipf,"backlog:",rest);
1845 close_input_file(ipf);
1846 if (unlink(ipf->path)) {
1847 if (errno != ENOENT)
1848 sysdie("could not unlink processed backlog file %s", ipf->path);
1849 warn("backlog file %s vanished while we were reading it"
1850 " so we couldn't remove it (but it's done now, anyway)",
1854 backlog_input_file= 0;
1855 search_backlog_file();
1859 static void statemc_check_flushing_done(void) {
1860 InputFile *ipf= flushing_input_file;
1861 if (!inputfile_is_done(ipf)) return;
1863 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1865 notice_processed(ipf,"feedfile",0);
1869 xunlink(path_flushing, "old flushing file");
1871 close_input_file(flushing_input_file);
1872 free(flushing_input_file);
1873 flushing_input_file= 0;
1875 if (sms==sm_SEPARATED) {
1876 notice("flush complete");
1877 SMS(NORMAL, 0, "flush complete");
1878 } else if (sms==sm_DROPPING) {
1879 SMS(DROPPED, 0, "old flush complete");
1880 search_backlog_file();
1881 notice("feed dropped, but will continue until backlog is finished");
1885 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
1887 assert(!inputfile_is_done(main_input_file));
1888 statemc_check_flushing_done();
1889 statemc_check_backlog_done();
1890 return OOP_CONTINUE;
1893 static void queue_check_input_done(void) {
1894 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
1897 static void statemc_setstate(StateMachineState newsms, int periods,
1898 const char *forlog, const char *why) {
1900 sm_period_counter= periods;
1902 const char *xtra= "";
1904 case sm_FLUSHING: sm_FLUSHFAILED:
1905 if (!main_input_file) xtra= "-ABSENT";
1907 case sm_SEPARATED: case sm_DROPPING:
1908 xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
1914 info("%s%s[%d] %s",forlog,xtra,periods,why);
1916 info("%s%s %s",forlog,xtra,why);
1920 /*---------- defer and backlog files ----------*/
1922 static void open_defer(void) {
1927 defer= fopen(path_defer, "a+");
1928 if (!defer) sysfatal("could not open defer file %s", path_defer);
1930 /* truncate away any half-written records */
1932 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1934 if (stab.st_size > LONG_MAX)
1935 die("defer file %s size is far too large", path_defer);
1940 long orgsize= stab.st_size;
1941 long truncto= stab.st_size;
1943 if (!truncto) break; /* was only (if anything) one half-truncated record */
1944 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1945 sysdie("seek in defer file %s while truncating partial", path_defer);
1950 sysdie("failed read from defer file %s", path_defer);
1952 die("defer file %s shrank while we were checking it!", path_defer);
1958 if (stab.st_size != truncto) {
1959 warn("truncating half-record at end of defer file %s -"
1960 " shrinking by %ld bytes from %ld to %ld",
1961 path_defer, orgsize - truncto, orgsize, truncto);
1964 sysfatal("could not flush defer file %s", path_defer);
1965 if (ftruncate(fileno(defer), truncto))
1966 sysdie("could not truncate defer file %s", path_defer);
1969 info("continuing existing defer file %s (%ld bytes)",
1970 path_defer, orgsize);
1972 if (fseek(defer, truncto, SEEK_SET))
1973 sysdie("could not seek to new end of defer file %s", path_defer);
1976 static void close_defer(void) {
1980 xfstat(fileno(defer), &stab, "defer file");
1982 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1985 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1986 (unsigned long)now.tv_sec,
1987 (unsigned long)stab.st_ino);
1988 if (link(path_defer, path_backlog))
1989 sysfatal("could not install defer file %s as backlog file %s",
1990 path_defer, backlog);
1991 if (unlink(path_defer))
1992 sysdie("could not unlink old defer link %s to backlog file %s",
1993 path_defer, backlog);
1995 if (until_backlog_nextscan < 0 ||
1996 until_backlog_nextscan > backlog_retry_minperiods + 1)
1997 until_backlog_nextscan= backlog_retry_minperiods + 1;
2000 static void poll_backlog_file(void) {
2001 if (until_backlog_nextscan < 0) return;
2002 if (until_backlog_nextscan-- > 0) return;
2003 search_backlog_file();
2006 static void search_backlog_file(void) {
2007 /* returns non-0 iff there are any backlog files */
2012 const char *oldest_path=0;
2013 time_t oldest_mtime, now;
2015 if (backlog_input_file) return 3;
2019 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2023 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2025 die("out of memory expanding backlog pattern %s", globpat_backlog);
2027 for (i=0; i<gl.gl_pathc; i++) {
2028 const char *path= gl.gl_pathv[i];
2030 if (strchr(path,'#') || strchr(path,'~')) {
2031 debug("backlog file search skipping %s", path);
2034 r= stat(path, &stab);
2036 syswarn("failed to stat backlog file %s", path);
2039 if (!S_ISREG(stab.st_mode)) {
2040 warn("backlog file %s is not a plain file (or link to one)", path);
2043 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2045 oldest_mtime= stab.st_mtime;
2048 case GLOB_NOMATCH: /* fall through */
2051 sysdie("glob expansion of backlog pattern %s gave unexpected"
2052 " nonzero (error?) return value %d", globpat_backlog, r);
2058 debug("backlog scan: none");
2060 if (sms==sm_DROPPED) {
2061 notice("feed dropped and our work is complete");
2062 xunlink(path_lock, "lockfile for old feed");
2065 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2069 now= time(); if (now==-1) sysdie("time(2) failed");
2070 double age= difftime(now, oldest_mtime);
2071 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
2073 if (age_deficiency <= 0) {
2074 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2075 age, age_deficiency, oldest_path);
2077 backlog_input_file= open_input_file(oldest_path);
2078 if (!backlog_input_file) {
2079 warn("backlog file %s vanished as we opened it", backlog_input_file);
2082 inputfile_tailing_start(backlog_input_file);
2083 until_backlog_nextscan= -1;
2087 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
2089 if (backlog_spontaneous_rescan_periods >= 0 &&
2090 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2091 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2093 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2094 age, age_deficiency, until_backlog_nextscan, oldest_path);
2098 /*========== flushing the feed ==========*/
2100 static pid_t inndcomm_child;
2102 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2103 assert(inndcomm_child);
2104 int status= xwaitpid(&inndcomm_child, "inndcomm");
2105 loop->cancel_fd(fd);
2108 assert(!flushing_input_file);
2110 if (WIFEXITED(status)) {
2111 switch (WEXITSTATUS(status)) {
2113 case INNDCOMMCHILD_ESTATUS_FAIL:
2116 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2117 warn("feed has been dropped by innd, finishing up");
2118 flushing_input_file= main_input_file;
2119 tailing_queue_readable(flushing_input_file);
2120 /* we probably previously returned EAGAIN from our fake read method
2121 * when in fact we were at EOF, so signal another readable event
2122 * so we actually see the EOF */
2126 if (flushing_input_file) {
2127 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2130 SMS(DROPPED, 0, "feed dropped by innd");
2131 search_backlog_file();
2133 return OOP_CONTINUE;
2137 flushing_input_file= main_input_file;
2138 tailing_queue_readable(flushing_input_file);
2140 main_input_file= open_input_file(feedfile);
2141 if (!main_input_file)
2142 die("flush succeeded but feedfile %s does not exist!", feedfile);
2144 if (flushing_input_file) {
2145 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2148 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2150 return OOP_CONTINUE;
2153 goto unexpected_exitstatus;
2156 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2157 warn("flush timed out trying to talk to innd");
2160 unexpected_exitstatus:
2161 report_child_status("inndcomm child", status);
2165 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2168 static void inndcommfail(const char *what) {
2169 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2170 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2173 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2176 notice("flushing %s",why);
2178 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2179 assert(!inndcomm_child);
2181 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2183 inndcomm_child= xfork();
2185 if (!inndcomm_child) {
2186 static char flushargv[2]= { sitename, 0 };
2191 alarm(inndcomm_flush_timeout);
2192 r= ICCopen(); if (r) inndcommfail("connect");
2193 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2194 if (!r) exit(0); /* yay! */
2196 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2197 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2198 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2202 int sentinel_fd= pipefds[0];
2203 on_fd_read_except(sentinel_fd, inndcomm_event);
2205 SMS(FLUSHING, 0, why);
2208 /*========== main program ==========*/
2210 static void postfork_inputfile(InputFile *ipf) {
2212 assert(ipf->fd >= 0);
2217 static void postfork_stdio(FILE *f) {
2218 /* we have no stdio streams that are buffered long-term */
2222 static void postfork(const char *what) {
2223 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2224 sysdie("%s child: failed to reset SIGPIPE");
2226 postfork_inputfile(main_input_file);
2227 postfork_inputfile(flushing_input_file);
2230 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2233 postfork_stdio(defer);
2236 #define EVERY(what, interval, body) \
2237 static const struct timeval what##_timeout = { 5, 0 }; \
2238 static void what##_schedule(void); \
2239 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2241 what##_schedule(); \
2243 static void what##_schedule(void) { \
2244 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2247 EVERY(filepoll, {5,0}, {
2248 if (main_input_file && main_input_file->readable_callback)
2249 filemon_callback(main_input_file);
2252 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s" \
2253 #define DEBUG_IPF(sh) \
2254 wh##_input_file, debug_ipf_path(wh##_input_file), \
2255 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2256 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2257 static const char *debug_ipf_path(InputFile *ipf) {
2258 char *slash= strrchr(ipf->path,'/');
2259 return slash ? slash+1 : ipf->path;
2262 EVERY(period, {PERIOD_SECONDS,0}, {
2264 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2265 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_FMT(flushing)
2266 " children connecting=%ld inndcomm_child"
2268 sms_names[sms], sm_period_counter,
2269 queue.count, conns.count, until_connect,
2270 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2271 (long)connecting_child, (long)inndcomm_child
2274 if (until_connect) until_connect--;
2276 poll_backlog_file();
2277 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2278 statemc_period_poll();
2279 check_master_queue();
2283 /*========== option parsing ==========*/
2286 of_seconds= 001000u;
2287 of_boolean= 002000u;
2290 typedef struct Option Option;
2291 typedef void OptionParser(const Option*, const char *val);
2301 void op_integer(const Option *o, const char *val) {
2304 unsigned long ul= strtoul(val,&ep,10);
2305 if (*ep || ep==val || errno || ul>INT_MAX)
2306 badusage("bad integer value for %s",o->long);
2307 int *store= o->store;
2311 void op_double(const Option *o, const char *val) {
2312 int *store= o->store;
2315 *store= strtod(val, &ep);
2316 if (*ep || ep==val || errno)
2317 badusage("bad floating point value for %s",o->long);
2320 void op_string(const Option *o, const char *val) {
2321 char **store= o->store;
2326 void op_seconds(const Option *o, const char *val) {
2327 int *store= o->store;
2330 double v= strtod(val,&ep);
2331 if (ep==val) badusage("bad time/duration value for %s",o->long);
2333 if (!*ep || !strcmp(ep,"s")) unit= 1;
2334 else if (!strcmp(ep,"m")) unit= 60;
2335 else if (!strcmp(ep,"h")) unit= 3600;
2336 else if (!strcmp(ep,"d")) unit= 86400;
2337 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2341 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2345 void op_periods_rndup(const Option *o, const char *val) {
2346 int *store= o->store;
2348 *store += PERIOD_SECONDS-1;
2349 *store /= PERIOD_SECONDS;
2352 void op_periods_booltrue(const Option *o, const char *val) {
2353 int *store= o->store;
2356 void op_periods_boolfalse(const Option *o, const char *val) {
2357 int *store= o->store;
2361 static const Option options[]= {
2362 {'f',"feedfile", &feedfile, op_string },
2363 {'q',"quiet-multiple", &quiet_multiple, op_booltrue, 1 },
2365 { 0, "max-connections", &max_connections op_integer },
2366 { 0, "max-queue-per-conn", &max_queue_per_conn op_integer },
2369 { 0, "streaming", &try_stream, op_booltrue, 1 },
2370 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2371 {'P',"port", &port op_integer },
2372 { 0, "inndconf", &inndconffile, op_string },
2373 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2374 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2376 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2377 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2379 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2380 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2381 { 0, "connection-timeout", &connection_timeout, op_seconds },
2382 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2385 int main(int argc, char **argv) {
2391 if (*arg != '-') break;
2392 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2394 while ((a= *++arg)) {
2398 char *equals= strchr(arg,'=');
2399 int len= equals ? (equals - arg) : strlen(arg);
2400 for (o=options; o->long; o++)
2401 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2403 badusage("unknown long option --%s",arg);
2406 if (equals) badusage("option --%s does not take a value",o->long);
2408 } else if (equals) {
2412 if (!arg) badusage("option --%s needs a value",o->long);
2415 break; /* eaten the whole argument now */
2417 for (o=options; o->long; o++)
2420 badusage("unknown short option -%c",a);
2427 if (!arg) badusage("option -%c needs a value",o->short);
2430 break; /* eaten the whole argument now */
2435 if (!arg) badusage("need site name argument");
2441 if (*++argv) badusage("too many non-option arguments");
2443 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2444 badusage("nocheck threshold percentage must be between 0..100");
2445 nocheck_thresh= nocheck_thresh_pct * 0.01;
2447 if (nocheck_decay_articles < 0.1)
2448 badusage("nocheck decay articles must be at least 0.1");
2449 nocheck_decay= 1 - 1/nocheck_decay_articles;
2452 pathoutgoing= innconf->pathoutgoing;
2453 innconf_read(inndconffile);
2456 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2457 else if (!feedfile[0])
2458 badusage("feed filename must be nonempty");
2459 else if (feedfile[strlen(feedfile)-1]=='/')
2460 feedfile= xasprintf("%s%s",feedfile,sitename);
2462 const char *feedfile_forbidden= "?*[~#";
2464 while ((c= *feedfile_forbidden++))
2465 if (strchr(feedfile, c))
2466 badusage("feed filename may not contain metacharacter %c",c);
2468 loop= oop_sys_new();
2469 if (!loop) sysdie("could not create liboop event loop");
2471 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2472 sysdie("could not ignore SIGPIPE");
2474 if (become_daemon) {
2475 for (i=3; i<255; i++)
2476 /* do this now before we open syslog, etc. */
2478 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2480 int null= open("/dev/null",O_RDWR);
2481 if (null<0) sysdie("failed to open /dev/null");
2487 pid_t child1= xfork("daemonise first fork");
2488 if (child1) _exit(0);
2490 pid_t sid= setsid();
2491 if (sid != child1) sysdie("setsid failed");
2493 pid_t child2= xfork("daemonise second fork");
2494 if (child2) _exit(0);
2499 if (!filemon_init()) {
2500 warn("no file monitoring available, polling");
2501 filepoll_schedule();