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;
157 static double accept_proportion;
158 static double nocheck_thresh= 0.95;
159 static double nocheck_decay= 1-1/100;
160 static int nocheck, nocheck_reported;
163 /*----- doubly linked lists -----*/
165 #define ISNODE(T) T *next, *back;
166 #define LIST(T) struct { T *head, *tail, *tailpred; int count; }
168 #define NODE(n) ((struct node*)&(n)->head)
170 #define LIST_ADDHEAD(l,n) \
171 (list_addhead((struct list*)&(l), NODE((n))), (void)(l).count++)
172 #define LIST_ADDTAIL(l,n) \
173 (list_addtail((struct list*)&(l), NODE((n))), (void)(l).count++)
175 #define LIST_REMHEAD(l) \
176 ((l).count ? ((l).count--, (void*)list_remhead((struct list*)&(l))) : 0)
177 #define LIST_REMTAIL(l) \
178 ((l).count ? ((l).count--, (void*)list_remtail((struct list*)&(l))) : 0)
179 #define LIST_REMOVE(l,n) \
180 (list_remove(NODE((n))), (void)(l).count--)
181 #define LIST_INSERT(l,n,pred) \
182 (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
185 /*----- statistics -----*/
187 #define RESULT_COUNTS \
196 #define RC_INDEX(x) RCI_##x
202 int articles[2 /* checked */][RCI_max];
206 /*----- transmission buffers -----*/
211 xk_Malloc, xk_Const, xk_Artdata;
223 /*----- core operational data structure types -----*/
227 int checked, sentbody;
236 /* This is an instance of struct oop_readable */
237 struct oop_readable readable; /* first */
238 oop_readable_call *readable_callback;
239 void *readable_callback_user;
242 const char *path; /* ptr copy of path_<foo> or feedfile */
243 struct Filemon_Perfile *filemon;
246 long inprogress; /* no. of articles read but not processed */
256 sm_SEPARATED2, /* must follow SEPARATED2 - see feedfile_eof */
258 sm_DROPPING2, /* must follow DROPPING1 - see feedfile_eof */
263 int fd, max_queue, stream;
264 LIST(Article) queue; /* not yet told peer, or CHECK said send it */
265 LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
266 struct iovec xmit[CONNIOVS];
267 XmitDetails xmitd[CONNIOVS];
272 /*----- operational variables -----*/
274 static int since_connect_attempt;
276 static LIST(Conn) idle, working, full;
277 static LIST(Article) *queue;
279 static char *path_ductlock, *path_duct, *path_ductdefer;
281 static StateMachineState sms;
283 static InputFile *main_input_file, *old_input_file;
284 static int waiting_periods_sofar;
287 /*----- function predeclarations -----*/
289 static void conn_check_work(Conn *conn);
291 static int filemon_init(void);
292 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
293 static void filemon_callback(void);
296 /*========== utility functions etc. ==========*/
298 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
300 static pid_t xfork(const char *what) {
304 if (child==-1) sysdie("cannot fork for %s",what);
305 if (!child) postfork(what);
309 static void on_fd_read_except(int fd, oop_call_fd callback) {
310 loop->on_fd(loop, fd, OOP_READ, callback, 0);
311 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
313 static void cancel_fd_read_except(int fd) {
314 loop->cancel_fd(loop, fd, OOP_READ);
315 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
318 static void report_child_status(const char *what, int status) {
319 if (WIFEXITED(status)) {
320 int es= WEXITSTATUS(status);
322 warn("%s: child died with error exit status %d",es);
323 } else if (WIFSIGNALED(status)) {
324 int sig= WTERMSIG(status);
325 const char *sigstr= strsignal(sig);
326 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
328 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
330 warn("%s: child died due to unknown fatal signal %d%s",
331 what, sig, coredump);
333 warn("%s: child died with unknown wait status %d", status);
337 static int xwaitpid(pid_t *pid, const char *what) {
340 r= kill(*pid, SIGKILL);
341 if (r) sysdie("cannot kill %s child", what);
343 pid_t got= waitpid(*pid, &status, WNOHANG);
344 if (got==-1) sysdie("cannot reap %s child", what);
351 /*========== making new connections ==========*/
353 static int connecting_sockets[2]= {-1,-1};
354 static pid_t connecting_child;
356 static void connect_attempt_discard(void) {
357 if (connecting_sockets[0])
358 cancel_fd(connecting_sockets[0]);
360 perhaps_close(&connecting_sockets[0]);
361 perhaps_close(&connecting_sockets[1]);
363 if (connecting_child) {
364 int status= xwaitpid(&connecting_child, "connect");
366 if (!(WIFEXITED(status) ||
367 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
368 report_child_status("connect", status);
372 #define PREP_DECL_MSG_CMSG(msg) \
374 memset(&msg,0,sizeof(msg)); \
375 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
376 msg.msg_control= msg##cbuf; \
377 msg.msg_controllen= sizeof(msg##cbuf);
379 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
382 conn= xcalloc(sizeof(*conn));
385 struct cmsghdr *h= 0;
386 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
387 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
390 pid_t got= waitpid(connecting_child, &status, WNOHANG);
392 assert(got==connecting_child);
394 if (WIFEXITED(status) &&
395 (WEXITSTATUS(status) != 0
396 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
397 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
398 /* child already reported the problem */
399 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
400 warn("connect: connection attempt timed out");
401 } else if (!WIFEXITED(status)) {
402 report_child_status("connect", status);
403 /* that's probably the root cause then */
406 /* child is still running apparently, report the socket problem */
408 syswarn("connect: read from child socket failed");
409 else if (e == OOP_EXCEPTIONN)
410 warn("connect: unexpected exception on child socket");
412 warn("connect: unexpected EOF on child socket");
417 #define CHK(field, val) \
418 if (h->cmsg_##field != val) { \
419 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
422 CHK(level, SOL_SOCKET);
423 CHK(type, SCM_RIGHTS);
424 CHK(len, CMSG_LEN(sizeof(conn-b>fd)));
427 if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
429 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
431 pid_t got= waitpid(connecting_child, &status, 0);
432 if (got==-1) sysdie("connect: real wait for child");
433 assert(got == connecting_child);
436 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
437 int es= WEXITSTATUS(status);
439 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
440 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
442 die("connect: child gave unexpected exit status %d", es);
448 LIST_ADDHEAD(idle, conn);
449 notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
450 connect_attempt_discard();
451 check_master_queue();
456 perhaps_close(&conn->fd);
459 connect_attempt_discard();
462 static void connect_start() {
463 assert(!connecting_sockets[0]);
464 assert(!connecting_sockets[1]);
465 assert(!connecting_child);
467 notice("starting connection attempt");
469 r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
470 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
472 connecting_child= xfork("connection");
474 if (!connecting_child) {
475 FILE *cn_from, *cn_to;
476 char buf[NNTP_STRLEN+100];
477 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
479 r= close(connecting_sockets[0]);
480 if (r) sysdie("connect: close parent socket in child");
482 alarm(connection_setup_timeout);
483 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
485 sanitise_inplace(buf);
486 die("connect: rejected: %s", buf);
488 sysdie("connect: connection attempt failed");
491 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
492 sysdie("connect: authentication failed");
494 if (fputs("MODE STREAM\r\n", cn_to) ||
496 sysdie("connect: could not send MODE STREAM");
497 buf[sizeof(buf)-1]= 0;
498 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
500 sysdie("connect: could not read response to MODE STREAM");
502 die("connect: connection close in response to MODE STREAM");
507 sanitise_inplace(buf);
508 die("connect: response to MODE STREAM is too long: %.100s...",
511 l--; if (l>0 && buf[1-]=='\r') l--;
514 int rcode= strtoul(buf,&ep,10);
516 sanitise_inplace(buf);
517 die("connect: bad response to MODE STREAM: %.50s", buf);
521 exitstatus= CONNCHILD_ESTATUS_STREAM;
527 sanitise_inplace(buf);
528 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
533 int fd= fileno(cn_from);
535 PREP_DECL_MSG_CMSG(msg);
536 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
537 cmsg->cmsg_level= SOL_SOCKET;
538 cmsg->cmsg_type= SCM_RIGHTS;
539 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
540 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
542 msg.msg_controllen= cmsg->cmsg_len;
543 r= sendmsg(connecting_sockets[1], &msg, 0);
544 if (r) sysdie("sendmsg failed for new connection");
549 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
550 if (r) sysdie("connect: close child socket in parent");
552 on_fd_read_except(connecting_sockets[0], connchild_event);
556 connect_attempt_discard();
560 /*========== overall control of article flow ==========*/
562 static void check_master_queue(void) {
563 try reading current feed file;
568 Conn *last_assigned=0;
571 conn_assign_one_article(&working, &last_assigned);
572 } else if (idle.head) {
573 conn_assign_one_article(&idle, &last_assigned);
574 } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
575 !connecting_child && !connect_delay) {
576 connect_delay= reconnect_delay_periods;
582 conn_check_work(last_assigned);
585 static void conn_assign_one_article(LIST(Conn) *connlist,
586 Conn **last_assigned) {
587 Conn *conn= connlist->head;
589 LIST_REMOVE(*connlist, conn);
590 Article *art= LIST_REMHEAD(queue);
591 LIST_ADDTAIL(conn->queue, art);
592 LIST_ADD(*conn_determine_right_list(conn), conn);
594 /* This slightly odd arrangement is so that we call conn_check_work
595 * once after filling the queue for a new connection in
596 * check_master_queue, rather than for each article. */
597 if (conn != *last_assigned && *last_assigned)
598 conn_check_work(*last_assigned);
599 *last_assigned= conn;
602 static int conn_total_queued_articles(Conn *conn) {
603 return conn->sent.count + conn->queue.count;
606 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
607 int inqueue= conn_total_queued_articles(conn);
608 assert(inqueue <= max_queue);
609 if (inqueue == 0) return &idle;
610 if (inqueue == conn->max_queue) return &full;
614 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
619 static void conn_check_work(Conn *conn) {
622 conn_make_some_xmits(conn);
624 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
628 void *rp= conn_write_some_xmits(conn);
629 if (rp==OOP_CONTINUE) {
630 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
632 } else if (rp==OOP_HALT) {
635 /* transmitted everything */
643 /*========== article transmission ==========*/
645 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
646 XmitKind kind) { /* caller must then fill in details */
647 struct iovec *v= &conn->xmit[conn->xmitu];
648 XmitDetails *d= &conn->xmitd[conn->xmitu++];
655 static void xmit_noalloc(Conn *conn, const char *data, int len) {
656 xmit_core(conn,data,len, xk_Const);
658 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
660 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
661 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
665 static void xmit_free(XmitDetails *d) {
667 case xk_Malloc: free(d->info.malloc_tofree); break;
668 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
669 case xk_Const: break;
674 static void *conn_write_some_xmits(Conn *conn) {
676 * 0: nothing more to write, no need to call us again
677 * OOP_CONTINUE: more to write but fd not writeable
678 * OOP_HALT: disaster, have destroyed conn
681 int count= conn->xmitu;
682 if (!count) return 0;
684 if (count > IOV_MAX) count= IOV_MAX;
685 ssize_t rs= writev(conn->fd, conn->xmit, count);
687 if (errno == EAGAIN) return OOP_CONTINUE;
688 connfail(conn, "write failed: %s", strerror(errno));
693 for (done=0; rs && done<xmitu; done++) {
694 struct iovec *vp= &conn->xmit[done];
695 XmitDetails *dp= &conn->xmitd[done];
696 if (rs > vp->iov_len) {
704 int newu= conn->xmitu - done;
705 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
706 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
711 static void conn_make_some_xmits(Conn *conn) {
713 if (conn->xmitu+5 > CONNIOVS)
716 Article *art= LIST_REMHEAD(queue);
719 if (art->checked || (conn->stream && nocheck)) {
720 /* actually send it */
722 ARTHANDLE *artdata= SMretrieve();
726 XMIT_LITERAL("TAKETHIS ");
727 xmit_noalloc(conn, art->mid, art->midlen);
728 XMIT_LITERAL("\r\n");
729 xmit_artbody(conn, artdata);
732 /* we got 235 from IHAVE */
734 xmit_artbody(conn, artdata);
736 XMIT_LITERAL(".\r\n");
741 LIST_ADDTAIL(conn->sent, art);
743 counts[art->checked].sent++;
749 XMIT_LITERAL("IHAVE ");
751 XMIT_LITERAL("CHECK ");
752 xmit_noalloc(art->mid, art->midlen);
753 XMIT_LITERAL("\r\n");
755 LIST_ADDTAIL(conn->sent, art);
756 counts[art->checked].offered++;
762 /*========== handling responses from peer ==========*/
764 static const oop_rd_style peer_rd_style= {
765 OOP_RD_DELIM_STRIP, '\n',
767 OOP_RD_SHORTREC_FORBID
770 static Article *article_reply_check(Connection *conn, const char *response,
771 int code_indicates_streaming,
772 const char *sanitised_response) {
773 Article *art= LIST_REMHEAD(conn->sent);
777 "peer gave unexpected response when no commands outstanding: %s",
782 if (code_indicates_streaming) {
783 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
785 connfail("peer gave streaming response code "
786 " to IHAVE or subsequent body: %s", sanitised_response);
789 const char *got_mid= response+4;
790 int got_midlen= strcspn(got_mid, " \n\r");
791 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
792 connfail("peer gave streaming response with syntactically invalid"
793 " messageid: %s", sanitised_response);
796 if (got_midlen != art->midlen ||
797 memcmp(got_mid, art->messageid, got_midlen)) {
798 connfail("peer gave streaming response code to wrong article -"
799 " probable synchronisation problem; we offered: %s;"
801 art->messageid, sanitised_response);
806 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
815 static void update_nocheck(int accepted) {
816 accept_proportion *= accept_decay;
817 accept_proportion += accepted;
818 nocheck= accept_proportion >= nocheck_thresh;
819 if (nocheck && !nocheck_reported) {
820 notice("entering nocheck mode for the first time");
825 static void article_done(Connection *conn, Article *art, int whichcount) {
827 counts.articles[art->checked][whichcount]++;
828 if (whichcount == RC_accepted) update_nocheck(1);
829 else if (whichcount == RC_unwanted) update_nocheck(0);
831 InputFile *ipf= art->ipf;
832 while (art->blanklen) {
833 static const char spaces[]=
838 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
839 int r= pwrite(ipf->fd, spaces, w, art->offset);
841 if (errno==EINTR) continue;
842 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
843 art->messageid, art->blanklen, art->offset, ipf->path);
845 assert(r>=0 && r<=w);
851 assert(ipf->inprogress >= 0);
853 if (!ipf->inprogress)
854 loop->on_time(loop, OOP_TIME_NOW, statemc_check_oldinput_done, 0);
859 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
860 const char *errmsg, int errnoval,
861 const char *data, size_t recsz, void *conn_v) {
863 connfail(conn, "error receiving from peer: %s", errmsg);
867 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
868 const char *errmsg, int errnoval,
869 const char *data, size_t recsz, void *conn_v) {
872 if (ev == OOP_RD_EOF) {
873 connfail(conn, "unexpected EOF from peer");
876 assert(ev == OOP_RD_OK);
879 unsigned long code= strtoul(data, &ep, 10);
880 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
886 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
888 if (!c) { *q++= '\''; break; }
889 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
890 sprintf(q,"\\x%02x",c);
893 connfail(conn, "badly formatted response from peer: %s", sanibuf);
897 if (conn->quitting) {
899 connfail(conn, "peer gave failure response to QUIT: %s", sani);
908 #define GET_ARTICLE \
909 art= article_reply_check(conn, data, code_streaming, sani); \
910 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
912 #define ARTICLE_DEALTWITH(streaming,how) \
913 code_streaming= (streaming) \
915 article_done(conn, art, RC_##how); break;
917 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
919 int code_streaming= 0;
923 case 400: PEERBADMSG("peer stopped accepting articles");
924 case 503: PEERBADMSG("peer timed us out");
925 default: PEERBADMSG("peer sent unexpected message");
927 case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
928 case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
930 case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
931 case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
933 case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
934 case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
936 case 238: /* CHECK says send it */
938 case 335: /* IHAVE says send it */
940 count_checkedwanted++;
941 LIST_ADDTAIL(conn->queue);
943 connfail("peer gave %d response to article body: %s",code, sani);
949 case 431: /* CHECK or TAKETHIS says try later */
951 case 436: /* IHAVE says try later */
953 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
955 sysdie("write to defer file %s",path_ductdefer);
956 article_done(conn, art, RC_deferred);
961 check_check_work(conn);
966 /*========== monitoring of input files ==========*/
968 static void feedfile_eof(InputFile *ipf) {
969 assert(ipf != main_input_file); /* promised by tailing_try_read */
970 assert(ipf == old_input_file);
971 assert(sms==sm_SEPARATED1 || sms==sm_DROPPING1);
973 inputfile_tailing_stop(ipf);
975 inputfile_tailing_start(main_input_file);
978 static InputFile *open_input_file(const char *path) {
979 int fd= open(path, O_RDONLY);
981 if (errno==ENOENT) return 0;
982 sysdie("unable to open input file %s", path);
985 InputFile *ipf= xmalloc(sizeof(InputFile));
986 memset(ipf,0,sizeof(*ipf));
988 ipf->readable.on_readable= tailing_on_readable;
989 ipf->readable.on_cancel= tailing_on_cancel;
990 ipf->readable.try_read= tailing_try_read;
998 static void close_input_file(InputFile *ipf) {
999 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1000 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1001 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1002 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1004 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1009 /*---------- dealing with articles read in the input file ----------*/
1011 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1012 oop_rd_event ev, const char *errmsg,
1014 const char *data, size_t recsz,
1016 InputFile *ipf= ipf_v;
1018 char tokentextbuf[sizeof(TOKEN)*2+3];
1020 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1022 if (data[0] && data[0]!=' ') {
1023 char *space= strchr(data,' ');
1024 int tokenlen= space-data;
1025 int midlen= (int)recsz-tokenlen-1;
1026 if (midlen < 0) goto bad_data;
1028 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1029 memcpy(tokentextbuf, data, tokenlen);
1030 tokentextbuf[tokenlen]= 0;
1031 if (!IsToken(tokentextbuf)) goto bad_data;
1033 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1034 art->offset= ipf->offset;
1035 art->blanklen= recsz;
1036 art->midlen= midlen;
1037 art->checked= art->sentbody= 0;
1038 art->ipf= ipf; ipf->inprogress++;
1039 art->token= TextToToken(tokentextbuf);
1040 strcpy(art->messageid, space+1);
1041 LIST_ADDTAIL(queue, art);
1043 ipf->offset += recsz + 1;
1045 if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
1046 notice("starting flush (%lu >= %lu)",
1047 (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1049 int r= link(feedfile, duct_path);
1050 if (r) sysdie("link feedfile %s to ductfile %s", feedfile, dut_path);
1053 r= unlink(feedfile);
1054 if (r) sysdie("unlink old feedfile link %s", feedfile);
1057 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1060 check_master_queue();
1064 /*========== tailing input file ==========*/
1066 static void filemon_start(InputFile *ipf) {
1067 assert(!ipf->filemon);
1069 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1070 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1071 filemon_method_startfile(ipf, ipf->filemon);
1074 static void filemon_stop(InputFile *ipf) {
1075 if (!ipf->filemon) return;
1076 filemon_method_stopfile(ipf, ipf->filemon);
1081 static void filemon_callback(InputFile *ipf) {
1082 ipf->readable_callback(ipf->readable_callback_user);
1085 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1087 InputFile *ipf= user;
1088 return ipf->readable_callback(ipf->readable_callback_user);
1091 static void on_cancel(struct oop_readable *rable) {
1092 InputFile *ipf= (void*)rable;
1094 if (ipf->filemon) filemon_stopfile(ipf);
1095 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1096 ipf->readable_callback= 0;
1099 static int tailing_on_readable(struct oop_readable *rable,
1100 oop_readable_call *cb, void *user) {
1101 InputFile *ipf= (void*)rable;
1103 tailing_on_cancel(rable);
1104 ipf->readable_callback= cb;
1105 ipf->readable_callback_user= user;
1106 filemon_startfile(ipf);
1108 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1112 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1114 InputFile *ipf= (void*)rable;
1116 ssize_t r= read(ipf->fd, buffer, length);
1118 if (errno==EINTR) continue;
1122 if (ipf==main_input_file) { errno=EAGAIN; return -1; }
1123 assert(sms==sm_SEPARATED1 || sms==sm_DROPPING1);
1129 /*---------- filemon implemented with inotify ----------*/
1131 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1132 #define HAVE_FILEMON
1134 #include <linux/inotify.h>
1136 static int filemon_inotify_fd;
1137 static int filemon_inotify_wdmax;
1138 static InputFile **filemon_inotify_wd2ipf;
1140 typedef struct Filemon_Perfile {
1142 } Filemon_Inotify_Perfile;
1144 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1145 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1146 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1148 if (wd >= filemon_inotify_wdmax) {
1150 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1151 sizeof(*filemon_inotify_wd2ipf) * newmax);
1152 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1153 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1154 filemon_inotify_wdmax= newmax;
1157 assert(!filemon_inotify_wd2ipf[wd]);
1158 filemon_inotify_wd2ipf[wd]= ipf;
1163 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1165 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1166 if (r) sysdie("inotify_rm_watch");
1167 filemon_inotify_wd2ipf[wd]= 0;
1170 static void *filemon_inotify_readable(oop_source *lp, int fd,
1171 oop_event e, void *u) {
1172 struct inotify_event iev;
1174 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1176 if (errno==EAGAIN) break;
1177 sysdie("read from inotify master");
1178 } else if (r==sizeof(iev)) {
1179 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1181 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1183 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1184 filemon_callback(ipf);
1186 return OOP_CONTINUE;
1189 static int filemon_method_init(void) {
1190 filemon_inotify_fd= inotify_init();
1191 if (filemon_inotify_fd<0) {
1192 syswarn("could not initialise inotify: inotify_init failed");
1196 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1201 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1203 /*---------- filemon dummy implementation ----------*/
1205 #if !defined(HAVE_FILEMON)
1207 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1209 static int filemon_method_init(void) { return 0; }
1210 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1211 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1213 #endif /* !HAVE_FILEMON */
1215 /*---------- interface to start and stop an input file ----------*/
1217 static const oop_rd_style feedfile_rdstyle= {
1218 OOP_RD_DELIM_STRIP, '\n',
1220 OOP_RD_SHORTREC_EOF,
1223 static void inputfile_tailing_start(InputFile *ipf) {
1225 ipf->readable->on_readable= tailing_on_readable;
1226 ipf->readable->on_cancel= tailing_on_cancel;
1227 ipf->readable->try_read= tailing_try_read;
1228 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1229 ipf->readable->delete_kill= 0;
1231 ipf->readable_callback= 0;
1232 ipf->readable_callback_user= 0;
1234 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1237 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1238 feedfile_got_article,ipf, feedfile_problem,ipf);
1239 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1242 static void inputfile_tailing_stop(InputFile *ipf) {
1244 oop_rd_delete(ipf->rd);
1246 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1250 /*========== interaction with innd ==========*/
1252 /* See official state diagram at top of file. We implement
1262 |`--------------------------.
1263 | | install defer as backlog
1264 | OPEN F SUCCEEDS | exit
1269 | [Normal] =========
1273 | | F IS SO BIG WE SHOULD FLUSH
1277 | | our handle onto F is now onto D
1280 | |<---------------------------------------------------.
1282 | | spawn inndcomm flush |
1290 | | INNDCOMM FLUSH FAILS ^
1291 | |`----------------------->----------. |
1293 | | NO SUCH SITE V |
1294 ^ |`--------------->----. =========== |
1300 | | \ | TIME TO RETRY |
1301 | | \ `----------------'
1305 | ============= ============
1306 | SEPARATED1 DROPPING1
1307 | [Separated] [Dropping]
1308 | main F idle main none
1309 | old D tail old D tail
1310 | ============= ============
1312 ^ | EOF ON D | EOF ON D
1314 | ============= ============
1315 | SEPARATED2 DROPPING2
1316 | [Finishing] [Dropping]
1317 | main F tail main none
1318 | old D idle old D idle
1319 | ============= ============
1321 | | ALL D PROCESSED | ALL D PROCESSED
1322 | V install defer as backlog V install defer as backlog
1323 ^ | close D | close D
1324 | | unlink D | unlink D
1325 | | start new defer | exit
1327 `----------' ==========
1333 static void open_defer(void) {
1337 defer= fopen(path_ductdefer, "a+");
1338 if (!defer) sysdie("could not open defer file %s", path_ductdefer);
1340 /* truncate away any half-written records */
1342 r= fstat(fileno(defer), &stab);
1343 if (r) sysdie("could not stat newly opened defer file %s", path_ductdefer);
1345 if (stab.st_size > LONG_MAX)
1346 die("defer file %s size is far too large", path_ductdefer);
1351 long orgsize= stab.st_size;
1352 long truncto= stab.st_size;
1354 if (!truncto) break; /* was only (if anything) one half-truncated record */
1355 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1356 sysdie("seek in defer file %s while truncating partial", path_ductdefer);
1361 sysdie("failed read from defer file %s", path_ductdefer);
1363 die("defer file %s shrank while we were checking it!", path_ductdefer);
1369 if (stab.st_size != truncto) {
1370 warn("truncating half-record at end of defer file %s -"
1371 " shrinking by %ld bytes from %ld to %ld",
1372 path_ductdefer, orgsize - truncto, orgsize, truncto);
1374 if (fflush(defer)) sysdie("could not flush defer file %s", path_ductdefer);
1375 if (ftruncate(fileno(defer), truncto))
1376 sysdie("could not truncate defer file %s", path_ductdefer);
1379 info("continuing existing defer file %s (%ld bytes)",
1380 path_ductdefer, orgsize);
1382 if (fseek(defer, truncto, SEEK_SET))
1383 sysdie("could not seek to new end of defer file %s", path_ductdefer);
1386 static void statemc_init(void) {
1389 path_ductlock= xasprintf("%s_duct.lock", feedfile);
1390 path_duct= xasprintf("%s_duct", feedfile);
1391 path_ductdefer= xasprintf("%s_duct.defer", feedfile);
1393 if (lstat(path_ductdefer, &stab)) {
1394 if (errno!=ENOENT) sysdie("could not check defer file %s", path_defer);
1396 if (!S_ISREG(stab.st_mode))
1397 die("defer file %s not a plain file (mode 0%lo)",
1398 path_defer, (unsigned long)stab.st_mode);
1399 switch (stab.st_nlink==1) {
1400 case 1: /* ok */ break;
1402 if (unlink(path_defer))
1403 sysdie("could not unlink stale defer file link %s (presumably"
1404 " hardlink to backlog file)", path_defer);
1407 die("defer file %s has unexpected link count %d",
1408 path_defer, stab.st_nlink);
1413 int lockfd= open(path_ductlock, O_CREAT|O_RDWR, 0600);
1414 if (lockfd<0) sysdie("open lockfile %s", path_ductlock);
1417 memset(&fl,0,sizeof(fl));
1419 fl.l_whence= SEEK_SET;
1420 r= fcntl(lockfd, F_SETLK, &fl);
1422 if (errno==EACCES || errno==EAGAIN)
1423 die("another duct holds the lockfile");
1424 sysdie("fcntl F_SETLK lockfile %s", path_ductlock);
1427 InputFile *file_d= open_input_file(path_duct);
1430 struct stat stab_f, stab_d;
1432 r= stat(feedfile, &stab_f);
1434 if (errno!=ENOENT) sysdie("check feed file %s", feedfile);
1435 /* D exists, F ENOENT => Moved */
1439 /* F and D both exist */
1441 r= fstat(file_d->fd, &stab_d);
1442 if (r) sysdie("check duct file %s", ductfile);
1444 if (stab_d.st_ino == stab_f.st_ino &&
1445 stab_d.st_dev == stab_f.st_dev) {
1446 /* F==D => Hardlinked*/
1447 r= unlink(path_duct);
1448 if (r) sysdie("unlink feed file %s during startup", feedfile);
1451 startup_set_input_file(file_d);
1452 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1454 /* F!=D => Separated */
1456 startup_set_input_file(file_d);
1458 } else { /*!file_d*/
1460 statemc_waiting_poll();
1464 static void statemc_poll(void) {
1465 if (sms==sm_WAITING) statemc_waiting_poll();
1468 static void statemc_waiting_poll(void) {
1469 InputFile *file_f= open_input_file(feedfile);
1471 if (waiting_periods_sofar++ > waiting_timeout_periods)
1472 die("timed out waiting for innd to create feed file %s", feedfile);
1475 startup_set_input_file(file_d);
1479 static void startup_set_input_file(InputFile *f) {
1480 assert(!main_input_file);
1482 inputfile_tailing_start(f);
1485 static void *statemc_check_oldinput_done(oop_source *lp,
1486 struct timeval now, void *u) {
1489 int done= (sms==sm_SEPARATED2 || sms==sm_DROPPING2)
1490 && old_input_file->inprogress;
1493 r= fstat(fileno(defer), &stab);
1494 if (r) sysdie("check defer file %s", path_defer);
1496 if (fclose(defer)) sysdie("could not close defer file %s", path_defer);
1499 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1500 (unsigned long)now.tv_sec,
1501 (unsigned long)stab.st_ino);
1502 if (link(path_defer, path_backlog))
1503 sysdie("could not install defer file %s as backlog file %s",
1504 path_defer, backlog);
1505 if (unlink(path_defer))
1506 sysdie("could not unlink old defer link %s to backlog file %s",
1507 path_defer, backlog);
1509 if (unlink(path_duct))
1510 sysdie("could not unlink old duct file %s", path_duct);
1512 if (sms==sm_DROPPING2) {
1513 notice("feed dropped and our work is complete"
1514 " (but check for backlog files)");
1520 close_input_file(old_input_file);
1526 /*========== flushing the feed ==========*/
1528 static pid_t inndcomm_child;
1530 static void inndcommfail(const char *what) {
1531 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1532 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1535 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1536 assert(inndcomm_child);
1537 int status= xwaitpid(&inndcomm_child, "inndcomm");
1538 loop->cancel_fd(fd);
1541 assert(!old_input_file);
1543 if (WIFEXITED(status)) {
1544 switch (WEXITSTATUS(status)) {
1546 case INNDCOMMCHILD_ESTATUS_FAIL:
1549 case INNDCOMMCHILD_ESTATUS_NONESUCH:
1550 warn("feed has been dropped by innd, finishing up");
1551 old_input_file= main_input_file;
1554 return OOP_CONTINUE;
1557 old_input_file= main_input_file;
1558 main_input_file= open_input_file(feedfile);
1559 if (!main_input_file)
1560 die("flush succeeded but feedfile %s does not exist!", feedfile);
1562 return OOP_CONTINUE;
1565 goto unexpected_exitstatus;
1568 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1569 warn("flush of %s timed out trying to talk to innd", feedname);
1572 unexpected_exitstatus:
1573 report_child_status("inndcomm child", status);
1579 void spawn_inndcomm_flush(void) {
1582 assert(sms == sm_NORMAL);
1583 assert(!inndcomm_child);
1585 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1587 inndcomm_child= xfork();
1589 if (!inndcomm_child) {
1590 static char flushargv[2]= { feedname, 0 };
1595 alarm(inndcomm_flush_timeout);
1596 r= ICCopen(); if (r) inndcommfail("connect");
1597 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
1598 if (!r) exit(0); /* yay! */
1600 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1601 syswarn("innd ctlinnd flush %s failed: innd said %s", feedname, reply);
1602 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1606 int sentinel_fd= pipefds[0];
1607 on_fd_read_except(sentinel_fd, inndcomm_event);
1612 /*========== main program ==========*/
1614 static void postfork_inputfile(InputFile *ipf) {
1616 assert(ipf->fd >= 0);
1621 static void postfork_conns(Connection *conn) {
1628 static void postfork_stdio(FILE *f) {
1629 /* we have no stdio streams that are buffered long-term */
1633 static void postfork(const char *what) {
1634 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1635 sysdie("%s child: failed to reset SIGPIPE");
1637 postfork_inputfile(main_input_file);
1638 postfork_inputfile(old_input_file);
1639 postfork_conns(idle.head);
1640 postfork_conns(working.head);
1641 postfork_conns(full.head);
1642 postfork_stdio(defer);
1646 #define EVERY(what, interval, body) \
1647 static const struct timeval what##_timeout = { 5, 0 }; \
1648 static void what##_schedule(void); \
1649 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1651 what##_schedule(); \
1653 static void what##_schedule(void) { \
1654 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
1657 EVERY(filepoll, {5,0}, { check_master_queue(); })
1659 EVERY(period, {PERIOD_SECONDS,0}, {
1660 if (connect_delay) connect_delay--;
1662 check_master_queue();
1667 if (!filemon_init())
1668 filepoll_schedule();