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 #define RESULT_COUNTS \
212 #define RC_INDEX(x) RCI_##x
218 int articles[2 /* checked */][RCI_max];
222 /*----- transmission buffers -----*/
227 xk_Malloc, xk_Const, xk_Artdata;
239 /*----- core operational data structure types -----*/
243 int checked, sentbody;
251 typedef struct InputFile {
252 /* This is an instance of struct oop_readable */
253 struct oop_readable readable; /* first */
254 oop_readable_call *readable_callback;
255 void *readable_callback_user;
258 struct Filemon_Perfile *filemon;
261 long inprogress; /* no. of articles read but not processed */
268 #define SMS_LIST(X) \
277 #define SMS_DEF_ENUM(s) sm_##s,
278 SMS_LIST(SMS_DEF_ENUM)
281 static const char *sms_names[]= {
282 #define SMS_DEF_NAME(s) #s ,
283 SMS_LIST(SMS_DEF_NAME)
289 int fd, max_queue, stream;
290 LIST(Article) queue; /* not yet told peer, or CHECK said send it */
291 LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
292 struct iovec xmit[CONNIOVS];
293 XmitDetails xmitd[CONNIOVS];
298 /*----- operational variables -----*/
301 static LIST(Conn) idle, working, full;
302 static LIST(Article) *queue;
304 static char *path_lock, *path_flushing, *path_defer;
306 #define SMS(newstate, periods, why) \
307 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
309 static StateMachineState sms;
311 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
312 static int sm_period_counter;
315 /*----- function predeclarations -----*/
317 static void conn_check_work(Conn *conn);
319 static int filemon_init(void);
320 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
321 static void filemon_callback(void);
323 static void statemc_setstate(StateMachineState newsms, int periods,
324 const char *forlog, const char *why);
326 /*========== utility functions etc. ==========*/
328 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
330 static pid_t xfork(const char *what) {
334 if (child==-1) sysdie("cannot fork for %s",what);
335 if (!child) postfork(what);
339 static void on_fd_read_except(int fd, oop_call_fd callback) {
340 loop->on_fd(loop, fd, OOP_READ, callback, 0);
341 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
343 static void cancel_fd_read_except(int fd) {
344 loop->cancel_fd(loop, fd, OOP_READ);
345 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
348 static void report_child_status(const char *what, int status) {
349 if (WIFEXITED(status)) {
350 int es= WEXITSTATUS(status);
352 warn("%s: child died with error exit status %d",es);
353 } else if (WIFSIGNALED(status)) {
354 int sig= WTERMSIG(status);
355 const char *sigstr= strsignal(sig);
356 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
358 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
360 warn("%s: child died due to unknown fatal signal %d%s",
361 what, sig, coredump);
363 warn("%s: child died with unknown wait status %d", status);
367 static int xwaitpid(pid_t *pid, const char *what) {
370 r= kill(*pid, SIGKILL);
371 if (r) sysdie("cannot kill %s child", what);
373 pid_t got= waitpid(*pid, &status, WNOHANG);
374 if (got==-1) sysdie("cannot reap %s child", what);
381 static void xunlink(const char *path, const char *what) {
383 if (r) sysdie("can't unlink %s %s", path, what);
386 static void check_isreg(const struct stat *stab, const char *path,
388 if (!S_ISREG(stab->st_mode))
389 die("%s %s not a plain file (mode 0%lo)",
390 what, path, (unsigned long)stab->st_mode);
393 static void xfstat(int fd, struct stat *stab_r, const char *what) {
394 int r= fstab(path, stab);
395 if (r) sysdie("could not fstat %s %s", what, path);
398 static void xfstat_isreg(int fd, struct stat *stab_r, const char *what) {
399 xfstat(fd, stab_r, what);
400 check_isreg(stab, path, what);
403 static void xlstat_isreg(const char *path, struct stat *stab,
404 int *enoent_r /* 0 means ENOENT is fatal */
406 int r= lstat(path, stab);
408 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
409 sysdie("could not lstat %s %s", what, path);
411 if (enoent_r) *enoent_r= 0;
412 check_isreg(stab, path, what);
415 static int samefile(const struct stat *a, const struct stat *b) {
416 assert(S_ISREG(a->st_mode));
417 assert(S_ISREG(b->st_mode));
418 return (a->st_ino == b->st_ino &&
419 a->st_dev == b->st_dev);
422 /*========== logging ==========*/
424 static void logcore(int sysloglevel, const char *fmt, ...)
425 __attribute__((printf,2,3))
426 static void logcore(int sysloglevel, const char *fmt, ...) {
430 vsyslog(sysloglevel,fmt,al);
432 vfprintf(stderr,fmt,al);
437 static void logv(int sysloglevel, const char *pfx, int errnoval,
438 int exitstatus, const char *fmt, va_list al)
439 __attribute__((printf,4,0))
440 static void logv(int sysloglevel, const char *pfx, int errnoval,
441 int exitstatus, const char *fmt, va_list al) {
443 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
444 msgbuf[sizeof(msgbuf)-1]= 0;
446 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
447 sysloglevel= LOG_ERR; /* run by wrong user, probably */
449 logcore(sysloglevel, "<%s>%s: %s%s%s",
450 sitename, pfx, msgbuf,
451 errnoval>=0 ? ": " : "",
452 errnoval>=0 ? strerror(errnoval) : "");
455 #define logwrap(fn, pfx, sysloglevel, errno, estatus) \
456 static void fn(const char *fmt, ...) \
457 __attribute__((printf,1,2)); \
458 static void fn(const char *fmt, ...) { \
461 logv(sysloglevel, pfx, errno, estatus, fmt, al); \
464 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
465 logwrap(die, " critical", LOG_CRIT, -1, 16);
467 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
468 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
470 logwrap(syswarn, " warning", LOG_WARN, errno, 0);
471 logwrap(warn, " warning", LOG_WARN, -1, 0);
473 logwrap(notice, "", LOG_NOTICE, -1, 0);
474 logwrap(info, " info", LOG_INFO, -1, 0);
475 logwrap(debug, " debug", LOG_DEBUG, -1, 0);
478 /*========== making new connections ==========*/
480 static int connecting_sockets[2]= {-1,-1};
481 static pid_t connecting_child;
483 static void connect_attempt_discard(void) {
484 if (connecting_sockets[0])
485 cancel_fd(connecting_sockets[0]);
487 perhaps_close(&connecting_sockets[0]);
488 perhaps_close(&connecting_sockets[1]);
490 if (connecting_child) {
491 int status= xwaitpid(&connecting_child, "connect");
493 if (!(WIFEXITED(status) ||
494 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
495 report_child_status("connect", status);
499 #define PREP_DECL_MSG_CMSG(msg) \
501 memset(&msg,0,sizeof(msg)); \
502 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
503 msg.msg_control= msg##cbuf; \
504 msg.msg_controllen= sizeof(msg##cbuf);
506 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
509 conn= xmalloc(sizeof(*conn));
510 memset(conn,0,sizeof(*conn));
513 struct cmsghdr *h= 0;
514 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
515 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
518 pid_t got= waitpid(connecting_child, &status, WNOHANG);
520 assert(got==connecting_child);
522 if (WIFEXITED(status) &&
523 (WEXITSTATUS(status) != 0
524 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
525 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
526 /* child already reported the problem */
527 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
528 warn("connect: connection attempt timed out");
529 } else if (!WIFEXITED(status)) {
530 report_child_status("connect", status);
531 /* that's probably the root cause then */
534 /* child is still running apparently, report the socket problem */
536 syswarn("connect: read from child socket failed");
537 else if (e == OOP_EXCEPTIONN)
538 warn("connect: unexpected exception on child socket");
540 warn("connect: unexpected EOF on child socket");
545 #define CHK(field, val) \
546 if (h->cmsg_##field != val) { \
547 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
550 CHK(level, SOL_SOCKET);
551 CHK(type, SCM_RIGHTS);
552 CHK(len, CMSG_LEN(sizeof(conn-b>fd)));
555 if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
557 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
559 pid_t got= waitpid(connecting_child, &status, 0);
560 if (got==-1) sysdie("connect: real wait for child");
561 assert(got == connecting_child);
564 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
565 int es= WEXITSTATUS(status);
567 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
568 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
570 fatal("connect: child gave unexpected exit status %d", es);
576 LIST_ADDHEAD(idle, conn);
577 notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
578 connect_attempt_discard();
579 check_master_queue();
584 perhaps_close(&conn->fd);
587 connect_attempt_discard();
590 static void connect_start() {
591 assert(!connecting_sockets[0]);
592 assert(!connecting_sockets[1]);
593 assert(!connecting_child);
595 notice("starting connection attempt");
597 r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
598 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
600 connecting_child= xfork("connection");
602 if (!connecting_child) {
603 FILE *cn_from, *cn_to;
604 char buf[NNTP_STRLEN+100];
605 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
607 r= close(connecting_sockets[0]);
608 if (r) sysdie("connect: close parent socket in child");
610 alarm(connection_setup_timeout);
611 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
613 sanitise_inplace(buf);
614 fatal("connect: rejected: %s", buf);
616 sysfatal("connect: connection attempt failed");
619 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
620 sysfatal("connect: authentication failed");
622 if (fputs("MODE STREAM\r\n", cn_to) ||
624 sysfatal("connect: could not send MODE STREAM");
625 buf[sizeof(buf)-1]= 0;
626 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
628 sysfatal("connect: could not read response to MODE STREAM");
630 fatal("connect: connection close in response to MODE STREAM");
635 sanitise_inplace(buf);
636 fatal("connect: response to MODE STREAM is too long: %.100s...",
639 l--; if (l>0 && buf[1-]=='\r') l--;
642 int rcode= strtoul(buf,&ep,10);
644 sanitise_inplace(buf);
645 fatal("connect: bad response to MODE STREAM: %.50s", buf);
649 exitstatus= CONNCHILD_ESTATUS_STREAM;
655 sanitise_inplace(buf);
656 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
661 int fd= fileno(cn_from);
663 PREP_DECL_MSG_CMSG(msg);
664 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
665 cmsg->cmsg_level= SOL_SOCKET;
666 cmsg->cmsg_type= SCM_RIGHTS;
667 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
668 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
670 msg.msg_controllen= cmsg->cmsg_len;
671 r= sendmsg(connecting_sockets[1], &msg, 0);
672 if (r) sysdie("sendmsg failed for new connection");
677 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
678 if (r) sysdie("connect: close child socket in parent");
680 on_fd_read_except(connecting_sockets[0], connchild_event);
684 connect_attempt_discard();
688 /*========== overall control of article flow ==========*/
690 static void check_master_queue(void) {
694 Conn *last_assigned=0;
697 conn_assign_one_article(&working, &last_assigned);
698 } else if (idle.head) {
699 conn_assign_one_article(&idle, &last_assigned);
700 } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
701 !connecting_child && !connect_delay) {
702 connect_delay= reconnect_delay_periods;
708 conn_check_work(last_assigned);
711 static void conn_assign_one_article(LIST(Conn) *connlist,
712 Conn **last_assigned) {
713 Conn *conn= connlist->head;
715 LIST_REMOVE(*connlist, conn);
716 Article *art= LIST_REMHEAD(queue);
717 LIST_ADDTAIL(conn->queue, art);
718 LIST_ADD(*conn_determine_right_list(conn), conn);
720 /* This slightly odd arrangement is so that we call conn_check_work
721 * once after filling the queue for a new connection in
722 * check_master_queue, rather than for each article. */
723 if (conn != *last_assigned && *last_assigned)
724 conn_check_work(*last_assigned);
725 *last_assigned= conn;
728 static int conn_total_queued_articles(Conn *conn) {
729 return conn->sent.count + conn->queue.count;
732 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
733 int inqueue= conn_total_queued_articles(conn);
734 assert(inqueue <= max_queue);
735 if (inqueue == 0) return &idle;
736 if (inqueue == conn->max_queue) return &full;
740 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
745 static void conn_check_work(Conn *conn) {
748 conn_make_some_xmits(conn);
750 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
754 void *rp= conn_write_some_xmits(conn);
755 if (rp==OOP_CONTINUE) {
756 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
758 } else if (rp==OOP_HALT) {
761 /* transmitted everything */
769 /*========== article transmission ==========*/
771 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
772 XmitKind kind) { /* caller must then fill in details */
773 struct iovec *v= &conn->xmit[conn->xmitu];
774 XmitDetails *d= &conn->xmitd[conn->xmitu++];
781 static void xmit_noalloc(Conn *conn, const char *data, int len) {
782 xmit_core(conn,data,len, xk_Const);
784 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
786 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
787 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
791 static void xmit_free(XmitDetails *d) {
793 case xk_Malloc: free(d->info.malloc_tofree); break;
794 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
795 case xk_Const: break;
800 static void *conn_write_some_xmits(Conn *conn) {
802 * 0: nothing more to write, no need to call us again
803 * OOP_CONTINUE: more to write but fd not writeable
804 * OOP_HALT: disaster, have destroyed conn
807 int count= conn->xmitu;
808 if (!count) return 0;
810 if (count > IOV_MAX) count= IOV_MAX;
811 ssize_t rs= writev(conn->fd, conn->xmit, count);
813 if (errno == EAGAIN) return OOP_CONTINUE;
814 connfail(conn, "write failed: %s", strerror(errno));
819 for (done=0; rs && done<xmitu; done++) {
820 struct iovec *vp= &conn->xmit[done];
821 XmitDetails *dp= &conn->xmitd[done];
822 if (rs > vp->iov_len) {
830 int newu= conn->xmitu - done;
831 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
832 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
837 static void conn_make_some_xmits(Conn *conn) {
839 if (conn->xmitu+5 > CONNIOVS)
842 Article *art= LIST_REMHEAD(queue);
845 if (art->checked || (conn->stream && nocheck)) {
846 /* actually send it */
848 ARTHANDLE *artdata= SMretrieve();
852 XMIT_LITERAL("TAKETHIS ");
853 xmit_noalloc(conn, art->mid, art->midlen);
854 XMIT_LITERAL("\r\n");
855 xmit_artbody(conn, artdata);
858 /* we got 235 from IHAVE */
860 xmit_artbody(conn, artdata);
862 XMIT_LITERAL(".\r\n");
867 LIST_ADDTAIL(conn->sent, art);
869 art->ipf->counts[art->checked].sent++;
875 XMIT_LITERAL("IHAVE ");
877 XMIT_LITERAL("CHECK ");
878 xmit_noalloc(art->mid, art->midlen);
879 XMIT_LITERAL("\r\n");
881 LIST_ADDTAIL(conn->sent, art);
882 art->ipf->counts[art->checked].offered++;
888 /*========== handling responses from peer ==========*/
890 static const oop_rd_style peer_rd_style= {
891 OOP_RD_DELIM_STRIP, '\n',
893 OOP_RD_SHORTREC_FORBID
896 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
897 const char *errmsg, int errnoval,
898 const char *data, size_t recsz, void *conn_v) {
900 connfail(conn, "error receiving from peer: %s", errmsg);
904 static Article *article_reply_check(Connection *conn, const char *response,
905 int code_indicates_streaming,
906 const char *sanitised_response) {
907 Article *art= LIST_REMHEAD(conn->sent);
911 "peer gave unexpected response when no commands outstanding: %s",
916 if (code_indicates_streaming) {
917 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
919 connfail("peer gave streaming response code "
920 " to IHAVE or subsequent body: %s", sanitised_response);
923 const char *got_mid= response+4;
924 int got_midlen= strcspn(got_mid, " \n\r");
925 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
926 connfail("peer gave streaming response with syntactically invalid"
927 " messageid: %s", sanitised_response);
930 if (got_midlen != art->midlen ||
931 memcmp(got_mid, art->messageid, got_midlen)) {
932 connfail("peer gave streaming response code to wrong article -"
933 " probable synchronisation problem; we offered: %s;"
935 art->messageid, sanitised_response);
940 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
949 static void update_nocheck(int accepted) {
950 accept_proportion *= accept_decay;
951 accept_proportion += accepted;
952 int new_nocheck= accept_proportion >= nocheck_thresh;
953 if (new_nocheck && !nocheck_reported) {
954 notice("entering nocheck mode for the first time");
956 } else if (new_nocheck != nockech) {
957 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
959 nocheck= new_nocheck;
962 static void article_done(Connection *conn, Article *art, int whichcount) {
964 art->ipf->counts.articles[art->checked][whichcount]++;
965 if (whichcount == RC_accepted) update_nocheck(1);
966 else if (whichcount == RC_unwanted) update_nocheck(0);
968 InputFile *ipf= art->ipf;
969 while (art->blanklen) {
970 static const char spaces[]=
975 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
976 int r= pwrite(ipf->fd, spaces, w, art->offset);
978 if (errno==EINTR) continue;
979 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
980 art->messageid, art->blanklen, art->offset, ipf->path);
982 assert(r>=0 && r<=w);
988 assert(ipf->inprogress >= 0);
990 if (!ipf->inprogress && ipf != main_input_file)
991 queue_check_input_done();
996 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
997 const char *errmsg, int errnoval,
998 const char *data, size_t recsz, void *conn_v) {
1001 if (ev == OOP_RD_EOF) {
1002 connfail(conn, "unexpected EOF from peer");
1003 return OOP_CONTINUE;
1005 assert(ev == OOP_RD_OK);
1008 unsigned long code= strtoul(data, &ep, 10);
1009 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1011 const char *p= data;
1015 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
1017 if (!c) { *q++= '\''; break; }
1018 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
1019 sprintf(q,"\\x%02x",c);
1022 connfail(conn, "badly formatted response from peer: %s", sanibuf);
1023 return OOP_CONTINUE;
1026 if (conn->quitting) {
1028 connfail(conn, "peer gave failure response to QUIT: %s", sani);
1029 return OOP_CONTINUE;
1037 #define GET_ARTICLE \
1038 art= article_reply_check(conn, data, code_streaming, sani); \
1039 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1041 #define ARTICLE_DEALTWITH(streaming,how) \
1042 code_streaming= (streaming) \
1044 article_done(conn, art, RC_##how); break;
1046 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1048 int code_streaming= 0;
1052 case 400: PEERBADMSG("peer stopped accepting articles");
1053 case 503: PEERBADMSG("peer timed us out");
1054 default: PEERBADMSG("peer sent unexpected message");
1056 case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
1057 case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
1059 case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
1060 case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
1062 case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
1063 case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
1065 case 238: /* CHECK says send it */
1067 case 335: /* IHAVE says send it */
1069 count_checkedwanted++;
1070 LIST_ADDTAIL(conn->queue);
1072 connfail("peer gave %d response to article body: %s",code, sani);
1073 return OOP_CONTINUE;
1078 case 431: /* CHECK or TAKETHIS says try later */
1080 case 436: /* IHAVE says try later */
1083 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1085 sysfatal("write to defer file %s",path_defer);
1086 article_done(conn, art, RC_deferred);
1091 check_check_work(conn);
1092 return OOP_CONTINUE;
1096 /*========== monitoring of input files ==========*/
1098 static void feedfile_eof(InputFile *ipf) {
1099 assert(ipf != main_input_file); /* promised by tailing_try_read */
1101 inputfile_tailing_stop(ipf);
1102 assert(ipf->fd >= 0);
1103 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1106 if (ipf == flushing_input_file) {
1107 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1108 if (main_input_file) inputfile_tailing_start(main_input_file);
1109 statemc_check_flushing_done();
1110 } else if (ipf == backlog_input_file) {
1111 statemc_check_backlog_done();
1113 abort(); /* supposed to wait rather than get EOF on main input file */
1117 static InputFile *open_input_file(const char *path) {
1118 int fd= open(path, O_RDONLY);
1120 if (errno==ENOENT) return 0;
1121 sysfatal("unable to open input file %s", path);
1124 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1125 memset(ipf,0,sizeof(*ipf));
1127 ipf->readable.on_readable= tailing_on_readable;
1128 ipf->readable.on_cancel= tailing_on_cancel;
1129 ipf->readable.try_read= tailing_try_read;
1132 strcpy(ipf->path, path);
1137 static void close_input_file(InputFile *ipf) {
1138 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1139 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1140 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1141 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1144 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1148 /*---------- dealing with articles read in the input file ----------*/
1150 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1151 oop_rd_event ev, const char *errmsg,
1153 const char *data, size_t recsz,
1155 InputFile *ipf= ipf_v;
1157 char tokentextbuf[sizeof(TOKEN)*2+3];
1159 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1161 if (data[0] && data[0]!=' ') {
1162 char *space= strchr(data,' ');
1163 int tokenlen= space-data;
1164 int midlen= (int)recsz-tokenlen-1;
1165 if (midlen < 0) goto bad_data;
1167 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1168 memcpy(tokentextbuf, data, tokenlen);
1169 tokentextbuf[tokenlen]= 0;
1170 if (!IsToken(tokentextbuf)) goto bad_data;
1172 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1173 art->offset= ipf->offset;
1174 art->blanklen= recsz;
1175 art->midlen= midlen;
1176 art->checked= art->sentbody= 0;
1177 art->ipf= ipf; ipf->inprogress++;
1178 art->token= TextToToken(tokentextbuf);
1179 strcpy(art->messageid, space+1);
1180 LIST_ADDTAIL(queue, art);
1182 ipf->offset += recsz + 1;
1184 if (sms==sm_NORMAL && ipf==main_input_file &&
1185 ipf->offset >= flush_threshold)
1186 statemc_start_flush("feed file size");
1188 check_master_queue();
1191 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1192 assert(sms == sm_NORMAL);
1194 debug("starting flush (%s) (%lu >= %lu) (%d)",
1196 (unsigned long)ipf->offset, (unsigned long)flush_threshold,
1199 int r= link(feedfile, duct_path);
1200 if (r) sysdie("link feedfile %s to flushing file %s", feedfile,
1204 xunlink(feedfile, "old feedfile link");
1207 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1210 /*========== tailing input file ==========*/
1212 static void filemon_start(InputFile *ipf) {
1213 assert(!ipf->filemon);
1215 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1216 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1217 filemon_method_startfile(ipf, ipf->filemon);
1220 static void filemon_stop(InputFile *ipf) {
1221 if (!ipf->filemon) return;
1222 filemon_method_stopfile(ipf, ipf->filemon);
1227 static void filemon_callback(InputFile *ipf) {
1228 ipf->readable_callback(ipf->readable_callback_user);
1231 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1233 InputFile *ipf= user;
1234 return ipf->readable_callback(ipf->readable_callback_user);
1237 static void on_cancel(struct oop_readable *rable) {
1238 InputFile *ipf= (void*)rable;
1240 if (ipf->filemon) filemon_stopfile(ipf);
1241 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1242 ipf->readable_callback= 0;
1245 static void tailing_queue_readable(InputFile *ipf) {
1246 /* lifetime of ipf here is OK because destruction will cause
1247 * on_cancel which will cancel this callback */
1248 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1251 static int tailing_on_readable(struct oop_readable *rable,
1252 oop_readable_call *cb, void *user) {
1253 InputFile *ipf= (void*)rable;
1255 tailing_on_cancel(rable);
1256 ipf->readable_callback= cb;
1257 ipf->readable_callback_user= user;
1258 filemon_startfile(ipf);
1260 tailing_queue_readable(ipf);
1264 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1266 InputFile *ipf= (void*)rable;
1268 ssize_t r= read(ipf->fd, buffer, length);
1270 if (errno==EINTR) continue;
1274 if (ipf==main_input_file) {
1277 } else if (ipf==flushing_input_file) {
1279 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1280 } else if (ipf==backlog_input_file) {
1290 /*---------- filemon implemented with inotify ----------*/
1292 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1293 #define HAVE_FILEMON
1295 #include <linux/inotify.h>
1297 static int filemon_inotify_fd;
1298 static int filemon_inotify_wdmax;
1299 static InputFile **filemon_inotify_wd2ipf;
1301 typedef struct Filemon_Perfile {
1303 } Filemon_Inotify_Perfile;
1305 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1306 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1307 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1309 if (wd >= filemon_inotify_wdmax) {
1311 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1312 sizeof(*filemon_inotify_wd2ipf) * newmax);
1313 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1314 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1315 filemon_inotify_wdmax= newmax;
1318 assert(!filemon_inotify_wd2ipf[wd]);
1319 filemon_inotify_wd2ipf[wd]= ipf;
1321 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1322 ipf, wd, filemon_inotify_wdmax);
1327 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1329 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1330 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1331 if (r) sysdie("inotify_rm_watch");
1332 filemon_inotify_wd2ipf[wd]= 0;
1335 static void *filemon_inotify_readable(oop_source *lp, int fd,
1336 oop_event e, void *u) {
1337 struct inotify_event iev;
1339 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1341 if (errno==EAGAIN) break;
1342 sysdie("read from inotify master");
1343 } else if (r==sizeof(iev)) {
1344 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1346 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1348 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1349 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1350 filemon_callback(ipf);
1352 return OOP_CONTINUE;
1355 static int filemon_method_init(void) {
1356 filemon_inotify_fd= inotify_init();
1357 if (filemon_inotify_fd<0) {
1358 syswarn("could not initialise inotify: inotify_init failed");
1362 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1364 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1368 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1370 /*---------- filemon dummy implementation ----------*/
1372 #if !defined(HAVE_FILEMON)
1374 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1376 static int filemon_method_init(void) { return 0; }
1377 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1378 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1380 #endif /* !HAVE_FILEMON */
1382 /*---------- interface to start and stop an input file ----------*/
1384 static const oop_rd_style feedfile_rdstyle= {
1385 OOP_RD_DELIM_STRIP, '\n',
1387 OOP_RD_SHORTREC_EOF,
1390 static void inputfile_tailing_start(InputFile *ipf) {
1392 ipf->readable->on_readable= tailing_on_readable;
1393 ipf->readable->on_cancel= tailing_on_cancel;
1394 ipf->readable->try_read= tailing_try_read;
1395 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1396 ipf->readable->delete_kill= 0;
1398 ipf->readable_callback= 0;
1399 ipf->readable_callback_user= 0;
1401 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1404 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1405 feedfile_got_article,ipf, feedfile_problem,ipf);
1406 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1409 static void inputfile_tailing_stop(InputFile *ipf) {
1411 oop_rd_cancel(ipf->rd);
1412 oop_rd_delete(ipf->rd);
1414 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1418 /*========== interaction with innd - state machine ==========*/
1420 /* See official state diagram at top of file. We implement
1431 |`---------------------------------------------------.
1433 |`---------------- - - - |
1434 D ENOENT | D EXISTS see OVERALL STATES diagram |
1435 | for full startup logic |
1438 | ============ try to |
1444 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1445 ^ | hardlink F to D |
1448 | | our handle onto F is now onto D |
1451 | |<-------------------<---------------------<---------+
1453 | | spawn inndcomm flush |
1455 | ================== |
1456 | FLUSHING[-ABSENT] |
1458 | main D tail/none |
1459 | ================== |
1461 | | INNDCOMM FLUSH FAILS ^
1462 | |`----------------------->----------. |
1464 | | NO SUCH SITE V |
1465 ^ |`--------------->----. ==================== |
1466 | | \ FLUSHFAILED[-ABSENT] |
1468 | | FLUSH OK \ main D tail/none |
1469 | | open F \ ==================== |
1471 | | \ | TIME TO RETRY |
1472 | |`------->----. ,---<---'\ `----------------'
1473 | | D NONE | | D NONE `----.
1475 | ============= V V ============
1476 | SEPARATED-1 | | DROPPING-1
1477 | flsh->fd>=0 | | flsh->fd>=0
1478 | [Separated] | | [Dropping]
1479 | main F idle | | main none
1480 | old D tail | | old D tail
1481 | ============= | | ============
1483 ^ | EOF ON D | | defer | EOF ON D
1485 | =============== | | ===============
1486 | SEPARATED-2 | | DROPPING-2
1487 | flsh->fd==-1 | V flsh->fd==-1
1488 | [Finishing] | | [Dropping]
1489 | main F tail | `. main none
1490 | old D closed | `. old D closed
1491 | =============== V `. ===============
1493 | | ALL D PROCESSED `. | ALL D PROCESSED
1494 | V install defer as backlog `. | install defer
1495 ^ | close D `. | close D
1496 | | unlink D `. | unlink D
1499 `----------' ==============
1519 static void statemc_init(void) {
1520 struct stat stab, stabf;
1522 path_lock= xasprintf("%s_lock", feedfile);
1523 path_flushing= xasprintf("%s_flushing", feedfile);
1524 path_defer= xasprintf("%s_defer", feedfile);
1525 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1528 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1529 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1532 memset(&fl,0,sizeof(fl));
1534 fl.l_whence= SEEK_SET;
1535 r= fcntl(lockfd, F_SETLK, &fl);
1537 if (errno==EACCES || errno==EAGAIN) {
1538 if (quiet_if_locked) exit(0);
1539 fatal("another duct holds the lockfile");
1541 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1544 xfstat_isreg(lockfd, &stabf, "lockfile");
1546 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1548 if (!lock_noent && samefile(&stab, &stabf))
1552 sysdie("could not close stale lockfile %s", path_lock);
1554 debug("startup: locked");
1556 search_backlog_file();
1559 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1561 debug("startup: ductdefer ENOENT");
1563 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1564 switch (stab.st_nlink==1) {
1566 open_defer(); /* so that we will later close it and rename it */
1569 xunlink(path_defer, "stale defer file link"
1570 " (presumably hardlink to backlog file)");
1573 die("defer file %s has unexpected link count %d",
1574 path_defer, stab.st_nlink);
1578 struct stat stab_f, stab_d;
1581 InputFile *file_d= open_input_file(path_flushing);
1582 if (file_d) xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1584 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1586 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1587 debug("startup: F==D => Hardlinked");
1588 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1593 debug("startup: F ENOENT => Moved");
1594 if (file_d) startup_set_input_file(file_d);
1595 spawn_inndcomm_flush("feedfile missing at startup");
1596 /* => Flushing, sms:=FLUSHING */
1599 debug("startup: F!=D => Separated");
1600 startup_set_input_file(file_d);
1601 SMS(SEPARATED, 0, "found both old and current feed files");
1603 debug("startup: F exists, D ENOENT => Normal");
1604 FILE *file_f= open_input_file(feedfile);
1605 if (!file_f) die("feed file vanished during startup");
1606 startup_set_input_file(file_f);
1607 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1612 static void statemc_period_poll(void) {
1613 if (!sm_period_counter) return;
1614 sm_period_counter--;
1615 assert(sm_period_counter>=0);
1617 if (sm_period_counter) return;
1620 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1622 case sm_FLUSHFAILED:
1623 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1630 static void startup_set_input_file(InputFile *f) {
1631 assert(!main_input_file);
1633 inputfile_tailing_start(f);
1636 static int inputfile_is_done(InputFile *ipf) {
1638 if (ipf->inprogress) return 0; /* new article in the meantime */
1639 if (ipf->fd >= 0); return 0; /* not had EOF */
1643 static void statemc_check_backlog_done(void) {
1644 InputFile *ipf= backlog_input_file();
1645 if (!inputfile_is_done(ipf)) return;
1647 notice_processed(ipf,"backlog file",ipf->path);
1648 close_input_file(ipf);
1649 if (unlink(ipf->path)) {
1650 if (errno != ENOENT)
1651 sysdie("could not unlink processed backlog file %s", ipf->path);
1652 warn("backlog file %s vanished while we were reading it"
1653 " so we couldn't remove it (but it's done now, anyway)",
1657 backlog_input_file= 0;
1658 search_backlog_file();
1662 static void statemc_check_flushing_done(void) {
1663 InputFile *ipf= flushing_input_file;
1664 if (!inputfile_is_done(ipf)) return;
1666 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1668 notice_processed(ipf,"feed file",0);
1672 xunlink(path_flushing, "old flushing file");
1674 close_input_file(flushing_input_file);
1675 free(flushing_input_file);
1676 flushing_input_file= 0;
1678 if (sms==sm_SEPARATED) {
1679 notice("flush complete");
1680 SMS(NORMAL, 0, "flush complete");
1681 } else if (sms==sm_DROPPING) {
1682 SMS(DROPPED, 0, "old flush complete");
1683 search_backlog_file();
1684 notice("feed dropped, but will continue until backlog is finished");
1688 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
1690 assert(!inputfile_is_done(main_input_file));
1691 statemc_check_flushing_done();
1692 statemc_check_backlog_done();
1693 return OOP_CONTINUE;
1696 static void queue_check_input_done(void) {
1697 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
1700 static void statemc_setstate(StateMachineState newsms, int periods,
1701 const char *forlog, const char *why) {
1703 sm_period_counter= periods;
1705 const char *xtra= "";
1707 case sm_FLUSHING: sm_FLUSHFAILED:
1708 if (!main_input_file) xtra= "-ABSENT";
1710 case sm_SEPARATED: case sm_DROPPING:
1711 xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
1717 info("%s%s[%d] %s",forlog,xtra,periods,why);
1719 info("%s%s %s",forlog,xtra,why);
1723 /*---------- defer and backlog files ----------*/
1725 static void open_defer(void) {
1730 defer= fopen(path_defer, "a+");
1731 if (!defer) sysfatal("could not open defer file %s", path_defer);
1733 /* truncate away any half-written records */
1735 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1737 if (stab.st_size > LONG_MAX)
1738 die("defer file %s size is far too large", path_defer);
1743 long orgsize= stab.st_size;
1744 long truncto= stab.st_size;
1746 if (!truncto) break; /* was only (if anything) one half-truncated record */
1747 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1748 sysdie("seek in defer file %s while truncating partial", path_defer);
1753 sysdie("failed read from defer file %s", path_defer);
1755 die("defer file %s shrank while we were checking it!", path_defer);
1761 if (stab.st_size != truncto) {
1762 warn("truncating half-record at end of defer file %s -"
1763 " shrinking by %ld bytes from %ld to %ld",
1764 path_defer, orgsize - truncto, orgsize, truncto);
1767 sysfatal("could not flush defer file %s", path_defer);
1768 if (ftruncate(fileno(defer), truncto))
1769 sysdie("could not truncate defer file %s", path_defer);
1772 info("continuing existing defer file %s (%ld bytes)",
1773 path_defer, orgsize);
1775 if (fseek(defer, truncto, SEEK_SET))
1776 sysdie("could not seek to new end of defer file %s", path_defer);
1779 static void close_defer(void) {
1783 xfstat(fileno(defer), &stab, "defer file");
1785 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1788 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1789 (unsigned long)now.tv_sec,
1790 (unsigned long)stab.st_ino);
1791 if (link(path_defer, path_backlog))
1792 sysfatal("could not install defer file %s as backlog file %s",
1793 path_defer, backlog);
1794 if (unlink(path_defer))
1795 sysdie("could not unlink old defer link %s to backlog file %s",
1796 path_defer, backlog);
1798 if (until_backlog_nextscan < 0 ||
1799 until_backlog_nextscan > backlog_retry_minperiods + 1)
1800 until_backlog_nextscan= backlog_retry_minperiods + 1;
1803 static void poll_backlog_file(void) {
1804 if (until_backlog_nextscan < 0) return;
1805 if (until_backlog_nextscan-- > 0) return;
1806 search_backlog_file();
1809 static void search_backlog_file(void) {
1810 /* returns non-0 iff there are any backlog files */
1815 const char *oldest_path=0;
1816 time_t oldest_mtime, now;
1818 if (backlog_input_file) return 3;
1822 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
1826 sysdie("failed to expand backlog pattern %s", globpat_backlog);
1828 die("out of memory expanding backlog pattern %s", globpat_backlog);
1830 for (i=0; i<gl.gl_pathc; i++) {
1831 const char *path= gl.gl_pathv[i];
1833 if (strchr(path,'#') || strchr(path,'~')) {
1834 debug("backlog file search skipping %s", path);
1837 r= stat(path, &stab);
1839 syswarn("failed to stat backlog file %s", path);
1842 if (!S_ISREG(stab.st_mode)) {
1843 warn("backlog file %s is not a plain file (or link to one)", path);
1846 if (!oldest_path || stab.st_mtime < oldest_mtime) {
1848 oldest_mtime= stab.st_mtime;
1851 case GLOB_NOMATCH: /* fall through */
1854 sysdie("glob expansion of backlog pattern %s gave unexpected"
1855 " nonzero (error?) return value %d", globpat_backlog, r);
1861 debug("backlog scan: none");
1863 if (sms==sm_DROPPED) {
1864 notice("feed dropped and our work is complete");
1865 xunlink(path_lock, "lockfile for old feed");
1868 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
1872 now= time(); if (now==-1) sysdie("time(2) failed");
1873 double age= difftime(now, oldest_mtime);
1874 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
1876 if (age_deficiency <= 0) {
1877 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
1878 age, age_deficiency, oldest_path);
1880 backlog_input_file= open_input_file(oldest_path);
1881 if (!backlog_input_file) {
1882 warn("backlog file %s vanished as we opened it", backlog_input_file);
1885 inputfile_tailing_start(backlog_input_file);
1886 until_backlog_nextscan= -1;
1890 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
1892 if (backlog_spontaneous_rescan_periods >= 0 &&
1893 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
1894 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
1896 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
1897 age, age_deficiency, until_backlog_nextscan, oldest_path);
1901 /*========== flushing the feed ==========*/
1903 static pid_t inndcomm_child;
1905 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1906 assert(inndcomm_child);
1907 int status= xwaitpid(&inndcomm_child, "inndcomm");
1908 loop->cancel_fd(fd);
1911 assert(!flushing_input_file);
1913 if (WIFEXITED(status)) {
1914 switch (WEXITSTATUS(status)) {
1916 case INNDCOMMCHILD_ESTATUS_FAIL:
1919 case INNDCOMMCHILD_ESTATUS_NONESUCH:
1920 warn("feed has been dropped by innd, finishing up");
1921 flushing_input_file= main_input_file;
1922 tailing_queue_readable(flushing_input_file);
1923 /* we probably previously returned EAGAIN from our fake read method
1924 * when in fact we were at EOF, so signal another readable event
1925 * so we actually see the EOF */
1929 if (flushing_input_file) {
1930 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
1933 SMS(DROPPED, 0, "feed dropped by innd");
1934 search_backlog_file();
1936 return OOP_CONTINUE;
1940 flushing_input_file= main_input_file;
1941 tailing_queue_readable(flushing_input_file);
1943 main_input_file= open_input_file(feedfile);
1944 if (!main_input_file)
1945 die("flush succeeded but feedfile %s does not exist!", feedfile);
1947 if (flushing_input_file) {
1948 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
1951 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
1953 return OOP_CONTINUE;
1956 goto unexpected_exitstatus;
1959 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1960 warn("flush timed out trying to talk to innd");
1963 unexpected_exitstatus:
1964 report_child_status("inndcomm child", status);
1968 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
1971 static void inndcommfail(const char *what) {
1972 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1973 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1976 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
1979 notice("flushing %s",why);
1981 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
1982 assert(!inndcomm_child);
1984 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1986 inndcomm_child= xfork();
1988 if (!inndcomm_child) {
1989 static char flushargv[2]= { sitename, 0 };
1994 alarm(inndcomm_flush_timeout);
1995 r= ICCopen(); if (r) inndcommfail("connect");
1996 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
1997 if (!r) exit(0); /* yay! */
1999 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2000 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2001 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2005 int sentinel_fd= pipefds[0];
2006 on_fd_read_except(sentinel_fd, inndcomm_event);
2008 SMS(FLUSHING, 0, why);
2011 /*========== main program ==========*/
2013 static void postfork_inputfile(InputFile *ipf) {
2015 assert(ipf->fd >= 0);
2020 static void postfork_conns(Connection *conn) {
2027 static void postfork_stdio(FILE *f) {
2028 /* we have no stdio streams that are buffered long-term */
2032 static void postfork(const char *what) {
2033 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2034 sysdie("%s child: failed to reset SIGPIPE");
2036 postfork_inputfile(main_input_file);
2037 postfork_inputfile(flushing_input_file);
2038 postfork_conns(idle.head);
2039 postfork_conns(working.head);
2040 postfork_conns(full.head);
2041 postfork_stdio(defer);
2044 #define EVERY(what, interval, body) \
2045 static const struct timeval what##_timeout = { 5, 0 }; \
2046 static void what##_schedule(void); \
2047 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2049 what##_schedule(); \
2051 static void what##_schedule(void) { \
2052 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2055 EVERY(filepoll, {5,0}, {
2056 if (main_input_file && main_input_file->readable_callback)
2057 filemon_callback(main_input_file);
2060 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s" \
2061 #define DEBUG_IPF(sh) \
2062 wh##_input_file, debug_ipf_path(wh##_input_file), \
2063 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2064 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2065 static const char *debug_ipf_path(InputFile *ipf) {
2066 char *slash= strrchr(ipf->path,'/');
2067 return slash ? slash+1 : ipf->path;
2070 EVERY(period, {PERIOD_SECONDS,0}, {
2072 " sms=%s[%d] queue=%d connect_delay=%d"
2073 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_FMT(flushing)
2074 " conns idle=%d working=%d full=%d"
2075 " children connecting=%ld inndcomm_child"
2077 sms_names[sms], sm_period_counter, queue.count, connect_delay,
2078 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2079 idle.count, working.count, full.count,
2080 (long)connecting_child, (long)inndcomm_child
2083 if (connect_delay) connect_delay--;
2085 poll_backlog_file();
2086 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2087 statemc_period_poll();
2088 check_master_queue();
2092 /*========== option parsing ==========*/
2095 of_seconds= 001000u;
2096 of_boolean= 002000u;
2099 typedef struct Option Option;
2100 typedef void OptionParser(const Option*, const char *val);
2110 void op_integer(const Option *o, const char *val) {
2113 unsigned long ul= strtoul(val,&ep,10);
2114 if (*ep || ep==val || errno || ul>INT_MAX)
2115 badusage("bad integer value for %s",o->long);
2116 int *store= o->store;
2120 void op_double(const Option *o, const char *val) {
2121 int *store= o->store;
2124 *store= strtod(val, &ep);
2125 if (*ep || ep==val || errno)
2126 badusage("bad floating point value for %s",o->long);
2129 void op_string(const Option *o, const char *val) {
2130 char **store= o->store;
2135 void op_seconds(const Option *o, const char *val) {
2136 int *store= o->store;
2139 double v= strtod(val,&ep);
2140 if (ep==val) badusage("bad time/duration value for %s",o->long);
2142 if (!*ep || !strcmp(ep,"s")) unit= 1;
2143 else if (!strcmp(ep,"m")) unit= 60;
2144 else if (!strcmp(ep,"h")) unit= 3600;
2145 else if (!strcmp(ep,"d")) unit= 86400;
2146 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2150 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2154 void op_periods_rndup(const Option *o, const char *val) {
2155 int *store= o->store;
2157 *store += PERIOD_SECONDS-1;
2158 *store /= PERIOD_SECONDS;
2161 void op_periods_booltrue(const Option *o, const char *val) {
2162 int *store= o->store;
2165 void op_periods_boolfalse(const Option *o, const char *val) {
2166 int *store= o->store;
2170 static const Option options[]= {
2171 { 0, "max-connections", &max_connections op_integer },
2172 { 0, "streaming", &try_stream, op_booltrue, 1 },
2173 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2174 {'h',"host", &remote_host, op_string },
2175 {'P',"port", &port op_integer },
2176 { 0, "inndconf", &inndconffile, op_string },
2177 {'f',"feedfile", &feedfile, op_string },
2178 {'q',"quiet-multiple", &quiet_if_locked, op_booltrue, 1 },
2179 { 0, "no-quiet-multiple", &quiet_if_locked, op_boolfalse, 1 },
2180 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2181 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2183 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2184 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2186 { 0, "max-queue-size", &max_queue_per_conn op_integer },
2187 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2188 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2189 { 0, "connection-timeout", &connection_timeout, op_seconds },
2190 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2193 int main(int argc, char **argv) {
2199 if (*arg != '-') break;
2200 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2202 while ((a= *++arg)) {
2206 char *equals= strchr(arg,'=');
2207 int len= equals ? (equals - arg) : strlen(arg);
2208 for (o=options; o->long; o++)
2209 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2211 badusage("unknown long option --%s",arg);
2214 if (equals) badusage("option --%s does not take a value",o->long);
2216 } else if (equals) {
2220 if (!arg) badusage("option --%s needs a value",o->long);
2223 break; /* eaten the whole argument now */
2225 for (o=options; o->long; o++)
2228 badusage("unknown short option -%c",a);
2235 if (!arg) badusage("option -%c needs a value",o->short);
2238 break; /* eaten the whole argument now */
2243 if (!arg) badusage("need site name argument");
2246 if ((arg= *++argv)) {
2247 if (remote_host) badusage("must not specify -h and also host as argument");
2251 if (*++argv) badusage("too many non-option arguments");
2253 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2254 badusage("nocheck threshold percentage must be between 0..100");
2255 nocheck_thresh= nocheck_thresh_pct * 0.01;
2257 if (nocheck_decay_articles < 0.1)
2258 badusage("nocheck decay articles must be at least 0.1");
2259 nocheck_decay= 1 - 1/nocheck_decay_articles;
2261 innconf_read(inndconffile);
2264 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2265 else if (!feedfile[0])
2266 badusage("feed filename must be nonempty");
2267 else if (feedfile[strlen(feedfile)-1]=='/')
2268 feedfile= xasprintf("%s%s",feedfile,sitename);
2270 const char *feedfile_forbidden= "?*[~#";
2272 while ((c= *feedfile_forbidden++))
2273 if (strchr(feedfile, c))
2274 badusage("feed filename may not contain metacharacter %c",c);
2276 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2277 sysdie("could not ignore SIGPIPE");
2279 if (become_daemon) {
2280 for (i=3; i<255; i++)
2281 /* do this now before we open syslog, etc. */
2283 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2285 int null= open("/dev/null",O_RDWR);
2286 if (null<0) sysdie("failed to open /dev/null");
2292 pid_t child1= xfork("daemonise first fork");
2293 if (child1) _exit(0);
2295 pid_t sid= setsid();
2296 if (sid != child1) sysdie("setsid failed");
2298 pid_t child2= xfork("daemonise second fork");
2299 if (child2) _exit(0);
2304 if (!filemon_init()) {
2305 warn("no file monitoring available, polling");
2306 filepoll_schedule();