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 const char *path; /* ptr copy of path_<foo> or feedfile */
263 struct Filemon_Perfile *filemon;
266 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(InputFile));
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;
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);
1138 fixme maybe free ipf->path;
1144 /*---------- dealing with articles read in the input file ----------*/
1146 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1147 oop_rd_event ev, const char *errmsg,
1149 const char *data, size_t recsz,
1151 InputFile *ipf= ipf_v;
1153 char tokentextbuf[sizeof(TOKEN)*2+3];
1155 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1157 if (data[0] && data[0]!=' ') {
1158 char *space= strchr(data,' ');
1159 int tokenlen= space-data;
1160 int midlen= (int)recsz-tokenlen-1;
1161 if (midlen < 0) goto bad_data;
1163 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1164 memcpy(tokentextbuf, data, tokenlen);
1165 tokentextbuf[tokenlen]= 0;
1166 if (!IsToken(tokentextbuf)) goto bad_data;
1168 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1169 art->offset= ipf->offset;
1170 art->blanklen= recsz;
1171 art->midlen= midlen;
1172 art->checked= art->sentbody= 0;
1173 art->ipf= ipf; ipf->inprogress++;
1174 art->token= TextToToken(tokentextbuf);
1175 strcpy(art->messageid, space+1);
1176 LIST_ADDTAIL(queue, art);
1178 ipf->offset += recsz + 1;
1180 if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
1181 notice("starting flush (%lu >= %lu)",
1182 (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1184 int r= link(feedfile, duct_path);
1185 if (r) sysdie("link feedfile %s to flushing file %s", feedfile, dut_path);
1188 r= unlink(feedfile);
1189 if (r) sysdie("unlink old feedfile link %s", feedfile);
1192 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1195 check_master_queue();
1199 /*========== tailing input file ==========*/
1201 static void filemon_start(InputFile *ipf) {
1202 assert(!ipf->filemon);
1204 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1205 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1206 filemon_method_startfile(ipf, ipf->filemon);
1209 static void filemon_stop(InputFile *ipf) {
1210 if (!ipf->filemon) return;
1211 filemon_method_stopfile(ipf, ipf->filemon);
1216 static void filemon_callback(InputFile *ipf) {
1217 ipf->readable_callback(ipf->readable_callback_user);
1220 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1222 InputFile *ipf= user;
1223 return ipf->readable_callback(ipf->readable_callback_user);
1226 static void on_cancel(struct oop_readable *rable) {
1227 InputFile *ipf= (void*)rable;
1229 if (ipf->filemon) filemon_stopfile(ipf);
1230 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1231 ipf->readable_callback= 0;
1234 static int tailing_on_readable(struct oop_readable *rable,
1235 oop_readable_call *cb, void *user) {
1236 InputFile *ipf= (void*)rable;
1238 tailing_on_cancel(rable);
1239 ipf->readable_callback= cb;
1240 ipf->readable_callback_user= user;
1241 filemon_startfile(ipf);
1243 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1247 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1249 InputFile *ipf= (void*)rable;
1251 ssize_t r= read(ipf->fd, buffer, length);
1253 if (errno==EINTR) continue;
1257 if (ipf==main_input_file) {
1260 } else if (ipf==old_input_file) {
1262 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1263 } else if (ipf==backlog_input_file) {
1273 /*---------- filemon implemented with inotify ----------*/
1275 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1276 #define HAVE_FILEMON
1278 #include <linux/inotify.h>
1280 static int filemon_inotify_fd;
1281 static int filemon_inotify_wdmax;
1282 static InputFile **filemon_inotify_wd2ipf;
1284 typedef struct Filemon_Perfile {
1286 } Filemon_Inotify_Perfile;
1288 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1289 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1290 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1292 if (wd >= filemon_inotify_wdmax) {
1294 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1295 sizeof(*filemon_inotify_wd2ipf) * newmax);
1296 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1297 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1298 filemon_inotify_wdmax= newmax;
1301 assert(!filemon_inotify_wd2ipf[wd]);
1302 filemon_inotify_wd2ipf[wd]= ipf;
1307 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1309 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1310 if (r) sysdie("inotify_rm_watch");
1311 filemon_inotify_wd2ipf[wd]= 0;
1314 static void *filemon_inotify_readable(oop_source *lp, int fd,
1315 oop_event e, void *u) {
1316 struct inotify_event iev;
1318 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1320 if (errno==EAGAIN) break;
1321 sysdie("read from inotify master");
1322 } else if (r==sizeof(iev)) {
1323 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1325 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1327 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1328 filemon_callback(ipf);
1330 return OOP_CONTINUE;
1333 static int filemon_method_init(void) {
1334 filemon_inotify_fd= inotify_init();
1335 if (filemon_inotify_fd<0) {
1336 syswarn("could not initialise inotify: inotify_init failed");
1340 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1345 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1347 /*---------- filemon dummy implementation ----------*/
1349 #if !defined(HAVE_FILEMON)
1351 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1353 static int filemon_method_init(void) { return 0; }
1354 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1355 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1357 #endif /* !HAVE_FILEMON */
1359 /*---------- interface to start and stop an input file ----------*/
1361 static const oop_rd_style feedfile_rdstyle= {
1362 OOP_RD_DELIM_STRIP, '\n',
1364 OOP_RD_SHORTREC_EOF,
1367 static void inputfile_tailing_start(InputFile *ipf) {
1369 ipf->readable->on_readable= tailing_on_readable;
1370 ipf->readable->on_cancel= tailing_on_cancel;
1371 ipf->readable->try_read= tailing_try_read;
1372 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1373 ipf->readable->delete_kill= 0;
1375 ipf->readable_callback= 0;
1376 ipf->readable_callback_user= 0;
1378 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1381 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1382 feedfile_got_article,ipf, feedfile_problem,ipf);
1383 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1386 static void inputfile_tailing_stop(InputFile *ipf) {
1388 oop_rd_cancel(ipf->rd);
1389 oop_rd_delete(ipf->rd);
1391 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1395 /*========== interaction with innd - state machine ==========*/
1397 /* See official state diagram at top of file. We implement
1406 | TIMEOUT and no defer, no backlog
1407 |`--------------------------.
1409 | OPEN F SUCCEEDS | exit
1414 | [Normal] =========
1418 | | F IS SO BIG WE SHOULD FLUSH
1422 | | our handle onto F is now onto D
1425 | |<---------------------------------------------------.
1427 | | spawn inndcomm flush |
1435 | | INNDCOMM FLUSH FAILS ^
1436 | |`----------------------->----------. |
1438 | | NO SUCH SITE V |
1439 ^ |`--------------->----. =========== |
1445 | | \ | TIME TO RETRY |
1446 | | \ `----------------'
1450 | ============= ============
1451 | SEPARATED/ DROPPING/
1452 | old->fd>=0 old->fd>=0
1453 | [Separated] [Dropping]
1454 | main F idle main none
1455 | old D tail old D tail
1456 | ============= ============
1458 ^ | EOF ON D | EOF ON D
1460 | =============== ===============
1461 | SEPARATED/ DROPPING/
1462 | old->fd==-1 old->fd==-1
1463 | [Finishing] [Dropping]
1464 | main F tail main none
1465 | old D closed old D closed
1466 | =============== ===============
1468 | | ALL D PROCESSED | ALL D PROCESSED
1469 | V install defer as backlog V install defer as backlog
1470 ^ | close D | close D
1471 | | unlink D | unlink D
1480 static void statemc_init(void) {
1481 struct stat stab, stabf;
1484 path_lock= xasprintf("%s_lock", feedfile);
1485 path_flushing= xasprintf("%s_flushing", feedfile);
1486 path_defer= xasprintf("%s_defer", feedfile);
1487 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1490 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1491 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1494 memset(&fl,0,sizeof(fl));
1496 fl.l_whence= SEEK_SET;
1497 r= fcntl(lockfd, F_SETLK, &fl);
1499 if (errno==EACCES || errno==EAGAIN) {
1500 if (quiet_if_locked) exit(0);
1501 fatal("another duct holds the lockfile");
1503 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1506 xfstat_isreg(lockfd, &stabf, "lockfile");
1507 xlstat_isreg(path_lock, &stab, &noent, "lockfile");
1509 if (!noent && samefile(&stab, &stabf))
1513 sysdie("could not close stale lockfile %s", path_lock);
1515 debug("startup: locked");
1517 search_backlog_file();
1519 xlstat_isreg(path_defer, &stab, &noent, "defer file");
1521 debug("startup: ductdefer ENOENT");
1523 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1524 switch (stab.st_nlink==1) {
1526 open_defer(); /* so that we will later close it and rename it */
1529 if (unlink(path_defer))
1530 sysdie("could not unlink stale defer file link %s (presumably"
1531 " hardlink to backlog file)", path_defer);
1534 die("defer file %s has unexpected link count %d",
1535 path_defer, stab.st_nlink);
1539 InputFile *file_d= open_input_file(path_flushing);
1542 struct stat stab_f, stab_d;
1544 xlstat_isreg(feedfile, &stab_f, &noent, "feed file");
1546 debug("startup: D exists, F ENOENT => Moved");
1550 debug("startup: F and D both exist");
1552 xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1554 if (samefile(&stab_d, &stab_f)) {
1555 debug("startup: F==D => Hardlinked");
1556 r= unlink(path_flushing);
1557 if (r) sysdie("unlink feed file %s during startup", feedfile);
1560 startup_set_input_file(file_d);
1561 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1563 debug("F!=D => Separated");
1564 SMS(SEPARATED, 0, "found both old and current feed files");
1565 startup_set_input_file(file_d);
1568 debug("startup: D ENOENT => Nothing");
1569 SMS(WAITING, open_wait_periods, "no feed file currently exists");
1573 static void statemc_poll(void) {
1574 if (sms==sm_WAITING) { statemc_waiting_poll(); return; }
1576 if (!sm_period_counter) return;
1577 sm_period_counter--;
1578 assert(sm_period_counter>=0);
1580 if (sm_period_counter) return;
1583 fatal("timed out waiting for innd to create feed file %s", feedfile);
1585 spawn_inndcomm_flush(void);
1592 static void statemc_waiting_poll(void) {
1593 InputFile *file_f= open_input_file(feedfile);
1594 if (!file_f) return;
1595 startup_set_input_file(file_d);
1596 SMS(NORMAL, 0, "found and opened feed file");
1599 static void startup_set_input_file(InputFile *f) {
1600 assert(!main_input_file);
1602 inputfile_tailing_start(f);
1605 static void *statemc_check_input_done(oop_source *lp,
1606 struct timeval now, void *ipf_v) {
1607 InputFile *ipf= ipf_v;
1610 if (ipf->inprogress) return; /* new article in the meantime */
1611 if (ipf->fd >= 0); return; /* not had EOF */
1613 if (ipf == backlog_input_file) {
1614 notice_processed(ipf,"backlog file",ipf->path);
1615 close_input_file(ipf);
1616 if (unlink(ipf->path)) {
1617 if (errno != ENOENT)
1618 sysdie("could not unlink processed backlog file %s", ipf->path);
1619 warn("backlog file %s vanished while we were reading it"
1620 " so we couldn't remove it (but it's done now, anyway)",
1623 backlog_input_file= 0;
1624 search_backlog_file();
1628 assert(ipf == old_input_file);
1629 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1631 notice_processed(ipf,"feed file",0);
1635 if (unlink(path_flushing))
1636 sysdie("could not unlink old flushing file %s", path_flushing);
1638 if (sms==sm_DROPPING) {
1639 if (search_backlog_file()) {
1640 debug("feed dropped but still backlogs to process");
1643 notice("feed dropped and our work is complete");
1644 r= unlink(path_lock);
1645 if (r) sysdie("unlink lockfile for old feed %s", path_lock);
1651 close_input_file(old_input_file);
1654 notice("flush complete");
1655 SMS(NORMAL, 0, "flush complete");
1658 static void statemc_setstate(StateMachineState newsms, int periods,
1659 const char *forlog, const char *why) {
1661 sm_period_counter= periods;
1663 info("%s[%d] %s",periods,forlog,why);
1665 info("%s %s",forlog,why);
1669 /*---------- defer and backlog files ----------*/
1671 static void open_defer(void) {
1676 defer= fopen(path_defer, "a+");
1677 if (!defer) sysfatal("could not open defer file %s", path_defer);
1679 /* truncate away any half-written records */
1681 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1683 if (stab.st_size > LONG_MAX)
1684 die("defer file %s size is far too large", path_defer);
1689 long orgsize= stab.st_size;
1690 long truncto= stab.st_size;
1692 if (!truncto) break; /* was only (if anything) one half-truncated record */
1693 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1694 sysdie("seek in defer file %s while truncating partial", path_defer);
1699 sysdie("failed read from defer file %s", path_defer);
1701 die("defer file %s shrank while we were checking it!", path_defer);
1707 if (stab.st_size != truncto) {
1708 warn("truncating half-record at end of defer file %s -"
1709 " shrinking by %ld bytes from %ld to %ld",
1710 path_defer, orgsize - truncto, orgsize, truncto);
1713 sysfatal("could not flush defer file %s", path_defer);
1714 if (ftruncate(fileno(defer), truncto))
1715 sysdie("could not truncate defer file %s", path_defer);
1718 info("continuing existing defer file %s (%ld bytes)",
1719 path_defer, orgsize);
1721 if (fseek(defer, truncto, SEEK_SET))
1722 sysdie("could not seek to new end of defer file %s", path_defer);
1725 static void close_defer(void) {
1729 xfstat(fileno(defer), &stab, "defer file");
1731 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1734 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1735 (unsigned long)now.tv_sec,
1736 (unsigned long)stab.st_ino);
1737 if (link(path_defer, path_backlog))
1738 sysfatal("could not install defer file %s as backlog file %s",
1739 path_defer, backlog);
1740 if (unlink(path_defer))
1741 sysdie("could not unlink old defer link %s to backlog file %s",
1742 path_defer, backlog);
1744 if (backlog_nextscan_periods < 0 ||
1745 backlog_nextscan_periods > backlog_retry_minperiods + 1)
1746 backlog_nextscan_periods= backlog_retry_minperiods + 1;
1749 static void poll_backlog_file(void) {
1750 if (backlog_nextscan_periods < 0) return;
1751 if (backlog_nextscan_periods-- > 0) return;
1752 search_backlog_file();
1755 static int search_backlog_file(void) {
1756 /* returns non-0 iff there are any backlog files */
1761 const char *oldest_path=0;
1762 time_t oldest_mtime, now;
1764 if (backlog_input_file) return 3;
1768 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
1772 sysdie("failed to expand backlog pattern %s", globpat_backlog);
1774 die("out of memory expanding backlog pattern %s", globpat_backlog);
1776 for (i=0; i<gl.gl_pathc; i++) {
1777 const char *path= gl.gl_pathv[i];
1779 if (strchr(path,'#') || strchr(path,'~')) {
1780 debug("backlog file search skipping %s", path);
1783 r= stat(path, &stab);
1785 syswarn("failed to stat backlog file %s", path);
1788 if (!S_ISREG(stab.st_mode)) {
1789 warn("backlog file %s is not a plain file (or link to one)", path);
1792 if (!oldest_path || stab.st_mtime < oldest_mtime) {
1794 oldest_mtime= stab.st_mtime;
1797 case GLOB_NOMATCH: /* fall through */
1800 sysdie("glob expansion of backlog pattern %s gave unexpected"
1801 " nonzero (error?) return value %d", globpat_backlog, r);
1807 debug("backlog scan: none");
1808 backlog_nextscan_periods= backlog_spontaneous_rescan_periods;
1812 now= time(); if (now==-1) sysdie("time(2) failed");
1813 double age= difftime(now, oldest_mtime);
1814 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
1816 if (age_deficiency <= 0) {
1817 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
1818 age, age_deficiency, oldest_path);
1820 backlog_input_file= open_input_file();
1821 if (!backlog_input_file) {
1822 warn("backlog file %s vanished as we opened it", backlog_input_file);
1825 inputfile_tailing_start(backlog_input_file);
1826 backlog_nextscan_periods= -1;
1830 backlog_nextscan_periods= age_deficiency / PERIOD_SECONDS;
1832 if (backlog_spontaneous_rescan_periods >= 0 &&
1833 backlog_nextscan_periods > backlog_spontaneous_rescan_periods)
1834 backlog_nextscan_periods= backlog_spontaneous_rescan_periods;
1836 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
1837 age, age_deficiency, backlog_nextscan_periods, oldest_path);
1841 /*========== flushing the feed ==========*/
1843 static pid_t inndcomm_child;
1845 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1846 assert(inndcomm_child);
1847 int status= xwaitpid(&inndcomm_child, "inndcomm");
1848 loop->cancel_fd(fd);
1851 assert(!old_input_file);
1853 if (WIFEXITED(status)) {
1854 switch (WEXITSTATUS(status)) {
1856 case INNDCOMMCHILD_ESTATUS_FAIL:
1859 case INNDCOMMCHILD_ESTATUS_NONESUCH:
1860 warn("feed has been dropped by innd, finishing up");
1861 old_input_file= main_input_file;
1863 SMS(DROPPING, 0, "dropped by innd");
1864 return OOP_CONTINUE;
1867 old_input_file= main_input_file;
1868 main_input_file= open_input_file(feedfile);
1869 if (!main_input_file)
1870 die("flush succeeded but feedfile %s does not exist!", feedfile);
1871 SMS(SEPARATED, 0, "feed file missing");
1872 return OOP_CONTINUE;
1875 goto unexpected_exitstatus;
1878 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1879 warn("flush timed out trying to talk to innd");
1882 unexpected_exitstatus:
1883 report_child_status("inndcomm child", status);
1887 SMS(FLUSHFAIL, flushfail_retry_periods, "flush failed, will retry");
1890 static void inndcommfail(const char *what) {
1891 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1892 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1895 void spawn_inndcomm_flush(void) {
1898 assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1899 assert(!inndcomm_child);
1901 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1903 inndcomm_child= xfork();
1905 if (!inndcomm_child) {
1906 static char flushargv[2]= { sitename, 0 };
1911 alarm(inndcomm_flush_timeout);
1912 r= ICCopen(); if (r) inndcommfail("connect");
1913 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
1914 if (!r) exit(0); /* yay! */
1916 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1917 syswarn("innd ctlinnd flush failed: innd said %s", reply);
1918 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1922 int sentinel_fd= pipefds[0];
1923 on_fd_read_except(sentinel_fd, inndcomm_event);
1925 SMS(FLUSHING, 0, "flush is in progress");
1928 /*========== main program ==========*/
1930 static void postfork_inputfile(InputFile *ipf) {
1932 assert(ipf->fd >= 0);
1937 static void postfork_conns(Connection *conn) {
1944 static void postfork_stdio(FILE *f) {
1945 /* we have no stdio streams that are buffered long-term */
1949 static void postfork(const char *what) {
1950 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1951 sysdie("%s child: failed to reset SIGPIPE");
1953 postfork_inputfile(main_input_file);
1954 postfork_inputfile(old_input_file);
1955 postfork_conns(idle.head);
1956 postfork_conns(working.head);
1957 postfork_conns(full.head);
1958 postfork_stdio(defer);
1961 #define EVERY(what, interval, body) \
1962 static const struct timeval what##_timeout = { 5, 0 }; \
1963 static void what##_schedule(void); \
1964 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1966 what##_schedule(); \
1968 static void what##_schedule(void) { \
1969 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
1972 EVERY(filepoll, {5,0}, {
1973 if (main_input_file && main_input_file->readable_callback)
1974 filemon_callback(main_input_file);
1977 EVERY(period, {PERIOD_SECONDS,0}, {
1978 if (connect_delay) connect_delay--;
1979 poll_backlog_file();
1980 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
1982 check_master_queue();
1986 /*========== option parsing ==========*/
1989 of_seconds= 001000u;
1990 of_boolean= 002000u;
1993 typedef struct Option Option;
1994 typedef void OptionParser(const Option*, const char *val);
2004 void op_integer(const Option *o, const char *val) {
2007 unsigned long ul= strtoul(val,&ep,10);
2008 if (*ep || ep==val || errno || ul>INT_MAX)
2009 badusage("bad integer value for %s",o->long);
2010 int *store= o->store;
2014 void op_double(const Option *o, const char *val) {
2015 int *store= o->store;
2018 *store= strtod(val, &ep);
2019 if (*ep || ep==val || errno)
2020 badusage("bad floating point value for %s",o->long);
2023 void op_string(const Option *o, const char *val) {
2024 char **store= o->store;
2029 void op_seconds(const Option *o, const char *val) {
2030 int *store= o->store;
2033 double v= strtod(val,&ep);
2034 if (ep==val) badusage("bad time/duration value for %s",o->long);
2036 if (!*ep || !strcmp(ep,"s")) unit= 1;
2037 else if (!strcmp(ep,"m")) unit= 60;
2038 else if (!strcmp(ep,"h")) unit= 3600;
2039 else if (!strcmp(ep,"d")) unit= 86400;
2040 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2044 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2048 void op_periods_rndup(const Option *o, const char *val) {
2049 int *store= o->store;
2051 *store += PERIOD_SECONDS-1;
2052 *store /= PERIOD_SECONDS;
2055 void op_periods_booltrue(const Option *o, const char *val) {
2056 int *store= o->store;
2059 void op_periods_boolfalse(const Option *o, const char *val) {
2060 int *store= o->store;
2064 static const Option options[]= {
2065 { 0, "max-connections", &max_connections op_integer },
2066 { 0, "streaming", &try_stream, op_booltrue, 1 },
2067 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2068 {'h',"host", &remote_host, op_string },
2069 {'P',"port", &port op_integer },
2070 { 0, "inndconf", &inndconffile, op_string },
2071 {'f',"feedfile", &feedfile, op_string },
2072 {'q',"quiet-multiple", &quiet_if_locked, op_booltrue, 1 },
2073 { 0, "no-quiet-multiple", &quiet_if_locked, op_boolfalse, 1 },
2074 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2075 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2077 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2078 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2080 { 0, "max-queue-size", &max_queue_per_conn op_integer },
2081 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2082 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2083 { 0, "feedfile-open-timeout", &open_wait_periods, op_periods_rndup },
2084 { 0, "connection-timeout", &connection_timeout, op_seconds },
2085 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2088 int main(int argc, char **argv) {
2094 if (*arg != '-') break;
2095 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2097 while ((a= *++arg)) {
2101 char *equals= strchr(arg,'=');
2102 int len= equals ? (equals - arg) : strlen(arg);
2103 for (o=options; o->long; o++)
2104 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2106 badusage("unknown long option --%s",arg);
2109 if (equals) badusage("option --%s does not take a value",o->long);
2111 } else if (equals) {
2115 if (!arg) badusage("option --%s needs a value",o->long);
2118 break; /* eaten the whole argument now */
2120 for (o=options; o->long; o++)
2123 badusage("unknown short option -%c",a);
2130 if (!arg) badusage("option -%c needs a value",o->short);
2133 break; /* eaten the whole argument now */
2138 if (!arg) badusage("need site name argument");
2139 if (*++argv) badusage("too many non-option arguments");
2142 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2143 badusage("nocheck threshold percentage must be between 0..100");
2144 nocheck_thresh= nocheck_thresh_pct * 0.01;
2146 if (nocheck_decay_articles < 0.1)
2147 badusage("nocheck decay articles must be at least 0.1");
2148 nocheck_decay= 1 - 1/nocheck_decay_articles;
2150 innconf_read(inndconffile);
2153 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2154 else if (!feedfile[0])
2155 badusage("feed filename must be nonempty");
2156 else if (feedfile[strlen(feedfile)-1]=='/')
2157 feedfile= xasprintf("%s%s",feedfile,sitename);
2159 const char *feedfile_forbidden= "?*[";
2161 while ((c= *feedfile_forbidden++))
2162 if (strchr(feedfile, c))
2163 badusage("feed filename may not contain glob metacharacter %c",c);
2165 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2166 sysdie("could not ignore SIGPIPE");
2168 if (become_daemon) {
2169 for (i=3; i<255; i++)
2170 /* do this now before we open syslog, etc. */
2172 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2174 int null= open("/dev/null",O_RDWR);
2175 if (null<0) sysdie("failed to open /dev/null");
2181 pid_t child1= xfork("daemonise first fork");
2182 if (child1) _exit(0);
2184 pid_t sid= setsid();
2185 if (sid != child1) sysdie("setsid failed");
2187 pid_t child2= xfork("daemonise second fork");
2188 if (child2) _exit(0);
2193 if (!filemon_init()) {
2194 warn("no file monitoring available, polling");
2195 filepoll_schedule();