3 * - close idle connections
4 * - check all structs initialised
5 * - check all fd watches properly undone
6 * - check all init functions called
7 * - actually implement badusage
8 * - options for all options
10 * - pid, sitename, hostname in lockfile
15 * Newsfeeds file entries should look like this:
16 * host.name.of.site[/exclude,exclude,...]\
17 * :pattern,pattern...[/distribution,distribution...]\
21 * sitename[/exclude,exclude,...]\
22 * :pattern,pattern...[/distribution,distribution...]\
28 * or might be blanked out
29 * <spc><spc><spc><spc>....
31 * F site.name main feed file
32 * opened/created, then written, by innd
35 * tokens blanked out by duct when processed
36 * site.name_lock lock preventing multiple ducts
37 * to hold lock must open,F_SETLK[W]
38 * and then stat to check that locked file
39 * still has name site.name_lock
40 * holder of this lock is "duct"
41 * (only) lockholder may remove the lockfile
42 * D site.name_flushing temporary feed file during flush (or crash)
43 * hardlink created by duct
45 * site.name_defer 431'd articles, still being written,
46 * created, written, used by duct
48 * site.name_backlog.<date>.<inum>
49 * 431'd articles, ready for innxmit or duct
50 * created (link/mv) by duct
51 * site.name_backlog<anything-else> (where <anything-else> does not
52 * contain '#' or '~') eg
53 * site.name_backlog.manual
54 * anything the sysadmin likes (eg, feed files
55 * from old feeds to be merged into this one)
56 * created (link/mv) by admin
57 * may be symlinks (in which case links
58 * may be written through, but only links
61 * It is safe to remove backlog files manually,
62 * if it's desired to throw away the backlog.
64 * Backlog files are also processed by innduct. We find the oldest
65 * backlog file which is at least a certain amount old, and feed it
66 * back into our processing. When every article in it has been read
67 * and processed, we unlink it and look for another backlog file.
69 * If we don't have a backlog file that we're reading, we close the
70 * defer file that we're writing and make it into a backlog file at
71 * the first convenient opportunity.
82 | | <----------------<---------------------------------'|
88 | F: innd writing, duct reading |
91 | | duct decides time to flush |
92 | | duct makes hardlink |
94 | V <------------------------'|
96 | F == D: innd writing, duct reading both exist |
99 | | <-----------<-------------<--'|
100 | | open D F ENOENT |
103 | V <---------------------. |
106 | D: innd writing, duct reading; or ENOENT | |
108 | | duct requests flush of feed | |
109 | | (others can too, harmlessly) | |
113 | D: innd flushing, duct; or ENOENT | |
115 | | inndcomm flush fails | |
116 | |`-------------------------->------------------' |
118 | | inndcomm reports no such site |
119 | |`---------------------------------------------------- | -.
121 | | innd finishes writing D, creates F | |
122 | | inndcomm reports flush successful | |
125 | Separated <----------------' |
126 | F: innd writing F!=D /
127 | D: duct reading; or ENOENT both exist /
129 | | duct gets to the end of D /
130 | | duct opens F too /
133 | F: innd writing, duct reading |
134 | D: duct finishing V
136 | | duct finishes processing D F: ENOENT
137 | V duct unlinks D D: duct reading
139 `--<--' | duct finishes
149 "duct reading" means innduct is reading the file but also
150 overwriting processed tokens.
154 * rune for printing diagrams:
156 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
161 /*============================== PROGRAM ==============================*/
169 #include "inndcomm.h"
171 #include "inn/list.h"
172 #include "inn/innconf.h"
175 #include <sys/types.h>
176 #include <sys/wait.h>
177 #include <sys/stat.h>
178 #include <sys/socket.h>
194 #include <oop-read.h>
196 /*----- general definitions, probably best not changed -----*/
198 #define PERIOD_SECONDS 60
200 #define CONNCHILD_ESTATUS_STREAM 4
201 #define CONNCHILD_ESTATUS_NOSTREAM 5
203 #define INNDCOMMCHILD_ESTATUS_FAIL 6
204 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
206 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
208 /*----- doubly linked lists -----*/
210 #define ISNODE(T) struct { T *succ, *pred; } node /* must be at start */
211 #define DEFLIST(T) typedef struct { T *hd, *tl, *tp; int count; } T##List
213 #define NODE(n) (assert((void*)&(n)->node == &(n)), \
214 (struct node*)&(n)->node)
216 #define LIST_CHECKCANHAVENODE(l,n) \
217 ((void)((n) == ((l).hd))) /* just for the type check */
219 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
220 ( LIST_CHECKCANHAVENODE(l,n), \
221 list_addsomehow((struct list*)&(l), NODE((n))), \
225 #define LIST_REMSOMEHOW(l,list_remsomehow) \
229 list_remsomehow((struct list*)&(l)) ) \
235 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
236 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
237 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
238 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
240 #define LIST_HEAD(l) ((typeof((l).hd))(list_head((struct list*)&(l))))
241 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
242 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
244 #define LIST_REMOVE(l,n) \
245 ( LIST_CHECKCANHAVENODE(l,n), \
246 list_remove(NODE((n))), \
250 #define LIST_INSERT(l,n,pred) \
251 ( LIST_CHECKCANHAVENODE(l,n), \
252 LIST_CHECKCANHAVENODE(l,pred), \
253 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
257 /*----- type predeclarations -----*/
259 typedef struct Conn Conn;
260 typedef struct Article Article;
261 typedef struct InputFile InputFile;
262 typedef struct XmitDetails XmitDetails;
263 typedef struct Filemon_Perfile Filemon_Perfile;
264 typedef enum StateMachineState StateMachineState;
269 /*----- function predeclarations -----*/
271 static void conn_maybe_write(Conn *conn);
272 static void conn_make_some_xmits(Conn *conn);
273 static void *conn_write_some_xmits(Conn *conn);
275 static void xmit_free(XmitDetails *d);
277 static void statemc_setstate(StateMachineState newsms, int periods,
278 const char *forlog, const char *why);
279 static void statemc_start_flush(const char *why); /* Normal => Flushing */
280 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
282 static void check_master_queue(void);
283 static void queue_check_input_done(void);
285 static void statemc_check_flushing_done(void);
286 static void statemc_check_backlog_done(void);
288 static void postfork(const char *what);
289 static void postfork_inputfile(InputFile *ipf);
291 static void open_defer(void);
292 static void close_defer(void);
293 static void search_backlog_file(void);
295 static void inputfile_tailing_start(InputFile *ipf);
296 static void inputfile_tailing_stop(InputFile *ipf);
298 static int filemon_init(void);
299 static void filemon_start(InputFile *ipf);
300 static void filemon_stop(InputFile *ipf);
301 static void filemon_callback(InputFile *ipf);
303 /*----- configuration options -----*/
305 static const char *sitename, *feedfile, *pathoutgoing;
306 static const char *remote_host;
307 static int quiet_multiple=0, become_daemon=1;
309 static int max_connections=10, max_queue_per_conn=200;
310 static int target_max_feedfile_size=100000;
312 static double max_bad_data_ratio= 0.01;
313 static int max_bad_data_initial= 30;
314 /* in one corrupt 4096-byte block the number of newlines has
315 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
317 static int connection_setup_timeout=200, port=119, try_stream=1;
318 static int inndcomm_flush_timeout=100;
319 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
320 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
321 static int spontaneous_flush_periods;
322 static const char *inndconffile;
324 static double nocheck_thresh_pct= 95.0;
325 static double nocheck_thresh; /* computed in main from _pct */
326 static double nocheck_decay_articles= 100; /* converted to _decay */
327 static double nocheck_decay; /* computed in main from _articles */
330 /*----- statistics -----*/
332 typedef enum { /* in queue in conn->sent */
333 art_Unchecked, /* not checked, not sent checking */
334 art_Wanted, /* checked, wanted sent body as requested */
335 art_Unsolicited, /* - sent body without check */
339 #define RESULT_COUNTS(RCS,RCN) \
347 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
348 #define RCI_TRIPLE_VALS_BASE(counts,x) \
349 counts[art_Unchecked] x \
350 + counts[art_Wanted] x \
351 + counts[art_Unsolicited] x, \
352 counts[art_Unchecked] x \
353 , counts[art_Wanted] x \
354 , counts[art_Unsolicited] x
357 #define RC_INDEX(x) RC_##x,
358 RESULT_COUNTS(RC_INDEX, RC_INDEX)
363 /*----- transmission buffers -----*/
368 xk_Malloc, xk_Const, xk_Artdata
380 /*----- core operational data structure types -----*/
383 /* This is also an instance of struct oop_readable */
384 struct oop_readable readable; /* first */
385 oop_readable_call *readable_callback;
386 void *readable_callback_user;
389 Filemon_Perfile *filemon;
392 long inprogress; /* no. of articles read but not processed */
396 int counts[art_MaxState][RCI_max];
397 int readcount_ok, readcount_blank, readcount_err;
412 #define SMS_LIST(X) \
420 enum StateMachineState {
421 #define SMS_DEF_ENUM(s) sm_##s,
422 SMS_LIST(SMS_DEF_ENUM)
425 static const char *sms_names[]= {
426 #define SMS_DEF_NAME(s) #s ,
427 SMS_LIST(SMS_DEF_NAME)
433 int fd, max_queue, stream, quitting;
434 ArticleList waiting; /* not yet told peer */
435 ArticleList priority; /* peer says send it now */
436 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
437 struct iovec xmit[CONNIOVS];
438 XmitDetails xmitd[CONNIOVS];
443 /*----- operational variables -----*/
445 static oop_source *loop;
447 static int until_connect;
448 static ConnList conns;
449 static ArticleList queue;
451 static char *path_lock, *path_flushing, *path_defer, *globpat_backlog;
453 #define SMS(newstate, periods, why) \
454 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
456 static StateMachineState sms;
458 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
459 static int sm_period_counter, until_backlog_nextscan;
461 static double accept_proportion;
462 static int nocheck, nocheck_reported;
464 /*========== logging ==========*/
466 #define VA va_list al; va_start(al,fmt)
467 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
468 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
470 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
471 static void logcore(int sysloglevel, const char *fmt, ...) {
474 vsyslog(sysloglevel,fmt,al);
476 vfprintf(stderr,fmt,al);
482 static void logv(int sysloglevel, const char *pfx, int errnoval,
483 const char *fmt, va_list al) PRINTF(5,0);
484 static void logv(int sysloglevel, const char *pfx, int errnoval,
485 const char *fmt, va_list al) {
486 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
487 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
488 msgbuf[sizeof(msgbuf)-1]= 0;
490 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
491 sysloglevel= LOG_ERR; /* run by wrong user, probably */
493 logcore(sysloglevel, "<%s>%s: %s%s%s",
494 sitename, pfx, msgbuf,
495 errnoval>=0 ? ": " : "",
496 errnoval>=0 ? strerror(errnoval) : "");
499 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
500 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
501 static void fn(const char *fmt, ...) { \
503 logv(sysloglevel, pfx, err, fmt, al); \
507 #define logwrap(fn, pfx, sysloglevel, err) \
508 static void fn(const char *fmt, ...) PRINTF(1,2); \
509 static void fn(const char *fmt, ...) { \
511 logv(sysloglevel, pfx, err, fmt, al); \
515 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
516 diewrap(die, " critical", LOG_CRIT, -1, 16);
518 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
519 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
521 logwrap(syswarn, " warning", LOG_WARNING, errno);
522 logwrap(warn, " warning", LOG_WARNING, -1);
524 logwrap(notice, "", LOG_NOTICE, -1);
525 logwrap(info, " info", LOG_INFO, -1);
526 logwrap(debug, " debug", LOG_DEBUG, -1);
529 /*========== utility functions etc. ==========*/
531 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
532 static char *xvasprintf(const char *fmt, va_list al) {
534 int rc= vasprintf(&str,fmt,al);
535 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
538 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
539 static char *xasprintf(const char *fmt, ...) {
541 char *str= xvasprintf(fmt,al);
546 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
548 static pid_t xfork(const char *what) {
552 if (child==-1) sysdie("cannot fork for %s",what);
553 if (!child) postfork(what);
554 debug("forked %s %ld", what, (unsigned long)child);
558 static void on_fd_read_except(int fd, oop_call_fd callback) {
559 loop->on_fd(loop, fd, OOP_READ, callback, 0);
560 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
562 static void cancel_fd_read_except(int fd) {
563 loop->cancel_fd(loop, fd, OOP_READ);
564 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
567 static void report_child_status(const char *what, int status) {
568 if (WIFEXITED(status)) {
569 int es= WEXITSTATUS(status);
571 warn("%s: child died with error exit status %d",es);
572 } else if (WIFSIGNALED(status)) {
573 int sig= WTERMSIG(status);
574 const char *sigstr= strsignal(sig);
575 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
577 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
579 warn("%s: child died due to unknown fatal signal %d%s",
580 what, sig, coredump);
582 warn("%s: child died with unknown wait status %d", status);
586 static int xwaitpid(pid_t *pid, const char *what) {
589 int r= kill(*pid, SIGKILL);
590 if (r) sysdie("cannot kill %s child", what);
592 pid_t got= waitpid(*pid, &status, WNOHANG);
593 if (got==-1) sysdie("cannot reap %s child", what);
600 static void xunlink(const char *path, const char *what) {
602 if (r) sysdie("can't unlink %s %s", path, what);
605 static time_t xtime(void) {
607 if (now==-1) sysdie("time(2) failed");
610 static void check_isreg(const struct stat *stab, const char *path,
612 if (!S_ISREG(stab->st_mode))
613 die("%s %s not a plain file (mode 0%lo)",
614 what, path, (unsigned long)stab->st_mode);
617 static void xfstat(int fd, struct stat *stab_r, const char *what) {
618 int r= fstat(fd, stab_r);
619 if (r) sysdie("could not fstat %s", what);
622 static void xfstat_isreg(int fd, struct stat *stab_r,
623 const char *path, const char *what) {
624 xfstat(fd, stab_r, what);
625 check_isreg(stab_r, path, what);
628 static void xlstat_isreg(const char *path, struct stat *stab,
629 int *enoent_r /* 0 means ENOENT is fatal */,
631 int r= lstat(path, stab);
633 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
634 sysdie("could not lstat %s %s", what, path);
636 if (enoent_r) *enoent_r= 0;
637 check_isreg(stab, path, what);
640 static void setnonblock(int fd, int nonblocking) {
641 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
642 if (nonblocking) r |= O_NONBLOCK;
643 else r &= ~O_NONBLOCK;
644 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
647 static int samefile(const struct stat *a, const struct stat *b) {
648 assert(S_ISREG(a->st_mode));
649 assert(S_ISREG(b->st_mode));
650 return (a->st_ino == b->st_ino &&
651 a->st_dev == b->st_dev);
654 static char *sanitise(const char *input) {
655 static char sanibuf[100]; /* returns pointer to this buffer! */
657 const char *p= input;
661 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
663 if (!c) { *q++= '\''; *q=0; break; }
664 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
665 sprintf(q,"\\x%02x",c);
671 /*========== making new connections ==========*/
673 static void conn_dispose(Conn *conn) {
675 perhaps_close(&conn->fd);
677 until_connect= reconnect_delay_periods;
680 static int connecting_sockets[2]= {-1,-1};
681 static pid_t connecting_child;
683 static void connect_attempt_discard(void) {
684 if (connecting_sockets[0])
685 cancel_fd_read_except(connecting_sockets[0]);
687 perhaps_close(&connecting_sockets[0]);
688 perhaps_close(&connecting_sockets[1]);
690 if (connecting_child) {
691 int r= kill(connecting_child, SIGTERM);
692 if (r) syswarn("failed to kill connecting child");
693 int status= xwaitpid(&connecting_child, "connect");
695 if (!(WIFEXITED(status) ||
696 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
697 report_child_status("connect", status);
701 #define PREP_DECL_MSG_CMSG(msg) \
703 memset(&msg,0,sizeof(msg)); \
704 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
705 msg.msg_control= msg##cbuf; \
706 msg.msg_controllen= sizeof(msg##cbuf);
708 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
711 conn= xmalloc(sizeof(*conn));
712 memset(conn,0,sizeof(*conn));
714 PREP_DECL_MSG_CMSG(msg);
715 struct cmsghdr *h= 0;
716 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
717 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
720 pid_t got= waitpid(connecting_child, &status, WNOHANG);
722 assert(got==connecting_child);
724 if (WIFEXITED(status) &&
725 (WEXITSTATUS(status) != 0 &&
726 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
727 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
728 /* child already reported the problem */
729 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
730 warn("connect: connection attempt timed out");
731 } else if (!WIFEXITED(status)) {
732 report_child_status("connect", status);
733 /* that's probably the root cause then */
736 /* child is still running apparently, report the socket problem */
738 syswarn("connect: read from child socket failed");
739 else if (e == OOP_EXCEPTION)
740 warn("connect: unexpected exception on child socket");
742 warn("connect: unexpected EOF on child socket");
747 #define CHK(field, val) \
748 if (h->cmsg_##field != val) { \
749 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
752 CHK(level, SOL_SOCKET);
753 CHK(type, SCM_RIGHTS);
754 CHK(len, CMSG_LEN(sizeof(conn->fd)));
757 if (CMSG_NXTHDR(&msg,h)) { die("connect: child sent many cmsgs"); goto x; }
759 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
762 pid_t got= waitpid(connecting_child, &status, 0);
763 if (got==-1) sysdie("connect: real wait for child");
764 assert(got == connecting_child);
767 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
768 int es= WEXITSTATUS(status);
770 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
771 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
773 fatal("connect: child gave unexpected exit status %d", es);
777 setnonblock(conn->fd, 1);
778 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
779 LIST_ADDHEAD(conns, conn);
780 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
781 connect_attempt_discard();
782 check_master_queue();
787 connect_attempt_discard();
790 static int allow_connect_start(void) {
791 return conns.count < max_connections
796 static void connect_start(void) {
797 assert(!connecting_sockets[0]);
798 assert(!connecting_sockets[1]);
799 assert(!connecting_child);
801 notice("starting connection attempt");
803 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
804 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
806 connecting_child= xfork("connection");
808 if (!connecting_child) {
809 FILE *cn_from, *cn_to;
810 char buf[NNTP_STRLEN+100];
811 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
813 r= close(connecting_sockets[0]);
814 if (r) sysdie("connect: close parent socket in child");
816 alarm(connection_setup_timeout);
817 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
818 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
819 else sysfatal("connect: connection attempt failed");
821 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
822 sysfatal("connect: authentication failed");
824 if (fputs("MODE STREAM\r\n", cn_to) ||
826 sysfatal("connect: could not send MODE STREAM");
827 buf[sizeof(buf)-1]= 0;
828 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
830 sysfatal("connect: could not read response to MODE STREAM");
832 fatal("connect: connection close in response to MODE STREAM");
837 fatal("connect: response to MODE STREAM is too long: %.100s...",
838 remote_host, sanitise(buf));
839 l--; if (l>0 && buf[l-1]=='\r') l--;
842 int rcode= strtoul(buf,&ep,10);
844 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
848 exitstatus= CONNCHILD_ESTATUS_STREAM;
854 warn("connect: unexpected response to MODE STREAM: %.50s",
860 int fd= fileno(cn_from);
862 PREP_DECL_MSG_CMSG(msg);
863 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
864 cmsg->cmsg_level= SOL_SOCKET;
865 cmsg->cmsg_type= SCM_RIGHTS;
866 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
867 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
869 msg.msg_controllen= cmsg->cmsg_len;
870 r= sendmsg(connecting_sockets[1], &msg, 0);
871 if (r) sysdie("sendmsg failed for new connection");
876 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
877 if (r) sysdie("connect: close child socket in parent");
879 on_fd_read_except(connecting_sockets[0], connchild_event);
883 connect_attempt_discard();
887 /*========== overall control of article flow ==========*/
889 static void check_master_queue(void) {
897 /* Find a connection to offer this article. We prefer a busy
898 * connection to an idle one, provided it's not full. We take the
899 * first (oldest) and since that's stable, it will mean we fill up
900 * connections in order. That way if we have too many
901 * connections, the spare ones will go away eventually.
903 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
904 int inqueue= walk->sent.count + walk->priority.count
905 + walk->waiting.count;
906 spare= walk->max_queue - inqueue;
907 assert(inqueue <= max_queue_per_conn);
909 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
910 else if (spare>0) /*working*/ { use= walk; break; }
914 Article *art= LIST_REMHEAD(queue);
915 LIST_ADDTAIL(use->waiting, art);
918 conn_maybe_write(use);
919 } else if (allow_connect_start()) {
920 until_connect= reconnect_delay_periods;
929 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
934 static void conn_maybe_write(Conn *conn) {
937 conn_make_some_xmits(conn);
939 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
943 void *rp= conn_write_some_xmits(conn);
944 if (rp==OOP_CONTINUE) {
945 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
947 } else if (rp==OOP_HALT) {
950 /* transmitted everything */
957 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
958 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
959 int requeue[art_MaxState];
962 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
963 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
964 while ((art= LIST_REMHEAD(conn->sent))) {
965 requeue[art->state]++;
966 if (art->state==art_Unsolicited) art->state= art_Unchecked;
967 LIST_ADDTAIL(queue,art);
972 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
975 char *m= xvasprintf(fmt,al);
976 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
977 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
980 LIST_REMOVE(conns,conn);
982 check_master_queue();
985 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
986 static void connfail(Conn *conn, const char *fmt, ...) {
989 vconnfail(conn,fmt,al);
993 /*========== article transmission ==========*/
995 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
996 XmitKind kind) { /* caller must then fill in details */
997 struct iovec *v= &conn->xmit[conn->xmitu];
998 XmitDetails *d= &conn->xmitd[conn->xmitu++];
999 v->iov_base= (char*)data;
1005 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1006 xmit_core(conn,data,len, xk_Const);
1008 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1010 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1011 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1015 static void xmit_free(XmitDetails *d) {
1017 case xk_Malloc: free(d->info.malloc_tofree); break;
1018 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1019 case xk_Const: break;
1024 static void *conn_write_some_xmits(Conn *conn) {
1026 * 0: nothing more to write, no need to call us again
1027 * OOP_CONTINUE: more to write but fd not writeable
1028 * OOP_HALT: disaster, have destroyed conn
1031 int count= conn->xmitu;
1032 if (!count) return 0;
1034 if (count > IOV_MAX) count= IOV_MAX;
1035 ssize_t rs= writev(conn->fd, conn->xmit, count);
1037 if (errno == EAGAIN) return OOP_CONTINUE;
1038 connfail(conn, "write failed: %s", strerror(errno));
1044 for (done=0; rs && done<conn->xmitu; done++) {
1045 struct iovec *vp= &conn->xmit[done];
1046 XmitDetails *dp= &conn->xmitd[done];
1047 if (rs > vp->iov_len) {
1055 int newu= conn->xmitu - done;
1056 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1057 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1062 static void conn_make_some_xmits(Conn *conn) {
1064 if (conn->xmitu+5 > CONNIOVS)
1067 Article *art= LIST_REMHEAD(conn->priority);
1068 if (!art) art= LIST_REMHEAD(conn->waiting);
1071 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1072 /* actually send it */
1074 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1078 XMIT_LITERAL("TAKETHIS ");
1079 xmit_noalloc(conn, art->messageid, art->midlen);
1080 XMIT_LITERAL("\r\n");
1081 xmit_artbody(conn, artdata);
1084 /* we got 235 from IHAVE */
1086 xmit_artbody(conn, artdata);
1088 XMIT_LITERAL(".\r\n");
1093 art->state == art_Unchecked ? art_Unsolicited :
1094 art->state == art_Wanted ? art_Wanted :
1096 art->ipf->counts[art->state][RC_sent]++;
1097 LIST_ADDTAIL(conn->sent, art);
1103 XMIT_LITERAL("IHAVE ");
1105 XMIT_LITERAL("CHECK ");
1106 xmit_noalloc(conn, art->messageid, art->midlen);
1107 XMIT_LITERAL("\r\n");
1109 assert(art->state == art_Unchecked);
1110 art->ipf->counts[art->state][RC_sent]++;
1111 LIST_ADDTAIL(conn->sent, art);
1117 /*========== handling responses from peer ==========*/
1119 static const oop_rd_style peer_rd_style= {
1120 OOP_RD_DELIM_STRIP, '\n',
1122 OOP_RD_SHORTREC_FORBID
1125 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1126 const char *errmsg, int errnoval,
1127 const char *data, size_t recsz, void *conn_v) {
1129 connfail(conn, "error receiving from peer: %s", errmsg);
1130 return OOP_CONTINUE;
1133 static Article *article_reply_check(Conn *conn, const char *response,
1134 int code_indicates_streaming,
1136 /* 1:yes, -1:no, 0:dontcare */,
1137 const char *sanitised_response) {
1138 Article *art= LIST_HEAD(conn->sent);
1142 "peer gave unexpected response when no commands outstanding: %s",
1143 sanitised_response);
1147 if (code_indicates_streaming) {
1148 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1149 if (!conn->stream) {
1150 connfail(conn, "peer gave streaming response code "
1151 " to IHAVE or subsequent body: %s", sanitised_response);
1154 const char *got_mid= response+4;
1155 int got_midlen= strcspn(got_mid, " \n\r");
1156 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1157 connfail(conn, "peer gave streaming response with syntactically invalid"
1158 " messageid: %s", sanitised_response);
1161 if (got_midlen != art->midlen ||
1162 memcmp(got_mid, art->messageid, got_midlen)) {
1163 connfail(conn, "peer gave streaming response code to wrong article -"
1164 " probable synchronisation problem; we offered: %s;"
1166 art->messageid, sanitised_response);
1171 connfail(conn, "peer gave non-streaming response code to"
1172 " CHECK/TAKETHIS: %s", sanitised_response);
1177 if (must_have_sent>0 && art->state < art_Wanted) {
1178 connfail(conn, "peer says article accepted but"
1179 " we had not sent the body: %s", sanitised_response);
1182 if (must_have_sent<0 && art->state >= art_Wanted) {
1183 connfail(conn, "peer says please sent the article but we just did: %s",
1184 sanitised_response);
1188 Article *art_again= LIST_REMHEAD(conn->sent);
1189 assert(art_again == art);
1193 static void update_nocheck(int accepted) {
1194 accept_proportion *= nocheck_decay;
1195 accept_proportion += accepted * (1.0 - nocheck_decay);
1196 int new_nocheck= accept_proportion >= nocheck_thresh;
1197 if (new_nocheck && !nocheck_reported) {
1198 notice("entering nocheck mode for the first time");
1199 nocheck_reported= 1;
1200 } else if (new_nocheck != nocheck) {
1201 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1203 nocheck= new_nocheck;
1206 static void article_done(Conn *conn, Article *art, int whichcount) {
1207 art->ipf->counts[art->state][whichcount]++;
1208 if (whichcount == RC_accepted) update_nocheck(1);
1209 else if (whichcount == RC_unwanted) update_nocheck(0);
1211 InputFile *ipf= art->ipf;
1212 while (art->blanklen) {
1213 static const char spaces[]=
1218 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1219 int r= pwrite(ipf->fd, spaces, w, art->offset);
1221 if (errno==EINTR) continue;
1222 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1223 art->messageid, art->blanklen, art->offset, ipf->path);
1225 assert(r>=0 && r<=w);
1231 assert(ipf->inprogress >= 0);
1233 if (!ipf->inprogress && ipf != main_input_file)
1234 queue_check_input_done();
1239 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1240 const char *errmsg, int errnoval,
1241 const char *data, size_t recsz, void *conn_v) {
1244 if (ev == OOP_RD_EOF) {
1245 connfail(conn, "unexpected EOF from peer");
1246 return OOP_CONTINUE;
1248 assert(ev == OOP_RD_OK);
1250 char *sani= sanitise(data);
1253 unsigned long code= strtoul(data, &ep, 10);
1254 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1255 connfail(conn, "badly formatted response from peer: %s", sani);
1256 return OOP_CONTINUE;
1259 if (conn->quitting) {
1260 if (code!=205 && code!=503) {
1261 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1263 notice("C%d idle connection closed\n");
1264 assert(!conn->waiting.count);
1265 assert(!conn->priority.count);
1266 assert(!conn->sent.count);
1267 assert(!conn->xmitu);
1268 LIST_REMOVE(conns,conn);
1271 return OOP_CONTINUE;
1276 #define GET_ARTICLE(musthavesent) \
1277 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1278 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1280 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1281 code_streaming= (streaming); \
1282 GET_ARTICLE(musthavesent); \
1283 article_done(conn, art, RC_##how); break;
1285 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1287 int code_streaming= 0;
1291 case 400: PEERBADMSG("peer stopped accepting articles");
1292 case 503: PEERBADMSG("peer timed us out");
1293 default: PEERBADMSG("peer sent unexpected message");
1295 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1296 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1298 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1299 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1301 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1302 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1304 case 238: /* CHECK says send it */
1306 case 335: /* IHAVE says send it */
1308 assert(art->state == art_Unchecked);
1309 art->ipf->counts[art->state][RC_accepted]++;
1310 art->state= art_Wanted;
1311 LIST_ADDTAIL(conn->priority, art);
1314 case 431: /* CHECK or TAKETHIS says try later */
1316 case 436: /* IHAVE says try later */
1319 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1321 sysfatal("write to defer file %s",path_defer);
1322 article_done(conn, art, RC_deferred);
1327 conn_maybe_write(conn);
1328 check_master_queue();
1329 return OOP_CONTINUE;
1333 /*========== monitoring of input files ==========*/
1335 static void feedfile_eof(InputFile *ipf) {
1336 assert(ipf != main_input_file); /* promised by tailing_try_read */
1338 inputfile_tailing_stop(ipf);
1339 assert(ipf->fd >= 0);
1340 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1343 if (ipf == flushing_input_file) {
1344 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1345 if (main_input_file) inputfile_tailing_start(main_input_file);
1346 statemc_check_flushing_done();
1347 } else if (ipf == backlog_input_file) {
1348 statemc_check_backlog_done();
1350 abort(); /* supposed to wait rather than get EOF on main input file */
1354 static InputFile *open_input_file(const char *path) {
1355 int fd= open(path, O_RDONLY);
1357 if (errno==ENOENT) return 0;
1358 sysfatal("unable to open input file %s", path);
1361 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1362 memset(ipf,0,sizeof(*ipf));
1365 strcpy(ipf->path, path);
1370 static void close_input_file(InputFile *ipf) {
1371 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1372 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1373 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1374 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1377 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1381 /*---------- dealing with articles read in the input file ----------*/
1383 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1384 const char *data, const char *how) {
1385 warn("corrupted file: %s, offset %lu: %s: %s",
1386 ipf->path, (unsigned long)offset, how, sanitise(data));
1387 ipf->readcount_err++;
1388 if (ipf->readcount_err > max_bad_data_initial +
1389 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1390 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1391 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1392 return OOP_CONTINUE;
1395 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1396 oop_rd_event ev, const char *errmsg,
1397 int errnoval, const char *data, size_t recsz,
1399 InputFile *ipf= ipf_v;
1400 assert(ev == OOP_RD_SYSTEM);
1402 sysdie("error reading input file: %s, offset %lu",
1403 ipf->path, (unsigned long)ipf->offset);
1406 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1407 oop_rd_event ev, const char *errmsg,
1408 int errnoval, const char *data, size_t recsz,
1410 InputFile *ipf= ipf_v;
1412 char tokentextbuf[sizeof(TOKEN)*2+3];
1414 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1416 off_t old_offset= ipf->offset;
1417 ipf->offset += recsz + 1;
1419 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1421 if (ev==OOP_RD_PARTREC)
1422 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1423 /* but process it anyway */
1425 if (ipf->skippinglong) {
1426 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1429 if (ev==OOP_RD_LONG) {
1430 ipf->skippinglong= 1;
1431 X_BAD_DATA("overly long line");
1434 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1435 if (!recsz) X_BAD_DATA("empty line");
1438 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1439 ipf->readcount_blank++;
1440 return OOP_CONTINUE;
1443 char *space= strchr(data,' ');
1444 int tokenlen= space-data;
1445 int midlen= (int)recsz-tokenlen-1;
1446 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1447 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1449 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1450 memcpy(tokentextbuf, data, tokenlen);
1451 tokentextbuf[tokenlen]= 0;
1452 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1454 ipf->readcount_ok++;
1456 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1457 art->offset= ipf->offset;
1458 art->blanklen= recsz;
1459 art->midlen= midlen;
1460 art->state= art_Unchecked;
1461 art->ipf= ipf; ipf->inprogress++;
1462 art->token= TextToToken(tokentextbuf);
1463 strcpy(art->messageid, space+1);
1464 LIST_ADDTAIL(queue, art);
1466 if (sms==sm_NORMAL && ipf==main_input_file &&
1467 ipf->offset >= target_max_feedfile_size)
1468 statemc_start_flush("feed file size");
1470 check_master_queue();
1471 return OOP_CONTINUE;
1474 /*========== tailing input file ==========*/
1476 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1478 InputFile *ipf= user;
1479 return ipf->readable_callback(loop, &ipf->readable,
1480 ipf->readable_callback_user);
1483 static void tailing_on_cancel(struct oop_readable *rable) {
1484 InputFile *ipf= (void*)rable;
1486 if (ipf->filemon) filemon_stop(ipf);
1487 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1488 ipf->readable_callback= 0;
1491 static void tailing_queue_readable(InputFile *ipf) {
1492 /* lifetime of ipf here is OK because destruction will cause
1493 * on_cancel which will cancel this callback */
1494 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1497 static int tailing_on_readable(struct oop_readable *rable,
1498 oop_readable_call *cb, void *user) {
1499 InputFile *ipf= (void*)rable;
1501 tailing_on_cancel(rable);
1502 ipf->readable_callback= cb;
1503 ipf->readable_callback_user= user;
1506 tailing_queue_readable(ipf);
1510 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1512 InputFile *ipf= (void*)rable;
1514 ssize_t r= read(ipf->fd, buffer, length);
1516 if (errno==EINTR) continue;
1520 if (ipf==main_input_file) {
1523 } else if (ipf==flushing_input_file) {
1525 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1526 } else if (ipf==backlog_input_file) {
1536 /*---------- filemon implemented with inotify ----------*/
1538 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1539 #define HAVE_FILEMON
1541 #include <linux/inotify.h>
1543 static int filemon_inotify_fd;
1544 static int filemon_inotify_wdmax;
1545 static InputFile **filemon_inotify_wd2ipf;
1547 struct Filemon_Perfile {
1551 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1552 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1553 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1555 if (wd >= filemon_inotify_wdmax) {
1557 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1558 sizeof(*filemon_inotify_wd2ipf) * newmax);
1559 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1560 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1561 filemon_inotify_wdmax= newmax;
1564 assert(!filemon_inotify_wd2ipf[wd]);
1565 filemon_inotify_wd2ipf[wd]= ipf;
1567 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1568 ipf, wd, filemon_inotify_wdmax);
1573 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1575 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1576 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1577 if (r) sysdie("inotify_rm_watch");
1578 filemon_inotify_wd2ipf[wd]= 0;
1581 static void *filemon_inotify_readable(oop_source *lp, int fd,
1582 oop_event e, void *u) {
1583 struct inotify_event iev;
1585 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1587 if (errno==EAGAIN) break;
1588 sysdie("read from inotify master");
1589 } else if (r==sizeof(iev)) {
1590 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1592 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1594 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1595 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1596 filemon_callback(ipf);
1598 return OOP_CONTINUE;
1601 static int filemon_method_init(void) {
1602 filemon_inotify_fd= inotify_init();
1603 if (filemon_inotify_fd<0) {
1604 syswarn("could not initialise inotify: inotify_init failed");
1608 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1610 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1614 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1616 /*---------- filemon dummy implementation ----------*/
1618 #if !defined(HAVE_FILEMON)
1620 struct Filemon_Perfile { int dummy; };
1622 static int filemon_method_init(void) { return 0; }
1623 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1624 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1626 #endif /* !HAVE_FILEMON */
1628 /*---------- filemon generic interface ----------*/
1630 static void filemon_start(InputFile *ipf) {
1631 assert(!ipf->filemon);
1633 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1634 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1635 filemon_method_startfile(ipf, ipf->filemon);
1638 static void filemon_stop(InputFile *ipf) {
1639 if (!ipf->filemon) return;
1640 filemon_method_stopfile(ipf, ipf->filemon);
1645 static void filemon_callback(InputFile *ipf) {
1646 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1649 /*---------- interface to start and stop an input file ----------*/
1651 static const oop_rd_style feedfile_rdstyle= {
1652 OOP_RD_DELIM_STRIP, '\n',
1654 OOP_RD_SHORTREC_LONG,
1657 static void inputfile_tailing_start(InputFile *ipf) {
1659 ipf->readable.on_readable= tailing_on_readable;
1660 ipf->readable.on_cancel= tailing_on_cancel;
1661 ipf->readable.try_read= tailing_try_read;
1662 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1663 ipf->readable.delete_kill= 0;
1665 ipf->readable_callback= 0;
1666 ipf->readable_callback_user= 0;
1668 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1671 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1672 feedfile_got_article,ipf, feedfile_read_err, ipf);
1673 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1676 static void inputfile_tailing_stop(InputFile *ipf) {
1678 oop_rd_cancel(ipf->rd);
1679 oop_rd_delete(ipf->rd);
1681 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1685 /*========== interaction with innd - state machine ==========*/
1687 /* See official state diagram at top of file. We implement
1698 |`---------------------------------------------------.
1700 |`---------------- - - - |
1701 D ENOENT | D EXISTS see OVERALL STATES diagram |
1702 | for full startup logic |
1705 | ============ try to |
1711 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1712 ^ | hardlink F to D |
1715 | | our handle onto F is now onto D |
1718 | |<-------------------<---------------------<---------+
1720 | | spawn inndcomm flush |
1722 | ================== |
1723 | FLUSHING[-ABSENT] |
1725 | main D tail/none |
1726 | ================== |
1728 | | INNDCOMM FLUSH FAILS ^
1729 | |`----------------------->----------. |
1731 | | NO SUCH SITE V |
1732 ^ |`--------------->----. ==================== |
1733 | | \ FLUSHFAILED[-ABSENT] |
1735 | | FLUSH OK \ main D tail/none |
1736 | | open F \ ==================== |
1738 | | \ | TIME TO RETRY |
1739 | |`------->----. ,---<---'\ `----------------'
1740 | | D NONE | | D NONE `----.
1742 | ============= V V ============
1743 | SEPARATED-1 | | DROPPING-1
1744 | flsh->fd>=0 | | flsh->fd>=0
1745 | [Separated] | | [Dropping]
1746 | main F idle | | main none
1747 | old D tail | | old D tail
1748 | ============= | | ============
1750 ^ | EOF ON D | | defer | EOF ON D
1752 | =============== | | ===============
1753 | SEPARATED-2 | | DROPPING-2
1754 | flsh->fd==-1 | V flsh->fd==-1
1755 | [Finishing] | | [Dropping]
1756 | main F tail | `. main none
1757 | old D closed | `. old D closed
1758 | =============== V `. ===============
1760 | | ALL D PROCESSED `. | ALL D PROCESSED
1761 | V install defer as backlog `. | install defer
1762 ^ | close D `. | close D
1763 | | unlink D `. | unlink D
1766 `----------' ==============
1786 static void startup_set_input_file(InputFile *f) {
1787 assert(!main_input_file);
1789 inputfile_tailing_start(f);
1792 static void statemc_init(void) {
1793 struct stat stab, stabf;
1795 path_lock= xasprintf("%s_lock", feedfile);
1796 path_flushing= xasprintf("%s_flushing", feedfile);
1797 path_defer= xasprintf("%s_defer", feedfile);
1798 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1801 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1802 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1805 memset(&fl,0,sizeof(fl));
1807 fl.l_whence= SEEK_SET;
1808 int r= fcntl(lockfd, F_SETLK, &fl);
1810 if (errno==EACCES || errno==EAGAIN) {
1811 if (quiet_multiple) exit(0);
1812 fatal("another duct holds the lockfile");
1814 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1817 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
1819 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1821 if (!lock_noent && samefile(&stab, &stabf))
1825 sysdie("could not close stale lockfile %s", path_lock);
1827 debug("startup: locked");
1829 search_backlog_file();
1832 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1834 debug("startup: ductdefer ENOENT");
1836 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1837 switch (stab.st_nlink==1) {
1839 open_defer(); /* so that we will later close it and rename it */
1842 xunlink(path_defer, "stale defer file link"
1843 " (presumably hardlink to backlog file)");
1846 die("defer file %s has unexpected link count %d",
1847 path_defer, stab.st_nlink);
1851 struct stat stab_f, stab_d;
1854 InputFile *file_d= open_input_file(path_flushing);
1855 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
1857 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1859 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1860 debug("startup: F==D => Hardlinked");
1861 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1866 debug("startup: F ENOENT => Moved");
1867 if (file_d) startup_set_input_file(file_d);
1868 spawn_inndcomm_flush("feedfile missing at startup");
1869 /* => Flushing, sms:=FLUSHING */
1872 debug("startup: F!=D => Separated");
1873 startup_set_input_file(file_d);
1874 SMS(SEPARATED, 0, "found both old and current feed files");
1876 debug("startup: F exists, D ENOENT => Normal");
1877 InputFile *file_f= open_input_file(feedfile);
1878 if (!file_f) die("feed file vanished during startup");
1879 startup_set_input_file(file_f);
1880 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1885 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1886 assert(sms == sm_NORMAL);
1888 debug("starting flush (%s) (%lu >?= %lu) (%d)",
1890 (unsigned long)(main_input_file ? main_input_file->offset : 0),
1891 (unsigned long)target_max_feedfile_size,
1894 int r= link(feedfile, path_flushing);
1895 if (r) sysdie("link feedfile %s to flushing file %s",
1896 feedfile, path_flushing);
1899 xunlink(feedfile, "old feedfile link");
1902 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1905 static void statemc_period_poll(void) {
1906 if (!sm_period_counter) return;
1907 sm_period_counter--;
1908 assert(sm_period_counter>=0);
1910 if (sm_period_counter) return;
1913 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1915 case sm_FLUSHFAILED:
1916 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1923 static int inputfile_is_done(InputFile *ipf) {
1925 if (ipf->inprogress) return 0; /* new article in the meantime */
1926 if (ipf->fd >= 0); return 0; /* not had EOF */
1930 static void notice_processed(InputFile *ipf, const char *what,
1932 #define RCI_NOTHING(x) /* nothing */
1933 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
1934 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
1936 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
1938 info("processed %s%s read=%d(+%dbl,+%derr)"
1939 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
1940 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
1943 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
1944 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
1945 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
1946 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
1947 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
1948 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
1954 static void statemc_check_backlog_done(void) {
1955 InputFile *ipf= backlog_input_file;
1956 if (!inputfile_is_done(ipf)) return;
1958 const char *slash= strrchr(ipf->path, '/');
1959 const char *leaf= slash ? slash+1 : ipf->path;
1960 const char *under= strchr(slash, '_');
1961 const char *rest= under ? under+1 : leaf;
1962 if (!strncmp(rest,"backlog",7)) rest += 7;
1963 notice_processed(ipf,"backlog:",rest);
1965 close_input_file(ipf);
1966 if (unlink(ipf->path)) {
1967 if (errno != ENOENT)
1968 sysdie("could not unlink processed backlog file %s", ipf->path);
1969 warn("backlog file %s vanished while we were reading it"
1970 " so we couldn't remove it (but it's done now, anyway)",
1974 backlog_input_file= 0;
1975 search_backlog_file();
1979 static void statemc_check_flushing_done(void) {
1980 InputFile *ipf= flushing_input_file;
1981 if (!inputfile_is_done(ipf)) return;
1983 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1985 notice_processed(ipf,"feedfile",0);
1989 xunlink(path_flushing, "old flushing file");
1991 close_input_file(flushing_input_file);
1992 free(flushing_input_file);
1993 flushing_input_file= 0;
1995 if (sms==sm_SEPARATED) {
1996 notice("flush complete");
1997 SMS(NORMAL, 0, "flush complete");
1998 } else if (sms==sm_DROPPING) {
1999 SMS(DROPPED, 0, "old flush complete");
2000 search_backlog_file();
2001 notice("feed dropped, but will continue until backlog is finished");
2005 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2007 assert(!inputfile_is_done(main_input_file));
2008 statemc_check_flushing_done();
2009 statemc_check_backlog_done();
2010 return OOP_CONTINUE;
2013 static void queue_check_input_done(void) {
2014 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2017 static void statemc_setstate(StateMachineState newsms, int periods,
2018 const char *forlog, const char *why) {
2020 sm_period_counter= periods;
2022 const char *xtra= "";
2024 case sm_FLUSHING: sm_FLUSHFAILED:
2025 if (!main_input_file) xtra= "-ABSENT";
2027 case sm_SEPARATED: case sm_DROPPING:
2028 xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
2034 info("%s%s[%d] %s",forlog,xtra,periods,why);
2036 info("%s%s %s",forlog,xtra,why);
2040 /*---------- defer and backlog files ----------*/
2042 static void open_defer(void) {
2047 defer= fopen(path_defer, "a+");
2048 if (!defer) sysfatal("could not open defer file %s", path_defer);
2050 /* truncate away any half-written records */
2052 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2054 if (stab.st_size > LONG_MAX)
2055 die("defer file %s size is far too large", path_defer);
2060 long orgsize= stab.st_size;
2061 long truncto= stab.st_size;
2063 if (!truncto) break; /* was only (if anything) one half-truncated record */
2064 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2065 sysdie("seek in defer file %s while truncating partial", path_defer);
2070 sysdie("failed read from defer file %s", path_defer);
2072 die("defer file %s shrank while we were checking it!", path_defer);
2078 if (stab.st_size != truncto) {
2079 warn("truncating half-record at end of defer file %s -"
2080 " shrinking by %ld bytes from %ld to %ld",
2081 path_defer, orgsize - truncto, orgsize, truncto);
2084 sysfatal("could not flush defer file %s", path_defer);
2085 if (ftruncate(fileno(defer), truncto))
2086 sysdie("could not truncate defer file %s", path_defer);
2089 info("continuing existing defer file %s (%ld bytes)",
2090 path_defer, orgsize);
2092 if (fseek(defer, truncto, SEEK_SET))
2093 sysdie("could not seek to new end of defer file %s", path_defer);
2096 static void close_defer(void) {
2101 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2103 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2106 time_t now= xtime();
2108 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2110 (unsigned long)stab.st_ino);
2111 if (link(path_defer, backlog))
2112 sysfatal("could not install defer file %s as backlog file %s",
2113 path_defer, backlog);
2114 if (unlink(path_defer))
2115 sysdie("could not unlink old defer link %s to backlog file %s",
2116 path_defer, backlog);
2120 if (until_backlog_nextscan < 0 ||
2121 until_backlog_nextscan > backlog_retry_minperiods + 1)
2122 until_backlog_nextscan= backlog_retry_minperiods + 1;
2125 static void poll_backlog_file(void) {
2126 if (until_backlog_nextscan < 0) return;
2127 if (until_backlog_nextscan-- > 0) return;
2128 search_backlog_file();
2131 static void search_backlog_file(void) {
2132 /* returns non-0 iff there are any backlog files */
2137 const char *oldest_path=0;
2138 time_t oldest_mtime, now;
2140 if (backlog_input_file) return;
2144 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2148 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2150 die("out of memory expanding backlog pattern %s", globpat_backlog);
2152 for (i=0; i<gl.gl_pathc; i++) {
2153 const char *path= gl.gl_pathv[i];
2155 if (strchr(path,'#') || strchr(path,'~')) {
2156 debug("backlog file search skipping %s", path);
2159 r= stat(path, &stab);
2161 syswarn("failed to stat backlog file %s", path);
2164 if (!S_ISREG(stab.st_mode)) {
2165 warn("backlog file %s is not a plain file (or link to one)", path);
2168 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2170 oldest_mtime= stab.st_mtime;
2173 case GLOB_NOMATCH: /* fall through */
2176 sysdie("glob expansion of backlog pattern %s gave unexpected"
2177 " nonzero (error?) return value %d", globpat_backlog, r);
2183 debug("backlog scan: none");
2185 if (sms==sm_DROPPED) {
2186 notice("feed dropped and our work is complete");
2187 xunlink(path_lock, "lockfile for old feed");
2190 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2195 double age= difftime(now, oldest_mtime);
2196 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
2198 if (age_deficiency <= 0) {
2199 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2200 age, age_deficiency, oldest_path);
2202 backlog_input_file= open_input_file(oldest_path);
2203 if (!backlog_input_file) {
2204 warn("backlog file %s vanished as we opened it", backlog_input_file);
2207 inputfile_tailing_start(backlog_input_file);
2208 until_backlog_nextscan= -1;
2212 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
2214 if (backlog_spontaneous_rescan_periods >= 0 &&
2215 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2216 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2218 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2219 age, age_deficiency, until_backlog_nextscan, oldest_path);
2223 /*========== flushing the feed ==========*/
2225 static pid_t inndcomm_child;
2227 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2228 assert(inndcomm_child);
2229 int status= xwaitpid(&inndcomm_child, "inndcomm");
2230 cancel_fd_read_except(fd);
2233 assert(!flushing_input_file);
2235 if (WIFEXITED(status)) {
2236 switch (WEXITSTATUS(status)) {
2238 case INNDCOMMCHILD_ESTATUS_FAIL:
2241 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2242 warn("feed has been dropped by innd, finishing up");
2243 flushing_input_file= main_input_file;
2244 tailing_queue_readable(flushing_input_file);
2245 /* we probably previously returned EAGAIN from our fake read method
2246 * when in fact we were at EOF, so signal another readable event
2247 * so we actually see the EOF */
2251 if (flushing_input_file) {
2252 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2255 SMS(DROPPED, 0, "feed dropped by innd");
2256 search_backlog_file();
2258 return OOP_CONTINUE;
2262 flushing_input_file= main_input_file;
2263 tailing_queue_readable(flushing_input_file);
2265 main_input_file= open_input_file(feedfile);
2266 if (!main_input_file)
2267 die("flush succeeded but feedfile %s does not exist!", feedfile);
2269 if (flushing_input_file) {
2270 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2273 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2275 return OOP_CONTINUE;
2278 goto unexpected_exitstatus;
2281 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2282 warn("flush timed out trying to talk to innd");
2285 unexpected_exitstatus:
2286 report_child_status("inndcomm child", status);
2290 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2293 static void inndcommfail(const char *what) {
2294 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2295 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2298 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2301 notice("flushing %s",why);
2303 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2304 assert(!inndcomm_child);
2306 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2308 inndcomm_child= xfork("inndcomm child");
2310 if (!inndcomm_child) {
2311 const char *flushargv[2]= { sitename, 0 };
2317 alarm(inndcomm_flush_timeout);
2318 r= ICCopen(); if (r) inndcommfail("connect");
2319 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2320 if (!r) exit(0); /* yay! */
2322 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2323 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2324 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2328 int sentinel_fd= pipefds[0];
2329 on_fd_read_except(sentinel_fd, inndcomm_event);
2331 SMS(FLUSHING, 0, why);
2334 /*========== main program ==========*/
2336 static void postfork_inputfile(InputFile *ipf) {
2338 assert(ipf->fd >= 0);
2343 static void postfork_stdio(FILE *f) {
2344 /* we have no stdio streams that are buffered long-term */
2348 static void postfork(const char *what) {
2349 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2350 sysdie("%s child: failed to reset SIGPIPE");
2352 postfork_inputfile(main_input_file);
2353 postfork_inputfile(flushing_input_file);
2356 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2359 postfork_stdio(defer);
2362 #define EVERY(what, interval_sec, interval_usec, body) \
2363 static const struct timeval what##_timeout = \
2364 { interval_sec, interval_usec }; \
2365 static void what##_schedule(void); \
2366 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2368 what##_schedule(); \
2370 static void what##_schedule(void) { \
2371 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2374 EVERY(filepoll, 5,0, {
2375 if (main_input_file && main_input_file->readable_callback)
2376 filemon_callback(main_input_file);
2379 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s"
2380 #define DEBUG_IPF(wh) \
2381 wh##_input_file, debug_ipf_path(wh##_input_file), \
2382 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2383 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2384 static const char *debug_ipf_path(InputFile *ipf) {
2385 char *slash= strrchr(ipf->path,'/');
2386 return slash ? slash+1 : ipf->path;
2389 EVERY(period, PERIOD_SECONDS,0, {
2391 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2392 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_IPF(flushing)
2393 " children connecting=%ld inndcomm_child"
2395 sms_names[sms], sm_period_counter,
2396 queue.count, conns.count, until_connect,
2397 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2398 (long)connecting_child, (long)inndcomm_child
2401 if (until_connect) until_connect--;
2403 poll_backlog_file();
2404 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2405 statemc_period_poll();
2406 check_master_queue();
2410 /*========== option parsing ==========*/
2412 /*---------- generic option parser and logging ----------*/
2414 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2415 static void vbadusage(const char *fmt, va_list al) {
2418 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2419 static void badusage(const char *fmt, ...) {
2426 of_seconds= 001000u,
2427 of_boolean= 002000u,
2430 typedef struct Option Option;
2431 typedef void OptionParser(const Option*, const char *val);
2441 /*---------- specific option types ----------*/
2443 static void op_integer(const Option *o, const char *val) {
2446 unsigned long ul= strtoul(val,&ep,10);
2447 if (*ep || ep==val || errno || ul>INT_MAX)
2448 badusage("bad integer value for %s",o->lng);
2449 int *store= o->store;
2453 static void op_double(const Option *o, const char *val) {
2454 int *store= o->store;
2457 *store= strtod(val, &ep);
2458 if (*ep || ep==val || errno)
2459 badusage("bad floating point value for %s",o->lng);
2462 static void op_string(const Option *o, const char *val) {
2463 const char **store= o->store;
2467 static void op_seconds(const Option *o, const char *val) {
2468 int *store= o->store;
2472 double v= strtod(val,&ep);
2473 if (ep==val) badusage("bad time/duration value for %s",o->lng);
2475 if (!*ep || !strcmp(ep,"s")) unit= 1;
2476 else if (!strcmp(ep,"m")) unit= 60;
2477 else if (!strcmp(ep,"h")) unit= 3600;
2478 else if (!strcmp(ep,"d")) unit= 86400;
2479 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2483 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2487 static void op_periods_rndup(const Option *o, const char *val) {
2488 int *store= o->store;
2490 *store += PERIOD_SECONDS-1;
2491 *store /= PERIOD_SECONDS;
2494 static void op_setint(const Option *o, const char *val) {
2495 int *store= o->store;
2499 /*---------- specific options ----------*/
2501 static const Option options[]= {
2502 {'f',"feedfile", &feedfile, op_string },
2503 {'q',"quiet-multiple", &quiet_multiple, op_setint, 1,1 },
2505 { 0, "max-connections", &max_connections, op_integer },
2506 { 0, "max-queue-per-conn", &max_queue_per_conn, op_integer },
2509 { 0, "streaming", &try_stream, op_setint, 1,1 },
2510 { 0, "no-streaming", &try_stream, op_setint, 1,0 },
2511 {'P',"port", &port, op_integer },
2512 { 0, "inndconf", &inndconffile, op_string },
2513 {'d',"daemon", &become_daemon, op_setint, 1,1 },
2514 { 0, "no-daemon", &become_daemon, op_setint, 1,0 },
2516 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2517 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2519 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2520 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2521 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2524 int main(int argc, char **argv) {
2530 if (*arg != '-') break;
2531 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2533 while ((a= *++arg)) {
2537 char *equals= strchr(arg,'=');
2538 int len= equals ? (equals - arg) : strlen(arg);
2539 for (o=options; o->lng; o++)
2540 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2542 badusage("unknown long option --%s",arg);
2545 if (equals) badusage("option --%s does not take a value",o->lng);
2547 } else if (equals) {
2551 if (!arg) badusage("option --%s needs a value",o->lng);
2554 break; /* eaten the whole argument now */
2556 for (o=options; o->lng; o++)
2559 badusage("unknown short option -%c",a);
2566 if (!arg) badusage("option -%c needs a value",o->shrt);
2569 break; /* eaten the whole argument now */
2574 if (!arg) badusage("need site name argument");
2580 if (*++argv) badusage("too many non-option arguments");
2582 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2583 badusage("nocheck threshold percentage must be between 0..100");
2584 nocheck_thresh= nocheck_thresh_pct * 0.01;
2586 if (nocheck_decay_articles < 0.1)
2587 badusage("nocheck decay articles must be at least 0.1");
2588 nocheck_decay= 1 - 1/nocheck_decay_articles;
2591 pathoutgoing= innconf->pathoutgoing;
2592 innconf_read(inndconffile);
2595 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2596 else if (!feedfile[0])
2597 badusage("feed filename must be nonempty");
2598 else if (feedfile[strlen(feedfile)-1]=='/')
2599 feedfile= xasprintf("%s%s",feedfile,sitename);
2601 const char *feedfile_forbidden= "?*[~#";
2603 while ((c= *feedfile_forbidden++))
2604 if (strchr(feedfile, c))
2605 badusage("feed filename may not contain metacharacter %c",c);
2607 oop_source_sys *sysloop= oop_sys_new();
2608 if (!sysloop) sysdie("could not create liboop event loop");
2609 loop= (oop_source*)sysloop;
2611 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2612 sysdie("could not ignore SIGPIPE");
2614 if (become_daemon) {
2616 for (i=3; i<255; i++)
2617 /* do this now before we open syslog, etc. */
2619 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2621 int null= open("/dev/null",O_RDWR);
2622 if (null<0) sysdie("failed to open /dev/null");
2628 pid_t child1= xfork("daemonise first fork");
2629 if (child1) _exit(0);
2631 pid_t sid= setsid();
2632 if (sid != child1) sysdie("setsid failed");
2634 pid_t child2= xfork("daemonise second fork");
2635 if (child2) _exit(0);
2640 if (!filemon_method_init()) {
2641 warn("no file monitoring available, polling");
2642 filepoll_schedule();
2649 void *r= oop_sys_run(sysloop);
2650 assert(r == OOP_ERROR);
2651 sysdie("event loop failed");