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 * site.name_duct.lock lock preventing multiple ducts
19 * holder of this lock is "duct"
20 * F site.name main feed file
21 * opened/created, then written, by innd
24 * tokens blanked out by duct when processed
25 * D site.name_duct temporary feed file during flush (or crash)
26 * hardlink created by duct
28 * site.name_duct.defer 431'd articles, still being written,
29 * created, written, used by duct
30 * site.name_backlog.lock lock taken out by innxmit wrapper
31 * holder and its child are "xmit"
32 * site.name_backlog_<date>.<inum>
33 * 431'd articles, ready for innxmit
34 * created (link/mv) by duct
37 * site.name_backlog_<letters> eg
38 * site.name_backlog_manual
39 * anything the sysadmin likes (eg, feed files
40 * from old feeds to be merged into this one)
41 * created (link/mv) by admin
52 <--------------------------------------'|
53 Nothing F, D both ENOENT |
56 duct: not not reading anything |
58 |`---------------------. |
59 | | duct times out waiting for F |
60 V innd creates F | duct exits |
62 Noduct GO TO Dropped |
65 duct: not running or not reading anything |
68 ,-->--+ <---------------------------------'|
69 | | duct opens F F exists |
73 | F: innd writing, duct reading |
76 | | duct decides time to flush |
77 | | duct makes hardlink |
79 | V <------------------------'|
81 | F == D: innd writing, duct reading both exist |
85 | Moved <----+------------<--'|
86 | F: ENOENT | F ENOENT |
87 | D: innd writing, duct reading | D exists |
89 | | duct requests flush of feed | |
90 | | (others can too, harmlessly) | |
94 | D: innd flushing, duct reading | |
96 | | inndcomm flush fails | |
97 | |`-------------------------->---------' |
99 | | inndcomm reports no such site |
100 | |`---------------------------------------------------- | -.
102 | | innd finishes writing D, creates F | |
103 | | inndcomm reports flush successful | |
106 | Separated <----------------' |
107 | F: innd writing F!=D /
108 | D: duct reading both exist /
110 | | duct gets to the end of D /
111 | | duct opens F too /
114 | F: innd writing, duct reading |
115 | D: duct finishing V
117 | | duct finishes processing D F: ENOENT
118 | V duct unlinks D D: duct reading
120 `--<--' | duct finishes
130 "duct reading" means innduct is reading the file but also
131 overwriting processed tokens.
138 /*----- general definitions, probably best not changed -----*/
140 #define PERIOD_SECONDS 60
142 #define CONNCHILD_ESTATUS_STREAM 4
143 #define CONNCHILD_ESTATUS_NOSTREAM 5
145 #define INNDCOMMCHILD_ESTATUS_FAIL 6
146 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
149 /*----- configuration options -----*/
151 static char *feedname, *feedfile;
152 static int max_connections, max_queue_per_conn;
153 static int connection_setup_timeout, port, try_stream;
154 static int inndcomm_flush_timeout;
155 static const char *remote_host;
156 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
158 static double accept_proportion;
159 static double nocheck_thresh= 0.95;
160 static double nocheck_decay= 1-1/100;
161 static int nocheck, nocheck_reported;
164 /*----- doubly linked lists -----*/
166 #define ISNODE(T) T *next, *back;
167 #define LIST(T) struct { T *head, *tail, *tailpred; int count; }
169 #define NODE(n) ((struct node*)&(n)->head)
171 #define LIST_ADDHEAD(l,n) \
172 (list_addhead((struct list*)&(l), NODE((n))), (void)(l).count++)
173 #define LIST_ADDTAIL(l,n) \
174 (list_addtail((struct list*)&(l), NODE((n))), (void)(l).count++)
176 #define LIST_REMHEAD(l) \
177 ((l).count ? ((l).count--, (void*)list_remhead((struct list*)&(l))) : 0)
178 #define LIST_REMTAIL(l) \
179 ((l).count ? ((l).count--, (void*)list_remtail((struct list*)&(l))) : 0)
180 #define LIST_REMOVE(l,n) \
181 (list_remove(NODE((n))), (void)(l).count--)
182 #define LIST_INSERT(l,n,pred) \
183 (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
186 /*----- statistics -----*/
188 #define RESULT_COUNTS \
197 #define RC_INDEX(x) RCI_##x
203 int articles[2 /* checked */][RCI_max];
207 /*----- transmission buffers -----*/
212 xk_Malloc, xk_Const, xk_Artdata;
224 /*----- core operational data structure types -----*/
228 int checked, sentbody;
237 /* This is an instance of struct oop_readable */
238 struct oop_readable readable; /* first */
239 oop_readable_call *readable_callback;
240 void *readable_callback_user;
243 const char *path; /* ptr copy of path_<foo> or feedfile */
244 struct Filemon_Perfile *filemon;
247 long inprogress; /* no. of articles read but not processed */
257 sm_SEPARATED2, /* must follow SEPARATED2 - see feedfile_eof */
259 sm_DROPPING2, /* must follow DROPPING1 - see feedfile_eof */
264 int fd, max_queue, stream;
265 LIST(Article) queue; /* not yet told peer, or CHECK said send it */
266 LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
267 struct iovec xmit[CONNIOVS];
268 XmitDetails xmitd[CONNIOVS];
273 /*----- operational variables -----*/
275 static int since_connect_attempt;
277 static LIST(Conn) idle, working, full;
278 static LIST(Article) *queue;
280 static char *path_ductlock, *path_duct, *path_ductdefer;
282 static StateMachineState sms;
284 static InputFile *main_input_file, *old_input_file;
285 static int sm_period_counter;
288 /*----- function predeclarations -----*/
290 static void conn_check_work(Conn *conn);
292 static int filemon_init(void);
293 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
294 static void filemon_callback(void);
297 /*========== utility functions etc. ==========*/
299 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
301 static pid_t xfork(const char *what) {
305 if (child==-1) sysdie("cannot fork for %s",what);
306 if (!child) postfork(what);
310 static void on_fd_read_except(int fd, oop_call_fd callback) {
311 loop->on_fd(loop, fd, OOP_READ, callback, 0);
312 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
314 static void cancel_fd_read_except(int fd) {
315 loop->cancel_fd(loop, fd, OOP_READ);
316 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
319 static void report_child_status(const char *what, int status) {
320 if (WIFEXITED(status)) {
321 int es= WEXITSTATUS(status);
323 warn("%s: child died with error exit status %d",es);
324 } else if (WIFSIGNALED(status)) {
325 int sig= WTERMSIG(status);
326 const char *sigstr= strsignal(sig);
327 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
329 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
331 warn("%s: child died due to unknown fatal signal %d%s",
332 what, sig, coredump);
334 warn("%s: child died with unknown wait status %d", status);
338 static int xwaitpid(pid_t *pid, const char *what) {
341 r= kill(*pid, SIGKILL);
342 if (r) sysdie("cannot kill %s child", what);
344 pid_t got= waitpid(*pid, &status, WNOHANG);
345 if (got==-1) sysdie("cannot reap %s child", what);
352 /*========== making new connections ==========*/
354 static int connecting_sockets[2]= {-1,-1};
355 static pid_t connecting_child;
357 static void connect_attempt_discard(void) {
358 if (connecting_sockets[0])
359 cancel_fd(connecting_sockets[0]);
361 perhaps_close(&connecting_sockets[0]);
362 perhaps_close(&connecting_sockets[1]);
364 if (connecting_child) {
365 int status= xwaitpid(&connecting_child, "connect");
367 if (!(WIFEXITED(status) ||
368 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
369 report_child_status("connect", status);
373 #define PREP_DECL_MSG_CMSG(msg) \
375 memset(&msg,0,sizeof(msg)); \
376 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
377 msg.msg_control= msg##cbuf; \
378 msg.msg_controllen= sizeof(msg##cbuf);
380 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
383 conn= xcalloc(sizeof(*conn));
386 struct cmsghdr *h= 0;
387 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
388 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
391 pid_t got= waitpid(connecting_child, &status, WNOHANG);
393 assert(got==connecting_child);
395 if (WIFEXITED(status) &&
396 (WEXITSTATUS(status) != 0
397 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
398 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
399 /* child already reported the problem */
400 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
401 warn("connect: connection attempt timed out");
402 } else if (!WIFEXITED(status)) {
403 report_child_status("connect", status);
404 /* that's probably the root cause then */
407 /* child is still running apparently, report the socket problem */
409 syswarn("connect: read from child socket failed");
410 else if (e == OOP_EXCEPTIONN)
411 warn("connect: unexpected exception on child socket");
413 warn("connect: unexpected EOF on child socket");
418 #define CHK(field, val) \
419 if (h->cmsg_##field != val) { \
420 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
423 CHK(level, SOL_SOCKET);
424 CHK(type, SCM_RIGHTS);
425 CHK(len, CMSG_LEN(sizeof(conn-b>fd)));
428 if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
430 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
432 pid_t got= waitpid(connecting_child, &status, 0);
433 if (got==-1) sysdie("connect: real wait for child");
434 assert(got == connecting_child);
437 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
438 int es= WEXITSTATUS(status);
440 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
441 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
443 die("connect: child gave unexpected exit status %d", es);
449 LIST_ADDHEAD(idle, conn);
450 notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
451 connect_attempt_discard();
452 check_master_queue();
457 perhaps_close(&conn->fd);
460 connect_attempt_discard();
463 static void connect_start() {
464 assert(!connecting_sockets[0]);
465 assert(!connecting_sockets[1]);
466 assert(!connecting_child);
468 notice("starting connection attempt");
470 r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
471 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
473 connecting_child= xfork("connection");
475 if (!connecting_child) {
476 FILE *cn_from, *cn_to;
477 char buf[NNTP_STRLEN+100];
478 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
480 r= close(connecting_sockets[0]);
481 if (r) sysdie("connect: close parent socket in child");
483 alarm(connection_setup_timeout);
484 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
486 sanitise_inplace(buf);
487 die("connect: rejected: %s", buf);
489 sysdie("connect: connection attempt failed");
492 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
493 sysdie("connect: authentication failed");
495 if (fputs("MODE STREAM\r\n", cn_to) ||
497 sysdie("connect: could not send MODE STREAM");
498 buf[sizeof(buf)-1]= 0;
499 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
501 sysdie("connect: could not read response to MODE STREAM");
503 die("connect: connection close in response to MODE STREAM");
508 sanitise_inplace(buf);
509 die("connect: response to MODE STREAM is too long: %.100s...",
512 l--; if (l>0 && buf[1-]=='\r') l--;
515 int rcode= strtoul(buf,&ep,10);
517 sanitise_inplace(buf);
518 die("connect: bad response to MODE STREAM: %.50s", buf);
522 exitstatus= CONNCHILD_ESTATUS_STREAM;
528 sanitise_inplace(buf);
529 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
534 int fd= fileno(cn_from);
536 PREP_DECL_MSG_CMSG(msg);
537 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
538 cmsg->cmsg_level= SOL_SOCKET;
539 cmsg->cmsg_type= SCM_RIGHTS;
540 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
541 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
543 msg.msg_controllen= cmsg->cmsg_len;
544 r= sendmsg(connecting_sockets[1], &msg, 0);
545 if (r) sysdie("sendmsg failed for new connection");
550 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
551 if (r) sysdie("connect: close child socket in parent");
553 on_fd_read_except(connecting_sockets[0], connchild_event);
557 connect_attempt_discard();
561 /*========== overall control of article flow ==========*/
563 static void check_master_queue(void) {
564 try reading current feed file;
569 Conn *last_assigned=0;
572 conn_assign_one_article(&working, &last_assigned);
573 } else if (idle.head) {
574 conn_assign_one_article(&idle, &last_assigned);
575 } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
576 !connecting_child && !connect_delay) {
577 connect_delay= reconnect_delay_periods;
583 conn_check_work(last_assigned);
586 static void conn_assign_one_article(LIST(Conn) *connlist,
587 Conn **last_assigned) {
588 Conn *conn= connlist->head;
590 LIST_REMOVE(*connlist, conn);
591 Article *art= LIST_REMHEAD(queue);
592 LIST_ADDTAIL(conn->queue, art);
593 LIST_ADD(*conn_determine_right_list(conn), conn);
595 /* This slightly odd arrangement is so that we call conn_check_work
596 * once after filling the queue for a new connection in
597 * check_master_queue, rather than for each article. */
598 if (conn != *last_assigned && *last_assigned)
599 conn_check_work(*last_assigned);
600 *last_assigned= conn;
603 static int conn_total_queued_articles(Conn *conn) {
604 return conn->sent.count + conn->queue.count;
607 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
608 int inqueue= conn_total_queued_articles(conn);
609 assert(inqueue <= max_queue);
610 if (inqueue == 0) return &idle;
611 if (inqueue == conn->max_queue) return &full;
615 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
620 static void conn_check_work(Conn *conn) {
623 conn_make_some_xmits(conn);
625 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
629 void *rp= conn_write_some_xmits(conn);
630 if (rp==OOP_CONTINUE) {
631 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
633 } else if (rp==OOP_HALT) {
636 /* transmitted everything */
644 /*========== article transmission ==========*/
646 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
647 XmitKind kind) { /* caller must then fill in details */
648 struct iovec *v= &conn->xmit[conn->xmitu];
649 XmitDetails *d= &conn->xmitd[conn->xmitu++];
656 static void xmit_noalloc(Conn *conn, const char *data, int len) {
657 xmit_core(conn,data,len, xk_Const);
659 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
661 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
662 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
666 static void xmit_free(XmitDetails *d) {
668 case xk_Malloc: free(d->info.malloc_tofree); break;
669 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
670 case xk_Const: break;
675 static void *conn_write_some_xmits(Conn *conn) {
677 * 0: nothing more to write, no need to call us again
678 * OOP_CONTINUE: more to write but fd not writeable
679 * OOP_HALT: disaster, have destroyed conn
682 int count= conn->xmitu;
683 if (!count) return 0;
685 if (count > IOV_MAX) count= IOV_MAX;
686 ssize_t rs= writev(conn->fd, conn->xmit, count);
688 if (errno == EAGAIN) return OOP_CONTINUE;
689 connfail(conn, "write failed: %s", strerror(errno));
694 for (done=0; rs && done<xmitu; done++) {
695 struct iovec *vp= &conn->xmit[done];
696 XmitDetails *dp= &conn->xmitd[done];
697 if (rs > vp->iov_len) {
705 int newu= conn->xmitu - done;
706 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
707 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
712 static void conn_make_some_xmits(Conn *conn) {
714 if (conn->xmitu+5 > CONNIOVS)
717 Article *art= LIST_REMHEAD(queue);
720 if (art->checked || (conn->stream && nocheck)) {
721 /* actually send it */
723 ARTHANDLE *artdata= SMretrieve();
727 XMIT_LITERAL("TAKETHIS ");
728 xmit_noalloc(conn, art->mid, art->midlen);
729 XMIT_LITERAL("\r\n");
730 xmit_artbody(conn, artdata);
733 /* we got 235 from IHAVE */
735 xmit_artbody(conn, artdata);
737 XMIT_LITERAL(".\r\n");
742 LIST_ADDTAIL(conn->sent, art);
744 counts[art->checked].sent++;
750 XMIT_LITERAL("IHAVE ");
752 XMIT_LITERAL("CHECK ");
753 xmit_noalloc(art->mid, art->midlen);
754 XMIT_LITERAL("\r\n");
756 LIST_ADDTAIL(conn->sent, art);
757 counts[art->checked].offered++;
763 /*========== handling responses from peer ==========*/
765 static const oop_rd_style peer_rd_style= {
766 OOP_RD_DELIM_STRIP, '\n',
768 OOP_RD_SHORTREC_FORBID
771 static Article *article_reply_check(Connection *conn, const char *response,
772 int code_indicates_streaming,
773 const char *sanitised_response) {
774 Article *art= LIST_REMHEAD(conn->sent);
778 "peer gave unexpected response when no commands outstanding: %s",
783 if (code_indicates_streaming) {
784 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
786 connfail("peer gave streaming response code "
787 " to IHAVE or subsequent body: %s", sanitised_response);
790 const char *got_mid= response+4;
791 int got_midlen= strcspn(got_mid, " \n\r");
792 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
793 connfail("peer gave streaming response with syntactically invalid"
794 " messageid: %s", sanitised_response);
797 if (got_midlen != art->midlen ||
798 memcmp(got_mid, art->messageid, got_midlen)) {
799 connfail("peer gave streaming response code to wrong article -"
800 " probable synchronisation problem; we offered: %s;"
802 art->messageid, sanitised_response);
807 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
816 static void update_nocheck(int accepted) {
817 accept_proportion *= accept_decay;
818 accept_proportion += accepted;
819 nocheck= accept_proportion >= nocheck_thresh;
820 if (nocheck && !nocheck_reported) {
821 notice("entering nocheck mode for the first time");
826 static void article_done(Connection *conn, Article *art, int whichcount) {
828 counts.articles[art->checked][whichcount]++;
829 if (whichcount == RC_accepted) update_nocheck(1);
830 else if (whichcount == RC_unwanted) update_nocheck(0);
832 InputFile *ipf= art->ipf;
833 while (art->blanklen) {
834 static const char spaces[]=
839 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
840 int r= pwrite(ipf->fd, spaces, w, art->offset);
842 if (errno==EINTR) continue;
843 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
844 art->messageid, art->blanklen, art->offset, ipf->path);
846 assert(r>=0 && r<=w);
852 assert(ipf->inprogress >= 0);
854 if (!ipf->inprogress)
855 loop->on_time(loop, OOP_TIME_NOW, statemc_check_oldinput_done, 0);
860 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
861 const char *errmsg, int errnoval,
862 const char *data, size_t recsz, void *conn_v) {
864 connfail(conn, "error receiving from peer: %s", errmsg);
868 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
869 const char *errmsg, int errnoval,
870 const char *data, size_t recsz, void *conn_v) {
873 if (ev == OOP_RD_EOF) {
874 connfail(conn, "unexpected EOF from peer");
877 assert(ev == OOP_RD_OK);
880 unsigned long code= strtoul(data, &ep, 10);
881 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
887 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
889 if (!c) { *q++= '\''; break; }
890 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
891 sprintf(q,"\\x%02x",c);
894 connfail(conn, "badly formatted response from peer: %s", sanibuf);
898 if (conn->quitting) {
900 connfail(conn, "peer gave failure response to QUIT: %s", sani);
909 #define GET_ARTICLE \
910 art= article_reply_check(conn, data, code_streaming, sani); \
911 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
913 #define ARTICLE_DEALTWITH(streaming,how) \
914 code_streaming= (streaming) \
916 article_done(conn, art, RC_##how); break;
918 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
920 int code_streaming= 0;
924 case 400: PEERBADMSG("peer stopped accepting articles");
925 case 503: PEERBADMSG("peer timed us out");
926 default: PEERBADMSG("peer sent unexpected message");
928 case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
929 case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
931 case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
932 case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
934 case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
935 case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
937 case 238: /* CHECK says send it */
939 case 335: /* IHAVE says send it */
941 count_checkedwanted++;
942 LIST_ADDTAIL(conn->queue);
944 connfail("peer gave %d response to article body: %s",code, sani);
950 case 431: /* CHECK or TAKETHIS says try later */
952 case 436: /* IHAVE says try later */
954 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
956 sysdie("write to defer file %s",path_ductdefer);
957 article_done(conn, art, RC_deferred);
962 check_check_work(conn);
967 /*========== monitoring of input files ==========*/
969 static void feedfile_eof(InputFile *ipf) {
970 assert(ipf != main_input_file); /* promised by tailing_try_read */
971 assert(ipf == old_input_file);
972 assert(sms==sm_SEPARATED1 || sms==sm_DROPPING1);
974 inputfile_tailing_stop(ipf);
976 inputfile_tailing_start(main_input_file);
979 static InputFile *open_input_file(const char *path) {
980 int fd= open(path, O_RDONLY);
982 if (errno==ENOENT) return 0;
983 sysdie("unable to open input file %s", path);
986 InputFile *ipf= xmalloc(sizeof(InputFile));
987 memset(ipf,0,sizeof(*ipf));
989 ipf->readable.on_readable= tailing_on_readable;
990 ipf->readable.on_cancel= tailing_on_cancel;
991 ipf->readable.try_read= tailing_try_read;
999 static void close_input_file(InputFile *ipf) {
1000 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1001 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1002 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1003 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1005 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1010 /*---------- dealing with articles read in the input file ----------*/
1012 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1013 oop_rd_event ev, const char *errmsg,
1015 const char *data, size_t recsz,
1017 InputFile *ipf= ipf_v;
1019 char tokentextbuf[sizeof(TOKEN)*2+3];
1021 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1023 if (data[0] && data[0]!=' ') {
1024 char *space= strchr(data,' ');
1025 int tokenlen= space-data;
1026 int midlen= (int)recsz-tokenlen-1;
1027 if (midlen < 0) goto bad_data;
1029 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1030 memcpy(tokentextbuf, data, tokenlen);
1031 tokentextbuf[tokenlen]= 0;
1032 if (!IsToken(tokentextbuf)) goto bad_data;
1034 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1035 art->offset= ipf->offset;
1036 art->blanklen= recsz;
1037 art->midlen= midlen;
1038 art->checked= art->sentbody= 0;
1039 art->ipf= ipf; ipf->inprogress++;
1040 art->token= TextToToken(tokentextbuf);
1041 strcpy(art->messageid, space+1);
1042 LIST_ADDTAIL(queue, art);
1044 ipf->offset += recsz + 1;
1046 if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
1047 notice("starting flush (%lu >= %lu)",
1048 (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1050 int r= link(feedfile, duct_path);
1051 if (r) sysdie("link feedfile %s to ductfile %s", feedfile, dut_path);
1054 r= unlink(feedfile);
1055 if (r) sysdie("unlink old feedfile link %s", feedfile);
1058 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1061 check_master_queue();
1065 /*========== tailing input file ==========*/
1067 static void filemon_start(InputFile *ipf) {
1068 assert(!ipf->filemon);
1070 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1071 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1072 filemon_method_startfile(ipf, ipf->filemon);
1075 static void filemon_stop(InputFile *ipf) {
1076 if (!ipf->filemon) return;
1077 filemon_method_stopfile(ipf, ipf->filemon);
1082 static void filemon_callback(InputFile *ipf) {
1083 ipf->readable_callback(ipf->readable_callback_user);
1086 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1088 InputFile *ipf= user;
1089 return ipf->readable_callback(ipf->readable_callback_user);
1092 static void on_cancel(struct oop_readable *rable) {
1093 InputFile *ipf= (void*)rable;
1095 if (ipf->filemon) filemon_stopfile(ipf);
1096 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1097 ipf->readable_callback= 0;
1100 static int tailing_on_readable(struct oop_readable *rable,
1101 oop_readable_call *cb, void *user) {
1102 InputFile *ipf= (void*)rable;
1104 tailing_on_cancel(rable);
1105 ipf->readable_callback= cb;
1106 ipf->readable_callback_user= user;
1107 filemon_startfile(ipf);
1109 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1113 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1115 InputFile *ipf= (void*)rable;
1117 ssize_t r= read(ipf->fd, buffer, length);
1119 if (errno==EINTR) continue;
1123 if (ipf==main_input_file) { errno=EAGAIN; return -1; }
1124 assert(sms==sm_SEPARATED1 || sms==sm_DROPPING1);
1130 /*---------- filemon implemented with inotify ----------*/
1132 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1133 #define HAVE_FILEMON
1135 #include <linux/inotify.h>
1137 static int filemon_inotify_fd;
1138 static int filemon_inotify_wdmax;
1139 static InputFile **filemon_inotify_wd2ipf;
1141 typedef struct Filemon_Perfile {
1143 } Filemon_Inotify_Perfile;
1145 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1146 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1147 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1149 if (wd >= filemon_inotify_wdmax) {
1151 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1152 sizeof(*filemon_inotify_wd2ipf) * newmax);
1153 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1154 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1155 filemon_inotify_wdmax= newmax;
1158 assert(!filemon_inotify_wd2ipf[wd]);
1159 filemon_inotify_wd2ipf[wd]= ipf;
1164 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1166 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1167 if (r) sysdie("inotify_rm_watch");
1168 filemon_inotify_wd2ipf[wd]= 0;
1171 static void *filemon_inotify_readable(oop_source *lp, int fd,
1172 oop_event e, void *u) {
1173 struct inotify_event iev;
1175 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1177 if (errno==EAGAIN) break;
1178 sysdie("read from inotify master");
1179 } else if (r==sizeof(iev)) {
1180 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1182 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1184 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1185 filemon_callback(ipf);
1187 return OOP_CONTINUE;
1190 static int filemon_method_init(void) {
1191 filemon_inotify_fd= inotify_init();
1192 if (filemon_inotify_fd<0) {
1193 syswarn("could not initialise inotify: inotify_init failed");
1197 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1202 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1204 /*---------- filemon dummy implementation ----------*/
1206 #if !defined(HAVE_FILEMON)
1208 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1210 static int filemon_method_init(void) { return 0; }
1211 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1212 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1214 #endif /* !HAVE_FILEMON */
1216 /*---------- interface to start and stop an input file ----------*/
1218 static const oop_rd_style feedfile_rdstyle= {
1219 OOP_RD_DELIM_STRIP, '\n',
1221 OOP_RD_SHORTREC_EOF,
1224 static void inputfile_tailing_start(InputFile *ipf) {
1226 ipf->readable->on_readable= tailing_on_readable;
1227 ipf->readable->on_cancel= tailing_on_cancel;
1228 ipf->readable->try_read= tailing_try_read;
1229 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1230 ipf->readable->delete_kill= 0;
1232 ipf->readable_callback= 0;
1233 ipf->readable_callback_user= 0;
1235 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1238 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1239 feedfile_got_article,ipf, feedfile_problem,ipf);
1240 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1243 static void inputfile_tailing_stop(InputFile *ipf) {
1245 oop_rd_delete(ipf->rd);
1247 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1251 /*========== interaction with innd ==========*/
1253 /* See official state diagram at top of file. We implement
1263 |`--------------------------.
1264 | | install defer as backlog
1265 | OPEN F SUCCEEDS | exit
1270 | [Normal] =========
1274 | | F IS SO BIG WE SHOULD FLUSH
1278 | | our handle onto F is now onto D
1281 | |<---------------------------------------------------.
1283 | | spawn inndcomm flush |
1291 | | INNDCOMM FLUSH FAILS ^
1292 | |`----------------------->----------. |
1294 | | NO SUCH SITE V |
1295 ^ |`--------------->----. =========== |
1301 | | \ | TIME TO RETRY |
1302 | | \ `----------------'
1306 | ============= ============
1307 | SEPARATED1 DROPPING1
1308 | [Separated] [Dropping]
1309 | main F idle main none
1310 | old D tail old D tail
1311 | ============= ============
1313 ^ | EOF ON D | EOF ON D
1315 | ============= ============
1316 | SEPARATED2 DROPPING2
1317 | [Finishing] [Dropping]
1318 | main F tail main none
1319 | old D idle old D idle
1320 | ============= ============
1322 | | ALL D PROCESSED | ALL D PROCESSED
1323 | V install defer as backlog V install defer as backlog
1324 ^ | close D | close D
1325 | | unlink D | unlink D
1326 | | start new defer | exit
1328 `----------' ==========
1334 static void open_defer(void) {
1338 defer= fopen(path_ductdefer, "a+");
1339 if (!defer) sysdie("could not open defer file %s", path_ductdefer);
1341 /* truncate away any half-written records */
1343 r= fstat(fileno(defer), &stab);
1344 if (r) sysdie("could not stat newly opened defer file %s", path_ductdefer);
1346 if (stab.st_size > LONG_MAX)
1347 die("defer file %s size is far too large", path_ductdefer);
1352 long orgsize= stab.st_size;
1353 long truncto= stab.st_size;
1355 if (!truncto) break; /* was only (if anything) one half-truncated record */
1356 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1357 sysdie("seek in defer file %s while truncating partial", path_ductdefer);
1362 sysdie("failed read from defer file %s", path_ductdefer);
1364 die("defer file %s shrank while we were checking it!", path_ductdefer);
1370 if (stab.st_size != truncto) {
1371 warn("truncating half-record at end of defer file %s -"
1372 " shrinking by %ld bytes from %ld to %ld",
1373 path_ductdefer, orgsize - truncto, orgsize, truncto);
1375 if (fflush(defer)) sysdie("could not flush defer file %s", path_ductdefer);
1376 if (ftruncate(fileno(defer), truncto))
1377 sysdie("could not truncate defer file %s", path_ductdefer);
1380 info("continuing existing defer file %s (%ld bytes)",
1381 path_ductdefer, orgsize);
1383 if (fseek(defer, truncto, SEEK_SET))
1384 sysdie("could not seek to new end of defer file %s", path_ductdefer);
1387 static void statemc_init(void) {
1390 path_ductlock= xasprintf("%s_duct.lock", feedfile);
1391 path_duct= xasprintf("%s_duct", feedfile);
1392 path_ductdefer= xasprintf("%s_duct.defer", feedfile);
1394 if (lstat(path_ductdefer, &stab)) {
1395 if (errno!=ENOENT) sysdie("could not check defer file %s", path_defer);
1397 if (!S_ISREG(stab.st_mode))
1398 die("defer file %s not a plain file (mode 0%lo)",
1399 path_defer, (unsigned long)stab.st_mode);
1400 switch (stab.st_nlink==1) {
1401 case 1: /* ok */ break;
1403 if (unlink(path_defer))
1404 sysdie("could not unlink stale defer file link %s (presumably"
1405 " hardlink to backlog file)", path_defer);
1408 die("defer file %s has unexpected link count %d",
1409 path_defer, stab.st_nlink);
1414 int lockfd= open(path_ductlock, O_CREAT|O_RDWR, 0600);
1415 if (lockfd<0) sysdie("open lockfile %s", path_ductlock);
1418 memset(&fl,0,sizeof(fl));
1420 fl.l_whence= SEEK_SET;
1421 r= fcntl(lockfd, F_SETLK, &fl);
1423 if (errno==EACCES || errno==EAGAIN)
1424 die("another duct holds the lockfile");
1425 sysdie("fcntl F_SETLK lockfile %s", path_ductlock);
1428 InputFile *file_d= open_input_file(path_duct);
1431 struct stat stab_f, stab_d;
1433 r= stat(feedfile, &stab_f);
1435 if (errno!=ENOENT) sysdie("check feed file %s", feedfile);
1436 /* D exists, F ENOENT => Moved */
1440 /* F and D both exist */
1442 r= fstat(file_d->fd, &stab_d);
1443 if (r) sysdie("check duct file %s", ductfile);
1445 if (stab_d.st_ino == stab_f.st_ino &&
1446 stab_d.st_dev == stab_f.st_dev) {
1447 /* F==D => Hardlinked*/
1448 r= unlink(path_duct);
1449 if (r) sysdie("unlink feed file %s during startup", feedfile);
1452 startup_set_input_file(file_d);
1453 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1455 /* F!=D => Separated */
1457 startup_set_input_file(file_d);
1459 } else { /*!file_d*/
1461 sm_period_counter= open_wait_periods;
1465 static void statemc_poll(void) {
1466 if (sms==sm_WAITING)
1467 statemc_waiting_poll();
1469 if (!sm_period_counter) return;
1470 sm_period_counter--;
1471 assert(sm_period_counter>=0);
1473 if (sm_period_counter) return;
1476 die("timed out waiting for innd to create feed file %s", feedfile);
1478 spawn_inndcomm_flush(void);
1485 static void statemc_waiting_poll(void) {
1486 InputFile *file_f= open_input_file(feedfile);
1487 if (!file_f) return;
1488 startup_set_input_file(file_d);
1492 static void startup_set_input_file(InputFile *f) {
1493 assert(!main_input_file);
1495 inputfile_tailing_start(f);
1498 static void *statemc_check_oldinput_done(oop_source *lp,
1499 struct timeval now, void *u) {
1502 int done= (sms==sm_SEPARATED2 || sms==sm_DROPPING2)
1503 && old_input_file->inprogress;
1506 r= fstat(fileno(defer), &stab);
1507 if (r) sysdie("check defer file %s", path_defer);
1509 if (fclose(defer)) sysdie("could not close defer file %s", path_defer);
1512 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1513 (unsigned long)now.tv_sec,
1514 (unsigned long)stab.st_ino);
1515 if (link(path_defer, path_backlog))
1516 sysdie("could not install defer file %s as backlog file %s",
1517 path_defer, backlog);
1518 if (unlink(path_defer))
1519 sysdie("could not unlink old defer link %s to backlog file %s",
1520 path_defer, backlog);
1522 if (unlink(path_duct))
1523 sysdie("could not unlink old duct file %s", path_duct);
1525 if (sms==sm_DROPPING2) {
1526 notice("feed dropped and our work is complete"
1527 " (but check for backlog files)");
1533 close_input_file(old_input_file);
1536 notice("flush complete");
1541 /*========== flushing the feed ==========*/
1543 static pid_t inndcomm_child;
1545 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1546 assert(inndcomm_child);
1547 int status= xwaitpid(&inndcomm_child, "inndcomm");
1548 loop->cancel_fd(fd);
1551 assert(!old_input_file);
1553 if (WIFEXITED(status)) {
1554 switch (WEXITSTATUS(status)) {
1556 case INNDCOMMCHILD_ESTATUS_FAIL:
1559 case INNDCOMMCHILD_ESTATUS_NONESUCH:
1560 warn("feed has been dropped by innd, finishing up");
1561 old_input_file= main_input_file;
1564 return OOP_CONTINUE;
1567 old_input_file= main_input_file;
1568 main_input_file= open_input_file(feedfile);
1569 if (!main_input_file)
1570 die("flush succeeded but feedfile %s does not exist!", feedfile);
1572 return OOP_CONTINUE;
1575 goto unexpected_exitstatus;
1578 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1579 warn("flush timed out trying to talk to innd");
1582 unexpected_exitstatus:
1583 report_child_status("inndcomm child", status);
1587 sm_period_counter= flushfail_retry_periods;
1591 static void inndcommfail(const char *what) {
1592 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1593 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1596 void spawn_inndcomm_flush(void) {
1599 assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1600 assert(!inndcomm_child);
1602 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1604 inndcomm_child= xfork();
1606 if (!inndcomm_child) {
1607 static char flushargv[2]= { feedname, 0 };
1612 alarm(inndcomm_flush_timeout);
1613 r= ICCopen(); if (r) inndcommfail("connect");
1614 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
1615 if (!r) exit(0); /* yay! */
1617 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1618 syswarn("innd ctlinnd flush failed: innd said %s", reply);
1619 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1623 int sentinel_fd= pipefds[0];
1624 on_fd_read_except(sentinel_fd, inndcomm_event);
1629 /*========== main program ==========*/
1631 static void postfork_inputfile(InputFile *ipf) {
1633 assert(ipf->fd >= 0);
1638 static void postfork_conns(Connection *conn) {
1645 static void postfork_stdio(FILE *f) {
1646 /* we have no stdio streams that are buffered long-term */
1650 static void postfork(const char *what) {
1651 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1652 sysdie("%s child: failed to reset SIGPIPE");
1654 postfork_inputfile(main_input_file);
1655 postfork_inputfile(old_input_file);
1656 postfork_conns(idle.head);
1657 postfork_conns(working.head);
1658 postfork_conns(full.head);
1659 postfork_stdio(defer);
1663 #define EVERY(what, interval, body) \
1664 static const struct timeval what##_timeout = { 5, 0 }; \
1665 static void what##_schedule(void); \
1666 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1668 what##_schedule(); \
1670 static void what##_schedule(void) { \
1671 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
1674 EVERY(filepoll, {5,0}, { check_master_queue(); })
1676 EVERY(period, {PERIOD_SECONDS,0}, {
1677 if (connect_delay) connect_delay--;
1679 check_master_queue();
1683 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1684 sysdie("could not ignore SIGPIPE");
1685 if (!filemon_init())
1686 filepoll_schedule();