2 * Newsfeeds file entries should look like this:
3 * host.name.of.site[/exclude,exclude,...]\
4 * :pattern,pattern...[/distribution,distribution...]\
8 * sitename[/exclude,exclude,...]\
9 * :pattern,pattern...[/distribution,distribution...]\
15 * or might be blanked out
16 * <spc><spc><spc><spc>....
18 * site.name_duct.lock lock preventing multiple ducts
19 * holder of this lock is "duct"
20 * F site.name main feed file
21 * opened/created, then written, by innd
24 * tokens blanked out by duct when processed
25 * D site.name_duct temporary feed file during flush (or crash)
26 * hardlink created by duct
28 * site.name_duct.defer 431'd articles, still being written,
29 * created, written, used by duct
30 * site.name_backlog.lock lock taken out by innxmit wrapper
31 * holder and its child are "xmit"
32 * site.name_backlog_<date>.<inum>
33 * 431'd articles, ready for innxmit or duct
34 * created (link/mv) by duct
35 * site.name_backlog_<anything-else> eg
36 * site.name_backlog_manual
37 * anything the sysadmin likes (eg, feed files
38 * from old feeds to be merged into this one)
39 * created (link/mv) by admin
41 * Backlog files are also processed by innduct. We find the oldest
42 * backlog file which is at least a certain amount old, and feed it
43 * back into our processing. When every article in it has been read
44 * and processed, we unlink it and look for another backlog file.
46 * If we don't have a backlog file that we're reading, we close the
47 * defer file that we're writing and make it into a backlog file at
48 * the first convenient opportunity.
57 <--------------------------------------'|
58 Nothing F, D both ENOENT |
61 duct: not not reading anything |
63 |`---------------------. |
64 | | duct times out waiting for F |
65 V innd creates F | duct exits |
67 Noduct GO TO Dropped |
70 duct: not running or not reading anything |
73 ,-->--+ <---------------------------------'|
74 | | duct opens F F exists |
78 | F: innd writing, duct reading |
81 | | duct decides time to flush |
82 | | duct makes hardlink |
84 | V <------------------------'|
86 | F == D: innd writing, duct reading both exist |
90 | Moved <----+------------<--'|
91 | F: ENOENT | F ENOENT |
92 | D: innd writing, duct reading | D exists |
94 | | duct requests flush of feed | |
95 | | (others can too, harmlessly) | |
99 | D: innd flushing, duct reading | |
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 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 const char *path; /* ptr copy of path_<foo> or feedfile */
253 struct Filemon_Perfile *filemon;
256 long inprogress; /* no. of articles read but not processed */
273 int fd, max_queue, stream;
274 LIST(Article) queue; /* not yet told peer, or CHECK said send it */
275 LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
276 struct iovec xmit[CONNIOVS];
277 XmitDetails xmitd[CONNIOVS];
282 /*----- operational variables -----*/
284 static int since_connect_attempt;
286 static LIST(Conn) idle, working, full;
287 static LIST(Article) *queue;
289 static char *path_ductlock, *path_duct, *path_ductdefer;
291 #define SMS(newstate, periods, why) \
292 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
294 static StateMachineState sms;
296 static InputFile *main_input_file, *old_input_file, *backlog_input_file;
297 static int sm_period_counter;
300 /*----- function predeclarations -----*/
302 static void conn_check_work(Conn *conn);
304 static int filemon_init(void);
305 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
306 static void filemon_callback(void);
308 static void statemc_setstate(StateMachineState newsms, int periods,
309 const char *forlog, const char *why);
311 /*========== utility functions etc. ==========*/
313 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
315 static pid_t xfork(const char *what) {
319 if (child==-1) sysdie("cannot fork for %s",what);
320 if (!child) postfork(what);
324 static void on_fd_read_except(int fd, oop_call_fd callback) {
325 loop->on_fd(loop, fd, OOP_READ, callback, 0);
326 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
328 static void cancel_fd_read_except(int fd) {
329 loop->cancel_fd(loop, fd, OOP_READ);
330 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
333 static void report_child_status(const char *what, int status) {
334 if (WIFEXITED(status)) {
335 int es= WEXITSTATUS(status);
337 warn("%s: child died with error exit status %d",es);
338 } else if (WIFSIGNALED(status)) {
339 int sig= WTERMSIG(status);
340 const char *sigstr= strsignal(sig);
341 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
343 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
345 warn("%s: child died due to unknown fatal signal %d%s",
346 what, sig, coredump);
348 warn("%s: child died with unknown wait status %d", status);
352 static int xwaitpid(pid_t *pid, const char *what) {
355 r= kill(*pid, SIGKILL);
356 if (r) sysdie("cannot kill %s child", what);
358 pid_t got= waitpid(*pid, &status, WNOHANG);
359 if (got==-1) sysdie("cannot reap %s child", what);
366 static void check_isreg(const struct stat *stab, const char *path,
368 if (!S_ISREG(stab->st_mode))
369 die("%s %s not a plain file (mode 0%lo)",
370 what, path, (unsigned long)stab->st_mode);
373 static void xfstat(int fd, struct stat *stab_r, const char *what) {
374 int r= fstab(path, stab);
375 if (r) sysdie("could not fstat %s %s", what, path);
378 static void xfstat_isreg(int fd, struct stat *stab_r, const char *what) {
379 xfstat(fd, stab_r, what);
380 check_isreg(stab, path, what);
383 static void xlstat_isreg(const char *path, struct stat *stab,
384 int *enoent_r /* 0 means ENOENT is fatal */
386 int r= lstat(path, stab);
388 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
389 sysdie("could not lstat %s %s", what, path);
391 if (enoent_r) *enoent_r= 0;
392 check_isreg(stab, path, what);
395 static int samefile(const struct stat *a, const struct stat *b) {
396 assert(S_ISREG(a->st_mode));
397 assert(S_ISREG(b->st_mode));
398 return (a->st_ino == b->st_ino &&
399 a->st_dev == b->st_dev);
402 /*========== logging ==========*/
404 static void logcore(int sysloglevel, const char *fmt, ...)
405 __attribute__((printf,2,3))
406 static void logcore(int sysloglevel, const char *fmt, ...) {
410 vsyslog(sysloglevel,fmt,al);
412 vfprintf(stderr,fmt,al);
417 static void logv(int sysloglevel, const char *pfx, int errnoval,
418 int exitstatus, const char *fmt, va_list al)
419 __attribute__((printf,4,0))
420 static void logv(int sysloglevel, const char *pfx, int errnoval,
421 int exitstatus, const char *fmt, va_list al) {
423 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
424 msgbuf[sizeof(msgbuf)-1]= 0;
426 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
427 sysloglevel= LOG_ERR; /* run by wrong user, probably */
429 logcore(sysloglevel, "<%s>%s: %s%s%s",
430 sitename, pfx, msgbuf,
431 errnoval>=0 ? ": " : "",
432 errnoval>=0 ? strerror(errnoval) : "");
435 #define logwrap(fn, pfx, sysloglevel, errno, estatus) \
436 static void fn(const char *fmt, ...) \
437 __attribute__((printf,1,2)); \
438 static void fn(const char *fmt, ...) { \
441 logv(sysloglevel, pfx, errno, estatus, fmt, al); \
444 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
445 logwrap(die, " critical", LOG_CRIT, -1, 16);
447 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
448 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
450 logwrap(syswarn, " warning", LOG_WARN, errno, 0);
451 logwrap(warn, " warning", LOG_WARN, -1, 0);
453 logwrap(notice, "", LOG_NOTICE, -1, 0);
454 logwrap(info, " info", LOG_INFO, -1, 0);
457 /*========== making new connections ==========*/
459 static int connecting_sockets[2]= {-1,-1};
460 static pid_t connecting_child;
462 static void connect_attempt_discard(void) {
463 if (connecting_sockets[0])
464 cancel_fd(connecting_sockets[0]);
466 perhaps_close(&connecting_sockets[0]);
467 perhaps_close(&connecting_sockets[1]);
469 if (connecting_child) {
470 int status= xwaitpid(&connecting_child, "connect");
472 if (!(WIFEXITED(status) ||
473 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
474 report_child_status("connect", status);
478 #define PREP_DECL_MSG_CMSG(msg) \
480 memset(&msg,0,sizeof(msg)); \
481 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
482 msg.msg_control= msg##cbuf; \
483 msg.msg_controllen= sizeof(msg##cbuf);
485 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
488 conn= xmalloc(sizeof(*conn));
489 memset(conn,0,sizeof(*conn));
492 struct cmsghdr *h= 0;
493 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
494 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
497 pid_t got= waitpid(connecting_child, &status, WNOHANG);
499 assert(got==connecting_child);
501 if (WIFEXITED(status) &&
502 (WEXITSTATUS(status) != 0
503 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
504 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
505 /* child already reported the problem */
506 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
507 warn("connect: connection attempt timed out");
508 } else if (!WIFEXITED(status)) {
509 report_child_status("connect", status);
510 /* that's probably the root cause then */
513 /* child is still running apparently, report the socket problem */
515 syswarn("connect: read from child socket failed");
516 else if (e == OOP_EXCEPTIONN)
517 warn("connect: unexpected exception on child socket");
519 warn("connect: unexpected EOF on child socket");
524 #define CHK(field, val) \
525 if (h->cmsg_##field != val) { \
526 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
529 CHK(level, SOL_SOCKET);
530 CHK(type, SCM_RIGHTS);
531 CHK(len, CMSG_LEN(sizeof(conn-b>fd)));
534 if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
536 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
538 pid_t got= waitpid(connecting_child, &status, 0);
539 if (got==-1) sysdie("connect: real wait for child");
540 assert(got == connecting_child);
543 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
544 int es= WEXITSTATUS(status);
546 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
547 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
549 fatal("connect: child gave unexpected exit status %d", es);
555 LIST_ADDHEAD(idle, conn);
556 notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
557 connect_attempt_discard();
558 check_master_queue();
563 perhaps_close(&conn->fd);
566 connect_attempt_discard();
569 static void connect_start() {
570 assert(!connecting_sockets[0]);
571 assert(!connecting_sockets[1]);
572 assert(!connecting_child);
574 notice("starting connection attempt");
576 r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
577 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
579 connecting_child= xfork("connection");
581 if (!connecting_child) {
582 FILE *cn_from, *cn_to;
583 char buf[NNTP_STRLEN+100];
584 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
586 r= close(connecting_sockets[0]);
587 if (r) sysdie("connect: close parent socket in child");
589 alarm(connection_setup_timeout);
590 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
592 sanitise_inplace(buf);
593 fatal("connect: rejected: %s", buf);
595 sysfatal("connect: connection attempt failed");
598 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
599 sysfatal("connect: authentication failed");
601 if (fputs("MODE STREAM\r\n", cn_to) ||
603 sysfatal("connect: could not send MODE STREAM");
604 buf[sizeof(buf)-1]= 0;
605 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
607 sysfatal("connect: could not read response to MODE STREAM");
609 fatal("connect: connection close in response to MODE STREAM");
614 sanitise_inplace(buf);
615 fatal("connect: response to MODE STREAM is too long: %.100s...",
618 l--; if (l>0 && buf[1-]=='\r') l--;
621 int rcode= strtoul(buf,&ep,10);
623 sanitise_inplace(buf);
624 fatal("connect: bad response to MODE STREAM: %.50s", buf);
628 exitstatus= CONNCHILD_ESTATUS_STREAM;
634 sanitise_inplace(buf);
635 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
640 int fd= fileno(cn_from);
642 PREP_DECL_MSG_CMSG(msg);
643 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
644 cmsg->cmsg_level= SOL_SOCKET;
645 cmsg->cmsg_type= SCM_RIGHTS;
646 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
647 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
649 msg.msg_controllen= cmsg->cmsg_len;
650 r= sendmsg(connecting_sockets[1], &msg, 0);
651 if (r) sysdie("sendmsg failed for new connection");
656 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
657 if (r) sysdie("connect: close child socket in parent");
659 on_fd_read_except(connecting_sockets[0], connchild_event);
663 connect_attempt_discard();
667 /*========== overall control of article flow ==========*/
669 static void check_master_queue(void) {
673 Conn *last_assigned=0;
676 conn_assign_one_article(&working, &last_assigned);
677 } else if (idle.head) {
678 conn_assign_one_article(&idle, &last_assigned);
679 } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
680 !connecting_child && !connect_delay) {
681 connect_delay= reconnect_delay_periods;
687 conn_check_work(last_assigned);
690 static void conn_assign_one_article(LIST(Conn) *connlist,
691 Conn **last_assigned) {
692 Conn *conn= connlist->head;
694 LIST_REMOVE(*connlist, conn);
695 Article *art= LIST_REMHEAD(queue);
696 LIST_ADDTAIL(conn->queue, art);
697 LIST_ADD(*conn_determine_right_list(conn), conn);
699 /* This slightly odd arrangement is so that we call conn_check_work
700 * once after filling the queue for a new connection in
701 * check_master_queue, rather than for each article. */
702 if (conn != *last_assigned && *last_assigned)
703 conn_check_work(*last_assigned);
704 *last_assigned= conn;
707 static int conn_total_queued_articles(Conn *conn) {
708 return conn->sent.count + conn->queue.count;
711 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
712 int inqueue= conn_total_queued_articles(conn);
713 assert(inqueue <= max_queue);
714 if (inqueue == 0) return &idle;
715 if (inqueue == conn->max_queue) return &full;
719 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
724 static void conn_check_work(Conn *conn) {
727 conn_make_some_xmits(conn);
729 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
733 void *rp= conn_write_some_xmits(conn);
734 if (rp==OOP_CONTINUE) {
735 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
737 } else if (rp==OOP_HALT) {
740 /* transmitted everything */
748 /*========== article transmission ==========*/
750 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
751 XmitKind kind) { /* caller must then fill in details */
752 struct iovec *v= &conn->xmit[conn->xmitu];
753 XmitDetails *d= &conn->xmitd[conn->xmitu++];
760 static void xmit_noalloc(Conn *conn, const char *data, int len) {
761 xmit_core(conn,data,len, xk_Const);
763 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
765 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
766 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
770 static void xmit_free(XmitDetails *d) {
772 case xk_Malloc: free(d->info.malloc_tofree); break;
773 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
774 case xk_Const: break;
779 static void *conn_write_some_xmits(Conn *conn) {
781 * 0: nothing more to write, no need to call us again
782 * OOP_CONTINUE: more to write but fd not writeable
783 * OOP_HALT: disaster, have destroyed conn
786 int count= conn->xmitu;
787 if (!count) return 0;
789 if (count > IOV_MAX) count= IOV_MAX;
790 ssize_t rs= writev(conn->fd, conn->xmit, count);
792 if (errno == EAGAIN) return OOP_CONTINUE;
793 connfail(conn, "write failed: %s", strerror(errno));
798 for (done=0; rs && done<xmitu; done++) {
799 struct iovec *vp= &conn->xmit[done];
800 XmitDetails *dp= &conn->xmitd[done];
801 if (rs > vp->iov_len) {
809 int newu= conn->xmitu - done;
810 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
811 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
816 static void conn_make_some_xmits(Conn *conn) {
818 if (conn->xmitu+5 > CONNIOVS)
821 Article *art= LIST_REMHEAD(queue);
824 if (art->checked || (conn->stream && nocheck)) {
825 /* actually send it */
827 ARTHANDLE *artdata= SMretrieve();
831 XMIT_LITERAL("TAKETHIS ");
832 xmit_noalloc(conn, art->mid, art->midlen);
833 XMIT_LITERAL("\r\n");
834 xmit_artbody(conn, artdata);
837 /* we got 235 from IHAVE */
839 xmit_artbody(conn, artdata);
841 XMIT_LITERAL(".\r\n");
846 LIST_ADDTAIL(conn->sent, art);
848 art->ipf->counts[art->checked].sent++;
854 XMIT_LITERAL("IHAVE ");
856 XMIT_LITERAL("CHECK ");
857 xmit_noalloc(art->mid, art->midlen);
858 XMIT_LITERAL("\r\n");
860 LIST_ADDTAIL(conn->sent, art);
861 art->ipf->counts[art->checked].offered++;
867 /*========== handling responses from peer ==========*/
869 static const oop_rd_style peer_rd_style= {
870 OOP_RD_DELIM_STRIP, '\n',
872 OOP_RD_SHORTREC_FORBID
875 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
876 const char *errmsg, int errnoval,
877 const char *data, size_t recsz, void *conn_v) {
879 connfail(conn, "error receiving from peer: %s", errmsg);
883 static Article *article_reply_check(Connection *conn, const char *response,
884 int code_indicates_streaming,
885 const char *sanitised_response) {
886 Article *art= LIST_REMHEAD(conn->sent);
890 "peer gave unexpected response when no commands outstanding: %s",
895 if (code_indicates_streaming) {
896 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
898 connfail("peer gave streaming response code "
899 " to IHAVE or subsequent body: %s", sanitised_response);
902 const char *got_mid= response+4;
903 int got_midlen= strcspn(got_mid, " \n\r");
904 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
905 connfail("peer gave streaming response with syntactically invalid"
906 " messageid: %s", sanitised_response);
909 if (got_midlen != art->midlen ||
910 memcmp(got_mid, art->messageid, got_midlen)) {
911 connfail("peer gave streaming response code to wrong article -"
912 " probable synchronisation problem; we offered: %s;"
914 art->messageid, sanitised_response);
919 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
928 static void update_nocheck(int accepted) {
929 accept_proportion *= accept_decay;
930 accept_proportion += accepted;
931 nocheck= accept_proportion >= nocheck_thresh;
932 if (nocheck && !nocheck_reported) {
933 notice("entering nocheck mode for the first time");
938 static void article_done(Connection *conn, Article *art, int whichcount) {
940 art->ipf->counts.articles[art->checked][whichcount]++;
941 if (whichcount == RC_accepted) update_nocheck(1);
942 else if (whichcount == RC_unwanted) update_nocheck(0);
944 InputFile *ipf= art->ipf;
945 while (art->blanklen) {
946 static const char spaces[]=
951 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
952 int r= pwrite(ipf->fd, spaces, w, art->offset);
954 if (errno==EINTR) continue;
955 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
956 art->messageid, art->blanklen, art->offset, ipf->path);
958 assert(r>=0 && r<=w);
964 assert(ipf->inprogress >= 0);
966 if (!ipf->inprogress)
967 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, ipf);
972 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
973 const char *errmsg, int errnoval,
974 const char *data, size_t recsz, void *conn_v) {
977 if (ev == OOP_RD_EOF) {
978 connfail(conn, "unexpected EOF from peer");
981 assert(ev == OOP_RD_OK);
984 unsigned long code= strtoul(data, &ep, 10);
985 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
991 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
993 if (!c) { *q++= '\''; break; }
994 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
995 sprintf(q,"\\x%02x",c);
998 connfail(conn, "badly formatted response from peer: %s", sanibuf);
1002 if (conn->quitting) {
1004 connfail(conn, "peer gave failure response to QUIT: %s", sani);
1005 return OOP_CONTINUE;
1013 #define GET_ARTICLE \
1014 art= article_reply_check(conn, data, code_streaming, sani); \
1015 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1017 #define ARTICLE_DEALTWITH(streaming,how) \
1018 code_streaming= (streaming) \
1020 article_done(conn, art, RC_##how); break;
1022 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1024 int code_streaming= 0;
1028 case 400: PEERBADMSG("peer stopped accepting articles");
1029 case 503: PEERBADMSG("peer timed us out");
1030 default: PEERBADMSG("peer sent unexpected message");
1032 case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
1033 case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
1035 case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
1036 case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
1038 case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
1039 case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
1041 case 238: /* CHECK says send it */
1043 case 335: /* IHAVE says send it */
1045 count_checkedwanted++;
1046 LIST_ADDTAIL(conn->queue);
1048 connfail("peer gave %d response to article body: %s",code, sani);
1049 return OOP_CONTINUE;
1054 case 431: /* CHECK or TAKETHIS says try later */
1056 case 436: /* IHAVE says try later */
1059 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1061 sysfatal("write to defer file %s",path_ductdefer);
1062 article_done(conn, art, RC_deferred);
1067 check_check_work(conn);
1068 return OOP_CONTINUE;
1072 /*========== monitoring of input files ==========*/
1074 static void feedfile_eof(InputFile *ipf) {
1075 assert(ipf != main_input_file); /* promised by tailing_try_read */
1077 inputfile_tailing_stop(ipf);
1079 if (ipf == backlog_input_file) {
1080 assert(ipf->fd >= 0);
1081 if (close(ipf->fd)) sysdie("could not close backlog file %s", ipf->path);
1086 assert(ipf == old_input_file);
1088 inputfile_tailing_stop(ipf);
1089 assert(ipf->fd >= 0);
1090 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1093 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1095 if (main_input_file)
1096 inputfile_tailing_start(main_input_file);
1099 static InputFile *open_input_file(const char *path) {
1100 int fd= open(path, O_RDONLY);
1102 if (errno==ENOENT) return 0;
1103 sysfatal("unable to open input file %s", path);
1106 InputFile *ipf= xmalloc(sizeof(InputFile));
1107 memset(ipf,0,sizeof(*ipf));
1109 ipf->readable.on_readable= tailing_on_readable;
1110 ipf->readable.on_cancel= tailing_on_cancel;
1111 ipf->readable.try_read= tailing_try_read;
1119 static void close_input_file(InputFile *ipf) {
1120 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1121 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1122 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1123 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1126 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1128 fixme maybe free ipf->path;
1134 /*---------- dealing with articles read in the input file ----------*/
1136 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1137 oop_rd_event ev, const char *errmsg,
1139 const char *data, size_t recsz,
1141 InputFile *ipf= ipf_v;
1143 char tokentextbuf[sizeof(TOKEN)*2+3];
1145 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1147 if (data[0] && data[0]!=' ') {
1148 char *space= strchr(data,' ');
1149 int tokenlen= space-data;
1150 int midlen= (int)recsz-tokenlen-1;
1151 if (midlen < 0) goto bad_data;
1153 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1154 memcpy(tokentextbuf, data, tokenlen);
1155 tokentextbuf[tokenlen]= 0;
1156 if (!IsToken(tokentextbuf)) goto bad_data;
1158 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1159 art->offset= ipf->offset;
1160 art->blanklen= recsz;
1161 art->midlen= midlen;
1162 art->checked= art->sentbody= 0;
1163 art->ipf= ipf; ipf->inprogress++;
1164 art->token= TextToToken(tokentextbuf);
1165 strcpy(art->messageid, space+1);
1166 LIST_ADDTAIL(queue, art);
1168 ipf->offset += recsz + 1;
1170 if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
1171 notice("starting flush (%lu >= %lu)",
1172 (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1174 int r= link(feedfile, duct_path);
1175 if (r) sysdie("link feedfile %s to ductfile %s", feedfile, dut_path);
1178 r= unlink(feedfile);
1179 if (r) sysdie("unlink old feedfile link %s", feedfile);
1182 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1185 check_master_queue();
1189 /*========== tailing input file ==========*/
1191 static void filemon_start(InputFile *ipf) {
1192 assert(!ipf->filemon);
1194 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1195 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1196 filemon_method_startfile(ipf, ipf->filemon);
1199 static void filemon_stop(InputFile *ipf) {
1200 if (!ipf->filemon) return;
1201 filemon_method_stopfile(ipf, ipf->filemon);
1206 static void filemon_callback(InputFile *ipf) {
1207 ipf->readable_callback(ipf->readable_callback_user);
1210 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1212 InputFile *ipf= user;
1213 return ipf->readable_callback(ipf->readable_callback_user);
1216 static void on_cancel(struct oop_readable *rable) {
1217 InputFile *ipf= (void*)rable;
1219 if (ipf->filemon) filemon_stopfile(ipf);
1220 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1221 ipf->readable_callback= 0;
1224 static int tailing_on_readable(struct oop_readable *rable,
1225 oop_readable_call *cb, void *user) {
1226 InputFile *ipf= (void*)rable;
1228 tailing_on_cancel(rable);
1229 ipf->readable_callback= cb;
1230 ipf->readable_callback_user= user;
1231 filemon_startfile(ipf);
1233 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1237 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1239 InputFile *ipf= (void*)rable;
1241 ssize_t r= read(ipf->fd, buffer, length);
1243 if (errno==EINTR) continue;
1247 if (ipf==main_input_file) {
1250 } else if (ipf==old_input_file) {
1252 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1253 } else if (ipf==backlog_input_file) {
1263 /*---------- filemon implemented with inotify ----------*/
1265 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1266 #define HAVE_FILEMON
1268 #include <linux/inotify.h>
1270 static int filemon_inotify_fd;
1271 static int filemon_inotify_wdmax;
1272 static InputFile **filemon_inotify_wd2ipf;
1274 typedef struct Filemon_Perfile {
1276 } Filemon_Inotify_Perfile;
1278 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1279 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1280 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1282 if (wd >= filemon_inotify_wdmax) {
1284 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1285 sizeof(*filemon_inotify_wd2ipf) * newmax);
1286 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1287 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1288 filemon_inotify_wdmax= newmax;
1291 assert(!filemon_inotify_wd2ipf[wd]);
1292 filemon_inotify_wd2ipf[wd]= ipf;
1297 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1299 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1300 if (r) sysdie("inotify_rm_watch");
1301 filemon_inotify_wd2ipf[wd]= 0;
1304 static void *filemon_inotify_readable(oop_source *lp, int fd,
1305 oop_event e, void *u) {
1306 struct inotify_event iev;
1308 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1310 if (errno==EAGAIN) break;
1311 sysdie("read from inotify master");
1312 } else if (r==sizeof(iev)) {
1313 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1315 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1317 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1318 filemon_callback(ipf);
1320 return OOP_CONTINUE;
1323 static int filemon_method_init(void) {
1324 filemon_inotify_fd= inotify_init();
1325 if (filemon_inotify_fd<0) {
1326 syswarn("could not initialise inotify: inotify_init failed");
1330 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1335 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1337 /*---------- filemon dummy implementation ----------*/
1339 #if !defined(HAVE_FILEMON)
1341 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1343 static int filemon_method_init(void) { return 0; }
1344 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1345 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1347 #endif /* !HAVE_FILEMON */
1349 /*---------- interface to start and stop an input file ----------*/
1351 static const oop_rd_style feedfile_rdstyle= {
1352 OOP_RD_DELIM_STRIP, '\n',
1354 OOP_RD_SHORTREC_EOF,
1357 static void inputfile_tailing_start(InputFile *ipf) {
1359 ipf->readable->on_readable= tailing_on_readable;
1360 ipf->readable->on_cancel= tailing_on_cancel;
1361 ipf->readable->try_read= tailing_try_read;
1362 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1363 ipf->readable->delete_kill= 0;
1365 ipf->readable_callback= 0;
1366 ipf->readable_callback_user= 0;
1368 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1371 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1372 feedfile_got_article,ipf, feedfile_problem,ipf);
1373 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1376 static void inputfile_tailing_stop(InputFile *ipf) {
1378 oop_rd_cancel(ipf->rd);
1379 oop_rd_delete(ipf->rd);
1381 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1385 /*========== interaction with innd - state machine ==========*/
1387 /* See official state diagram at top of file. We implement
1396 | TIMEOUT and no defer, no backlog
1397 |`--------------------------.
1399 | OPEN F SUCCEEDS | exit
1404 | [Normal] =========
1408 | | F IS SO BIG WE SHOULD FLUSH
1412 | | our handle onto F is now onto D
1415 | |<---------------------------------------------------.
1417 | | spawn inndcomm flush |
1425 | | INNDCOMM FLUSH FAILS ^
1426 | |`----------------------->----------. |
1428 | | NO SUCH SITE V |
1429 ^ |`--------------->----. =========== |
1435 | | \ | TIME TO RETRY |
1436 | | \ `----------------'
1440 | ============= ============
1441 | SEPARATED/ DROPPING/
1442 | old->fd>=0 old->fd>=0
1443 | [Separated] [Dropping]
1444 | main F idle main none
1445 | old D tail old D tail
1446 | ============= ============
1448 ^ | EOF ON D | EOF ON D
1450 | =============== ===============
1451 | SEPARATED/ DROPPING/
1452 | old->fd==-1 old->fd==-1
1453 | [Finishing] [Dropping]
1454 | main F tail main none
1455 | old D closed old D closed
1456 | =============== ===============
1458 | | ALL D PROCESSED | ALL D PROCESSED
1459 | V install defer as backlog V install defer as backlog
1460 ^ | close D | close D
1461 | | unlink D | unlink D
1470 static void statemc_init(void) {
1471 struct stat stab, stabf;
1474 path_ductlock= xasprintf("%s_duct.lock", feedfile);
1475 path_duct= xasprintf("%s_duct", feedfile);
1476 path_ductdefer= xasprintf("%s_duct.defer", feedfile);
1477 globpat_backlog= xasprintf("%s_backlog_*", feedfile);
1480 int lockfd= open(path_ductlock, O_CREAT|O_RDWR, 0600);
1481 if (lockfd<0) sysfatal("open lockfile %s", path_ductlock);
1484 memset(&fl,0,sizeof(fl));
1486 fl.l_whence= SEEK_SET;
1487 r= fcntl(lockfd, F_SETLK, &fl);
1489 if (errno==EACCES || errno==EAGAIN) {
1490 if (quiet_if_locked) exit(0);
1491 fatal("another duct holds the lockfile");
1493 sysdie("fcntl F_SETLK lockfile %s", path_ductlock);
1496 xfstat_isreg(lockfd, &stabf, "lockfile");
1497 xlstat_isreg(path_ductlock, &stab, &noent, "lockfile");
1499 if (!noent && samefile(&stab, &stabf))
1503 sysdie("could not close stale lockfile %s", path_ductlock);
1505 debug("startup: locked");
1507 search_backlog_file();
1509 xlstat_isreg(path_ductdefer, &stab, &noent, "defer file");
1511 debug("startup: ductdefer ENOENT");
1513 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1514 switch (stab.st_nlink==1) {
1516 open_defer(); /* so that we will later close it and rename it */
1519 if (unlink(path_defer))
1520 sysdie("could not unlink stale defer file link %s (presumably"
1521 " hardlink to backlog file)", path_defer);
1524 die("defer file %s has unexpected link count %d",
1525 path_defer, stab.st_nlink);
1529 InputFile *file_d= open_input_file(path_duct);
1532 struct stat stab_f, stab_d;
1534 xlstat_isreg(feedfile, &stab_f, &noent, "feed file");
1536 debug("startup: D exists, F ENOENT => Moved");
1540 debug("startup: F and D both exist");
1542 xfstat_isreg(file_d->fd, &stab_d, "ductfile");
1544 if (samefile(&stab_d, &stab_f)) {
1545 debug("startup: F==D => Hardlinked");
1546 r= unlink(path_duct);
1547 if (r) sysdie("unlink feed file %s during startup", feedfile);
1550 startup_set_input_file(file_d);
1551 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1553 debug("F!=D => Separated");
1554 SMS(SEPARATED, 0, "found both old and current feed files");
1555 startup_set_input_file(file_d);
1558 debug("startup: D ENOENT => Nothing");
1559 SMS(WAITING, open_wait_periods, "no feed file currently exists");
1563 static void statemc_poll(void) {
1564 if (sms==sm_WAITING) { statemc_waiting_poll(); return; }
1566 if (!sm_period_counter) return;
1567 sm_period_counter--;
1568 assert(sm_period_counter>=0);
1570 if (sm_period_counter) return;
1573 fatal("timed out waiting for innd to create feed file %s", feedfile);
1575 spawn_inndcomm_flush(void);
1582 static void statemc_waiting_poll(void) {
1583 InputFile *file_f= open_input_file(feedfile);
1584 if (!file_f) return;
1585 startup_set_input_file(file_d);
1586 SMS(NORMAL, 0, "found and opened feed file");
1589 static void startup_set_input_file(InputFile *f) {
1590 assert(!main_input_file);
1592 inputfile_tailing_start(f);
1595 static void *statemc_check_input_done(oop_source *lp,
1596 struct timeval now, void *ipf_v) {
1597 InputFile *ipf= ipf_v;
1600 if (ipf->inprogress) return; /* new article in the meantime */
1601 if (ipf->fd >= 0); return; /* not had EOF */
1603 if (ipf == backlog_input_file) {
1604 notice_processed(ipf,"backlog file",ipf->path);
1605 close_input_file(ipf);
1606 if (unlink(ipf->path)) {
1607 if (errno != ENOENT)
1608 sysdie("could not unlink processed backlog file %s", ipf->path);
1609 warn("backlog file %s vanished while we were reading it"
1610 " so we couldn't remove it (but it's done now, anyway)",
1613 backlog_input_file= 0;
1614 search_backlog_file();
1618 assert(ipf == old_input_file);
1619 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1621 notice_processed(ipf,"feed file",0);
1625 if (unlink(path_duct))
1626 sysdie("could not unlink old duct file %s", path_duct);
1628 if (sms==sm_DROPPING) {
1629 if (search_backlog_file()) {
1630 debug("feed dropped but still backlogs to process");
1633 notice("feed dropped and our work is complete");
1634 r= unlink(path_ductlock);
1635 if (r) sysdie("unlink lock file for old feed %s", path_ductlock);
1641 close_input_file(old_input_file);
1644 notice("flush complete");
1645 SMS(NORMAL, 0, "flush complete");
1648 static void statemc_setstate(StateMachineState newsms, int periods,
1649 const char *forlog, const char *why) {
1651 sm_period_counter= periods;
1653 info("%s[%d] %s",periods,forlog,why);
1655 info("%s %s",forlog,why);
1659 /*---------- defer and backlog files ----------*/
1661 static void open_defer(void) {
1666 defer= fopen(path_ductdefer, "a+");
1667 if (!defer) sysfatal("could not open defer file %s", path_ductdefer);
1669 /* truncate away any half-written records */
1671 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1673 if (stab.st_size > LONG_MAX)
1674 die("defer file %s size is far too large", path_ductdefer);
1679 long orgsize= stab.st_size;
1680 long truncto= stab.st_size;
1682 if (!truncto) break; /* was only (if anything) one half-truncated record */
1683 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1684 sysdie("seek in defer file %s while truncating partial", path_ductdefer);
1689 sysdie("failed read from defer file %s", path_ductdefer);
1691 die("defer file %s shrank while we were checking it!", path_ductdefer);
1697 if (stab.st_size != truncto) {
1698 warn("truncating half-record at end of defer file %s -"
1699 " shrinking by %ld bytes from %ld to %ld",
1700 path_ductdefer, orgsize - truncto, orgsize, truncto);
1703 sysfatal("could not flush defer file %s", path_ductdefer);
1704 if (ftruncate(fileno(defer), truncto))
1705 sysdie("could not truncate defer file %s", path_ductdefer);
1708 info("continuing existing defer file %s (%ld bytes)",
1709 path_ductdefer, orgsize);
1711 if (fseek(defer, truncto, SEEK_SET))
1712 sysdie("could not seek to new end of defer file %s", path_ductdefer);
1715 static void close_defer(void) {
1719 xfstat(fileno(defer), &stab, "defer file");
1721 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1724 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1725 (unsigned long)now.tv_sec,
1726 (unsigned long)stab.st_ino);
1727 if (link(path_defer, path_backlog))
1728 sysfatal("could not install defer file %s as backlog file %s",
1729 path_defer, backlog);
1730 if (unlink(path_defer))
1731 sysdie("could not unlink old defer link %s to backlog file %s",
1732 path_defer, backlog);
1734 if (backlog_nextscan_periods < 0 ||
1735 backlog_nextscan_periods > backlog_retry_minperiods + 1)
1736 backlog_nextscan_periods= backlog_retry_minperiods + 1;
1739 static void poll_backlog_file(void) {
1740 if (backlog_nextscan_periods < 0) return;
1741 if (backlog_nextscan_periods-- > 0) return;
1742 search_backlog_file();
1745 static int search_backlog_file(void) {
1746 /* returns non-0 iff there are any backlog files */
1751 const char *oldest_path=0;
1752 time_t oldest_mtime, now;
1754 if (backlog_input_file) return 3;
1758 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
1762 sysdie("failed to expand backlog pattern %s", globpat_backlog);
1764 die("out of memory expanding backlog pattern %s", globpat_backlog);
1766 for (i=0; i<gl.gl_pathc; i++) {
1767 const char *path= gl.gl_pathv[i];
1768 r= stat(path, &stab);
1770 syswarn("failed to stat backlog file %s", path);
1773 if (!S_ISREG(stab.st_mode)) {
1774 warn("backlog file %s is not a plain file (or link to one)", path);
1777 if (!oldest_path || stab.st_mtime < oldest_mtime) {
1779 oldest_mtime= stab.st_mtime;
1782 case GLOB_NOMATCH: /* fall through */
1785 sysdie("glob expansion of backlog pattern %s gave unexpected"
1786 " nonzero (error?) return value %d", globpat_backlog, r);
1792 debug("backlog scan: none");
1793 backlog_nextscan_periods= backlog_spontaneous_rescan_periods;
1797 now= time(); if (now==-1) sysdie("time(2) failed");
1798 double age= difftime(now, oldest_mtime);
1799 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
1801 if (age_deficiency <= 0) {
1802 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
1803 age, age_deficiency, oldest_path);
1805 backlog_input_file= open_input_file();
1806 if (!backlog_input_file) {
1807 warn("backlog file %s vanished as we opened it", backlog_input_file);
1810 inputfile_tailing_start(backlog_input_file);
1811 backlog_nextscan_periods= -1;
1815 backlog_nextscan_periods= age_deficiency / PERIOD_SECONDS;
1817 if (backlog_spontaneous_rescan_periods >= 0 &&
1818 backlog_nextscan_periods > backlog_spontaneous_rescan_periods)
1819 backlog_nextscan_periods= backlog_spontaneous_rescan_periods;
1821 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
1822 age, age_deficiency, backlog_nextscan_periods, oldest_path);
1826 /*========== flushing the feed ==========*/
1828 static pid_t inndcomm_child;
1830 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1831 assert(inndcomm_child);
1832 int status= xwaitpid(&inndcomm_child, "inndcomm");
1833 loop->cancel_fd(fd);
1836 assert(!old_input_file);
1838 if (WIFEXITED(status)) {
1839 switch (WEXITSTATUS(status)) {
1841 case INNDCOMMCHILD_ESTATUS_FAIL:
1844 case INNDCOMMCHILD_ESTATUS_NONESUCH:
1845 warn("feed has been dropped by innd, finishing up");
1846 old_input_file= main_input_file;
1848 SMS(DROPPING, 0, "dropped by innd");
1849 return OOP_CONTINUE;
1852 old_input_file= main_input_file;
1853 main_input_file= open_input_file(feedfile);
1854 if (!main_input_file)
1855 die("flush succeeded but feedfile %s does not exist!", feedfile);
1856 SMS(SEPARATED, 0, "feed file missing");
1857 return OOP_CONTINUE;
1860 goto unexpected_exitstatus;
1863 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1864 warn("flush timed out trying to talk to innd");
1867 unexpected_exitstatus:
1868 report_child_status("inndcomm child", status);
1872 SMS(FLUSHFAIL, flushfail_retry_periods, "flush failed, will retry");
1875 static void inndcommfail(const char *what) {
1876 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1877 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1880 void spawn_inndcomm_flush(void) {
1883 assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1884 assert(!inndcomm_child);
1886 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1888 inndcomm_child= xfork();
1890 if (!inndcomm_child) {
1891 static char flushargv[2]= { sitename, 0 };
1896 alarm(inndcomm_flush_timeout);
1897 r= ICCopen(); if (r) inndcommfail("connect");
1898 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
1899 if (!r) exit(0); /* yay! */
1901 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1902 syswarn("innd ctlinnd flush failed: innd said %s", reply);
1903 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1907 int sentinel_fd= pipefds[0];
1908 on_fd_read_except(sentinel_fd, inndcomm_event);
1910 SMS(FLUSHING, 0, "flush is in progress");
1913 /*========== main program ==========*/
1915 static void postfork_inputfile(InputFile *ipf) {
1917 assert(ipf->fd >= 0);
1922 static void postfork_conns(Connection *conn) {
1929 static void postfork_stdio(FILE *f) {
1930 /* we have no stdio streams that are buffered long-term */
1934 static void postfork(const char *what) {
1935 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1936 sysdie("%s child: failed to reset SIGPIPE");
1938 postfork_inputfile(main_input_file);
1939 postfork_inputfile(old_input_file);
1940 postfork_conns(idle.head);
1941 postfork_conns(working.head);
1942 postfork_conns(full.head);
1943 postfork_stdio(defer);
1946 #define EVERY(what, interval, body) \
1947 static const struct timeval what##_timeout = { 5, 0 }; \
1948 static void what##_schedule(void); \
1949 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1951 what##_schedule(); \
1953 static void what##_schedule(void) { \
1954 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
1957 EVERY(filepoll, {5,0}, {
1958 if (main_input_file && main_input_file->readable_callback)
1959 filemon_callback(main_input_file);
1962 EVERY(period, {PERIOD_SECONDS,0}, {
1963 if (connect_delay) connect_delay--;
1964 poll_backlog_file();
1965 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
1967 check_master_queue();
1971 /*========== option parsing ==========*/
1974 of_seconds= 001000u;
1975 of_boolean= 002000u;
1978 typedef struct Option Option;
1979 typedef void OptionParser(const Option*, const char *val);
1989 void op_integer(const Option *o, const char *val) {
1992 unsigned long ul= strtoul(val,&ep,10);
1993 if (*ep || ep==val || errno || ul>INT_MAX)
1994 badusage("bad integer value for %s",o->long);
1995 int *store= o->store;
1999 void op_double(const Option *o, const char *val) {
2000 int *store= o->store;
2003 *store= strtod(val, &ep);
2004 if (*ep || ep==val || errno)
2005 badusage("bad floating point value for %s",o->long);
2008 void op_string(const Option *o, const char *val) {
2009 char **store= o->store;
2014 void op_seconds(const Option *o, const char *val) {
2015 int *store= o->store;
2018 double v= strtod(val,&ep);
2019 if (ep==val) badusage("bad time/duration value for %s",o->long);
2021 if (!*ep || !strcmp(ep,"s")) unit= 1;
2022 else if (!strcmp(ep,"m")) unit= 60;
2023 else if (!strcmp(ep,"h")) unit= 3600;
2024 else if (!strcmp(ep,"d")) unit= 86400;
2025 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2029 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2033 void op_periods_rndup(const Option *o, const char *val) {
2034 int *store= o->store;
2036 *store += PERIOD_SECONDS-1;
2037 *store /= PERIOD_SECONDS;
2040 void op_periods_booltrue(const Option *o, const char *val) {
2041 int *store= o->store;
2044 void op_periods_boolfalse(const Option *o, const char *val) {
2045 int *store= o->store;
2049 static const Option options[]= {
2050 { 0, "max-connections", &max_connections op_integer },
2051 { 0, "streaming", &try_stream, op_booltrue, 1 },
2052 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2053 {'h',"host", &remote_host, op_string },
2054 {'P',"port", &port op_integer },
2055 { 0, "inndconf", &inndconffile, op_string },
2056 {'f',"feedfile", &feedfile, op_string },
2057 {'q',"quiet-multiple", &quiet_if_locked, op_booltrue, 1 },
2058 { 0, "no-quiet-multiple", &quiet_if_locked, op_boolfalse, 1 },
2059 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2060 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2062 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2063 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2065 { 0, "max-queue-size", &max_queue_per_conn op_integer },
2066 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2067 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2068 { 0, "feedfile-open-timeout", &open_wait_periods, op_periods_rndup },
2069 { 0, "connection-timeout", &connection_timeout, op_seconds },
2070 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2073 int main(int argc, char **argv) {
2079 if (*arg != '-') break;
2080 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2082 while ((a= *++arg)) {
2086 char *equals= strchr(arg,'=');
2087 int len= equals ? (equals - arg) : strlen(arg);
2088 for (o=options; o->long; o++)
2089 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2091 badusage("unknown long option --%s",arg);
2094 if (equals) badusage("option --%s does not take a value",o->long);
2096 } else if (equals) {
2100 if (!arg) badusage("option --%s needs a value",o->long);
2103 break; /* eaten the whole argument now */
2105 for (o=options; o->long; o++)
2108 badusage("unknown short option -%c",a);
2115 if (!arg) badusage("option -%c needs a value",o->short);
2118 break; /* eaten the whole argument now */
2123 if (!arg) badusage("need site name argument");
2124 if (*++argv) badusage("too many non-option arguments");
2127 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2128 badusage("nocheck threshold percentage must be between 0..100");
2129 nocheck_thresh= nocheck_thresh_pct * 0.01;
2131 if (nocheck_decay_articles < 0.1)
2132 badusage("nocheck decay articles must be at least 0.1");
2133 nocheck_decay= 1 - 1/nocheck_decay_articles;
2135 innconf_read(inndconffile);
2138 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2139 else if (!feedfile[0])
2140 badusage("feed filename must be nonempty");
2141 else if (feedfile[strlen(feedfile)-1]=='/')
2142 feedfile= xasprintf("%s%s",feedfile,sitename);
2144 const char *feedfile_forbidden= "?*[";
2146 while ((c= *feedfile_forbidden++))
2147 if (strchr(feedfile, c))
2148 badusage("feed filename may not contain glob metacharacter %c",c);
2150 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2151 sysdie("could not ignore SIGPIPE");
2153 if (become_daemon) {
2154 for (i=3; i<255; i++)
2155 /* do this now before we open syslog, etc. */
2157 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2159 int null= open("/dev/null",O_RDWR);
2160 if (null<0) sysdie("failed to open /dev/null");
2166 pid_t child1= xfork("daemonise first fork");
2167 if (child1) _exit(0);
2169 pid_t sid= setsid();
2170 if (sid != child1) sysdie("setsid failed");
2172 pid_t child2= xfork("daemonise second fork");
2173 if (child2) _exit(0);
2178 if (!filemon_init()) {
2179 warn("no file monitoring available, polling");
2180 filepoll_schedule();