3 * - make period size a tuneable
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 ==============================*/
163 #define _GNU_SOURCE 1
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 #define VA va_list al; va_start(al,fmt)
209 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
210 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
212 /*----- doubly linked lists -----*/
214 #define ISNODE(T) struct { T *succ, *pred; } node /* must be at start */
215 #define DEFLIST(T) typedef struct { T *hd, *tl, *tp; int count; } T##List
217 #define NODE(n) (assert((void*)&(n)->node == &(n)), \
218 (struct node*)&(n)->node)
220 #define LIST_CHECKCANHAVENODE(l,n) \
221 ((void)((n) == ((l).hd))) /* just for the type check */
223 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
224 ( LIST_CHECKCANHAVENODE(l,n), \
225 list_addsomehow((struct list*)&(l), NODE((n))), \
229 #define LIST_REMSOMEHOW(l,list_remsomehow) \
233 list_remsomehow((struct list*)&(l)) ) \
239 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
240 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
241 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
242 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
244 #define LIST_HEAD(l) ((typeof((l).hd))(list_head((struct list*)&(l))))
245 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
246 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
248 #define LIST_REMOVE(l,n) \
249 ( LIST_CHECKCANHAVENODE(l,n), \
250 list_remove(NODE((n))), \
254 #define LIST_INSERT(l,n,pred) \
255 ( LIST_CHECKCANHAVENODE(l,n), \
256 LIST_CHECKCANHAVENODE(l,pred), \
257 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
261 /*----- type predeclarations -----*/
263 typedef struct Conn Conn;
264 typedef struct Article Article;
265 typedef struct InputFile InputFile;
266 typedef struct XmitDetails XmitDetails;
267 typedef struct Filemon_Perfile Filemon_Perfile;
268 typedef enum StateMachineState StateMachineState;
273 /*----- function predeclarations -----*/
275 static void conn_maybe_write(Conn *conn);
276 static void conn_make_some_xmits(Conn *conn);
277 static void *conn_write_some_xmits(Conn *conn);
279 static void xmit_free(XmitDetails *d);
281 static void statemc_setstate(StateMachineState newsms, int periods,
282 const char *forlog, const char *why);
283 static void statemc_start_flush(const char *why); /* Normal => Flushing */
284 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
286 static void check_master_queue(void);
287 static void queue_check_input_done(void);
289 static void statemc_check_flushing_done(void);
290 static void statemc_check_backlog_done(void);
292 static void postfork(const char *what);
293 static void postfork_inputfile(InputFile *ipf);
295 static void open_defer(void);
296 static void close_defer(void);
297 static void search_backlog_file(void);
299 static void inputfile_tailing_start(InputFile *ipf);
300 static void inputfile_tailing_stop(InputFile *ipf);
302 static int filemon_init(void);
303 static void filemon_start(InputFile *ipf);
304 static void filemon_stop(InputFile *ipf);
305 static void filemon_callback(InputFile *ipf);
307 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
308 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
310 /*----- configuration options -----*/
312 static const char *sitename, *feedfile, *pathoutgoing;
313 static const char *remote_host;
314 static int quiet_multiple=0, become_daemon=1;
316 static int max_connections=10, max_queue_per_conn=200;
317 static int target_max_feedfile_size=100000;
319 static double max_bad_data_ratio= 0.01;
320 static int max_bad_data_initial= 30;
321 /* in one corrupt 4096-byte block the number of newlines has
322 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
324 static int connection_setup_timeout=200, port=119, try_stream=1;
325 static int inndcomm_flush_timeout=100;
326 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
327 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
328 static int spontaneous_flush_periods, need_activity_periods;
329 static const char *inndconffile;
331 static double nocheck_thresh_pct= 95.0;
332 static double nocheck_thresh; /* computed in main from _pct */
333 static double nocheck_decay_articles= 100; /* converted to _decay */
334 static double nocheck_decay; /* computed in main from _articles */
337 /*----- statistics -----*/
339 typedef enum { /* in queue in conn->sent */
340 art_Unchecked, /* not checked, not sent checking */
341 art_Wanted, /* checked, wanted sent body as requested */
342 art_Unsolicited, /* - sent body without check */
346 #define RESULT_COUNTS(RCS,RCN) \
354 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
355 #define RCI_TRIPLE_VALS_BASE(counts,x) \
356 counts[art_Unchecked] x \
357 + counts[art_Wanted] x \
358 + counts[art_Unsolicited] x, \
359 counts[art_Unchecked] x \
360 , counts[art_Wanted] x \
361 , counts[art_Unsolicited] x
364 #define RC_INDEX(x) RC_##x,
365 RESULT_COUNTS(RC_INDEX, RC_INDEX)
370 /*----- transmission buffers -----*/
375 xk_Malloc, xk_Const, xk_Artdata
387 /*----- core operational data structure types -----*/
390 /* This is also an instance of struct oop_readable */
391 struct oop_readable readable; /* first */
392 oop_readable_call *readable_callback;
393 void *readable_callback_user;
396 Filemon_Perfile *filemon;
399 long inprogress; /* no. of articles read but not processed */
403 int counts[art_MaxState][RCI_max];
404 int readcount_ok, readcount_blank, readcount_err;
419 #define SMS_LIST(X) \
427 enum StateMachineState {
428 #define SMS_DEF_ENUM(s) sm_##s,
429 SMS_LIST(SMS_DEF_ENUM)
432 static const char *sms_names[]= {
433 #define SMS_DEF_NAME(s) #s ,
434 SMS_LIST(SMS_DEF_NAME)
440 int fd, max_queue, stream, quitting;
441 int since_activity; /* periods */
442 ArticleList waiting; /* not yet told peer */
443 ArticleList priority; /* peer says send it now */
444 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
445 struct iovec xmit[CONNIOVS];
446 XmitDetails xmitd[CONNIOVS];
451 /*----- operational variables -----*/
453 static oop_source *loop;
455 static int until_connect;
456 static ConnList conns;
457 static ArticleList queue;
459 static char *path_lock, *path_flushing, *path_defer, *globpat_backlog;
461 #define SMS(newstate, periods, why) \
462 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
464 static StateMachineState sms;
466 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
467 static int sm_period_counter, until_backlog_nextscan;
469 static double accept_proportion;
470 static int nocheck, nocheck_reported;
472 /*========== logging ==========*/
474 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
475 static void logcore(int sysloglevel, const char *fmt, ...) {
478 vsyslog(sysloglevel,fmt,al);
480 vfprintf(stderr,fmt,al);
486 static void logv(int sysloglevel, const char *pfx, int errnoval,
487 const char *fmt, va_list al) PRINTF(5,0);
488 static void logv(int sysloglevel, const char *pfx, int errnoval,
489 const char *fmt, va_list al) {
490 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
491 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
492 msgbuf[sizeof(msgbuf)-1]= 0;
494 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
495 sysloglevel= LOG_ERR; /* run by wrong user, probably */
497 logcore(sysloglevel, "<%s>%s: %s%s%s",
498 sitename, pfx, msgbuf,
499 errnoval>=0 ? ": " : "",
500 errnoval>=0 ? strerror(errnoval) : "");
503 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
504 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
505 static void fn(const char *fmt, ...) { \
507 logv(sysloglevel, pfx, err, fmt, al); \
511 #define logwrap(fn, pfx, sysloglevel, err) \
512 static void fn(const char *fmt, ...) PRINTF(1,2); \
513 static void fn(const char *fmt, ...) { \
515 logv(sysloglevel, pfx, err, fmt, al); \
519 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
520 diewrap(die, " critical", LOG_CRIT, -1, 16);
522 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
523 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
525 logwrap(syswarn, " warning", LOG_WARNING, errno);
526 logwrap(warn, " warning", LOG_WARNING, -1);
528 logwrap(notice, "", LOG_NOTICE, -1);
529 logwrap(info, " info", LOG_INFO, -1);
530 logwrap(debug, " debug", LOG_DEBUG, -1);
533 /*========== utility functions etc. ==========*/
535 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
536 static char *xvasprintf(const char *fmt, va_list al) {
538 int rc= vasprintf(&str,fmt,al);
539 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
542 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
543 static char *xasprintf(const char *fmt, ...) {
545 char *str= xvasprintf(fmt,al);
550 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
552 static pid_t xfork(const char *what) {
556 if (child==-1) sysdie("cannot fork for %s",what);
557 if (!child) postfork(what);
558 debug("forked %s %ld", what, (unsigned long)child);
562 static void on_fd_read_except(int fd, oop_call_fd callback) {
563 loop->on_fd(loop, fd, OOP_READ, callback, 0);
564 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
566 static void cancel_fd_read_except(int fd) {
567 loop->cancel_fd(loop, fd, OOP_READ);
568 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
571 static void report_child_status(const char *what, int status) {
572 if (WIFEXITED(status)) {
573 int es= WEXITSTATUS(status);
575 warn("%s: child died with error exit status %d",es);
576 } else if (WIFSIGNALED(status)) {
577 int sig= WTERMSIG(status);
578 const char *sigstr= strsignal(sig);
579 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
581 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
583 warn("%s: child died due to unknown fatal signal %d%s",
584 what, sig, coredump);
586 warn("%s: child died with unknown wait status %d", status);
590 static int xwaitpid(pid_t *pid, const char *what) {
593 int r= kill(*pid, SIGKILL);
594 if (r) sysdie("cannot kill %s child", what);
596 pid_t got= waitpid(*pid, &status, WNOHANG);
597 if (got==-1) sysdie("cannot reap %s child", what);
604 static void xunlink(const char *path, const char *what) {
606 if (r) sysdie("can't unlink %s %s", path, what);
609 static time_t xtime(void) {
611 if (now==-1) sysdie("time(2) failed");
614 static void check_isreg(const struct stat *stab, const char *path,
616 if (!S_ISREG(stab->st_mode))
617 die("%s %s not a plain file (mode 0%lo)",
618 what, path, (unsigned long)stab->st_mode);
621 static void xfstat(int fd, struct stat *stab_r, const char *what) {
622 int r= fstat(fd, stab_r);
623 if (r) sysdie("could not fstat %s", what);
626 static void xfstat_isreg(int fd, struct stat *stab_r,
627 const char *path, const char *what) {
628 xfstat(fd, stab_r, what);
629 check_isreg(stab_r, path, what);
632 static void xlstat_isreg(const char *path, struct stat *stab,
633 int *enoent_r /* 0 means ENOENT is fatal */,
635 int r= lstat(path, stab);
637 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
638 sysdie("could not lstat %s %s", what, path);
640 if (enoent_r) *enoent_r= 0;
641 check_isreg(stab, path, what);
644 static void setnonblock(int fd, int nonblocking) {
645 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
646 if (nonblocking) r |= O_NONBLOCK;
647 else r &= ~O_NONBLOCK;
648 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
651 static int samefile(const struct stat *a, const struct stat *b) {
652 assert(S_ISREG(a->st_mode));
653 assert(S_ISREG(b->st_mode));
654 return (a->st_ino == b->st_ino &&
655 a->st_dev == b->st_dev);
658 static char *sanitise(const char *input) {
659 static char sanibuf[100]; /* returns pointer to this buffer! */
661 const char *p= input;
665 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
667 if (!c) { *q++= '\''; *q=0; break; }
668 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
669 sprintf(q,"\\x%02x",c);
675 static int isewouldblock(int errnoval) {
676 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
679 /*========== making new connections ==========*/
681 static void conn_dispose(Conn *conn) {
683 perhaps_close(&conn->fd);
685 until_connect= reconnect_delay_periods;
688 static int connecting_sockets[2]= {-1,-1};
689 static pid_t connecting_child;
691 static void connect_attempt_discard(void) {
692 if (connecting_sockets[0])
693 cancel_fd_read_except(connecting_sockets[0]);
695 perhaps_close(&connecting_sockets[0]);
696 perhaps_close(&connecting_sockets[1]);
698 if (connecting_child) {
699 int r= kill(connecting_child, SIGTERM);
700 if (r) syswarn("failed to kill connecting child");
701 int status= xwaitpid(&connecting_child, "connect");
703 if (!(WIFEXITED(status) ||
704 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
705 report_child_status("connect", status);
709 #define PREP_DECL_MSG_CMSG(msg) \
711 memset(&msg,0,sizeof(msg)); \
712 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
713 msg.msg_control= msg##cbuf; \
714 msg.msg_controllen= sizeof(msg##cbuf);
716 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
719 conn= xmalloc(sizeof(*conn));
720 memset(conn,0,sizeof(*conn));
722 PREP_DECL_MSG_CMSG(msg);
723 struct cmsghdr *h= 0;
724 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
725 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
728 pid_t got= waitpid(connecting_child, &status, WNOHANG);
730 assert(got==connecting_child);
732 if (WIFEXITED(status) &&
733 (WEXITSTATUS(status) != 0 &&
734 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
735 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
736 /* child already reported the problem */
737 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
738 warn("connect: connection attempt timed out");
739 } else if (!WIFEXITED(status)) {
740 report_child_status("connect", status);
741 /* that's probably the root cause then */
744 /* child is still running apparently, report the socket problem */
746 syswarn("connect: read from child socket failed");
747 else if (e == OOP_EXCEPTION)
748 warn("connect: unexpected exception on child socket");
750 warn("connect: unexpected EOF on child socket");
755 #define CHK(field, val) \
756 if (h->cmsg_##field != val) { \
757 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
760 CHK(level, SOL_SOCKET);
761 CHK(type, SCM_RIGHTS);
762 CHK(len, CMSG_LEN(sizeof(conn->fd)));
765 if (CMSG_NXTHDR(&msg,h)) { die("connect: child sent many cmsgs"); goto x; }
767 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
770 pid_t got= waitpid(connecting_child, &status, 0);
771 if (got==-1) sysdie("connect: real wait for child");
772 assert(got == connecting_child);
775 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
776 int es= WEXITSTATUS(status);
778 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
779 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
781 fatal("connect: child gave unexpected exit status %d", es);
785 setnonblock(conn->fd, 1);
786 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
787 LIST_ADDHEAD(conns, conn);
788 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
789 connect_attempt_discard();
790 check_master_queue();
795 connect_attempt_discard();
798 static int allow_connect_start(void) {
799 return conns.count < max_connections
804 static void connect_start(void) {
805 assert(!connecting_sockets[0]);
806 assert(!connecting_sockets[1]);
807 assert(!connecting_child);
809 notice("starting connection attempt");
811 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
812 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
814 connecting_child= xfork("connection");
816 if (!connecting_child) {
817 FILE *cn_from, *cn_to;
818 char buf[NNTP_STRLEN+100];
819 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
821 r= close(connecting_sockets[0]);
822 if (r) sysdie("connect: close parent socket in child");
824 alarm(connection_setup_timeout);
825 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
826 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
827 else sysfatal("connect: connection attempt failed");
829 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
830 sysfatal("connect: authentication failed");
832 if (fputs("MODE STREAM\r\n", cn_to) ||
834 sysfatal("connect: could not send MODE STREAM");
835 buf[sizeof(buf)-1]= 0;
836 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
838 sysfatal("connect: could not read response to MODE STREAM");
840 fatal("connect: connection close in response to MODE STREAM");
845 fatal("connect: response to MODE STREAM is too long: %.100s...",
846 remote_host, sanitise(buf));
847 l--; if (l>0 && buf[l-1]=='\r') l--;
850 int rcode= strtoul(buf,&ep,10);
852 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
856 exitstatus= CONNCHILD_ESTATUS_STREAM;
862 warn("connect: unexpected response to MODE STREAM: %.50s",
868 int fd= fileno(cn_from);
870 PREP_DECL_MSG_CMSG(msg);
871 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
872 cmsg->cmsg_level= SOL_SOCKET;
873 cmsg->cmsg_type= SCM_RIGHTS;
874 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
875 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
877 msg.msg_controllen= cmsg->cmsg_len;
878 r= sendmsg(connecting_sockets[1], &msg, 0);
879 if (r) sysdie("sendmsg failed for new connection");
884 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
885 if (r) sysdie("connect: close child socket in parent");
887 on_fd_read_except(connecting_sockets[0], connchild_event);
891 connect_attempt_discard();
894 static void check_idle_conns(void) {
896 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
897 conn->since_activity++;
899 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
900 if (conn->since_activity <= need_activity_periods) continue;
902 /* We need to shut this down */
904 connfail(conn,"timed out waiting for response to QUIT");
905 else if (conn->sent.count)
906 connfail(conn,"timed out waiting for responses");
907 else if (conn->waiting.count || conn->priority.count)
908 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
909 else if (conn->xmitu)
910 connfail(conn,"peer has been sending responses"
911 " before receiving our commands!");
913 static const char quitcmd[]= "QUIT\r\n";
914 int todo= sizeof(quitcmd)-1;
915 const char *p= quitcmd;
917 int r= write(conn->fd, p, todo);
919 if (isewouldblock(errno))
920 connfail(conn, "blocked writing QUIT to idle connection");
922 connfail(conn, "failed to write QUIT to idle connection: %s",
930 conn->since_activity= 0;
931 debug("C%d is idle, quitting", conn->fd);
940 /*========== overall control of article flow ==========*/
942 static void check_master_queue(void) {
950 /* Find a connection to offer this article. We prefer a busy
951 * connection to an idle one, provided it's not full. We take the
952 * first (oldest) and since that's stable, it will mean we fill up
953 * connections in order. That way if we have too many
954 * connections, the spare ones will go away eventually.
956 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
957 if (walk->quitting) continue;
958 inqueue= walk->sent.count + walk->priority.count
959 + walk->waiting.count;
960 spare= walk->max_queue - inqueue;
961 assert(inqueue <= max_queue_per_conn);
963 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
964 else if (spare>0) /*working*/ { use= walk; break; }
967 if (!inqueue) use->since_activity= 0; /* reset idle counter */
969 Article *art= LIST_REMHEAD(queue);
970 LIST_ADDTAIL(use->waiting, art);
973 conn_maybe_write(use);
974 } else if (allow_connect_start()) {
975 until_connect= reconnect_delay_periods;
984 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
989 static void conn_maybe_write(Conn *conn) {
992 conn_make_some_xmits(conn);
994 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
998 void *rp= conn_write_some_xmits(conn);
999 if (rp==OOP_CONTINUE) {
1000 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1002 } else if (rp==OOP_HALT) {
1005 /* transmitted everything */
1012 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1013 int requeue[art_MaxState];
1016 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1017 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1018 while ((art= LIST_REMHEAD(conn->sent))) {
1019 requeue[art->state]++;
1020 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1021 LIST_ADDTAIL(queue,art);
1026 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1029 char *m= xvasprintf(fmt,al);
1030 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1031 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1034 LIST_REMOVE(conns,conn);
1036 check_master_queue();
1039 static void connfail(Conn *conn, const char *fmt, ...) {
1042 vconnfail(conn,fmt,al);
1046 /*========== article transmission ==========*/
1048 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1049 XmitKind kind) { /* caller must then fill in details */
1050 struct iovec *v= &conn->xmit[conn->xmitu];
1051 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1052 v->iov_base= (char*)data;
1058 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1059 xmit_core(conn,data,len, xk_Const);
1061 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1063 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1064 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1068 static void xmit_free(XmitDetails *d) {
1070 case xk_Malloc: free(d->info.malloc_tofree); break;
1071 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1072 case xk_Const: break;
1077 static void *conn_write_some_xmits(Conn *conn) {
1079 * 0: nothing more to write, no need to call us again
1080 * OOP_CONTINUE: more to write but fd not writeable
1081 * OOP_HALT: disaster, have destroyed conn
1084 int count= conn->xmitu;
1085 if (!count) return 0;
1087 if (count > IOV_MAX) count= IOV_MAX;
1088 ssize_t rs= writev(conn->fd, conn->xmit, count);
1090 if (isewouldblock(errno)) return OOP_CONTINUE;
1091 connfail(conn, "write failed: %s", strerror(errno));
1097 for (done=0; rs && done<conn->xmitu; done++) {
1098 struct iovec *vp= &conn->xmit[done];
1099 XmitDetails *dp= &conn->xmitd[done];
1100 if (rs > vp->iov_len) {
1108 int newu= conn->xmitu - done;
1109 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1110 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1115 static void conn_make_some_xmits(Conn *conn) {
1117 if (conn->xmitu+5 > CONNIOVS)
1120 Article *art= LIST_REMHEAD(conn->priority);
1121 if (!art) art= LIST_REMHEAD(conn->waiting);
1124 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1125 /* actually send it */
1127 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1131 XMIT_LITERAL("TAKETHIS ");
1132 xmit_noalloc(conn, art->messageid, art->midlen);
1133 XMIT_LITERAL("\r\n");
1134 xmit_artbody(conn, artdata);
1137 /* we got 235 from IHAVE */
1139 xmit_artbody(conn, artdata);
1141 XMIT_LITERAL(".\r\n");
1146 art->state == art_Unchecked ? art_Unsolicited :
1147 art->state == art_Wanted ? art_Wanted :
1149 art->ipf->counts[art->state][RC_sent]++;
1150 LIST_ADDTAIL(conn->sent, art);
1156 XMIT_LITERAL("IHAVE ");
1158 XMIT_LITERAL("CHECK ");
1159 xmit_noalloc(conn, art->messageid, art->midlen);
1160 XMIT_LITERAL("\r\n");
1162 assert(art->state == art_Unchecked);
1163 art->ipf->counts[art->state][RC_sent]++;
1164 LIST_ADDTAIL(conn->sent, art);
1170 /*========== handling responses from peer ==========*/
1172 static const oop_rd_style peer_rd_style= {
1173 OOP_RD_DELIM_STRIP, '\n',
1175 OOP_RD_SHORTREC_FORBID
1178 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1179 const char *errmsg, int errnoval,
1180 const char *data, size_t recsz, void *conn_v) {
1182 connfail(conn, "error receiving from peer: %s", errmsg);
1183 return OOP_CONTINUE;
1186 static Article *article_reply_check(Conn *conn, const char *response,
1187 int code_indicates_streaming,
1189 /* 1:yes, -1:no, 0:dontcare */,
1190 const char *sanitised_response) {
1191 Article *art= LIST_HEAD(conn->sent);
1195 "peer gave unexpected response when no commands outstanding: %s",
1196 sanitised_response);
1200 if (code_indicates_streaming) {
1201 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1202 if (!conn->stream) {
1203 connfail(conn, "peer gave streaming response code "
1204 " to IHAVE or subsequent body: %s", sanitised_response);
1207 const char *got_mid= response+4;
1208 int got_midlen= strcspn(got_mid, " \n\r");
1209 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1210 connfail(conn, "peer gave streaming response with syntactically invalid"
1211 " messageid: %s", sanitised_response);
1214 if (got_midlen != art->midlen ||
1215 memcmp(got_mid, art->messageid, got_midlen)) {
1216 connfail(conn, "peer gave streaming response code to wrong article -"
1217 " probable synchronisation problem; we offered: %s;"
1219 art->messageid, sanitised_response);
1224 connfail(conn, "peer gave non-streaming response code to"
1225 " CHECK/TAKETHIS: %s", sanitised_response);
1230 if (must_have_sent>0 && art->state < art_Wanted) {
1231 connfail(conn, "peer says article accepted but"
1232 " we had not sent the body: %s", sanitised_response);
1235 if (must_have_sent<0 && art->state >= art_Wanted) {
1236 connfail(conn, "peer says please sent the article but we just did: %s",
1237 sanitised_response);
1241 Article *art_again= LIST_REMHEAD(conn->sent);
1242 assert(art_again == art);
1246 static void update_nocheck(int accepted) {
1247 accept_proportion *= nocheck_decay;
1248 accept_proportion += accepted * (1.0 - nocheck_decay);
1249 int new_nocheck= accept_proportion >= nocheck_thresh;
1250 if (new_nocheck && !nocheck_reported) {
1251 notice("entering nocheck mode for the first time");
1252 nocheck_reported= 1;
1253 } else if (new_nocheck != nocheck) {
1254 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1256 nocheck= new_nocheck;
1259 static void article_done(Conn *conn, Article *art, int whichcount) {
1260 art->ipf->counts[art->state][whichcount]++;
1261 if (whichcount == RC_accepted) update_nocheck(1);
1262 else if (whichcount == RC_unwanted) update_nocheck(0);
1264 InputFile *ipf= art->ipf;
1265 while (art->blanklen) {
1266 static const char spaces[]=
1271 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1272 int r= pwrite(ipf->fd, spaces, w, art->offset);
1274 if (errno==EINTR) continue;
1275 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1276 art->messageid, art->blanklen, art->offset, ipf->path);
1278 assert(r>=0 && r<=w);
1284 assert(ipf->inprogress >= 0);
1286 if (!ipf->inprogress && ipf != main_input_file)
1287 queue_check_input_done();
1292 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1293 const char *errmsg, int errnoval,
1294 const char *data, size_t recsz, void *conn_v) {
1297 if (ev == OOP_RD_EOF) {
1298 connfail(conn, "unexpected EOF from peer");
1299 return OOP_CONTINUE;
1301 assert(ev == OOP_RD_OK);
1303 char *sani= sanitise(data);
1306 unsigned long code= strtoul(data, &ep, 10);
1307 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1308 connfail(conn, "badly formatted response from peer: %s", sani);
1309 return OOP_CONTINUE;
1312 if (conn->quitting) {
1313 if (code!=205 && code!=503) {
1314 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1316 notice("C%d idle connection closed", conn->fd);
1317 assert(!conn->waiting.count);
1318 assert(!conn->priority.count);
1319 assert(!conn->sent.count);
1320 assert(!conn->xmitu);
1321 LIST_REMOVE(conns,conn);
1324 return OOP_CONTINUE;
1327 conn->since_activity= 0;
1330 #define GET_ARTICLE(musthavesent) \
1331 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1332 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1334 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1335 code_streaming= (streaming); \
1336 GET_ARTICLE(musthavesent); \
1337 article_done(conn, art, RC_##how); break;
1339 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1341 int code_streaming= 0;
1345 case 400: PEERBADMSG("peer stopped accepting articles");
1346 case 503: PEERBADMSG("peer timed us out");
1347 default: PEERBADMSG("peer sent unexpected message");
1349 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1350 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1352 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1353 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1355 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1356 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1358 case 238: /* CHECK says send it */
1360 case 335: /* IHAVE says send it */
1362 assert(art->state == art_Unchecked);
1363 art->ipf->counts[art->state][RC_accepted]++;
1364 art->state= art_Wanted;
1365 LIST_ADDTAIL(conn->priority, art);
1368 case 431: /* CHECK or TAKETHIS says try later */
1370 case 436: /* IHAVE says try later */
1373 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1375 sysfatal("write to defer file %s",path_defer);
1376 article_done(conn, art, RC_deferred);
1381 conn_maybe_write(conn);
1382 check_master_queue();
1383 return OOP_CONTINUE;
1387 /*========== monitoring of input files ==========*/
1389 static void feedfile_eof(InputFile *ipf) {
1390 assert(ipf != main_input_file); /* promised by tailing_try_read */
1392 inputfile_tailing_stop(ipf);
1393 assert(ipf->fd >= 0);
1394 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1397 if (ipf == flushing_input_file) {
1398 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1399 if (main_input_file) inputfile_tailing_start(main_input_file);
1400 statemc_check_flushing_done();
1401 } else if (ipf == backlog_input_file) {
1402 statemc_check_backlog_done();
1404 abort(); /* supposed to wait rather than get EOF on main input file */
1408 static InputFile *open_input_file(const char *path) {
1409 int fd= open(path, O_RDONLY);
1411 if (errno==ENOENT) return 0;
1412 sysfatal("unable to open input file %s", path);
1415 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1416 memset(ipf,0,sizeof(*ipf));
1419 strcpy(ipf->path, path);
1424 static void close_input_file(InputFile *ipf) {
1425 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1426 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1427 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1428 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1431 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1435 /*---------- dealing with articles read in the input file ----------*/
1437 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1438 const char *data, const char *how) {
1439 warn("corrupted file: %s, offset %lu: %s: %s",
1440 ipf->path, (unsigned long)offset, how, sanitise(data));
1441 ipf->readcount_err++;
1442 if (ipf->readcount_err > max_bad_data_initial +
1443 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1444 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1445 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1446 return OOP_CONTINUE;
1449 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1450 oop_rd_event ev, const char *errmsg,
1451 int errnoval, const char *data, size_t recsz,
1453 InputFile *ipf= ipf_v;
1454 assert(ev == OOP_RD_SYSTEM);
1456 sysdie("error reading input file: %s, offset %lu",
1457 ipf->path, (unsigned long)ipf->offset);
1460 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1461 oop_rd_event ev, const char *errmsg,
1462 int errnoval, const char *data, size_t recsz,
1464 InputFile *ipf= ipf_v;
1466 char tokentextbuf[sizeof(TOKEN)*2+3];
1468 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1470 off_t old_offset= ipf->offset;
1471 ipf->offset += recsz + 1;
1473 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1475 if (ev==OOP_RD_PARTREC)
1476 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1477 /* but process it anyway */
1479 if (ipf->skippinglong) {
1480 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1483 if (ev==OOP_RD_LONG) {
1484 ipf->skippinglong= 1;
1485 X_BAD_DATA("overly long line");
1488 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1489 if (!recsz) X_BAD_DATA("empty line");
1492 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1493 ipf->readcount_blank++;
1494 return OOP_CONTINUE;
1497 char *space= strchr(data,' ');
1498 int tokenlen= space-data;
1499 int midlen= (int)recsz-tokenlen-1;
1500 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1501 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1503 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1504 memcpy(tokentextbuf, data, tokenlen);
1505 tokentextbuf[tokenlen]= 0;
1506 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1508 ipf->readcount_ok++;
1510 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1511 art->offset= ipf->offset;
1512 art->blanklen= recsz;
1513 art->midlen= midlen;
1514 art->state= art_Unchecked;
1515 art->ipf= ipf; ipf->inprogress++;
1516 art->token= TextToToken(tokentextbuf);
1517 strcpy(art->messageid, space+1);
1518 LIST_ADDTAIL(queue, art);
1520 if (sms==sm_NORMAL && ipf==main_input_file &&
1521 ipf->offset >= target_max_feedfile_size)
1522 statemc_start_flush("feed file size");
1524 check_master_queue();
1525 return OOP_CONTINUE;
1528 /*========== tailing input file ==========*/
1530 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1532 InputFile *ipf= user;
1533 return ipf->readable_callback(loop, &ipf->readable,
1534 ipf->readable_callback_user);
1537 static void tailing_on_cancel(struct oop_readable *rable) {
1538 InputFile *ipf= (void*)rable;
1540 if (ipf->filemon) filemon_stop(ipf);
1541 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1542 ipf->readable_callback= 0;
1545 static void tailing_queue_readable(InputFile *ipf) {
1546 /* lifetime of ipf here is OK because destruction will cause
1547 * on_cancel which will cancel this callback */
1548 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1551 static int tailing_on_readable(struct oop_readable *rable,
1552 oop_readable_call *cb, void *user) {
1553 InputFile *ipf= (void*)rable;
1555 tailing_on_cancel(rable);
1556 ipf->readable_callback= cb;
1557 ipf->readable_callback_user= user;
1560 tailing_queue_readable(ipf);
1564 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1566 InputFile *ipf= (void*)rable;
1568 ssize_t r= read(ipf->fd, buffer, length);
1570 if (errno==EINTR) continue;
1574 if (ipf==main_input_file) {
1577 } else if (ipf==flushing_input_file) {
1579 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1580 } else if (ipf==backlog_input_file) {
1590 /*---------- filemon implemented with inotify ----------*/
1592 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1593 #define HAVE_FILEMON
1595 #include <linux/inotify.h>
1597 static int filemon_inotify_fd;
1598 static int filemon_inotify_wdmax;
1599 static InputFile **filemon_inotify_wd2ipf;
1601 struct Filemon_Perfile {
1605 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1606 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1607 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1609 if (wd >= filemon_inotify_wdmax) {
1611 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1612 sizeof(*filemon_inotify_wd2ipf) * newmax);
1613 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1614 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1615 filemon_inotify_wdmax= newmax;
1618 assert(!filemon_inotify_wd2ipf[wd]);
1619 filemon_inotify_wd2ipf[wd]= ipf;
1621 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1622 ipf, wd, filemon_inotify_wdmax);
1627 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1629 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1630 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1631 if (r) sysdie("inotify_rm_watch");
1632 filemon_inotify_wd2ipf[wd]= 0;
1635 static void *filemon_inotify_readable(oop_source *lp, int fd,
1636 oop_event e, void *u) {
1637 struct inotify_event iev;
1639 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1641 if (isewouldblock(errno)) break;
1642 sysdie("read from inotify master");
1643 } else if (r==sizeof(iev)) {
1644 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1646 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1648 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1649 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1650 filemon_callback(ipf);
1652 return OOP_CONTINUE;
1655 static int filemon_method_init(void) {
1656 filemon_inotify_fd= inotify_init();
1657 if (filemon_inotify_fd<0) {
1658 syswarn("could not initialise inotify: inotify_init failed");
1662 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1664 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1668 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1670 /*---------- filemon dummy implementation ----------*/
1672 #if !defined(HAVE_FILEMON)
1674 struct Filemon_Perfile { int dummy; };
1676 static int filemon_method_init(void) { return 0; }
1677 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1678 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1680 #endif /* !HAVE_FILEMON */
1682 /*---------- filemon generic interface ----------*/
1684 static void filemon_start(InputFile *ipf) {
1685 assert(!ipf->filemon);
1687 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1688 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1689 filemon_method_startfile(ipf, ipf->filemon);
1692 static void filemon_stop(InputFile *ipf) {
1693 if (!ipf->filemon) return;
1694 filemon_method_stopfile(ipf, ipf->filemon);
1699 static void filemon_callback(InputFile *ipf) {
1700 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1703 /*---------- interface to start and stop an input file ----------*/
1705 static const oop_rd_style feedfile_rdstyle= {
1706 OOP_RD_DELIM_STRIP, '\n',
1708 OOP_RD_SHORTREC_LONG,
1711 static void inputfile_tailing_start(InputFile *ipf) {
1713 ipf->readable.on_readable= tailing_on_readable;
1714 ipf->readable.on_cancel= tailing_on_cancel;
1715 ipf->readable.try_read= tailing_try_read;
1716 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1717 ipf->readable.delete_kill= 0;
1719 ipf->readable_callback= 0;
1720 ipf->readable_callback_user= 0;
1722 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1725 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1726 feedfile_got_article,ipf, feedfile_read_err, ipf);
1727 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1730 static void inputfile_tailing_stop(InputFile *ipf) {
1732 oop_rd_cancel(ipf->rd);
1733 oop_rd_delete(ipf->rd);
1735 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1739 /*========== interaction with innd - state machine ==========*/
1741 /* See official state diagram at top of file. We implement
1752 |`---------------------------------------------------.
1754 |`---------------- - - - |
1755 D ENOENT | D EXISTS see OVERALL STATES diagram |
1756 | for full startup logic |
1759 | ============ try to |
1765 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1766 ^ | hardlink F to D |
1769 | | our handle onto F is now onto D |
1772 | |<-------------------<---------------------<---------+
1774 | | spawn inndcomm flush |
1776 | ================== |
1777 | FLUSHING[-ABSENT] |
1779 | main D tail/none |
1780 | ================== |
1782 | | INNDCOMM FLUSH FAILS ^
1783 | |`----------------------->----------. |
1785 | | NO SUCH SITE V |
1786 ^ |`--------------->----. ==================== |
1787 | | \ FLUSHFAILED[-ABSENT] |
1789 | | FLUSH OK \ main D tail/none |
1790 | | open F \ ==================== |
1792 | | \ | TIME TO RETRY |
1793 | |`------->----. ,---<---'\ `----------------'
1794 | | D NONE | | D NONE `----.
1796 | ============= V V ============
1797 | SEPARATED-1 | | DROPPING-1
1798 | flsh->fd>=0 | | flsh->fd>=0
1799 | [Separated] | | [Dropping]
1800 | main F idle | | main none
1801 | old D tail | | old D tail
1802 | ============= | | ============
1804 ^ | EOF ON D | | defer | EOF ON D
1806 | =============== | | ===============
1807 | SEPARATED-2 | | DROPPING-2
1808 | flsh->fd==-1 | V flsh->fd==-1
1809 | [Finishing] | | [Dropping]
1810 | main F tail | `. main none
1811 | old D closed | `. old D closed
1812 | =============== V `. ===============
1814 | | ALL D PROCESSED `. | ALL D PROCESSED
1815 | V install defer as backlog `. | install defer
1816 ^ | close D `. | close D
1817 | | unlink D `. | unlink D
1820 `----------' ==============
1840 static void startup_set_input_file(InputFile *f) {
1841 assert(!main_input_file);
1843 inputfile_tailing_start(f);
1846 static void statemc_init(void) {
1847 struct stat stab, stabf;
1849 path_lock= xasprintf("%s_lock", feedfile);
1850 path_flushing= xasprintf("%s_flushing", feedfile);
1851 path_defer= xasprintf("%s_defer", feedfile);
1852 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1855 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1856 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1859 memset(&fl,0,sizeof(fl));
1861 fl.l_whence= SEEK_SET;
1862 int r= fcntl(lockfd, F_SETLK, &fl);
1864 if (errno==EACCES || isewouldblock(errno)) {
1865 if (quiet_multiple) exit(0);
1866 fatal("another duct holds the lockfile");
1868 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1871 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
1873 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1875 if (!lock_noent && samefile(&stab, &stabf))
1879 sysdie("could not close stale lockfile %s", path_lock);
1881 debug("startup: locked");
1883 search_backlog_file();
1886 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1888 debug("startup: ductdefer ENOENT");
1890 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1891 switch (stab.st_nlink==1) {
1893 open_defer(); /* so that we will later close it and rename it */
1896 xunlink(path_defer, "stale defer file link"
1897 " (presumably hardlink to backlog file)");
1900 die("defer file %s has unexpected link count %d",
1901 path_defer, stab.st_nlink);
1905 struct stat stab_f, stab_d;
1908 InputFile *file_d= open_input_file(path_flushing);
1909 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
1911 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1913 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1914 debug("startup: F==D => Hardlinked");
1915 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1920 debug("startup: F ENOENT => Moved");
1921 if (file_d) startup_set_input_file(file_d);
1922 spawn_inndcomm_flush("feedfile missing at startup");
1923 /* => Flushing, sms:=FLUSHING */
1926 debug("startup: F!=D => Separated");
1927 startup_set_input_file(file_d);
1928 SMS(SEPARATED, 0, "found both old and current feed files");
1930 debug("startup: F exists, D ENOENT => Normal");
1931 InputFile *file_f= open_input_file(feedfile);
1932 if (!file_f) die("feed file vanished during startup");
1933 startup_set_input_file(file_f);
1934 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1939 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1940 assert(sms == sm_NORMAL);
1942 debug("starting flush (%s) (%lu >?= %lu) (%d)",
1944 (unsigned long)(main_input_file ? main_input_file->offset : 0),
1945 (unsigned long)target_max_feedfile_size,
1948 int r= link(feedfile, path_flushing);
1949 if (r) sysdie("link feedfile %s to flushing file %s",
1950 feedfile, path_flushing);
1953 xunlink(feedfile, "old feedfile link");
1956 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1959 static void statemc_period_poll(void) {
1960 if (!sm_period_counter) return;
1961 sm_period_counter--;
1962 assert(sm_period_counter>=0);
1964 if (sm_period_counter) return;
1967 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
1969 case sm_FLUSHFAILED:
1970 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
1977 static int inputfile_is_done(InputFile *ipf) {
1979 if (ipf->inprogress) return 0; /* new article in the meantime */
1980 if (ipf->fd >= 0); return 0; /* not had EOF */
1984 static void notice_processed(InputFile *ipf, const char *what,
1986 #define RCI_NOTHING(x) /* nothing */
1987 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
1988 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
1990 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
1992 info("processed %s%s read=%d(+%dbl,+%derr)"
1993 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
1994 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
1997 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
1998 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
1999 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2000 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2001 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2002 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2008 static void statemc_check_backlog_done(void) {
2009 InputFile *ipf= backlog_input_file;
2010 if (!inputfile_is_done(ipf)) return;
2012 const char *slash= strrchr(ipf->path, '/');
2013 const char *leaf= slash ? slash+1 : ipf->path;
2014 const char *under= strchr(slash, '_');
2015 const char *rest= under ? under+1 : leaf;
2016 if (!strncmp(rest,"backlog",7)) rest += 7;
2017 notice_processed(ipf,"backlog:",rest);
2019 close_input_file(ipf);
2020 if (unlink(ipf->path)) {
2021 if (errno != ENOENT)
2022 sysdie("could not unlink processed backlog file %s", ipf->path);
2023 warn("backlog file %s vanished while we were reading it"
2024 " so we couldn't remove it (but it's done now, anyway)",
2028 backlog_input_file= 0;
2029 search_backlog_file();
2033 static void statemc_check_flushing_done(void) {
2034 InputFile *ipf= flushing_input_file;
2035 if (!inputfile_is_done(ipf)) return;
2037 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2039 notice_processed(ipf,"feedfile",0);
2043 xunlink(path_flushing, "old flushing file");
2045 close_input_file(flushing_input_file);
2046 free(flushing_input_file);
2047 flushing_input_file= 0;
2049 if (sms==sm_SEPARATED) {
2050 notice("flush complete");
2051 SMS(NORMAL, 0, "flush complete");
2052 } else if (sms==sm_DROPPING) {
2053 SMS(DROPPED, 0, "old flush complete");
2054 search_backlog_file();
2055 notice("feed dropped, but will continue until backlog is finished");
2059 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2061 assert(!inputfile_is_done(main_input_file));
2062 statemc_check_flushing_done();
2063 statemc_check_backlog_done();
2064 return OOP_CONTINUE;
2067 static void queue_check_input_done(void) {
2068 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2071 static void statemc_setstate(StateMachineState newsms, int periods,
2072 const char *forlog, const char *why) {
2074 sm_period_counter= periods;
2076 const char *xtra= "";
2078 case sm_FLUSHING: sm_FLUSHFAILED:
2079 if (!main_input_file) xtra= "-ABSENT";
2081 case sm_SEPARATED: case sm_DROPPING:
2082 xtra= flushing_input_file->fd >= 0 ? "-1" : "-2";
2088 info("%s%s[%d] %s",forlog,xtra,periods,why);
2090 info("%s%s %s",forlog,xtra,why);
2094 /*---------- defer and backlog files ----------*/
2096 static void open_defer(void) {
2101 defer= fopen(path_defer, "a+");
2102 if (!defer) sysfatal("could not open defer file %s", path_defer);
2104 /* truncate away any half-written records */
2106 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2108 if (stab.st_size > LONG_MAX)
2109 die("defer file %s size is far too large", path_defer);
2114 long orgsize= stab.st_size;
2115 long truncto= stab.st_size;
2117 if (!truncto) break; /* was only (if anything) one half-truncated record */
2118 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2119 sysdie("seek in defer file %s while truncating partial", path_defer);
2124 sysdie("failed read from defer file %s", path_defer);
2126 die("defer file %s shrank while we were checking it!", path_defer);
2132 if (stab.st_size != truncto) {
2133 warn("truncating half-record at end of defer file %s -"
2134 " shrinking by %ld bytes from %ld to %ld",
2135 path_defer, orgsize - truncto, orgsize, truncto);
2138 sysfatal("could not flush defer file %s", path_defer);
2139 if (ftruncate(fileno(defer), truncto))
2140 sysdie("could not truncate defer file %s", path_defer);
2143 info("continuing existing defer file %s (%ld bytes)",
2144 path_defer, orgsize);
2146 if (fseek(defer, truncto, SEEK_SET))
2147 sysdie("could not seek to new end of defer file %s", path_defer);
2150 static void close_defer(void) {
2155 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2157 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2160 time_t now= xtime();
2162 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2164 (unsigned long)stab.st_ino);
2165 if (link(path_defer, backlog))
2166 sysfatal("could not install defer file %s as backlog file %s",
2167 path_defer, backlog);
2168 if (unlink(path_defer))
2169 sysdie("could not unlink old defer link %s to backlog file %s",
2170 path_defer, backlog);
2174 if (until_backlog_nextscan < 0 ||
2175 until_backlog_nextscan > backlog_retry_minperiods + 1)
2176 until_backlog_nextscan= backlog_retry_minperiods + 1;
2179 static void poll_backlog_file(void) {
2180 if (until_backlog_nextscan < 0) return;
2181 if (until_backlog_nextscan-- > 0) return;
2182 search_backlog_file();
2185 static void search_backlog_file(void) {
2186 /* returns non-0 iff there are any backlog files */
2191 const char *oldest_path=0;
2192 time_t oldest_mtime, now;
2194 if (backlog_input_file) return;
2198 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2202 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2204 die("out of memory expanding backlog pattern %s", globpat_backlog);
2206 for (i=0; i<gl.gl_pathc; i++) {
2207 const char *path= gl.gl_pathv[i];
2209 if (strchr(path,'#') || strchr(path,'~')) {
2210 debug("backlog file search skipping %s", path);
2213 r= stat(path, &stab);
2215 syswarn("failed to stat backlog file %s", path);
2218 if (!S_ISREG(stab.st_mode)) {
2219 warn("backlog file %s is not a plain file (or link to one)", path);
2222 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2224 oldest_mtime= stab.st_mtime;
2227 case GLOB_NOMATCH: /* fall through */
2230 sysdie("glob expansion of backlog pattern %s gave unexpected"
2231 " nonzero (error?) return value %d", globpat_backlog, r);
2237 debug("backlog scan: none");
2239 if (sms==sm_DROPPED) {
2240 notice("feed dropped and our work is complete");
2241 xunlink(path_lock, "lockfile for old feed");
2244 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2249 double age= difftime(now, oldest_mtime);
2250 long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
2252 if (age_deficiency <= 0) {
2253 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2254 age, age_deficiency, oldest_path);
2256 backlog_input_file= open_input_file(oldest_path);
2257 if (!backlog_input_file) {
2258 warn("backlog file %s vanished as we opened it", backlog_input_file);
2261 inputfile_tailing_start(backlog_input_file);
2262 until_backlog_nextscan= -1;
2266 until_backlog_nextscan= age_deficiency / PERIOD_SECONDS;
2268 if (backlog_spontaneous_rescan_periods >= 0 &&
2269 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2270 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2272 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2273 age, age_deficiency, until_backlog_nextscan, oldest_path);
2277 /*========== flushing the feed ==========*/
2279 static pid_t inndcomm_child;
2281 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2282 assert(inndcomm_child);
2283 int status= xwaitpid(&inndcomm_child, "inndcomm");
2284 cancel_fd_read_except(fd);
2287 assert(!flushing_input_file);
2289 if (WIFEXITED(status)) {
2290 switch (WEXITSTATUS(status)) {
2292 case INNDCOMMCHILD_ESTATUS_FAIL:
2295 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2296 warn("feed has been dropped by innd, finishing up");
2297 flushing_input_file= main_input_file;
2298 tailing_queue_readable(flushing_input_file);
2299 /* we probably previously returned EAGAIN from our fake read method
2300 * when in fact we were at EOF, so signal another readable event
2301 * so we actually see the EOF */
2305 if (flushing_input_file) {
2306 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2309 SMS(DROPPED, 0, "feed dropped by innd");
2310 search_backlog_file();
2312 return OOP_CONTINUE;
2316 flushing_input_file= main_input_file;
2317 tailing_queue_readable(flushing_input_file);
2319 main_input_file= open_input_file(feedfile);
2320 if (!main_input_file)
2321 die("flush succeeded but feedfile %s does not exist!", feedfile);
2323 if (flushing_input_file) {
2324 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2327 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2329 return OOP_CONTINUE;
2332 goto unexpected_exitstatus;
2335 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2336 warn("flush timed out trying to talk to innd");
2339 unexpected_exitstatus:
2340 report_child_status("inndcomm child", status);
2344 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2347 static void inndcommfail(const char *what) {
2348 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2349 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2352 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2355 notice("flushing %s",why);
2357 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2358 assert(!inndcomm_child);
2360 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2362 inndcomm_child= xfork("inndcomm child");
2364 if (!inndcomm_child) {
2365 const char *flushargv[2]= { sitename, 0 };
2371 alarm(inndcomm_flush_timeout);
2372 r= ICCopen(); if (r) inndcommfail("connect");
2373 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2374 if (!r) exit(0); /* yay! */
2376 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2377 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2378 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2382 int sentinel_fd= pipefds[0];
2383 on_fd_read_except(sentinel_fd, inndcomm_event);
2385 SMS(FLUSHING, 0, why);
2388 /*========== main program ==========*/
2390 static void postfork_inputfile(InputFile *ipf) {
2392 assert(ipf->fd >= 0);
2397 static void postfork_stdio(FILE *f) {
2398 /* we have no stdio streams that are buffered long-term */
2402 static void postfork(const char *what) {
2403 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2404 sysdie("%s child: failed to reset SIGPIPE");
2406 postfork_inputfile(main_input_file);
2407 postfork_inputfile(flushing_input_file);
2410 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2413 postfork_stdio(defer);
2416 #define EVERY(what, interval_sec, interval_usec, body) \
2417 static const struct timeval what##_timeout = \
2418 { interval_sec, interval_usec }; \
2419 static void what##_schedule(void); \
2420 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2422 what##_schedule(); \
2424 static void what##_schedule(void) { \
2425 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2428 EVERY(filepoll, 5,0, {
2429 if (main_input_file && main_input_file->readable_callback)
2430 filemon_callback(main_input_file);
2433 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s"
2434 #define DEBUG_IPF(wh) \
2435 wh##_input_file, debug_ipf_path(wh##_input_file), \
2436 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2437 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2438 static const char *debug_ipf_path(InputFile *ipf) {
2439 char *slash= strrchr(ipf->path,'/');
2440 return slash ? slash+1 : ipf->path;
2443 EVERY(period, PERIOD_SECONDS,0, {
2445 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2446 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_IPF(flushing)
2447 " children connecting=%ld inndcomm_child"
2449 sms_names[sms], sm_period_counter,
2450 queue.count, conns.count, until_connect,
2451 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2452 (long)connecting_child, (long)inndcomm_child
2455 if (until_connect) until_connect--;
2457 poll_backlog_file();
2458 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2459 statemc_period_poll();
2460 check_master_queue();
2465 /*========== option parsing ==========*/
2467 /*---------- generic option parser and logging ----------*/
2469 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2470 static void vbadusage(const char *fmt, va_list al) {
2473 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2474 static void badusage(const char *fmt, ...) {
2481 of_seconds= 001000u,
2482 of_boolean= 002000u,
2485 typedef struct Option Option;
2486 typedef void OptionParser(const Option*, const char *val);
2496 /*---------- specific option types ----------*/
2498 static void op_integer(const Option *o, const char *val) {
2501 unsigned long ul= strtoul(val,&ep,10);
2502 if (*ep || ep==val || errno || ul>INT_MAX)
2503 badusage("bad integer value for %s",o->lng);
2504 int *store= o->store;
2508 static void op_double(const Option *o, const char *val) {
2509 int *store= o->store;
2512 *store= strtod(val, &ep);
2513 if (*ep || ep==val || errno)
2514 badusage("bad floating point value for %s",o->lng);
2517 static void op_string(const Option *o, const char *val) {
2518 const char **store= o->store;
2522 static void op_seconds(const Option *o, const char *val) {
2523 int *store= o->store;
2527 double v= strtod(val,&ep);
2528 if (ep==val) badusage("bad time/duration value for %s",o->lng);
2530 if (!*ep || !strcmp(ep,"s")) unit= 1;
2531 else if (!strcmp(ep,"m")) unit= 60;
2532 else if (!strcmp(ep,"h")) unit= 3600;
2533 else if (!strcmp(ep,"d")) unit= 86400;
2534 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2538 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2542 static void op_periods_rndup(const Option *o, const char *val) {
2543 int *store= o->store;
2545 *store += PERIOD_SECONDS-1;
2546 *store /= PERIOD_SECONDS;
2549 static void op_setint(const Option *o, const char *val) {
2550 int *store= o->store;
2554 /*---------- specific options ----------*/
2556 static const Option options[]= {
2557 {'f',"feedfile", &feedfile, op_string },
2558 {'q',"quiet-multiple", &quiet_multiple, op_setint, 1,1 },
2560 { 0, "max-connections", &max_connections, op_integer },
2561 { 0, "max-queue-per-conn", &max_queue_per_conn, op_integer },
2564 { 0, "streaming", &try_stream, op_setint, 1,1 },
2565 { 0, "no-streaming", &try_stream, op_setint, 1,0 },
2566 {'P',"port", &port, op_integer },
2567 { 0, "inndconf", &inndconffile, op_string },
2568 {'d',"daemon", &become_daemon, op_setint, 1,1 },
2569 { 0, "no-daemon", &become_daemon, op_setint, 1,0 },
2571 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2572 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2574 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2575 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2576 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2579 int main(int argc, char **argv) {
2585 if (*arg != '-') break;
2586 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2588 while ((a= *++arg)) {
2592 char *equals= strchr(arg,'=');
2593 int len= equals ? (equals - arg) : strlen(arg);
2594 for (o=options; o->lng; o++)
2595 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2597 badusage("unknown long option --%s",arg);
2600 if (equals) badusage("option --%s does not take a value",o->lng);
2602 } else if (equals) {
2606 if (!arg) badusage("option --%s needs a value",o->lng);
2609 break; /* eaten the whole argument now */
2611 for (o=options; o->lng; o++)
2614 badusage("unknown short option -%c",a);
2621 if (!arg) badusage("option -%c needs a value",o->shrt);
2624 break; /* eaten the whole argument now */
2629 if (!arg) badusage("need site name argument");
2635 if (*++argv) badusage("too many non-option arguments");
2637 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2638 badusage("nocheck threshold percentage must be between 0..100");
2639 nocheck_thresh= nocheck_thresh_pct * 0.01;
2641 if (nocheck_decay_articles < 0.1)
2642 badusage("nocheck decay articles must be at least 0.1");
2643 nocheck_decay= 1 - 1/nocheck_decay_articles;
2646 pathoutgoing= innconf->pathoutgoing;
2647 innconf_read(inndconffile);
2650 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2651 else if (!feedfile[0])
2652 badusage("feed filename must be nonempty");
2653 else if (feedfile[strlen(feedfile)-1]=='/')
2654 feedfile= xasprintf("%s%s",feedfile,sitename);
2656 const char *feedfile_forbidden= "?*[~#";
2658 while ((c= *feedfile_forbidden++))
2659 if (strchr(feedfile, c))
2660 badusage("feed filename may not contain metacharacter %c",c);
2662 oop_source_sys *sysloop= oop_sys_new();
2663 if (!sysloop) sysdie("could not create liboop event loop");
2664 loop= (oop_source*)sysloop;
2666 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2667 sysdie("could not ignore SIGPIPE");
2669 if (become_daemon) {
2671 for (i=3; i<255; i++)
2672 /* do this now before we open syslog, etc. */
2674 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2676 int null= open("/dev/null",O_RDWR);
2677 if (null<0) sysdie("failed to open /dev/null");
2683 pid_t child1= xfork("daemonise first fork");
2684 if (child1) _exit(0);
2686 pid_t sid= setsid();
2687 if (sid != child1) sysdie("setsid failed");
2689 pid_t child2= xfork("daemonise second fork");
2690 if (child2) _exit(0);
2695 if (!filemon_method_init()) {
2696 warn("no file monitoring available, polling");
2697 filepoll_schedule();
2704 void *r= oop_sys_run(sysloop);
2705 assert(r == OOP_ERROR);
2706 sysdie("event loop failed");