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.
68 | | <----------------<---------------------------------'|
74 | F: innd writing, duct reading |
77 | | duct decides time to flush |
78 | | duct makes hardlink |
80 | V <------------------------'|
82 | F == D: innd writing, duct reading both exist |
85 | | <-----------<-------------<--'|
89 | V <---------------------. |
92 | D: innd writing, duct reading; or ENOENT | |
94 | | duct requests flush of feed | |
95 | | (others can too, harmlessly) | |
99 | D: innd flushing, duct; or ENOENT | |
101 | | inndcomm flush fails | |
102 | |`-------------------------->------------------' |
104 | | inndcomm reports no such site |
105 | |`---------------------------------------------------- | -.
107 | | innd finishes writing D, creates F | |
108 | | inndcomm reports flush successful | |
111 | Separated <----------------' |
112 | F: innd writing F!=D /
113 | D: duct reading; or ENOENT both exist /
115 | | duct gets to the end of D /
116 | | duct opens F too /
119 | F: innd writing, duct reading |
120 | D: duct finishing V
122 | | duct finishes processing D F: ENOENT
123 | V duct unlinks D D: duct reading
125 `--<--' | duct finishes
135 "duct reading" means innduct is reading the file but also
136 overwriting processed tokens.
143 /*----- general definitions, probably best not changed -----*/
145 #define PERIOD_SECONDS 60
147 #define CONNCHILD_ESTATUS_STREAM 4
148 #define CONNCHILD_ESTATUS_NOSTREAM 5
150 #define INNDCOMMCHILD_ESTATUS_FAIL 6
151 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
154 /*----- configuration options -----*/
156 static char *sitename, *feedfile;
157 static int max_connections=10, max_queue_per_conn=200;
158 static int connection_setup_timeout=200, port=119, try_stream=1;
159 static int inndcomm_flush_timeout=100, quiet_if_locked=0;
160 static const char *remote_host;
161 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
162 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
163 static const char *inndconffile;
165 static double accept_proportion;
166 static double nocheck_thresh_pct= 95.0;
167 static double nocheck_thresh; /* computed in main from _pct */
168 static double nocheck_decay_articles= 100; /* converted to _decay */
169 static double nocheck_decay; /* computed in main from _articles */
170 static int nocheck, nocheck_reported;
173 /*----- doubly linked lists -----*/
175 #define ISNODE(T) T *next, *back;
176 #define LIST(T) struct { T *head, *tail, *tailpred; int count; }
178 #define NODE(n) ((struct node*)&(n)->head)
180 #define LIST_ADDHEAD(l,n) \
181 (list_addhead((struct list*)&(l), NODE((n))), (void)(l).count++)
182 #define LIST_ADDTAIL(l,n) \
183 (list_addtail((struct list*)&(l), NODE((n))), (void)(l).count++)
185 #define LIST_REMHEAD(l) \
186 ((l).count ? ((l).count--, (void*)list_remhead((struct list*)&(l))) : 0)
187 #define LIST_REMTAIL(l) \
188 ((l).count ? ((l).count--, (void*)list_remtail((struct list*)&(l))) : 0)
189 #define LIST_REMOVE(l,n) \
190 (list_remove(NODE((n))), (void)(l).count--)
191 #define LIST_INSERT(l,n,pred) \
192 (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
195 /*----- statistics -----*/
197 #define RESULT_COUNTS \
206 #define RC_INDEX(x) RCI_##x
212 int articles[2 /* checked */][RCI_max];
216 /*----- transmission buffers -----*/
221 xk_Malloc, xk_Const, xk_Artdata;
233 /*----- core operational data structure types -----*/
237 int checked, sentbody;
245 typedef struct InputFile {
246 /* This is an instance of struct oop_readable */
247 struct oop_readable readable; /* first */
248 oop_readable_call *readable_callback;
249 void *readable_callback_user;
252 struct Filemon_Perfile *filemon;
255 long inprogress; /* no. of articles read but not processed */
262 #define SMS_LIST(X) \
271 #define SMS_DEF_ENUM(s) sm_##s,
272 SMS_LIST(SMS_DEF_ENUM)
275 static const char *sms_names[]= {
276 #define SMS_DEF_NAME(s) #s ,
277 SMS_LIST(SMS_DEF_NAME)
283 int fd, max_queue, stream;
284 LIST(Article) queue; /* not yet told peer, or CHECK said send it */
285 LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
286 struct iovec xmit[CONNIOVS];
287 XmitDetails xmitd[CONNIOVS];
292 /*----- operational variables -----*/
295 static LIST(Conn) idle, working, full;
296 static LIST(Article) *queue;
298 static char *path_lock, *path_flushing, *path_defer;
300 #define SMS(newstate, periods, why) \
301 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
303 static StateMachineState sms;
305 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
306 static int sm_period_counter;
309 /*----- function predeclarations -----*/
311 static void conn_check_work(Conn *conn);
313 static int filemon_init(void);
314 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
315 static void filemon_callback(void);
317 static void statemc_setstate(StateMachineState newsms, int periods,
318 const char *forlog, const char *why);
320 /*========== utility functions etc. ==========*/
322 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
324 static pid_t xfork(const char *what) {
328 if (child==-1) sysdie("cannot fork for %s",what);
329 if (!child) postfork(what);
333 static void on_fd_read_except(int fd, oop_call_fd callback) {
334 loop->on_fd(loop, fd, OOP_READ, callback, 0);
335 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
337 static void cancel_fd_read_except(int fd) {
338 loop->cancel_fd(loop, fd, OOP_READ);
339 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
342 static void report_child_status(const char *what, int status) {
343 if (WIFEXITED(status)) {
344 int es= WEXITSTATUS(status);
346 warn("%s: child died with error exit status %d",es);
347 } else if (WIFSIGNALED(status)) {
348 int sig= WTERMSIG(status);
349 const char *sigstr= strsignal(sig);
350 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
352 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
354 warn("%s: child died due to unknown fatal signal %d%s",
355 what, sig, coredump);
357 warn("%s: child died with unknown wait status %d", status);
361 static int xwaitpid(pid_t *pid, const char *what) {
364 r= kill(*pid, SIGKILL);
365 if (r) sysdie("cannot kill %s child", what);
367 pid_t got= waitpid(*pid, &status, WNOHANG);
368 if (got==-1) sysdie("cannot reap %s child", what);
375 static void xunlink(const char *path, const char *what) {
377 if (r) sysdie("can't unlink %s %s", path, what);
380 static void check_isreg(const struct stat *stab, const char *path,
382 if (!S_ISREG(stab->st_mode))
383 die("%s %s not a plain file (mode 0%lo)",
384 what, path, (unsigned long)stab->st_mode);
387 static void xfstat(int fd, struct stat *stab_r, const char *what) {
388 int r= fstab(path, stab);
389 if (r) sysdie("could not fstat %s %s", what, path);
392 static void xfstat_isreg(int fd, struct stat *stab_r, const char *what) {
393 xfstat(fd, stab_r, what);
394 check_isreg(stab, path, what);
397 static void xlstat_isreg(const char *path, struct stat *stab,
398 int *enoent_r /* 0 means ENOENT is fatal */
400 int r= lstat(path, stab);
402 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
403 sysdie("could not lstat %s %s", what, path);
405 if (enoent_r) *enoent_r= 0;
406 check_isreg(stab, path, what);
409 static int samefile(const struct stat *a, const struct stat *b) {
410 assert(S_ISREG(a->st_mode));
411 assert(S_ISREG(b->st_mode));
412 return (a->st_ino == b->st_ino &&
413 a->st_dev == b->st_dev);
416 /*========== logging ==========*/
418 static void logcore(int sysloglevel, const char *fmt, ...)
419 __attribute__((printf,2,3))
420 static void logcore(int sysloglevel, const char *fmt, ...) {
424 vsyslog(sysloglevel,fmt,al);
426 vfprintf(stderr,fmt,al);
431 static void logv(int sysloglevel, const char *pfx, int errnoval,
432 int exitstatus, const char *fmt, va_list al)
433 __attribute__((printf,4,0))
434 static void logv(int sysloglevel, const char *pfx, int errnoval,
435 int exitstatus, const char *fmt, va_list al) {
437 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
438 msgbuf[sizeof(msgbuf)-1]= 0;
440 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
441 sysloglevel= LOG_ERR; /* run by wrong user, probably */
443 logcore(sysloglevel, "<%s>%s: %s%s%s",
444 sitename, pfx, msgbuf,
445 errnoval>=0 ? ": " : "",
446 errnoval>=0 ? strerror(errnoval) : "");
449 #define logwrap(fn, pfx, sysloglevel, errno, estatus) \
450 static void fn(const char *fmt, ...) \
451 __attribute__((printf,1,2)); \
452 static void fn(const char *fmt, ...) { \
455 logv(sysloglevel, pfx, errno, estatus, fmt, al); \
458 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
459 logwrap(die, " critical", LOG_CRIT, -1, 16);
461 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
462 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
464 logwrap(syswarn, " warning", LOG_WARN, errno, 0);
465 logwrap(warn, " warning", LOG_WARN, -1, 0);
467 logwrap(notice, "", LOG_NOTICE, -1, 0);
468 logwrap(info, " info", LOG_INFO, -1, 0);
469 logwrap(debug, " debug", LOG_DEBUG, -1, 0);
472 /*========== making new connections ==========*/
474 static int connecting_sockets[2]= {-1,-1};
475 static pid_t connecting_child;
477 static void connect_attempt_discard(void) {
478 if (connecting_sockets[0])
479 cancel_fd(connecting_sockets[0]);
481 perhaps_close(&connecting_sockets[0]);
482 perhaps_close(&connecting_sockets[1]);
484 if (connecting_child) {
485 int status= xwaitpid(&connecting_child, "connect");
487 if (!(WIFEXITED(status) ||
488 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
489 report_child_status("connect", status);
493 #define PREP_DECL_MSG_CMSG(msg) \
495 memset(&msg,0,sizeof(msg)); \
496 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
497 msg.msg_control= msg##cbuf; \
498 msg.msg_controllen= sizeof(msg##cbuf);
500 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
503 conn= xmalloc(sizeof(*conn));
504 memset(conn,0,sizeof(*conn));
507 struct cmsghdr *h= 0;
508 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
509 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
512 pid_t got= waitpid(connecting_child, &status, WNOHANG);
514 assert(got==connecting_child);
516 if (WIFEXITED(status) &&
517 (WEXITSTATUS(status) != 0
518 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
519 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
520 /* child already reported the problem */
521 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
522 warn("connect: connection attempt timed out");
523 } else if (!WIFEXITED(status)) {
524 report_child_status("connect", status);
525 /* that's probably the root cause then */
528 /* child is still running apparently, report the socket problem */
530 syswarn("connect: read from child socket failed");
531 else if (e == OOP_EXCEPTIONN)
532 warn("connect: unexpected exception on child socket");
534 warn("connect: unexpected EOF on child socket");
539 #define CHK(field, val) \
540 if (h->cmsg_##field != val) { \
541 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
544 CHK(level, SOL_SOCKET);
545 CHK(type, SCM_RIGHTS);
546 CHK(len, CMSG_LEN(sizeof(conn-b>fd)));
549 if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
551 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
553 pid_t got= waitpid(connecting_child, &status, 0);
554 if (got==-1) sysdie("connect: real wait for child");
555 assert(got == connecting_child);
558 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
559 int es= WEXITSTATUS(status);
561 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
562 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
564 fatal("connect: child gave unexpected exit status %d", es);
570 LIST_ADDHEAD(idle, conn);
571 notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
572 connect_attempt_discard();
573 check_master_queue();
578 perhaps_close(&conn->fd);
581 connect_attempt_discard();
584 static void connect_start() {
585 assert(!connecting_sockets[0]);
586 assert(!connecting_sockets[1]);
587 assert(!connecting_child);
589 notice("starting connection attempt");
591 r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
592 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
594 connecting_child= xfork("connection");
596 if (!connecting_child) {
597 FILE *cn_from, *cn_to;
598 char buf[NNTP_STRLEN+100];
599 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
601 r= close(connecting_sockets[0]);
602 if (r) sysdie("connect: close parent socket in child");
604 alarm(connection_setup_timeout);
605 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
607 sanitise_inplace(buf);
608 fatal("connect: rejected: %s", buf);
610 sysfatal("connect: connection attempt failed");
613 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
614 sysfatal("connect: authentication failed");
616 if (fputs("MODE STREAM\r\n", cn_to) ||
618 sysfatal("connect: could not send MODE STREAM");
619 buf[sizeof(buf)-1]= 0;
620 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
622 sysfatal("connect: could not read response to MODE STREAM");
624 fatal("connect: connection close in response to MODE STREAM");
629 sanitise_inplace(buf);
630 fatal("connect: response to MODE STREAM is too long: %.100s...",
633 l--; if (l>0 && buf[1-]=='\r') l--;
636 int rcode= strtoul(buf,&ep,10);
638 sanitise_inplace(buf);
639 fatal("connect: bad response to MODE STREAM: %.50s", buf);
643 exitstatus= CONNCHILD_ESTATUS_STREAM;
649 sanitise_inplace(buf);
650 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
655 int fd= fileno(cn_from);
657 PREP_DECL_MSG_CMSG(msg);
658 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
659 cmsg->cmsg_level= SOL_SOCKET;
660 cmsg->cmsg_type= SCM_RIGHTS;
661 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
662 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
664 msg.msg_controllen= cmsg->cmsg_len;
665 r= sendmsg(connecting_sockets[1], &msg, 0);
666 if (r) sysdie("sendmsg failed for new connection");
671 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
672 if (r) sysdie("connect: close child socket in parent");
674 on_fd_read_except(connecting_sockets[0], connchild_event);
678 connect_attempt_discard();
682 /*========== overall control of article flow ==========*/
684 static void check_master_queue(void) {
688 Conn *last_assigned=0;
691 conn_assign_one_article(&working, &last_assigned);
692 } else if (idle.head) {
693 conn_assign_one_article(&idle, &last_assigned);
694 } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
695 !connecting_child && !connect_delay) {
696 connect_delay= reconnect_delay_periods;
702 conn_check_work(last_assigned);
705 static void conn_assign_one_article(LIST(Conn) *connlist,
706 Conn **last_assigned) {
707 Conn *conn= connlist->head;
709 LIST_REMOVE(*connlist, conn);
710 Article *art= LIST_REMHEAD(queue);
711 LIST_ADDTAIL(conn->queue, art);
712 LIST_ADD(*conn_determine_right_list(conn), conn);
714 /* This slightly odd arrangement is so that we call conn_check_work
715 * once after filling the queue for a new connection in
716 * check_master_queue, rather than for each article. */
717 if (conn != *last_assigned && *last_assigned)
718 conn_check_work(*last_assigned);
719 *last_assigned= conn;
722 static int conn_total_queued_articles(Conn *conn) {
723 return conn->sent.count + conn->queue.count;
726 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
727 int inqueue= conn_total_queued_articles(conn);
728 assert(inqueue <= max_queue);
729 if (inqueue == 0) return &idle;
730 if (inqueue == conn->max_queue) return &full;
734 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
739 static void conn_check_work(Conn *conn) {
742 conn_make_some_xmits(conn);
744 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
748 void *rp= conn_write_some_xmits(conn);
749 if (rp==OOP_CONTINUE) {
750 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
752 } else if (rp==OOP_HALT) {
755 /* transmitted everything */
763 /*========== article transmission ==========*/
765 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
766 XmitKind kind) { /* caller must then fill in details */
767 struct iovec *v= &conn->xmit[conn->xmitu];
768 XmitDetails *d= &conn->xmitd[conn->xmitu++];
775 static void xmit_noalloc(Conn *conn, const char *data, int len) {
776 xmit_core(conn,data,len, xk_Const);
778 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
780 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
781 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
785 static void xmit_free(XmitDetails *d) {
787 case xk_Malloc: free(d->info.malloc_tofree); break;
788 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
789 case xk_Const: break;
794 static void *conn_write_some_xmits(Conn *conn) {
796 * 0: nothing more to write, no need to call us again
797 * OOP_CONTINUE: more to write but fd not writeable
798 * OOP_HALT: disaster, have destroyed conn
801 int count= conn->xmitu;
802 if (!count) return 0;
804 if (count > IOV_MAX) count= IOV_MAX;
805 ssize_t rs= writev(conn->fd, conn->xmit, count);
807 if (errno == EAGAIN) return OOP_CONTINUE;
808 connfail(conn, "write failed: %s", strerror(errno));
813 for (done=0; rs && done<xmitu; done++) {
814 struct iovec *vp= &conn->xmit[done];
815 XmitDetails *dp= &conn->xmitd[done];
816 if (rs > vp->iov_len) {
824 int newu= conn->xmitu - done;
825 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
826 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
831 static void conn_make_some_xmits(Conn *conn) {
833 if (conn->xmitu+5 > CONNIOVS)
836 Article *art= LIST_REMHEAD(queue);
839 if (art->checked || (conn->stream && nocheck)) {
840 /* actually send it */
842 ARTHANDLE *artdata= SMretrieve();
846 XMIT_LITERAL("TAKETHIS ");
847 xmit_noalloc(conn, art->mid, art->midlen);
848 XMIT_LITERAL("\r\n");
849 xmit_artbody(conn, artdata);
852 /* we got 235 from IHAVE */
854 xmit_artbody(conn, artdata);
856 XMIT_LITERAL(".\r\n");
861 LIST_ADDTAIL(conn->sent, art);
863 art->ipf->counts[art->checked].sent++;
869 XMIT_LITERAL("IHAVE ");
871 XMIT_LITERAL("CHECK ");
872 xmit_noalloc(art->mid, art->midlen);
873 XMIT_LITERAL("\r\n");
875 LIST_ADDTAIL(conn->sent, art);
876 art->ipf->counts[art->checked].offered++;
882 /*========== handling responses from peer ==========*/
884 static const oop_rd_style peer_rd_style= {
885 OOP_RD_DELIM_STRIP, '\n',
887 OOP_RD_SHORTREC_FORBID
890 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
891 const char *errmsg, int errnoval,
892 const char *data, size_t recsz, void *conn_v) {
894 connfail(conn, "error receiving from peer: %s", errmsg);
898 static Article *article_reply_check(Connection *conn, const char *response,
899 int code_indicates_streaming,
900 const char *sanitised_response) {
901 Article *art= LIST_REMHEAD(conn->sent);
905 "peer gave unexpected response when no commands outstanding: %s",
910 if (code_indicates_streaming) {
911 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
913 connfail("peer gave streaming response code "
914 " to IHAVE or subsequent body: %s", sanitised_response);
917 const char *got_mid= response+4;
918 int got_midlen= strcspn(got_mid, " \n\r");
919 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
920 connfail("peer gave streaming response with syntactically invalid"
921 " messageid: %s", sanitised_response);
924 if (got_midlen != art->midlen ||
925 memcmp(got_mid, art->messageid, got_midlen)) {
926 connfail("peer gave streaming response code to wrong article -"
927 " probable synchronisation problem; we offered: %s;"
929 art->messageid, sanitised_response);
934 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
943 static void update_nocheck(int accepted) {
944 accept_proportion *= accept_decay;
945 accept_proportion += accepted;
946 int new_nocheck= accept_proportion >= nocheck_thresh;
947 if (new_nocheck && !nocheck_reported) {
948 notice("entering nocheck mode for the first time");
950 } else if (new_nocheck != nockech) {
951 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
953 nocheck= new_nocheck;
956 static void article_done(Connection *conn, Article *art, int whichcount) {
958 art->ipf->counts.articles[art->checked][whichcount]++;
959 if (whichcount == RC_accepted) update_nocheck(1);
960 else if (whichcount == RC_unwanted) update_nocheck(0);
962 InputFile *ipf= art->ipf;
963 while (art->blanklen) {
964 static const char spaces[]=
969 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
970 int r= pwrite(ipf->fd, spaces, w, art->offset);
972 if (errno==EINTR) continue;
973 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
974 art->messageid, art->blanklen, art->offset, ipf->path);
976 assert(r>=0 && r<=w);
982 assert(ipf->inprogress >= 0);
984 if (!ipf->inprogress)
985 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, ipf);
990 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
991 const char *errmsg, int errnoval,
992 const char *data, size_t recsz, void *conn_v) {
995 if (ev == OOP_RD_EOF) {
996 connfail(conn, "unexpected EOF from peer");
999 assert(ev == OOP_RD_OK);
1002 unsigned long code= strtoul(data, &ep, 10);
1003 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1005 const char *p= data;
1009 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
1011 if (!c) { *q++= '\''; break; }
1012 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
1013 sprintf(q,"\\x%02x",c);
1016 connfail(conn, "badly formatted response from peer: %s", sanibuf);
1017 return OOP_CONTINUE;
1020 if (conn->quitting) {
1022 connfail(conn, "peer gave failure response to QUIT: %s", sani);
1023 return OOP_CONTINUE;
1031 #define GET_ARTICLE \
1032 art= article_reply_check(conn, data, code_streaming, sani); \
1033 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1035 #define ARTICLE_DEALTWITH(streaming,how) \
1036 code_streaming= (streaming) \
1038 article_done(conn, art, RC_##how); break;
1040 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1042 int code_streaming= 0;
1046 case 400: PEERBADMSG("peer stopped accepting articles");
1047 case 503: PEERBADMSG("peer timed us out");
1048 default: PEERBADMSG("peer sent unexpected message");
1050 case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
1051 case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
1053 case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
1054 case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
1056 case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
1057 case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
1059 case 238: /* CHECK says send it */
1061 case 335: /* IHAVE says send it */
1063 count_checkedwanted++;
1064 LIST_ADDTAIL(conn->queue);
1066 connfail("peer gave %d response to article body: %s",code, sani);
1067 return OOP_CONTINUE;
1072 case 431: /* CHECK or TAKETHIS says try later */
1074 case 436: /* IHAVE says try later */
1077 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1079 sysfatal("write to defer file %s",path_defer);
1080 article_done(conn, art, RC_deferred);
1085 check_check_work(conn);
1086 return OOP_CONTINUE;
1090 /*========== monitoring of input files ==========*/
1092 static void feedfile_eof(InputFile *ipf) {
1093 assert(ipf != main_input_file); /* promised by tailing_try_read */
1095 inputfile_tailing_stop(ipf);
1097 if (ipf == backlog_input_file) {
1098 assert(ipf->fd >= 0);
1099 if (close(ipf->fd)) sysdie("could not close backlog file %s", ipf->path);
1104 assert(ipf == flushing_input_file);
1106 inputfile_tailing_stop(ipf);
1107 assert(ipf->fd >= 0);
1108 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1111 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1113 if (main_input_file)
1114 inputfile_tailing_start(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);
1150 /*---------- dealing with articles read in the input file ----------*/
1152 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1153 oop_rd_event ev, const char *errmsg,
1155 const char *data, size_t recsz,
1157 InputFile *ipf= ipf_v;
1159 char tokentextbuf[sizeof(TOKEN)*2+3];
1161 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1163 if (data[0] && data[0]!=' ') {
1164 char *space= strchr(data,' ');
1165 int tokenlen= space-data;
1166 int midlen= (int)recsz-tokenlen-1;
1167 if (midlen < 0) goto bad_data;
1169 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1170 memcpy(tokentextbuf, data, tokenlen);
1171 tokentextbuf[tokenlen]= 0;
1172 if (!IsToken(tokentextbuf)) goto bad_data;
1174 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1175 art->offset= ipf->offset;
1176 art->blanklen= recsz;
1177 art->midlen= midlen;
1178 art->checked= art->sentbody= 0;
1179 art->ipf= ipf; ipf->inprogress++;
1180 art->token= TextToToken(tokentextbuf);
1181 strcpy(art->messageid, space+1);
1182 LIST_ADDTAIL(queue, art);
1184 ipf->offset += recsz + 1;
1186 if (sms==sm_NORMAL && ipf==main_input_file &&
1187 (ipf->offset >= flush_threshold || !until_spontaneous_flush) {
1189 notice("starting flush (%lu >= %lu)",
1190 (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1192 int r= link(feedfile, duct_path);
1193 if (r) sysdie("link feedfile %s to flushing file %s", feedfile, dut_path);
1196 xunlink(feedfile, "old feedfile link");
1199 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1202 check_master_queue();
1206 /*========== tailing input file ==========*/
1208 static void filemon_start(InputFile *ipf) {
1209 assert(!ipf->filemon);
1211 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1212 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1213 filemon_method_startfile(ipf, ipf->filemon);
1216 static void filemon_stop(InputFile *ipf) {
1217 if (!ipf->filemon) return;
1218 filemon_method_stopfile(ipf, ipf->filemon);
1223 static void filemon_callback(InputFile *ipf) {
1224 ipf->readable_callback(ipf->readable_callback_user);
1227 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1229 InputFile *ipf= user;
1230 return ipf->readable_callback(ipf->readable_callback_user);
1233 static void on_cancel(struct oop_readable *rable) {
1234 InputFile *ipf= (void*)rable;
1236 if (ipf->filemon) filemon_stopfile(ipf);
1237 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1238 ipf->readable_callback= 0;
1241 static int tailing_on_readable(struct oop_readable *rable,
1242 oop_readable_call *cb, void *user) {
1243 InputFile *ipf= (void*)rable;
1245 tailing_on_cancel(rable);
1246 ipf->readable_callback= cb;
1247 ipf->readable_callback_user= user;
1248 filemon_startfile(ipf);
1250 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1254 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1256 InputFile *ipf= (void*)rable;
1258 ssize_t r= read(ipf->fd, buffer, length);
1260 if (errno==EINTR) continue;
1264 if (ipf==main_input_file) {
1267 } else if (ipf==flushing_input_file) {
1269 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1270 } else if (ipf==backlog_input_file) {
1280 /*---------- filemon implemented with inotify ----------*/
1282 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1283 #define HAVE_FILEMON
1285 #include <linux/inotify.h>
1287 static int filemon_inotify_fd;
1288 static int filemon_inotify_wdmax;
1289 static InputFile **filemon_inotify_wd2ipf;
1291 typedef struct Filemon_Perfile {
1293 } Filemon_Inotify_Perfile;
1295 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1296 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1297 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1299 if (wd >= filemon_inotify_wdmax) {
1301 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1302 sizeof(*filemon_inotify_wd2ipf) * newmax);
1303 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1304 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1305 filemon_inotify_wdmax= newmax;
1308 assert(!filemon_inotify_wd2ipf[wd]);
1309 filemon_inotify_wd2ipf[wd]= ipf;
1311 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1312 ipf, wd, filemon_inotify_wdmax);
1317 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1319 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1320 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1321 if (r) sysdie("inotify_rm_watch");
1322 filemon_inotify_wd2ipf[wd]= 0;
1325 static void *filemon_inotify_readable(oop_source *lp, int fd,
1326 oop_event e, void *u) {
1327 struct inotify_event iev;
1329 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1331 if (errno==EAGAIN) break;
1332 sysdie("read from inotify master");
1333 } else if (r==sizeof(iev)) {
1334 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1336 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1338 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1339 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1340 filemon_callback(ipf);
1342 return OOP_CONTINUE;
1345 static int filemon_method_init(void) {
1346 filemon_inotify_fd= inotify_init();
1347 if (filemon_inotify_fd<0) {
1348 syswarn("could not initialise inotify: inotify_init failed");
1352 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1354 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1358 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1360 /*---------- filemon dummy implementation ----------*/
1362 #if !defined(HAVE_FILEMON)
1364 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1366 static int filemon_method_init(void) { return 0; }
1367 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1368 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1370 #endif /* !HAVE_FILEMON */
1372 /*---------- interface to start and stop an input file ----------*/
1374 static const oop_rd_style feedfile_rdstyle= {
1375 OOP_RD_DELIM_STRIP, '\n',
1377 OOP_RD_SHORTREC_EOF,
1380 static void inputfile_tailing_start(InputFile *ipf) {
1382 ipf->readable->on_readable= tailing_on_readable;
1383 ipf->readable->on_cancel= tailing_on_cancel;
1384 ipf->readable->try_read= tailing_try_read;
1385 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1386 ipf->readable->delete_kill= 0;
1388 ipf->readable_callback= 0;
1389 ipf->readable_callback_user= 0;
1391 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1394 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1395 feedfile_got_article,ipf, feedfile_problem,ipf);
1396 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1399 static void inputfile_tailing_stop(InputFile *ipf) {
1401 oop_rd_cancel(ipf->rd);
1402 oop_rd_delete(ipf->rd);
1404 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1408 /*========== interaction with innd - state machine ==========*/
1410 /* See official state diagram at top of file. We implement
1420 |`---------------------------------------------------.
1422 |`---------------- - - - |
1423 D ENOENT | D EXISTS see OVERALL STATES diagram |
1424 | for full startup logic |
1427 | ============ try to |
1433 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1434 ^ | hardlink F to D |
1437 | | our handle onto F is now onto D |
1440 | |<-------------------<---------------------<---------+
1442 | | spawn inndcomm flush |
1444 | ================ |
1447 | main D tail/none |
1448 | ================ |
1450 | | INNDCOMM FLUSH FAILS ^
1451 | |`----------------------->----------. |
1453 | | NO SUCH SITE V |
1454 ^ |`--------------->----. ================ |
1457 | | FLUSH OK \ main D tail/none |
1458 | | open F \ ================ |
1460 | | \ | TIME TO RETRY |
1461 |<--------'| ,---<---'\ `----------------'
1462 | D NONE | | D NONE \
1467 | ============= | ============
1468 | SEPARATED/ | DROPPING/
1469 | flsh->fd>=0 | flsh->fd>=0
1470 | [Separated] | [Dropping]
1471 | main F idle | main none
1472 | old D tail | old D tail
1473 | ============= | ============
1475 ^ | EOF ON D | | EOF ON D
1477 | =============== | ===============
1478 | SEPARATED/ | DROPPING/
1479 | flsh->fd==-1 V flsh->fd==-1
1480 | [Finishing] | [Dropping]
1481 | main F tail `. main none
1482 | old D closed `. old D closed
1483 | =============== `. ===============
1485 | | ALL D PROCESSED `. | ALL D PROCESSED
1486 | V install defer as backlog `. V install defer as backlog
1487 ^ | close D \| close D
1488 | | unlink D | unlink D
1498 static void statemc_init(void) {
1499 struct stat stab, stabf;
1502 path_lock= xasprintf("%s_lock", feedfile);
1503 path_flushing= xasprintf("%s_flushing", feedfile);
1504 path_defer= xasprintf("%s_defer", feedfile);
1505 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1508 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1509 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1512 memset(&fl,0,sizeof(fl));
1514 fl.l_whence= SEEK_SET;
1515 r= fcntl(lockfd, F_SETLK, &fl);
1517 if (errno==EACCES || errno==EAGAIN) {
1518 if (quiet_if_locked) exit(0);
1519 fatal("another duct holds the lockfile");
1521 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1524 xfstat_isreg(lockfd, &stabf, "lockfile");
1525 xlstat_isreg(path_lock, &stab, &noent, "lockfile");
1527 if (!noent && samefile(&stab, &stabf))
1531 sysdie("could not close stale lockfile %s", path_lock);
1533 debug("startup: locked");
1535 search_backlog_file();
1537 xlstat_isreg(path_defer, &stab, &noent, "defer file");
1539 debug("startup: ductdefer ENOENT");
1541 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1542 switch (stab.st_nlink==1) {
1544 open_defer(); /* so that we will later close it and rename it */
1547 xunlink(path_defer, "stale defer file link"
1548 " (presumably hardlink to backlog file)");
1551 die("defer file %s has unexpected link count %d",
1552 path_defer, stab.st_nlink);
1556 InputFile *file_d= open_input_file(path_flushing);
1559 struct stat stab_f, stab_d;
1561 xlstat_isreg(feedfile, &stab_f, &noent, "feed file");
1563 debug("startup: D exists, F ENOENT => Moved");
1567 debug("startup: F and D both exist");
1569 xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1571 if (samefile(&stab_d, &stab_f)) {
1572 debug("startup: F==D => Hardlinked");
1573 xunlink(path_flushing, "feed file (during startup)");
1576 startup_set_input_file(file_d);
1577 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1579 debug("F!=D => Separated");
1580 SMS(SEPARATED, 0, "found both old and current feed files");
1581 startup_set_input_file(file_d);
1584 debug("startup: D ENOENT => Nothing");
1585 SMS(WAITING, open_wait_periods, "no feed file currently exists");
1589 static void statemc_poll(void) {
1590 if (sms==sm_WAITING) { statemc_waiting_poll(); return; }
1592 if (!sm_period_counter) return;
1593 sm_period_counter--;
1594 assert(sm_period_counter>=0);
1596 if (sm_period_counter) return;
1599 fatal("timed out waiting for innd to create feed file %s", feedfile);
1601 spawn_inndcomm_flush(void);
1608 static void statemc_waiting_poll(void) {
1609 InputFile *file_f= open_input_file(feedfile);
1610 if (!file_f) return;
1611 startup_set_input_file(file_d);
1612 SMS(NORMAL, 0, "found and opened feed file");
1615 static void startup_set_input_file(InputFile *f) {
1616 assert(!main_input_file);
1618 until_spontaneous_flush= spontaneous_flush_periods;
1619 inputfile_tailing_start(f);
1622 static void *statemc_check_input_done(oop_source *lp,
1623 struct timeval now, void *ipf_v) {
1624 InputFile *ipf= ipf_v;
1627 if (ipf->inprogress) return; /* new article in the meantime */
1628 if (ipf->fd >= 0); return; /* not had EOF */
1630 if (ipf == backlog_input_file) {
1631 notice_processed(ipf,"backlog file",ipf->path);
1632 close_input_file(ipf);
1633 if (unlink(ipf->path)) {
1634 if (errno != ENOENT)
1635 sysdie("could not unlink processed backlog file %s", ipf->path);
1636 warn("backlog file %s vanished while we were reading it"
1637 " so we couldn't remove it (but it's done now, anyway)",
1640 backlog_input_file= 0;
1641 search_backlog_file();
1645 assert(ipf == flushing_input_file);
1646 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1648 notice_processed(ipf,"feed file",0);
1652 xunlink(path_flushing, "old flushing file");
1654 if (sms==sm_DROPPING) {
1655 if (search_backlog_file()) {
1656 debug("feed dropped but still backlogs to process");
1659 notice("feed dropped and our work is complete");
1660 xunlink(path_lock, "lockfile for old feed");
1666 close_input_file(flushing_input_file);
1667 flushing_input_file= 0;
1669 notice("flush complete");
1670 SMS(NORMAL, 0, "flush complete");
1673 static void statemc_setstate(StateMachineState newsms, int periods,
1674 const char *forlog, const char *why) {
1676 sm_period_counter= periods;
1678 info("%s[%d] %s",periods,forlog,why);
1680 info("%s %s",forlog,why);
1684 /*---------- defer and backlog files ----------*/
1686 static void open_defer(void) {
1691 defer= fopen(path_defer, "a+");
1692 if (!defer) sysfatal("could not open defer file %s", path_defer);
1694 /* truncate away any half-written records */
1696 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1698 if (stab.st_size > LONG_MAX)
1699 die("defer file %s size is far too large", path_defer);
1704 long orgsize= stab.st_size;
1705 long truncto= stab.st_size;
1707 if (!truncto) break; /* was only (if anything) one half-truncated record */
1708 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1709 sysdie("seek in defer file %s while truncating partial", path_defer);
1714 sysdie("failed read from defer file %s", path_defer);
1716 die("defer file %s shrank while we were checking it!", path_defer);
1722 if (stab.st_size != truncto) {
1723 warn("truncating half-record at end of defer file %s -"
1724 " shrinking by %ld bytes from %ld to %ld",
1725 path_defer, orgsize - truncto, orgsize, truncto);
1728 sysfatal("could not flush defer file %s", path_defer);
1729 if (ftruncate(fileno(defer), truncto))
1730 sysdie("could not truncate defer file %s", path_defer);
1733 info("continuing existing defer file %s (%ld bytes)",
1734 path_defer, orgsize);
1736 if (fseek(defer, truncto, SEEK_SET))
1737 sysdie("could not seek to new end of defer file %s", path_defer);
1740 static void close_defer(void) {
1744 xfstat(fileno(defer), &stab, "defer file");
1746 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1749 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1750 (unsigned long)now.tv_sec,
1751 (unsigned long)stab.st_ino);
1752 if (link(path_defer, path_backlog))
1753 sysfatal("could not install defer file %s as backlog file %s",
1754 path_defer, backlog);
1755 if (unlink(path_defer))
1756 sysdie("could not unlink old defer link %s to backlog file %s",
1757 path_defer, backlog);
1759 if (until_backlog_nextscan < 0 ||
1760 until_backlog_nextscan > backlog_retry_minperiods + 1)
1761 until_backlog_nextscan= backlog_retry_minperiods + 1;
1764 static void poll_backlog_file(void) {
1765 if (until_backlog_nextscan < 0) return;
1766 if (until_backlog_nextscan-- > 0) return;
1767 search_backlog_file();
1770 static int search_backlog_file(void) {
1771 /* returns non-0 iff there are any backlog files */
1776 const char *oldest_path=0;
1777 time_t oldest_mtime, now;
1779 if (backlog_input_file) return 3;
1783 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
1787 sysdie("failed to expand backlog pattern %s", globpat_backlog);
1789 die("out of memory expanding backlog pattern %s", globpat_backlog);
1791 for (i=0; i<gl.gl_pathc; i++) {
1792 const char *path= gl.gl_pathv[i];
1794 if (strchr(path,'#') || strchr(path,'~')) {
1795 debug("backlog file search skipping %s", path);
1798 r= stat(path, &stab);
1800 syswarn("failed to stat backlog file %s", path);
1803 if (!S_ISREG(stab.st_mode)) {
1804 warn("backlog file %s is not a plain file (or link to one)", path);
1807 if (!oldest_path || stab.st_mtime < oldest_mtime) {
1809 oldest_mtime= stab.st_mtime;
1812 case GLOB_NOMATCH: /* fall through */
1815 sysdie("glob expansion of backlog pattern %s gave unexpected"
1816 " nonzero (error?) return value %d", globpat_backlog, r);
1822 debug("backlog scan: none");
1823 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
1827 now= time(); if (now==-1) sysdie("time(2) failed");
1828 double age= difftime(now, oldest_mtime);
1829 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
1831 if (age_deficiency <= 0) {
1832 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
1833 age, age_deficiency, oldest_path);
1835 backlog_input_file= open_input_file(oldest_path);
1836 if (!backlog_input_file) {
1837 warn("backlog file %s vanished as we opened it", backlog_input_file);
1840 inputfile_tailing_start(backlog_input_file);
1841 until_backlog_nextscan= -1;
1845 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
1847 if (backlog_spontaneous_rescan_periods >= 0 &&
1848 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
1849 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
1851 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
1852 age, age_deficiency, until_backlog_nextscan, oldest_path);
1856 /*========== flushing the feed ==========*/
1858 static pid_t inndcomm_child;
1860 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1861 assert(inndcomm_child);
1862 int status= xwaitpid(&inndcomm_child, "inndcomm");
1863 loop->cancel_fd(fd);
1866 assert(!flushing_input_file);
1868 if (WIFEXITED(status)) {
1869 switch (WEXITSTATUS(status)) {
1871 case INNDCOMMCHILD_ESTATUS_FAIL:
1874 case INNDCOMMCHILD_ESTATUS_NONESUCH:
1875 warn("feed has been dropped by innd, finishing up");
1876 flushing_input_file= main_input_file;
1878 SMS(DROPPING, 0, "dropped by innd");
1879 return OOP_CONTINUE;
1882 flushing_input_file= main_input_file;
1883 main_input_file= open_input_file(feedfile);
1884 if (!main_input_file)
1885 die("flush succeeded but feedfile %s does not exist!", feedfile);
1886 until_spontaneous_flush= spontaneous_flush_periods;
1887 SMS(SEPARATED, 0, "feed file missing");
1888 return OOP_CONTINUE;
1891 goto unexpected_exitstatus;
1894 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1895 warn("flush timed out trying to talk to innd");
1898 unexpected_exitstatus:
1899 report_child_status("inndcomm child", status);
1903 SMS(FLUSHFAIL, flushfail_retry_periods, "flush failed, will retry");
1906 static void inndcommfail(const char *what) {
1907 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1908 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1911 void spawn_inndcomm_flush(void) {
1914 assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1915 assert(!inndcomm_child);
1917 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1919 inndcomm_child= xfork();
1921 if (!inndcomm_child) {
1922 static char flushargv[2]= { sitename, 0 };
1927 alarm(inndcomm_flush_timeout);
1928 r= ICCopen(); if (r) inndcommfail("connect");
1929 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
1930 if (!r) exit(0); /* yay! */
1932 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1933 syswarn("innd ctlinnd flush failed: innd said %s", reply);
1934 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1938 int sentinel_fd= pipefds[0];
1939 on_fd_read_except(sentinel_fd, inndcomm_event);
1941 SMS(FLUSHING, 0, "flush is in progress");
1944 /*========== main program ==========*/
1946 static void postfork_inputfile(InputFile *ipf) {
1948 assert(ipf->fd >= 0);
1953 static void postfork_conns(Connection *conn) {
1960 static void postfork_stdio(FILE *f) {
1961 /* we have no stdio streams that are buffered long-term */
1965 static void postfork(const char *what) {
1966 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1967 sysdie("%s child: failed to reset SIGPIPE");
1969 postfork_inputfile(main_input_file);
1970 postfork_inputfile(flushing_input_file);
1971 postfork_conns(idle.head);
1972 postfork_conns(working.head);
1973 postfork_conns(full.head);
1974 postfork_stdio(defer);
1977 #define EVERY(what, interval, body) \
1978 static const struct timeval what##_timeout = { 5, 0 }; \
1979 static void what##_schedule(void); \
1980 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1982 what##_schedule(); \
1984 static void what##_schedule(void) { \
1985 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
1988 EVERY(filepoll, {5,0}, {
1989 if (main_input_file && main_input_file->readable_callback)
1990 filemon_callback(main_input_file);
1993 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s" \
1994 #define DEBUG_IPF(sh) \
1995 wh##_input_file, debug_ipf_path(wh##_input_file), \
1996 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
1997 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
1998 static const char *debug_ipf_path(InputFile *ipf) {
1999 char *slash= strrchr(ipf->path,'/');
2000 return slash ? slash+1 : ipf->path;
2003 EVERY(period, {PERIOD_SECONDS,0}, {
2005 " sms=%s queue=%d sm_period_counter=%d"
2006 " connect_delay=%d until_spontaneous_flush=%d"
2007 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_FMT(flushing)
2008 " conns idle=%d working=%d full=%d"
2009 " children connecting=%ld inndcomm_child"
2011 sms_names[sms], queue.count, sm_period_counter,
2012 connect_delay, until_spontaneous_flush,
2013 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2014 idle.count, working.count, full.count,
2015 (long)connecting_child, (long)inndcomm_child
2017 if (connect_delay) connect_delay--;
2018 if (until_spontaneous_flush) until_spontaneous_flush--;
2019 poll_backlog_file();
2020 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2022 check_master_queue();
2026 /*========== option parsing ==========*/
2029 of_seconds= 001000u;
2030 of_boolean= 002000u;
2033 typedef struct Option Option;
2034 typedef void OptionParser(const Option*, const char *val);
2044 void op_integer(const Option *o, const char *val) {
2047 unsigned long ul= strtoul(val,&ep,10);
2048 if (*ep || ep==val || errno || ul>INT_MAX)
2049 badusage("bad integer value for %s",o->long);
2050 int *store= o->store;
2054 void op_double(const Option *o, const char *val) {
2055 int *store= o->store;
2058 *store= strtod(val, &ep);
2059 if (*ep || ep==val || errno)
2060 badusage("bad floating point value for %s",o->long);
2063 void op_string(const Option *o, const char *val) {
2064 char **store= o->store;
2069 void op_seconds(const Option *o, const char *val) {
2070 int *store= o->store;
2073 double v= strtod(val,&ep);
2074 if (ep==val) badusage("bad time/duration value for %s",o->long);
2076 if (!*ep || !strcmp(ep,"s")) unit= 1;
2077 else if (!strcmp(ep,"m")) unit= 60;
2078 else if (!strcmp(ep,"h")) unit= 3600;
2079 else if (!strcmp(ep,"d")) unit= 86400;
2080 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2084 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2088 void op_periods_rndup(const Option *o, const char *val) {
2089 int *store= o->store;
2091 *store += PERIOD_SECONDS-1;
2092 *store /= PERIOD_SECONDS;
2095 void op_periods_booltrue(const Option *o, const char *val) {
2096 int *store= o->store;
2099 void op_periods_boolfalse(const Option *o, const char *val) {
2100 int *store= o->store;
2104 static const Option options[]= {
2105 { 0, "max-connections", &max_connections op_integer },
2106 { 0, "streaming", &try_stream, op_booltrue, 1 },
2107 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2108 {'h',"host", &remote_host, op_string },
2109 {'P',"port", &port op_integer },
2110 { 0, "inndconf", &inndconffile, op_string },
2111 {'f',"feedfile", &feedfile, op_string },
2112 {'q',"quiet-multiple", &quiet_if_locked, op_booltrue, 1 },
2113 { 0, "no-quiet-multiple", &quiet_if_locked, op_boolfalse, 1 },
2114 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2115 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2117 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2118 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2120 { 0, "max-queue-size", &max_queue_per_conn op_integer },
2121 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2122 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2123 { 0, "feedfile-open-timeout", &open_wait_periods, op_periods_rndup },
2124 { 0, "connection-timeout", &connection_timeout, op_seconds },
2125 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2128 int main(int argc, char **argv) {
2134 if (*arg != '-') break;
2135 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2137 while ((a= *++arg)) {
2141 char *equals= strchr(arg,'=');
2142 int len= equals ? (equals - arg) : strlen(arg);
2143 for (o=options; o->long; o++)
2144 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2146 badusage("unknown long option --%s",arg);
2149 if (equals) badusage("option --%s does not take a value",o->long);
2151 } else if (equals) {
2155 if (!arg) badusage("option --%s needs a value",o->long);
2158 break; /* eaten the whole argument now */
2160 for (o=options; o->long; o++)
2163 badusage("unknown short option -%c",a);
2170 if (!arg) badusage("option -%c needs a value",o->short);
2173 break; /* eaten the whole argument now */
2178 if (!arg) badusage("need site name argument");
2181 if ((arg= *++argv)) {
2182 if (remote_host) badusage("must not specify -h and also host as argument");
2186 if (*++argv) badusage("too many non-option arguments");
2188 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2189 badusage("nocheck threshold percentage must be between 0..100");
2190 nocheck_thresh= nocheck_thresh_pct * 0.01;
2192 if (nocheck_decay_articles < 0.1)
2193 badusage("nocheck decay articles must be at least 0.1");
2194 nocheck_decay= 1 - 1/nocheck_decay_articles;
2196 innconf_read(inndconffile);
2199 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2200 else if (!feedfile[0])
2201 badusage("feed filename must be nonempty");
2202 else if (feedfile[strlen(feedfile)-1]=='/')
2203 feedfile= xasprintf("%s%s",feedfile,sitename);
2205 const char *feedfile_forbidden= "?*[~#";
2207 while ((c= *feedfile_forbidden++))
2208 if (strchr(feedfile, c))
2209 badusage("feed filename may not contain metacharacter %c",c);
2211 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2212 sysdie("could not ignore SIGPIPE");
2214 if (become_daemon) {
2215 for (i=3; i<255; i++)
2216 /* do this now before we open syslog, etc. */
2218 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2220 int null= open("/dev/null",O_RDWR);
2221 if (null<0) sysdie("failed to open /dev/null");
2227 pid_t child1= xfork("daemonise first fork");
2228 if (child1) _exit(0);
2230 pid_t sid= setsid();
2231 if (sid != child1) sysdie("setsid failed");
2233 pid_t child2= xfork("daemonise second fork");
2234 if (child2) _exit(0);
2239 if (!filemon_init()) {
2240 warn("no file monitoring available, polling");
2241 filepoll_schedule();