3 * - close idle connections
4 * - cope better with garbage in feed file
5 * - cope better with NULs in feed file
10 * Newsfeeds file entries should look like this:
11 * host.name.of.site[/exclude,exclude,...]\
12 * :pattern,pattern...[/distribution,distribution...]\
16 * sitename[/exclude,exclude,...]\
17 * :pattern,pattern...[/distribution,distribution...]\
23 * or might be blanked out
24 * <spc><spc><spc><spc>....
26 * F site.name main feed file
27 * opened/created, then written, by innd
30 * tokens blanked out by duct when processed
31 * site.name_lock lock preventing multiple ducts
32 * to hold lock must open,F_SETLK[W]
33 * and then stat to check that locked file
34 * still has name site.name_lock
35 * holder of this lock is "duct"
36 * (only) lockholder may remove the lockfile
37 * D site.name_flushing temporary feed file during flush (or crash)
38 * hardlink created by duct
40 * site.name_defer 431'd articles, still being written,
41 * created, written, used by duct
43 * site.name_backlog.<date>.<inum>
44 * 431'd articles, ready for innxmit or duct
45 * created (link/mv) by duct
46 * site.name_backlog<anything-else> (where <anything-else> does not
47 * contain '#' or '~') eg
48 * site.name_backlog.manual
49 * anything the sysadmin likes (eg, feed files
50 * from old feeds to be merged into this one)
51 * created (link/mv) by admin
52 * may be symlinks (in which case links
53 * may be written through, but only links
56 * It is safe to remove backlog files manually,
57 * if it's desired to throw away the backlog.
59 * Backlog files are also processed by innduct. We find the oldest
60 * backlog file which is at least a certain amount old, and feed it
61 * back into our processing. When every article in it has been read
62 * and processed, we unlink it and look for another backlog file.
64 * If we don't have a backlog file that we're reading, we close the
65 * defer file that we're writing and make it into a backlog file at
66 * the first convenient opportunity.
77 | | <----------------<---------------------------------'|
83 | F: innd writing, duct reading |
86 | | duct decides time to flush |
87 | | duct makes hardlink |
89 | V <------------------------'|
91 | F == D: innd writing, duct reading both exist |
94 | | <-----------<-------------<--'|
98 | V <---------------------. |
101 | D: innd writing, duct reading; or ENOENT | |
103 | | duct requests flush of feed | |
104 | | (others can too, harmlessly) | |
108 | D: innd flushing, duct; or ENOENT | |
110 | | inndcomm flush fails | |
111 | |`-------------------------->------------------' |
113 | | inndcomm reports no such site |
114 | |`---------------------------------------------------- | -.
116 | | innd finishes writing D, creates F | |
117 | | inndcomm reports flush successful | |
120 | Separated <----------------' |
121 | F: innd writing F!=D /
122 | D: duct reading; or ENOENT both exist /
124 | | duct gets to the end of D /
125 | | duct opens F too /
128 | F: innd writing, duct reading |
129 | D: duct finishing V
131 | | duct finishes processing D F: ENOENT
132 | V duct unlinks D D: duct reading
134 `--<--' | duct finishes
144 "duct reading" means innduct is reading the file but also
145 overwriting processed tokens.
149 * rune for printing diagrams:
151 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
156 /*============================== PROGRAM ==============================*/
160 #include "inn/list.h"
167 #include <sys/types.h>
168 #include <sys/wait.h>
169 #include <sys/stat.h>
170 #include <sys/socket.h>
183 #include <oop-read.h>
185 /*----- general definitions, probably best not changed -----*/
187 #define PERIOD_SECONDS 60
189 #define CONNCHILD_ESTATUS_STREAM 4
190 #define CONNCHILD_ESTATUS_NOSTREAM 5
192 #define INNDCOMMCHILD_ESTATUS_FAIL 6
193 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
195 /*----- doubly linked lists -----*/
197 #define ISNODE(T) struct { T *succ, *pred; } node /* must be at start */
198 #define DEFLIST(T) typedef struct { T *hd, *tl, *tp; int count; } T##List
200 #define NODE(n) (assert((void*)&(n)->node == &(n)), \
201 (struct node*)&(n)->node)
203 #define LIST_CHECKCANHAVENODE(l,n) \
204 ((void)((n) == ((l).hd))) /* just for the type check */
206 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
207 ( LIST_CHECKCANHAVENODE(l,n), \
208 list_addsomehow((struct list*)&(l), NODE((n))), \
212 #define LIST_REMSOMEHOW(l,list_remsomehow) \
216 list_remsomehow((struct list*)&(l)) ) \
222 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
223 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
224 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
225 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
227 #define LIST_HEAD(l) ((typeof((l).hd))(list_head((struct list*)&(l))))
228 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
229 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
231 #define LIST_REMOVE(l,n) \
232 ( LIST_CHECKCANHAVENODE(l,n), \
233 list_remove(NODE((n))), \
237 #define LIST_INSERT(l,n,pred) \
238 ( LIST_CHECKCANHAVENODE(l,n), \
239 LIST_CHECKCANHAVENODE(l,pred), \
240 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
244 /*----- type predeclarations -----*/
246 typedef struct Conn Conn;
247 typedef struct Article Article;
248 typedef struct InputFile InputFile;
249 typedef struct XmitDetails XmitDetails;
250 typedef struct Filemon_Perfile Filemon_Perfile;
251 typedef enum StateMachineState StateMachineState;
256 /*----- function predeclarations -----*/
258 static void conn_maybe_write(Conn *conn);
259 static void conn_make_some_xmits(Conn *conn);
260 static void *conn_write_some_xmits(Conn *conn);
262 static void xmit_free(XmitDetails *d);
264 static void statemc_setstate(StateMachineState newsms, int periods,
265 const char *forlog, const char *why);
266 static void check_master_queue(void);
267 static void queue_check_input_done(void);
269 static void statemc_start_flush(const char *why); /* Normal => Flushing */
270 static void statemc_check_flushing_done(void);
271 static void statemc_check_backlog_done(void);
273 static void postfork(const char *what);
274 static void postfork_inputfile(InputFile *ipf);
276 static void open_defer(void);
278 static void inputfile_tailing_start(InputFile *ipf);
279 static void inputfile_tailing_stop(InputFile *ipf);
281 static int filemon_init(void);
282 static void filemon_start(InputFile *ipf);
283 static void filemon_stop(InputFile *ipf);
284 static void filemon_callback(InputFile *ipf);
286 /*----- configuration options -----*/
288 static char *sitename, *feedfile;
289 static const char *remote_host;
290 static int quiet_multiple=0, become_daemon=1;
292 static int max_connections=10, max_queue_per_conn=200;
293 static int target_max_feedfile_size=100000;
295 static double max_bad_data_ratio= 0.01;
296 static int max_bad_data_initial= 30;
297 /* in one corrupt 4096-byte block the number of newlines has
298 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
300 static int connection_setup_timeout=200, port=119, try_stream=1;
301 static int inndcomm_flush_timeout=100;
302 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
303 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
304 static const char *inndconffile;
306 static double accept_proportion;
307 static double nocheck_thresh_pct= 95.0;
308 static double nocheck_thresh; /* computed in main from _pct */
309 static double nocheck_decay_articles= 100; /* converted to _decay */
310 static double nocheck_decay; /* computed in main from _articles */
311 static int nocheck, nocheck_reported;
314 /*----- statistics -----*/
316 typedef enum { /* in queue in conn->sent */
317 art_Unchecked, /* not checked, not sent checking */
318 art_Wanted, /* checked, wanted sent body as requested */
319 art_Unsolicited, /* - sent body without check */
323 #define RESULT_COUNTS(RCS,RCN) \
331 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
332 #define RCI_TRIPLE_VALS_BASE(counts,x) \
333 counts[art_Unchecked] x \
334 + counts[art_Wanted] x \
335 + counts[art_Unsolicited] x, \
336 counts[art_Unchecked] x \
337 , counts[art_Wanted] x \
338 , counts[art_Unsolicited] x
341 #define RC_INDEX(x) RC_##x,
342 RESULT_COUNTS(RC_INDEX, RC_INDEX)
347 /*----- transmission buffers -----*/
352 xk_Malloc, xk_Const, xk_Artdata
364 /*----- core operational data structure types -----*/
367 /* This is also an instance of struct oop_readable */
368 struct oop_readable readable; /* first */
369 oop_readable_call *readable_callback;
370 void *readable_callback_user;
373 Filemon_Perfile *filemon;
376 long inprogress; /* no. of articles read but not processed */
379 int counts[art_MaxState][RCI_max];
380 int readcount_ok, readcount_blank, readcount_err;
395 #define SMS_LIST(X) \
403 enum StateMachineState {
404 #define SMS_DEF_ENUM(s) sm_##s,
405 SMS_LIST(SMS_DEF_ENUM)
408 static const char *sms_names[]= {
409 #define SMS_DEF_NAME(s) #s ,
410 SMS_LIST(SMS_DEF_NAME)
416 int fd, max_queue, stream, quitting;
417 ArticleList waiting; /* not yet told peer */
418 ArticleList priority; /* peer says send it now */
419 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
420 struct iovec xmit[CONNIOVS];
421 XmitDetails xmitd[CONNIOVS];
426 /*----- operational variables -----*/
428 static oop_source *loop;
430 static int until_connect;
431 static ConnList conns;
432 static ArticleList queue;
434 static char *path_lock, *path_flushing, *path_defer;
436 #define SMS(newstate, periods, why) \
437 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
439 static StateMachineState sms;
441 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
442 static int sm_period_counter;
445 /*========== logging ==========*/
447 static void logcore(int sysloglevel, const char *fmt, ...)
448 __attribute__((__format__(printf,2,3)));
449 static void logcore(int sysloglevel, const char *fmt, ...) {
453 vsyslog(sysloglevel,fmt,al);
455 vfprintf(stderr,fmt,al);
461 static void logv(int sysloglevel, const char *pfx, int errnoval,
462 int exitstatus, const char *fmt, va_list al)
463 __attribute__((__format__(printf,5,0)));
464 static void logv(int sysloglevel, const char *pfx, int errnoval,
465 int exitstatus, const char *fmt, va_list al) {
466 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
467 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
468 msgbuf[sizeof(msgbuf)-1]= 0;
470 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
471 sysloglevel= LOG_ERR; /* run by wrong user, probably */
473 logcore(sysloglevel, "<%s>%s: %s%s%s",
474 sitename, pfx, msgbuf,
475 errnoval>=0 ? ": " : "",
476 errnoval>=0 ? strerror(errnoval) : "");
479 #define logwrap(fn, pfx, sysloglevel, err, estatus) \
480 static void fn(const char *fmt, ...) \
481 __attribute__((__format__(printf,1,2))); \
482 static void fn(const char *fmt, ...) { \
485 logv(sysloglevel, pfx, err, estatus, fmt, al); \
488 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
489 logwrap(die, " critical", LOG_CRIT, -1, 16);
491 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
492 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
494 logwrap(syswarn, " warning", LOG_WARNING, errno, 0);
495 logwrap(warn, " warning", LOG_WARNING, -1, 0);
497 logwrap(notice, "", LOG_NOTICE, -1, 0);
498 logwrap(info, " info", LOG_INFO, -1, 0);
499 logwrap(debug, " debug", LOG_DEBUG, -1, 0);
502 /*========== utility functions etc. ==========*/
504 static char *xvasprintf(const char *fmt, va_list al)
505 __attribute__((__format__(printf,1,0)));
506 static char *xvasprintf(const char *fmt, va_list al) {
508 int rc= vasprintf(&str,fmt,al);
509 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
512 static char *xasprintf(const char *fmt, ...)
513 __attribute__((__format__(printf,1,2)));
514 static char *xasprintf(const char *fmt, ...) {
517 char *str= xvasprintf(fmt,al);
522 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
524 static pid_t xfork(const char *what) {
528 if (child==-1) sysdie("cannot fork for %s",what);
529 if (!child) postfork(what);
530 debug("forked %s %ld", what, (unsigned long)child);
534 static void on_fd_read_except(int fd, oop_call_fd callback) {
535 loop->on_fd(loop, fd, OOP_READ, callback, 0);
536 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
538 static void cancel_fd_read_except(int fd) {
539 loop->cancel_fd(loop, fd, OOP_READ);
540 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
543 static void report_child_status(const char *what, int status) {
544 if (WIFEXITED(status)) {
545 int es= WEXITSTATUS(status);
547 warn("%s: child died with error exit status %d",es);
548 } else if (WIFSIGNALED(status)) {
549 int sig= WTERMSIG(status);
550 const char *sigstr= strsignal(sig);
551 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
553 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
555 warn("%s: child died due to unknown fatal signal %d%s",
556 what, sig, coredump);
558 warn("%s: child died with unknown wait status %d", status);
562 static int xwaitpid(pid_t *pid, const char *what) {
565 int r= kill(*pid, SIGKILL);
566 if (r) sysdie("cannot kill %s child", what);
568 pid_t got= waitpid(*pid, &status, WNOHANG);
569 if (got==-1) sysdie("cannot reap %s child", what);
576 static void xunlink(const char *path, const char *what) {
578 if (r) sysdie("can't unlink %s %s", path, what);
581 static void check_isreg(const struct stat *stab, const char *path,
583 if (!S_ISREG(stab->st_mode))
584 die("%s %s not a plain file (mode 0%lo)",
585 what, path, (unsigned long)stab->st_mode);
588 static void xfstat(int fd, struct stat *stab_r, const char *what) {
589 int r= fstat(fd, stab_r);
590 if (r) sysdie("could not fstat %s", what);
593 static void xfstat_isreg(int fd, struct stat *stab_r,
594 const char *path, const char *what) {
595 xfstat(fd, stab_r, what);
596 check_isreg(stab_r, path, what);
599 static void xlstat_isreg(const char *path, struct stat *stab,
600 int *enoent_r /* 0 means ENOENT is fatal */,
602 int r= lstat(path, stab);
604 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
605 sysdie("could not lstat %s %s", what, path);
607 if (enoent_r) *enoent_r= 0;
608 check_isreg(stab, path, what);
611 static void setnonblock(int fd, int nonblocking) {
612 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
613 if (nonblocking) r |= O_NONBLOCK;
614 else r &= ~O_NONBLOCK;
615 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
618 static int samefile(const struct stat *a, const struct stat *b) {
619 assert(S_ISREG(a->st_mode));
620 assert(S_ISREG(b->st_mode));
621 return (a->st_ino == b->st_ino &&
622 a->st_dev == b->st_dev);
625 static char *sanitise(const char *input) {
626 static char sanibuf[100]; /* returns pointer to this buffer! */
628 const char *p= input;
632 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
634 if (!c) { *q++= '\''; *q=0; break; }
635 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
636 sprintf(q,"\\x%02x",c);
642 /*========== making new connections ==========*/
644 static void conn_dispose(Conn *conn) {
646 perhaps_close(&conn->fd);
648 until_connect= reconnect_delay_periods;
651 static int connecting_sockets[2]= {-1,-1};
652 static pid_t connecting_child;
654 static void connect_attempt_discard(void) {
655 if (connecting_sockets[0])
656 cancel_fd_read_except(connecting_sockets[0]);
658 perhaps_close(&connecting_sockets[0]);
659 perhaps_close(&connecting_sockets[1]);
661 if (connecting_child) {
662 int r= kill(connecting_child, SIGTERM);
663 if (r) syswarn("failed to kill connecting child");
664 int status= xwaitpid(&connecting_child, "connect");
666 if (!(WIFEXITED(status) ||
667 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
668 report_child_status("connect", status);
672 #define PREP_DECL_MSG_CMSG(msg) \
674 memset(&msg,0,sizeof(msg)); \
675 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
676 msg.msg_control= msg##cbuf; \
677 msg.msg_controllen= sizeof(msg##cbuf);
679 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
682 conn= xmalloc(sizeof(*conn));
683 memset(conn,0,sizeof(*conn));
685 PREP_DECL_MSG_CMSG(msg);
686 struct cmsghdr *h= 0;
687 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
688 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
691 pid_t got= waitpid(connecting_child, &status, WNOHANG);
693 assert(got==connecting_child);
695 if (WIFEXITED(status) &&
696 (WEXITSTATUS(status) != 0 &&
697 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
698 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
699 /* child already reported the problem */
700 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
701 warn("connect: connection attempt timed out");
702 } else if (!WIFEXITED(status)) {
703 report_child_status("connect", status);
704 /* that's probably the root cause then */
707 /* child is still running apparently, report the socket problem */
709 syswarn("connect: read from child socket failed");
710 else if (e == OOP_EXCEPTION)
711 warn("connect: unexpected exception on child socket");
713 warn("connect: unexpected EOF on child socket");
718 #define CHK(field, val) \
719 if (h->cmsg_##field != val) { \
720 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
723 CHK(level, SOL_SOCKET);
724 CHK(type, SCM_RIGHTS);
725 CHK(len, CMSG_LEN(sizeof(conn->fd)));
728 if (CMSG_NXTHDR(&msg,h)) { die("connect: child sent many cmsgs"); goto x; }
730 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
733 pid_t got= waitpid(connecting_child, &status, 0);
734 if (got==-1) sysdie("connect: real wait for child");
735 assert(got == connecting_child);
738 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
739 int es= WEXITSTATUS(status);
741 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
742 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
744 fatal("connect: child gave unexpected exit status %d", es);
748 setnonblock(conn->fd, 1);
749 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
750 LIST_ADDHEAD(conns, conn);
751 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
752 connect_attempt_discard();
753 check_master_queue();
758 connect_attempt_discard();
761 static int allow_connect_start(void) {
762 return conns.count < max_connections
767 static void connect_start(void) {
768 assert(!connecting_sockets[0]);
769 assert(!connecting_sockets[1]);
770 assert(!connecting_child);
772 notice("starting connection attempt");
774 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
775 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
777 connecting_child= xfork("connection");
779 if (!connecting_child) {
780 FILE *cn_from, *cn_to;
781 char buf[NNTP_STRLEN+100];
782 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
784 r= close(connecting_sockets[0]);
785 if (r) sysdie("connect: close parent socket in child");
787 alarm(connection_setup_timeout);
788 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
789 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
790 else sysfatal("connect: connection attempt failed");
792 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
793 sysfatal("connect: authentication failed");
795 if (fputs("MODE STREAM\r\n", cn_to) ||
797 sysfatal("connect: could not send MODE STREAM");
798 buf[sizeof(buf)-1]= 0;
799 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
801 sysfatal("connect: could not read response to MODE STREAM");
803 fatal("connect: connection close in response to MODE STREAM");
808 fatal("connect: response to MODE STREAM is too long: %.100s...",
809 remote_host, sanitise(buf));
810 l--; if (l>0 && buf[l-1]=='\r') l--;
813 int rcode= strtoul(buf,&ep,10);
815 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
819 exitstatus= CONNCHILD_ESTATUS_STREAM;
825 warn("connect: unexpected response to MODE STREAM: %.50s",
831 int fd= fileno(cn_from);
833 PREP_DECL_MSG_CMSG(msg);
834 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
835 cmsg->cmsg_level= SOL_SOCKET;
836 cmsg->cmsg_type= SCM_RIGHTS;
837 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
838 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
840 msg.msg_controllen= cmsg->cmsg_len;
841 r= sendmsg(connecting_sockets[1], &msg, 0);
842 if (r) sysdie("sendmsg failed for new connection");
847 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
848 if (r) sysdie("connect: close child socket in parent");
850 on_fd_read_except(connecting_sockets[0], connchild_event);
854 connect_attempt_discard();
858 /*========== overall control of article flow ==========*/
860 static void check_master_queue(void) {
868 /* Find a connection to offer this article. We prefer a busy
869 * connection to an idle one, provided it's not full. We take the
870 * first (oldest) and since that's stable, it will mean we fill up
871 * connections in order. That way if we have too many
872 * connections, the spare ones will go away eventually.
874 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
875 int inqueue= walk->sent.count + walk->priority.count
876 + walk->waiting.count;
877 spare= walk->max_queue - inqueue;
878 assert(inqueue <= max_queue_per_conn);
880 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
881 else if (spare>0) /*working*/ { use= walk; break; }
885 Article *art= LIST_REMHEAD(queue);
886 LIST_ADDTAIL(use->waiting, art);
889 conn_maybe_write(use);
890 } else if (allow_connect_start()) {
891 until_connect= reconnect_delay_periods;
900 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
905 static void conn_maybe_write(Conn *conn) {
908 conn_make_some_xmits(conn);
910 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
914 void *rp= conn_write_some_xmits(conn);
915 if (rp==OOP_CONTINUE) {
916 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
918 } else if (rp==OOP_HALT) {
921 /* transmitted everything */
928 static void vconnfail(Conn *conn, const char *fmt, va_list al)
929 __attribute__((__format__(printf,2,0)));
931 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
932 int requeue[art_MaxState];
935 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
936 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
937 while ((art= LIST_REMHEAD(conn->sent))) {
938 requeue[art->state]++;
939 if (art->state==art_Unsolicited) art->state= art_Unchecked;
940 LIST_ADDTAIL(queue,art);
945 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
948 char *m= xvasprintf(fmt,al);
949 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
950 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
953 LIST_REMOVE(conns,conn);
955 check_master_queue();
958 static void connfail(Conn *conn, const char *fmt, ...)
959 __attribute__((__format__(printf,2,3)));
960 static void connfail(Conn *conn, const char *fmt, ...) {
963 vconnfail(conn,fmt,al);
967 /*========== article transmission ==========*/
969 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
970 XmitKind kind) { /* caller must then fill in details */
971 struct iovec *v= &conn->xmit[conn->xmitu];
972 XmitDetails *d= &conn->xmitd[conn->xmitu++];
973 v->iov_base= (char*)data;
979 static void xmit_noalloc(Conn *conn, const char *data, int len) {
980 xmit_core(conn,data,len, xk_Const);
982 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
984 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
985 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
989 static void xmit_free(XmitDetails *d) {
991 case xk_Malloc: free(d->info.malloc_tofree); break;
992 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
993 case xk_Const: break;
998 static void *conn_write_some_xmits(Conn *conn) {
1000 * 0: nothing more to write, no need to call us again
1001 * OOP_CONTINUE: more to write but fd not writeable
1002 * OOP_HALT: disaster, have destroyed conn
1005 int count= conn->xmitu;
1006 if (!count) return 0;
1008 if (count > IOV_MAX) count= IOV_MAX;
1009 ssize_t rs= writev(conn->fd, conn->xmit, count);
1011 if (errno == EAGAIN) return OOP_CONTINUE;
1012 connfail(conn, "write failed: %s", strerror(errno));
1018 for (done=0; rs && done<conn->xmitu; done++) {
1019 struct iovec *vp= &conn->xmit[done];
1020 XmitDetails *dp= &conn->xmitd[done];
1021 if (rs > vp->iov_len) {
1029 int newu= conn->xmitu - done;
1030 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1031 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1036 static void conn_make_some_xmits(Conn *conn) {
1038 if (conn->xmitu+5 > CONNIOVS)
1041 Article *art= LIST_REMHEAD(conn->priority);
1042 if (!art) art= LIST_REMHEAD(conn->waiting);
1045 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1046 /* actually send it */
1048 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1052 XMIT_LITERAL("TAKETHIS ");
1053 xmit_noalloc(conn, art->messageid, art->midlen);
1054 XMIT_LITERAL("\r\n");
1055 xmit_artbody(conn, artdata);
1058 /* we got 235 from IHAVE */
1060 xmit_artbody(conn, artdata);
1062 XMIT_LITERAL(".\r\n");
1067 art->state == art_Unchecked ? art_Unsolicited :
1068 art->state == art_Wanted ? art_Wanted :
1070 art->ipf->counts[art->state][RC_sent]++;
1071 LIST_ADDTAIL(conn->sent, art);
1077 XMIT_LITERAL("IHAVE ");
1079 XMIT_LITERAL("CHECK ");
1080 xmit_noalloc(conn, art->messageid, art->midlen);
1081 XMIT_LITERAL("\r\n");
1083 assert(art->state == art_Unchecked);
1084 art->ipf->counts[art->state][RC_sent]++;
1085 LIST_ADDTAIL(conn->sent, art);
1091 /*========== handling responses from peer ==========*/
1093 static const oop_rd_style peer_rd_style= {
1094 OOP_RD_DELIM_STRIP, '\n',
1096 OOP_RD_SHORTREC_FORBID
1099 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1100 const char *errmsg, int errnoval,
1101 const char *data, size_t recsz, void *conn_v) {
1103 connfail(conn, "error receiving from peer: %s", errmsg);
1104 return OOP_CONTINUE;
1107 static Article *article_reply_check(Conn *conn, const char *response,
1108 int code_indicates_streaming,
1110 /* 1:yes, -1:no, 0:dontcare */,
1111 const char *sanitised_response) {
1112 Article *art= LIST_HEAD(conn->sent);
1116 "peer gave unexpected response when no commands outstanding: %s",
1117 sanitised_response);
1121 if (code_indicates_streaming) {
1122 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1123 if (!conn->stream) {
1124 connfail(conn, "peer gave streaming response code "
1125 " to IHAVE or subsequent body: %s", sanitised_response);
1128 const char *got_mid= response+4;
1129 int got_midlen= strcspn(got_mid, " \n\r");
1130 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1131 connfail(conn, "peer gave streaming response with syntactically invalid"
1132 " messageid: %s", sanitised_response);
1135 if (got_midlen != art->midlen ||
1136 memcmp(got_mid, art->messageid, got_midlen)) {
1137 connfail(conn, "peer gave streaming response code to wrong article -"
1138 " probable synchronisation problem; we offered: %s;"
1140 art->messageid, sanitised_response);
1145 connfail(conn, "peer gave non-streaming response code to"
1146 " CHECK/TAKETHIS: %s", sanitised_response);
1151 if (must_have_sent>0 && art->state < art_Wanted) {
1152 connfail(conn, "peer says article accepted but"
1153 " we had not sent the body: %s", sanitised_response);
1156 if (must_have_sent<0 && art->state >= art_Wanted) {
1157 connfail(conn, "peer says please sent the article but we just did: %s",
1158 sanitised_response);
1162 Article *art_again= LIST_REMHEAD(conn->sent);
1163 assert(art_again == art);
1167 static void update_nocheck(int accepted) {
1168 accept_proportion *= nocheck_decay;
1169 accept_proportion += accepted * (1.0 - nocheck_decay);
1170 int new_nocheck= accept_proportion >= nocheck_thresh;
1171 if (new_nocheck && !nocheck_reported) {
1172 notice("entering nocheck mode for the first time");
1173 nocheck_reported= 1;
1174 } else if (new_nocheck != nocheck) {
1175 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1177 nocheck= new_nocheck;
1180 static void article_done(Conn *conn, Article *art, int whichcount) {
1181 art->ipf->counts[art->state][whichcount]++;
1182 if (whichcount == RC_accepted) update_nocheck(1);
1183 else if (whichcount == RC_unwanted) update_nocheck(0);
1185 InputFile *ipf= art->ipf;
1186 while (art->blanklen) {
1187 static const char spaces[]=
1192 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1193 int r= pwrite(ipf->fd, spaces, w, art->offset);
1195 if (errno==EINTR) continue;
1196 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1197 art->messageid, art->blanklen, art->offset, ipf->path);
1199 assert(r>=0 && r<=w);
1205 assert(ipf->inprogress >= 0);
1207 if (!ipf->inprogress && ipf != main_input_file)
1208 queue_check_input_done();
1213 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1214 const char *errmsg, int errnoval,
1215 const char *data, size_t recsz, void *conn_v) {
1218 if (ev == OOP_RD_EOF) {
1219 connfail(conn, "unexpected EOF from peer");
1220 return OOP_CONTINUE;
1222 assert(ev == OOP_RD_OK);
1224 char *sani= sanitise(data);
1227 unsigned long code= strtoul(data, &ep, 10);
1228 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1229 connfail(conn, "badly formatted response from peer: %s", sani);
1230 return OOP_CONTINUE;
1233 if (conn->quitting) {
1234 if (code!=205 && code!=503) {
1235 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1237 notice("C%d idle connection closed\n");
1238 assert(!conn->waiting.count);
1239 assert(!conn->priority.count);
1240 assert(!conn->sent.count);
1241 assert(!conn->xmitu);
1242 LIST_REMOVE(conns,conn);
1245 return OOP_CONTINUE;
1250 #define GET_ARTICLE(musthavesent) \
1251 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1252 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1254 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1255 code_streaming= (streaming); \
1256 GET_ARTICLE(musthavesent); \
1257 article_done(conn, art, RC_##how); break;
1259 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1261 int code_streaming= 0;
1265 case 400: PEERBADMSG("peer stopped accepting articles");
1266 case 503: PEERBADMSG("peer timed us out");
1267 default: PEERBADMSG("peer sent unexpected message");
1269 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1270 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1272 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1273 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1275 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1276 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1278 case 238: /* CHECK says send it */
1280 case 335: /* IHAVE says send it */
1282 assert(art->state == art_Unchecked);
1283 art->ipf->counts[art->state][RC_accepted]++;
1284 art->state= art_Wanted;
1285 LIST_ADDTAIL(conn->priority, art);
1288 case 431: /* CHECK or TAKETHIS says try later */
1290 case 436: /* IHAVE says try later */
1293 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1295 sysfatal("write to defer file %s",path_defer);
1296 article_done(conn, art, RC_deferred);
1301 conn_maybe_write(conn);
1302 check_master_queue();
1303 return OOP_CONTINUE;
1307 /*========== monitoring of input files ==========*/
1309 static void feedfile_eof(InputFile *ipf) {
1310 assert(ipf != main_input_file); /* promised by tailing_try_read */
1312 inputfile_tailing_stop(ipf);
1313 assert(ipf->fd >= 0);
1314 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1317 if (ipf == flushing_input_file) {
1318 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1319 if (main_input_file) inputfile_tailing_start(main_input_file);
1320 statemc_check_flushing_done();
1321 } else if (ipf == backlog_input_file) {
1322 statemc_check_backlog_done();
1324 abort(); /* supposed to wait rather than get EOF on main input file */
1328 static InputFile *open_input_file(const char *path) {
1329 int fd= open(path, O_RDONLY);
1331 if (errno==ENOENT) return 0;
1332 sysfatal("unable to open input file %s", path);
1335 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1336 memset(ipf,0,sizeof(*ipf));
1339 strcpy(ipf->path, path);
1344 static void close_input_file(InputFile *ipf) {
1345 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1346 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1347 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1348 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1351 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1355 /*---------- dealing with articles read in the input file ----------*/
1357 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1358 const char *data, size_t recsz,
1360 warn("corrupted file: %s, offset %lu: %s: %s",
1361 ipf->path, (unsigned long)offset, how, sanitise(data));
1362 ipf->readcount_err++;
1363 if (ipf->readcount_err > max_bad_data_initial +
1364 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1365 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1366 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1367 return OOP_CONTINUE;
1370 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1371 oop_rd_event ev, const char *errmsg,
1372 int errnoval, const char *data, size_t recsz,
1374 InputFile *ipf= ipf_v;
1376 char tokentextbuf[sizeof(TOKEN)*2+3];
1378 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1380 off_t old_offset= ipf->offset;
1381 ipf->offset += recsz + 1;
1383 #define BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,recsz,m);
1385 if (memchr(data,'\0',recsz)) BAD_DATA("nul byte");
1386 if (!recsz) BAD_DATA("empty line");
1389 if (strspn(data," ") != recsz) BAD_DATA("line partially blanked");
1390 ipf->readcount_blank++;
1391 return OOP_CONTINUE;
1394 char *space= strchr(data,' ');
1395 int tokenlen= space-data;
1396 int midlen= (int)recsz-tokenlen-1;
1397 if (midlen <= 0) BAD_DATA("no room for messageid");
1399 if (tokenlen != sizeof(TOKEN)*2+2) BAD_DATA("token wrong length");
1400 memcpy(tokentextbuf, data, tokenlen);
1401 tokentextbuf[tokenlen]= 0;
1402 if (!IsToken(tokentextbuf)) BAD_DATA("token wrong syntax");
1404 ipf->readcount_ok++;
1406 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1407 art->offset= ipf->offset;
1408 art->blanklen= recsz;
1409 art->midlen= midlen;
1410 art->state= art_Unchecked;
1411 art->ipf= ipf; ipf->inprogress++;
1412 art->token= TextToToken(tokentextbuf);
1413 strcpy(art->messageid, space+1);
1414 LIST_ADDTAIL(queue, art);
1416 if (sms==sm_NORMAL && ipf==main_input_file &&
1417 ipf->offset >= target_max_feedfile_size)
1418 statemc_start_flush("feed file size");
1420 check_master_queue();
1421 return OOP_CONTINUE;
1424 /*========== tailing input file ==========*/
1426 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1428 InputFile *ipf= user;
1429 return ipf->readable_callback(loop, &ipf->readable,
1430 ipf->readable_callback_user);
1433 static void tailing_on_cancel(struct oop_readable *rable) {
1434 InputFile *ipf= (void*)rable;
1436 if (ipf->filemon) filemon_stop(ipf);
1437 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1438 ipf->readable_callback= 0;
1441 static void tailing_queue_readable(InputFile *ipf) {
1442 /* lifetime of ipf here is OK because destruction will cause
1443 * on_cancel which will cancel this callback */
1444 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1447 static int tailing_on_readable(struct oop_readable *rable,
1448 oop_readable_call *cb, void *user) {
1449 InputFile *ipf= (void*)rable;
1451 tailing_on_cancel(rable);
1452 ipf->readable_callback= cb;
1453 ipf->readable_callback_user= user;
1456 tailing_queue_readable(ipf);
1460 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1462 InputFile *ipf= (void*)rable;
1464 ssize_t r= read(ipf->fd, buffer, length);
1466 if (errno==EINTR) continue;
1470 if (ipf==main_input_file) {
1473 } else if (ipf==flushing_input_file) {
1475 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1476 } else if (ipf==backlog_input_file) {
1486 /*---------- filemon implemented with inotify ----------*/
1488 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1489 #define HAVE_FILEMON
1491 #include <linux/inotify.h>
1493 static int filemon_inotify_fd;
1494 static int filemon_inotify_wdmax;
1495 static InputFile **filemon_inotify_wd2ipf;
1497 struct Filemon_Perfile {
1501 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1502 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1503 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1505 if (wd >= filemon_inotify_wdmax) {
1507 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1508 sizeof(*filemon_inotify_wd2ipf) * newmax);
1509 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1510 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1511 filemon_inotify_wdmax= newmax;
1514 assert(!filemon_inotify_wd2ipf[wd]);
1515 filemon_inotify_wd2ipf[wd]= ipf;
1517 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1518 ipf, wd, filemon_inotify_wdmax);
1523 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1525 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1526 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1527 if (r) sysdie("inotify_rm_watch");
1528 filemon_inotify_wd2ipf[wd]= 0;
1531 static void *filemon_inotify_readable(oop_source *lp, int fd,
1532 oop_event e, void *u) {
1533 struct inotify_event iev;
1535 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1537 if (errno==EAGAIN) break;
1538 sysdie("read from inotify master");
1539 } else if (r==sizeof(iev)) {
1540 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1542 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1544 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1545 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1546 filemon_callback(ipf);
1548 return OOP_CONTINUE;
1551 static int filemon_method_init(void) {
1552 filemon_inotify_fd= inotify_init();
1553 if (filemon_inotify_fd<0) {
1554 syswarn("could not initialise inotify: inotify_init failed");
1558 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1560 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1564 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1566 /*---------- filemon dummy implementation ----------*/
1568 #if !defined(HAVE_FILEMON)
1570 struct Filemon_Perfile { int dummy; };
1572 static int filemon_method_init(void) { return 0; }
1573 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1574 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1576 #endif /* !HAVE_FILEMON */
1578 /*---------- filemon generic interface ----------*/
1580 static void filemon_start(InputFile *ipf) {
1581 assert(!ipf->filemon);
1583 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1584 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1585 filemon_method_startfile(ipf, ipf->filemon);
1588 static void filemon_stop(InputFile *ipf) {
1589 if (!ipf->filemon) return;
1590 filemon_method_stopfile(ipf, ipf->filemon);
1595 static void filemon_callback(InputFile *ipf) {
1596 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1599 /*---------- interface to start and stop an input file ----------*/
1601 static const oop_rd_style feedfile_rdstyle= {
1602 OOP_RD_DELIM_STRIP, '\n',
1604 OOP_RD_SHORTREC_EOF,
1607 static void inputfile_tailing_start(InputFile *ipf) {
1609 ipf->readable->on_readable= tailing_on_readable;
1610 ipf->readable.on_cancel= tailing_on_cancel;
1611 ipf->readable.try_read= tailing_try_read;
1612 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1613 ipf->readable.delete_kill= 0;
1615 ipf->readable_callback= 0;
1616 ipf->readable_callback_user= 0;
1618 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1621 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1622 feedfile_got_article,ipf, feedfile_problem,ipf);
1623 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1626 static void inputfile_tailing_stop(InputFile *ipf) {
1628 oop_rd_cancel(ipf->rd);
1629 oop_rd_delete(ipf->rd);
1631 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1635 /*========== interaction with innd - state machine ==========*/
1637 /* See official state diagram at top of file. We implement
1648 |`---------------------------------------------------.
1650 |`---------------- - - - |
1651 D ENOENT | D EXISTS see OVERALL STATES diagram |
1652 | for full startup logic |
1655 | ============ try to |
1661 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1662 ^ | hardlink F to D |
1665 | | our handle onto F is now onto D |
1668 | |<-------------------<---------------------<---------+
1670 | | spawn inndcomm flush |
1672 | ================== |
1673 | FLUSHING[-ABSENT] |
1675 | main D tail/none |
1676 | ================== |
1678 | | INNDCOMM FLUSH FAILS ^
1679 | |`----------------------->----------. |
1681 | | NO SUCH SITE V |
1682 ^ |`--------------->----. ==================== |
1683 | | \ FLUSHFAILED[-ABSENT] |
1685 | | FLUSH OK \ main D tail/none |
1686 | | open F \ ==================== |
1688 | | \ | TIME TO RETRY |
1689 | |`------->----. ,---<---'\ `----------------'
1690 | | D NONE | | D NONE `----.
1692 | ============= V V ============
1693 | SEPARATED-1 | | DROPPING-1
1694 | flsh->fd>=0 | | flsh->fd>=0
1695 | [Separated] | | [Dropping]
1696 | main F idle | | main none
1697 | old D tail | | old D tail
1698 | ============= | | ============
1700 ^ | EOF ON D | | defer | EOF ON D
1702 | =============== | | ===============
1703 | SEPARATED-2 | | DROPPING-2
1704 | flsh->fd==-1 | V flsh->fd==-1
1705 | [Finishing] | | [Dropping]
1706 | main F tail | `. main none
1707 | old D closed | `. old D closed
1708 | =============== V `. ===============
1710 | | ALL D PROCESSED `. | ALL D PROCESSED
1711 | V install defer as backlog `. | install defer
1712 ^ | close D `. | close D
1713 | | unlink D `. | unlink D
1716 `----------' ==============
1736 static void statemc_init(void) {
1737 struct stat stab, stabf;
1739 path_lock= xasprintf("%s_lock", feedfile);
1740 path_flushing= xasprintf("%s_flushing", feedfile);
1741 path_defer= xasprintf("%s_defer", feedfile);
1742 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1745 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1746 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1749 memset(&fl,0,sizeof(fl));
1751 fl.l_whence= SEEK_SET;
1752 r= fcntl(lockfd, F_SETLK, &fl);
1754 if (errno==EACCES || errno==EAGAIN) {
1755 if (quiet_multiple) exit(0);
1756 fatal("another duct holds the lockfile");
1758 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1761 xfstat_isreg(lockfd, &stabf, "lockfile");
1763 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1765 if (!lock_noent && samefile(&stab, &stabf))
1769 sysdie("could not close stale lockfile %s", path_lock);
1771 debug("startup: locked");
1773 search_backlog_file();
1776 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1778 debug("startup: ductdefer ENOENT");
1780 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1781 switch (stab.st_nlink==1) {
1783 open_defer(); /* so that we will later close it and rename it */
1786 xunlink(path_defer, "stale defer file link"
1787 " (presumably hardlink to backlog file)");
1790 die("defer file %s has unexpected link count %d",
1791 path_defer, stab.st_nlink);
1795 struct stat stab_f, stab_d;
1798 InputFile *file_d= open_input_file(path_flushing);
1799 if (file_d) xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1801 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1803 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1804 debug("startup: F==D => Hardlinked");
1805 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1810 debug("startup: F ENOENT => Moved");
1811 if (file_d) startup_set_input_file(file_d);
1812 spawn_inndcomm_flush("feedfile missing at startup");
1813 /* => Flushing, sms:=FLUSHING */
1816 debug("startup: F!=D => Separated");
1817 startup_set_input_file(file_d);
1818 SMS(SEPARATED, 0, "found both old and current feed files");
1820 debug("startup: F exists, D ENOENT => Normal");
1821 FILE *file_f= open_input_file(feedfile);
1822 if (!file_f) die("feed file vanished during startup");
1823 startup_set_input_file(file_f);
1824 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1829 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1830 assert(sms == sm_NORMAL);
1832 debug("starting flush (%s) (%lu >= %lu) (%d)",
1834 (unsigned long)ipf->offset, (unsigned long)flush_threshold,
1837 int r= link(feedfile, duct_path);
1838 if (r) sysdie("link feedfile %s to flushing file %s", feedfile,
1842 xunlink(feedfile, "old feedfile link");
1845 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1848 static void statemc_period_poll(void) {
1849 if (!sm_period_counter) return;
1850 sm_period_counter--;
1851 assert(sm_period_counter>=0);
1853 if (sm_period_counter) return;
1856 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1858 case sm_FLUSHFAILED:
1859 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1866 static void startup_set_input_file(InputFile *f) {
1867 assert(!main_input_file);
1869 inputfile_tailing_start(f);
1872 static int inputfile_is_done(InputFile *ipf) {
1874 if (ipf->inprogress) return 0; /* new article in the meantime */
1875 if (ipf->fd >= 0); return 0; /* not had EOF */
1879 static void notice_processed(InputFile *ipf, const char *what,
1881 #define RCI_NOTHING(x) /* nothing */
1882 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
1883 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, .x)
1885 info("processed %s%s read=%d(+%dbl,+%derr)"
1886 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
1887 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
1890 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
1891 ipf->counts[art_Unchecked].sent + ipf->counts[art_Unsolicited].sent
1892 , ipf->counts[art_Unchecked].sent, ipf->counts[art_Unsolicited].sent,
1893 ipf->counts[art_Wanted].accepted + ipf->counts[art_Unsolicited].accepted
1894 ,ipf->counts[art_Wanted].accepted,ipf->counts[art_Unsolicited].accepted
1895 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
1899 static void statemc_check_backlog_done(void) {
1900 InputFile *ipf= backlog_input_file();
1901 if (!inputfile_is_done(ipf)) return;
1903 const char *slash= strrchr(ipf->path, "/");
1904 const char *leaf= slash ? slash+1 : ipf->path;
1905 const char *under= strchr(slash, "_");
1906 const char *rest= under ? under+1 : leaf;
1907 if (!strncmp(rest,"backlog",7)) rest += 7;
1908 notice_processed(ipf,"backlog:",rest);
1910 close_input_file(ipf);
1911 if (unlink(ipf->path)) {
1912 if (errno != ENOENT)
1913 sysdie("could not unlink processed backlog file %s", ipf->path);
1914 warn("backlog file %s vanished while we were reading it"
1915 " so we couldn't remove it (but it's done now, anyway)",
1919 backlog_input_file= 0;
1920 search_backlog_file();
1924 static void statemc_check_flushing_done(void) {
1925 InputFile *ipf= flushing_input_file;
1926 if (!inputfile_is_done(ipf)) return;
1928 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1930 notice_processed(ipf,"feedfile",0);
1934 xunlink(path_flushing, "old flushing file");
1936 close_input_file(flushing_input_file);
1937 free(flushing_input_file);
1938 flushing_input_file= 0;
1940 if (sms==sm_SEPARATED) {
1941 notice("flush complete");
1942 SMS(NORMAL, 0, "flush complete");
1943 } else if (sms==sm_DROPPING) {
1944 SMS(DROPPED, 0, "old flush complete");
1945 search_backlog_file();
1946 notice("feed dropped, but will continue until backlog is finished");
1950 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
1952 assert(!inputfile_is_done(main_input_file));
1953 statemc_check_flushing_done();
1954 statemc_check_backlog_done();
1955 return OOP_CONTINUE;
1958 static void queue_check_input_done(void) {
1959 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
1962 static void statemc_setstate(StateMachineState newsms, int periods,
1963 const char *forlog, const char *why) {
1965 sm_period_counter= periods;
1967 const char *xtra= "";
1969 case sm_FLUSHING: sm_FLUSHFAILED:
1970 if (!main_input_file) xtra= "-ABSENT";
1972 case sm_SEPARATED: case sm_DROPPING:
1973 xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
1979 info("%s%s[%d] %s",forlog,xtra,periods,why);
1981 info("%s%s %s",forlog,xtra,why);
1985 /*---------- defer and backlog files ----------*/
1987 static void open_defer(void) {
1992 defer= fopen(path_defer, "a+");
1993 if (!defer) sysfatal("could not open defer file %s", path_defer);
1995 /* truncate away any half-written records */
1997 xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1999 if (stab.st_size > LONG_MAX)
2000 die("defer file %s size is far too large", path_defer);
2005 long orgsize= stab.st_size;
2006 long truncto= stab.st_size;
2008 if (!truncto) break; /* was only (if anything) one half-truncated record */
2009 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2010 sysdie("seek in defer file %s while truncating partial", path_defer);
2015 sysdie("failed read from defer file %s", path_defer);
2017 die("defer file %s shrank while we were checking it!", path_defer);
2023 if (stab.st_size != truncto) {
2024 warn("truncating half-record at end of defer file %s -"
2025 " shrinking by %ld bytes from %ld to %ld",
2026 path_defer, orgsize - truncto, orgsize, truncto);
2029 sysfatal("could not flush defer file %s", path_defer);
2030 if (ftruncate(fileno(defer), truncto))
2031 sysdie("could not truncate defer file %s", path_defer);
2034 info("continuing existing defer file %s (%ld bytes)",
2035 path_defer, orgsize);
2037 if (fseek(defer, truncto, SEEK_SET))
2038 sysdie("could not seek to new end of defer file %s", path_defer);
2041 static void close_defer(void) {
2045 xfstat(fileno(defer), &stab, "defer file");
2047 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2050 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2051 (unsigned long)now.tv_sec,
2052 (unsigned long)stab.st_ino);
2053 if (link(path_defer, path_backlog))
2054 sysfatal("could not install defer file %s as backlog file %s",
2055 path_defer, backlog);
2056 if (unlink(path_defer))
2057 sysdie("could not unlink old defer link %s to backlog file %s",
2058 path_defer, backlog);
2060 if (until_backlog_nextscan < 0 ||
2061 until_backlog_nextscan > backlog_retry_minperiods + 1)
2062 until_backlog_nextscan= backlog_retry_minperiods + 1;
2065 static void poll_backlog_file(void) {
2066 if (until_backlog_nextscan < 0) return;
2067 if (until_backlog_nextscan-- > 0) return;
2068 search_backlog_file();
2071 static void search_backlog_file(void) {
2072 /* returns non-0 iff there are any backlog files */
2077 const char *oldest_path=0;
2078 time_t oldest_mtime, now;
2080 if (backlog_input_file) return 3;
2084 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2088 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2090 die("out of memory expanding backlog pattern %s", globpat_backlog);
2092 for (i=0; i<gl.gl_pathc; i++) {
2093 const char *path= gl.gl_pathv[i];
2095 if (strchr(path,'#') || strchr(path,'~')) {
2096 debug("backlog file search skipping %s", path);
2099 r= stat(path, &stab);
2101 syswarn("failed to stat backlog file %s", path);
2104 if (!S_ISREG(stab.st_mode)) {
2105 warn("backlog file %s is not a plain file (or link to one)", path);
2108 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2110 oldest_mtime= stab.st_mtime;
2113 case GLOB_NOMATCH: /* fall through */
2116 sysdie("glob expansion of backlog pattern %s gave unexpected"
2117 " nonzero (error?) return value %d", globpat_backlog, r);
2123 debug("backlog scan: none");
2125 if (sms==sm_DROPPED) {
2126 notice("feed dropped and our work is complete");
2127 xunlink(path_lock, "lockfile for old feed");
2130 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2134 now= time(); if (now==-1) sysdie("time(2) failed");
2135 double age= difftime(now, oldest_mtime);
2136 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
2138 if (age_deficiency <= 0) {
2139 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2140 age, age_deficiency, oldest_path);
2142 backlog_input_file= open_input_file(oldest_path);
2143 if (!backlog_input_file) {
2144 warn("backlog file %s vanished as we opened it", backlog_input_file);
2147 inputfile_tailing_start(backlog_input_file);
2148 until_backlog_nextscan= -1;
2152 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
2154 if (backlog_spontaneous_rescan_periods >= 0 &&
2155 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2156 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2158 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2159 age, age_deficiency, until_backlog_nextscan, oldest_path);
2163 /*========== flushing the feed ==========*/
2165 static pid_t inndcomm_child;
2167 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2168 assert(inndcomm_child);
2169 int status= xwaitpid(&inndcomm_child, "inndcomm");
2170 loop->cancel_fd(fd);
2173 assert(!flushing_input_file);
2175 if (WIFEXITED(status)) {
2176 switch (WEXITSTATUS(status)) {
2178 case INNDCOMMCHILD_ESTATUS_FAIL:
2181 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2182 warn("feed has been dropped by innd, finishing up");
2183 flushing_input_file= main_input_file;
2184 tailing_queue_readable(flushing_input_file);
2185 /* we probably previously returned EAGAIN from our fake read method
2186 * when in fact we were at EOF, so signal another readable event
2187 * so we actually see the EOF */
2191 if (flushing_input_file) {
2192 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2195 SMS(DROPPED, 0, "feed dropped by innd");
2196 search_backlog_file();
2198 return OOP_CONTINUE;
2202 flushing_input_file= main_input_file;
2203 tailing_queue_readable(flushing_input_file);
2205 main_input_file= open_input_file(feedfile);
2206 if (!main_input_file)
2207 die("flush succeeded but feedfile %s does not exist!", feedfile);
2209 if (flushing_input_file) {
2210 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2213 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2215 return OOP_CONTINUE;
2218 goto unexpected_exitstatus;
2221 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2222 warn("flush timed out trying to talk to innd");
2225 unexpected_exitstatus:
2226 report_child_status("inndcomm child", status);
2230 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2233 static void inndcommfail(const char *what) {
2234 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2235 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2238 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2241 notice("flushing %s",why);
2243 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2244 assert(!inndcomm_child);
2246 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2248 inndcomm_child= xfork();
2250 if (!inndcomm_child) {
2251 static char flushargv[2]= { sitename, 0 };
2256 alarm(inndcomm_flush_timeout);
2257 r= ICCopen(); if (r) inndcommfail("connect");
2258 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2259 if (!r) exit(0); /* yay! */
2261 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2262 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2263 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2267 int sentinel_fd= pipefds[0];
2268 on_fd_read_except(sentinel_fd, inndcomm_event);
2270 SMS(FLUSHING, 0, why);
2273 /*========== main program ==========*/
2275 static void postfork_inputfile(InputFile *ipf) {
2277 assert(ipf->fd >= 0);
2282 static void postfork_stdio(FILE *f) {
2283 /* we have no stdio streams that are buffered long-term */
2287 static void postfork(const char *what) {
2288 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2289 sysdie("%s child: failed to reset SIGPIPE");
2291 postfork_inputfile(main_input_file);
2292 postfork_inputfile(flushing_input_file);
2295 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2298 postfork_stdio(defer);
2301 #define EVERY(what, interval, body) \
2302 static const struct timeval what##_timeout = { 5, 0 }; \
2303 static void what##_schedule(void); \
2304 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2306 what##_schedule(); \
2308 static void what##_schedule(void) { \
2309 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2312 EVERY(filepoll, {5,0}, {
2313 if (main_input_file && main_input_file->readable_callback)
2314 filemon_callback(main_input_file);
2317 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s" \
2318 #define DEBUG_IPF(sh) \
2319 wh##_input_file, debug_ipf_path(wh##_input_file), \
2320 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2321 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2322 static const char *debug_ipf_path(InputFile *ipf) {
2323 char *slash= strrchr(ipf->path,'/');
2324 return slash ? slash+1 : ipf->path;
2327 EVERY(period, {PERIOD_SECONDS,0}, {
2329 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2330 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_FMT(flushing)
2331 " children connecting=%ld inndcomm_child"
2333 sms_names[sms], sm_period_counter,
2334 queue.count, conns.count, until_connect,
2335 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2336 (long)connecting_child, (long)inndcomm_child
2339 if (until_connect) until_connect--;
2341 poll_backlog_file();
2342 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2343 statemc_period_poll();
2344 check_master_queue();
2348 /*========== option parsing ==========*/
2351 of_seconds= 001000u;
2352 of_boolean= 002000u;
2355 typedef struct Option Option;
2356 typedef void OptionParser(const Option*, const char *val);
2366 void op_integer(const Option *o, const char *val) {
2369 unsigned long ul= strtoul(val,&ep,10);
2370 if (*ep || ep==val || errno || ul>INT_MAX)
2371 badusage("bad integer value for %s",o->long);
2372 int *store= o->store;
2376 void op_double(const Option *o, const char *val) {
2377 int *store= o->store;
2380 *store= strtod(val, &ep);
2381 if (*ep || ep==val || errno)
2382 badusage("bad floating point value for %s",o->long);
2385 void op_string(const Option *o, const char *val) {
2386 char **store= o->store;
2391 void op_seconds(const Option *o, const char *val) {
2392 int *store= o->store;
2395 double v= strtod(val,&ep);
2396 if (ep==val) badusage("bad time/duration value for %s",o->long);
2398 if (!*ep || !strcmp(ep,"s")) unit= 1;
2399 else if (!strcmp(ep,"m")) unit= 60;
2400 else if (!strcmp(ep,"h")) unit= 3600;
2401 else if (!strcmp(ep,"d")) unit= 86400;
2402 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2406 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2410 void op_periods_rndup(const Option *o, const char *val) {
2411 int *store= o->store;
2413 *store += PERIOD_SECONDS-1;
2414 *store /= PERIOD_SECONDS;
2417 void op_periods_booltrue(const Option *o, const char *val) {
2418 int *store= o->store;
2421 void op_periods_boolfalse(const Option *o, const char *val) {
2422 int *store= o->store;
2426 static const Option options[]= {
2427 {'f',"feedfile", &feedfile, op_string },
2428 {'q',"quiet-multiple", &quiet_multiple, op_booltrue, 1 },
2430 { 0, "max-connections", &max_connections op_integer },
2431 { 0, "max-queue-per-conn", &max_queue_per_conn op_integer },
2434 { 0, "streaming", &try_stream, op_booltrue, 1 },
2435 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2436 {'P',"port", &port op_integer },
2437 { 0, "inndconf", &inndconffile, op_string },
2438 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2439 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2441 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2442 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2444 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2445 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2446 { 0, "connection-timeout", &connection_timeout, op_seconds },
2447 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2450 int main(int argc, char **argv) {
2456 if (*arg != '-') break;
2457 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2459 while ((a= *++arg)) {
2463 char *equals= strchr(arg,'=');
2464 int len= equals ? (equals - arg) : strlen(arg);
2465 for (o=options; o->long; o++)
2466 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2468 badusage("unknown long option --%s",arg);
2471 if (equals) badusage("option --%s does not take a value",o->long);
2473 } else if (equals) {
2477 if (!arg) badusage("option --%s needs a value",o->long);
2480 break; /* eaten the whole argument now */
2482 for (o=options; o->long; o++)
2485 badusage("unknown short option -%c",a);
2492 if (!arg) badusage("option -%c needs a value",o->short);
2495 break; /* eaten the whole argument now */
2500 if (!arg) badusage("need site name argument");
2506 if (*++argv) badusage("too many non-option arguments");
2508 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2509 badusage("nocheck threshold percentage must be between 0..100");
2510 nocheck_thresh= nocheck_thresh_pct * 0.01;
2512 if (nocheck_decay_articles < 0.1)
2513 badusage("nocheck decay articles must be at least 0.1");
2514 nocheck_decay= 1 - 1/nocheck_decay_articles;
2517 pathoutgoing= innconf->pathoutgoing;
2518 innconf_read(inndconffile);
2521 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2522 else if (!feedfile[0])
2523 badusage("feed filename must be nonempty");
2524 else if (feedfile[strlen(feedfile)-1]=='/')
2525 feedfile= xasprintf("%s%s",feedfile,sitename);
2527 const char *feedfile_forbidden= "?*[~#";
2529 while ((c= *feedfile_forbidden++))
2530 if (strchr(feedfile, c))
2531 badusage("feed filename may not contain metacharacter %c",c);
2533 loop= oop_sys_new();
2534 if (!loop) sysdie("could not create liboop event loop");
2536 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2537 sysdie("could not ignore SIGPIPE");
2539 if (become_daemon) {
2540 for (i=3; i<255; i++)
2541 /* do this now before we open syslog, etc. */
2543 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2545 int null= open("/dev/null",O_RDWR);
2546 if (null<0) sysdie("failed to open /dev/null");
2552 pid_t child1= xfork("daemonise first fork");
2553 if (child1) _exit(0);
2555 pid_t sid= setsid();
2556 if (sid != child1) sysdie("setsid failed");
2558 pid_t child2= xfork("daemonise second fork");
2559 if (child2) _exit(0);
2564 if (!filemon_init()) {
2565 warn("no file monitoring available, polling");
2566 filepoll_schedule();