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
31 * site.name_backlog_<date>.<inum>
32 * 431'd articles, ready for innxmit or duct
33 * created (link/mv) by duct
34 * site.name_backlog_<anything-else> eg
35 * site.name_backlog_manual
36 * anything the sysadmin likes (eg, feed files
37 * from old feeds to be merged into this one)
38 * created (link/mv) by admin
39 * may be symlinks (in which case links
40 * may be written through, but only links
43 * It is safe to remove backlog files manually,
44 * if it's desired to throw away the backlog.
46 * Backlog files are also processed by innduct. We find the oldest
47 * backlog file which is at least a certain amount old, and feed it
48 * back into our processing. When every article in it has been read
49 * and processed, we unlink it and look for another backlog file.
51 * If we don't have a backlog file that we're reading, we close the
52 * defer file that we're writing and make it into a backlog file at
53 * the first convenient opportunity.
62 <--------------------------------------'|
63 Nothing F, D both ENOENT |
66 duct: not not reading anything |
68 |`---------------------. |
69 | | duct times out waiting for F |
70 V innd creates F | duct exits |
72 Noduct GO TO Dropped |
75 duct: not running or not reading anything |
78 ,-->--+ <---------------------------------'|
79 | | duct opens F F exists |
83 | F: innd writing, duct reading |
86 | | duct decides time to flush |
87 | | duct makes hardlink |
89 | V <------------------------'|
91 | F == D: innd writing, duct reading both exist |
95 | Moved <----+------------<--'|
96 | F: ENOENT | F ENOENT |
97 | D: innd writing, duct reading | D exists |
99 | | duct requests flush of feed | |
100 | | (others can too, harmlessly) | |
104 | D: innd flushing, duct reading | |
106 | | inndcomm flush fails | |
107 | |`-------------------------->---------' |
109 | | inndcomm reports no such site |
110 | |`---------------------------------------------------- | -.
112 | | innd finishes writing D, creates F | |
113 | | inndcomm reports flush successful | |
116 | Separated <----------------' |
117 | F: innd writing F!=D /
118 | D: duct reading both exist /
120 | | duct gets to the end of D /
121 | | duct opens F too /
124 | F: innd writing, duct reading |
125 | D: duct finishing V
127 | | duct finishes processing D F: ENOENT
128 | V duct unlinks D D: duct reading
130 `--<--' | duct finishes
140 "duct reading" means innduct is reading the file but also
141 overwriting processed tokens.
148 /*----- general definitions, probably best not changed -----*/
150 #define PERIOD_SECONDS 60
152 #define CONNCHILD_ESTATUS_STREAM 4
153 #define CONNCHILD_ESTATUS_NOSTREAM 5
155 #define INNDCOMMCHILD_ESTATUS_FAIL 6
156 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
159 /*----- configuration options -----*/
161 static char *sitename, *feedfile;
162 static int max_connections=10, max_queue_per_conn=200;
163 static int connection_setup_timeout=200, port=119, try_stream=1;
164 static int inndcomm_flush_timeout=100, quiet_if_locked=0;
165 static const char *remote_host;
166 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
167 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
168 static const char *inndconffile;
170 static double accept_proportion;
171 static double nocheck_thresh_pct= 95.0;
172 static double nocheck_thresh; /* computed in main from _pct */
173 static double nocheck_decay_articles= 100; /* converted to _decay */
174 static double nocheck_decay; /* computed in main from _articles */
175 static int nocheck, nocheck_reported;
178 /*----- doubly linked lists -----*/
180 #define ISNODE(T) T *next, *back;
181 #define LIST(T) struct { T *head, *tail, *tailpred; int count; }
183 #define NODE(n) ((struct node*)&(n)->head)
185 #define LIST_ADDHEAD(l,n) \
186 (list_addhead((struct list*)&(l), NODE((n))), (void)(l).count++)
187 #define LIST_ADDTAIL(l,n) \
188 (list_addtail((struct list*)&(l), NODE((n))), (void)(l).count++)
190 #define LIST_REMHEAD(l) \
191 ((l).count ? ((l).count--, (void*)list_remhead((struct list*)&(l))) : 0)
192 #define LIST_REMTAIL(l) \
193 ((l).count ? ((l).count--, (void*)list_remtail((struct list*)&(l))) : 0)
194 #define LIST_REMOVE(l,n) \
195 (list_remove(NODE((n))), (void)(l).count--)
196 #define LIST_INSERT(l,n,pred) \
197 (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
200 /*----- statistics -----*/
202 #define RESULT_COUNTS \
211 #define RC_INDEX(x) RCI_##x
217 int articles[2 /* checked */][RCI_max];
221 /*----- transmission buffers -----*/
226 xk_Malloc, xk_Const, xk_Artdata;
238 /*----- core operational data structure types -----*/
242 int checked, sentbody;
250 typedef struct InputFile {
251 /* This is an instance of struct oop_readable */
252 struct oop_readable readable; /* first */
253 oop_readable_call *readable_callback;
254 void *readable_callback_user;
257 const char *path; /* ptr copy of path_<foo> or feedfile */
258 struct Filemon_Perfile *filemon;
261 long inprogress; /* no. of articles read but not processed */
278 int fd, max_queue, stream;
279 LIST(Article) queue; /* not yet told peer, or CHECK said send it */
280 LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
281 struct iovec xmit[CONNIOVS];
282 XmitDetails xmitd[CONNIOVS];
287 /*----- operational variables -----*/
289 static int since_connect_attempt;
291 static LIST(Conn) idle, working, full;
292 static LIST(Article) *queue;
294 static char *path_ductlock, *path_duct, *path_ductdefer;
296 #define SMS(newstate, periods, why) \
297 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
299 static StateMachineState sms;
301 static InputFile *main_input_file, *old_input_file, *backlog_input_file;
302 static int sm_period_counter;
305 /*----- function predeclarations -----*/
307 static void conn_check_work(Conn *conn);
309 static int filemon_init(void);
310 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
311 static void filemon_callback(void);
313 static void statemc_setstate(StateMachineState newsms, int periods,
314 const char *forlog, const char *why);
316 /*========== utility functions etc. ==========*/
318 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
320 static pid_t xfork(const char *what) {
324 if (child==-1) sysdie("cannot fork for %s",what);
325 if (!child) postfork(what);
329 static void on_fd_read_except(int fd, oop_call_fd callback) {
330 loop->on_fd(loop, fd, OOP_READ, callback, 0);
331 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
333 static void cancel_fd_read_except(int fd) {
334 loop->cancel_fd(loop, fd, OOP_READ);
335 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
338 static void report_child_status(const char *what, int status) {
339 if (WIFEXITED(status)) {
340 int es= WEXITSTATUS(status);
342 warn("%s: child died with error exit status %d",es);
343 } else if (WIFSIGNALED(status)) {
344 int sig= WTERMSIG(status);
345 const char *sigstr= strsignal(sig);
346 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
348 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
350 warn("%s: child died due to unknown fatal signal %d%s",
351 what, sig, coredump);
353 warn("%s: child died with unknown wait status %d", status);
357 static int xwaitpid(pid_t *pid, const char *what) {
360 r= kill(*pid, SIGKILL);
361 if (r) sysdie("cannot kill %s child", what);
363 pid_t got= waitpid(*pid, &status, WNOHANG);
364 if (got==-1) sysdie("cannot reap %s child", what);
371 static void check_isreg(const struct stat *stab, const char *path,
373 if (!S_ISREG(stab->st_mode))
374 die("%s %s not a plain file (mode 0%lo)",
375 what, path, (unsigned long)stab->st_mode);
378 static void xfstat(int fd, struct stat *stab_r, const char *what) {
379 int r= fstab(path, stab);
380 if (r) sysdie("could not fstat %s %s", what, path);
383 static void xfstat_isreg(int fd, struct stat *stab_r, const char *what) {
384 xfstat(fd, stab_r, what);
385 check_isreg(stab, path, what);
388 static void xlstat_isreg(const char *path, struct stat *stab,
389 int *enoent_r /* 0 means ENOENT is fatal */
391 int r= lstat(path, stab);
393 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
394 sysdie("could not lstat %s %s", what, path);
396 if (enoent_r) *enoent_r= 0;
397 check_isreg(stab, path, what);
400 static int samefile(const struct stat *a, const struct stat *b) {
401 assert(S_ISREG(a->st_mode));
402 assert(S_ISREG(b->st_mode));
403 return (a->st_ino == b->st_ino &&
404 a->st_dev == b->st_dev);
407 /*========== logging ==========*/
409 static void logcore(int sysloglevel, const char *fmt, ...)
410 __attribute__((printf,2,3))
411 static void logcore(int sysloglevel, const char *fmt, ...) {
415 vsyslog(sysloglevel,fmt,al);
417 vfprintf(stderr,fmt,al);
422 static void logv(int sysloglevel, const char *pfx, int errnoval,
423 int exitstatus, const char *fmt, va_list al)
424 __attribute__((printf,4,0))
425 static void logv(int sysloglevel, const char *pfx, int errnoval,
426 int exitstatus, const char *fmt, va_list al) {
428 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
429 msgbuf[sizeof(msgbuf)-1]= 0;
431 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
432 sysloglevel= LOG_ERR; /* run by wrong user, probably */
434 logcore(sysloglevel, "<%s>%s: %s%s%s",
435 sitename, pfx, msgbuf,
436 errnoval>=0 ? ": " : "",
437 errnoval>=0 ? strerror(errnoval) : "");
440 #define logwrap(fn, pfx, sysloglevel, errno, estatus) \
441 static void fn(const char *fmt, ...) \
442 __attribute__((printf,1,2)); \
443 static void fn(const char *fmt, ...) { \
446 logv(sysloglevel, pfx, errno, estatus, fmt, al); \
449 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
450 logwrap(die, " critical", LOG_CRIT, -1, 16);
452 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
453 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
455 logwrap(syswarn, " warning", LOG_WARN, errno, 0);
456 logwrap(warn, " warning", LOG_WARN, -1, 0);
458 logwrap(notice, "", LOG_NOTICE, -1, 0);
459 logwrap(info, " info", LOG_INFO, -1, 0);
462 /*========== making new connections ==========*/
464 static int connecting_sockets[2]= {-1,-1};
465 static pid_t connecting_child;
467 static void connect_attempt_discard(void) {
468 if (connecting_sockets[0])
469 cancel_fd(connecting_sockets[0]);
471 perhaps_close(&connecting_sockets[0]);
472 perhaps_close(&connecting_sockets[1]);
474 if (connecting_child) {
475 int status= xwaitpid(&connecting_child, "connect");
477 if (!(WIFEXITED(status) ||
478 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
479 report_child_status("connect", status);
483 #define PREP_DECL_MSG_CMSG(msg) \
485 memset(&msg,0,sizeof(msg)); \
486 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
487 msg.msg_control= msg##cbuf; \
488 msg.msg_controllen= sizeof(msg##cbuf);
490 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
493 conn= xmalloc(sizeof(*conn));
494 memset(conn,0,sizeof(*conn));
497 struct cmsghdr *h= 0;
498 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
499 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
502 pid_t got= waitpid(connecting_child, &status, WNOHANG);
504 assert(got==connecting_child);
506 if (WIFEXITED(status) &&
507 (WEXITSTATUS(status) != 0
508 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
509 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
510 /* child already reported the problem */
511 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
512 warn("connect: connection attempt timed out");
513 } else if (!WIFEXITED(status)) {
514 report_child_status("connect", status);
515 /* that's probably the root cause then */
518 /* child is still running apparently, report the socket problem */
520 syswarn("connect: read from child socket failed");
521 else if (e == OOP_EXCEPTIONN)
522 warn("connect: unexpected exception on child socket");
524 warn("connect: unexpected EOF on child socket");
529 #define CHK(field, val) \
530 if (h->cmsg_##field != val) { \
531 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
534 CHK(level, SOL_SOCKET);
535 CHK(type, SCM_RIGHTS);
536 CHK(len, CMSG_LEN(sizeof(conn-b>fd)));
539 if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
541 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
543 pid_t got= waitpid(connecting_child, &status, 0);
544 if (got==-1) sysdie("connect: real wait for child");
545 assert(got == connecting_child);
548 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
549 int es= WEXITSTATUS(status);
551 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
552 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
554 fatal("connect: child gave unexpected exit status %d", es);
560 LIST_ADDHEAD(idle, conn);
561 notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
562 connect_attempt_discard();
563 check_master_queue();
568 perhaps_close(&conn->fd);
571 connect_attempt_discard();
574 static void connect_start() {
575 assert(!connecting_sockets[0]);
576 assert(!connecting_sockets[1]);
577 assert(!connecting_child);
579 notice("starting connection attempt");
581 r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
582 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
584 connecting_child= xfork("connection");
586 if (!connecting_child) {
587 FILE *cn_from, *cn_to;
588 char buf[NNTP_STRLEN+100];
589 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
591 r= close(connecting_sockets[0]);
592 if (r) sysdie("connect: close parent socket in child");
594 alarm(connection_setup_timeout);
595 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
597 sanitise_inplace(buf);
598 fatal("connect: rejected: %s", buf);
600 sysfatal("connect: connection attempt failed");
603 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
604 sysfatal("connect: authentication failed");
606 if (fputs("MODE STREAM\r\n", cn_to) ||
608 sysfatal("connect: could not send MODE STREAM");
609 buf[sizeof(buf)-1]= 0;
610 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
612 sysfatal("connect: could not read response to MODE STREAM");
614 fatal("connect: connection close in response to MODE STREAM");
619 sanitise_inplace(buf);
620 fatal("connect: response to MODE STREAM is too long: %.100s...",
623 l--; if (l>0 && buf[1-]=='\r') l--;
626 int rcode= strtoul(buf,&ep,10);
628 sanitise_inplace(buf);
629 fatal("connect: bad response to MODE STREAM: %.50s", buf);
633 exitstatus= CONNCHILD_ESTATUS_STREAM;
639 sanitise_inplace(buf);
640 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
645 int fd= fileno(cn_from);
647 PREP_DECL_MSG_CMSG(msg);
648 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
649 cmsg->cmsg_level= SOL_SOCKET;
650 cmsg->cmsg_type= SCM_RIGHTS;
651 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
652 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
654 msg.msg_controllen= cmsg->cmsg_len;
655 r= sendmsg(connecting_sockets[1], &msg, 0);
656 if (r) sysdie("sendmsg failed for new connection");
661 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
662 if (r) sysdie("connect: close child socket in parent");
664 on_fd_read_except(connecting_sockets[0], connchild_event);
668 connect_attempt_discard();
672 /*========== overall control of article flow ==========*/
674 static void check_master_queue(void) {
678 Conn *last_assigned=0;
681 conn_assign_one_article(&working, &last_assigned);
682 } else if (idle.head) {
683 conn_assign_one_article(&idle, &last_assigned);
684 } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
685 !connecting_child && !connect_delay) {
686 connect_delay= reconnect_delay_periods;
692 conn_check_work(last_assigned);
695 static void conn_assign_one_article(LIST(Conn) *connlist,
696 Conn **last_assigned) {
697 Conn *conn= connlist->head;
699 LIST_REMOVE(*connlist, conn);
700 Article *art= LIST_REMHEAD(queue);
701 LIST_ADDTAIL(conn->queue, art);
702 LIST_ADD(*conn_determine_right_list(conn), conn);
704 /* This slightly odd arrangement is so that we call conn_check_work
705 * once after filling the queue for a new connection in
706 * check_master_queue, rather than for each article. */
707 if (conn != *last_assigned && *last_assigned)
708 conn_check_work(*last_assigned);
709 *last_assigned= conn;
712 static int conn_total_queued_articles(Conn *conn) {
713 return conn->sent.count + conn->queue.count;
716 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
717 int inqueue= conn_total_queued_articles(conn);
718 assert(inqueue <= max_queue);
719 if (inqueue == 0) return &idle;
720 if (inqueue == conn->max_queue) return &full;
724 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
729 static void conn_check_work(Conn *conn) {
732 conn_make_some_xmits(conn);
734 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
738 void *rp= conn_write_some_xmits(conn);
739 if (rp==OOP_CONTINUE) {
740 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
742 } else if (rp==OOP_HALT) {
745 /* transmitted everything */
753 /*========== article transmission ==========*/
755 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
756 XmitKind kind) { /* caller must then fill in details */
757 struct iovec *v= &conn->xmit[conn->xmitu];
758 XmitDetails *d= &conn->xmitd[conn->xmitu++];
765 static void xmit_noalloc(Conn *conn, const char *data, int len) {
766 xmit_core(conn,data,len, xk_Const);
768 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
770 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
771 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
775 static void xmit_free(XmitDetails *d) {
777 case xk_Malloc: free(d->info.malloc_tofree); break;
778 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
779 case xk_Const: break;
784 static void *conn_write_some_xmits(Conn *conn) {
786 * 0: nothing more to write, no need to call us again
787 * OOP_CONTINUE: more to write but fd not writeable
788 * OOP_HALT: disaster, have destroyed conn
791 int count= conn->xmitu;
792 if (!count) return 0;
794 if (count > IOV_MAX) count= IOV_MAX;
795 ssize_t rs= writev(conn->fd, conn->xmit, count);
797 if (errno == EAGAIN) return OOP_CONTINUE;
798 connfail(conn, "write failed: %s", strerror(errno));
803 for (done=0; rs && done<xmitu; done++) {
804 struct iovec *vp= &conn->xmit[done];
805 XmitDetails *dp= &conn->xmitd[done];
806 if (rs > vp->iov_len) {
814 int newu= conn->xmitu - done;
815 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
816 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
821 static void conn_make_some_xmits(Conn *conn) {
823 if (conn->xmitu+5 > CONNIOVS)
826 Article *art= LIST_REMHEAD(queue);
829 if (art->checked || (conn->stream && nocheck)) {
830 /* actually send it */
832 ARTHANDLE *artdata= SMretrieve();
836 XMIT_LITERAL("TAKETHIS ");
837 xmit_noalloc(conn, art->mid, art->midlen);
838 XMIT_LITERAL("\r\n");
839 xmit_artbody(conn, artdata);
842 /* we got 235 from IHAVE */
844 xmit_artbody(conn, artdata);
846 XMIT_LITERAL(".\r\n");
851 LIST_ADDTAIL(conn->sent, art);
853 art->ipf->counts[art->checked].sent++;
859 XMIT_LITERAL("IHAVE ");
861 XMIT_LITERAL("CHECK ");
862 xmit_noalloc(art->mid, art->midlen);
863 XMIT_LITERAL("\r\n");
865 LIST_ADDTAIL(conn->sent, art);
866 art->ipf->counts[art->checked].offered++;
872 /*========== handling responses from peer ==========*/
874 static const oop_rd_style peer_rd_style= {
875 OOP_RD_DELIM_STRIP, '\n',
877 OOP_RD_SHORTREC_FORBID
880 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
881 const char *errmsg, int errnoval,
882 const char *data, size_t recsz, void *conn_v) {
884 connfail(conn, "error receiving from peer: %s", errmsg);
888 static Article *article_reply_check(Connection *conn, const char *response,
889 int code_indicates_streaming,
890 const char *sanitised_response) {
891 Article *art= LIST_REMHEAD(conn->sent);
895 "peer gave unexpected response when no commands outstanding: %s",
900 if (code_indicates_streaming) {
901 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
903 connfail("peer gave streaming response code "
904 " to IHAVE or subsequent body: %s", sanitised_response);
907 const char *got_mid= response+4;
908 int got_midlen= strcspn(got_mid, " \n\r");
909 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
910 connfail("peer gave streaming response with syntactically invalid"
911 " messageid: %s", sanitised_response);
914 if (got_midlen != art->midlen ||
915 memcmp(got_mid, art->messageid, got_midlen)) {
916 connfail("peer gave streaming response code to wrong article -"
917 " probable synchronisation problem; we offered: %s;"
919 art->messageid, sanitised_response);
924 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
933 static void update_nocheck(int accepted) {
934 accept_proportion *= accept_decay;
935 accept_proportion += accepted;
936 nocheck= accept_proportion >= nocheck_thresh;
937 if (nocheck && !nocheck_reported) {
938 notice("entering nocheck mode for the first time");
943 static void article_done(Connection *conn, Article *art, int whichcount) {
945 art->ipf->counts.articles[art->checked][whichcount]++;
946 if (whichcount == RC_accepted) update_nocheck(1);
947 else if (whichcount == RC_unwanted) update_nocheck(0);
949 InputFile *ipf= art->ipf;
950 while (art->blanklen) {
951 static const char spaces[]=
956 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
957 int r= pwrite(ipf->fd, spaces, w, art->offset);
959 if (errno==EINTR) continue;
960 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
961 art->messageid, art->blanklen, art->offset, ipf->path);
963 assert(r>=0 && r<=w);
969 assert(ipf->inprogress >= 0);
971 if (!ipf->inprogress)
972 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, ipf);
977 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
978 const char *errmsg, int errnoval,
979 const char *data, size_t recsz, void *conn_v) {
982 if (ev == OOP_RD_EOF) {
983 connfail(conn, "unexpected EOF from peer");
986 assert(ev == OOP_RD_OK);
989 unsigned long code= strtoul(data, &ep, 10);
990 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
996 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
998 if (!c) { *q++= '\''; break; }
999 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
1000 sprintf(q,"\\x%02x",c);
1003 connfail(conn, "badly formatted response from peer: %s", sanibuf);
1004 return OOP_CONTINUE;
1007 if (conn->quitting) {
1009 connfail(conn, "peer gave failure response to QUIT: %s", sani);
1010 return OOP_CONTINUE;
1018 #define GET_ARTICLE \
1019 art= article_reply_check(conn, data, code_streaming, sani); \
1020 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1022 #define ARTICLE_DEALTWITH(streaming,how) \
1023 code_streaming= (streaming) \
1025 article_done(conn, art, RC_##how); break;
1027 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1029 int code_streaming= 0;
1033 case 400: PEERBADMSG("peer stopped accepting articles");
1034 case 503: PEERBADMSG("peer timed us out");
1035 default: PEERBADMSG("peer sent unexpected message");
1037 case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
1038 case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
1040 case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
1041 case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
1043 case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
1044 case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
1046 case 238: /* CHECK says send it */
1048 case 335: /* IHAVE says send it */
1050 count_checkedwanted++;
1051 LIST_ADDTAIL(conn->queue);
1053 connfail("peer gave %d response to article body: %s",code, sani);
1054 return OOP_CONTINUE;
1059 case 431: /* CHECK or TAKETHIS says try later */
1061 case 436: /* IHAVE says try later */
1064 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1066 sysfatal("write to defer file %s",path_ductdefer);
1067 article_done(conn, art, RC_deferred);
1072 check_check_work(conn);
1073 return OOP_CONTINUE;
1077 /*========== monitoring of input files ==========*/
1079 static void feedfile_eof(InputFile *ipf) {
1080 assert(ipf != main_input_file); /* promised by tailing_try_read */
1082 inputfile_tailing_stop(ipf);
1084 if (ipf == backlog_input_file) {
1085 assert(ipf->fd >= 0);
1086 if (close(ipf->fd)) sysdie("could not close backlog file %s", ipf->path);
1091 assert(ipf == old_input_file);
1093 inputfile_tailing_stop(ipf);
1094 assert(ipf->fd >= 0);
1095 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1098 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1100 if (main_input_file)
1101 inputfile_tailing_start(main_input_file);
1104 static InputFile *open_input_file(const char *path) {
1105 int fd= open(path, O_RDONLY);
1107 if (errno==ENOENT) return 0;
1108 sysfatal("unable to open input file %s", path);
1111 InputFile *ipf= xmalloc(sizeof(InputFile));
1112 memset(ipf,0,sizeof(*ipf));
1114 ipf->readable.on_readable= tailing_on_readable;
1115 ipf->readable.on_cancel= tailing_on_cancel;
1116 ipf->readable.try_read= tailing_try_read;
1124 static void close_input_file(InputFile *ipf) {
1125 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1126 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1127 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1128 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1131 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1133 fixme maybe free ipf->path;
1139 /*---------- dealing with articles read in the input file ----------*/
1141 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1142 oop_rd_event ev, const char *errmsg,
1144 const char *data, size_t recsz,
1146 InputFile *ipf= ipf_v;
1148 char tokentextbuf[sizeof(TOKEN)*2+3];
1150 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1152 if (data[0] && data[0]!=' ') {
1153 char *space= strchr(data,' ');
1154 int tokenlen= space-data;
1155 int midlen= (int)recsz-tokenlen-1;
1156 if (midlen < 0) goto bad_data;
1158 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1159 memcpy(tokentextbuf, data, tokenlen);
1160 tokentextbuf[tokenlen]= 0;
1161 if (!IsToken(tokentextbuf)) goto bad_data;
1163 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1164 art->offset= ipf->offset;
1165 art->blanklen= recsz;
1166 art->midlen= midlen;
1167 art->checked= art->sentbody= 0;
1168 art->ipf= ipf; ipf->inprogress++;
1169 art->token= TextToToken(tokentextbuf);
1170 strcpy(art->messageid, space+1);
1171 LIST_ADDTAIL(queue, art);
1173 ipf->offset += recsz + 1;
1175 if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
1176 notice("starting flush (%lu >= %lu)",
1177 (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1179 int r= link(feedfile, duct_path);
1180 if (r) sysdie("link feedfile %s to ductfile %s", feedfile, dut_path);
1183 r= unlink(feedfile);
1184 if (r) sysdie("unlink old feedfile link %s", feedfile);
1187 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1190 check_master_queue();
1194 /*========== tailing input file ==========*/
1196 static void filemon_start(InputFile *ipf) {
1197 assert(!ipf->filemon);
1199 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1200 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1201 filemon_method_startfile(ipf, ipf->filemon);
1204 static void filemon_stop(InputFile *ipf) {
1205 if (!ipf->filemon) return;
1206 filemon_method_stopfile(ipf, ipf->filemon);
1211 static void filemon_callback(InputFile *ipf) {
1212 ipf->readable_callback(ipf->readable_callback_user);
1215 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1217 InputFile *ipf= user;
1218 return ipf->readable_callback(ipf->readable_callback_user);
1221 static void on_cancel(struct oop_readable *rable) {
1222 InputFile *ipf= (void*)rable;
1224 if (ipf->filemon) filemon_stopfile(ipf);
1225 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1226 ipf->readable_callback= 0;
1229 static int tailing_on_readable(struct oop_readable *rable,
1230 oop_readable_call *cb, void *user) {
1231 InputFile *ipf= (void*)rable;
1233 tailing_on_cancel(rable);
1234 ipf->readable_callback= cb;
1235 ipf->readable_callback_user= user;
1236 filemon_startfile(ipf);
1238 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1242 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1244 InputFile *ipf= (void*)rable;
1246 ssize_t r= read(ipf->fd, buffer, length);
1248 if (errno==EINTR) continue;
1252 if (ipf==main_input_file) {
1255 } else if (ipf==old_input_file) {
1257 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1258 } else if (ipf==backlog_input_file) {
1268 /*---------- filemon implemented with inotify ----------*/
1270 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1271 #define HAVE_FILEMON
1273 #include <linux/inotify.h>
1275 static int filemon_inotify_fd;
1276 static int filemon_inotify_wdmax;
1277 static InputFile **filemon_inotify_wd2ipf;
1279 typedef struct Filemon_Perfile {
1281 } Filemon_Inotify_Perfile;
1283 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1284 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1285 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1287 if (wd >= filemon_inotify_wdmax) {
1289 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1290 sizeof(*filemon_inotify_wd2ipf) * newmax);
1291 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1292 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1293 filemon_inotify_wdmax= newmax;
1296 assert(!filemon_inotify_wd2ipf[wd]);
1297 filemon_inotify_wd2ipf[wd]= ipf;
1302 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1304 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1305 if (r) sysdie("inotify_rm_watch");
1306 filemon_inotify_wd2ipf[wd]= 0;
1309 static void *filemon_inotify_readable(oop_source *lp, int fd,
1310 oop_event e, void *u) {
1311 struct inotify_event iev;
1313 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1315 if (errno==EAGAIN) break;
1316 sysdie("read from inotify master");
1317 } else if (r==sizeof(iev)) {
1318 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1320 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1322 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1323 filemon_callback(ipf);
1325 return OOP_CONTINUE;
1328 static int filemon_method_init(void) {
1329 filemon_inotify_fd= inotify_init();
1330 if (filemon_inotify_fd<0) {
1331 syswarn("could not initialise inotify: inotify_init failed");
1335 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1340 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1342 /*---------- filemon dummy implementation ----------*/
1344 #if !defined(HAVE_FILEMON)
1346 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1348 static int filemon_method_init(void) { return 0; }
1349 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1350 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1352 #endif /* !HAVE_FILEMON */
1354 /*---------- interface to start and stop an input file ----------*/
1356 static const oop_rd_style feedfile_rdstyle= {
1357 OOP_RD_DELIM_STRIP, '\n',
1359 OOP_RD_SHORTREC_EOF,
1362 static void inputfile_tailing_start(InputFile *ipf) {
1364 ipf->readable->on_readable= tailing_on_readable;
1365 ipf->readable->on_cancel= tailing_on_cancel;
1366 ipf->readable->try_read= tailing_try_read;
1367 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1368 ipf->readable->delete_kill= 0;
1370 ipf->readable_callback= 0;
1371 ipf->readable_callback_user= 0;
1373 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1376 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1377 feedfile_got_article,ipf, feedfile_problem,ipf);
1378 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1381 static void inputfile_tailing_stop(InputFile *ipf) {
1383 oop_rd_cancel(ipf->rd);
1384 oop_rd_delete(ipf->rd);
1386 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1390 /*========== interaction with innd - state machine ==========*/
1392 /* See official state diagram at top of file. We implement
1401 | TIMEOUT and no defer, no backlog
1402 |`--------------------------.
1404 | OPEN F SUCCEEDS | exit
1409 | [Normal] =========
1413 | | F IS SO BIG WE SHOULD FLUSH
1417 | | our handle onto F is now onto D
1420 | |<---------------------------------------------------.
1422 | | spawn inndcomm flush |
1430 | | INNDCOMM FLUSH FAILS ^
1431 | |`----------------------->----------. |
1433 | | NO SUCH SITE V |
1434 ^ |`--------------->----. =========== |
1440 | | \ | TIME TO RETRY |
1441 | | \ `----------------'
1445 | ============= ============
1446 | SEPARATED/ DROPPING/
1447 | old->fd>=0 old->fd>=0
1448 | [Separated] [Dropping]
1449 | main F idle main none
1450 | old D tail old D tail
1451 | ============= ============
1453 ^ | EOF ON D | EOF ON D
1455 | =============== ===============
1456 | SEPARATED/ DROPPING/
1457 | old->fd==-1 old->fd==-1
1458 | [Finishing] [Dropping]
1459 | main F tail main none
1460 | old D closed old D closed
1461 | =============== ===============
1463 | | ALL D PROCESSED | ALL D PROCESSED
1464 | V install defer as backlog V install defer as backlog
1465 ^ | close D | close D
1466 | | unlink D | unlink D
1475 static void statemc_init(void) {
1476 struct stat stab, stabf;
1479 path_ductlock= xasprintf("%s_duct.lock", feedfile);
1480 path_duct= xasprintf("%s_duct", feedfile);
1481 path_ductdefer= xasprintf("%s_duct.defer", feedfile);
1482 globpat_backlog= xasprintf("%s_backlog_*", feedfile);
1485 int lockfd= open(path_ductlock, O_CREAT|O_RDWR, 0600);
1486 if (lockfd<0) sysfatal("open lockfile %s", path_ductlock);
1489 memset(&fl,0,sizeof(fl));
1491 fl.l_whence= SEEK_SET;
1492 r= fcntl(lockfd, F_SETLK, &fl);
1494 if (errno==EACCES || errno==EAGAIN) {
1495 if (quiet_if_locked) exit(0);
1496 fatal("another duct holds the lockfile");
1498 sysdie("fcntl F_SETLK lockfile %s", path_ductlock);
1501 xfstat_isreg(lockfd, &stabf, "lockfile");
1502 xlstat_isreg(path_ductlock, &stab, &noent, "lockfile");
1504 if (!noent && samefile(&stab, &stabf))
1508 sysdie("could not close stale lockfile %s", path_ductlock);
1510 debug("startup: locked");
1512 search_backlog_file();
1514 xlstat_isreg(path_ductdefer, &stab, &noent, "defer file");
1516 debug("startup: ductdefer ENOENT");
1518 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1519 switch (stab.st_nlink==1) {
1521 open_defer(); /* so that we will later close it and rename it */
1524 if (unlink(path_defer))
1525 sysdie("could not unlink stale defer file link %s (presumably"
1526 " hardlink to backlog file)", path_defer);
1529 die("defer file %s has unexpected link count %d",
1530 path_defer, stab.st_nlink);
1534 InputFile *file_d= open_input_file(path_duct);
1537 struct stat stab_f, stab_d;
1539 xlstat_isreg(feedfile, &stab_f, &noent, "feed file");
1541 debug("startup: D exists, F ENOENT => Moved");
1545 debug("startup: F and D both exist");
1547 xfstat_isreg(file_d->fd, &stab_d, "ductfile");
1549 if (samefile(&stab_d, &stab_f)) {
1550 debug("startup: F==D => Hardlinked");
1551 r= unlink(path_duct);
1552 if (r) sysdie("unlink feed file %s during startup", feedfile);
1555 startup_set_input_file(file_d);
1556 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1558 debug("F!=D => Separated");
1559 SMS(SEPARATED, 0, "found both old and current feed files");
1560 startup_set_input_file(file_d);
1563 debug("startup: D ENOENT => Nothing");
1564 SMS(WAITING, open_wait_periods, "no feed file currently exists");
1568 static void statemc_poll(void) {
1569 if (sms==sm_WAITING) { statemc_waiting_poll(); return; }
1571 if (!sm_period_counter) return;
1572 sm_period_counter--;
1573 assert(sm_period_counter>=0);
1575 if (sm_period_counter) return;
1578 fatal("timed out waiting for innd to create feed file %s", feedfile);
1580 spawn_inndcomm_flush(void);
1587 static void statemc_waiting_poll(void) {
1588 InputFile *file_f= open_input_file(feedfile);
1589 if (!file_f) return;
1590 startup_set_input_file(file_d);
1591 SMS(NORMAL, 0, "found and opened feed file");
1594 static void startup_set_input_file(InputFile *f) {
1595 assert(!main_input_file);
1597 inputfile_tailing_start(f);
1600 static void *statemc_check_input_done(oop_source *lp,
1601 struct timeval now, void *ipf_v) {
1602 InputFile *ipf= ipf_v;
1605 if (ipf->inprogress) return; /* new article in the meantime */
1606 if (ipf->fd >= 0); return; /* not had EOF */
1608 if (ipf == backlog_input_file) {
1609 notice_processed(ipf,"backlog file",ipf->path);
1610 close_input_file(ipf);
1611 if (unlink(ipf->path)) {
1612 if (errno != ENOENT)
1613 sysdie("could not unlink processed backlog file %s", ipf->path);
1614 warn("backlog file %s vanished while we were reading it"
1615 " so we couldn't remove it (but it's done now, anyway)",
1618 backlog_input_file= 0;
1619 search_backlog_file();
1623 assert(ipf == old_input_file);
1624 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1626 notice_processed(ipf,"feed file",0);
1630 if (unlink(path_duct))
1631 sysdie("could not unlink old duct file %s", path_duct);
1633 if (sms==sm_DROPPING) {
1634 if (search_backlog_file()) {
1635 debug("feed dropped but still backlogs to process");
1638 notice("feed dropped and our work is complete");
1639 r= unlink(path_ductlock);
1640 if (r) sysdie("unlink lock file for old feed %s", path_ductlock);
1646 close_input_file(old_input_file);
1649 notice("flush complete");
1650 SMS(NORMAL, 0, "flush complete");
1653 static void statemc_setstate(StateMachineState newsms, int periods,
1654 const char *forlog, const char *why) {
1656 sm_period_counter= periods;
1658 info("%s[%d] %s",periods,forlog,why);
1660 info("%s %s",forlog,why);
1664 /*---------- defer and backlog files ----------*/
1666 static void open_defer(void) {
1671 defer= fopen(path_ductdefer, "a+");
1672 if (!defer) sysfatal("could not open defer file %s", path_ductdefer);
1674 /* truncate away any half-written records */
1676 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1678 if (stab.st_size > LONG_MAX)
1679 die("defer file %s size is far too large", path_ductdefer);
1684 long orgsize= stab.st_size;
1685 long truncto= stab.st_size;
1687 if (!truncto) break; /* was only (if anything) one half-truncated record */
1688 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1689 sysdie("seek in defer file %s while truncating partial", path_ductdefer);
1694 sysdie("failed read from defer file %s", path_ductdefer);
1696 die("defer file %s shrank while we were checking it!", path_ductdefer);
1702 if (stab.st_size != truncto) {
1703 warn("truncating half-record at end of defer file %s -"
1704 " shrinking by %ld bytes from %ld to %ld",
1705 path_ductdefer, orgsize - truncto, orgsize, truncto);
1708 sysfatal("could not flush defer file %s", path_ductdefer);
1709 if (ftruncate(fileno(defer), truncto))
1710 sysdie("could not truncate defer file %s", path_ductdefer);
1713 info("continuing existing defer file %s (%ld bytes)",
1714 path_ductdefer, orgsize);
1716 if (fseek(defer, truncto, SEEK_SET))
1717 sysdie("could not seek to new end of defer file %s", path_ductdefer);
1720 static void close_defer(void) {
1724 xfstat(fileno(defer), &stab, "defer file");
1726 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1729 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1730 (unsigned long)now.tv_sec,
1731 (unsigned long)stab.st_ino);
1732 if (link(path_defer, path_backlog))
1733 sysfatal("could not install defer file %s as backlog file %s",
1734 path_defer, backlog);
1735 if (unlink(path_defer))
1736 sysdie("could not unlink old defer link %s to backlog file %s",
1737 path_defer, backlog);
1739 if (backlog_nextscan_periods < 0 ||
1740 backlog_nextscan_periods > backlog_retry_minperiods + 1)
1741 backlog_nextscan_periods= backlog_retry_minperiods + 1;
1744 static void poll_backlog_file(void) {
1745 if (backlog_nextscan_periods < 0) return;
1746 if (backlog_nextscan_periods-- > 0) return;
1747 search_backlog_file();
1750 static int search_backlog_file(void) {
1751 /* returns non-0 iff there are any backlog files */
1756 const char *oldest_path=0;
1757 time_t oldest_mtime, now;
1759 if (backlog_input_file) return 3;
1763 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
1767 sysdie("failed to expand backlog pattern %s", globpat_backlog);
1769 die("out of memory expanding backlog pattern %s", globpat_backlog);
1771 for (i=0; i<gl.gl_pathc; i++) {
1772 const char *path= gl.gl_pathv[i];
1773 r= stat(path, &stab);
1775 syswarn("failed to stat backlog file %s", path);
1778 if (!S_ISREG(stab.st_mode)) {
1779 warn("backlog file %s is not a plain file (or link to one)", path);
1782 if (!oldest_path || stab.st_mtime < oldest_mtime) {
1784 oldest_mtime= stab.st_mtime;
1787 case GLOB_NOMATCH: /* fall through */
1790 sysdie("glob expansion of backlog pattern %s gave unexpected"
1791 " nonzero (error?) return value %d", globpat_backlog, r);
1797 debug("backlog scan: none");
1798 backlog_nextscan_periods= backlog_spontaneous_rescan_periods;
1802 now= time(); if (now==-1) sysdie("time(2) failed");
1803 double age= difftime(now, oldest_mtime);
1804 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
1806 if (age_deficiency <= 0) {
1807 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
1808 age, age_deficiency, oldest_path);
1810 backlog_input_file= open_input_file();
1811 if (!backlog_input_file) {
1812 warn("backlog file %s vanished as we opened it", backlog_input_file);
1815 inputfile_tailing_start(backlog_input_file);
1816 backlog_nextscan_periods= -1;
1820 backlog_nextscan_periods= age_deficiency / PERIOD_SECONDS;
1822 if (backlog_spontaneous_rescan_periods >= 0 &&
1823 backlog_nextscan_periods > backlog_spontaneous_rescan_periods)
1824 backlog_nextscan_periods= backlog_spontaneous_rescan_periods;
1826 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
1827 age, age_deficiency, backlog_nextscan_periods, oldest_path);
1831 /*========== flushing the feed ==========*/
1833 static pid_t inndcomm_child;
1835 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1836 assert(inndcomm_child);
1837 int status= xwaitpid(&inndcomm_child, "inndcomm");
1838 loop->cancel_fd(fd);
1841 assert(!old_input_file);
1843 if (WIFEXITED(status)) {
1844 switch (WEXITSTATUS(status)) {
1846 case INNDCOMMCHILD_ESTATUS_FAIL:
1849 case INNDCOMMCHILD_ESTATUS_NONESUCH:
1850 warn("feed has been dropped by innd, finishing up");
1851 old_input_file= main_input_file;
1853 SMS(DROPPING, 0, "dropped by innd");
1854 return OOP_CONTINUE;
1857 old_input_file= main_input_file;
1858 main_input_file= open_input_file(feedfile);
1859 if (!main_input_file)
1860 die("flush succeeded but feedfile %s does not exist!", feedfile);
1861 SMS(SEPARATED, 0, "feed file missing");
1862 return OOP_CONTINUE;
1865 goto unexpected_exitstatus;
1868 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1869 warn("flush timed out trying to talk to innd");
1872 unexpected_exitstatus:
1873 report_child_status("inndcomm child", status);
1877 SMS(FLUSHFAIL, flushfail_retry_periods, "flush failed, will retry");
1880 static void inndcommfail(const char *what) {
1881 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1882 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1885 void spawn_inndcomm_flush(void) {
1888 assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1889 assert(!inndcomm_child);
1891 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1893 inndcomm_child= xfork();
1895 if (!inndcomm_child) {
1896 static char flushargv[2]= { sitename, 0 };
1901 alarm(inndcomm_flush_timeout);
1902 r= ICCopen(); if (r) inndcommfail("connect");
1903 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
1904 if (!r) exit(0); /* yay! */
1906 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1907 syswarn("innd ctlinnd flush failed: innd said %s", reply);
1908 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1912 int sentinel_fd= pipefds[0];
1913 on_fd_read_except(sentinel_fd, inndcomm_event);
1915 SMS(FLUSHING, 0, "flush is in progress");
1918 /*========== main program ==========*/
1920 static void postfork_inputfile(InputFile *ipf) {
1922 assert(ipf->fd >= 0);
1927 static void postfork_conns(Connection *conn) {
1934 static void postfork_stdio(FILE *f) {
1935 /* we have no stdio streams that are buffered long-term */
1939 static void postfork(const char *what) {
1940 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1941 sysdie("%s child: failed to reset SIGPIPE");
1943 postfork_inputfile(main_input_file);
1944 postfork_inputfile(old_input_file);
1945 postfork_conns(idle.head);
1946 postfork_conns(working.head);
1947 postfork_conns(full.head);
1948 postfork_stdio(defer);
1951 #define EVERY(what, interval, body) \
1952 static const struct timeval what##_timeout = { 5, 0 }; \
1953 static void what##_schedule(void); \
1954 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1956 what##_schedule(); \
1958 static void what##_schedule(void) { \
1959 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
1962 EVERY(filepoll, {5,0}, {
1963 if (main_input_file && main_input_file->readable_callback)
1964 filemon_callback(main_input_file);
1967 EVERY(period, {PERIOD_SECONDS,0}, {
1968 if (connect_delay) connect_delay--;
1969 poll_backlog_file();
1970 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
1972 check_master_queue();
1976 /*========== option parsing ==========*/
1979 of_seconds= 001000u;
1980 of_boolean= 002000u;
1983 typedef struct Option Option;
1984 typedef void OptionParser(const Option*, const char *val);
1994 void op_integer(const Option *o, const char *val) {
1997 unsigned long ul= strtoul(val,&ep,10);
1998 if (*ep || ep==val || errno || ul>INT_MAX)
1999 badusage("bad integer value for %s",o->long);
2000 int *store= o->store;
2004 void op_double(const Option *o, const char *val) {
2005 int *store= o->store;
2008 *store= strtod(val, &ep);
2009 if (*ep || ep==val || errno)
2010 badusage("bad floating point value for %s",o->long);
2013 void op_string(const Option *o, const char *val) {
2014 char **store= o->store;
2019 void op_seconds(const Option *o, const char *val) {
2020 int *store= o->store;
2023 double v= strtod(val,&ep);
2024 if (ep==val) badusage("bad time/duration value for %s",o->long);
2026 if (!*ep || !strcmp(ep,"s")) unit= 1;
2027 else if (!strcmp(ep,"m")) unit= 60;
2028 else if (!strcmp(ep,"h")) unit= 3600;
2029 else if (!strcmp(ep,"d")) unit= 86400;
2030 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2034 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2038 void op_periods_rndup(const Option *o, const char *val) {
2039 int *store= o->store;
2041 *store += PERIOD_SECONDS-1;
2042 *store /= PERIOD_SECONDS;
2045 void op_periods_booltrue(const Option *o, const char *val) {
2046 int *store= o->store;
2049 void op_periods_boolfalse(const Option *o, const char *val) {
2050 int *store= o->store;
2054 static const Option options[]= {
2055 { 0, "max-connections", &max_connections op_integer },
2056 { 0, "streaming", &try_stream, op_booltrue, 1 },
2057 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2058 {'h',"host", &remote_host, op_string },
2059 {'P',"port", &port op_integer },
2060 { 0, "inndconf", &inndconffile, op_string },
2061 {'f',"feedfile", &feedfile, op_string },
2062 {'q',"quiet-multiple", &quiet_if_locked, op_booltrue, 1 },
2063 { 0, "no-quiet-multiple", &quiet_if_locked, op_boolfalse, 1 },
2064 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2065 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2067 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2068 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2070 { 0, "max-queue-size", &max_queue_per_conn op_integer },
2071 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2072 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2073 { 0, "feedfile-open-timeout", &open_wait_periods, op_periods_rndup },
2074 { 0, "connection-timeout", &connection_timeout, op_seconds },
2075 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2078 int main(int argc, char **argv) {
2084 if (*arg != '-') break;
2085 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2087 while ((a= *++arg)) {
2091 char *equals= strchr(arg,'=');
2092 int len= equals ? (equals - arg) : strlen(arg);
2093 for (o=options; o->long; o++)
2094 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2096 badusage("unknown long option --%s",arg);
2099 if (equals) badusage("option --%s does not take a value",o->long);
2101 } else if (equals) {
2105 if (!arg) badusage("option --%s needs a value",o->long);
2108 break; /* eaten the whole argument now */
2110 for (o=options; o->long; o++)
2113 badusage("unknown short option -%c",a);
2120 if (!arg) badusage("option -%c needs a value",o->short);
2123 break; /* eaten the whole argument now */
2128 if (!arg) badusage("need site name argument");
2129 if (*++argv) badusage("too many non-option arguments");
2132 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2133 badusage("nocheck threshold percentage must be between 0..100");
2134 nocheck_thresh= nocheck_thresh_pct * 0.01;
2136 if (nocheck_decay_articles < 0.1)
2137 badusage("nocheck decay articles must be at least 0.1");
2138 nocheck_decay= 1 - 1/nocheck_decay_articles;
2140 innconf_read(inndconffile);
2143 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2144 else if (!feedfile[0])
2145 badusage("feed filename must be nonempty");
2146 else if (feedfile[strlen(feedfile)-1]=='/')
2147 feedfile= xasprintf("%s%s",feedfile,sitename);
2149 const char *feedfile_forbidden= "?*[";
2151 while ((c= *feedfile_forbidden++))
2152 if (strchr(feedfile, c))
2153 badusage("feed filename may not contain glob metacharacter %c",c);
2155 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2156 sysdie("could not ignore SIGPIPE");
2158 if (become_daemon) {
2159 for (i=3; i<255; i++)
2160 /* do this now before we open syslog, etc. */
2162 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2164 int null= open("/dev/null",O_RDWR);
2165 if (null<0) sysdie("failed to open /dev/null");
2171 pid_t child1= xfork("daemonise first fork");
2172 if (child1) _exit(0);
2174 pid_t sid= setsid();
2175 if (sid != child1) sysdie("setsid failed");
2177 pid_t child2= xfork("daemonise second fork");
2178 if (child2) _exit(0);
2183 if (!filemon_init()) {
2184 warn("no file monitoring available, polling");
2185 filepoll_schedule();