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 */
272 #define SMS_LIST(X) \
281 #define SMS_DEF_ENUM(s) sm_##s,
282 SMS_LIST(SMS_DEF_ENUM)
285 static const char *sms_names[]= {
286 #define SMS_DEF_NAME(s) #s ,
287 SMS_LIST(SMS_DEF_NAME)
293 int fd, max_queue, stream;
294 LIST(Article) queue; /* not yet told peer, or CHECK said send it */
295 LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
296 struct iovec xmit[CONNIOVS];
297 XmitDetails xmitd[CONNIOVS];
302 /*----- operational variables -----*/
305 static LIST(Conn) idle, working, full;
306 static LIST(Article) *queue;
308 static char *path_lock, *path_flushing, *path_defer;
310 #define SMS(newstate, periods, why) \
311 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
313 static StateMachineState sms;
315 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
316 static int sm_period_counter;
319 /*----- function predeclarations -----*/
321 static void conn_check_work(Conn *conn);
323 static int filemon_init(void);
324 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
325 static void filemon_callback(void);
327 static void statemc_setstate(StateMachineState newsms, int periods,
328 const char *forlog, const char *why);
330 /*========== utility functions etc. ==========*/
332 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
334 static pid_t xfork(const char *what) {
338 if (child==-1) sysdie("cannot fork for %s",what);
339 if (!child) postfork(what);
343 static void on_fd_read_except(int fd, oop_call_fd callback) {
344 loop->on_fd(loop, fd, OOP_READ, callback, 0);
345 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
347 static void cancel_fd_read_except(int fd) {
348 loop->cancel_fd(loop, fd, OOP_READ);
349 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
352 static void report_child_status(const char *what, int status) {
353 if (WIFEXITED(status)) {
354 int es= WEXITSTATUS(status);
356 warn("%s: child died with error exit status %d",es);
357 } else if (WIFSIGNALED(status)) {
358 int sig= WTERMSIG(status);
359 const char *sigstr= strsignal(sig);
360 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
362 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
364 warn("%s: child died due to unknown fatal signal %d%s",
365 what, sig, coredump);
367 warn("%s: child died with unknown wait status %d", status);
371 static int xwaitpid(pid_t *pid, const char *what) {
374 r= kill(*pid, SIGKILL);
375 if (r) sysdie("cannot kill %s child", what);
377 pid_t got= waitpid(*pid, &status, WNOHANG);
378 if (got==-1) sysdie("cannot reap %s child", what);
385 static void check_isreg(const struct stat *stab, const char *path,
387 if (!S_ISREG(stab->st_mode))
388 die("%s %s not a plain file (mode 0%lo)",
389 what, path, (unsigned long)stab->st_mode);
392 static void xfstat(int fd, struct stat *stab_r, const char *what) {
393 int r= fstab(path, stab);
394 if (r) sysdie("could not fstat %s %s", what, path);
397 static void xfstat_isreg(int fd, struct stat *stab_r, const char *what) {
398 xfstat(fd, stab_r, what);
399 check_isreg(stab, path, what);
402 static void xlstat_isreg(const char *path, struct stat *stab,
403 int *enoent_r /* 0 means ENOENT is fatal */
405 int r= lstat(path, stab);
407 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
408 sysdie("could not lstat %s %s", what, path);
410 if (enoent_r) *enoent_r= 0;
411 check_isreg(stab, path, what);
414 static int samefile(const struct stat *a, const struct stat *b) {
415 assert(S_ISREG(a->st_mode));
416 assert(S_ISREG(b->st_mode));
417 return (a->st_ino == b->st_ino &&
418 a->st_dev == b->st_dev);
421 /*========== logging ==========*/
423 static void logcore(int sysloglevel, const char *fmt, ...)
424 __attribute__((printf,2,3))
425 static void logcore(int sysloglevel, const char *fmt, ...) {
429 vsyslog(sysloglevel,fmt,al);
431 vfprintf(stderr,fmt,al);
436 static void logv(int sysloglevel, const char *pfx, int errnoval,
437 int exitstatus, const char *fmt, va_list al)
438 __attribute__((printf,4,0))
439 static void logv(int sysloglevel, const char *pfx, int errnoval,
440 int exitstatus, const char *fmt, va_list al) {
442 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
443 msgbuf[sizeof(msgbuf)-1]= 0;
445 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
446 sysloglevel= LOG_ERR; /* run by wrong user, probably */
448 logcore(sysloglevel, "<%s>%s: %s%s%s",
449 sitename, pfx, msgbuf,
450 errnoval>=0 ? ": " : "",
451 errnoval>=0 ? strerror(errnoval) : "");
454 #define logwrap(fn, pfx, sysloglevel, errno, estatus) \
455 static void fn(const char *fmt, ...) \
456 __attribute__((printf,1,2)); \
457 static void fn(const char *fmt, ...) { \
460 logv(sysloglevel, pfx, errno, estatus, fmt, al); \
463 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
464 logwrap(die, " critical", LOG_CRIT, -1, 16);
466 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
467 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
469 logwrap(syswarn, " warning", LOG_WARN, errno, 0);
470 logwrap(warn, " warning", LOG_WARN, -1, 0);
472 logwrap(notice, "", LOG_NOTICE, -1, 0);
473 logwrap(info, " info", LOG_INFO, -1, 0);
474 logwrap(debug, " debug", LOG_DEBUG, -1, 0);
477 /*========== making new connections ==========*/
479 static int connecting_sockets[2]= {-1,-1};
480 static pid_t connecting_child;
482 static void connect_attempt_discard(void) {
483 if (connecting_sockets[0])
484 cancel_fd(connecting_sockets[0]);
486 perhaps_close(&connecting_sockets[0]);
487 perhaps_close(&connecting_sockets[1]);
489 if (connecting_child) {
490 int status= xwaitpid(&connecting_child, "connect");
492 if (!(WIFEXITED(status) ||
493 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
494 report_child_status("connect", status);
498 #define PREP_DECL_MSG_CMSG(msg) \
500 memset(&msg,0,sizeof(msg)); \
501 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
502 msg.msg_control= msg##cbuf; \
503 msg.msg_controllen= sizeof(msg##cbuf);
505 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
508 conn= xmalloc(sizeof(*conn));
509 memset(conn,0,sizeof(*conn));
512 struct cmsghdr *h= 0;
513 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
514 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
517 pid_t got= waitpid(connecting_child, &status, WNOHANG);
519 assert(got==connecting_child);
521 if (WIFEXITED(status) &&
522 (WEXITSTATUS(status) != 0
523 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
524 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
525 /* child already reported the problem */
526 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
527 warn("connect: connection attempt timed out");
528 } else if (!WIFEXITED(status)) {
529 report_child_status("connect", status);
530 /* that's probably the root cause then */
533 /* child is still running apparently, report the socket problem */
535 syswarn("connect: read from child socket failed");
536 else if (e == OOP_EXCEPTIONN)
537 warn("connect: unexpected exception on child socket");
539 warn("connect: unexpected EOF on child socket");
544 #define CHK(field, val) \
545 if (h->cmsg_##field != val) { \
546 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
549 CHK(level, SOL_SOCKET);
550 CHK(type, SCM_RIGHTS);
551 CHK(len, CMSG_LEN(sizeof(conn-b>fd)));
554 if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
556 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
558 pid_t got= waitpid(connecting_child, &status, 0);
559 if (got==-1) sysdie("connect: real wait for child");
560 assert(got == connecting_child);
563 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
564 int es= WEXITSTATUS(status);
566 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
567 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
569 fatal("connect: child gave unexpected exit status %d", es);
575 LIST_ADDHEAD(idle, conn);
576 notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
577 connect_attempt_discard();
578 check_master_queue();
583 perhaps_close(&conn->fd);
586 connect_attempt_discard();
589 static void connect_start() {
590 assert(!connecting_sockets[0]);
591 assert(!connecting_sockets[1]);
592 assert(!connecting_child);
594 notice("starting connection attempt");
596 r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
597 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
599 connecting_child= xfork("connection");
601 if (!connecting_child) {
602 FILE *cn_from, *cn_to;
603 char buf[NNTP_STRLEN+100];
604 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
606 r= close(connecting_sockets[0]);
607 if (r) sysdie("connect: close parent socket in child");
609 alarm(connection_setup_timeout);
610 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
612 sanitise_inplace(buf);
613 fatal("connect: rejected: %s", buf);
615 sysfatal("connect: connection attempt failed");
618 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
619 sysfatal("connect: authentication failed");
621 if (fputs("MODE STREAM\r\n", cn_to) ||
623 sysfatal("connect: could not send MODE STREAM");
624 buf[sizeof(buf)-1]= 0;
625 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
627 sysfatal("connect: could not read response to MODE STREAM");
629 fatal("connect: connection close in response to MODE STREAM");
634 sanitise_inplace(buf);
635 fatal("connect: response to MODE STREAM is too long: %.100s...",
638 l--; if (l>0 && buf[1-]=='\r') l--;
641 int rcode= strtoul(buf,&ep,10);
643 sanitise_inplace(buf);
644 fatal("connect: bad response to MODE STREAM: %.50s", buf);
648 exitstatus= CONNCHILD_ESTATUS_STREAM;
654 sanitise_inplace(buf);
655 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
660 int fd= fileno(cn_from);
662 PREP_DECL_MSG_CMSG(msg);
663 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
664 cmsg->cmsg_level= SOL_SOCKET;
665 cmsg->cmsg_type= SCM_RIGHTS;
666 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
667 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
669 msg.msg_controllen= cmsg->cmsg_len;
670 r= sendmsg(connecting_sockets[1], &msg, 0);
671 if (r) sysdie("sendmsg failed for new connection");
676 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
677 if (r) sysdie("connect: close child socket in parent");
679 on_fd_read_except(connecting_sockets[0], connchild_event);
683 connect_attempt_discard();
687 /*========== overall control of article flow ==========*/
689 static void check_master_queue(void) {
693 Conn *last_assigned=0;
696 conn_assign_one_article(&working, &last_assigned);
697 } else if (idle.head) {
698 conn_assign_one_article(&idle, &last_assigned);
699 } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
700 !connecting_child && !connect_delay) {
701 connect_delay= reconnect_delay_periods;
707 conn_check_work(last_assigned);
710 static void conn_assign_one_article(LIST(Conn) *connlist,
711 Conn **last_assigned) {
712 Conn *conn= connlist->head;
714 LIST_REMOVE(*connlist, conn);
715 Article *art= LIST_REMHEAD(queue);
716 LIST_ADDTAIL(conn->queue, art);
717 LIST_ADD(*conn_determine_right_list(conn), conn);
719 /* This slightly odd arrangement is so that we call conn_check_work
720 * once after filling the queue for a new connection in
721 * check_master_queue, rather than for each article. */
722 if (conn != *last_assigned && *last_assigned)
723 conn_check_work(*last_assigned);
724 *last_assigned= conn;
727 static int conn_total_queued_articles(Conn *conn) {
728 return conn->sent.count + conn->queue.count;
731 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
732 int inqueue= conn_total_queued_articles(conn);
733 assert(inqueue <= max_queue);
734 if (inqueue == 0) return &idle;
735 if (inqueue == conn->max_queue) return &full;
739 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
744 static void conn_check_work(Conn *conn) {
747 conn_make_some_xmits(conn);
749 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
753 void *rp= conn_write_some_xmits(conn);
754 if (rp==OOP_CONTINUE) {
755 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
757 } else if (rp==OOP_HALT) {
760 /* transmitted everything */
768 /*========== article transmission ==========*/
770 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
771 XmitKind kind) { /* caller must then fill in details */
772 struct iovec *v= &conn->xmit[conn->xmitu];
773 XmitDetails *d= &conn->xmitd[conn->xmitu++];
780 static void xmit_noalloc(Conn *conn, const char *data, int len) {
781 xmit_core(conn,data,len, xk_Const);
783 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
785 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
786 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
790 static void xmit_free(XmitDetails *d) {
792 case xk_Malloc: free(d->info.malloc_tofree); break;
793 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
794 case xk_Const: break;
799 static void *conn_write_some_xmits(Conn *conn) {
801 * 0: nothing more to write, no need to call us again
802 * OOP_CONTINUE: more to write but fd not writeable
803 * OOP_HALT: disaster, have destroyed conn
806 int count= conn->xmitu;
807 if (!count) return 0;
809 if (count > IOV_MAX) count= IOV_MAX;
810 ssize_t rs= writev(conn->fd, conn->xmit, count);
812 if (errno == EAGAIN) return OOP_CONTINUE;
813 connfail(conn, "write failed: %s", strerror(errno));
818 for (done=0; rs && done<xmitu; done++) {
819 struct iovec *vp= &conn->xmit[done];
820 XmitDetails *dp= &conn->xmitd[done];
821 if (rs > vp->iov_len) {
829 int newu= conn->xmitu - done;
830 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
831 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
836 static void conn_make_some_xmits(Conn *conn) {
838 if (conn->xmitu+5 > CONNIOVS)
841 Article *art= LIST_REMHEAD(queue);
844 if (art->checked || (conn->stream && nocheck)) {
845 /* actually send it */
847 ARTHANDLE *artdata= SMretrieve();
851 XMIT_LITERAL("TAKETHIS ");
852 xmit_noalloc(conn, art->mid, art->midlen);
853 XMIT_LITERAL("\r\n");
854 xmit_artbody(conn, artdata);
857 /* we got 235 from IHAVE */
859 xmit_artbody(conn, artdata);
861 XMIT_LITERAL(".\r\n");
866 LIST_ADDTAIL(conn->sent, art);
868 art->ipf->counts[art->checked].sent++;
874 XMIT_LITERAL("IHAVE ");
876 XMIT_LITERAL("CHECK ");
877 xmit_noalloc(art->mid, art->midlen);
878 XMIT_LITERAL("\r\n");
880 LIST_ADDTAIL(conn->sent, art);
881 art->ipf->counts[art->checked].offered++;
887 /*========== handling responses from peer ==========*/
889 static const oop_rd_style peer_rd_style= {
890 OOP_RD_DELIM_STRIP, '\n',
892 OOP_RD_SHORTREC_FORBID
895 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
896 const char *errmsg, int errnoval,
897 const char *data, size_t recsz, void *conn_v) {
899 connfail(conn, "error receiving from peer: %s", errmsg);
903 static Article *article_reply_check(Connection *conn, const char *response,
904 int code_indicates_streaming,
905 const char *sanitised_response) {
906 Article *art= LIST_REMHEAD(conn->sent);
910 "peer gave unexpected response when no commands outstanding: %s",
915 if (code_indicates_streaming) {
916 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
918 connfail("peer gave streaming response code "
919 " to IHAVE or subsequent body: %s", sanitised_response);
922 const char *got_mid= response+4;
923 int got_midlen= strcspn(got_mid, " \n\r");
924 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
925 connfail("peer gave streaming response with syntactically invalid"
926 " messageid: %s", sanitised_response);
929 if (got_midlen != art->midlen ||
930 memcmp(got_mid, art->messageid, got_midlen)) {
931 connfail("peer gave streaming response code to wrong article -"
932 " probable synchronisation problem; we offered: %s;"
934 art->messageid, sanitised_response);
939 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
948 static void update_nocheck(int accepted) {
949 accept_proportion *= accept_decay;
950 accept_proportion += accepted;
951 int new_nocheck= accept_proportion >= nocheck_thresh;
952 if (new_nocheck && !nocheck_reported) {
953 notice("entering nocheck mode for the first time");
955 } else if (new_nocheck != nockech) {
956 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
958 nocheck= new_nocheck;
961 static void article_done(Connection *conn, Article *art, int whichcount) {
963 art->ipf->counts.articles[art->checked][whichcount]++;
964 if (whichcount == RC_accepted) update_nocheck(1);
965 else if (whichcount == RC_unwanted) update_nocheck(0);
967 InputFile *ipf= art->ipf;
968 while (art->blanklen) {
969 static const char spaces[]=
974 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
975 int r= pwrite(ipf->fd, spaces, w, art->offset);
977 if (errno==EINTR) continue;
978 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
979 art->messageid, art->blanklen, art->offset, ipf->path);
981 assert(r>=0 && r<=w);
987 assert(ipf->inprogress >= 0);
989 if (!ipf->inprogress)
990 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, ipf);
995 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
996 const char *errmsg, int errnoval,
997 const char *data, size_t recsz, void *conn_v) {
1000 if (ev == OOP_RD_EOF) {
1001 connfail(conn, "unexpected EOF from peer");
1002 return OOP_CONTINUE;
1004 assert(ev == OOP_RD_OK);
1007 unsigned long code= strtoul(data, &ep, 10);
1008 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1010 const char *p= data;
1014 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
1016 if (!c) { *q++= '\''; break; }
1017 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
1018 sprintf(q,"\\x%02x",c);
1021 connfail(conn, "badly formatted response from peer: %s", sanibuf);
1022 return OOP_CONTINUE;
1025 if (conn->quitting) {
1027 connfail(conn, "peer gave failure response to QUIT: %s", sani);
1028 return OOP_CONTINUE;
1036 #define GET_ARTICLE \
1037 art= article_reply_check(conn, data, code_streaming, sani); \
1038 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1040 #define ARTICLE_DEALTWITH(streaming,how) \
1041 code_streaming= (streaming) \
1043 article_done(conn, art, RC_##how); break;
1045 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1047 int code_streaming= 0;
1051 case 400: PEERBADMSG("peer stopped accepting articles");
1052 case 503: PEERBADMSG("peer timed us out");
1053 default: PEERBADMSG("peer sent unexpected message");
1055 case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
1056 case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
1058 case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
1059 case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
1061 case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
1062 case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
1064 case 238: /* CHECK says send it */
1066 case 335: /* IHAVE says send it */
1068 count_checkedwanted++;
1069 LIST_ADDTAIL(conn->queue);
1071 connfail("peer gave %d response to article body: %s",code, sani);
1072 return OOP_CONTINUE;
1077 case 431: /* CHECK or TAKETHIS says try later */
1079 case 436: /* IHAVE says try later */
1082 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1084 sysfatal("write to defer file %s",path_defer);
1085 article_done(conn, art, RC_deferred);
1090 check_check_work(conn);
1091 return OOP_CONTINUE;
1095 /*========== monitoring of input files ==========*/
1097 static void feedfile_eof(InputFile *ipf) {
1098 assert(ipf != main_input_file); /* promised by tailing_try_read */
1100 inputfile_tailing_stop(ipf);
1102 if (ipf == backlog_input_file) {
1103 assert(ipf->fd >= 0);
1104 if (close(ipf->fd)) sysdie("could not close backlog file %s", ipf->path);
1109 assert(ipf == flushing_input_file);
1111 inputfile_tailing_stop(ipf);
1112 assert(ipf->fd >= 0);
1113 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1116 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1118 if (main_input_file)
1119 inputfile_tailing_start(main_input_file);
1122 static InputFile *open_input_file(const char *path) {
1123 int fd= open(path, O_RDONLY);
1125 if (errno==ENOENT) return 0;
1126 sysfatal("unable to open input file %s", path);
1129 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1130 memset(ipf,0,sizeof(*ipf));
1132 ipf->readable.on_readable= tailing_on_readable;
1133 ipf->readable.on_cancel= tailing_on_cancel;
1134 ipf->readable.try_read= tailing_try_read;
1137 strcpy(ipf->path, path);
1142 static void close_input_file(InputFile *ipf) {
1143 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1144 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1145 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1146 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1149 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1155 /*---------- dealing with articles read in the input file ----------*/
1157 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1158 oop_rd_event ev, const char *errmsg,
1160 const char *data, size_t recsz,
1162 InputFile *ipf= ipf_v;
1164 char tokentextbuf[sizeof(TOKEN)*2+3];
1166 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1168 if (data[0] && data[0]!=' ') {
1169 char *space= strchr(data,' ');
1170 int tokenlen= space-data;
1171 int midlen= (int)recsz-tokenlen-1;
1172 if (midlen < 0) goto bad_data;
1174 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1175 memcpy(tokentextbuf, data, tokenlen);
1176 tokentextbuf[tokenlen]= 0;
1177 if (!IsToken(tokentextbuf)) goto bad_data;
1179 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1180 art->offset= ipf->offset;
1181 art->blanklen= recsz;
1182 art->midlen= midlen;
1183 art->checked= art->sentbody= 0;
1184 art->ipf= ipf; ipf->inprogress++;
1185 art->token= TextToToken(tokentextbuf);
1186 strcpy(art->messageid, space+1);
1187 LIST_ADDTAIL(queue, art);
1189 ipf->offset += recsz + 1;
1191 if (sms==sm_NORMAL && ipf==main_input_file &&
1192 (ipf->offset >= flush_threshold || !until_spontaneous_flush) {
1194 notice("starting flush (%lu >= %lu)",
1195 (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1197 int r= link(feedfile, duct_path);
1198 if (r) sysdie("link feedfile %s to flushing file %s", feedfile, dut_path);
1201 r= unlink(feedfile);
1202 if (r) sysdie("unlink old feedfile link %s", feedfile);
1205 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1208 check_master_queue();
1212 /*========== tailing input file ==========*/
1214 static void filemon_start(InputFile *ipf) {
1215 assert(!ipf->filemon);
1217 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1218 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1219 filemon_method_startfile(ipf, ipf->filemon);
1222 static void filemon_stop(InputFile *ipf) {
1223 if (!ipf->filemon) return;
1224 filemon_method_stopfile(ipf, ipf->filemon);
1229 static void filemon_callback(InputFile *ipf) {
1230 ipf->readable_callback(ipf->readable_callback_user);
1233 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1235 InputFile *ipf= user;
1236 return ipf->readable_callback(ipf->readable_callback_user);
1239 static void on_cancel(struct oop_readable *rable) {
1240 InputFile *ipf= (void*)rable;
1242 if (ipf->filemon) filemon_stopfile(ipf);
1243 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1244 ipf->readable_callback= 0;
1247 static int tailing_on_readable(struct oop_readable *rable,
1248 oop_readable_call *cb, void *user) {
1249 InputFile *ipf= (void*)rable;
1251 tailing_on_cancel(rable);
1252 ipf->readable_callback= cb;
1253 ipf->readable_callback_user= user;
1254 filemon_startfile(ipf);
1256 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1260 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1262 InputFile *ipf= (void*)rable;
1264 ssize_t r= read(ipf->fd, buffer, length);
1266 if (errno==EINTR) continue;
1270 if (ipf==main_input_file) {
1273 } else if (ipf==flushing_input_file) {
1275 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1276 } else if (ipf==backlog_input_file) {
1286 /*---------- filemon implemented with inotify ----------*/
1288 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1289 #define HAVE_FILEMON
1291 #include <linux/inotify.h>
1293 static int filemon_inotify_fd;
1294 static int filemon_inotify_wdmax;
1295 static InputFile **filemon_inotify_wd2ipf;
1297 typedef struct Filemon_Perfile {
1299 } Filemon_Inotify_Perfile;
1301 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1302 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1303 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1305 if (wd >= filemon_inotify_wdmax) {
1307 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1308 sizeof(*filemon_inotify_wd2ipf) * newmax);
1309 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1310 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1311 filemon_inotify_wdmax= newmax;
1314 assert(!filemon_inotify_wd2ipf[wd]);
1315 filemon_inotify_wd2ipf[wd]= ipf;
1317 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1318 ipf, wd, filemon_inotify_wdmax);
1323 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1325 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1326 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1327 if (r) sysdie("inotify_rm_watch");
1328 filemon_inotify_wd2ipf[wd]= 0;
1331 static void *filemon_inotify_readable(oop_source *lp, int fd,
1332 oop_event e, void *u) {
1333 struct inotify_event iev;
1335 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1337 if (errno==EAGAIN) break;
1338 sysdie("read from inotify master");
1339 } else if (r==sizeof(iev)) {
1340 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1342 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1344 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1345 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1346 filemon_callback(ipf);
1348 return OOP_CONTINUE;
1351 static int filemon_method_init(void) {
1352 filemon_inotify_fd= inotify_init();
1353 if (filemon_inotify_fd<0) {
1354 syswarn("could not initialise inotify: inotify_init failed");
1358 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1360 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1364 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1366 /*---------- filemon dummy implementation ----------*/
1368 #if !defined(HAVE_FILEMON)
1370 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1372 static int filemon_method_init(void) { return 0; }
1373 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1374 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1376 #endif /* !HAVE_FILEMON */
1378 /*---------- interface to start and stop an input file ----------*/
1380 static const oop_rd_style feedfile_rdstyle= {
1381 OOP_RD_DELIM_STRIP, '\n',
1383 OOP_RD_SHORTREC_EOF,
1386 static void inputfile_tailing_start(InputFile *ipf) {
1388 ipf->readable->on_readable= tailing_on_readable;
1389 ipf->readable->on_cancel= tailing_on_cancel;
1390 ipf->readable->try_read= tailing_try_read;
1391 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1392 ipf->readable->delete_kill= 0;
1394 ipf->readable_callback= 0;
1395 ipf->readable_callback_user= 0;
1397 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1400 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1401 feedfile_got_article,ipf, feedfile_problem,ipf);
1402 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1405 static void inputfile_tailing_stop(InputFile *ipf) {
1407 oop_rd_cancel(ipf->rd);
1408 oop_rd_delete(ipf->rd);
1410 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1414 /*========== interaction with innd - state machine ==========*/
1416 /* See official state diagram at top of file. We implement
1425 | TIMEOUT and no defer, no backlog
1426 |`--------------------------.
1428 | OPEN F SUCCEEDS | exit
1433 | [Normal] =========
1437 | | F IS SO BIG WE SHOULD FLUSH
1441 | | our handle onto F is now onto D
1444 | |<---------------------------------------------------.
1446 | | spawn inndcomm flush |
1454 | | INNDCOMM FLUSH FAILS ^
1455 | |`----------------------->----------. |
1457 | | NO SUCH SITE V |
1458 ^ |`--------------->----. =========== |
1464 | | \ | TIME TO RETRY |
1465 | | \ `----------------'
1469 | ============= ============
1470 | SEPARATED/ DROPPING/
1471 | flsh->fd>=0 flsh->fd>=0
1472 | [Separated] [Dropping]
1473 | main F idle main none
1474 | old D tail old D tail
1475 | ============= ============
1477 ^ | EOF ON D | EOF ON D
1479 | =============== ===============
1480 | SEPARATED/ DROPPING/
1481 | flsh->fd==-1 flsh->fd==-1
1482 | [Finishing] [Dropping]
1483 | main F tail main none
1484 | old D closed old D closed
1485 | =============== ===============
1487 | | ALL D PROCESSED | ALL D PROCESSED
1488 | V install defer as backlog V install defer as backlog
1489 ^ | close D | close D
1490 | | unlink D | unlink D
1499 static void statemc_init(void) {
1500 struct stat stab, stabf;
1503 path_lock= xasprintf("%s_lock", feedfile);
1504 path_flushing= xasprintf("%s_flushing", feedfile);
1505 path_defer= xasprintf("%s_defer", feedfile);
1506 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1509 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1510 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1513 memset(&fl,0,sizeof(fl));
1515 fl.l_whence= SEEK_SET;
1516 r= fcntl(lockfd, F_SETLK, &fl);
1518 if (errno==EACCES || errno==EAGAIN) {
1519 if (quiet_if_locked) exit(0);
1520 fatal("another duct holds the lockfile");
1522 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1525 xfstat_isreg(lockfd, &stabf, "lockfile");
1526 xlstat_isreg(path_lock, &stab, &noent, "lockfile");
1528 if (!noent && samefile(&stab, &stabf))
1532 sysdie("could not close stale lockfile %s", path_lock);
1534 debug("startup: locked");
1536 search_backlog_file();
1538 xlstat_isreg(path_defer, &stab, &noent, "defer file");
1540 debug("startup: ductdefer ENOENT");
1542 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1543 switch (stab.st_nlink==1) {
1545 open_defer(); /* so that we will later close it and rename it */
1548 if (unlink(path_defer))
1549 sysdie("could not unlink stale defer file link %s (presumably"
1550 " hardlink to backlog file)", path_defer);
1553 die("defer file %s has unexpected link count %d",
1554 path_defer, stab.st_nlink);
1558 InputFile *file_d= open_input_file(path_flushing);
1561 struct stat stab_f, stab_d;
1563 xlstat_isreg(feedfile, &stab_f, &noent, "feed file");
1565 debug("startup: D exists, F ENOENT => Moved");
1569 debug("startup: F and D both exist");
1571 xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1573 if (samefile(&stab_d, &stab_f)) {
1574 debug("startup: F==D => Hardlinked");
1575 r= unlink(path_flushing);
1576 if (r) sysdie("unlink feed file %s during startup", feedfile);
1579 startup_set_input_file(file_d);
1580 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1582 debug("F!=D => Separated");
1583 SMS(SEPARATED, 0, "found both old and current feed files");
1584 startup_set_input_file(file_d);
1587 debug("startup: D ENOENT => Nothing");
1588 SMS(WAITING, open_wait_periods, "no feed file currently exists");
1592 static void statemc_poll(void) {
1593 if (sms==sm_WAITING) { statemc_waiting_poll(); return; }
1595 if (!sm_period_counter) return;
1596 sm_period_counter--;
1597 assert(sm_period_counter>=0);
1599 if (sm_period_counter) return;
1602 fatal("timed out waiting for innd to create feed file %s", feedfile);
1604 spawn_inndcomm_flush(void);
1611 static void statemc_waiting_poll(void) {
1612 InputFile *file_f= open_input_file(feedfile);
1613 if (!file_f) return;
1614 startup_set_input_file(file_d);
1615 SMS(NORMAL, 0, "found and opened feed file");
1618 static void startup_set_input_file(InputFile *f) {
1619 assert(!main_input_file);
1621 until_spontaneous_flush= spontaneous_flush_periods;
1622 inputfile_tailing_start(f);
1625 static void *statemc_check_input_done(oop_source *lp,
1626 struct timeval now, void *ipf_v) {
1627 InputFile *ipf= ipf_v;
1630 if (ipf->inprogress) return; /* new article in the meantime */
1631 if (ipf->fd >= 0); return; /* not had EOF */
1633 if (ipf == backlog_input_file) {
1634 notice_processed(ipf,"backlog file",ipf->path);
1635 close_input_file(ipf);
1636 if (unlink(ipf->path)) {
1637 if (errno != ENOENT)
1638 sysdie("could not unlink processed backlog file %s", ipf->path);
1639 warn("backlog file %s vanished while we were reading it"
1640 " so we couldn't remove it (but it's done now, anyway)",
1643 backlog_input_file= 0;
1644 search_backlog_file();
1648 assert(ipf == flushing_input_file);
1649 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1651 notice_processed(ipf,"feed file",0);
1655 if (unlink(path_flushing))
1656 sysdie("could not unlink old flushing file %s", path_flushing);
1658 if (sms==sm_DROPPING) {
1659 if (search_backlog_file()) {
1660 debug("feed dropped but still backlogs to process");
1663 notice("feed dropped and our work is complete");
1664 r= unlink(path_lock);
1665 if (r) sysdie("unlink lockfile for old feed %s", path_lock);
1671 close_input_file(flushing_input_file);
1672 flushing_input_file= 0;
1674 notice("flush complete");
1675 SMS(NORMAL, 0, "flush complete");
1678 static void statemc_setstate(StateMachineState newsms, int periods,
1679 const char *forlog, const char *why) {
1681 sm_period_counter= periods;
1683 info("%s[%d] %s",periods,forlog,why);
1685 info("%s %s",forlog,why);
1689 /*---------- defer and backlog files ----------*/
1691 static void open_defer(void) {
1696 defer= fopen(path_defer, "a+");
1697 if (!defer) sysfatal("could not open defer file %s", path_defer);
1699 /* truncate away any half-written records */
1701 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1703 if (stab.st_size > LONG_MAX)
1704 die("defer file %s size is far too large", path_defer);
1709 long orgsize= stab.st_size;
1710 long truncto= stab.st_size;
1712 if (!truncto) break; /* was only (if anything) one half-truncated record */
1713 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1714 sysdie("seek in defer file %s while truncating partial", path_defer);
1719 sysdie("failed read from defer file %s", path_defer);
1721 die("defer file %s shrank while we were checking it!", path_defer);
1727 if (stab.st_size != truncto) {
1728 warn("truncating half-record at end of defer file %s -"
1729 " shrinking by %ld bytes from %ld to %ld",
1730 path_defer, orgsize - truncto, orgsize, truncto);
1733 sysfatal("could not flush defer file %s", path_defer);
1734 if (ftruncate(fileno(defer), truncto))
1735 sysdie("could not truncate defer file %s", path_defer);
1738 info("continuing existing defer file %s (%ld bytes)",
1739 path_defer, orgsize);
1741 if (fseek(defer, truncto, SEEK_SET))
1742 sysdie("could not seek to new end of defer file %s", path_defer);
1745 static void close_defer(void) {
1749 xfstat(fileno(defer), &stab, "defer file");
1751 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1754 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1755 (unsigned long)now.tv_sec,
1756 (unsigned long)stab.st_ino);
1757 if (link(path_defer, path_backlog))
1758 sysfatal("could not install defer file %s as backlog file %s",
1759 path_defer, backlog);
1760 if (unlink(path_defer))
1761 sysdie("could not unlink old defer link %s to backlog file %s",
1762 path_defer, backlog);
1764 if (until_backlog_nextscan < 0 ||
1765 until_backlog_nextscan > backlog_retry_minperiods + 1)
1766 until_backlog_nextscan= backlog_retry_minperiods + 1;
1769 static void poll_backlog_file(void) {
1770 if (until_backlog_nextscan < 0) return;
1771 if (until_backlog_nextscan-- > 0) return;
1772 search_backlog_file();
1775 static int search_backlog_file(void) {
1776 /* returns non-0 iff there are any backlog files */
1781 const char *oldest_path=0;
1782 time_t oldest_mtime, now;
1784 if (backlog_input_file) return 3;
1788 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
1792 sysdie("failed to expand backlog pattern %s", globpat_backlog);
1794 die("out of memory expanding backlog pattern %s", globpat_backlog);
1796 for (i=0; i<gl.gl_pathc; i++) {
1797 const char *path= gl.gl_pathv[i];
1799 if (strchr(path,'#') || strchr(path,'~')) {
1800 debug("backlog file search skipping %s", path);
1803 r= stat(path, &stab);
1805 syswarn("failed to stat backlog file %s", path);
1808 if (!S_ISREG(stab.st_mode)) {
1809 warn("backlog file %s is not a plain file (or link to one)", path);
1812 if (!oldest_path || stab.st_mtime < oldest_mtime) {
1814 oldest_mtime= stab.st_mtime;
1817 case GLOB_NOMATCH: /* fall through */
1820 sysdie("glob expansion of backlog pattern %s gave unexpected"
1821 " nonzero (error?) return value %d", globpat_backlog, r);
1827 debug("backlog scan: none");
1828 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
1832 now= time(); if (now==-1) sysdie("time(2) failed");
1833 double age= difftime(now, oldest_mtime);
1834 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
1836 if (age_deficiency <= 0) {
1837 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
1838 age, age_deficiency, oldest_path);
1840 backlog_input_file= open_input_file(oldest_path);
1841 if (!backlog_input_file) {
1842 warn("backlog file %s vanished as we opened it", backlog_input_file);
1845 inputfile_tailing_start(backlog_input_file);
1846 until_backlog_nextscan= -1;
1850 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
1852 if (backlog_spontaneous_rescan_periods >= 0 &&
1853 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
1854 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
1856 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
1857 age, age_deficiency, until_backlog_nextscan, oldest_path);
1861 /*========== flushing the feed ==========*/
1863 static pid_t inndcomm_child;
1865 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1866 assert(inndcomm_child);
1867 int status= xwaitpid(&inndcomm_child, "inndcomm");
1868 loop->cancel_fd(fd);
1871 assert(!flushing_input_file);
1873 if (WIFEXITED(status)) {
1874 switch (WEXITSTATUS(status)) {
1876 case INNDCOMMCHILD_ESTATUS_FAIL:
1879 case INNDCOMMCHILD_ESTATUS_NONESUCH:
1880 warn("feed has been dropped by innd, finishing up");
1881 flushing_input_file= main_input_file;
1883 SMS(DROPPING, 0, "dropped by innd");
1884 return OOP_CONTINUE;
1887 flushing_input_file= main_input_file;
1888 main_input_file= open_input_file(feedfile);
1889 if (!main_input_file)
1890 die("flush succeeded but feedfile %s does not exist!", feedfile);
1891 until_spontaneous_flush= spontaneous_flush_periods;
1892 SMS(SEPARATED, 0, "feed file missing");
1893 return OOP_CONTINUE;
1896 goto unexpected_exitstatus;
1899 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1900 warn("flush timed out trying to talk to innd");
1903 unexpected_exitstatus:
1904 report_child_status("inndcomm child", status);
1908 SMS(FLUSHFAIL, flushfail_retry_periods, "flush failed, will retry");
1911 static void inndcommfail(const char *what) {
1912 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1913 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1916 void spawn_inndcomm_flush(void) {
1919 assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1920 assert(!inndcomm_child);
1922 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1924 inndcomm_child= xfork();
1926 if (!inndcomm_child) {
1927 static char flushargv[2]= { sitename, 0 };
1932 alarm(inndcomm_flush_timeout);
1933 r= ICCopen(); if (r) inndcommfail("connect");
1934 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
1935 if (!r) exit(0); /* yay! */
1937 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1938 syswarn("innd ctlinnd flush failed: innd said %s", reply);
1939 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1943 int sentinel_fd= pipefds[0];
1944 on_fd_read_except(sentinel_fd, inndcomm_event);
1946 SMS(FLUSHING, 0, "flush is in progress");
1949 /*========== main program ==========*/
1951 static void postfork_inputfile(InputFile *ipf) {
1953 assert(ipf->fd >= 0);
1958 static void postfork_conns(Connection *conn) {
1965 static void postfork_stdio(FILE *f) {
1966 /* we have no stdio streams that are buffered long-term */
1970 static void postfork(const char *what) {
1971 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1972 sysdie("%s child: failed to reset SIGPIPE");
1974 postfork_inputfile(main_input_file);
1975 postfork_inputfile(flushing_input_file);
1976 postfork_conns(idle.head);
1977 postfork_conns(working.head);
1978 postfork_conns(full.head);
1979 postfork_stdio(defer);
1982 #define EVERY(what, interval, body) \
1983 static const struct timeval what##_timeout = { 5, 0 }; \
1984 static void what##_schedule(void); \
1985 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1987 what##_schedule(); \
1989 static void what##_schedule(void) { \
1990 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
1993 EVERY(filepoll, {5,0}, {
1994 if (main_input_file && main_input_file->readable_callback)
1995 filemon_callback(main_input_file);
1998 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s" \
1999 #define DEBUG_IPF(sh) \
2000 wh##_input_file, debug_ipf_path(wh##_input_file), \
2001 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2002 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2003 static const char *debug_ipf_path(InputFile *ipf) {
2004 char *slash= strrchr(ipf->path,'/');
2005 return slash ? slash+1 : ipf->path;
2008 EVERY(period, {PERIOD_SECONDS,0}, {
2010 " sms=%s queue=%d sm_period_counter=%d"
2011 " connect_delay=%d until_spontaneous_flush=%d"
2012 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_FMT(flushing)
2013 " conns idle=%d working=%d full=%d"
2014 " children connecting=%ld inndcomm_child"
2016 sms_names[sms], queue.count, sm_period_counter,
2017 connect_delay, until_spontaneous_flush,
2018 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2019 idle.count, working.count, full.count,
2020 (long)connecting_child, (long)inndcomm_child
2022 if (connect_delay) connect_delay--;
2023 if (until_spontaneous_flush) until_spontaneous_flush--;
2024 poll_backlog_file();
2025 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2027 check_master_queue();
2031 /*========== option parsing ==========*/
2034 of_seconds= 001000u;
2035 of_boolean= 002000u;
2038 typedef struct Option Option;
2039 typedef void OptionParser(const Option*, const char *val);
2049 void op_integer(const Option *o, const char *val) {
2052 unsigned long ul= strtoul(val,&ep,10);
2053 if (*ep || ep==val || errno || ul>INT_MAX)
2054 badusage("bad integer value for %s",o->long);
2055 int *store= o->store;
2059 void op_double(const Option *o, const char *val) {
2060 int *store= o->store;
2063 *store= strtod(val, &ep);
2064 if (*ep || ep==val || errno)
2065 badusage("bad floating point value for %s",o->long);
2068 void op_string(const Option *o, const char *val) {
2069 char **store= o->store;
2074 void op_seconds(const Option *o, const char *val) {
2075 int *store= o->store;
2078 double v= strtod(val,&ep);
2079 if (ep==val) badusage("bad time/duration value for %s",o->long);
2081 if (!*ep || !strcmp(ep,"s")) unit= 1;
2082 else if (!strcmp(ep,"m")) unit= 60;
2083 else if (!strcmp(ep,"h")) unit= 3600;
2084 else if (!strcmp(ep,"d")) unit= 86400;
2085 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2089 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2093 void op_periods_rndup(const Option *o, const char *val) {
2094 int *store= o->store;
2096 *store += PERIOD_SECONDS-1;
2097 *store /= PERIOD_SECONDS;
2100 void op_periods_booltrue(const Option *o, const char *val) {
2101 int *store= o->store;
2104 void op_periods_boolfalse(const Option *o, const char *val) {
2105 int *store= o->store;
2109 static const Option options[]= {
2110 { 0, "max-connections", &max_connections op_integer },
2111 { 0, "streaming", &try_stream, op_booltrue, 1 },
2112 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2113 {'h',"host", &remote_host, op_string },
2114 {'P',"port", &port op_integer },
2115 { 0, "inndconf", &inndconffile, op_string },
2116 {'f',"feedfile", &feedfile, op_string },
2117 {'q',"quiet-multiple", &quiet_if_locked, op_booltrue, 1 },
2118 { 0, "no-quiet-multiple", &quiet_if_locked, op_boolfalse, 1 },
2119 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2120 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2122 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2123 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2125 { 0, "max-queue-size", &max_queue_per_conn op_integer },
2126 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2127 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2128 { 0, "feedfile-open-timeout", &open_wait_periods, op_periods_rndup },
2129 { 0, "connection-timeout", &connection_timeout, op_seconds },
2130 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2133 int main(int argc, char **argv) {
2139 if (*arg != '-') break;
2140 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2142 while ((a= *++arg)) {
2146 char *equals= strchr(arg,'=');
2147 int len= equals ? (equals - arg) : strlen(arg);
2148 for (o=options; o->long; o++)
2149 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2151 badusage("unknown long option --%s",arg);
2154 if (equals) badusage("option --%s does not take a value",o->long);
2156 } else if (equals) {
2160 if (!arg) badusage("option --%s needs a value",o->long);
2163 break; /* eaten the whole argument now */
2165 for (o=options; o->long; o++)
2168 badusage("unknown short option -%c",a);
2175 if (!arg) badusage("option -%c needs a value",o->short);
2178 break; /* eaten the whole argument now */
2183 if (!arg) badusage("need site name argument");
2186 if ((arg= *++argv)) {
2187 if (remote_host) badusage("must not specify -h and also host as argument");
2191 if (*++argv) badusage("too many non-option arguments");
2193 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2194 badusage("nocheck threshold percentage must be between 0..100");
2195 nocheck_thresh= nocheck_thresh_pct * 0.01;
2197 if (nocheck_decay_articles < 0.1)
2198 badusage("nocheck decay articles must be at least 0.1");
2199 nocheck_decay= 1 - 1/nocheck_decay_articles;
2201 innconf_read(inndconffile);
2204 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2205 else if (!feedfile[0])
2206 badusage("feed filename must be nonempty");
2207 else if (feedfile[strlen(feedfile)-1]=='/')
2208 feedfile= xasprintf("%s%s",feedfile,sitename);
2210 const char *feedfile_forbidden= "?*[~#";
2212 while ((c= *feedfile_forbidden++))
2213 if (strchr(feedfile, c))
2214 badusage("feed filename may not contain metacharacter %c",c);
2216 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2217 sysdie("could not ignore SIGPIPE");
2219 if (become_daemon) {
2220 for (i=3; i<255; i++)
2221 /* do this now before we open syslog, etc. */
2223 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2225 int null= open("/dev/null",O_RDWR);
2226 if (null<0) sysdie("failed to open /dev/null");
2232 pid_t child1= xfork("daemonise first fork");
2233 if (child1) _exit(0);
2235 pid_t sid= setsid();
2236 if (sid != child1) sysdie("setsid failed");
2238 pid_t child2= xfork("daemonise second fork");
2239 if (child2) _exit(0);
2244 if (!filemon_init()) {
2245 warn("no file monitoring available, polling");
2246 filepoll_schedule();