3 * - close idle connections
4 * - cope better with garbage in feed file
5 * - cope better with NULs in feed file
6 * - check all structs initialised
7 * - check all fd watches properly undone
8 * - check all init functions called
9 * - actually implement badusage
10 * - options for all options
12 * - pid, sitename, hostname in lockfile
17 * Newsfeeds file entries should look like this:
18 * host.name.of.site[/exclude,exclude,...]\
19 * :pattern,pattern...[/distribution,distribution...]\
23 * sitename[/exclude,exclude,...]\
24 * :pattern,pattern...[/distribution,distribution...]\
30 * or might be blanked out
31 * <spc><spc><spc><spc>....
33 * F site.name main feed file
34 * opened/created, then written, by innd
37 * tokens blanked out by duct when processed
38 * site.name_lock lock preventing multiple ducts
39 * to hold lock must open,F_SETLK[W]
40 * and then stat to check that locked file
41 * still has name site.name_lock
42 * holder of this lock is "duct"
43 * (only) lockholder may remove the lockfile
44 * D site.name_flushing temporary feed file during flush (or crash)
45 * hardlink created by duct
47 * site.name_defer 431'd articles, still being written,
48 * created, written, used by duct
50 * site.name_backlog.<date>.<inum>
51 * 431'd articles, ready for innxmit or duct
52 * created (link/mv) by duct
53 * site.name_backlog<anything-else> (where <anything-else> does not
54 * contain '#' or '~') eg
55 * site.name_backlog.manual
56 * anything the sysadmin likes (eg, feed files
57 * from old feeds to be merged into this one)
58 * created (link/mv) by admin
59 * may be symlinks (in which case links
60 * may be written through, but only links
63 * It is safe to remove backlog files manually,
64 * if it's desired to throw away the backlog.
66 * Backlog files are also processed by innduct. We find the oldest
67 * backlog file which is at least a certain amount old, and feed it
68 * back into our processing. When every article in it has been read
69 * and processed, we unlink it and look for another backlog file.
71 * If we don't have a backlog file that we're reading, we close the
72 * defer file that we're writing and make it into a backlog file at
73 * the first convenient opportunity.
84 | | <----------------<---------------------------------'|
90 | F: innd writing, duct reading |
93 | | duct decides time to flush |
94 | | duct makes hardlink |
96 | V <------------------------'|
98 | F == D: innd writing, duct reading both exist |
101 | | <-----------<-------------<--'|
102 | | open D F ENOENT |
105 | V <---------------------. |
108 | D: innd writing, duct reading; or ENOENT | |
110 | | duct requests flush of feed | |
111 | | (others can too, harmlessly) | |
115 | D: innd flushing, duct; or ENOENT | |
117 | | inndcomm flush fails | |
118 | |`-------------------------->------------------' |
120 | | inndcomm reports no such site |
121 | |`---------------------------------------------------- | -.
123 | | innd finishes writing D, creates F | |
124 | | inndcomm reports flush successful | |
127 | Separated <----------------' |
128 | F: innd writing F!=D /
129 | D: duct reading; or ENOENT both exist /
131 | | duct gets to the end of D /
132 | | duct opens F too /
135 | F: innd writing, duct reading |
136 | D: duct finishing V
138 | | duct finishes processing D F: ENOENT
139 | V duct unlinks D D: duct reading
141 `--<--' | duct finishes
151 "duct reading" means innduct is reading the file but also
152 overwriting processed tokens.
156 * rune for printing diagrams:
158 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
163 /*============================== PROGRAM ==============================*/
171 #include "inndcomm.h"
173 #include "inn/list.h"
174 #include "inn/innconf.h"
177 #include <sys/types.h>
178 #include <sys/wait.h>
179 #include <sys/stat.h>
180 #include <sys/socket.h>
196 #include <oop-read.h>
198 /*----- general definitions, probably best not changed -----*/
200 #define PERIOD_SECONDS 60
202 #define CONNCHILD_ESTATUS_STREAM 4
203 #define CONNCHILD_ESTATUS_NOSTREAM 5
205 #define INNDCOMMCHILD_ESTATUS_FAIL 6
206 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
208 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
210 /*----- doubly linked lists -----*/
212 #define ISNODE(T) struct { T *succ, *pred; } node /* must be at start */
213 #define DEFLIST(T) typedef struct { T *hd, *tl, *tp; int count; } T##List
215 #define NODE(n) (assert((void*)&(n)->node == &(n)), \
216 (struct node*)&(n)->node)
218 #define LIST_CHECKCANHAVENODE(l,n) \
219 ((void)((n) == ((l).hd))) /* just for the type check */
221 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
222 ( LIST_CHECKCANHAVENODE(l,n), \
223 list_addsomehow((struct list*)&(l), NODE((n))), \
227 #define LIST_REMSOMEHOW(l,list_remsomehow) \
231 list_remsomehow((struct list*)&(l)) ) \
237 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
238 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
239 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
240 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
242 #define LIST_HEAD(l) ((typeof((l).hd))(list_head((struct list*)&(l))))
243 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
244 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
246 #define LIST_REMOVE(l,n) \
247 ( LIST_CHECKCANHAVENODE(l,n), \
248 list_remove(NODE((n))), \
252 #define LIST_INSERT(l,n,pred) \
253 ( LIST_CHECKCANHAVENODE(l,n), \
254 LIST_CHECKCANHAVENODE(l,pred), \
255 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
259 /*----- type predeclarations -----*/
261 typedef struct Conn Conn;
262 typedef struct Article Article;
263 typedef struct InputFile InputFile;
264 typedef struct XmitDetails XmitDetails;
265 typedef struct Filemon_Perfile Filemon_Perfile;
266 typedef enum StateMachineState StateMachineState;
271 /*----- function predeclarations -----*/
273 static void conn_maybe_write(Conn *conn);
274 static void conn_make_some_xmits(Conn *conn);
275 static void *conn_write_some_xmits(Conn *conn);
277 static void xmit_free(XmitDetails *d);
279 static void statemc_setstate(StateMachineState newsms, int periods,
280 const char *forlog, const char *why);
281 static void statemc_start_flush(const char *why); /* Normal => Flushing */
282 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
284 static void check_master_queue(void);
285 static void queue_check_input_done(void);
287 static void statemc_check_flushing_done(void);
288 static void statemc_check_backlog_done(void);
290 static void postfork(const char *what);
291 static void postfork_inputfile(InputFile *ipf);
293 static void open_defer(void);
294 static void close_defer(void);
295 static void search_backlog_file(void);
297 static void inputfile_tailing_start(InputFile *ipf);
298 static void inputfile_tailing_stop(InputFile *ipf);
300 static int filemon_init(void);
301 static void filemon_start(InputFile *ipf);
302 static void filemon_stop(InputFile *ipf);
303 static void filemon_callback(InputFile *ipf);
305 /*----- configuration options -----*/
307 static const char *sitename, *feedfile, *pathoutgoing;
308 static const char *remote_host;
309 static int quiet_multiple=0, become_daemon=1;
311 static int max_connections=10, max_queue_per_conn=200;
312 static int target_max_feedfile_size=100000;
314 static double max_bad_data_ratio= 0.01;
315 static int max_bad_data_initial= 30;
316 /* in one corrupt 4096-byte block the number of newlines has
317 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
319 static int connection_setup_timeout=200, port=119, try_stream=1;
320 static int inndcomm_flush_timeout=100;
321 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
322 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
323 static int spontaneous_flush_periods;
324 static const char *inndconffile;
326 static double nocheck_thresh_pct= 95.0;
327 static double nocheck_thresh; /* computed in main from _pct */
328 static double nocheck_decay_articles= 100; /* converted to _decay */
329 static double nocheck_decay; /* computed in main from _articles */
332 /*----- statistics -----*/
334 typedef enum { /* in queue in conn->sent */
335 art_Unchecked, /* not checked, not sent checking */
336 art_Wanted, /* checked, wanted sent body as requested */
337 art_Unsolicited, /* - sent body without check */
341 #define RESULT_COUNTS(RCS,RCN) \
349 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
350 #define RCI_TRIPLE_VALS_BASE(counts,x) \
351 counts[art_Unchecked] x \
352 + counts[art_Wanted] x \
353 + counts[art_Unsolicited] x, \
354 counts[art_Unchecked] x \
355 , counts[art_Wanted] x \
356 , counts[art_Unsolicited] x
359 #define RC_INDEX(x) RC_##x,
360 RESULT_COUNTS(RC_INDEX, RC_INDEX)
365 /*----- transmission buffers -----*/
370 xk_Malloc, xk_Const, xk_Artdata
382 /*----- core operational data structure types -----*/
385 /* This is also an instance of struct oop_readable */
386 struct oop_readable readable; /* first */
387 oop_readable_call *readable_callback;
388 void *readable_callback_user;
391 Filemon_Perfile *filemon;
394 long inprogress; /* no. of articles read but not processed */
398 int counts[art_MaxState][RCI_max];
399 int readcount_ok, readcount_blank, readcount_err;
414 #define SMS_LIST(X) \
422 enum StateMachineState {
423 #define SMS_DEF_ENUM(s) sm_##s,
424 SMS_LIST(SMS_DEF_ENUM)
427 static const char *sms_names[]= {
428 #define SMS_DEF_NAME(s) #s ,
429 SMS_LIST(SMS_DEF_NAME)
435 int fd, max_queue, stream, quitting;
436 ArticleList waiting; /* not yet told peer */
437 ArticleList priority; /* peer says send it now */
438 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
439 struct iovec xmit[CONNIOVS];
440 XmitDetails xmitd[CONNIOVS];
445 /*----- operational variables -----*/
447 static oop_source *loop;
449 static int until_connect;
450 static ConnList conns;
451 static ArticleList queue;
453 static char *path_lock, *path_flushing, *path_defer, *globpat_backlog;
455 #define SMS(newstate, periods, why) \
456 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
458 static StateMachineState sms;
460 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
461 static int sm_period_counter, until_backlog_nextscan;
463 static double accept_proportion;
464 static int nocheck, nocheck_reported;
466 /*========== logging ==========*/
468 #define VA va_list al; va_start(al,fmt)
469 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
470 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
472 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
473 static void logcore(int sysloglevel, const char *fmt, ...) {
476 vsyslog(sysloglevel,fmt,al);
478 vfprintf(stderr,fmt,al);
484 static void logv(int sysloglevel, const char *pfx, int errnoval,
485 const char *fmt, va_list al) PRINTF(5,0);
486 static void logv(int sysloglevel, const char *pfx, int errnoval,
487 const char *fmt, va_list al) {
488 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
489 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
490 msgbuf[sizeof(msgbuf)-1]= 0;
492 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
493 sysloglevel= LOG_ERR; /* run by wrong user, probably */
495 logcore(sysloglevel, "<%s>%s: %s%s%s",
496 sitename, pfx, msgbuf,
497 errnoval>=0 ? ": " : "",
498 errnoval>=0 ? strerror(errnoval) : "");
501 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
502 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
503 static void fn(const char *fmt, ...) { \
505 logv(sysloglevel, pfx, err, fmt, al); \
509 #define logwrap(fn, pfx, sysloglevel, err) \
510 static void fn(const char *fmt, ...) PRINTF(1,2); \
511 static void fn(const char *fmt, ...) { \
513 logv(sysloglevel, pfx, err, fmt, al); \
517 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
518 diewrap(die, " critical", LOG_CRIT, -1, 16);
520 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
521 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
523 logwrap(syswarn, " warning", LOG_WARNING, errno);
524 logwrap(warn, " warning", LOG_WARNING, -1);
526 logwrap(notice, "", LOG_NOTICE, -1);
527 logwrap(info, " info", LOG_INFO, -1);
528 logwrap(debug, " debug", LOG_DEBUG, -1);
531 /*========== utility functions etc. ==========*/
533 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
534 static char *xvasprintf(const char *fmt, va_list al) {
536 int rc= vasprintf(&str,fmt,al);
537 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
540 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
541 static char *xasprintf(const char *fmt, ...) {
543 char *str= xvasprintf(fmt,al);
548 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
550 static pid_t xfork(const char *what) {
554 if (child==-1) sysdie("cannot fork for %s",what);
555 if (!child) postfork(what);
556 debug("forked %s %ld", what, (unsigned long)child);
560 static void on_fd_read_except(int fd, oop_call_fd callback) {
561 loop->on_fd(loop, fd, OOP_READ, callback, 0);
562 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
564 static void cancel_fd_read_except(int fd) {
565 loop->cancel_fd(loop, fd, OOP_READ);
566 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
569 static void report_child_status(const char *what, int status) {
570 if (WIFEXITED(status)) {
571 int es= WEXITSTATUS(status);
573 warn("%s: child died with error exit status %d",es);
574 } else if (WIFSIGNALED(status)) {
575 int sig= WTERMSIG(status);
576 const char *sigstr= strsignal(sig);
577 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
579 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
581 warn("%s: child died due to unknown fatal signal %d%s",
582 what, sig, coredump);
584 warn("%s: child died with unknown wait status %d", status);
588 static int xwaitpid(pid_t *pid, const char *what) {
591 int r= kill(*pid, SIGKILL);
592 if (r) sysdie("cannot kill %s child", what);
594 pid_t got= waitpid(*pid, &status, WNOHANG);
595 if (got==-1) sysdie("cannot reap %s child", what);
602 static void xunlink(const char *path, const char *what) {
604 if (r) sysdie("can't unlink %s %s", path, what);
607 static time_t xtime(void) {
609 if (now==-1) sysdie("time(2) failed");
612 static void check_isreg(const struct stat *stab, const char *path,
614 if (!S_ISREG(stab->st_mode))
615 die("%s %s not a plain file (mode 0%lo)",
616 what, path, (unsigned long)stab->st_mode);
619 static void xfstat(int fd, struct stat *stab_r, const char *what) {
620 int r= fstat(fd, stab_r);
621 if (r) sysdie("could not fstat %s", what);
624 static void xfstat_isreg(int fd, struct stat *stab_r,
625 const char *path, const char *what) {
626 xfstat(fd, stab_r, what);
627 check_isreg(stab_r, path, what);
630 static void xlstat_isreg(const char *path, struct stat *stab,
631 int *enoent_r /* 0 means ENOENT is fatal */,
633 int r= lstat(path, stab);
635 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
636 sysdie("could not lstat %s %s", what, path);
638 if (enoent_r) *enoent_r= 0;
639 check_isreg(stab, path, what);
642 static void setnonblock(int fd, int nonblocking) {
643 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
644 if (nonblocking) r |= O_NONBLOCK;
645 else r &= ~O_NONBLOCK;
646 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
649 static int samefile(const struct stat *a, const struct stat *b) {
650 assert(S_ISREG(a->st_mode));
651 assert(S_ISREG(b->st_mode));
652 return (a->st_ino == b->st_ino &&
653 a->st_dev == b->st_dev);
656 static char *sanitise(const char *input) {
657 static char sanibuf[100]; /* returns pointer to this buffer! */
659 const char *p= input;
663 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
665 if (!c) { *q++= '\''; *q=0; break; }
666 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
667 sprintf(q,"\\x%02x",c);
673 /*========== making new connections ==========*/
675 static void conn_dispose(Conn *conn) {
677 perhaps_close(&conn->fd);
679 until_connect= reconnect_delay_periods;
682 static int connecting_sockets[2]= {-1,-1};
683 static pid_t connecting_child;
685 static void connect_attempt_discard(void) {
686 if (connecting_sockets[0])
687 cancel_fd_read_except(connecting_sockets[0]);
689 perhaps_close(&connecting_sockets[0]);
690 perhaps_close(&connecting_sockets[1]);
692 if (connecting_child) {
693 int r= kill(connecting_child, SIGTERM);
694 if (r) syswarn("failed to kill connecting child");
695 int status= xwaitpid(&connecting_child, "connect");
697 if (!(WIFEXITED(status) ||
698 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
699 report_child_status("connect", status);
703 #define PREP_DECL_MSG_CMSG(msg) \
705 memset(&msg,0,sizeof(msg)); \
706 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
707 msg.msg_control= msg##cbuf; \
708 msg.msg_controllen= sizeof(msg##cbuf);
710 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
713 conn= xmalloc(sizeof(*conn));
714 memset(conn,0,sizeof(*conn));
716 PREP_DECL_MSG_CMSG(msg);
717 struct cmsghdr *h= 0;
718 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
719 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
722 pid_t got= waitpid(connecting_child, &status, WNOHANG);
724 assert(got==connecting_child);
726 if (WIFEXITED(status) &&
727 (WEXITSTATUS(status) != 0 &&
728 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
729 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
730 /* child already reported the problem */
731 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
732 warn("connect: connection attempt timed out");
733 } else if (!WIFEXITED(status)) {
734 report_child_status("connect", status);
735 /* that's probably the root cause then */
738 /* child is still running apparently, report the socket problem */
740 syswarn("connect: read from child socket failed");
741 else if (e == OOP_EXCEPTION)
742 warn("connect: unexpected exception on child socket");
744 warn("connect: unexpected EOF on child socket");
749 #define CHK(field, val) \
750 if (h->cmsg_##field != val) { \
751 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
754 CHK(level, SOL_SOCKET);
755 CHK(type, SCM_RIGHTS);
756 CHK(len, CMSG_LEN(sizeof(conn->fd)));
759 if (CMSG_NXTHDR(&msg,h)) { die("connect: child sent many cmsgs"); goto x; }
761 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
764 pid_t got= waitpid(connecting_child, &status, 0);
765 if (got==-1) sysdie("connect: real wait for child");
766 assert(got == connecting_child);
769 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
770 int es= WEXITSTATUS(status);
772 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
773 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
775 fatal("connect: child gave unexpected exit status %d", es);
779 setnonblock(conn->fd, 1);
780 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
781 LIST_ADDHEAD(conns, conn);
782 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
783 connect_attempt_discard();
784 check_master_queue();
789 connect_attempt_discard();
792 static int allow_connect_start(void) {
793 return conns.count < max_connections
798 static void connect_start(void) {
799 assert(!connecting_sockets[0]);
800 assert(!connecting_sockets[1]);
801 assert(!connecting_child);
803 notice("starting connection attempt");
805 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
806 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
808 connecting_child= xfork("connection");
810 if (!connecting_child) {
811 FILE *cn_from, *cn_to;
812 char buf[NNTP_STRLEN+100];
813 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
815 r= close(connecting_sockets[0]);
816 if (r) sysdie("connect: close parent socket in child");
818 alarm(connection_setup_timeout);
819 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
820 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
821 else sysfatal("connect: connection attempt failed");
823 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
824 sysfatal("connect: authentication failed");
826 if (fputs("MODE STREAM\r\n", cn_to) ||
828 sysfatal("connect: could not send MODE STREAM");
829 buf[sizeof(buf)-1]= 0;
830 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
832 sysfatal("connect: could not read response to MODE STREAM");
834 fatal("connect: connection close in response to MODE STREAM");
839 fatal("connect: response to MODE STREAM is too long: %.100s...",
840 remote_host, sanitise(buf));
841 l--; if (l>0 && buf[l-1]=='\r') l--;
844 int rcode= strtoul(buf,&ep,10);
846 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
850 exitstatus= CONNCHILD_ESTATUS_STREAM;
856 warn("connect: unexpected response to MODE STREAM: %.50s",
862 int fd= fileno(cn_from);
864 PREP_DECL_MSG_CMSG(msg);
865 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
866 cmsg->cmsg_level= SOL_SOCKET;
867 cmsg->cmsg_type= SCM_RIGHTS;
868 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
869 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
871 msg.msg_controllen= cmsg->cmsg_len;
872 r= sendmsg(connecting_sockets[1], &msg, 0);
873 if (r) sysdie("sendmsg failed for new connection");
878 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
879 if (r) sysdie("connect: close child socket in parent");
881 on_fd_read_except(connecting_sockets[0], connchild_event);
885 connect_attempt_discard();
889 /*========== overall control of article flow ==========*/
891 static void check_master_queue(void) {
899 /* Find a connection to offer this article. We prefer a busy
900 * connection to an idle one, provided it's not full. We take the
901 * first (oldest) and since that's stable, it will mean we fill up
902 * connections in order. That way if we have too many
903 * connections, the spare ones will go away eventually.
905 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
906 int inqueue= walk->sent.count + walk->priority.count
907 + walk->waiting.count;
908 spare= walk->max_queue - inqueue;
909 assert(inqueue <= max_queue_per_conn);
911 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
912 else if (spare>0) /*working*/ { use= walk; break; }
916 Article *art= LIST_REMHEAD(queue);
917 LIST_ADDTAIL(use->waiting, art);
920 conn_maybe_write(use);
921 } else if (allow_connect_start()) {
922 until_connect= reconnect_delay_periods;
931 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
936 static void conn_maybe_write(Conn *conn) {
939 conn_make_some_xmits(conn);
941 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
945 void *rp= conn_write_some_xmits(conn);
946 if (rp==OOP_CONTINUE) {
947 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
949 } else if (rp==OOP_HALT) {
952 /* transmitted everything */
959 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
960 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
961 int requeue[art_MaxState];
964 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
965 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
966 while ((art= LIST_REMHEAD(conn->sent))) {
967 requeue[art->state]++;
968 if (art->state==art_Unsolicited) art->state= art_Unchecked;
969 LIST_ADDTAIL(queue,art);
974 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
977 char *m= xvasprintf(fmt,al);
978 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
979 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
982 LIST_REMOVE(conns,conn);
984 check_master_queue();
987 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
988 static void connfail(Conn *conn, const char *fmt, ...) {
991 vconnfail(conn,fmt,al);
995 /*========== article transmission ==========*/
997 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
998 XmitKind kind) { /* caller must then fill in details */
999 struct iovec *v= &conn->xmit[conn->xmitu];
1000 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1001 v->iov_base= (char*)data;
1007 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1008 xmit_core(conn,data,len, xk_Const);
1010 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1012 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1013 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1017 static void xmit_free(XmitDetails *d) {
1019 case xk_Malloc: free(d->info.malloc_tofree); break;
1020 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1021 case xk_Const: break;
1026 static void *conn_write_some_xmits(Conn *conn) {
1028 * 0: nothing more to write, no need to call us again
1029 * OOP_CONTINUE: more to write but fd not writeable
1030 * OOP_HALT: disaster, have destroyed conn
1033 int count= conn->xmitu;
1034 if (!count) return 0;
1036 if (count > IOV_MAX) count= IOV_MAX;
1037 ssize_t rs= writev(conn->fd, conn->xmit, count);
1039 if (errno == EAGAIN) return OOP_CONTINUE;
1040 connfail(conn, "write failed: %s", strerror(errno));
1046 for (done=0; rs && done<conn->xmitu; done++) {
1047 struct iovec *vp= &conn->xmit[done];
1048 XmitDetails *dp= &conn->xmitd[done];
1049 if (rs > vp->iov_len) {
1057 int newu= conn->xmitu - done;
1058 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1059 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1064 static void conn_make_some_xmits(Conn *conn) {
1066 if (conn->xmitu+5 > CONNIOVS)
1069 Article *art= LIST_REMHEAD(conn->priority);
1070 if (!art) art= LIST_REMHEAD(conn->waiting);
1073 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1074 /* actually send it */
1076 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1080 XMIT_LITERAL("TAKETHIS ");
1081 xmit_noalloc(conn, art->messageid, art->midlen);
1082 XMIT_LITERAL("\r\n");
1083 xmit_artbody(conn, artdata);
1086 /* we got 235 from IHAVE */
1088 xmit_artbody(conn, artdata);
1090 XMIT_LITERAL(".\r\n");
1095 art->state == art_Unchecked ? art_Unsolicited :
1096 art->state == art_Wanted ? art_Wanted :
1098 art->ipf->counts[art->state][RC_sent]++;
1099 LIST_ADDTAIL(conn->sent, art);
1105 XMIT_LITERAL("IHAVE ");
1107 XMIT_LITERAL("CHECK ");
1108 xmit_noalloc(conn, art->messageid, art->midlen);
1109 XMIT_LITERAL("\r\n");
1111 assert(art->state == art_Unchecked);
1112 art->ipf->counts[art->state][RC_sent]++;
1113 LIST_ADDTAIL(conn->sent, art);
1119 /*========== handling responses from peer ==========*/
1121 static const oop_rd_style peer_rd_style= {
1122 OOP_RD_DELIM_STRIP, '\n',
1124 OOP_RD_SHORTREC_FORBID
1127 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1128 const char *errmsg, int errnoval,
1129 const char *data, size_t recsz, void *conn_v) {
1131 connfail(conn, "error receiving from peer: %s", errmsg);
1132 return OOP_CONTINUE;
1135 static Article *article_reply_check(Conn *conn, const char *response,
1136 int code_indicates_streaming,
1138 /* 1:yes, -1:no, 0:dontcare */,
1139 const char *sanitised_response) {
1140 Article *art= LIST_HEAD(conn->sent);
1144 "peer gave unexpected response when no commands outstanding: %s",
1145 sanitised_response);
1149 if (code_indicates_streaming) {
1150 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1151 if (!conn->stream) {
1152 connfail(conn, "peer gave streaming response code "
1153 " to IHAVE or subsequent body: %s", sanitised_response);
1156 const char *got_mid= response+4;
1157 int got_midlen= strcspn(got_mid, " \n\r");
1158 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1159 connfail(conn, "peer gave streaming response with syntactically invalid"
1160 " messageid: %s", sanitised_response);
1163 if (got_midlen != art->midlen ||
1164 memcmp(got_mid, art->messageid, got_midlen)) {
1165 connfail(conn, "peer gave streaming response code to wrong article -"
1166 " probable synchronisation problem; we offered: %s;"
1168 art->messageid, sanitised_response);
1173 connfail(conn, "peer gave non-streaming response code to"
1174 " CHECK/TAKETHIS: %s", sanitised_response);
1179 if (must_have_sent>0 && art->state < art_Wanted) {
1180 connfail(conn, "peer says article accepted but"
1181 " we had not sent the body: %s", sanitised_response);
1184 if (must_have_sent<0 && art->state >= art_Wanted) {
1185 connfail(conn, "peer says please sent the article but we just did: %s",
1186 sanitised_response);
1190 Article *art_again= LIST_REMHEAD(conn->sent);
1191 assert(art_again == art);
1195 static void update_nocheck(int accepted) {
1196 accept_proportion *= nocheck_decay;
1197 accept_proportion += accepted * (1.0 - nocheck_decay);
1198 int new_nocheck= accept_proportion >= nocheck_thresh;
1199 if (new_nocheck && !nocheck_reported) {
1200 notice("entering nocheck mode for the first time");
1201 nocheck_reported= 1;
1202 } else if (new_nocheck != nocheck) {
1203 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1205 nocheck= new_nocheck;
1208 static void article_done(Conn *conn, Article *art, int whichcount) {
1209 art->ipf->counts[art->state][whichcount]++;
1210 if (whichcount == RC_accepted) update_nocheck(1);
1211 else if (whichcount == RC_unwanted) update_nocheck(0);
1213 InputFile *ipf= art->ipf;
1214 while (art->blanklen) {
1215 static const char spaces[]=
1220 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1221 int r= pwrite(ipf->fd, spaces, w, art->offset);
1223 if (errno==EINTR) continue;
1224 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1225 art->messageid, art->blanklen, art->offset, ipf->path);
1227 assert(r>=0 && r<=w);
1233 assert(ipf->inprogress >= 0);
1235 if (!ipf->inprogress && ipf != main_input_file)
1236 queue_check_input_done();
1241 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1242 const char *errmsg, int errnoval,
1243 const char *data, size_t recsz, void *conn_v) {
1246 if (ev == OOP_RD_EOF) {
1247 connfail(conn, "unexpected EOF from peer");
1248 return OOP_CONTINUE;
1250 assert(ev == OOP_RD_OK);
1252 char *sani= sanitise(data);
1255 unsigned long code= strtoul(data, &ep, 10);
1256 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1257 connfail(conn, "badly formatted response from peer: %s", sani);
1258 return OOP_CONTINUE;
1261 if (conn->quitting) {
1262 if (code!=205 && code!=503) {
1263 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1265 notice("C%d idle connection closed\n");
1266 assert(!conn->waiting.count);
1267 assert(!conn->priority.count);
1268 assert(!conn->sent.count);
1269 assert(!conn->xmitu);
1270 LIST_REMOVE(conns,conn);
1273 return OOP_CONTINUE;
1278 #define GET_ARTICLE(musthavesent) \
1279 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1280 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1282 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1283 code_streaming= (streaming); \
1284 GET_ARTICLE(musthavesent); \
1285 article_done(conn, art, RC_##how); break;
1287 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1289 int code_streaming= 0;
1293 case 400: PEERBADMSG("peer stopped accepting articles");
1294 case 503: PEERBADMSG("peer timed us out");
1295 default: PEERBADMSG("peer sent unexpected message");
1297 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1298 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1300 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1301 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1303 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1304 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1306 case 238: /* CHECK says send it */
1308 case 335: /* IHAVE says send it */
1310 assert(art->state == art_Unchecked);
1311 art->ipf->counts[art->state][RC_accepted]++;
1312 art->state= art_Wanted;
1313 LIST_ADDTAIL(conn->priority, art);
1316 case 431: /* CHECK or TAKETHIS says try later */
1318 case 436: /* IHAVE says try later */
1321 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1323 sysfatal("write to defer file %s",path_defer);
1324 article_done(conn, art, RC_deferred);
1329 conn_maybe_write(conn);
1330 check_master_queue();
1331 return OOP_CONTINUE;
1335 /*========== monitoring of input files ==========*/
1337 static void feedfile_eof(InputFile *ipf) {
1338 assert(ipf != main_input_file); /* promised by tailing_try_read */
1340 inputfile_tailing_stop(ipf);
1341 assert(ipf->fd >= 0);
1342 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1345 if (ipf == flushing_input_file) {
1346 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1347 if (main_input_file) inputfile_tailing_start(main_input_file);
1348 statemc_check_flushing_done();
1349 } else if (ipf == backlog_input_file) {
1350 statemc_check_backlog_done();
1352 abort(); /* supposed to wait rather than get EOF on main input file */
1356 static InputFile *open_input_file(const char *path) {
1357 int fd= open(path, O_RDONLY);
1359 if (errno==ENOENT) return 0;
1360 sysfatal("unable to open input file %s", path);
1363 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1364 memset(ipf,0,sizeof(*ipf));
1367 strcpy(ipf->path, path);
1372 static void close_input_file(InputFile *ipf) {
1373 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1374 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1375 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1376 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1379 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1383 /*---------- dealing with articles read in the input file ----------*/
1385 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1386 const char *data, const char *how) {
1387 warn("corrupted file: %s, offset %lu: %s: %s",
1388 ipf->path, (unsigned long)offset, how, sanitise(data));
1389 ipf->readcount_err++;
1390 if (ipf->readcount_err > max_bad_data_initial +
1391 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1392 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1393 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1394 return OOP_CONTINUE;
1397 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1398 oop_rd_event ev, const char *errmsg,
1399 int errnoval, const char *data, size_t recsz,
1401 InputFile *ipf= ipf_v;
1402 assert(ev == OOP_RD_SYSTEM);
1404 sysdie("error reading input file: %s, offset %lu",
1405 ipf->path, (unsigned long)ipf->offset);
1408 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1409 oop_rd_event ev, const char *errmsg,
1410 int errnoval, const char *data, size_t recsz,
1412 InputFile *ipf= ipf_v;
1414 char tokentextbuf[sizeof(TOKEN)*2+3];
1416 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1418 off_t old_offset= ipf->offset;
1419 ipf->offset += recsz + 1;
1421 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1423 if (ev==OOP_RD_PARTREC)
1424 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1425 /* but process it anyway */
1427 if (ipf->skippinglong) {
1428 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1431 if (ev==OOP_RD_LONG) {
1432 ipf->skippinglong= 1;
1433 X_BAD_DATA("overly long line");
1436 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1437 if (!recsz) X_BAD_DATA("empty line");
1440 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1441 ipf->readcount_blank++;
1442 return OOP_CONTINUE;
1445 char *space= strchr(data,' ');
1446 int tokenlen= space-data;
1447 int midlen= (int)recsz-tokenlen-1;
1448 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1449 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1451 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1452 memcpy(tokentextbuf, data, tokenlen);
1453 tokentextbuf[tokenlen]= 0;
1454 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1456 ipf->readcount_ok++;
1458 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1459 art->offset= ipf->offset;
1460 art->blanklen= recsz;
1461 art->midlen= midlen;
1462 art->state= art_Unchecked;
1463 art->ipf= ipf; ipf->inprogress++;
1464 art->token= TextToToken(tokentextbuf);
1465 strcpy(art->messageid, space+1);
1466 LIST_ADDTAIL(queue, art);
1468 if (sms==sm_NORMAL && ipf==main_input_file &&
1469 ipf->offset >= target_max_feedfile_size)
1470 statemc_start_flush("feed file size");
1472 check_master_queue();
1473 return OOP_CONTINUE;
1476 /*========== tailing input file ==========*/
1478 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1480 InputFile *ipf= user;
1481 return ipf->readable_callback(loop, &ipf->readable,
1482 ipf->readable_callback_user);
1485 static void tailing_on_cancel(struct oop_readable *rable) {
1486 InputFile *ipf= (void*)rable;
1488 if (ipf->filemon) filemon_stop(ipf);
1489 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1490 ipf->readable_callback= 0;
1493 static void tailing_queue_readable(InputFile *ipf) {
1494 /* lifetime of ipf here is OK because destruction will cause
1495 * on_cancel which will cancel this callback */
1496 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1499 static int tailing_on_readable(struct oop_readable *rable,
1500 oop_readable_call *cb, void *user) {
1501 InputFile *ipf= (void*)rable;
1503 tailing_on_cancel(rable);
1504 ipf->readable_callback= cb;
1505 ipf->readable_callback_user= user;
1508 tailing_queue_readable(ipf);
1512 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1514 InputFile *ipf= (void*)rable;
1516 ssize_t r= read(ipf->fd, buffer, length);
1518 if (errno==EINTR) continue;
1522 if (ipf==main_input_file) {
1525 } else if (ipf==flushing_input_file) {
1527 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1528 } else if (ipf==backlog_input_file) {
1538 /*---------- filemon implemented with inotify ----------*/
1540 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1541 #define HAVE_FILEMON
1543 #include <linux/inotify.h>
1545 static int filemon_inotify_fd;
1546 static int filemon_inotify_wdmax;
1547 static InputFile **filemon_inotify_wd2ipf;
1549 struct Filemon_Perfile {
1553 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1554 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1555 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1557 if (wd >= filemon_inotify_wdmax) {
1559 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1560 sizeof(*filemon_inotify_wd2ipf) * newmax);
1561 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1562 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1563 filemon_inotify_wdmax= newmax;
1566 assert(!filemon_inotify_wd2ipf[wd]);
1567 filemon_inotify_wd2ipf[wd]= ipf;
1569 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1570 ipf, wd, filemon_inotify_wdmax);
1575 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1577 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1578 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1579 if (r) sysdie("inotify_rm_watch");
1580 filemon_inotify_wd2ipf[wd]= 0;
1583 static void *filemon_inotify_readable(oop_source *lp, int fd,
1584 oop_event e, void *u) {
1585 struct inotify_event iev;
1587 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1589 if (errno==EAGAIN) break;
1590 sysdie("read from inotify master");
1591 } else if (r==sizeof(iev)) {
1592 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1594 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1596 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1597 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1598 filemon_callback(ipf);
1600 return OOP_CONTINUE;
1603 static int filemon_method_init(void) {
1604 filemon_inotify_fd= inotify_init();
1605 if (filemon_inotify_fd<0) {
1606 syswarn("could not initialise inotify: inotify_init failed");
1610 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1612 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1616 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1618 /*---------- filemon dummy implementation ----------*/
1620 #if !defined(HAVE_FILEMON)
1622 struct Filemon_Perfile { int dummy; };
1624 static int filemon_method_init(void) { return 0; }
1625 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1626 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1628 #endif /* !HAVE_FILEMON */
1630 /*---------- filemon generic interface ----------*/
1632 static void filemon_start(InputFile *ipf) {
1633 assert(!ipf->filemon);
1635 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1636 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1637 filemon_method_startfile(ipf, ipf->filemon);
1640 static void filemon_stop(InputFile *ipf) {
1641 if (!ipf->filemon) return;
1642 filemon_method_stopfile(ipf, ipf->filemon);
1647 static void filemon_callback(InputFile *ipf) {
1648 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1651 /*---------- interface to start and stop an input file ----------*/
1653 static const oop_rd_style feedfile_rdstyle= {
1654 OOP_RD_DELIM_STRIP, '\n',
1656 OOP_RD_SHORTREC_LONG,
1659 static void inputfile_tailing_start(InputFile *ipf) {
1661 ipf->readable.on_readable= tailing_on_readable;
1662 ipf->readable.on_cancel= tailing_on_cancel;
1663 ipf->readable.try_read= tailing_try_read;
1664 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1665 ipf->readable.delete_kill= 0;
1667 ipf->readable_callback= 0;
1668 ipf->readable_callback_user= 0;
1670 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1673 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1674 feedfile_got_article,ipf, feedfile_read_err, ipf);
1675 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1678 static void inputfile_tailing_stop(InputFile *ipf) {
1680 oop_rd_cancel(ipf->rd);
1681 oop_rd_delete(ipf->rd);
1683 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1687 /*========== interaction with innd - state machine ==========*/
1689 /* See official state diagram at top of file. We implement
1700 |`---------------------------------------------------.
1702 |`---------------- - - - |
1703 D ENOENT | D EXISTS see OVERALL STATES diagram |
1704 | for full startup logic |
1707 | ============ try to |
1713 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1714 ^ | hardlink F to D |
1717 | | our handle onto F is now onto D |
1720 | |<-------------------<---------------------<---------+
1722 | | spawn inndcomm flush |
1724 | ================== |
1725 | FLUSHING[-ABSENT] |
1727 | main D tail/none |
1728 | ================== |
1730 | | INNDCOMM FLUSH FAILS ^
1731 | |`----------------------->----------. |
1733 | | NO SUCH SITE V |
1734 ^ |`--------------->----. ==================== |
1735 | | \ FLUSHFAILED[-ABSENT] |
1737 | | FLUSH OK \ main D tail/none |
1738 | | open F \ ==================== |
1740 | | \ | TIME TO RETRY |
1741 | |`------->----. ,---<---'\ `----------------'
1742 | | D NONE | | D NONE `----.
1744 | ============= V V ============
1745 | SEPARATED-1 | | DROPPING-1
1746 | flsh->fd>=0 | | flsh->fd>=0
1747 | [Separated] | | [Dropping]
1748 | main F idle | | main none
1749 | old D tail | | old D tail
1750 | ============= | | ============
1752 ^ | EOF ON D | | defer | EOF ON D
1754 | =============== | | ===============
1755 | SEPARATED-2 | | DROPPING-2
1756 | flsh->fd==-1 | V flsh->fd==-1
1757 | [Finishing] | | [Dropping]
1758 | main F tail | `. main none
1759 | old D closed | `. old D closed
1760 | =============== V `. ===============
1762 | | ALL D PROCESSED `. | ALL D PROCESSED
1763 | V install defer as backlog `. | install defer
1764 ^ | close D `. | close D
1765 | | unlink D `. | unlink D
1768 `----------' ==============
1788 static void startup_set_input_file(InputFile *f) {
1789 assert(!main_input_file);
1791 inputfile_tailing_start(f);
1794 static void statemc_init(void) {
1795 struct stat stab, stabf;
1797 path_lock= xasprintf("%s_lock", feedfile);
1798 path_flushing= xasprintf("%s_flushing", feedfile);
1799 path_defer= xasprintf("%s_defer", feedfile);
1800 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1803 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1804 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1807 memset(&fl,0,sizeof(fl));
1809 fl.l_whence= SEEK_SET;
1810 int r= fcntl(lockfd, F_SETLK, &fl);
1812 if (errno==EACCES || errno==EAGAIN) {
1813 if (quiet_multiple) exit(0);
1814 fatal("another duct holds the lockfile");
1816 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1819 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
1821 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1823 if (!lock_noent && samefile(&stab, &stabf))
1827 sysdie("could not close stale lockfile %s", path_lock);
1829 debug("startup: locked");
1831 search_backlog_file();
1834 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1836 debug("startup: ductdefer ENOENT");
1838 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1839 switch (stab.st_nlink==1) {
1841 open_defer(); /* so that we will later close it and rename it */
1844 xunlink(path_defer, "stale defer file link"
1845 " (presumably hardlink to backlog file)");
1848 die("defer file %s has unexpected link count %d",
1849 path_defer, stab.st_nlink);
1853 struct stat stab_f, stab_d;
1856 InputFile *file_d= open_input_file(path_flushing);
1857 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
1859 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1861 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1862 debug("startup: F==D => Hardlinked");
1863 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1868 debug("startup: F ENOENT => Moved");
1869 if (file_d) startup_set_input_file(file_d);
1870 spawn_inndcomm_flush("feedfile missing at startup");
1871 /* => Flushing, sms:=FLUSHING */
1874 debug("startup: F!=D => Separated");
1875 startup_set_input_file(file_d);
1876 SMS(SEPARATED, 0, "found both old and current feed files");
1878 debug("startup: F exists, D ENOENT => Normal");
1879 InputFile *file_f= open_input_file(feedfile);
1880 if (!file_f) die("feed file vanished during startup");
1881 startup_set_input_file(file_f);
1882 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1887 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1888 assert(sms == sm_NORMAL);
1890 debug("starting flush (%s) (%lu >?= %lu) (%d)",
1892 (unsigned long)(main_input_file ? main_input_file->offset : 0),
1893 (unsigned long)target_max_feedfile_size,
1896 int r= link(feedfile, path_flushing);
1897 if (r) sysdie("link feedfile %s to flushing file %s",
1898 feedfile, path_flushing);
1901 xunlink(feedfile, "old feedfile link");
1904 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1907 static void statemc_period_poll(void) {
1908 if (!sm_period_counter) return;
1909 sm_period_counter--;
1910 assert(sm_period_counter>=0);
1912 if (sm_period_counter) return;
1915 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1917 case sm_FLUSHFAILED:
1918 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1925 static int inputfile_is_done(InputFile *ipf) {
1927 if (ipf->inprogress) return 0; /* new article in the meantime */
1928 if (ipf->fd >= 0); return 0; /* not had EOF */
1932 static void notice_processed(InputFile *ipf, const char *what,
1934 #define RCI_NOTHING(x) /* nothing */
1935 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
1936 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
1938 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
1940 info("processed %s%s read=%d(+%dbl,+%derr)"
1941 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
1942 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
1945 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
1946 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
1947 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
1948 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
1949 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
1950 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
1956 static void statemc_check_backlog_done(void) {
1957 InputFile *ipf= backlog_input_file;
1958 if (!inputfile_is_done(ipf)) return;
1960 const char *slash= strrchr(ipf->path, '/');
1961 const char *leaf= slash ? slash+1 : ipf->path;
1962 const char *under= strchr(slash, '_');
1963 const char *rest= under ? under+1 : leaf;
1964 if (!strncmp(rest,"backlog",7)) rest += 7;
1965 notice_processed(ipf,"backlog:",rest);
1967 close_input_file(ipf);
1968 if (unlink(ipf->path)) {
1969 if (errno != ENOENT)
1970 sysdie("could not unlink processed backlog file %s", ipf->path);
1971 warn("backlog file %s vanished while we were reading it"
1972 " so we couldn't remove it (but it's done now, anyway)",
1976 backlog_input_file= 0;
1977 search_backlog_file();
1981 static void statemc_check_flushing_done(void) {
1982 InputFile *ipf= flushing_input_file;
1983 if (!inputfile_is_done(ipf)) return;
1985 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1987 notice_processed(ipf,"feedfile",0);
1991 xunlink(path_flushing, "old flushing file");
1993 close_input_file(flushing_input_file);
1994 free(flushing_input_file);
1995 flushing_input_file= 0;
1997 if (sms==sm_SEPARATED) {
1998 notice("flush complete");
1999 SMS(NORMAL, 0, "flush complete");
2000 } else if (sms==sm_DROPPING) {
2001 SMS(DROPPED, 0, "old flush complete");
2002 search_backlog_file();
2003 notice("feed dropped, but will continue until backlog is finished");
2007 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2009 assert(!inputfile_is_done(main_input_file));
2010 statemc_check_flushing_done();
2011 statemc_check_backlog_done();
2012 return OOP_CONTINUE;
2015 static void queue_check_input_done(void) {
2016 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2019 static void statemc_setstate(StateMachineState newsms, int periods,
2020 const char *forlog, const char *why) {
2022 sm_period_counter= periods;
2024 const char *xtra= "";
2026 case sm_FLUSHING: sm_FLUSHFAILED:
2027 if (!main_input_file) xtra= "-ABSENT";
2029 case sm_SEPARATED: case sm_DROPPING:
2030 xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
2036 info("%s%s[%d] %s",forlog,xtra,periods,why);
2038 info("%s%s %s",forlog,xtra,why);
2042 /*---------- defer and backlog files ----------*/
2044 static void open_defer(void) {
2049 defer= fopen(path_defer, "a+");
2050 if (!defer) sysfatal("could not open defer file %s", path_defer);
2052 /* truncate away any half-written records */
2054 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2056 if (stab.st_size > LONG_MAX)
2057 die("defer file %s size is far too large", path_defer);
2062 long orgsize= stab.st_size;
2063 long truncto= stab.st_size;
2065 if (!truncto) break; /* was only (if anything) one half-truncated record */
2066 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2067 sysdie("seek in defer file %s while truncating partial", path_defer);
2072 sysdie("failed read from defer file %s", path_defer);
2074 die("defer file %s shrank while we were checking it!", path_defer);
2080 if (stab.st_size != truncto) {
2081 warn("truncating half-record at end of defer file %s -"
2082 " shrinking by %ld bytes from %ld to %ld",
2083 path_defer, orgsize - truncto, orgsize, truncto);
2086 sysfatal("could not flush defer file %s", path_defer);
2087 if (ftruncate(fileno(defer), truncto))
2088 sysdie("could not truncate defer file %s", path_defer);
2091 info("continuing existing defer file %s (%ld bytes)",
2092 path_defer, orgsize);
2094 if (fseek(defer, truncto, SEEK_SET))
2095 sysdie("could not seek to new end of defer file %s", path_defer);
2098 static void close_defer(void) {
2103 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2105 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2108 time_t now= xtime();
2110 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2112 (unsigned long)stab.st_ino);
2113 if (link(path_defer, backlog))
2114 sysfatal("could not install defer file %s as backlog file %s",
2115 path_defer, backlog);
2116 if (unlink(path_defer))
2117 sysdie("could not unlink old defer link %s to backlog file %s",
2118 path_defer, backlog);
2122 if (until_backlog_nextscan < 0 ||
2123 until_backlog_nextscan > backlog_retry_minperiods + 1)
2124 until_backlog_nextscan= backlog_retry_minperiods + 1;
2127 static void poll_backlog_file(void) {
2128 if (until_backlog_nextscan < 0) return;
2129 if (until_backlog_nextscan-- > 0) return;
2130 search_backlog_file();
2133 static void search_backlog_file(void) {
2134 /* returns non-0 iff there are any backlog files */
2139 const char *oldest_path=0;
2140 time_t oldest_mtime, now;
2142 if (backlog_input_file) return;
2146 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2150 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2152 die("out of memory expanding backlog pattern %s", globpat_backlog);
2154 for (i=0; i<gl.gl_pathc; i++) {
2155 const char *path= gl.gl_pathv[i];
2157 if (strchr(path,'#') || strchr(path,'~')) {
2158 debug("backlog file search skipping %s", path);
2161 r= stat(path, &stab);
2163 syswarn("failed to stat backlog file %s", path);
2166 if (!S_ISREG(stab.st_mode)) {
2167 warn("backlog file %s is not a plain file (or link to one)", path);
2170 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2172 oldest_mtime= stab.st_mtime;
2175 case GLOB_NOMATCH: /* fall through */
2178 sysdie("glob expansion of backlog pattern %s gave unexpected"
2179 " nonzero (error?) return value %d", globpat_backlog, r);
2185 debug("backlog scan: none");
2187 if (sms==sm_DROPPED) {
2188 notice("feed dropped and our work is complete");
2189 xunlink(path_lock, "lockfile for old feed");
2192 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2197 double age= difftime(now, oldest_mtime);
2198 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
2200 if (age_deficiency <= 0) {
2201 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2202 age, age_deficiency, oldest_path);
2204 backlog_input_file= open_input_file(oldest_path);
2205 if (!backlog_input_file) {
2206 warn("backlog file %s vanished as we opened it", backlog_input_file);
2209 inputfile_tailing_start(backlog_input_file);
2210 until_backlog_nextscan= -1;
2214 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
2216 if (backlog_spontaneous_rescan_periods >= 0 &&
2217 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2218 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2220 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2221 age, age_deficiency, until_backlog_nextscan, oldest_path);
2225 /*========== flushing the feed ==========*/
2227 static pid_t inndcomm_child;
2229 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2230 assert(inndcomm_child);
2231 int status= xwaitpid(&inndcomm_child, "inndcomm");
2232 cancel_fd_read_except(fd);
2235 assert(!flushing_input_file);
2237 if (WIFEXITED(status)) {
2238 switch (WEXITSTATUS(status)) {
2240 case INNDCOMMCHILD_ESTATUS_FAIL:
2243 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2244 warn("feed has been dropped by innd, finishing up");
2245 flushing_input_file= main_input_file;
2246 tailing_queue_readable(flushing_input_file);
2247 /* we probably previously returned EAGAIN from our fake read method
2248 * when in fact we were at EOF, so signal another readable event
2249 * so we actually see the EOF */
2253 if (flushing_input_file) {
2254 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2257 SMS(DROPPED, 0, "feed dropped by innd");
2258 search_backlog_file();
2260 return OOP_CONTINUE;
2264 flushing_input_file= main_input_file;
2265 tailing_queue_readable(flushing_input_file);
2267 main_input_file= open_input_file(feedfile);
2268 if (!main_input_file)
2269 die("flush succeeded but feedfile %s does not exist!", feedfile);
2271 if (flushing_input_file) {
2272 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2275 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2277 return OOP_CONTINUE;
2280 goto unexpected_exitstatus;
2283 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2284 warn("flush timed out trying to talk to innd");
2287 unexpected_exitstatus:
2288 report_child_status("inndcomm child", status);
2292 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2295 static void inndcommfail(const char *what) {
2296 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2297 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2300 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2303 notice("flushing %s",why);
2305 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2306 assert(!inndcomm_child);
2308 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2310 inndcomm_child= xfork("inndcomm child");
2312 if (!inndcomm_child) {
2313 const char *flushargv[2]= { sitename, 0 };
2319 alarm(inndcomm_flush_timeout);
2320 r= ICCopen(); if (r) inndcommfail("connect");
2321 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2322 if (!r) exit(0); /* yay! */
2324 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2325 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2326 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2330 int sentinel_fd= pipefds[0];
2331 on_fd_read_except(sentinel_fd, inndcomm_event);
2333 SMS(FLUSHING, 0, why);
2336 /*========== main program ==========*/
2338 static void postfork_inputfile(InputFile *ipf) {
2340 assert(ipf->fd >= 0);
2345 static void postfork_stdio(FILE *f) {
2346 /* we have no stdio streams that are buffered long-term */
2350 static void postfork(const char *what) {
2351 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2352 sysdie("%s child: failed to reset SIGPIPE");
2354 postfork_inputfile(main_input_file);
2355 postfork_inputfile(flushing_input_file);
2358 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2361 postfork_stdio(defer);
2364 #define EVERY(what, interval_sec, interval_usec, body) \
2365 static const struct timeval what##_timeout = \
2366 { interval_sec, interval_usec }; \
2367 static void what##_schedule(void); \
2368 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2370 what##_schedule(); \
2372 static void what##_schedule(void) { \
2373 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2376 EVERY(filepoll, 5,0, {
2377 if (main_input_file && main_input_file->readable_callback)
2378 filemon_callback(main_input_file);
2381 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s"
2382 #define DEBUG_IPF(wh) \
2383 wh##_input_file, debug_ipf_path(wh##_input_file), \
2384 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2385 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2386 static const char *debug_ipf_path(InputFile *ipf) {
2387 char *slash= strrchr(ipf->path,'/');
2388 return slash ? slash+1 : ipf->path;
2391 EVERY(period, PERIOD_SECONDS,0, {
2393 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2394 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_IPF(flushing)
2395 " children connecting=%ld inndcomm_child"
2397 sms_names[sms], sm_period_counter,
2398 queue.count, conns.count, until_connect,
2399 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2400 (long)connecting_child, (long)inndcomm_child
2403 if (until_connect) until_connect--;
2405 poll_backlog_file();
2406 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2407 statemc_period_poll();
2408 check_master_queue();
2412 /*========== option parsing ==========*/
2414 /*---------- generic option parser and logging ----------*/
2416 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2417 static void vbadusage(const char *fmt, va_list al) {
2420 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2421 static void badusage(const char *fmt, ...) {
2428 of_seconds= 001000u,
2429 of_boolean= 002000u,
2432 typedef struct Option Option;
2433 typedef void OptionParser(const Option*, const char *val);
2443 /*---------- specific option types ----------*/
2445 static void op_integer(const Option *o, const char *val) {
2448 unsigned long ul= strtoul(val,&ep,10);
2449 if (*ep || ep==val || errno || ul>INT_MAX)
2450 badusage("bad integer value for %s",o->lng);
2451 int *store= o->store;
2455 static void op_double(const Option *o, const char *val) {
2456 int *store= o->store;
2459 *store= strtod(val, &ep);
2460 if (*ep || ep==val || errno)
2461 badusage("bad floating point value for %s",o->lng);
2464 static void op_string(const Option *o, const char *val) {
2465 const char **store= o->store;
2469 static void op_seconds(const Option *o, const char *val) {
2470 int *store= o->store;
2474 double v= strtod(val,&ep);
2475 if (ep==val) badusage("bad time/duration value for %s",o->lng);
2477 if (!*ep || !strcmp(ep,"s")) unit= 1;
2478 else if (!strcmp(ep,"m")) unit= 60;
2479 else if (!strcmp(ep,"h")) unit= 3600;
2480 else if (!strcmp(ep,"d")) unit= 86400;
2481 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2485 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2489 static void op_periods_rndup(const Option *o, const char *val) {
2490 int *store= o->store;
2492 *store += PERIOD_SECONDS-1;
2493 *store /= PERIOD_SECONDS;
2496 static void op_setint(const Option *o, const char *val) {
2497 int *store= o->store;
2501 /*---------- specific options ----------*/
2503 static const Option options[]= {
2504 {'f',"feedfile", &feedfile, op_string },
2505 {'q',"quiet-multiple", &quiet_multiple, op_setint, 1,1 },
2507 { 0, "max-connections", &max_connections, op_integer },
2508 { 0, "max-queue-per-conn", &max_queue_per_conn, op_integer },
2511 { 0, "streaming", &try_stream, op_setint, 1,1 },
2512 { 0, "no-streaming", &try_stream, op_setint, 1,0 },
2513 {'P',"port", &port, op_integer },
2514 { 0, "inndconf", &inndconffile, op_string },
2515 {'d',"daemon", &become_daemon, op_setint, 1,1 },
2516 { 0, "no-daemon", &become_daemon, op_setint, 1,0 },
2518 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2519 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2521 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2522 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2523 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2526 int main(int argc, char **argv) {
2532 if (*arg != '-') break;
2533 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2535 while ((a= *++arg)) {
2539 char *equals= strchr(arg,'=');
2540 int len= equals ? (equals - arg) : strlen(arg);
2541 for (o=options; o->lng; o++)
2542 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2544 badusage("unknown long option --%s",arg);
2547 if (equals) badusage("option --%s does not take a value",o->lng);
2549 } else if (equals) {
2553 if (!arg) badusage("option --%s needs a value",o->lng);
2556 break; /* eaten the whole argument now */
2558 for (o=options; o->lng; o++)
2561 badusage("unknown short option -%c",a);
2568 if (!arg) badusage("option -%c needs a value",o->shrt);
2571 break; /* eaten the whole argument now */
2576 if (!arg) badusage("need site name argument");
2582 if (*++argv) badusage("too many non-option arguments");
2584 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2585 badusage("nocheck threshold percentage must be between 0..100");
2586 nocheck_thresh= nocheck_thresh_pct * 0.01;
2588 if (nocheck_decay_articles < 0.1)
2589 badusage("nocheck decay articles must be at least 0.1");
2590 nocheck_decay= 1 - 1/nocheck_decay_articles;
2593 pathoutgoing= innconf->pathoutgoing;
2594 innconf_read(inndconffile);
2597 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2598 else if (!feedfile[0])
2599 badusage("feed filename must be nonempty");
2600 else if (feedfile[strlen(feedfile)-1]=='/')
2601 feedfile= xasprintf("%s%s",feedfile,sitename);
2603 const char *feedfile_forbidden= "?*[~#";
2605 while ((c= *feedfile_forbidden++))
2606 if (strchr(feedfile, c))
2607 badusage("feed filename may not contain metacharacter %c",c);
2609 oop_source_sys *sysloop= oop_sys_new();
2610 if (!sysloop) sysdie("could not create liboop event loop");
2611 loop= (oop_source*)sysloop;
2613 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2614 sysdie("could not ignore SIGPIPE");
2616 if (become_daemon) {
2618 for (i=3; i<255; i++)
2619 /* do this now before we open syslog, etc. */
2621 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2623 int null= open("/dev/null",O_RDWR);
2624 if (null<0) sysdie("failed to open /dev/null");
2630 pid_t child1= xfork("daemonise first fork");
2631 if (child1) _exit(0);
2633 pid_t sid= setsid();
2634 if (sid != child1) sysdie("setsid failed");
2636 pid_t child2= xfork("daemonise second fork");
2637 if (child2) _exit(0);
2642 if (!filemon_method_init()) {
2643 warn("no file monitoring available, polling");
2644 filepoll_schedule();
2651 void *r= oop_sys_run(sysloop);
2652 assert(r == OOP_ERROR);
2653 sysdie("event loop failed");