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
149 /*----- general definitions, probably best not changed -----*/
151 #define PERIOD_SECONDS 60
153 #define CONNCHILD_ESTATUS_STREAM 4
154 #define CONNCHILD_ESTATUS_NOSTREAM 5
156 #define INNDCOMMCHILD_ESTATUS_FAIL 6
157 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
160 /*----- configuration options -----*/
162 static char *sitename, *feedfile;
163 static int max_connections=10, max_queue_per_conn=200;
164 static int connection_setup_timeout=200, port=119, try_stream=1;
165 static int inndcomm_flush_timeout=100, quiet_if_locked=0;
166 static const char *remote_host;
167 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
168 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
169 static const char *inndconffile;
171 static double accept_proportion;
172 static double nocheck_thresh_pct= 95.0;
173 static double nocheck_thresh; /* computed in main from _pct */
174 static double nocheck_decay_articles= 100; /* converted to _decay */
175 static double nocheck_decay; /* computed in main from _articles */
176 static int nocheck, nocheck_reported;
179 /*----- doubly linked lists -----*/
181 #define ISNODE(T) T *next, *back;
182 #define LIST(T) struct { T *head, *tail, *tailpred; int count; }
184 #define NODE(n) ((struct node*)&(n)->head)
186 #define LIST_ADDHEAD(l,n) \
187 (list_addhead((struct list*)&(l), NODE((n))), (void)(l).count++)
188 #define LIST_ADDTAIL(l,n) \
189 (list_addtail((struct list*)&(l), NODE((n))), (void)(l).count++)
191 #define LIST_REMHEAD(l) \
192 ((l).count ? ((l).count--, (void*)list_remhead((struct list*)&(l))) : 0)
193 #define LIST_REMTAIL(l) \
194 ((l).count ? ((l).count--, (void*)list_remtail((struct list*)&(l))) : 0)
195 #define LIST_REMOVE(l,n) \
196 (list_remove(NODE((n))), (void)(l).count--)
197 #define LIST_INSERT(l,n,pred) \
198 (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
201 /*----- statistics -----*/
203 typedef enum { /* in queue in conn->sent */
204 art_Unchecked, /* not checked, not sent checking */
205 art_Wanted, /* checked, wanted sent body as requested */
206 art_Unsolicited, /* - sent body without check */
210 #define RESULT_COUNTS(RCS,RCN) \
218 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
219 #define RCI_TRIPLE_VALS_BASE(counts,x) \
220 , counts[art_Unchecked] x \
221 + counts[art_Wanted] x \
222 + counts[art_Unsolicited] x, \
223 counts[art_Unchecked] x \
224 , counts[art_Wanted] x \
225 , counts[art_Unsolicited] x
228 #define RC_INDEX(x) RCI_##x
229 RESULT_COUNTS(RC_INDEX, RC_INDEX)
234 /*----- transmission buffers -----*/
239 xk_Malloc, xk_Const, xk_Artdata;
251 /*----- core operational data structure types -----*/
263 typedef struct InputFile {
264 /* This is an instance of struct oop_readable */
265 struct oop_readable readable; /* first */
266 oop_readable_call *readable_callback;
267 void *readable_callback_user;
270 struct Filemon_Perfile *filemon;
273 long inprogress; /* no. of articles read but not processed */
276 int counts[art_MaxState][RCI_max];
280 #define SMS_LIST(X) \
289 #define SMS_DEF_ENUM(s) sm_##s,
290 SMS_LIST(SMS_DEF_ENUM)
293 static const char *sms_names[]= {
294 #define SMS_DEF_NAME(s) #s ,
295 SMS_LIST(SMS_DEF_NAME)
301 int fd, max_queue, stream;
302 LIST(Article) queue; /* not yet told peer, or CHECK said send it */
303 LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
304 struct iovec xmit[CONNIOVS];
305 XmitDetails xmitd[CONNIOVS];
310 /*----- operational variables -----*/
313 static LIST(Conn) idle, working, full;
314 static LIST(Article) *queue;
316 static char *path_lock, *path_flushing, *path_defer;
318 #define SMS(newstate, periods, why) \
319 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
321 static StateMachineState sms;
323 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
324 static int sm_period_counter;
327 /*----- function predeclarations -----*/
329 static void conn_check_work(Conn *conn);
331 static int filemon_init(void);
332 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
333 static void filemon_callback(void);
335 static void statemc_setstate(StateMachineState newsms, int periods,
336 const char *forlog, const char *why);
338 /*========== utility functions etc. ==========*/
340 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
342 static pid_t xfork(const char *what) {
346 if (child==-1) sysdie("cannot fork for %s",what);
347 if (!child) postfork(what);
348 debug("forked %s %ld", what, (unsigned long)child);
352 static void on_fd_read_except(int fd, oop_call_fd callback) {
353 loop->on_fd(loop, fd, OOP_READ, callback, 0);
354 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
356 static void cancel_fd_read_except(int fd) {
357 loop->cancel_fd(loop, fd, OOP_READ);
358 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
361 static void report_child_status(const char *what, int status) {
362 if (WIFEXITED(status)) {
363 int es= WEXITSTATUS(status);
365 warn("%s: child died with error exit status %d",es);
366 } else if (WIFSIGNALED(status)) {
367 int sig= WTERMSIG(status);
368 const char *sigstr= strsignal(sig);
369 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
371 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
373 warn("%s: child died due to unknown fatal signal %d%s",
374 what, sig, coredump);
376 warn("%s: child died with unknown wait status %d", status);
380 static int xwaitpid(pid_t *pid, const char *what) {
383 r= kill(*pid, SIGKILL);
384 if (r) sysdie("cannot kill %s child", what);
386 pid_t got= waitpid(*pid, &status, WNOHANG);
387 if (got==-1) sysdie("cannot reap %s child", what);
394 static void xunlink(const char *path, const char *what) {
396 if (r) sysdie("can't unlink %s %s", path, what);
399 static void check_isreg(const struct stat *stab, const char *path,
401 if (!S_ISREG(stab->st_mode))
402 die("%s %s not a plain file (mode 0%lo)",
403 what, path, (unsigned long)stab->st_mode);
406 static void xfstat(int fd, struct stat *stab_r, const char *what) {
407 int r= fstab(path, stab);
408 if (r) sysdie("could not fstat %s %s", what, path);
411 static void xfstat_isreg(int fd, struct stat *stab_r, const char *what) {
412 xfstat(fd, stab_r, what);
413 check_isreg(stab, path, what);
416 static void xlstat_isreg(const char *path, struct stat *stab,
417 int *enoent_r /* 0 means ENOENT is fatal */
419 int r= lstat(path, stab);
421 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
422 sysdie("could not lstat %s %s", what, path);
424 if (enoent_r) *enoent_r= 0;
425 check_isreg(stab, path, what);
428 static int samefile(const struct stat *a, const struct stat *b) {
429 assert(S_ISREG(a->st_mode));
430 assert(S_ISREG(b->st_mode));
431 return (a->st_ino == b->st_ino &&
432 a->st_dev == b->st_dev);
435 /*========== logging ==========*/
437 static void logcore(int sysloglevel, const char *fmt, ...)
438 __attribute__((printf,2,3))
439 static void logcore(int sysloglevel, const char *fmt, ...) {
443 vsyslog(sysloglevel,fmt,al);
445 vfprintf(stderr,fmt,al);
451 static void logv(int sysloglevel, const char *pfx, int errnoval,
452 int exitstatus, const char *fmt, va_list al)
453 __attribute__((printf,4,0))
454 static void logv(int sysloglevel, const char *pfx, int errnoval,
455 int exitstatus, const char *fmt, va_list al) {
457 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
458 msgbuf[sizeof(msgbuf)-1]= 0;
460 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
461 sysloglevel= LOG_ERR; /* run by wrong user, probably */
463 logcore(sysloglevel, "<%s>%s: %s%s%s",
464 sitename, pfx, msgbuf,
465 errnoval>=0 ? ": " : "",
466 errnoval>=0 ? strerror(errnoval) : "");
469 #define logwrap(fn, pfx, sysloglevel, errno, estatus) \
470 static void fn(const char *fmt, ...) \
471 __attribute__((printf,1,2)); \
472 static void fn(const char *fmt, ...) { \
475 logv(sysloglevel, pfx, errno, estatus, fmt, al); \
478 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
479 logwrap(die, " critical", LOG_CRIT, -1, 16);
481 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
482 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
484 logwrap(syswarn, " warning", LOG_WARN, errno, 0);
485 logwrap(warn, " warning", LOG_WARN, -1, 0);
487 logwrap(notice, "", LOG_NOTICE, -1, 0);
488 logwrap(info, " info", LOG_INFO, -1, 0);
489 logwrap(debug, " debug", LOG_DEBUG, -1, 0);
492 /*========== making new connections ==========*/
494 static int connecting_sockets[2]= {-1,-1};
495 static pid_t connecting_child;
497 static void connect_attempt_discard(void) {
498 if (connecting_sockets[0])
499 cancel_fd(connecting_sockets[0]);
501 perhaps_close(&connecting_sockets[0]);
502 perhaps_close(&connecting_sockets[1]);
504 if (connecting_child) {
505 r= kill(connecting_child, SIGTERM);
506 if (r) syswarn("failed to kill connecting child");
507 int status= xwaitpid(&connecting_child, "connect");
509 if (!(WIFEXITED(status) ||
510 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
511 report_child_status("connect", status);
515 #define PREP_DECL_MSG_CMSG(msg) \
517 memset(&msg,0,sizeof(msg)); \
518 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
519 msg.msg_control= msg##cbuf; \
520 msg.msg_controllen= sizeof(msg##cbuf);
522 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
525 conn= xmalloc(sizeof(*conn));
526 memset(conn,0,sizeof(*conn));
529 struct cmsghdr *h= 0;
530 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
531 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
534 pid_t got= waitpid(connecting_child, &status, WNOHANG);
536 assert(got==connecting_child);
538 if (WIFEXITED(status) &&
539 (WEXITSTATUS(status) != 0
540 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
541 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
542 /* child already reported the problem */
543 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
544 warn("connect: connection attempt timed out");
545 } else if (!WIFEXITED(status)) {
546 report_child_status("connect", status);
547 /* that's probably the root cause then */
550 /* child is still running apparently, report the socket problem */
552 syswarn("connect: read from child socket failed");
553 else if (e == OOP_EXCEPTIONN)
554 warn("connect: unexpected exception on child socket");
556 warn("connect: unexpected EOF on child socket");
561 #define CHK(field, val) \
562 if (h->cmsg_##field != val) { \
563 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
566 CHK(level, SOL_SOCKET);
567 CHK(type, SCM_RIGHTS);
568 CHK(len, CMSG_LEN(sizeof(conn-b>fd)));
571 if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
573 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
575 pid_t got= waitpid(connecting_child, &status, 0);
576 if (got==-1) sysdie("connect: real wait for child");
577 assert(got == connecting_child);
580 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
581 int es= WEXITSTATUS(status);
583 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
584 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
586 fatal("connect: child gave unexpected exit status %d", es);
592 LIST_ADDHEAD(idle, conn);
593 notice("#%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
594 connect_attempt_discard();
595 check_master_queue();
600 perhaps_close(&conn->fd);
603 connect_attempt_discard();
606 static void connect_start(void) {
607 assert(!connecting_sockets[0]);
608 assert(!connecting_sockets[1]);
609 assert(!connecting_child);
611 notice("starting connection attempt");
613 r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
614 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
616 connecting_child= xfork("connection");
618 if (!connecting_child) {
619 FILE *cn_from, *cn_to;
620 char buf[NNTP_STRLEN+100];
621 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
623 r= close(connecting_sockets[0]);
624 if (r) sysdie("connect: close parent socket in child");
626 alarm(connection_setup_timeout);
627 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
629 sanitise_inplace(buf);
630 fatal("connect: rejected: %s", buf);
632 sysfatal("connect: connection attempt failed");
635 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
636 sysfatal("connect: authentication failed");
638 if (fputs("MODE STREAM\r\n", cn_to) ||
640 sysfatal("connect: could not send MODE STREAM");
641 buf[sizeof(buf)-1]= 0;
642 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
644 sysfatal("connect: could not read response to MODE STREAM");
646 fatal("connect: connection close in response to MODE STREAM");
651 sanitise_inplace(buf);
652 fatal("connect: response to MODE STREAM is too long: %.100s...",
655 l--; if (l>0 && buf[1-]=='\r') l--;
658 int rcode= strtoul(buf,&ep,10);
660 sanitise_inplace(buf);
661 fatal("connect: bad response to MODE STREAM: %.50s", buf);
665 exitstatus= CONNCHILD_ESTATUS_STREAM;
671 sanitise_inplace(buf);
672 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
677 int fd= fileno(cn_from);
679 PREP_DECL_MSG_CMSG(msg);
680 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
681 cmsg->cmsg_level= SOL_SOCKET;
682 cmsg->cmsg_type= SCM_RIGHTS;
683 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
684 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
686 msg.msg_controllen= cmsg->cmsg_len;
687 r= sendmsg(connecting_sockets[1], &msg, 0);
688 if (r) sysdie("sendmsg failed for new connection");
693 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
694 if (r) sysdie("connect: close child socket in parent");
696 on_fd_read_except(connecting_sockets[0], connchild_event);
700 connect_attempt_discard();
704 /*========== overall control of article flow ==========*/
706 static void check_master_queue(void) {
710 Conn *last_assigned=0;
713 conn_assign_one_article(&working, &last_assigned);
714 } else if (idle.head) {
715 conn_assign_one_article(&idle, &last_assigned);
716 } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
717 !connecting_child && !connect_delay) {
718 connect_delay= reconnect_delay_periods;
724 conn_check_work(last_assigned);
727 static void conn_assign_one_article(LIST(Conn) *connlist,
728 Conn **last_assigned) {
729 Conn *conn= connlist->head;
731 LIST_REMOVE(*connlist, conn);
732 Article *art= LIST_REMHEAD(queue);
733 LIST_ADDTAIL(conn->queue, art);
734 LIST_ADD(*conn_determine_right_list(conn), conn);
736 /* This slightly odd arrangement is so that we call conn_check_work
737 * once after filling the queue for a new connection in
738 * check_master_queue, rather than for each article. */
739 if (conn != *last_assigned && *last_assigned)
740 conn_check_work(*last_assigned);
741 *last_assigned= conn;
744 static int conn_total_queued_articles(Conn *conn) {
745 return conn->sent.count + conn->queue.count;
748 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
749 int inqueue= conn_total_queued_articles(conn);
750 assert(inqueue <= max_queue);
751 if (inqueue == 0) return &idle;
752 if (inqueue == conn->max_queue) return &full;
756 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
761 static void conn_check_work(Conn *conn) {
764 conn_make_some_xmits(conn);
766 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
770 void *rp= conn_write_some_xmits(conn);
771 if (rp==OOP_CONTINUE) {
772 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
774 } else if (rp==OOP_HALT) {
777 /* transmitted everything */
784 static void vconnfail(Conn *conn, const char *fmt, va_list al)
785 __attribute__((printf,2,0));
787 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
788 int requeue[art_MaxState];
791 while ((art= LIST_REMHEAD(conn->queue))) LIST_ADDTAIL(queue);
792 while ((art= LIST_REMHEAD(conn->sent))) {
793 counts[art->state]++;
794 if (art->state==art_Unsolicited) art->state= art_Unchecked;
800 for (i=0, dp=&conn->xmitd; i<conn->xmitu; i++, dp++)
803 char *m= xvasprintf(fmt,al);
804 warn("#%d connection failed, requeueing " RCI_TRIPLE_FMT_BASE ": %s",
805 conn->fd, RCI_TRIPLE_FMT_VALS(requeue, /*nothing*/), m);
811 connect_delay= reconnect_delay_periods;
812 check_master_queue();
815 static void connfail(Connection *conn, const char *fmt, ...)
816 __attribute__((printf,2,3));
817 static void connfail(Connection *conn, const char *fmt, ...) {
824 /*========== article transmission ==========*/
826 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
827 XmitKind kind) { /* caller must then fill in details */
828 struct iovec *v= &conn->xmit[conn->xmitu];
829 XmitDetails *d= &conn->xmitd[conn->xmitu++];
836 static void xmit_noalloc(Conn *conn, const char *data, int len) {
837 xmit_core(conn,data,len, xk_Const);
839 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
841 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
842 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
846 static void xmit_free(XmitDetails *d) {
848 case xk_Malloc: free(d->info.malloc_tofree); break;
849 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
850 case xk_Const: break;
855 static void *conn_write_some_xmits(Conn *conn) {
857 * 0: nothing more to write, no need to call us again
858 * OOP_CONTINUE: more to write but fd not writeable
859 * OOP_HALT: disaster, have destroyed conn
862 int count= conn->xmitu;
863 if (!count) return 0;
865 if (count > IOV_MAX) count= IOV_MAX;
866 ssize_t rs= writev(conn->fd, conn->xmit, count);
868 if (errno == EAGAIN) return OOP_CONTINUE;
869 connfail(conn, "write failed: %s", strerror(errno));
874 for (done=0; rs && done<xmitu; done++) {
875 struct iovec *vp= &conn->xmit[done];
876 XmitDetails *dp= &conn->xmitd[done];
877 if (rs > vp->iov_len) {
885 int newu= conn->xmitu - done;
886 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
887 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
892 static void conn_make_some_xmits(Conn *conn) {
894 if (conn->xmitu+5 > CONNIOVS)
897 Article *art= LIST_REMHEAD(queue);
900 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
901 /* actually send it */
903 ARTHANDLE *artdata= SMretrieve();
907 XMIT_LITERAL("TAKETHIS ");
908 xmit_noalloc(conn, art->mid, art->midlen);
909 XMIT_LITERAL("\r\n");
910 xmit_artbody(conn, artdata);
913 /* we got 235 from IHAVE */
915 xmit_artbody(conn, artdata);
917 XMIT_LITERAL(".\r\n");
922 art->state == art_Unchecked ? art_Unsolicited :
923 art->state == art_Wanted ? art_Wanted :
925 art->ipf->counts[art->state].sent++;
926 LIST_ADDTAIL(conn->sent, art);
932 XMIT_LITERAL("IHAVE ");
934 XMIT_LITERAL("CHECK ");
935 xmit_noalloc(art->mid, art->midlen);
936 XMIT_LITERAL("\r\n");
938 assert(art->state == art_Unchecked);
939 art->ipf->counts[art->state].sent++;
940 LIST_ADDTAIL(conn->sent, art);
946 /*========== handling responses from peer ==========*/
948 static const oop_rd_style peer_rd_style= {
949 OOP_RD_DELIM_STRIP, '\n',
951 OOP_RD_SHORTREC_FORBID
954 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
955 const char *errmsg, int errnoval,
956 const char *data, size_t recsz, void *conn_v) {
958 connfail(conn, "error receiving from peer: %s", errmsg);
962 static Article *article_reply_check(Connection *conn, const char *response,
963 int code_indicates_streaming,
965 /* 1:yes, -1:no, 0:dontcare */,
966 const char *sanitised_response) {
967 Article *art= conn->sent.head;
971 "peer gave unexpected response when no commands outstanding: %s",
976 if (code_indicates_streaming) {
977 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
979 connfail("peer gave streaming response code "
980 " to IHAVE or subsequent body: %s", sanitised_response);
983 const char *got_mid= response+4;
984 int got_midlen= strcspn(got_mid, " \n\r");
985 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
986 connfail("peer gave streaming response with syntactically invalid"
987 " messageid: %s", sanitised_response);
990 if (got_midlen != art->midlen ||
991 memcmp(got_mid, art->messageid, got_midlen)) {
992 connfail("peer gave streaming response code to wrong article -"
993 " probable synchronisation problem; we offered: %s;"
995 art->messageid, sanitised_response);
1000 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
1001 sanitised_response);
1006 if (must_have_sent>0 && art->state < art_Wanted) {
1007 connfail("peer says article accepted but we had not sent the body: %s",
1008 sanitised_response);
1011 if (must_have_sent<0 && art->state >= art_Wanted) {
1012 connfail("peer says please sent the article but we just did: %s",
1013 sanitised_response);
1017 Article *art_again= LIST_REMHEAD(conn->sent);
1018 assert(art_again == art);
1022 static void update_nocheck(int accepted) {
1023 accept_proportion *= accept_decay;
1024 accept_proportion += accepted;
1025 int new_nocheck= accept_proportion >= nocheck_thresh;
1026 if (new_nocheck && !nocheck_reported) {
1027 notice("entering nocheck mode for the first time");
1028 nocheck_reported= 1;
1029 } else if (new_nocheck != nocheck) {
1030 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1032 nocheck= new_nocheck;
1035 static void article_done(Connection *conn, Article *art, int whichcount) {
1036 art->ipf->counts[art->state][whichcount]++;
1037 if (whichcount == RC_accepted) update_nocheck(1);
1038 else if (whichcount == RC_unwanted) update_nocheck(0);
1040 InputFile *ipf= art->ipf;
1041 while (art->blanklen) {
1042 static const char spaces[]=
1047 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1048 int r= pwrite(ipf->fd, spaces, w, art->offset);
1050 if (errno==EINTR) continue;
1051 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1052 art->messageid, art->blanklen, art->offset, ipf->path);
1054 assert(r>=0 && r<=w);
1060 assert(ipf->inprogress >= 0);
1062 if (!ipf->inprogress && ipf != main_input_file)
1063 queue_check_input_done();
1068 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1069 const char *errmsg, int errnoval,
1070 const char *data, size_t recsz, void *conn_v) {
1073 if (ev == OOP_RD_EOF) {
1074 connfail(conn, "unexpected EOF from peer");
1075 return OOP_CONTINUE;
1077 assert(ev == OOP_RD_OK);
1080 unsigned long code= strtoul(data, &ep, 10);
1081 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1083 const char *p= data;
1087 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
1089 if (!c) { *q++= '\''; break; }
1090 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
1091 sprintf(q,"\\x%02x",c);
1094 connfail(conn, "badly formatted response from peer: %s", sanibuf);
1095 return OOP_CONTINUE;
1098 if (conn->quitting) {
1100 connfail(conn, "peer gave failure response to QUIT: %s", sani);
1101 return OOP_CONTINUE;
1109 #define GET_ARTICLE(musthavesent) \
1110 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1111 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1113 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1114 code_streaming= (streaming) \
1115 GET_ARTICLE(musthavesent); \
1116 article_done(conn, art, RC_##how); break;
1118 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1120 int code_streaming= 0;
1124 case 400: PEERBADMSG("peer stopped accepting articles");
1125 case 503: PEERBADMSG("peer timed us out");
1126 default: PEERBADMSG("peer sent unexpected message");
1128 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1129 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1131 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1132 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1134 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1135 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1137 case 238: /* CHECK says send it */
1139 case 335: /* IHAVE says send it */
1141 assert(art->state == art_Unchecked);
1142 art->ipf->counts[art->state].accepted++;
1143 art->state= art_Wanted;
1144 LIST_ADDTAIL(conn->queue);
1147 case 431: /* CHECK or TAKETHIS says try later */
1149 case 436: /* IHAVE says try later */
1152 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1154 sysfatal("write to defer file %s",path_defer);
1155 article_done(conn, art, RC_deferred);
1160 check_check_work(conn);
1161 return OOP_CONTINUE;
1165 /*========== monitoring of input files ==========*/
1167 static void feedfile_eof(InputFile *ipf) {
1168 assert(ipf != main_input_file); /* promised by tailing_try_read */
1170 inputfile_tailing_stop(ipf);
1171 assert(ipf->fd >= 0);
1172 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1175 if (ipf == flushing_input_file) {
1176 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1177 if (main_input_file) inputfile_tailing_start(main_input_file);
1178 statemc_check_flushing_done();
1179 } else if (ipf == backlog_input_file) {
1180 statemc_check_backlog_done();
1182 abort(); /* supposed to wait rather than get EOF on main input file */
1186 static InputFile *open_input_file(const char *path) {
1187 int fd= open(path, O_RDONLY);
1189 if (errno==ENOENT) return 0;
1190 sysfatal("unable to open input file %s", path);
1193 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1194 memset(ipf,0,sizeof(*ipf));
1196 ipf->readable.on_readable= tailing_on_readable;
1197 ipf->readable.on_cancel= tailing_on_cancel;
1198 ipf->readable.try_read= tailing_try_read;
1201 strcpy(ipf->path, path);
1206 static void close_input_file(InputFile *ipf) {
1207 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1208 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1209 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1210 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1213 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1217 /*---------- dealing with articles read in the input file ----------*/
1219 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1220 oop_rd_event ev, const char *errmsg,
1222 const char *data, size_t recsz,
1224 InputFile *ipf= ipf_v;
1226 char tokentextbuf[sizeof(TOKEN)*2+3];
1228 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1230 if (data[0] && data[0]!=' ') {
1231 char *space= strchr(data,' ');
1232 int tokenlen= space-data;
1233 int midlen= (int)recsz-tokenlen-1;
1234 if (midlen < 0) goto bad_data;
1236 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1237 memcpy(tokentextbuf, data, tokenlen);
1238 tokentextbuf[tokenlen]= 0;
1239 if (!IsToken(tokentextbuf)) goto bad_data;
1241 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1242 art->offset= ipf->offset;
1243 art->blanklen= recsz;
1244 art->midlen= midlen;
1245 art->state= art_Unchecked;
1246 art->ipf= ipf; ipf->inprogress++;
1247 art->token= TextToToken(tokentextbuf);
1248 strcpy(art->messageid, space+1);
1249 LIST_ADDTAIL(queue, art);
1251 ipf->offset += recsz + 1;
1253 if (sms==sm_NORMAL && ipf==main_input_file &&
1254 ipf->offset >= flush_threshold)
1255 statemc_start_flush("feed file size");
1257 check_master_queue();
1260 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1261 assert(sms == sm_NORMAL);
1263 debug("starting flush (%s) (%lu >= %lu) (%d)",
1265 (unsigned long)ipf->offset, (unsigned long)flush_threshold,
1268 int r= link(feedfile, duct_path);
1269 if (r) sysdie("link feedfile %s to flushing file %s", feedfile,
1273 xunlink(feedfile, "old feedfile link");
1276 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1279 /*========== tailing input file ==========*/
1281 static void filemon_start(InputFile *ipf) {
1282 assert(!ipf->filemon);
1284 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1285 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1286 filemon_method_startfile(ipf, ipf->filemon);
1289 static void filemon_stop(InputFile *ipf) {
1290 if (!ipf->filemon) return;
1291 filemon_method_stopfile(ipf, ipf->filemon);
1296 static void filemon_callback(InputFile *ipf) {
1297 ipf->readable_callback(ipf->readable_callback_user);
1300 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1302 InputFile *ipf= user;
1303 return ipf->readable_callback(ipf->readable_callback_user);
1306 static void on_cancel(struct oop_readable *rable) {
1307 InputFile *ipf= (void*)rable;
1309 if (ipf->filemon) filemon_stopfile(ipf);
1310 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1311 ipf->readable_callback= 0;
1314 static void tailing_queue_readable(InputFile *ipf) {
1315 /* lifetime of ipf here is OK because destruction will cause
1316 * on_cancel which will cancel this callback */
1317 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1320 static int tailing_on_readable(struct oop_readable *rable,
1321 oop_readable_call *cb, void *user) {
1322 InputFile *ipf= (void*)rable;
1324 tailing_on_cancel(rable);
1325 ipf->readable_callback= cb;
1326 ipf->readable_callback_user= user;
1327 filemon_startfile(ipf);
1329 tailing_queue_readable(ipf);
1333 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1335 InputFile *ipf= (void*)rable;
1337 ssize_t r= read(ipf->fd, buffer, length);
1339 if (errno==EINTR) continue;
1343 if (ipf==main_input_file) {
1346 } else if (ipf==flushing_input_file) {
1348 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1349 } else if (ipf==backlog_input_file) {
1359 /*---------- filemon implemented with inotify ----------*/
1361 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1362 #define HAVE_FILEMON
1364 #include <linux/inotify.h>
1366 static int filemon_inotify_fd;
1367 static int filemon_inotify_wdmax;
1368 static InputFile **filemon_inotify_wd2ipf;
1370 typedef struct Filemon_Perfile {
1372 } Filemon_Inotify_Perfile;
1374 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1375 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1376 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1378 if (wd >= filemon_inotify_wdmax) {
1380 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1381 sizeof(*filemon_inotify_wd2ipf) * newmax);
1382 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1383 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1384 filemon_inotify_wdmax= newmax;
1387 assert(!filemon_inotify_wd2ipf[wd]);
1388 filemon_inotify_wd2ipf[wd]= ipf;
1390 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1391 ipf, wd, filemon_inotify_wdmax);
1396 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1398 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1399 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1400 if (r) sysdie("inotify_rm_watch");
1401 filemon_inotify_wd2ipf[wd]= 0;
1404 static void *filemon_inotify_readable(oop_source *lp, int fd,
1405 oop_event e, void *u) {
1406 struct inotify_event iev;
1408 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1410 if (errno==EAGAIN) break;
1411 sysdie("read from inotify master");
1412 } else if (r==sizeof(iev)) {
1413 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1415 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1417 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1418 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1419 filemon_callback(ipf);
1421 return OOP_CONTINUE;
1424 static int filemon_method_init(void) {
1425 filemon_inotify_fd= inotify_init();
1426 if (filemon_inotify_fd<0) {
1427 syswarn("could not initialise inotify: inotify_init failed");
1431 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1433 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1437 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1439 /*---------- filemon dummy implementation ----------*/
1441 #if !defined(HAVE_FILEMON)
1443 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1445 static int filemon_method_init(void) { return 0; }
1446 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1447 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1449 #endif /* !HAVE_FILEMON */
1451 /*---------- interface to start and stop an input file ----------*/
1453 static const oop_rd_style feedfile_rdstyle= {
1454 OOP_RD_DELIM_STRIP, '\n',
1456 OOP_RD_SHORTREC_EOF,
1459 static void inputfile_tailing_start(InputFile *ipf) {
1461 ipf->readable->on_readable= tailing_on_readable;
1462 ipf->readable->on_cancel= tailing_on_cancel;
1463 ipf->readable->try_read= tailing_try_read;
1464 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1465 ipf->readable->delete_kill= 0;
1467 ipf->readable_callback= 0;
1468 ipf->readable_callback_user= 0;
1470 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1473 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1474 feedfile_got_article,ipf, feedfile_problem,ipf);
1475 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1478 static void inputfile_tailing_stop(InputFile *ipf) {
1480 oop_rd_cancel(ipf->rd);
1481 oop_rd_delete(ipf->rd);
1483 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1487 /*========== interaction with innd - state machine ==========*/
1489 /* See official state diagram at top of file. We implement
1500 |`---------------------------------------------------.
1502 |`---------------- - - - |
1503 D ENOENT | D EXISTS see OVERALL STATES diagram |
1504 | for full startup logic |
1507 | ============ try to |
1513 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1514 ^ | hardlink F to D |
1517 | | our handle onto F is now onto D |
1520 | |<-------------------<---------------------<---------+
1522 | | spawn inndcomm flush |
1524 | ================== |
1525 | FLUSHING[-ABSENT] |
1527 | main D tail/none |
1528 | ================== |
1530 | | INNDCOMM FLUSH FAILS ^
1531 | |`----------------------->----------. |
1533 | | NO SUCH SITE V |
1534 ^ |`--------------->----. ==================== |
1535 | | \ FLUSHFAILED[-ABSENT] |
1537 | | FLUSH OK \ main D tail/none |
1538 | | open F \ ==================== |
1540 | | \ | TIME TO RETRY |
1541 | |`------->----. ,---<---'\ `----------------'
1542 | | D NONE | | D NONE `----.
1544 | ============= V V ============
1545 | SEPARATED-1 | | DROPPING-1
1546 | flsh->fd>=0 | | flsh->fd>=0
1547 | [Separated] | | [Dropping]
1548 | main F idle | | main none
1549 | old D tail | | old D tail
1550 | ============= | | ============
1552 ^ | EOF ON D | | defer | EOF ON D
1554 | =============== | | ===============
1555 | SEPARATED-2 | | DROPPING-2
1556 | flsh->fd==-1 | V flsh->fd==-1
1557 | [Finishing] | | [Dropping]
1558 | main F tail | `. main none
1559 | old D closed | `. old D closed
1560 | =============== V `. ===============
1562 | | ALL D PROCESSED `. | ALL D PROCESSED
1563 | V install defer as backlog `. | install defer
1564 ^ | close D `. | close D
1565 | | unlink D `. | unlink D
1568 `----------' ==============
1588 static void statemc_init(void) {
1589 struct stat stab, stabf;
1591 path_lock= xasprintf("%s_lock", feedfile);
1592 path_flushing= xasprintf("%s_flushing", feedfile);
1593 path_defer= xasprintf("%s_defer", feedfile);
1594 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1597 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1598 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1601 memset(&fl,0,sizeof(fl));
1603 fl.l_whence= SEEK_SET;
1604 r= fcntl(lockfd, F_SETLK, &fl);
1606 if (errno==EACCES || errno==EAGAIN) {
1607 if (quiet_if_locked) exit(0);
1608 fatal("another duct holds the lockfile");
1610 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1613 xfstat_isreg(lockfd, &stabf, "lockfile");
1615 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1617 if (!lock_noent && samefile(&stab, &stabf))
1621 sysdie("could not close stale lockfile %s", path_lock);
1623 debug("startup: locked");
1625 search_backlog_file();
1628 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1630 debug("startup: ductdefer ENOENT");
1632 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1633 switch (stab.st_nlink==1) {
1635 open_defer(); /* so that we will later close it and rename it */
1638 xunlink(path_defer, "stale defer file link"
1639 " (presumably hardlink to backlog file)");
1642 die("defer file %s has unexpected link count %d",
1643 path_defer, stab.st_nlink);
1647 struct stat stab_f, stab_d;
1650 InputFile *file_d= open_input_file(path_flushing);
1651 if (file_d) xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1653 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1655 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1656 debug("startup: F==D => Hardlinked");
1657 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1662 debug("startup: F ENOENT => Moved");
1663 if (file_d) startup_set_input_file(file_d);
1664 spawn_inndcomm_flush("feedfile missing at startup");
1665 /* => Flushing, sms:=FLUSHING */
1668 debug("startup: F!=D => Separated");
1669 startup_set_input_file(file_d);
1670 SMS(SEPARATED, 0, "found both old and current feed files");
1672 debug("startup: F exists, D ENOENT => Normal");
1673 FILE *file_f= open_input_file(feedfile);
1674 if (!file_f) die("feed file vanished during startup");
1675 startup_set_input_file(file_f);
1676 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1681 static void statemc_period_poll(void) {
1682 if (!sm_period_counter) return;
1683 sm_period_counter--;
1684 assert(sm_period_counter>=0);
1686 if (sm_period_counter) return;
1689 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1691 case sm_FLUSHFAILED:
1692 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1699 static void startup_set_input_file(InputFile *f) {
1700 assert(!main_input_file);
1702 inputfile_tailing_start(f);
1705 static int inputfile_is_done(InputFile *ipf) {
1707 if (ipf->inprogress) return 0; /* new article in the meantime */
1708 if (ipf->fd >= 0); return 0; /* not had EOF */
1712 static void notice_processed(InputFile *ipf, const char *what,
1714 #define RCI_NOTHING(x) /* nothing */
1715 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
1716 #define RCI_TRIPLE_VALS(x) RCI_TRIPLE_VALS_BASE(ipf->counts, .x)
1718 info("processed %s%s offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
1719 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
1722 ipf->counts[art_Unchecked].sent + ipf->counts[art_Unsolicited].sent
1723 , ipf->counts[art_Unchecked].sent, ipf->counts[art_Unsolicited].sent,
1724 ipf->counts[art_Wanted].accepted + ipf->counts[art_Unsolicited].accepted
1725 ,ipf->counts[art_Wanted].accepted,ipf->counts[art_Unsolicited].accepted
1726 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
1730 static void statemc_check_backlog_done(void) {
1731 InputFile *ipf= backlog_input_file();
1732 if (!inputfile_is_done(ipf)) return;
1734 const char *slash= strrchr(ipf->path, "/");
1735 const char *leaf= slash ? slash+1 : ipf->path;
1736 const char *under= strchr(slash, "_");
1737 const char *rest= under ? under+1 : leaf;
1738 if (!strncmp(rest,"backlog",7)) rest += 7;
1739 notice_processed(ipf,"backlog:",rest);
1741 close_input_file(ipf);
1742 if (unlink(ipf->path)) {
1743 if (errno != ENOENT)
1744 sysdie("could not unlink processed backlog file %s", ipf->path);
1745 warn("backlog file %s vanished while we were reading it"
1746 " so we couldn't remove it (but it's done now, anyway)",
1750 backlog_input_file= 0;
1751 search_backlog_file();
1755 static void statemc_check_flushing_done(void) {
1756 InputFile *ipf= flushing_input_file;
1757 if (!inputfile_is_done(ipf)) return;
1759 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1761 notice_processed(ipf,"feedfile",0);
1765 xunlink(path_flushing, "old flushing file");
1767 close_input_file(flushing_input_file);
1768 free(flushing_input_file);
1769 flushing_input_file= 0;
1771 if (sms==sm_SEPARATED) {
1772 notice("flush complete");
1773 SMS(NORMAL, 0, "flush complete");
1774 } else if (sms==sm_DROPPING) {
1775 SMS(DROPPED, 0, "old flush complete");
1776 search_backlog_file();
1777 notice("feed dropped, but will continue until backlog is finished");
1781 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
1783 assert(!inputfile_is_done(main_input_file));
1784 statemc_check_flushing_done();
1785 statemc_check_backlog_done();
1786 return OOP_CONTINUE;
1789 static void queue_check_input_done(void) {
1790 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
1793 static void statemc_setstate(StateMachineState newsms, int periods,
1794 const char *forlog, const char *why) {
1796 sm_period_counter= periods;
1798 const char *xtra= "";
1800 case sm_FLUSHING: sm_FLUSHFAILED:
1801 if (!main_input_file) xtra= "-ABSENT";
1803 case sm_SEPARATED: case sm_DROPPING:
1804 xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
1810 info("%s%s[%d] %s",forlog,xtra,periods,why);
1812 info("%s%s %s",forlog,xtra,why);
1816 /*---------- defer and backlog files ----------*/
1818 static void open_defer(void) {
1823 defer= fopen(path_defer, "a+");
1824 if (!defer) sysfatal("could not open defer file %s", path_defer);
1826 /* truncate away any half-written records */
1828 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1830 if (stab.st_size > LONG_MAX)
1831 die("defer file %s size is far too large", path_defer);
1836 long orgsize= stab.st_size;
1837 long truncto= stab.st_size;
1839 if (!truncto) break; /* was only (if anything) one half-truncated record */
1840 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1841 sysdie("seek in defer file %s while truncating partial", path_defer);
1846 sysdie("failed read from defer file %s", path_defer);
1848 die("defer file %s shrank while we were checking it!", path_defer);
1854 if (stab.st_size != truncto) {
1855 warn("truncating half-record at end of defer file %s -"
1856 " shrinking by %ld bytes from %ld to %ld",
1857 path_defer, orgsize - truncto, orgsize, truncto);
1860 sysfatal("could not flush defer file %s", path_defer);
1861 if (ftruncate(fileno(defer), truncto))
1862 sysdie("could not truncate defer file %s", path_defer);
1865 info("continuing existing defer file %s (%ld bytes)",
1866 path_defer, orgsize);
1868 if (fseek(defer, truncto, SEEK_SET))
1869 sysdie("could not seek to new end of defer file %s", path_defer);
1872 static void close_defer(void) {
1876 xfstat(fileno(defer), &stab, "defer file");
1878 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1881 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1882 (unsigned long)now.tv_sec,
1883 (unsigned long)stab.st_ino);
1884 if (link(path_defer, path_backlog))
1885 sysfatal("could not install defer file %s as backlog file %s",
1886 path_defer, backlog);
1887 if (unlink(path_defer))
1888 sysdie("could not unlink old defer link %s to backlog file %s",
1889 path_defer, backlog);
1891 if (until_backlog_nextscan < 0 ||
1892 until_backlog_nextscan > backlog_retry_minperiods + 1)
1893 until_backlog_nextscan= backlog_retry_minperiods + 1;
1896 static void poll_backlog_file(void) {
1897 if (until_backlog_nextscan < 0) return;
1898 if (until_backlog_nextscan-- > 0) return;
1899 search_backlog_file();
1902 static void search_backlog_file(void) {
1903 /* returns non-0 iff there are any backlog files */
1908 const char *oldest_path=0;
1909 time_t oldest_mtime, now;
1911 if (backlog_input_file) return 3;
1915 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
1919 sysdie("failed to expand backlog pattern %s", globpat_backlog);
1921 die("out of memory expanding backlog pattern %s", globpat_backlog);
1923 for (i=0; i<gl.gl_pathc; i++) {
1924 const char *path= gl.gl_pathv[i];
1926 if (strchr(path,'#') || strchr(path,'~')) {
1927 debug("backlog file search skipping %s", path);
1930 r= stat(path, &stab);
1932 syswarn("failed to stat backlog file %s", path);
1935 if (!S_ISREG(stab.st_mode)) {
1936 warn("backlog file %s is not a plain file (or link to one)", path);
1939 if (!oldest_path || stab.st_mtime < oldest_mtime) {
1941 oldest_mtime= stab.st_mtime;
1944 case GLOB_NOMATCH: /* fall through */
1947 sysdie("glob expansion of backlog pattern %s gave unexpected"
1948 " nonzero (error?) return value %d", globpat_backlog, r);
1954 debug("backlog scan: none");
1956 if (sms==sm_DROPPED) {
1957 notice("feed dropped and our work is complete");
1958 xunlink(path_lock, "lockfile for old feed");
1961 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
1965 now= time(); if (now==-1) sysdie("time(2) failed");
1966 double age= difftime(now, oldest_mtime);
1967 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
1969 if (age_deficiency <= 0) {
1970 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
1971 age, age_deficiency, oldest_path);
1973 backlog_input_file= open_input_file(oldest_path);
1974 if (!backlog_input_file) {
1975 warn("backlog file %s vanished as we opened it", backlog_input_file);
1978 inputfile_tailing_start(backlog_input_file);
1979 until_backlog_nextscan= -1;
1983 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
1985 if (backlog_spontaneous_rescan_periods >= 0 &&
1986 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
1987 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
1989 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
1990 age, age_deficiency, until_backlog_nextscan, oldest_path);
1994 /*========== flushing the feed ==========*/
1996 static pid_t inndcomm_child;
1998 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1999 assert(inndcomm_child);
2000 int status= xwaitpid(&inndcomm_child, "inndcomm");
2001 loop->cancel_fd(fd);
2004 assert(!flushing_input_file);
2006 if (WIFEXITED(status)) {
2007 switch (WEXITSTATUS(status)) {
2009 case INNDCOMMCHILD_ESTATUS_FAIL:
2012 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2013 warn("feed has been dropped by innd, finishing up");
2014 flushing_input_file= main_input_file;
2015 tailing_queue_readable(flushing_input_file);
2016 /* we probably previously returned EAGAIN from our fake read method
2017 * when in fact we were at EOF, so signal another readable event
2018 * so we actually see the EOF */
2022 if (flushing_input_file) {
2023 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2026 SMS(DROPPED, 0, "feed dropped by innd");
2027 search_backlog_file();
2029 return OOP_CONTINUE;
2033 flushing_input_file= main_input_file;
2034 tailing_queue_readable(flushing_input_file);
2036 main_input_file= open_input_file(feedfile);
2037 if (!main_input_file)
2038 die("flush succeeded but feedfile %s does not exist!", feedfile);
2040 if (flushing_input_file) {
2041 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2044 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2046 return OOP_CONTINUE;
2049 goto unexpected_exitstatus;
2052 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2053 warn("flush timed out trying to talk to innd");
2056 unexpected_exitstatus:
2057 report_child_status("inndcomm child", status);
2061 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2064 static void inndcommfail(const char *what) {
2065 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2066 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2069 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2072 notice("flushing %s",why);
2074 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2075 assert(!inndcomm_child);
2077 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2079 inndcomm_child= xfork();
2081 if (!inndcomm_child) {
2082 static char flushargv[2]= { sitename, 0 };
2087 alarm(inndcomm_flush_timeout);
2088 r= ICCopen(); if (r) inndcommfail("connect");
2089 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2090 if (!r) exit(0); /* yay! */
2092 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2093 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2094 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2098 int sentinel_fd= pipefds[0];
2099 on_fd_read_except(sentinel_fd, inndcomm_event);
2101 SMS(FLUSHING, 0, why);
2104 /*========== main program ==========*/
2106 static void postfork_inputfile(InputFile *ipf) {
2108 assert(ipf->fd >= 0);
2113 static void postfork_conns(Connection *conn) {
2120 static void postfork_stdio(FILE *f) {
2121 /* we have no stdio streams that are buffered long-term */
2125 static void postfork(const char *what) {
2126 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2127 sysdie("%s child: failed to reset SIGPIPE");
2129 postfork_inputfile(main_input_file);
2130 postfork_inputfile(flushing_input_file);
2131 postfork_conns(idle.head);
2132 postfork_conns(working.head);
2133 postfork_conns(full.head);
2134 postfork_stdio(defer);
2137 #define EVERY(what, interval, body) \
2138 static const struct timeval what##_timeout = { 5, 0 }; \
2139 static void what##_schedule(void); \
2140 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2142 what##_schedule(); \
2144 static void what##_schedule(void) { \
2145 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2148 EVERY(filepoll, {5,0}, {
2149 if (main_input_file && main_input_file->readable_callback)
2150 filemon_callback(main_input_file);
2153 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s" \
2154 #define DEBUG_IPF(sh) \
2155 wh##_input_file, debug_ipf_path(wh##_input_file), \
2156 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2157 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2158 static const char *debug_ipf_path(InputFile *ipf) {
2159 char *slash= strrchr(ipf->path,'/');
2160 return slash ? slash+1 : ipf->path;
2163 EVERY(period, {PERIOD_SECONDS,0}, {
2165 " sms=%s[%d] queue=%d connect_delay=%d"
2166 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_FMT(flushing)
2167 " conns idle=%d working=%d full=%d"
2168 " children connecting=%ld inndcomm_child"
2170 sms_names[sms], sm_period_counter, queue.count, connect_delay,
2171 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2172 idle.count, working.count, full.count,
2173 (long)connecting_child, (long)inndcomm_child
2176 if (connect_delay) connect_delay--;
2178 poll_backlog_file();
2179 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2180 statemc_period_poll();
2181 check_master_queue();
2185 /*========== option parsing ==========*/
2188 of_seconds= 001000u;
2189 of_boolean= 002000u;
2192 typedef struct Option Option;
2193 typedef void OptionParser(const Option*, const char *val);
2203 void op_integer(const Option *o, const char *val) {
2206 unsigned long ul= strtoul(val,&ep,10);
2207 if (*ep || ep==val || errno || ul>INT_MAX)
2208 badusage("bad integer value for %s",o->long);
2209 int *store= o->store;
2213 void op_double(const Option *o, const char *val) {
2214 int *store= o->store;
2217 *store= strtod(val, &ep);
2218 if (*ep || ep==val || errno)
2219 badusage("bad floating point value for %s",o->long);
2222 void op_string(const Option *o, const char *val) {
2223 char **store= o->store;
2228 void op_seconds(const Option *o, const char *val) {
2229 int *store= o->store;
2232 double v= strtod(val,&ep);
2233 if (ep==val) badusage("bad time/duration value for %s",o->long);
2235 if (!*ep || !strcmp(ep,"s")) unit= 1;
2236 else if (!strcmp(ep,"m")) unit= 60;
2237 else if (!strcmp(ep,"h")) unit= 3600;
2238 else if (!strcmp(ep,"d")) unit= 86400;
2239 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2243 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2247 void op_periods_rndup(const Option *o, const char *val) {
2248 int *store= o->store;
2250 *store += PERIOD_SECONDS-1;
2251 *store /= PERIOD_SECONDS;
2254 void op_periods_booltrue(const Option *o, const char *val) {
2255 int *store= o->store;
2258 void op_periods_boolfalse(const Option *o, const char *val) {
2259 int *store= o->store;
2263 static const Option options[]= {
2264 { 0, "max-connections", &max_connections op_integer },
2265 { 0, "streaming", &try_stream, op_booltrue, 1 },
2266 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2267 {'h',"host", &remote_host, op_string },
2268 {'P',"port", &port op_integer },
2269 { 0, "inndconf", &inndconffile, op_string },
2270 {'f',"feedfile", &feedfile, op_string },
2271 {'q',"quiet-multiple", &quiet_if_locked, op_booltrue, 1 },
2272 { 0, "no-quiet-multiple", &quiet_if_locked, op_boolfalse, 1 },
2273 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2274 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2276 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2277 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2279 { 0, "max-queue-size", &max_queue_per_conn op_integer },
2280 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2281 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2282 { 0, "connection-timeout", &connection_timeout, op_seconds },
2283 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2286 int main(int argc, char **argv) {
2292 if (*arg != '-') break;
2293 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2295 while ((a= *++arg)) {
2299 char *equals= strchr(arg,'=');
2300 int len= equals ? (equals - arg) : strlen(arg);
2301 for (o=options; o->long; o++)
2302 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2304 badusage("unknown long option --%s",arg);
2307 if (equals) badusage("option --%s does not take a value",o->long);
2309 } else if (equals) {
2313 if (!arg) badusage("option --%s needs a value",o->long);
2316 break; /* eaten the whole argument now */
2318 for (o=options; o->long; o++)
2321 badusage("unknown short option -%c",a);
2328 if (!arg) badusage("option -%c needs a value",o->short);
2331 break; /* eaten the whole argument now */
2336 if (!arg) badusage("need site name argument");
2339 if ((arg= *++argv)) {
2340 if (remote_host) badusage("must not specify -h and also host as argument");
2344 if (*++argv) badusage("too many non-option arguments");
2346 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2347 badusage("nocheck threshold percentage must be between 0..100");
2348 nocheck_thresh= nocheck_thresh_pct * 0.01;
2350 if (nocheck_decay_articles < 0.1)
2351 badusage("nocheck decay articles must be at least 0.1");
2352 nocheck_decay= 1 - 1/nocheck_decay_articles;
2354 innconf_read(inndconffile);
2357 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2358 else if (!feedfile[0])
2359 badusage("feed filename must be nonempty");
2360 else if (feedfile[strlen(feedfile)-1]=='/')
2361 feedfile= xasprintf("%s%s",feedfile,sitename);
2363 const char *feedfile_forbidden= "?*[~#";
2365 while ((c= *feedfile_forbidden++))
2366 if (strchr(feedfile, c))
2367 badusage("feed filename may not contain metacharacter %c",c);
2369 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2370 sysdie("could not ignore SIGPIPE");
2372 if (become_daemon) {
2373 for (i=3; i<255; i++)
2374 /* do this now before we open syslog, etc. */
2376 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2378 int null= open("/dev/null",O_RDWR);
2379 if (null<0) sysdie("failed to open /dev/null");
2385 pid_t child1= xfork("daemonise first fork");
2386 if (child1) _exit(0);
2388 pid_t sid= setsid();
2389 if (sid != child1) sysdie("setsid failed");
2391 pid_t child2= xfork("daemonise second fork");
2392 if (child2) _exit(0);
2397 if (!filemon_init()) {
2398 warn("no file monitoring available, polling");
2399 filepoll_schedule();