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.
67 <--------------------------------------'|
68 Nothing F, D both ENOENT |
71 duct: not not reading anything |
73 |`---------------------. |
74 | | duct times out waiting for F |
75 V innd creates F | duct exits |
77 Noduct GO TO Dropped |
80 duct: not running or not reading anything |
83 ,-->--+ <---------------------------------'|
84 | | duct opens F F exists |
88 | F: innd writing, duct reading |
91 | | duct decides time to flush |
92 | | duct makes hardlink |
94 | V <------------------------'|
96 | F == D: innd writing, duct reading both exist |
100 | Moved <----+------------<--'|
101 | F: ENOENT | F ENOENT |
102 | D: innd writing, duct reading | D exists |
104 | | duct requests flush of feed | |
105 | | (others can too, harmlessly) | |
109 | D: innd flushing, duct reading | |
111 | | inndcomm flush fails | |
112 | |`-------------------------->---------' |
114 | | inndcomm reports no such site |
115 | |`---------------------------------------------------- | -.
117 | | innd finishes writing D, creates F | |
118 | | inndcomm reports flush successful | |
121 | Separated <----------------' |
122 | F: innd writing F!=D /
123 | D: duct reading both exist /
125 | | duct gets to the end of D /
126 | | duct opens F too /
129 | F: innd writing, duct reading |
130 | D: duct finishing V
132 | | duct finishes processing D F: ENOENT
133 | V duct unlinks D D: duct reading
135 `--<--' | duct finishes
145 "duct reading" means innduct is reading the file but also
146 overwriting processed tokens.
153 /*----- general definitions, probably best not changed -----*/
155 #define PERIOD_SECONDS 60
157 #define CONNCHILD_ESTATUS_STREAM 4
158 #define CONNCHILD_ESTATUS_NOSTREAM 5
160 #define INNDCOMMCHILD_ESTATUS_FAIL 6
161 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
164 /*----- configuration options -----*/
166 static char *sitename, *feedfile;
167 static int max_connections=10, max_queue_per_conn=200;
168 static int connection_setup_timeout=200, port=119, try_stream=1;
169 static int inndcomm_flush_timeout=100, quiet_if_locked=0;
170 static const char *remote_host;
171 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
172 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
173 static const char *inndconffile;
175 static double accept_proportion;
176 static double nocheck_thresh_pct= 95.0;
177 static double nocheck_thresh; /* computed in main from _pct */
178 static double nocheck_decay_articles= 100; /* converted to _decay */
179 static double nocheck_decay; /* computed in main from _articles */
180 static int nocheck, nocheck_reported;
183 /*----- doubly linked lists -----*/
185 #define ISNODE(T) T *next, *back;
186 #define LIST(T) struct { T *head, *tail, *tailpred; int count; }
188 #define NODE(n) ((struct node*)&(n)->head)
190 #define LIST_ADDHEAD(l,n) \
191 (list_addhead((struct list*)&(l), NODE((n))), (void)(l).count++)
192 #define LIST_ADDTAIL(l,n) \
193 (list_addtail((struct list*)&(l), NODE((n))), (void)(l).count++)
195 #define LIST_REMHEAD(l) \
196 ((l).count ? ((l).count--, (void*)list_remhead((struct list*)&(l))) : 0)
197 #define LIST_REMTAIL(l) \
198 ((l).count ? ((l).count--, (void*)list_remtail((struct list*)&(l))) : 0)
199 #define LIST_REMOVE(l,n) \
200 (list_remove(NODE((n))), (void)(l).count--)
201 #define LIST_INSERT(l,n,pred) \
202 (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
205 /*----- statistics -----*/
207 #define RESULT_COUNTS \
216 #define RC_INDEX(x) RCI_##x
222 int articles[2 /* checked */][RCI_max];
226 /*----- transmission buffers -----*/
231 xk_Malloc, xk_Const, xk_Artdata;
243 /*----- core operational data structure types -----*/
247 int checked, sentbody;
255 typedef struct InputFile {
256 /* This is an instance of struct oop_readable */
257 struct oop_readable readable; /* first */
258 oop_readable_call *readable_callback;
259 void *readable_callback_user;
262 struct Filemon_Perfile *filemon;
265 long inprogress; /* no. of articles read but not processed */
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 -----*/
294 static int since_connect_attempt;
296 static LIST(Conn) idle, working, full;
297 static LIST(Article) *queue;
299 static char *path_lock, *path_flushing, *path_defer;
301 #define SMS(newstate, periods, why) \
302 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
304 static StateMachineState sms;
306 static InputFile *main_input_file, *old_input_file, *backlog_input_file;
307 static int sm_period_counter;
310 /*----- function predeclarations -----*/
312 static void conn_check_work(Conn *conn);
314 static int filemon_init(void);
315 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
316 static void filemon_callback(void);
318 static void statemc_setstate(StateMachineState newsms, int periods,
319 const char *forlog, const char *why);
321 /*========== utility functions etc. ==========*/
323 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
325 static pid_t xfork(const char *what) {
329 if (child==-1) sysdie("cannot fork for %s",what);
330 if (!child) postfork(what);
334 static void on_fd_read_except(int fd, oop_call_fd callback) {
335 loop->on_fd(loop, fd, OOP_READ, callback, 0);
336 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
338 static void cancel_fd_read_except(int fd) {
339 loop->cancel_fd(loop, fd, OOP_READ);
340 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
343 static void report_child_status(const char *what, int status) {
344 if (WIFEXITED(status)) {
345 int es= WEXITSTATUS(status);
347 warn("%s: child died with error exit status %d",es);
348 } else if (WIFSIGNALED(status)) {
349 int sig= WTERMSIG(status);
350 const char *sigstr= strsignal(sig);
351 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
353 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
355 warn("%s: child died due to unknown fatal signal %d%s",
356 what, sig, coredump);
358 warn("%s: child died with unknown wait status %d", status);
362 static int xwaitpid(pid_t *pid, const char *what) {
365 r= kill(*pid, SIGKILL);
366 if (r) sysdie("cannot kill %s child", what);
368 pid_t got= waitpid(*pid, &status, WNOHANG);
369 if (got==-1) sysdie("cannot reap %s child", what);
376 static void check_isreg(const struct stat *stab, const char *path,
378 if (!S_ISREG(stab->st_mode))
379 die("%s %s not a plain file (mode 0%lo)",
380 what, path, (unsigned long)stab->st_mode);
383 static void xfstat(int fd, struct stat *stab_r, const char *what) {
384 int r= fstab(path, stab);
385 if (r) sysdie("could not fstat %s %s", what, path);
388 static void xfstat_isreg(int fd, struct stat *stab_r, const char *what) {
389 xfstat(fd, stab_r, what);
390 check_isreg(stab, path, what);
393 static void xlstat_isreg(const char *path, struct stat *stab,
394 int *enoent_r /* 0 means ENOENT is fatal */
396 int r= lstat(path, stab);
398 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
399 sysdie("could not lstat %s %s", what, path);
401 if (enoent_r) *enoent_r= 0;
402 check_isreg(stab, path, what);
405 static int samefile(const struct stat *a, const struct stat *b) {
406 assert(S_ISREG(a->st_mode));
407 assert(S_ISREG(b->st_mode));
408 return (a->st_ino == b->st_ino &&
409 a->st_dev == b->st_dev);
412 /*========== logging ==========*/
414 static void logcore(int sysloglevel, const char *fmt, ...)
415 __attribute__((printf,2,3))
416 static void logcore(int sysloglevel, const char *fmt, ...) {
420 vsyslog(sysloglevel,fmt,al);
422 vfprintf(stderr,fmt,al);
427 static void logv(int sysloglevel, const char *pfx, int errnoval,
428 int exitstatus, const char *fmt, va_list al)
429 __attribute__((printf,4,0))
430 static void logv(int sysloglevel, const char *pfx, int errnoval,
431 int exitstatus, const char *fmt, va_list al) {
433 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
434 msgbuf[sizeof(msgbuf)-1]= 0;
436 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
437 sysloglevel= LOG_ERR; /* run by wrong user, probably */
439 logcore(sysloglevel, "<%s>%s: %s%s%s",
440 sitename, pfx, msgbuf,
441 errnoval>=0 ? ": " : "",
442 errnoval>=0 ? strerror(errnoval) : "");
445 #define logwrap(fn, pfx, sysloglevel, errno, estatus) \
446 static void fn(const char *fmt, ...) \
447 __attribute__((printf,1,2)); \
448 static void fn(const char *fmt, ...) { \
451 logv(sysloglevel, pfx, errno, estatus, fmt, al); \
454 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
455 logwrap(die, " critical", LOG_CRIT, -1, 16);
457 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
458 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
460 logwrap(syswarn, " warning", LOG_WARN, errno, 0);
461 logwrap(warn, " warning", LOG_WARN, -1, 0);
463 logwrap(notice, "", LOG_NOTICE, -1, 0);
464 logwrap(info, " info", LOG_INFO, -1, 0);
467 /*========== making new connections ==========*/
469 static int connecting_sockets[2]= {-1,-1};
470 static pid_t connecting_child;
472 static void connect_attempt_discard(void) {
473 if (connecting_sockets[0])
474 cancel_fd(connecting_sockets[0]);
476 perhaps_close(&connecting_sockets[0]);
477 perhaps_close(&connecting_sockets[1]);
479 if (connecting_child) {
480 int status= xwaitpid(&connecting_child, "connect");
482 if (!(WIFEXITED(status) ||
483 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
484 report_child_status("connect", status);
488 #define PREP_DECL_MSG_CMSG(msg) \
490 memset(&msg,0,sizeof(msg)); \
491 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
492 msg.msg_control= msg##cbuf; \
493 msg.msg_controllen= sizeof(msg##cbuf);
495 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
498 conn= xmalloc(sizeof(*conn));
499 memset(conn,0,sizeof(*conn));
502 struct cmsghdr *h= 0;
503 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
504 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
507 pid_t got= waitpid(connecting_child, &status, WNOHANG);
509 assert(got==connecting_child);
511 if (WIFEXITED(status) &&
512 (WEXITSTATUS(status) != 0
513 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
514 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
515 /* child already reported the problem */
516 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
517 warn("connect: connection attempt timed out");
518 } else if (!WIFEXITED(status)) {
519 report_child_status("connect", status);
520 /* that's probably the root cause then */
523 /* child is still running apparently, report the socket problem */
525 syswarn("connect: read from child socket failed");
526 else if (e == OOP_EXCEPTIONN)
527 warn("connect: unexpected exception on child socket");
529 warn("connect: unexpected EOF on child socket");
534 #define CHK(field, val) \
535 if (h->cmsg_##field != val) { \
536 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
539 CHK(level, SOL_SOCKET);
540 CHK(type, SCM_RIGHTS);
541 CHK(len, CMSG_LEN(sizeof(conn-b>fd)));
544 if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
546 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
548 pid_t got= waitpid(connecting_child, &status, 0);
549 if (got==-1) sysdie("connect: real wait for child");
550 assert(got == connecting_child);
553 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
554 int es= WEXITSTATUS(status);
556 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
557 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
559 fatal("connect: child gave unexpected exit status %d", es);
565 LIST_ADDHEAD(idle, conn);
566 notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
567 connect_attempt_discard();
568 check_master_queue();
573 perhaps_close(&conn->fd);
576 connect_attempt_discard();
579 static void connect_start() {
580 assert(!connecting_sockets[0]);
581 assert(!connecting_sockets[1]);
582 assert(!connecting_child);
584 notice("starting connection attempt");
586 r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
587 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
589 connecting_child= xfork("connection");
591 if (!connecting_child) {
592 FILE *cn_from, *cn_to;
593 char buf[NNTP_STRLEN+100];
594 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
596 r= close(connecting_sockets[0]);
597 if (r) sysdie("connect: close parent socket in child");
599 alarm(connection_setup_timeout);
600 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
602 sanitise_inplace(buf);
603 fatal("connect: rejected: %s", buf);
605 sysfatal("connect: connection attempt failed");
608 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
609 sysfatal("connect: authentication failed");
611 if (fputs("MODE STREAM\r\n", cn_to) ||
613 sysfatal("connect: could not send MODE STREAM");
614 buf[sizeof(buf)-1]= 0;
615 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
617 sysfatal("connect: could not read response to MODE STREAM");
619 fatal("connect: connection close in response to MODE STREAM");
624 sanitise_inplace(buf);
625 fatal("connect: response to MODE STREAM is too long: %.100s...",
628 l--; if (l>0 && buf[1-]=='\r') l--;
631 int rcode= strtoul(buf,&ep,10);
633 sanitise_inplace(buf);
634 fatal("connect: bad response to MODE STREAM: %.50s", buf);
638 exitstatus= CONNCHILD_ESTATUS_STREAM;
644 sanitise_inplace(buf);
645 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
650 int fd= fileno(cn_from);
652 PREP_DECL_MSG_CMSG(msg);
653 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
654 cmsg->cmsg_level= SOL_SOCKET;
655 cmsg->cmsg_type= SCM_RIGHTS;
656 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
657 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
659 msg.msg_controllen= cmsg->cmsg_len;
660 r= sendmsg(connecting_sockets[1], &msg, 0);
661 if (r) sysdie("sendmsg failed for new connection");
666 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
667 if (r) sysdie("connect: close child socket in parent");
669 on_fd_read_except(connecting_sockets[0], connchild_event);
673 connect_attempt_discard();
677 /*========== overall control of article flow ==========*/
679 static void check_master_queue(void) {
683 Conn *last_assigned=0;
686 conn_assign_one_article(&working, &last_assigned);
687 } else if (idle.head) {
688 conn_assign_one_article(&idle, &last_assigned);
689 } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
690 !connecting_child && !connect_delay) {
691 connect_delay= reconnect_delay_periods;
697 conn_check_work(last_assigned);
700 static void conn_assign_one_article(LIST(Conn) *connlist,
701 Conn **last_assigned) {
702 Conn *conn= connlist->head;
704 LIST_REMOVE(*connlist, conn);
705 Article *art= LIST_REMHEAD(queue);
706 LIST_ADDTAIL(conn->queue, art);
707 LIST_ADD(*conn_determine_right_list(conn), conn);
709 /* This slightly odd arrangement is so that we call conn_check_work
710 * once after filling the queue for a new connection in
711 * check_master_queue, rather than for each article. */
712 if (conn != *last_assigned && *last_assigned)
713 conn_check_work(*last_assigned);
714 *last_assigned= conn;
717 static int conn_total_queued_articles(Conn *conn) {
718 return conn->sent.count + conn->queue.count;
721 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
722 int inqueue= conn_total_queued_articles(conn);
723 assert(inqueue <= max_queue);
724 if (inqueue == 0) return &idle;
725 if (inqueue == conn->max_queue) return &full;
729 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
734 static void conn_check_work(Conn *conn) {
737 conn_make_some_xmits(conn);
739 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
743 void *rp= conn_write_some_xmits(conn);
744 if (rp==OOP_CONTINUE) {
745 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
747 } else if (rp==OOP_HALT) {
750 /* transmitted everything */
758 /*========== article transmission ==========*/
760 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
761 XmitKind kind) { /* caller must then fill in details */
762 struct iovec *v= &conn->xmit[conn->xmitu];
763 XmitDetails *d= &conn->xmitd[conn->xmitu++];
770 static void xmit_noalloc(Conn *conn, const char *data, int len) {
771 xmit_core(conn,data,len, xk_Const);
773 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
775 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
776 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
780 static void xmit_free(XmitDetails *d) {
782 case xk_Malloc: free(d->info.malloc_tofree); break;
783 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
784 case xk_Const: break;
789 static void *conn_write_some_xmits(Conn *conn) {
791 * 0: nothing more to write, no need to call us again
792 * OOP_CONTINUE: more to write but fd not writeable
793 * OOP_HALT: disaster, have destroyed conn
796 int count= conn->xmitu;
797 if (!count) return 0;
799 if (count > IOV_MAX) count= IOV_MAX;
800 ssize_t rs= writev(conn->fd, conn->xmit, count);
802 if (errno == EAGAIN) return OOP_CONTINUE;
803 connfail(conn, "write failed: %s", strerror(errno));
808 for (done=0; rs && done<xmitu; done++) {
809 struct iovec *vp= &conn->xmit[done];
810 XmitDetails *dp= &conn->xmitd[done];
811 if (rs > vp->iov_len) {
819 int newu= conn->xmitu - done;
820 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
821 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
826 static void conn_make_some_xmits(Conn *conn) {
828 if (conn->xmitu+5 > CONNIOVS)
831 Article *art= LIST_REMHEAD(queue);
834 if (art->checked || (conn->stream && nocheck)) {
835 /* actually send it */
837 ARTHANDLE *artdata= SMretrieve();
841 XMIT_LITERAL("TAKETHIS ");
842 xmit_noalloc(conn, art->mid, art->midlen);
843 XMIT_LITERAL("\r\n");
844 xmit_artbody(conn, artdata);
847 /* we got 235 from IHAVE */
849 xmit_artbody(conn, artdata);
851 XMIT_LITERAL(".\r\n");
856 LIST_ADDTAIL(conn->sent, art);
858 art->ipf->counts[art->checked].sent++;
864 XMIT_LITERAL("IHAVE ");
866 XMIT_LITERAL("CHECK ");
867 xmit_noalloc(art->mid, art->midlen);
868 XMIT_LITERAL("\r\n");
870 LIST_ADDTAIL(conn->sent, art);
871 art->ipf->counts[art->checked].offered++;
877 /*========== handling responses from peer ==========*/
879 static const oop_rd_style peer_rd_style= {
880 OOP_RD_DELIM_STRIP, '\n',
882 OOP_RD_SHORTREC_FORBID
885 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
886 const char *errmsg, int errnoval,
887 const char *data, size_t recsz, void *conn_v) {
889 connfail(conn, "error receiving from peer: %s", errmsg);
893 static Article *article_reply_check(Connection *conn, const char *response,
894 int code_indicates_streaming,
895 const char *sanitised_response) {
896 Article *art= LIST_REMHEAD(conn->sent);
900 "peer gave unexpected response when no commands outstanding: %s",
905 if (code_indicates_streaming) {
906 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
908 connfail("peer gave streaming response code "
909 " to IHAVE or subsequent body: %s", sanitised_response);
912 const char *got_mid= response+4;
913 int got_midlen= strcspn(got_mid, " \n\r");
914 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
915 connfail("peer gave streaming response with syntactically invalid"
916 " messageid: %s", sanitised_response);
919 if (got_midlen != art->midlen ||
920 memcmp(got_mid, art->messageid, got_midlen)) {
921 connfail("peer gave streaming response code to wrong article -"
922 " probable synchronisation problem; we offered: %s;"
924 art->messageid, sanitised_response);
929 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
938 static void update_nocheck(int accepted) {
939 accept_proportion *= accept_decay;
940 accept_proportion += accepted;
941 nocheck= accept_proportion >= nocheck_thresh;
942 if (nocheck && !nocheck_reported) {
943 notice("entering nocheck mode for the first time");
948 static void article_done(Connection *conn, Article *art, int whichcount) {
950 art->ipf->counts.articles[art->checked][whichcount]++;
951 if (whichcount == RC_accepted) update_nocheck(1);
952 else if (whichcount == RC_unwanted) update_nocheck(0);
954 InputFile *ipf= art->ipf;
955 while (art->blanklen) {
956 static const char spaces[]=
961 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
962 int r= pwrite(ipf->fd, spaces, w, art->offset);
964 if (errno==EINTR) continue;
965 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
966 art->messageid, art->blanklen, art->offset, ipf->path);
968 assert(r>=0 && r<=w);
974 assert(ipf->inprogress >= 0);
976 if (!ipf->inprogress)
977 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, ipf);
982 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
983 const char *errmsg, int errnoval,
984 const char *data, size_t recsz, void *conn_v) {
987 if (ev == OOP_RD_EOF) {
988 connfail(conn, "unexpected EOF from peer");
991 assert(ev == OOP_RD_OK);
994 unsigned long code= strtoul(data, &ep, 10);
995 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1001 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
1003 if (!c) { *q++= '\''; break; }
1004 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
1005 sprintf(q,"\\x%02x",c);
1008 connfail(conn, "badly formatted response from peer: %s", sanibuf);
1009 return OOP_CONTINUE;
1012 if (conn->quitting) {
1014 connfail(conn, "peer gave failure response to QUIT: %s", sani);
1015 return OOP_CONTINUE;
1023 #define GET_ARTICLE \
1024 art= article_reply_check(conn, data, code_streaming, sani); \
1025 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1027 #define ARTICLE_DEALTWITH(streaming,how) \
1028 code_streaming= (streaming) \
1030 article_done(conn, art, RC_##how); break;
1032 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1034 int code_streaming= 0;
1038 case 400: PEERBADMSG("peer stopped accepting articles");
1039 case 503: PEERBADMSG("peer timed us out");
1040 default: PEERBADMSG("peer sent unexpected message");
1042 case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
1043 case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
1045 case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
1046 case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
1048 case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
1049 case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
1051 case 238: /* CHECK says send it */
1053 case 335: /* IHAVE says send it */
1055 count_checkedwanted++;
1056 LIST_ADDTAIL(conn->queue);
1058 connfail("peer gave %d response to article body: %s",code, sani);
1059 return OOP_CONTINUE;
1064 case 431: /* CHECK or TAKETHIS says try later */
1066 case 436: /* IHAVE says try later */
1069 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1071 sysfatal("write to defer file %s",path_defer);
1072 article_done(conn, art, RC_deferred);
1077 check_check_work(conn);
1078 return OOP_CONTINUE;
1082 /*========== monitoring of input files ==========*/
1084 static void feedfile_eof(InputFile *ipf) {
1085 assert(ipf != main_input_file); /* promised by tailing_try_read */
1087 inputfile_tailing_stop(ipf);
1089 if (ipf == backlog_input_file) {
1090 assert(ipf->fd >= 0);
1091 if (close(ipf->fd)) sysdie("could not close backlog file %s", ipf->path);
1096 assert(ipf == old_input_file);
1098 inputfile_tailing_stop(ipf);
1099 assert(ipf->fd >= 0);
1100 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1103 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1105 if (main_input_file)
1106 inputfile_tailing_start(main_input_file);
1109 static InputFile *open_input_file(const char *path) {
1110 int fd= open(path, O_RDONLY);
1112 if (errno==ENOENT) return 0;
1113 sysfatal("unable to open input file %s", path);
1116 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1117 memset(ipf,0,sizeof(*ipf));
1119 ipf->readable.on_readable= tailing_on_readable;
1120 ipf->readable.on_cancel= tailing_on_cancel;
1121 ipf->readable.try_read= tailing_try_read;
1124 strcpy(ipf->path, path);
1129 static void close_input_file(InputFile *ipf) {
1130 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1131 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1132 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1133 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1136 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1142 /*---------- dealing with articles read in the input file ----------*/
1144 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1145 oop_rd_event ev, const char *errmsg,
1147 const char *data, size_t recsz,
1149 InputFile *ipf= ipf_v;
1151 char tokentextbuf[sizeof(TOKEN)*2+3];
1153 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1155 if (data[0] && data[0]!=' ') {
1156 char *space= strchr(data,' ');
1157 int tokenlen= space-data;
1158 int midlen= (int)recsz-tokenlen-1;
1159 if (midlen < 0) goto bad_data;
1161 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1162 memcpy(tokentextbuf, data, tokenlen);
1163 tokentextbuf[tokenlen]= 0;
1164 if (!IsToken(tokentextbuf)) goto bad_data;
1166 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1167 art->offset= ipf->offset;
1168 art->blanklen= recsz;
1169 art->midlen= midlen;
1170 art->checked= art->sentbody= 0;
1171 art->ipf= ipf; ipf->inprogress++;
1172 art->token= TextToToken(tokentextbuf);
1173 strcpy(art->messageid, space+1);
1174 LIST_ADDTAIL(queue, art);
1176 ipf->offset += recsz + 1;
1178 if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
1179 notice("starting flush (%lu >= %lu)",
1180 (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1182 int r= link(feedfile, duct_path);
1183 if (r) sysdie("link feedfile %s to flushing file %s", feedfile, dut_path);
1186 r= unlink(feedfile);
1187 if (r) sysdie("unlink old feedfile link %s", feedfile);
1190 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1193 check_master_queue();
1197 /*========== tailing input file ==========*/
1199 static void filemon_start(InputFile *ipf) {
1200 assert(!ipf->filemon);
1202 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1203 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1204 filemon_method_startfile(ipf, ipf->filemon);
1207 static void filemon_stop(InputFile *ipf) {
1208 if (!ipf->filemon) return;
1209 filemon_method_stopfile(ipf, ipf->filemon);
1214 static void filemon_callback(InputFile *ipf) {
1215 ipf->readable_callback(ipf->readable_callback_user);
1218 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1220 InputFile *ipf= user;
1221 return ipf->readable_callback(ipf->readable_callback_user);
1224 static void on_cancel(struct oop_readable *rable) {
1225 InputFile *ipf= (void*)rable;
1227 if (ipf->filemon) filemon_stopfile(ipf);
1228 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1229 ipf->readable_callback= 0;
1232 static int tailing_on_readable(struct oop_readable *rable,
1233 oop_readable_call *cb, void *user) {
1234 InputFile *ipf= (void*)rable;
1236 tailing_on_cancel(rable);
1237 ipf->readable_callback= cb;
1238 ipf->readable_callback_user= user;
1239 filemon_startfile(ipf);
1241 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1245 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1247 InputFile *ipf= (void*)rable;
1249 ssize_t r= read(ipf->fd, buffer, length);
1251 if (errno==EINTR) continue;
1255 if (ipf==main_input_file) {
1258 } else if (ipf==old_input_file) {
1260 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1261 } else if (ipf==backlog_input_file) {
1271 /*---------- filemon implemented with inotify ----------*/
1273 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1274 #define HAVE_FILEMON
1276 #include <linux/inotify.h>
1278 static int filemon_inotify_fd;
1279 static int filemon_inotify_wdmax;
1280 static InputFile **filemon_inotify_wd2ipf;
1282 typedef struct Filemon_Perfile {
1284 } Filemon_Inotify_Perfile;
1286 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1287 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1288 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1290 if (wd >= filemon_inotify_wdmax) {
1292 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1293 sizeof(*filemon_inotify_wd2ipf) * newmax);
1294 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1295 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1296 filemon_inotify_wdmax= newmax;
1299 assert(!filemon_inotify_wd2ipf[wd]);
1300 filemon_inotify_wd2ipf[wd]= ipf;
1305 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1307 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1308 if (r) sysdie("inotify_rm_watch");
1309 filemon_inotify_wd2ipf[wd]= 0;
1312 static void *filemon_inotify_readable(oop_source *lp, int fd,
1313 oop_event e, void *u) {
1314 struct inotify_event iev;
1316 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1318 if (errno==EAGAIN) break;
1319 sysdie("read from inotify master");
1320 } else if (r==sizeof(iev)) {
1321 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1323 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1325 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1326 filemon_callback(ipf);
1328 return OOP_CONTINUE;
1331 static int filemon_method_init(void) {
1332 filemon_inotify_fd= inotify_init();
1333 if (filemon_inotify_fd<0) {
1334 syswarn("could not initialise inotify: inotify_init failed");
1338 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1343 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1345 /*---------- filemon dummy implementation ----------*/
1347 #if !defined(HAVE_FILEMON)
1349 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1351 static int filemon_method_init(void) { return 0; }
1352 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1353 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1355 #endif /* !HAVE_FILEMON */
1357 /*---------- interface to start and stop an input file ----------*/
1359 static const oop_rd_style feedfile_rdstyle= {
1360 OOP_RD_DELIM_STRIP, '\n',
1362 OOP_RD_SHORTREC_EOF,
1365 static void inputfile_tailing_start(InputFile *ipf) {
1367 ipf->readable->on_readable= tailing_on_readable;
1368 ipf->readable->on_cancel= tailing_on_cancel;
1369 ipf->readable->try_read= tailing_try_read;
1370 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1371 ipf->readable->delete_kill= 0;
1373 ipf->readable_callback= 0;
1374 ipf->readable_callback_user= 0;
1376 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1379 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1380 feedfile_got_article,ipf, feedfile_problem,ipf);
1381 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1384 static void inputfile_tailing_stop(InputFile *ipf) {
1386 oop_rd_cancel(ipf->rd);
1387 oop_rd_delete(ipf->rd);
1389 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1393 /*========== interaction with innd - state machine ==========*/
1395 /* See official state diagram at top of file. We implement
1404 | TIMEOUT and no defer, no backlog
1405 |`--------------------------.
1407 | OPEN F SUCCEEDS | exit
1412 | [Normal] =========
1416 | | F IS SO BIG WE SHOULD FLUSH
1420 | | our handle onto F is now onto D
1423 | |<---------------------------------------------------.
1425 | | spawn inndcomm flush |
1433 | | INNDCOMM FLUSH FAILS ^
1434 | |`----------------------->----------. |
1436 | | NO SUCH SITE V |
1437 ^ |`--------------->----. =========== |
1443 | | \ | TIME TO RETRY |
1444 | | \ `----------------'
1448 | ============= ============
1449 | SEPARATED/ DROPPING/
1450 | old->fd>=0 old->fd>=0
1451 | [Separated] [Dropping]
1452 | main F idle main none
1453 | old D tail old D tail
1454 | ============= ============
1456 ^ | EOF ON D | EOF ON D
1458 | =============== ===============
1459 | SEPARATED/ DROPPING/
1460 | old->fd==-1 old->fd==-1
1461 | [Finishing] [Dropping]
1462 | main F tail main none
1463 | old D closed old D closed
1464 | =============== ===============
1466 | | ALL D PROCESSED | ALL D PROCESSED
1467 | V install defer as backlog V install defer as backlog
1468 ^ | close D | close D
1469 | | unlink D | unlink D
1478 static void statemc_init(void) {
1479 struct stat stab, stabf;
1482 path_lock= xasprintf("%s_lock", feedfile);
1483 path_flushing= xasprintf("%s_flushing", feedfile);
1484 path_defer= xasprintf("%s_defer", feedfile);
1485 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1488 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1489 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1492 memset(&fl,0,sizeof(fl));
1494 fl.l_whence= SEEK_SET;
1495 r= fcntl(lockfd, F_SETLK, &fl);
1497 if (errno==EACCES || errno==EAGAIN) {
1498 if (quiet_if_locked) exit(0);
1499 fatal("another duct holds the lockfile");
1501 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1504 xfstat_isreg(lockfd, &stabf, "lockfile");
1505 xlstat_isreg(path_lock, &stab, &noent, "lockfile");
1507 if (!noent && samefile(&stab, &stabf))
1511 sysdie("could not close stale lockfile %s", path_lock);
1513 debug("startup: locked");
1515 search_backlog_file();
1517 xlstat_isreg(path_defer, &stab, &noent, "defer file");
1519 debug("startup: ductdefer ENOENT");
1521 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1522 switch (stab.st_nlink==1) {
1524 open_defer(); /* so that we will later close it and rename it */
1527 if (unlink(path_defer))
1528 sysdie("could not unlink stale defer file link %s (presumably"
1529 " hardlink to backlog file)", path_defer);
1532 die("defer file %s has unexpected link count %d",
1533 path_defer, stab.st_nlink);
1537 InputFile *file_d= open_input_file(path_flushing);
1540 struct stat stab_f, stab_d;
1542 xlstat_isreg(feedfile, &stab_f, &noent, "feed file");
1544 debug("startup: D exists, F ENOENT => Moved");
1548 debug("startup: F and D both exist");
1550 xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1552 if (samefile(&stab_d, &stab_f)) {
1553 debug("startup: F==D => Hardlinked");
1554 r= unlink(path_flushing);
1555 if (r) sysdie("unlink feed file %s during startup", feedfile);
1558 startup_set_input_file(file_d);
1559 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1561 debug("F!=D => Separated");
1562 SMS(SEPARATED, 0, "found both old and current feed files");
1563 startup_set_input_file(file_d);
1566 debug("startup: D ENOENT => Nothing");
1567 fixme need to try flushing innd here - needs state diagram changes;
1568 SMS(WAITING, open_wait_periods, "no feed file currently exists");
1572 static void statemc_poll(void) {
1573 if (sms==sm_WAITING) { statemc_waiting_poll(); return; }
1575 if (!sm_period_counter) return;
1576 sm_period_counter--;
1577 assert(sm_period_counter>=0);
1579 if (sm_period_counter) return;
1582 fatal("timed out waiting for innd to create feed file %s", feedfile);
1584 spawn_inndcomm_flush(void);
1591 static void statemc_waiting_poll(void) {
1592 InputFile *file_f= open_input_file(feedfile);
1593 if (!file_f) return;
1594 startup_set_input_file(file_d);
1595 SMS(NORMAL, 0, "found and opened feed file");
1598 static void startup_set_input_file(InputFile *f) {
1599 assert(!main_input_file);
1601 inputfile_tailing_start(f);
1604 static void *statemc_check_input_done(oop_source *lp,
1605 struct timeval now, void *ipf_v) {
1606 InputFile *ipf= ipf_v;
1609 if (ipf->inprogress) return; /* new article in the meantime */
1610 if (ipf->fd >= 0); return; /* not had EOF */
1612 if (ipf == backlog_input_file) {
1613 notice_processed(ipf,"backlog file",ipf->path);
1614 close_input_file(ipf);
1615 if (unlink(ipf->path)) {
1616 if (errno != ENOENT)
1617 sysdie("could not unlink processed backlog file %s", ipf->path);
1618 warn("backlog file %s vanished while we were reading it"
1619 " so we couldn't remove it (but it's done now, anyway)",
1622 backlog_input_file= 0;
1623 search_backlog_file();
1627 assert(ipf == old_input_file);
1628 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1630 notice_processed(ipf,"feed file",0);
1634 if (unlink(path_flushing))
1635 sysdie("could not unlink old flushing file %s", path_flushing);
1637 if (sms==sm_DROPPING) {
1638 if (search_backlog_file()) {
1639 debug("feed dropped but still backlogs to process");
1642 notice("feed dropped and our work is complete");
1643 r= unlink(path_lock);
1644 if (r) sysdie("unlink lockfile for old feed %s", path_lock);
1650 close_input_file(old_input_file);
1653 notice("flush complete");
1654 SMS(NORMAL, 0, "flush complete");
1657 static void statemc_setstate(StateMachineState newsms, int periods,
1658 const char *forlog, const char *why) {
1660 sm_period_counter= periods;
1662 info("%s[%d] %s",periods,forlog,why);
1664 info("%s %s",forlog,why);
1668 /*---------- defer and backlog files ----------*/
1670 static void open_defer(void) {
1675 defer= fopen(path_defer, "a+");
1676 if (!defer) sysfatal("could not open defer file %s", path_defer);
1678 /* truncate away any half-written records */
1680 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1682 if (stab.st_size > LONG_MAX)
1683 die("defer file %s size is far too large", path_defer);
1688 long orgsize= stab.st_size;
1689 long truncto= stab.st_size;
1691 if (!truncto) break; /* was only (if anything) one half-truncated record */
1692 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1693 sysdie("seek in defer file %s while truncating partial", path_defer);
1698 sysdie("failed read from defer file %s", path_defer);
1700 die("defer file %s shrank while we were checking it!", path_defer);
1706 if (stab.st_size != truncto) {
1707 warn("truncating half-record at end of defer file %s -"
1708 " shrinking by %ld bytes from %ld to %ld",
1709 path_defer, orgsize - truncto, orgsize, truncto);
1712 sysfatal("could not flush defer file %s", path_defer);
1713 if (ftruncate(fileno(defer), truncto))
1714 sysdie("could not truncate defer file %s", path_defer);
1717 info("continuing existing defer file %s (%ld bytes)",
1718 path_defer, orgsize);
1720 if (fseek(defer, truncto, SEEK_SET))
1721 sysdie("could not seek to new end of defer file %s", path_defer);
1724 static void close_defer(void) {
1728 xfstat(fileno(defer), &stab, "defer file");
1730 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1733 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1734 (unsigned long)now.tv_sec,
1735 (unsigned long)stab.st_ino);
1736 if (link(path_defer, path_backlog))
1737 sysfatal("could not install defer file %s as backlog file %s",
1738 path_defer, backlog);
1739 if (unlink(path_defer))
1740 sysdie("could not unlink old defer link %s to backlog file %s",
1741 path_defer, backlog);
1743 if (backlog_nextscan_periods < 0 ||
1744 backlog_nextscan_periods > backlog_retry_minperiods + 1)
1745 backlog_nextscan_periods= backlog_retry_minperiods + 1;
1748 static void poll_backlog_file(void) {
1749 if (backlog_nextscan_periods < 0) return;
1750 if (backlog_nextscan_periods-- > 0) return;
1751 search_backlog_file();
1754 static int search_backlog_file(void) {
1755 /* returns non-0 iff there are any backlog files */
1760 const char *oldest_path=0;
1761 time_t oldest_mtime, now;
1763 if (backlog_input_file) return 3;
1767 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
1771 sysdie("failed to expand backlog pattern %s", globpat_backlog);
1773 die("out of memory expanding backlog pattern %s", globpat_backlog);
1775 for (i=0; i<gl.gl_pathc; i++) {
1776 const char *path= gl.gl_pathv[i];
1778 if (strchr(path,'#') || strchr(path,'~')) {
1779 debug("backlog file search skipping %s", path);
1782 r= stat(path, &stab);
1784 syswarn("failed to stat backlog file %s", path);
1787 if (!S_ISREG(stab.st_mode)) {
1788 warn("backlog file %s is not a plain file (or link to one)", path);
1791 if (!oldest_path || stab.st_mtime < oldest_mtime) {
1793 oldest_mtime= stab.st_mtime;
1796 case GLOB_NOMATCH: /* fall through */
1799 sysdie("glob expansion of backlog pattern %s gave unexpected"
1800 " nonzero (error?) return value %d", globpat_backlog, r);
1806 debug("backlog scan: none");
1807 backlog_nextscan_periods= backlog_spontaneous_rescan_periods;
1811 now= time(); if (now==-1) sysdie("time(2) failed");
1812 double age= difftime(now, oldest_mtime);
1813 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
1815 if (age_deficiency <= 0) {
1816 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
1817 age, age_deficiency, oldest_path);
1819 backlog_input_file= open_input_file(oldest_path);
1820 if (!backlog_input_file) {
1821 warn("backlog file %s vanished as we opened it", backlog_input_file);
1824 inputfile_tailing_start(backlog_input_file);
1825 backlog_nextscan_periods= -1;
1829 backlog_nextscan_periods= age_deficiency / PERIOD_SECONDS;
1831 if (backlog_spontaneous_rescan_periods >= 0 &&
1832 backlog_nextscan_periods > backlog_spontaneous_rescan_periods)
1833 backlog_nextscan_periods= backlog_spontaneous_rescan_periods;
1835 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
1836 age, age_deficiency, backlog_nextscan_periods, oldest_path);
1840 /*========== flushing the feed ==========*/
1842 static pid_t inndcomm_child;
1844 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1845 assert(inndcomm_child);
1846 int status= xwaitpid(&inndcomm_child, "inndcomm");
1847 loop->cancel_fd(fd);
1850 assert(!old_input_file);
1852 if (WIFEXITED(status)) {
1853 switch (WEXITSTATUS(status)) {
1855 case INNDCOMMCHILD_ESTATUS_FAIL:
1858 case INNDCOMMCHILD_ESTATUS_NONESUCH:
1859 warn("feed has been dropped by innd, finishing up");
1860 old_input_file= main_input_file;
1862 SMS(DROPPING, 0, "dropped by innd");
1863 return OOP_CONTINUE;
1866 old_input_file= main_input_file;
1867 main_input_file= open_input_file(feedfile);
1868 if (!main_input_file)
1869 die("flush succeeded but feedfile %s does not exist!", feedfile);
1870 SMS(SEPARATED, 0, "feed file missing");
1871 return OOP_CONTINUE;
1874 goto unexpected_exitstatus;
1877 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1878 warn("flush timed out trying to talk to innd");
1881 unexpected_exitstatus:
1882 report_child_status("inndcomm child", status);
1886 SMS(FLUSHFAIL, flushfail_retry_periods, "flush failed, will retry");
1889 static void inndcommfail(const char *what) {
1890 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1891 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1894 void spawn_inndcomm_flush(void) {
1897 assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1898 assert(!inndcomm_child);
1900 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1902 inndcomm_child= xfork();
1904 if (!inndcomm_child) {
1905 static char flushargv[2]= { sitename, 0 };
1910 alarm(inndcomm_flush_timeout);
1911 r= ICCopen(); if (r) inndcommfail("connect");
1912 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
1913 if (!r) exit(0); /* yay! */
1915 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1916 syswarn("innd ctlinnd flush failed: innd said %s", reply);
1917 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1921 int sentinel_fd= pipefds[0];
1922 on_fd_read_except(sentinel_fd, inndcomm_event);
1924 SMS(FLUSHING, 0, "flush is in progress");
1927 /*========== main program ==========*/
1929 static void postfork_inputfile(InputFile *ipf) {
1931 assert(ipf->fd >= 0);
1936 static void postfork_conns(Connection *conn) {
1943 static void postfork_stdio(FILE *f) {
1944 /* we have no stdio streams that are buffered long-term */
1948 static void postfork(const char *what) {
1949 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1950 sysdie("%s child: failed to reset SIGPIPE");
1952 postfork_inputfile(main_input_file);
1953 postfork_inputfile(old_input_file);
1954 postfork_conns(idle.head);
1955 postfork_conns(working.head);
1956 postfork_conns(full.head);
1957 postfork_stdio(defer);
1960 #define EVERY(what, interval, body) \
1961 static const struct timeval what##_timeout = { 5, 0 }; \
1962 static void what##_schedule(void); \
1963 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1965 what##_schedule(); \
1967 static void what##_schedule(void) { \
1968 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
1971 EVERY(filepoll, {5,0}, {
1972 if (main_input_file && main_input_file->readable_callback)
1973 filemon_callback(main_input_file);
1976 EVERY(period, {PERIOD_SECONDS,0}, {
1977 if (connect_delay) connect_delay--;
1978 poll_backlog_file();
1979 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
1981 check_master_queue();
1985 /*========== option parsing ==========*/
1988 of_seconds= 001000u;
1989 of_boolean= 002000u;
1992 typedef struct Option Option;
1993 typedef void OptionParser(const Option*, const char *val);
2003 void op_integer(const Option *o, const char *val) {
2006 unsigned long ul= strtoul(val,&ep,10);
2007 if (*ep || ep==val || errno || ul>INT_MAX)
2008 badusage("bad integer value for %s",o->long);
2009 int *store= o->store;
2013 void op_double(const Option *o, const char *val) {
2014 int *store= o->store;
2017 *store= strtod(val, &ep);
2018 if (*ep || ep==val || errno)
2019 badusage("bad floating point value for %s",o->long);
2022 void op_string(const Option *o, const char *val) {
2023 char **store= o->store;
2028 void op_seconds(const Option *o, const char *val) {
2029 int *store= o->store;
2032 double v= strtod(val,&ep);
2033 if (ep==val) badusage("bad time/duration value for %s",o->long);
2035 if (!*ep || !strcmp(ep,"s")) unit= 1;
2036 else if (!strcmp(ep,"m")) unit= 60;
2037 else if (!strcmp(ep,"h")) unit= 3600;
2038 else if (!strcmp(ep,"d")) unit= 86400;
2039 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2043 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2047 void op_periods_rndup(const Option *o, const char *val) {
2048 int *store= o->store;
2050 *store += PERIOD_SECONDS-1;
2051 *store /= PERIOD_SECONDS;
2054 void op_periods_booltrue(const Option *o, const char *val) {
2055 int *store= o->store;
2058 void op_periods_boolfalse(const Option *o, const char *val) {
2059 int *store= o->store;
2063 static const Option options[]= {
2064 { 0, "max-connections", &max_connections op_integer },
2065 { 0, "streaming", &try_stream, op_booltrue, 1 },
2066 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2067 {'h',"host", &remote_host, op_string },
2068 {'P',"port", &port op_integer },
2069 { 0, "inndconf", &inndconffile, op_string },
2070 {'f',"feedfile", &feedfile, op_string },
2071 {'q',"quiet-multiple", &quiet_if_locked, op_booltrue, 1 },
2072 { 0, "no-quiet-multiple", &quiet_if_locked, op_boolfalse, 1 },
2073 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2074 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2076 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2077 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2079 { 0, "max-queue-size", &max_queue_per_conn op_integer },
2080 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2081 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2082 { 0, "feedfile-open-timeout", &open_wait_periods, op_periods_rndup },
2083 { 0, "connection-timeout", &connection_timeout, op_seconds },
2084 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2087 int main(int argc, char **argv) {
2093 if (*arg != '-') break;
2094 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2096 while ((a= *++arg)) {
2100 char *equals= strchr(arg,'=');
2101 int len= equals ? (equals - arg) : strlen(arg);
2102 for (o=options; o->long; o++)
2103 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2105 badusage("unknown long option --%s",arg);
2108 if (equals) badusage("option --%s does not take a value",o->long);
2110 } else if (equals) {
2114 if (!arg) badusage("option --%s needs a value",o->long);
2117 break; /* eaten the whole argument now */
2119 for (o=options; o->long; o++)
2122 badusage("unknown short option -%c",a);
2129 if (!arg) badusage("option -%c needs a value",o->short);
2132 break; /* eaten the whole argument now */
2137 if (!arg) badusage("need site name argument");
2138 if (*++argv) badusage("too many non-option arguments");
2141 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2142 badusage("nocheck threshold percentage must be between 0..100");
2143 nocheck_thresh= nocheck_thresh_pct * 0.01;
2145 if (nocheck_decay_articles < 0.1)
2146 badusage("nocheck decay articles must be at least 0.1");
2147 nocheck_decay= 1 - 1/nocheck_decay_articles;
2149 innconf_read(inndconffile);
2152 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2153 else if (!feedfile[0])
2154 badusage("feed filename must be nonempty");
2155 else if (feedfile[strlen(feedfile)-1]=='/')
2156 feedfile= xasprintf("%s%s",feedfile,sitename);
2158 const char *feedfile_forbidden= "?*[";
2160 while ((c= *feedfile_forbidden++))
2161 if (strchr(feedfile, c))
2162 badusage("feed filename may not contain glob metacharacter %c",c);
2164 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2165 sysdie("could not ignore SIGPIPE");
2167 if (become_daemon) {
2168 for (i=3; i<255; i++)
2169 /* do this now before we open syslog, etc. */
2171 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2173 int null= open("/dev/null",O_RDWR);
2174 if (null<0) sysdie("failed to open /dev/null");
2180 pid_t child1= xfork("daemonise first fork");
2181 if (child1) _exit(0);
2183 pid_t sid= setsid();
2184 if (sid != child1) sysdie("setsid failed");
2186 pid_t child2= xfork("daemonise second fork");
2187 if (child2) _exit(0);
2192 if (!filemon_init()) {
2193 warn("no file monitoring available, polling");
2194 filepoll_schedule();