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 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
197 /*----- doubly linked lists -----*/
199 #define ISNODE(T) struct { T *succ, *pred; } node /* must be at start */
200 #define DEFLIST(T) typedef struct { T *hd, *tl, *tp; int count; } T##List
202 #define NODE(n) (assert((void*)&(n)->node == &(n)), \
203 (struct node*)&(n)->node)
205 #define LIST_CHECKCANHAVENODE(l,n) \
206 ((void)((n) == ((l).hd))) /* just for the type check */
208 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
209 ( LIST_CHECKCANHAVENODE(l,n), \
210 list_addsomehow((struct list*)&(l), NODE((n))), \
214 #define LIST_REMSOMEHOW(l,list_remsomehow) \
218 list_remsomehow((struct list*)&(l)) ) \
224 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
225 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
226 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
227 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
229 #define LIST_HEAD(l) ((typeof((l).hd))(list_head((struct list*)&(l))))
230 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
231 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
233 #define LIST_REMOVE(l,n) \
234 ( LIST_CHECKCANHAVENODE(l,n), \
235 list_remove(NODE((n))), \
239 #define LIST_INSERT(l,n,pred) \
240 ( LIST_CHECKCANHAVENODE(l,n), \
241 LIST_CHECKCANHAVENODE(l,pred), \
242 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
246 /*----- type predeclarations -----*/
248 typedef struct Conn Conn;
249 typedef struct Article Article;
250 typedef struct InputFile InputFile;
251 typedef struct XmitDetails XmitDetails;
252 typedef struct Filemon_Perfile Filemon_Perfile;
253 typedef enum StateMachineState StateMachineState;
258 /*----- function predeclarations -----*/
260 static void conn_maybe_write(Conn *conn);
261 static void conn_make_some_xmits(Conn *conn);
262 static void *conn_write_some_xmits(Conn *conn);
264 static void xmit_free(XmitDetails *d);
266 static void statemc_setstate(StateMachineState newsms, int periods,
267 const char *forlog, const char *why);
268 static void statemc_start_flush(const char *why); /* Normal => Flushing */
269 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
271 static void check_master_queue(void);
272 static void queue_check_input_done(void);
274 static void statemc_check_flushing_done(void);
275 static void statemc_check_backlog_done(void);
277 static void postfork(const char *what);
278 static void postfork_inputfile(InputFile *ipf);
280 static void open_defer(void);
281 static void close_defer(void);
282 static void search_backlog_file(void);
284 static void inputfile_tailing_start(InputFile *ipf);
285 static void inputfile_tailing_stop(InputFile *ipf);
287 static int filemon_init(void);
288 static void filemon_start(InputFile *ipf);
289 static void filemon_stop(InputFile *ipf);
290 static void filemon_callback(InputFile *ipf);
292 /*----- configuration options -----*/
294 static char *sitename, *feedfile;
295 static const char *remote_host;
296 static int quiet_multiple=0, become_daemon=1;
298 static int max_connections=10, max_queue_per_conn=200;
299 static int target_max_feedfile_size=100000;
301 static double max_bad_data_ratio= 0.01;
302 static int max_bad_data_initial= 30;
303 /* in one corrupt 4096-byte block the number of newlines has
304 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
306 static int connection_setup_timeout=200, port=119, try_stream=1;
307 static int inndcomm_flush_timeout=100;
308 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
309 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
310 static const char *inndconffile;
312 static double accept_proportion;
313 static double nocheck_thresh_pct= 95.0;
314 static double nocheck_thresh; /* computed in main from _pct */
315 static double nocheck_decay_articles= 100; /* converted to _decay */
316 static double nocheck_decay; /* computed in main from _articles */
317 static int nocheck, nocheck_reported;
320 /*----- statistics -----*/
322 typedef enum { /* in queue in conn->sent */
323 art_Unchecked, /* not checked, not sent checking */
324 art_Wanted, /* checked, wanted sent body as requested */
325 art_Unsolicited, /* - sent body without check */
329 #define RESULT_COUNTS(RCS,RCN) \
337 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
338 #define RCI_TRIPLE_VALS_BASE(counts,x) \
339 counts[art_Unchecked] x \
340 + counts[art_Wanted] x \
341 + counts[art_Unsolicited] x, \
342 counts[art_Unchecked] x \
343 , counts[art_Wanted] x \
344 , counts[art_Unsolicited] x
347 #define RC_INDEX(x) RC_##x,
348 RESULT_COUNTS(RC_INDEX, RC_INDEX)
353 /*----- transmission buffers -----*/
358 xk_Malloc, xk_Const, xk_Artdata
370 /*----- core operational data structure types -----*/
373 /* This is also an instance of struct oop_readable */
374 struct oop_readable readable; /* first */
375 oop_readable_call *readable_callback;
376 void *readable_callback_user;
379 Filemon_Perfile *filemon;
382 long inprogress; /* no. of articles read but not processed */
386 int counts[art_MaxState][RCI_max];
387 int readcount_ok, readcount_blank, readcount_err;
402 #define SMS_LIST(X) \
410 enum StateMachineState {
411 #define SMS_DEF_ENUM(s) sm_##s,
412 SMS_LIST(SMS_DEF_ENUM)
415 static const char *sms_names[]= {
416 #define SMS_DEF_NAME(s) #s ,
417 SMS_LIST(SMS_DEF_NAME)
423 int fd, max_queue, stream, quitting;
424 ArticleList waiting; /* not yet told peer */
425 ArticleList priority; /* peer says send it now */
426 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
427 struct iovec xmit[CONNIOVS];
428 XmitDetails xmitd[CONNIOVS];
433 /*----- operational variables -----*/
435 static oop_source *loop;
437 static int until_connect;
438 static ConnList conns;
439 static ArticleList queue;
441 static char *path_lock, *path_flushing, *path_defer, *globpat_backlog;
443 #define SMS(newstate, periods, why) \
444 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
446 static StateMachineState sms;
448 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
449 static int sm_period_counter;
452 /*========== logging ==========*/
454 static void logcore(int sysloglevel, const char *fmt, ...)
455 __attribute__((__format__(printf,2,3)));
456 static void logcore(int sysloglevel, const char *fmt, ...) {
460 vsyslog(sysloglevel,fmt,al);
462 vfprintf(stderr,fmt,al);
468 static void logv(int sysloglevel, const char *pfx, int errnoval,
469 int exitstatus, const char *fmt, va_list al)
470 __attribute__((__format__(printf,5,0)));
471 static void logv(int sysloglevel, const char *pfx, int errnoval,
472 int exitstatus, const char *fmt, va_list al) {
473 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
474 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
475 msgbuf[sizeof(msgbuf)-1]= 0;
477 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
478 sysloglevel= LOG_ERR; /* run by wrong user, probably */
480 logcore(sysloglevel, "<%s>%s: %s%s%s",
481 sitename, pfx, msgbuf,
482 errnoval>=0 ? ": " : "",
483 errnoval>=0 ? strerror(errnoval) : "");
486 #define logwrap(fn, pfx, sysloglevel, err, estatus) \
487 static void fn(const char *fmt, ...) \
488 __attribute__((__format__(printf,1,2))); \
489 static void fn(const char *fmt, ...) { \
492 logv(sysloglevel, pfx, err, estatus, fmt, al); \
495 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
496 logwrap(die, " critical", LOG_CRIT, -1, 16);
498 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
499 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
501 logwrap(syswarn, " warning", LOG_WARNING, errno, 0);
502 logwrap(warn, " warning", LOG_WARNING, -1, 0);
504 logwrap(notice, "", LOG_NOTICE, -1, 0);
505 logwrap(info, " info", LOG_INFO, -1, 0);
506 logwrap(debug, " debug", LOG_DEBUG, -1, 0);
509 /*========== utility functions etc. ==========*/
511 static char *xvasprintf(const char *fmt, va_list al)
512 __attribute__((__format__(printf,1,0)));
513 static char *xvasprintf(const char *fmt, va_list al) {
515 int rc= vasprintf(&str,fmt,al);
516 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
519 static char *xasprintf(const char *fmt, ...)
520 __attribute__((__format__(printf,1,2)));
521 static char *xasprintf(const char *fmt, ...) {
524 char *str= xvasprintf(fmt,al);
529 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
531 static pid_t xfork(const char *what) {
535 if (child==-1) sysdie("cannot fork for %s",what);
536 if (!child) postfork(what);
537 debug("forked %s %ld", what, (unsigned long)child);
541 static void on_fd_read_except(int fd, oop_call_fd callback) {
542 loop->on_fd(loop, fd, OOP_READ, callback, 0);
543 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
545 static void cancel_fd_read_except(int fd) {
546 loop->cancel_fd(loop, fd, OOP_READ);
547 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
550 static void report_child_status(const char *what, int status) {
551 if (WIFEXITED(status)) {
552 int es= WEXITSTATUS(status);
554 warn("%s: child died with error exit status %d",es);
555 } else if (WIFSIGNALED(status)) {
556 int sig= WTERMSIG(status);
557 const char *sigstr= strsignal(sig);
558 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
560 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
562 warn("%s: child died due to unknown fatal signal %d%s",
563 what, sig, coredump);
565 warn("%s: child died with unknown wait status %d", status);
569 static int xwaitpid(pid_t *pid, const char *what) {
572 int r= kill(*pid, SIGKILL);
573 if (r) sysdie("cannot kill %s child", what);
575 pid_t got= waitpid(*pid, &status, WNOHANG);
576 if (got==-1) sysdie("cannot reap %s child", what);
583 static void xunlink(const char *path, const char *what) {
585 if (r) sysdie("can't unlink %s %s", path, what);
588 static void check_isreg(const struct stat *stab, const char *path,
590 if (!S_ISREG(stab->st_mode))
591 die("%s %s not a plain file (mode 0%lo)",
592 what, path, (unsigned long)stab->st_mode);
595 static void xfstat(int fd, struct stat *stab_r, const char *what) {
596 int r= fstat(fd, stab_r);
597 if (r) sysdie("could not fstat %s", what);
600 static void xfstat_isreg(int fd, struct stat *stab_r,
601 const char *path, const char *what) {
602 xfstat(fd, stab_r, what);
603 check_isreg(stab_r, path, what);
606 static void xlstat_isreg(const char *path, struct stat *stab,
607 int *enoent_r /* 0 means ENOENT is fatal */,
609 int r= lstat(path, stab);
611 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
612 sysdie("could not lstat %s %s", what, path);
614 if (enoent_r) *enoent_r= 0;
615 check_isreg(stab, path, what);
618 static void setnonblock(int fd, int nonblocking) {
619 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
620 if (nonblocking) r |= O_NONBLOCK;
621 else r &= ~O_NONBLOCK;
622 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
625 static int samefile(const struct stat *a, const struct stat *b) {
626 assert(S_ISREG(a->st_mode));
627 assert(S_ISREG(b->st_mode));
628 return (a->st_ino == b->st_ino &&
629 a->st_dev == b->st_dev);
632 static char *sanitise(const char *input) {
633 static char sanibuf[100]; /* returns pointer to this buffer! */
635 const char *p= input;
639 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
641 if (!c) { *q++= '\''; *q=0; break; }
642 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
643 sprintf(q,"\\x%02x",c);
649 /*========== making new connections ==========*/
651 static void conn_dispose(Conn *conn) {
653 perhaps_close(&conn->fd);
655 until_connect= reconnect_delay_periods;
658 static int connecting_sockets[2]= {-1,-1};
659 static pid_t connecting_child;
661 static void connect_attempt_discard(void) {
662 if (connecting_sockets[0])
663 cancel_fd_read_except(connecting_sockets[0]);
665 perhaps_close(&connecting_sockets[0]);
666 perhaps_close(&connecting_sockets[1]);
668 if (connecting_child) {
669 int r= kill(connecting_child, SIGTERM);
670 if (r) syswarn("failed to kill connecting child");
671 int status= xwaitpid(&connecting_child, "connect");
673 if (!(WIFEXITED(status) ||
674 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
675 report_child_status("connect", status);
679 #define PREP_DECL_MSG_CMSG(msg) \
681 memset(&msg,0,sizeof(msg)); \
682 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
683 msg.msg_control= msg##cbuf; \
684 msg.msg_controllen= sizeof(msg##cbuf);
686 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
689 conn= xmalloc(sizeof(*conn));
690 memset(conn,0,sizeof(*conn));
692 PREP_DECL_MSG_CMSG(msg);
693 struct cmsghdr *h= 0;
694 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
695 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
698 pid_t got= waitpid(connecting_child, &status, WNOHANG);
700 assert(got==connecting_child);
702 if (WIFEXITED(status) &&
703 (WEXITSTATUS(status) != 0 &&
704 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
705 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
706 /* child already reported the problem */
707 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
708 warn("connect: connection attempt timed out");
709 } else if (!WIFEXITED(status)) {
710 report_child_status("connect", status);
711 /* that's probably the root cause then */
714 /* child is still running apparently, report the socket problem */
716 syswarn("connect: read from child socket failed");
717 else if (e == OOP_EXCEPTION)
718 warn("connect: unexpected exception on child socket");
720 warn("connect: unexpected EOF on child socket");
725 #define CHK(field, val) \
726 if (h->cmsg_##field != val) { \
727 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
730 CHK(level, SOL_SOCKET);
731 CHK(type, SCM_RIGHTS);
732 CHK(len, CMSG_LEN(sizeof(conn->fd)));
735 if (CMSG_NXTHDR(&msg,h)) { die("connect: child sent many cmsgs"); goto x; }
737 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
740 pid_t got= waitpid(connecting_child, &status, 0);
741 if (got==-1) sysdie("connect: real wait for child");
742 assert(got == connecting_child);
745 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
746 int es= WEXITSTATUS(status);
748 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
749 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
751 fatal("connect: child gave unexpected exit status %d", es);
755 setnonblock(conn->fd, 1);
756 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
757 LIST_ADDHEAD(conns, conn);
758 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
759 connect_attempt_discard();
760 check_master_queue();
765 connect_attempt_discard();
768 static int allow_connect_start(void) {
769 return conns.count < max_connections
774 static void connect_start(void) {
775 assert(!connecting_sockets[0]);
776 assert(!connecting_sockets[1]);
777 assert(!connecting_child);
779 notice("starting connection attempt");
781 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
782 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
784 connecting_child= xfork("connection");
786 if (!connecting_child) {
787 FILE *cn_from, *cn_to;
788 char buf[NNTP_STRLEN+100];
789 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
791 r= close(connecting_sockets[0]);
792 if (r) sysdie("connect: close parent socket in child");
794 alarm(connection_setup_timeout);
795 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
796 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
797 else sysfatal("connect: connection attempt failed");
799 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
800 sysfatal("connect: authentication failed");
802 if (fputs("MODE STREAM\r\n", cn_to) ||
804 sysfatal("connect: could not send MODE STREAM");
805 buf[sizeof(buf)-1]= 0;
806 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
808 sysfatal("connect: could not read response to MODE STREAM");
810 fatal("connect: connection close in response to MODE STREAM");
815 fatal("connect: response to MODE STREAM is too long: %.100s...",
816 remote_host, sanitise(buf));
817 l--; if (l>0 && buf[l-1]=='\r') l--;
820 int rcode= strtoul(buf,&ep,10);
822 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
826 exitstatus= CONNCHILD_ESTATUS_STREAM;
832 warn("connect: unexpected response to MODE STREAM: %.50s",
838 int fd= fileno(cn_from);
840 PREP_DECL_MSG_CMSG(msg);
841 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
842 cmsg->cmsg_level= SOL_SOCKET;
843 cmsg->cmsg_type= SCM_RIGHTS;
844 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
845 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
847 msg.msg_controllen= cmsg->cmsg_len;
848 r= sendmsg(connecting_sockets[1], &msg, 0);
849 if (r) sysdie("sendmsg failed for new connection");
854 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
855 if (r) sysdie("connect: close child socket in parent");
857 on_fd_read_except(connecting_sockets[0], connchild_event);
861 connect_attempt_discard();
865 /*========== overall control of article flow ==========*/
867 static void check_master_queue(void) {
875 /* Find a connection to offer this article. We prefer a busy
876 * connection to an idle one, provided it's not full. We take the
877 * first (oldest) and since that's stable, it will mean we fill up
878 * connections in order. That way if we have too many
879 * connections, the spare ones will go away eventually.
881 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
882 int inqueue= walk->sent.count + walk->priority.count
883 + walk->waiting.count;
884 spare= walk->max_queue - inqueue;
885 assert(inqueue <= max_queue_per_conn);
887 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
888 else if (spare>0) /*working*/ { use= walk; break; }
892 Article *art= LIST_REMHEAD(queue);
893 LIST_ADDTAIL(use->waiting, art);
896 conn_maybe_write(use);
897 } else if (allow_connect_start()) {
898 until_connect= reconnect_delay_periods;
907 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
912 static void conn_maybe_write(Conn *conn) {
915 conn_make_some_xmits(conn);
917 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
921 void *rp= conn_write_some_xmits(conn);
922 if (rp==OOP_CONTINUE) {
923 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
925 } else if (rp==OOP_HALT) {
928 /* transmitted everything */
935 static void vconnfail(Conn *conn, const char *fmt, va_list al)
936 __attribute__((__format__(printf,2,0)));
938 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
939 int requeue[art_MaxState];
942 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
943 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
944 while ((art= LIST_REMHEAD(conn->sent))) {
945 requeue[art->state]++;
946 if (art->state==art_Unsolicited) art->state= art_Unchecked;
947 LIST_ADDTAIL(queue,art);
952 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
955 char *m= xvasprintf(fmt,al);
956 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
957 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
960 LIST_REMOVE(conns,conn);
962 check_master_queue();
965 static void connfail(Conn *conn, const char *fmt, ...)
966 __attribute__((__format__(printf,2,3)));
967 static void connfail(Conn *conn, const char *fmt, ...) {
970 vconnfail(conn,fmt,al);
974 /*========== article transmission ==========*/
976 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
977 XmitKind kind) { /* caller must then fill in details */
978 struct iovec *v= &conn->xmit[conn->xmitu];
979 XmitDetails *d= &conn->xmitd[conn->xmitu++];
980 v->iov_base= (char*)data;
986 static void xmit_noalloc(Conn *conn, const char *data, int len) {
987 xmit_core(conn,data,len, xk_Const);
989 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
991 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
992 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
996 static void xmit_free(XmitDetails *d) {
998 case xk_Malloc: free(d->info.malloc_tofree); break;
999 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1000 case xk_Const: break;
1005 static void *conn_write_some_xmits(Conn *conn) {
1007 * 0: nothing more to write, no need to call us again
1008 * OOP_CONTINUE: more to write but fd not writeable
1009 * OOP_HALT: disaster, have destroyed conn
1012 int count= conn->xmitu;
1013 if (!count) return 0;
1015 if (count > IOV_MAX) count= IOV_MAX;
1016 ssize_t rs= writev(conn->fd, conn->xmit, count);
1018 if (errno == EAGAIN) return OOP_CONTINUE;
1019 connfail(conn, "write failed: %s", strerror(errno));
1025 for (done=0; rs && done<conn->xmitu; done++) {
1026 struct iovec *vp= &conn->xmit[done];
1027 XmitDetails *dp= &conn->xmitd[done];
1028 if (rs > vp->iov_len) {
1036 int newu= conn->xmitu - done;
1037 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1038 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1043 static void conn_make_some_xmits(Conn *conn) {
1045 if (conn->xmitu+5 > CONNIOVS)
1048 Article *art= LIST_REMHEAD(conn->priority);
1049 if (!art) art= LIST_REMHEAD(conn->waiting);
1052 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1053 /* actually send it */
1055 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1059 XMIT_LITERAL("TAKETHIS ");
1060 xmit_noalloc(conn, art->messageid, art->midlen);
1061 XMIT_LITERAL("\r\n");
1062 xmit_artbody(conn, artdata);
1065 /* we got 235 from IHAVE */
1067 xmit_artbody(conn, artdata);
1069 XMIT_LITERAL(".\r\n");
1074 art->state == art_Unchecked ? art_Unsolicited :
1075 art->state == art_Wanted ? art_Wanted :
1077 art->ipf->counts[art->state][RC_sent]++;
1078 LIST_ADDTAIL(conn->sent, art);
1084 XMIT_LITERAL("IHAVE ");
1086 XMIT_LITERAL("CHECK ");
1087 xmit_noalloc(conn, art->messageid, art->midlen);
1088 XMIT_LITERAL("\r\n");
1090 assert(art->state == art_Unchecked);
1091 art->ipf->counts[art->state][RC_sent]++;
1092 LIST_ADDTAIL(conn->sent, art);
1098 /*========== handling responses from peer ==========*/
1100 static const oop_rd_style peer_rd_style= {
1101 OOP_RD_DELIM_STRIP, '\n',
1103 OOP_RD_SHORTREC_FORBID
1106 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1107 const char *errmsg, int errnoval,
1108 const char *data, size_t recsz, void *conn_v) {
1110 connfail(conn, "error receiving from peer: %s", errmsg);
1111 return OOP_CONTINUE;
1114 static Article *article_reply_check(Conn *conn, const char *response,
1115 int code_indicates_streaming,
1117 /* 1:yes, -1:no, 0:dontcare */,
1118 const char *sanitised_response) {
1119 Article *art= LIST_HEAD(conn->sent);
1123 "peer gave unexpected response when no commands outstanding: %s",
1124 sanitised_response);
1128 if (code_indicates_streaming) {
1129 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1130 if (!conn->stream) {
1131 connfail(conn, "peer gave streaming response code "
1132 " to IHAVE or subsequent body: %s", sanitised_response);
1135 const char *got_mid= response+4;
1136 int got_midlen= strcspn(got_mid, " \n\r");
1137 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1138 connfail(conn, "peer gave streaming response with syntactically invalid"
1139 " messageid: %s", sanitised_response);
1142 if (got_midlen != art->midlen ||
1143 memcmp(got_mid, art->messageid, got_midlen)) {
1144 connfail(conn, "peer gave streaming response code to wrong article -"
1145 " probable synchronisation problem; we offered: %s;"
1147 art->messageid, sanitised_response);
1152 connfail(conn, "peer gave non-streaming response code to"
1153 " CHECK/TAKETHIS: %s", sanitised_response);
1158 if (must_have_sent>0 && art->state < art_Wanted) {
1159 connfail(conn, "peer says article accepted but"
1160 " we had not sent the body: %s", sanitised_response);
1163 if (must_have_sent<0 && art->state >= art_Wanted) {
1164 connfail(conn, "peer says please sent the article but we just did: %s",
1165 sanitised_response);
1169 Article *art_again= LIST_REMHEAD(conn->sent);
1170 assert(art_again == art);
1174 static void update_nocheck(int accepted) {
1175 accept_proportion *= nocheck_decay;
1176 accept_proportion += accepted * (1.0 - nocheck_decay);
1177 int new_nocheck= accept_proportion >= nocheck_thresh;
1178 if (new_nocheck && !nocheck_reported) {
1179 notice("entering nocheck mode for the first time");
1180 nocheck_reported= 1;
1181 } else if (new_nocheck != nocheck) {
1182 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1184 nocheck= new_nocheck;
1187 static void article_done(Conn *conn, Article *art, int whichcount) {
1188 art->ipf->counts[art->state][whichcount]++;
1189 if (whichcount == RC_accepted) update_nocheck(1);
1190 else if (whichcount == RC_unwanted) update_nocheck(0);
1192 InputFile *ipf= art->ipf;
1193 while (art->blanklen) {
1194 static const char spaces[]=
1199 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1200 int r= pwrite(ipf->fd, spaces, w, art->offset);
1202 if (errno==EINTR) continue;
1203 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1204 art->messageid, art->blanklen, art->offset, ipf->path);
1206 assert(r>=0 && r<=w);
1212 assert(ipf->inprogress >= 0);
1214 if (!ipf->inprogress && ipf != main_input_file)
1215 queue_check_input_done();
1220 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1221 const char *errmsg, int errnoval,
1222 const char *data, size_t recsz, void *conn_v) {
1225 if (ev == OOP_RD_EOF) {
1226 connfail(conn, "unexpected EOF from peer");
1227 return OOP_CONTINUE;
1229 assert(ev == OOP_RD_OK);
1231 char *sani= sanitise(data);
1234 unsigned long code= strtoul(data, &ep, 10);
1235 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1236 connfail(conn, "badly formatted response from peer: %s", sani);
1237 return OOP_CONTINUE;
1240 if (conn->quitting) {
1241 if (code!=205 && code!=503) {
1242 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1244 notice("C%d idle connection closed\n");
1245 assert(!conn->waiting.count);
1246 assert(!conn->priority.count);
1247 assert(!conn->sent.count);
1248 assert(!conn->xmitu);
1249 LIST_REMOVE(conns,conn);
1252 return OOP_CONTINUE;
1257 #define GET_ARTICLE(musthavesent) \
1258 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1259 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1261 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1262 code_streaming= (streaming); \
1263 GET_ARTICLE(musthavesent); \
1264 article_done(conn, art, RC_##how); break;
1266 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1268 int code_streaming= 0;
1272 case 400: PEERBADMSG("peer stopped accepting articles");
1273 case 503: PEERBADMSG("peer timed us out");
1274 default: PEERBADMSG("peer sent unexpected message");
1276 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1277 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1279 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1280 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1282 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1283 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1285 case 238: /* CHECK says send it */
1287 case 335: /* IHAVE says send it */
1289 assert(art->state == art_Unchecked);
1290 art->ipf->counts[art->state][RC_accepted]++;
1291 art->state= art_Wanted;
1292 LIST_ADDTAIL(conn->priority, art);
1295 case 431: /* CHECK or TAKETHIS says try later */
1297 case 436: /* IHAVE says try later */
1300 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1302 sysfatal("write to defer file %s",path_defer);
1303 article_done(conn, art, RC_deferred);
1308 conn_maybe_write(conn);
1309 check_master_queue();
1310 return OOP_CONTINUE;
1314 /*========== monitoring of input files ==========*/
1316 static void feedfile_eof(InputFile *ipf) {
1317 assert(ipf != main_input_file); /* promised by tailing_try_read */
1319 inputfile_tailing_stop(ipf);
1320 assert(ipf->fd >= 0);
1321 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1324 if (ipf == flushing_input_file) {
1325 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1326 if (main_input_file) inputfile_tailing_start(main_input_file);
1327 statemc_check_flushing_done();
1328 } else if (ipf == backlog_input_file) {
1329 statemc_check_backlog_done();
1331 abort(); /* supposed to wait rather than get EOF on main input file */
1335 static InputFile *open_input_file(const char *path) {
1336 int fd= open(path, O_RDONLY);
1338 if (errno==ENOENT) return 0;
1339 sysfatal("unable to open input file %s", path);
1342 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1343 memset(ipf,0,sizeof(*ipf));
1346 strcpy(ipf->path, path);
1351 static void close_input_file(InputFile *ipf) {
1352 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1353 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1354 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1355 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1358 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1362 /*---------- dealing with articles read in the input file ----------*/
1364 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1365 const char *data, const char *how) {
1366 warn("corrupted file: %s, offset %lu: %s: %s",
1367 ipf->path, (unsigned long)offset, how, sanitise(data));
1368 ipf->readcount_err++;
1369 if (ipf->readcount_err > max_bad_data_initial +
1370 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1371 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1372 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1373 return OOP_CONTINUE;
1376 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1377 oop_rd_event ev, const char *errmsg,
1378 int errnoval, const char *data, size_t recsz,
1380 InputFile *ipf= ipf_v;
1381 assert(ev == OOP_RD_SYSTEM);
1383 sysdie("error reading input file: %s, offset %lu",
1384 ipf->path, (unsigned long)ipf->offset);
1387 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1388 oop_rd_event ev, const char *errmsg,
1389 int errnoval, const char *data, size_t recsz,
1391 InputFile *ipf= ipf_v;
1393 char tokentextbuf[sizeof(TOKEN)*2+3];
1395 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1397 off_t old_offset= ipf->offset;
1398 ipf->offset += recsz + 1;
1400 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1402 if (ev==OOP_RD_PARTREC)
1403 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1404 /* but process it anyway */
1406 if (ipf->skippinglong) {
1407 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1410 if (ev==OOP_RD_LONG) {
1411 ipf->skippinglong= 1;
1412 X_BAD_DATA("overly long line");
1415 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1416 if (!recsz) X_BAD_DATA("empty line");
1419 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1420 ipf->readcount_blank++;
1421 return OOP_CONTINUE;
1424 char *space= strchr(data,' ');
1425 int tokenlen= space-data;
1426 int midlen= (int)recsz-tokenlen-1;
1427 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1428 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1430 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1431 memcpy(tokentextbuf, data, tokenlen);
1432 tokentextbuf[tokenlen]= 0;
1433 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1435 ipf->readcount_ok++;
1437 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1438 art->offset= ipf->offset;
1439 art->blanklen= recsz;
1440 art->midlen= midlen;
1441 art->state= art_Unchecked;
1442 art->ipf= ipf; ipf->inprogress++;
1443 art->token= TextToToken(tokentextbuf);
1444 strcpy(art->messageid, space+1);
1445 LIST_ADDTAIL(queue, art);
1447 if (sms==sm_NORMAL && ipf==main_input_file &&
1448 ipf->offset >= target_max_feedfile_size)
1449 statemc_start_flush("feed file size");
1451 check_master_queue();
1452 return OOP_CONTINUE;
1455 /*========== tailing input file ==========*/
1457 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1459 InputFile *ipf= user;
1460 return ipf->readable_callback(loop, &ipf->readable,
1461 ipf->readable_callback_user);
1464 static void tailing_on_cancel(struct oop_readable *rable) {
1465 InputFile *ipf= (void*)rable;
1467 if (ipf->filemon) filemon_stop(ipf);
1468 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1469 ipf->readable_callback= 0;
1472 static void tailing_queue_readable(InputFile *ipf) {
1473 /* lifetime of ipf here is OK because destruction will cause
1474 * on_cancel which will cancel this callback */
1475 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1478 static int tailing_on_readable(struct oop_readable *rable,
1479 oop_readable_call *cb, void *user) {
1480 InputFile *ipf= (void*)rable;
1482 tailing_on_cancel(rable);
1483 ipf->readable_callback= cb;
1484 ipf->readable_callback_user= user;
1487 tailing_queue_readable(ipf);
1491 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1493 InputFile *ipf= (void*)rable;
1495 ssize_t r= read(ipf->fd, buffer, length);
1497 if (errno==EINTR) continue;
1501 if (ipf==main_input_file) {
1504 } else if (ipf==flushing_input_file) {
1506 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1507 } else if (ipf==backlog_input_file) {
1517 /*---------- filemon implemented with inotify ----------*/
1519 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1520 #define HAVE_FILEMON
1522 #include <linux/inotify.h>
1524 static int filemon_inotify_fd;
1525 static int filemon_inotify_wdmax;
1526 static InputFile **filemon_inotify_wd2ipf;
1528 struct Filemon_Perfile {
1532 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1533 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1534 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1536 if (wd >= filemon_inotify_wdmax) {
1538 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1539 sizeof(*filemon_inotify_wd2ipf) * newmax);
1540 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1541 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1542 filemon_inotify_wdmax= newmax;
1545 assert(!filemon_inotify_wd2ipf[wd]);
1546 filemon_inotify_wd2ipf[wd]= ipf;
1548 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1549 ipf, wd, filemon_inotify_wdmax);
1554 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1556 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1557 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1558 if (r) sysdie("inotify_rm_watch");
1559 filemon_inotify_wd2ipf[wd]= 0;
1562 static void *filemon_inotify_readable(oop_source *lp, int fd,
1563 oop_event e, void *u) {
1564 struct inotify_event iev;
1566 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1568 if (errno==EAGAIN) break;
1569 sysdie("read from inotify master");
1570 } else if (r==sizeof(iev)) {
1571 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1573 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1575 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1576 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1577 filemon_callback(ipf);
1579 return OOP_CONTINUE;
1582 static int filemon_method_init(void) {
1583 filemon_inotify_fd= inotify_init();
1584 if (filemon_inotify_fd<0) {
1585 syswarn("could not initialise inotify: inotify_init failed");
1589 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1591 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1595 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1597 /*---------- filemon dummy implementation ----------*/
1599 #if !defined(HAVE_FILEMON)
1601 struct Filemon_Perfile { int dummy; };
1603 static int filemon_method_init(void) { return 0; }
1604 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1605 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1607 #endif /* !HAVE_FILEMON */
1609 /*---------- filemon generic interface ----------*/
1611 static void filemon_start(InputFile *ipf) {
1612 assert(!ipf->filemon);
1614 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1615 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1616 filemon_method_startfile(ipf, ipf->filemon);
1619 static void filemon_stop(InputFile *ipf) {
1620 if (!ipf->filemon) return;
1621 filemon_method_stopfile(ipf, ipf->filemon);
1626 static void filemon_callback(InputFile *ipf) {
1627 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1630 /*---------- interface to start and stop an input file ----------*/
1632 static const oop_rd_style feedfile_rdstyle= {
1633 OOP_RD_DELIM_STRIP, '\n',
1635 OOP_RD_SHORTREC_LONG,
1638 static void inputfile_tailing_start(InputFile *ipf) {
1640 ipf->readable.on_readable= tailing_on_readable;
1641 ipf->readable.on_cancel= tailing_on_cancel;
1642 ipf->readable.try_read= tailing_try_read;
1643 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1644 ipf->readable.delete_kill= 0;
1646 ipf->readable_callback= 0;
1647 ipf->readable_callback_user= 0;
1649 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1652 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1653 feedfile_got_article,ipf, feedfile_read_err, ipf);
1654 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1657 static void inputfile_tailing_stop(InputFile *ipf) {
1659 oop_rd_cancel(ipf->rd);
1660 oop_rd_delete(ipf->rd);
1662 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1666 /*========== interaction with innd - state machine ==========*/
1668 /* See official state diagram at top of file. We implement
1679 |`---------------------------------------------------.
1681 |`---------------- - - - |
1682 D ENOENT | D EXISTS see OVERALL STATES diagram |
1683 | for full startup logic |
1686 | ============ try to |
1692 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1693 ^ | hardlink F to D |
1696 | | our handle onto F is now onto D |
1699 | |<-------------------<---------------------<---------+
1701 | | spawn inndcomm flush |
1703 | ================== |
1704 | FLUSHING[-ABSENT] |
1706 | main D tail/none |
1707 | ================== |
1709 | | INNDCOMM FLUSH FAILS ^
1710 | |`----------------------->----------. |
1712 | | NO SUCH SITE V |
1713 ^ |`--------------->----. ==================== |
1714 | | \ FLUSHFAILED[-ABSENT] |
1716 | | FLUSH OK \ main D tail/none |
1717 | | open F \ ==================== |
1719 | | \ | TIME TO RETRY |
1720 | |`------->----. ,---<---'\ `----------------'
1721 | | D NONE | | D NONE `----.
1723 | ============= V V ============
1724 | SEPARATED-1 | | DROPPING-1
1725 | flsh->fd>=0 | | flsh->fd>=0
1726 | [Separated] | | [Dropping]
1727 | main F idle | | main none
1728 | old D tail | | old D tail
1729 | ============= | | ============
1731 ^ | EOF ON D | | defer | EOF ON D
1733 | =============== | | ===============
1734 | SEPARATED-2 | | DROPPING-2
1735 | flsh->fd==-1 | V flsh->fd==-1
1736 | [Finishing] | | [Dropping]
1737 | main F tail | `. main none
1738 | old D closed | `. old D closed
1739 | =============== V `. ===============
1741 | | ALL D PROCESSED `. | ALL D PROCESSED
1742 | V install defer as backlog `. | install defer
1743 ^ | close D `. | close D
1744 | | unlink D `. | unlink D
1747 `----------' ==============
1767 static void startup_set_input_file(InputFile *f) {
1768 assert(!main_input_file);
1770 inputfile_tailing_start(f);
1773 static void statemc_init(void) {
1774 struct stat stab, stabf;
1776 path_lock= xasprintf("%s_lock", feedfile);
1777 path_flushing= xasprintf("%s_flushing", feedfile);
1778 path_defer= xasprintf("%s_defer", feedfile);
1779 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1782 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1783 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1786 memset(&fl,0,sizeof(fl));
1788 fl.l_whence= SEEK_SET;
1789 int r= fcntl(lockfd, F_SETLK, &fl);
1791 if (errno==EACCES || errno==EAGAIN) {
1792 if (quiet_multiple) exit(0);
1793 fatal("another duct holds the lockfile");
1795 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1798 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
1800 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1802 if (!lock_noent && samefile(&stab, &stabf))
1806 sysdie("could not close stale lockfile %s", path_lock);
1808 debug("startup: locked");
1810 search_backlog_file();
1813 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1815 debug("startup: ductdefer ENOENT");
1817 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1818 switch (stab.st_nlink==1) {
1820 open_defer(); /* so that we will later close it and rename it */
1823 xunlink(path_defer, "stale defer file link"
1824 " (presumably hardlink to backlog file)");
1827 die("defer file %s has unexpected link count %d",
1828 path_defer, stab.st_nlink);
1832 struct stat stab_f, stab_d;
1835 InputFile *file_d= open_input_file(path_flushing);
1836 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
1838 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1840 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1841 debug("startup: F==D => Hardlinked");
1842 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1847 debug("startup: F ENOENT => Moved");
1848 if (file_d) startup_set_input_file(file_d);
1849 spawn_inndcomm_flush("feedfile missing at startup");
1850 /* => Flushing, sms:=FLUSHING */
1853 debug("startup: F!=D => Separated");
1854 startup_set_input_file(file_d);
1855 SMS(SEPARATED, 0, "found both old and current feed files");
1857 debug("startup: F exists, D ENOENT => Normal");
1858 InputFile *file_f= open_input_file(feedfile);
1859 if (!file_f) die("feed file vanished during startup");
1860 startup_set_input_file(file_f);
1861 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1866 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1867 assert(sms == sm_NORMAL);
1869 debug("starting flush (%s) (%lu >?= %lu) (%d)",
1871 (unsigned long)(main_input_file ? main_input_file->offset : 0),
1872 (unsigned long)target_max_feedfile_size,
1875 int r= link(feedfile, path_flushing);
1876 if (r) sysdie("link feedfile %s to flushing file %s",
1877 feedfile, path_flushing);
1880 xunlink(feedfile, "old feedfile link");
1883 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1886 static void statemc_period_poll(void) {
1887 if (!sm_period_counter) return;
1888 sm_period_counter--;
1889 assert(sm_period_counter>=0);
1891 if (sm_period_counter) return;
1894 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1896 case sm_FLUSHFAILED:
1897 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1904 static int inputfile_is_done(InputFile *ipf) {
1906 if (ipf->inprogress) return 0; /* new article in the meantime */
1907 if (ipf->fd >= 0); return 0; /* not had EOF */
1911 static void notice_processed(InputFile *ipf, const char *what,
1913 #define RCI_NOTHING(x) /* nothing */
1914 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
1915 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
1917 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
1919 info("processed %s%s read=%d(+%dbl,+%derr)"
1920 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
1921 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
1924 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
1925 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
1926 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
1927 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
1928 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
1929 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
1935 static void statemc_check_backlog_done(void) {
1936 InputFile *ipf= backlog_input_file;
1937 if (!inputfile_is_done(ipf)) return;
1939 const char *slash= strrchr(ipf->path, '/');
1940 const char *leaf= slash ? slash+1 : ipf->path;
1941 const char *under= strchr(slash, '_');
1942 const char *rest= under ? under+1 : leaf;
1943 if (!strncmp(rest,"backlog",7)) rest += 7;
1944 notice_processed(ipf,"backlog:",rest);
1946 close_input_file(ipf);
1947 if (unlink(ipf->path)) {
1948 if (errno != ENOENT)
1949 sysdie("could not unlink processed backlog file %s", ipf->path);
1950 warn("backlog file %s vanished while we were reading it"
1951 " so we couldn't remove it (but it's done now, anyway)",
1955 backlog_input_file= 0;
1956 search_backlog_file();
1960 static void statemc_check_flushing_done(void) {
1961 InputFile *ipf= flushing_input_file;
1962 if (!inputfile_is_done(ipf)) return;
1964 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1966 notice_processed(ipf,"feedfile",0);
1970 xunlink(path_flushing, "old flushing file");
1972 close_input_file(flushing_input_file);
1973 free(flushing_input_file);
1974 flushing_input_file= 0;
1976 if (sms==sm_SEPARATED) {
1977 notice("flush complete");
1978 SMS(NORMAL, 0, "flush complete");
1979 } else if (sms==sm_DROPPING) {
1980 SMS(DROPPED, 0, "old flush complete");
1981 search_backlog_file();
1982 notice("feed dropped, but will continue until backlog is finished");
1986 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
1988 assert(!inputfile_is_done(main_input_file));
1989 statemc_check_flushing_done();
1990 statemc_check_backlog_done();
1991 return OOP_CONTINUE;
1994 static void queue_check_input_done(void) {
1995 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
1998 static void statemc_setstate(StateMachineState newsms, int periods,
1999 const char *forlog, const char *why) {
2001 sm_period_counter= periods;
2003 const char *xtra= "";
2005 case sm_FLUSHING: sm_FLUSHFAILED:
2006 if (!main_input_file) xtra= "-ABSENT";
2008 case sm_SEPARATED: case sm_DROPPING:
2009 xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
2015 info("%s%s[%d] %s",forlog,xtra,periods,why);
2017 info("%s%s %s",forlog,xtra,why);
2021 /*---------- defer and backlog files ----------*/
2023 static void open_defer(void) {
2028 defer= fopen(path_defer, "a+");
2029 if (!defer) sysfatal("could not open defer file %s", path_defer);
2031 /* truncate away any half-written records */
2033 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2035 if (stab.st_size > LONG_MAX)
2036 die("defer file %s size is far too large", path_defer);
2041 long orgsize= stab.st_size;
2042 long truncto= stab.st_size;
2044 if (!truncto) break; /* was only (if anything) one half-truncated record */
2045 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2046 sysdie("seek in defer file %s while truncating partial", path_defer);
2051 sysdie("failed read from defer file %s", path_defer);
2053 die("defer file %s shrank while we were checking it!", path_defer);
2059 if (stab.st_size != truncto) {
2060 warn("truncating half-record at end of defer file %s -"
2061 " shrinking by %ld bytes from %ld to %ld",
2062 path_defer, orgsize - truncto, orgsize, truncto);
2065 sysfatal("could not flush defer file %s", path_defer);
2066 if (ftruncate(fileno(defer), truncto))
2067 sysdie("could not truncate defer file %s", path_defer);
2070 info("continuing existing defer file %s (%ld bytes)",
2071 path_defer, orgsize);
2073 if (fseek(defer, truncto, SEEK_SET))
2074 sysdie("could not seek to new end of defer file %s", path_defer);
2077 static void close_defer(void) {
2081 xfstat(fileno(defer), &stab, path_defer, "defer file");
2083 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2086 time_t now= time(0);
2087 if (now==-1) sysdie("time(2) failed");
2089 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2091 (unsigned long)stab.st_ino);
2092 if (link(path_defer, backlog))
2093 sysfatal("could not install defer file %s as backlog file %s",
2094 path_defer, backlog);
2095 if (unlink(path_defer))
2096 sysdie("could not unlink old defer link %s to backlog file %s",
2097 path_defer, backlog);
2101 if (until_backlog_nextscan < 0 ||
2102 until_backlog_nextscan > backlog_retry_minperiods + 1)
2103 until_backlog_nextscan= backlog_retry_minperiods + 1;
2106 static void poll_backlog_file(void) {
2107 if (until_backlog_nextscan < 0) return;
2108 if (until_backlog_nextscan-- > 0) return;
2109 search_backlog_file();
2112 static void search_backlog_file(void) {
2113 /* returns non-0 iff there are any backlog files */
2118 const char *oldest_path=0;
2119 time_t oldest_mtime, now;
2121 if (backlog_input_file) return 3;
2125 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2129 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2131 die("out of memory expanding backlog pattern %s", globpat_backlog);
2133 for (i=0; i<gl.gl_pathc; i++) {
2134 const char *path= gl.gl_pathv[i];
2136 if (strchr(path,'#') || strchr(path,'~')) {
2137 debug("backlog file search skipping %s", path);
2140 r= stat(path, &stab);
2142 syswarn("failed to stat backlog file %s", path);
2145 if (!S_ISREG(stab.st_mode)) {
2146 warn("backlog file %s is not a plain file (or link to one)", path);
2149 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2151 oldest_mtime= stab.st_mtime;
2154 case GLOB_NOMATCH: /* fall through */
2157 sysdie("glob expansion of backlog pattern %s gave unexpected"
2158 " nonzero (error?) return value %d", globpat_backlog, r);
2164 debug("backlog scan: none");
2166 if (sms==sm_DROPPED) {
2167 notice("feed dropped and our work is complete");
2168 xunlink(path_lock, "lockfile for old feed");
2171 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2175 now= time(); if (now==-1) sysdie("time(2) failed");
2176 double age= difftime(now, oldest_mtime);
2177 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
2179 if (age_deficiency <= 0) {
2180 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2181 age, age_deficiency, oldest_path);
2183 backlog_input_file= open_input_file(oldest_path);
2184 if (!backlog_input_file) {
2185 warn("backlog file %s vanished as we opened it", backlog_input_file);
2188 inputfile_tailing_start(backlog_input_file);
2189 until_backlog_nextscan= -1;
2193 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
2195 if (backlog_spontaneous_rescan_periods >= 0 &&
2196 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2197 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2199 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2200 age, age_deficiency, until_backlog_nextscan, oldest_path);
2204 /*========== flushing the feed ==========*/
2206 static pid_t inndcomm_child;
2208 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2209 assert(inndcomm_child);
2210 int status= xwaitpid(&inndcomm_child, "inndcomm");
2211 loop->cancel_fd(fd);
2214 assert(!flushing_input_file);
2216 if (WIFEXITED(status)) {
2217 switch (WEXITSTATUS(status)) {
2219 case INNDCOMMCHILD_ESTATUS_FAIL:
2222 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2223 warn("feed has been dropped by innd, finishing up");
2224 flushing_input_file= main_input_file;
2225 tailing_queue_readable(flushing_input_file);
2226 /* we probably previously returned EAGAIN from our fake read method
2227 * when in fact we were at EOF, so signal another readable event
2228 * so we actually see the EOF */
2232 if (flushing_input_file) {
2233 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2236 SMS(DROPPED, 0, "feed dropped by innd");
2237 search_backlog_file();
2239 return OOP_CONTINUE;
2243 flushing_input_file= main_input_file;
2244 tailing_queue_readable(flushing_input_file);
2246 main_input_file= open_input_file(feedfile);
2247 if (!main_input_file)
2248 die("flush succeeded but feedfile %s does not exist!", feedfile);
2250 if (flushing_input_file) {
2251 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2254 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2256 return OOP_CONTINUE;
2259 goto unexpected_exitstatus;
2262 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2263 warn("flush timed out trying to talk to innd");
2266 unexpected_exitstatus:
2267 report_child_status("inndcomm child", status);
2271 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2274 static void inndcommfail(const char *what) {
2275 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2276 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2279 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2282 notice("flushing %s",why);
2284 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2285 assert(!inndcomm_child);
2287 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2289 inndcomm_child= xfork();
2291 if (!inndcomm_child) {
2292 static char flushargv[2]= { sitename, 0 };
2297 alarm(inndcomm_flush_timeout);
2298 r= ICCopen(); if (r) inndcommfail("connect");
2299 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2300 if (!r) exit(0); /* yay! */
2302 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2303 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2304 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2308 int sentinel_fd= pipefds[0];
2309 on_fd_read_except(sentinel_fd, inndcomm_event);
2311 SMS(FLUSHING, 0, why);
2314 /*========== main program ==========*/
2316 static void postfork_inputfile(InputFile *ipf) {
2318 assert(ipf->fd >= 0);
2323 static void postfork_stdio(FILE *f) {
2324 /* we have no stdio streams that are buffered long-term */
2328 static void postfork(const char *what) {
2329 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2330 sysdie("%s child: failed to reset SIGPIPE");
2332 postfork_inputfile(main_input_file);
2333 postfork_inputfile(flushing_input_file);
2336 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2339 postfork_stdio(defer);
2342 #define EVERY(what, interval, body) \
2343 static const struct timeval what##_timeout = { 5, 0 }; \
2344 static void what##_schedule(void); \
2345 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2347 what##_schedule(); \
2349 static void what##_schedule(void) { \
2350 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2353 EVERY(filepoll, {5,0}, {
2354 if (main_input_file && main_input_file->readable_callback)
2355 filemon_callback(main_input_file);
2358 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s" \
2359 #define DEBUG_IPF(sh) \
2360 wh##_input_file, debug_ipf_path(wh##_input_file), \
2361 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2362 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2363 static const char *debug_ipf_path(InputFile *ipf) {
2364 char *slash= strrchr(ipf->path,'/');
2365 return slash ? slash+1 : ipf->path;
2368 EVERY(period, {PERIOD_SECONDS,0}, {
2370 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2371 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_FMT(flushing)
2372 " children connecting=%ld inndcomm_child"
2374 sms_names[sms], sm_period_counter,
2375 queue.count, conns.count, until_connect,
2376 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2377 (long)connecting_child, (long)inndcomm_child
2380 if (until_connect) until_connect--;
2382 poll_backlog_file();
2383 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2384 statemc_period_poll();
2385 check_master_queue();
2389 /*========== option parsing ==========*/
2392 of_seconds= 001000u;
2393 of_boolean= 002000u;
2396 typedef struct Option Option;
2397 typedef void OptionParser(const Option*, const char *val);
2407 void op_integer(const Option *o, const char *val) {
2410 unsigned long ul= strtoul(val,&ep,10);
2411 if (*ep || ep==val || errno || ul>INT_MAX)
2412 badusage("bad integer value for %s",o->long);
2413 int *store= o->store;
2417 void op_double(const Option *o, const char *val) {
2418 int *store= o->store;
2421 *store= strtod(val, &ep);
2422 if (*ep || ep==val || errno)
2423 badusage("bad floating point value for %s",o->long);
2426 void op_string(const Option *o, const char *val) {
2427 char **store= o->store;
2432 void op_seconds(const Option *o, const char *val) {
2433 int *store= o->store;
2436 double v= strtod(val,&ep);
2437 if (ep==val) badusage("bad time/duration value for %s",o->long);
2439 if (!*ep || !strcmp(ep,"s")) unit= 1;
2440 else if (!strcmp(ep,"m")) unit= 60;
2441 else if (!strcmp(ep,"h")) unit= 3600;
2442 else if (!strcmp(ep,"d")) unit= 86400;
2443 else badusage("bad units %s for time/duration value for %s",ep,o->long);
2447 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2451 void op_periods_rndup(const Option *o, const char *val) {
2452 int *store= o->store;
2454 *store += PERIOD_SECONDS-1;
2455 *store /= PERIOD_SECONDS;
2458 void op_periods_booltrue(const Option *o, const char *val) {
2459 int *store= o->store;
2462 void op_periods_boolfalse(const Option *o, const char *val) {
2463 int *store= o->store;
2467 static const Option options[]= {
2468 {'f',"feedfile", &feedfile, op_string },
2469 {'q',"quiet-multiple", &quiet_multiple, op_booltrue, 1 },
2471 { 0, "max-connections", &max_connections op_integer },
2472 { 0, "max-queue-per-conn", &max_queue_per_conn op_integer },
2475 { 0, "streaming", &try_stream, op_booltrue, 1 },
2476 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
2477 {'P',"port", &port op_integer },
2478 { 0, "inndconf", &inndconffile, op_string },
2479 {'d',"daemon", &become_daemon, op_booltrue, 1 },
2480 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
2482 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2483 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2485 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2486 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2487 { 0, "connection-timeout", &connection_timeout, op_seconds },
2488 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2491 int main(int argc, char **argv) {
2497 if (*arg != '-') break;
2498 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2500 while ((a= *++arg)) {
2504 char *equals= strchr(arg,'=');
2505 int len= equals ? (equals - arg) : strlen(arg);
2506 for (o=options; o->long; o++)
2507 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2509 badusage("unknown long option --%s",arg);
2512 if (equals) badusage("option --%s does not take a value",o->long);
2514 } else if (equals) {
2518 if (!arg) badusage("option --%s needs a value",o->long);
2521 break; /* eaten the whole argument now */
2523 for (o=options; o->long; o++)
2526 badusage("unknown short option -%c",a);
2533 if (!arg) badusage("option -%c needs a value",o->short);
2536 break; /* eaten the whole argument now */
2541 if (!arg) badusage("need site name argument");
2547 if (*++argv) badusage("too many non-option arguments");
2549 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2550 badusage("nocheck threshold percentage must be between 0..100");
2551 nocheck_thresh= nocheck_thresh_pct * 0.01;
2553 if (nocheck_decay_articles < 0.1)
2554 badusage("nocheck decay articles must be at least 0.1");
2555 nocheck_decay= 1 - 1/nocheck_decay_articles;
2558 pathoutgoing= innconf->pathoutgoing;
2559 innconf_read(inndconffile);
2562 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2563 else if (!feedfile[0])
2564 badusage("feed filename must be nonempty");
2565 else if (feedfile[strlen(feedfile)-1]=='/')
2566 feedfile= xasprintf("%s%s",feedfile,sitename);
2568 const char *feedfile_forbidden= "?*[~#";
2570 while ((c= *feedfile_forbidden++))
2571 if (strchr(feedfile, c))
2572 badusage("feed filename may not contain metacharacter %c",c);
2574 loop= oop_sys_new();
2575 if (!loop) sysdie("could not create liboop event loop");
2577 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2578 sysdie("could not ignore SIGPIPE");
2580 if (become_daemon) {
2581 for (i=3; i<255; i++)
2582 /* do this now before we open syslog, etc. */
2584 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2586 int null= open("/dev/null",O_RDWR);
2587 if (null<0) sysdie("failed to open /dev/null");
2593 pid_t child1= xfork("daemonise first fork");
2594 if (child1) _exit(0);
2596 pid_t sid= setsid();
2597 if (sid != child1) sysdie("setsid failed");
2599 pid_t child2= xfork("daemonise second fork");
2600 if (child2) _exit(0);
2605 if (!filemon_init()) {
2606 warn("no file monitoring available, polling");
2607 filepoll_schedule();