3 * - actually implement badusage
4 * - options for all options
6 * - pid, sitename, hostname in lockfile
11 * Newsfeeds file entries should look like this:
12 * host.name.of.site[/exclude,exclude,...]\
13 * :pattern,pattern...[/distribution,distribution...]\
17 * sitename[/exclude,exclude,...]\
18 * :pattern,pattern...[/distribution,distribution...]\
24 * or might be blanked out
25 * <spc><spc><spc><spc>....
27 * F site.name main feed file
28 * opened/created, then written, by innd
31 * tokens blanked out by duct when processed
32 * site.name_lock lock preventing multiple ducts
33 * to hold lock must open,F_SETLK[W]
34 * and then stat to check that locked file
35 * still has name site.name_lock
36 * holder of this lock is "duct"
37 * (only) lockholder may remove the lockfile
38 * D site.name_flushing temporary feed file during flush (or crash)
39 * hardlink created by duct
41 * site.name_defer 431'd articles, still being written,
42 * created, written, used by duct
44 * site.name_backlog.<date>.<inum>
45 * 431'd articles, ready for innxmit or duct
46 * created (link/mv) by duct
47 * site.name_backlog<anything-else> (where <anything-else> does not
48 * contain '#' or '~') eg
49 * site.name_backlog.manual
50 * anything the sysadmin likes (eg, feed files
51 * from old feeds to be merged into this one)
52 * created (link/mv) by admin
53 * may be symlinks (in which case links
54 * may be written through, but only links
57 * It is safe to remove backlog files manually,
58 * if it's desired to throw away the backlog.
60 * Backlog files are also processed by innduct. We find the oldest
61 * backlog file which is at least a certain amount old, and feed it
62 * back into our processing. When every article in it has been read
63 * and processed, we unlink it and look for another backlog file.
65 * If we don't have a backlog file that we're reading, we close the
66 * defer file that we're writing and make it into a backlog file at
67 * the first convenient opportunity.
78 | | <----------------<---------------------------------'|
84 | F: innd writing, duct reading |
87 | | duct decides time to flush |
88 | | duct makes hardlink |
90 | V <------------------------'|
92 | F == D: innd writing, duct reading both exist |
95 | | <-----------<-------------<--'|
99 | V <---------------------. |
102 | D: innd writing, duct reading; or ENOENT | |
104 | | duct requests flush of feed | |
105 | | (others can too, harmlessly) | |
109 | D: innd flushing, duct; or ENOENT | |
111 | | inndcomm flush fails | |
112 | |`-------------------------->------------------' |
114 | | inndcomm reports no such site |
115 | |`---------------------------------------------------- | -.
117 | | innd finishes writing D, creates F | |
118 | | inndcomm reports flush successful | |
121 | Separated <----------------' |
122 | F: innd writing F!=D /
123 | D: duct reading; or ENOENT both exist /
125 | | duct gets to the end of D /
126 | | duct opens F too /
129 | F: innd writing, duct reading |
130 | D: duct finishing V
132 | | duct finishes processing D F: ENOENT
133 | V duct unlinks D D: duct reading
135 `--<--' | duct finishes
145 "duct reading" means innduct is reading the file but also
146 overwriting processed tokens.
150 * rune for printing diagrams:
152 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
157 /*============================== PROGRAM ==============================*/
159 #define _GNU_SOURCE 1
165 #include "inndcomm.h"
167 #include "inn/list.h"
168 #include "inn/innconf.h"
171 #include <sys/types.h>
172 #include <sys/wait.h>
173 #include <sys/stat.h>
174 #include <sys/socket.h>
190 #include <oop-read.h>
192 /*----- general definitions, probably best not changed -----*/
194 #define CONNCHILD_ESTATUS_STREAM 4
195 #define CONNCHILD_ESTATUS_NOSTREAM 5
197 #define INNDCOMMCHILD_ESTATUS_FAIL 6
198 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
200 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
202 #define VA va_list al; va_start(al,fmt)
203 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
204 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
206 /*----- doubly linked lists -----*/
208 #define ISNODE(T) struct { T *succ, *pred; } node /* must be at start */
209 #define DEFLIST(T) typedef struct { T *hd, *tl, *tp; int count; } T##List
211 #define NODE(n) (assert((void*)&(n)->node == &(n)), \
212 (struct node*)&(n)->node)
214 #define LIST_CHECKCANHAVENODE(l,n) \
215 ((void)((n) == ((l).hd))) /* just for the type check */
217 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
218 ( LIST_CHECKCANHAVENODE(l,n), \
219 list_addsomehow((struct list*)&(l), NODE((n))), \
223 #define LIST_REMSOMEHOW(l,list_remsomehow) \
227 list_remsomehow((struct list*)&(l)) ) \
233 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
234 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
235 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
236 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
238 #define LIST_INIT(l) ((l).hd, list_new((struct list*)&(l)))
239 #define LIST_HEAD(l) ((typeof((l).hd))(list_head((struct list*)&(l))))
240 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
241 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
243 #define LIST_REMOVE(l,n) \
244 ( LIST_CHECKCANHAVENODE(l,n), \
245 list_remove(NODE((n))), \
249 #define LIST_INSERT(l,n,pred) \
250 ( LIST_CHECKCANHAVENODE(l,n), \
251 LIST_CHECKCANHAVENODE(l,pred), \
252 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
256 /*----- type predeclarations -----*/
258 typedef struct Conn Conn;
259 typedef struct Article Article;
260 typedef struct InputFile InputFile;
261 typedef struct XmitDetails XmitDetails;
262 typedef struct Filemon_Perfile Filemon_Perfile;
263 typedef enum StateMachineState StateMachineState;
268 /*----- function predeclarations -----*/
270 static void conn_maybe_write(Conn *conn);
271 static void conn_make_some_xmits(Conn *conn);
272 static void *conn_write_some_xmits(Conn *conn);
274 static void xmit_free(XmitDetails *d);
276 #define SMS(newstate, periods, why) \
277 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
278 static void statemc_setstate(StateMachineState newsms, int periods,
279 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_assign_articles(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(void);
292 static void open_defer(void);
293 static void close_defer(void);
294 static void search_backlog_file(void);
296 static void inputfile_reading_start(InputFile *ipf);
297 static void inputfile_reading_stop(InputFile *ipf);
299 static void filemon_start(InputFile *ipf);
300 static void filemon_stop(InputFile *ipf);
301 static void filemon_callback(InputFile *ipf);
303 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
304 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
306 /*----- configuration options -----*/
308 static const char *sitename, *feedfile, *pathoutgoing;
309 static const char *remote_host;
310 static int quiet_multiple=0, become_daemon=1;
312 static int max_connections=10, max_queue_per_conn=200;
313 static int target_max_feedfile_size=100000;
315 static int period_seconds=60;
317 static double max_bad_data_ratio= 0.01;
318 static int max_bad_data_initial= 30;
319 /* in one corrupt 4096-byte block the number of newlines has
320 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
322 static int connection_setup_timeout=200, port=119, try_stream=1;
323 static int inndcomm_flush_timeout=100;
324 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
325 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
326 static int spontaneous_flush_periods, need_activity_periods;
327 static const char *inndconffile;
329 static double nocheck_thresh_pct= 95.0;
330 static double nocheck_thresh; /* computed in main from _pct */
331 static double nocheck_decay_articles= 100; /* converted to _decay */
332 static double nocheck_decay; /* computed in main from _articles */
335 /*----- statistics -----*/
337 typedef enum { /* in queue in conn->sent */
338 art_Unchecked, /* not checked, not sent checking */
339 art_Wanted, /* checked, wanted sent body as requested */
340 art_Unsolicited, /* - sent body without check */
344 #define RESULT_COUNTS(RCS,RCN) \
352 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
353 #define RCI_TRIPLE_VALS_BASE(counts,x) \
354 counts[art_Unchecked] x \
355 + counts[art_Wanted] x \
356 + counts[art_Unsolicited] x, \
357 counts[art_Unchecked] x \
358 , counts[art_Wanted] x \
359 , counts[art_Unsolicited] x
362 #define RC_INDEX(x) RC_##x,
363 RESULT_COUNTS(RC_INDEX, RC_INDEX)
368 /*----- transmission buffers -----*/
373 xk_Malloc, xk_Const, xk_Artdata
385 /*----- core operational data structure types -----*/
388 /* This is also an instance of struct oop_readable */
389 struct oop_readable readable; /* first */
390 oop_readable_call *readable_callback;
391 void *readable_callback_user;
394 Filemon_Perfile *filemon;
396 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
397 long inprogress; /* no. of articles read but not processed */
401 int counts[art_MaxState][RCI_max];
402 int readcount_ok, readcount_blank, readcount_err;
417 #define SMS_LIST(X) \
425 enum StateMachineState {
426 #define SMS_DEF_ENUM(s) sm_##s,
427 SMS_LIST(SMS_DEF_ENUM)
430 static const char *sms_names[]= {
431 #define SMS_DEF_NAME(s) #s ,
432 SMS_LIST(SMS_DEF_NAME)
438 int fd; /* may be 0, meaning closed (during construction/destruction) */
439 int max_queue, stream, quitting;
440 int since_activity; /* periods */
441 ArticleList waiting; /* not yet told peer */
442 ArticleList priority; /* peer says send it now */
443 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
444 struct iovec xmit[CONNIOVS];
445 XmitDetails xmitd[CONNIOVS];
450 /*----- general operational variables -----*/
452 /* main initialises */
453 static oop_source *loop;
454 static ConnList conns;
455 static ArticleList queue;
456 static char *path_lock, *path_flushing, *path_defer, *globpat_backlog;
458 /* statemc_init initialises */
459 static StateMachineState sms;
461 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
462 static int sm_period_counter;
464 /* initialisation to 0 is good */
465 static int until_connect, until_backlog_nextscan;
466 static double accept_proportion;
467 static int nocheck, nocheck_reported;
469 /*========== logging ==========*/
471 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
472 static void logcore(int sysloglevel, const char *fmt, ...) {
475 vsyslog(sysloglevel,fmt,al);
477 vfprintf(stderr,fmt,al);
483 static void logv(int sysloglevel, const char *pfx, int errnoval,
484 const char *fmt, va_list al) PRINTF(5,0);
485 static void logv(int sysloglevel, const char *pfx, int errnoval,
486 const char *fmt, va_list al) {
487 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
488 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
489 msgbuf[sizeof(msgbuf)-1]= 0;
491 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
492 sysloglevel= LOG_ERR; /* run by wrong user, probably */
494 logcore(sysloglevel, "<%s>%s: %s%s%s",
495 sitename, pfx, msgbuf,
496 errnoval>=0 ? ": " : "",
497 errnoval>=0 ? strerror(errnoval) : "");
500 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
501 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
502 static void fn(const char *fmt, ...) { \
504 logv(sysloglevel, pfx, err, fmt, al); \
508 #define logwrap(fn, pfx, sysloglevel, err) \
509 static void fn(const char *fmt, ...) PRINTF(1,2); \
510 static void fn(const char *fmt, ...) { \
512 logv(sysloglevel, pfx, err, fmt, al); \
516 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
517 diewrap(die, " critical", LOG_CRIT, -1, 16);
519 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
520 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
522 logwrap(syswarn, " warning", LOG_WARNING, errno);
523 logwrap(warn, " warning", LOG_WARNING, -1);
525 logwrap(notice, "", LOG_NOTICE, -1);
526 logwrap(info, " info", LOG_INFO, -1);
527 logwrap(debug, " debug", LOG_DEBUG, -1);
530 /*========== utility functions etc. ==========*/
532 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
533 static char *xvasprintf(const char *fmt, va_list al) {
535 int rc= vasprintf(&str,fmt,al);
536 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
539 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
540 static char *xasprintf(const char *fmt, ...) {
542 char *str= xvasprintf(fmt,al);
547 static int close_perhaps(int *fd) {
553 static void xclose(int fd, const char *what, const char *what2) {
555 if (r) sysdie("close %s%s",what,what2?what2:"");
557 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
559 xclose(*fd,what,what2);
563 static pid_t xfork(const char *what) {
567 if (child==-1) sysdie("cannot fork for %s",what);
568 debug("forked %s %ld", what, (unsigned long)child);
569 if (!child) postfork();
573 static void on_fd_read_except(int fd, oop_call_fd callback) {
574 loop->on_fd(loop, fd, OOP_READ, callback, 0);
575 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
577 static void cancel_fd_read_except(int fd) {
578 loop->cancel_fd(loop, fd, OOP_READ);
579 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
582 static void report_child_status(const char *what, int status) {
583 if (WIFEXITED(status)) {
584 int es= WEXITSTATUS(status);
586 warn("%s: child died with error exit status %d", what, es);
587 } else if (WIFSIGNALED(status)) {
588 int sig= WTERMSIG(status);
589 const char *sigstr= strsignal(sig);
590 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
592 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
594 warn("%s: child died due to unknown fatal signal %d%s",
595 what, sig, coredump);
597 warn("%s: child died with unknown wait status %d", what,status);
601 static int xwaitpid(pid_t *pid, const char *what) {
604 int r= kill(*pid, SIGKILL);
605 if (r) sysdie("cannot kill %s child", what);
607 pid_t got= waitpid(*pid, &status, WNOHANG);
608 if (got==-1) sysdie("cannot reap %s child", what);
615 static void xunlink(const char *path, const char *what) {
617 if (r) sysdie("can't unlink %s %s", path, what);
620 static time_t xtime(void) {
622 if (now==-1) sysdie("time(2) failed");
625 static void check_isreg(const struct stat *stab, const char *path,
627 if (!S_ISREG(stab->st_mode))
628 die("%s %s not a plain file (mode 0%lo)",
629 what, path, (unsigned long)stab->st_mode);
632 static void xfstat(int fd, struct stat *stab_r, const char *what) {
633 int r= fstat(fd, stab_r);
634 if (r) sysdie("could not fstat %s", what);
637 static void xfstat_isreg(int fd, struct stat *stab_r,
638 const char *path, const char *what) {
639 xfstat(fd, stab_r, what);
640 check_isreg(stab_r, path, what);
643 static void xlstat_isreg(const char *path, struct stat *stab,
644 int *enoent_r /* 0 means ENOENT is fatal */,
646 int r= lstat(path, stab);
648 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
649 sysdie("could not lstat %s %s", what, path);
651 if (enoent_r) *enoent_r= 0;
652 check_isreg(stab, path, what);
655 static void setnonblock(int fd, int nonblocking) {
656 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
657 if (nonblocking) r |= O_NONBLOCK;
658 else r &= ~O_NONBLOCK;
659 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
662 static int samefile(const struct stat *a, const struct stat *b) {
663 assert(S_ISREG(a->st_mode));
664 assert(S_ISREG(b->st_mode));
665 return (a->st_ino == b->st_ino &&
666 a->st_dev == b->st_dev);
669 static char *sanitise(const char *input) {
670 static char sanibuf[100]; /* returns pointer to this buffer! */
672 const char *p= input;
676 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
678 if (!c) { *q++= '\''; *q=0; break; }
679 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
680 sprintf(q,"\\x%02x",c);
686 static int isewouldblock(int errnoval) {
687 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
690 /*========== management of connections ==========*/
692 static void conn_closefd(Conn *conn, const char *msgprefix) {
693 int r= close_perhaps(&conn->fd);
694 if (r) info("C%d %serror closing socket: %s",
695 conn->fd, msgprefix, strerror(errno));
698 static void conn_dispose(Conn *conn) {
701 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
702 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
704 conn_closefd(conn,"");
706 until_connect= reconnect_delay_periods;
709 static void *conn_exception(oop_source *lp, int fd,
710 oop_event ev, void *conn_v) {
713 assert(fd == conn->fd);
714 assert(ev == OOP_EXCEPTION);
715 int r= read(conn->fd, &ch, 1);
716 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
717 else connfail(conn,"exceptional condition on socket (peer sent urgent"
718 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
722 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
723 int requeue[art_MaxState];
726 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
727 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
728 while ((art= LIST_REMHEAD(conn->sent))) {
729 requeue[art->state]++;
730 if (art->state==art_Unsolicited) art->state= art_Unchecked;
731 LIST_ADDTAIL(queue,art);
736 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
739 char *m= xvasprintf(fmt,al);
740 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
741 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
744 LIST_REMOVE(conns,conn);
746 check_assign_articles();
749 static void connfail(Conn *conn, const char *fmt, ...) {
752 vconnfail(conn,fmt,al);
756 static void check_idle_conns(void) {
758 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
759 conn->since_activity++;
761 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
762 if (conn->since_activity <= need_activity_periods) continue;
764 /* We need to shut this down */
766 connfail(conn,"timed out waiting for response to QUIT");
767 else if (conn->sent.count)
768 connfail(conn,"timed out waiting for responses");
769 else if (conn->waiting.count || conn->priority.count)
770 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
771 else if (conn->xmitu)
772 connfail(conn,"peer has been sending responses"
773 " before receiving our commands!");
775 static const char quitcmd[]= "QUIT\r\n";
776 int todo= sizeof(quitcmd)-1;
777 const char *p= quitcmd;
779 int r= write(conn->fd, p, todo);
781 if (isewouldblock(errno))
782 connfail(conn, "blocked writing QUIT to idle connection");
784 connfail(conn, "failed to write QUIT to idle connection: %s",
792 conn->since_activity= 0;
793 debug("C%d is idle, quitting", conn->fd);
802 /*---------- making new connections ----------*/
804 static pid_t connecting_child;
805 static int connecting_fdpass_sock;
807 static void connect_attempt_discard(void) {
808 if (connecting_child) {
809 int r= kill(connecting_child, SIGTERM);
810 if (r) syswarn("failed to kill connecting child");
811 int status= xwaitpid(&connecting_child, "connect");
813 if (!(WIFEXITED(status) ||
814 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
815 report_child_status("connect", status);
817 if (connecting_fdpass_sock) {
818 cancel_fd_read_except(connecting_fdpass_sock);
819 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
823 #define PREP_DECL_MSG_CMSG(msg) \
825 memset(&msg,0,sizeof(msg)); \
826 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
827 msg.msg_control= msg##cbuf; \
828 msg.msg_controllen= sizeof(msg##cbuf);
830 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
833 assert(fd == connecting_fdpass_sock);
835 conn= xmalloc(sizeof(*conn));
836 memset(conn,0,sizeof(*conn));
838 PREP_DECL_MSG_CMSG(msg);
839 struct cmsghdr *h= 0;
840 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
841 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
844 pid_t got= waitpid(connecting_child, &status, WNOHANG);
846 assert(got==connecting_child);
848 if (WIFEXITED(status)) {
849 if (WEXITSTATUS(status) != 0 &&
850 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
851 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
852 /* child already reported the problem */;
854 warn("connect: connection child exited code %d but no cmsg",
855 WEXITSTATUS(status));
856 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
857 warn("connect: connection attempt timed out");
859 report_child_status("connect", status);
862 /* child is still running apparently, report the socket problem */
864 syswarn("connect: read from fdpass socket failed");
865 else if (e == OOP_EXCEPTION)
866 warn("connect: unexpected exception on fdpass socket");
868 warn("connect: unexpected EOF on fdpass socket");
870 fatal("connect: unexpected lack of cmsg from child");
875 #define CHK(field, val) \
876 if (h->cmsg_##field != val) { \
877 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
880 CHK(level, SOL_SOCKET);
881 CHK(type, SCM_RIGHTS);
882 CHK(len, CMSG_LEN(sizeof(conn->fd)));
885 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
887 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
888 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
891 pid_t got= waitpid(connecting_child, &status, 0);
892 if (got==-1) sysdie("connect: real wait for child");
893 assert(got == connecting_child);
896 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
897 int es= WEXITSTATUS(status);
899 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
900 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
902 fatal("connect: child gave unexpected exit status %d", es);
906 LIST_INIT(conn->waiting);
907 LIST_INIT(conn->priority);
908 LIST_INIT(conn->sent);
909 setnonblock(conn->fd, 1);
910 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
911 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
912 LIST_ADDHEAD(conns, conn);
914 connect_attempt_discard();
915 check_assign_articles();
920 connect_attempt_discard();
923 static int allow_connect_start(void) {
924 return conns.count < max_connections
929 static void connect_start(void) {
930 assert(!connecting_child);
931 assert(!connecting_fdpass_sock);
933 notice("starting connection attempt");
936 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
937 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
939 connecting_child= xfork("connection");
941 if (!connecting_child) {
942 FILE *cn_from, *cn_to;
943 char buf[NNTP_STRLEN+100];
944 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
946 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
948 alarm(connection_setup_timeout);
949 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
950 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
951 else sysfatal("connect: connection attempt failed");
953 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
954 sysfatal("connect: authentication failed");
956 if (fputs("MODE STREAM\r\n", cn_to) ||
958 sysfatal("connect: could not send MODE STREAM");
959 buf[sizeof(buf)-1]= 0;
960 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
962 sysfatal("connect: could not read response to MODE STREAM");
964 fatal("connect: connection close in response to MODE STREAM");
969 fatal("connect: response to MODE STREAM is too long: %.100s...",
970 remote_host, sanitise(buf));
971 l--; if (l>0 && buf[l-1]=='\r') l--;
974 int rcode= strtoul(buf,&ep,10);
976 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
980 exitstatus= CONNCHILD_ESTATUS_STREAM;
986 warn("connect: unexpected response to MODE STREAM: %.50s",
992 int fd= fileno(cn_from);
994 PREP_DECL_MSG_CMSG(msg);
995 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
996 cmsg->cmsg_level= SOL_SOCKET;
997 cmsg->cmsg_type= SCM_RIGHTS;
998 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
999 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1001 msg.msg_controllen= cmsg->cmsg_len;
1002 r= sendmsg(socks[1], &msg, 0);
1003 if (r) sysdie("sendmsg failed for new connection");
1008 xclose(socks[1], "connecting fdpass child's socket",0);
1009 connecting_fdpass_sock= socks[0];
1010 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1013 /*---------- assigning articles to conns, and transmitting ----------*/
1015 static void check_assign_articles(void) {
1023 /* Find a connection to offer this article. We prefer a busy
1024 * connection to an idle one, provided it's not full. We take the
1025 * first (oldest) and since that's stable, it will mean we fill up
1026 * connections in order. That way if we have too many
1027 * connections, the spare ones will go away eventually.
1029 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1030 if (walk->quitting) continue;
1031 inqueue= walk->sent.count + walk->priority.count
1032 + walk->waiting.count;
1033 spare= walk->max_queue - inqueue;
1034 assert(inqueue <= max_queue_per_conn);
1036 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1037 else if (spare>0) /*working*/ { use= walk; break; }
1040 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1042 Article *art= LIST_REMHEAD(queue);
1043 LIST_ADDTAIL(use->waiting, art);
1046 conn_maybe_write(use);
1047 } else if (allow_connect_start()) {
1048 until_connect= reconnect_delay_periods;
1057 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1058 conn_maybe_write(u);
1059 return OOP_CONTINUE;
1062 static void conn_maybe_write(Conn *conn) {
1065 conn_make_some_xmits(conn);
1067 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1071 void *rp= conn_write_some_xmits(conn);
1072 if (rp==OOP_CONTINUE) {
1073 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1075 } else if (rp==OOP_HALT) {
1078 /* transmitted everything */
1085 /*========== article transmission ==========*/
1087 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1088 XmitKind kind) { /* caller must then fill in details */
1089 struct iovec *v= &conn->xmit[conn->xmitu];
1090 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1091 v->iov_base= (char*)data;
1097 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1098 xmit_core(conn,data,len, xk_Const);
1100 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1102 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1103 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1107 static void xmit_free(XmitDetails *d) {
1109 case xk_Malloc: free(d->info.malloc_tofree); break;
1110 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1111 case xk_Const: break;
1116 static void *conn_write_some_xmits(Conn *conn) {
1118 * 0: nothing more to write, no need to call us again
1119 * OOP_CONTINUE: more to write but fd not writeable
1120 * OOP_HALT: disaster, have destroyed conn
1123 int count= conn->xmitu;
1124 if (!count) return 0;
1126 if (count > IOV_MAX) count= IOV_MAX;
1127 ssize_t rs= writev(conn->fd, conn->xmit, count);
1129 if (isewouldblock(errno)) return OOP_CONTINUE;
1130 connfail(conn, "write failed: %s", strerror(errno));
1136 for (done=0; rs && done<conn->xmitu; done++) {
1137 struct iovec *vp= &conn->xmit[done];
1138 XmitDetails *dp= &conn->xmitd[done];
1139 if (rs > vp->iov_len) {
1147 int newu= conn->xmitu - done;
1148 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1149 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1154 static void conn_make_some_xmits(Conn *conn) {
1156 if (conn->xmitu+5 > CONNIOVS)
1159 Article *art= LIST_REMHEAD(conn->priority);
1160 if (!art) art= LIST_REMHEAD(conn->waiting);
1163 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1164 /* actually send it */
1166 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1170 XMIT_LITERAL("TAKETHIS ");
1171 xmit_noalloc(conn, art->messageid, art->midlen);
1172 XMIT_LITERAL("\r\n");
1173 xmit_artbody(conn, artdata);
1176 /* we got 235 from IHAVE */
1178 xmit_artbody(conn, artdata);
1180 XMIT_LITERAL(".\r\n");
1185 art->state == art_Unchecked ? art_Unsolicited :
1186 art->state == art_Wanted ? art_Wanted :
1188 art->ipf->counts[art->state][RC_sent]++;
1189 LIST_ADDTAIL(conn->sent, art);
1195 XMIT_LITERAL("IHAVE ");
1197 XMIT_LITERAL("CHECK ");
1198 xmit_noalloc(conn, art->messageid, art->midlen);
1199 XMIT_LITERAL("\r\n");
1201 assert(art->state == art_Unchecked);
1202 art->ipf->counts[art->state][RC_sent]++;
1203 LIST_ADDTAIL(conn->sent, art);
1209 /*========== handling responses from peer ==========*/
1211 static const oop_rd_style peer_rd_style= {
1212 OOP_RD_DELIM_STRIP, '\n',
1214 OOP_RD_SHORTREC_FORBID
1217 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1218 const char *errmsg, int errnoval,
1219 const char *data, size_t recsz, void *conn_v) {
1221 connfail(conn, "error receiving from peer: %s", errmsg);
1222 return OOP_CONTINUE;
1225 static Article *article_reply_check(Conn *conn, const char *response,
1226 int code_indicates_streaming,
1228 /* 1:yes, -1:no, 0:dontcare */,
1229 const char *sanitised_response) {
1230 Article *art= LIST_HEAD(conn->sent);
1234 "peer gave unexpected response when no commands outstanding: %s",
1235 sanitised_response);
1239 if (code_indicates_streaming) {
1240 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1241 if (!conn->stream) {
1242 connfail(conn, "peer gave streaming response code "
1243 " to IHAVE or subsequent body: %s", sanitised_response);
1246 const char *got_mid= response+4;
1247 int got_midlen= strcspn(got_mid, " \n\r");
1248 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1249 connfail(conn, "peer gave streaming response with syntactically invalid"
1250 " messageid: %s", sanitised_response);
1253 if (got_midlen != art->midlen ||
1254 memcmp(got_mid, art->messageid, got_midlen)) {
1255 connfail(conn, "peer gave streaming response code to wrong article -"
1256 " probable synchronisation problem; we offered: %s;"
1258 art->messageid, sanitised_response);
1263 connfail(conn, "peer gave non-streaming response code to"
1264 " CHECK/TAKETHIS: %s", sanitised_response);
1269 if (must_have_sent>0 && art->state < art_Wanted) {
1270 connfail(conn, "peer says article accepted but"
1271 " we had not sent the body: %s", sanitised_response);
1274 if (must_have_sent<0 && art->state >= art_Wanted) {
1275 connfail(conn, "peer says please sent the article but we just did: %s",
1276 sanitised_response);
1280 Article *art_again= LIST_REMHEAD(conn->sent);
1281 assert(art_again == art);
1285 static void update_nocheck(int accepted) {
1286 accept_proportion *= nocheck_decay;
1287 accept_proportion += accepted * (1.0 - nocheck_decay);
1288 int new_nocheck= accept_proportion >= nocheck_thresh;
1289 if (new_nocheck && !nocheck_reported) {
1290 notice("entering nocheck mode for the first time");
1291 nocheck_reported= 1;
1292 } else if (new_nocheck != nocheck) {
1293 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1295 nocheck= new_nocheck;
1298 static void article_done(Conn *conn, Article *art, int whichcount) {
1299 art->ipf->counts[art->state][whichcount]++;
1300 if (whichcount == RC_accepted) update_nocheck(1);
1301 else if (whichcount == RC_unwanted) update_nocheck(0);
1303 InputFile *ipf= art->ipf;
1305 while (art->blanklen) {
1306 static const char spaces[]=
1311 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1312 int r= pwrite(ipf->fd, spaces, w, art->offset);
1314 if (errno==EINTR) continue;
1315 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1316 art->messageid, art->blanklen, art->offset, ipf->path);
1318 assert(r>=0 && r<=w);
1324 assert(ipf->inprogress >= 0);
1327 if (!ipf->inprogress && ipf != main_input_file)
1328 queue_check_input_done();
1331 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1332 const char *errmsg, int errnoval,
1333 const char *data, size_t recsz, void *conn_v) {
1336 if (ev == OOP_RD_EOF) {
1337 connfail(conn, "unexpected EOF from peer");
1338 return OOP_CONTINUE;
1340 assert(ev == OOP_RD_OK);
1342 char *sani= sanitise(data);
1345 unsigned long code= strtoul(data, &ep, 10);
1346 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1347 connfail(conn, "badly formatted response from peer: %s", sani);
1348 return OOP_CONTINUE;
1351 if (conn->quitting) {
1352 if (code!=205 && code!=503) {
1353 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1355 notice("C%d idle connection closed", conn->fd);
1356 assert(!conn->waiting.count);
1357 assert(!conn->priority.count);
1358 assert(!conn->sent.count);
1359 assert(!conn->xmitu);
1360 LIST_REMOVE(conns,conn);
1363 return OOP_CONTINUE;
1366 conn->since_activity= 0;
1369 #define GET_ARTICLE(musthavesent) \
1370 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1371 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1373 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1374 code_streaming= (streaming); \
1375 GET_ARTICLE(musthavesent); \
1376 article_done(conn, art, RC_##how); break;
1378 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1380 int code_streaming= 0;
1384 case 400: PEERBADMSG("peer stopped accepting articles");
1385 case 503: PEERBADMSG("peer timed us out");
1386 default: PEERBADMSG("peer sent unexpected message");
1388 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1389 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1391 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1392 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1394 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1395 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1397 case 238: /* CHECK says send it */
1399 case 335: /* IHAVE says send it */
1401 assert(art->state == art_Unchecked);
1402 art->ipf->counts[art->state][RC_accepted]++;
1403 art->state= art_Wanted;
1404 LIST_ADDTAIL(conn->priority, art);
1407 case 431: /* CHECK or TAKETHIS says try later */
1409 case 436: /* IHAVE says try later */
1412 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1414 sysfatal("write to defer file %s",path_defer);
1415 article_done(conn, art, RC_deferred);
1420 conn_maybe_write(conn);
1421 check_assign_articles();
1422 return OOP_CONTINUE;
1426 /*========== monitoring of input files ==========*/
1428 static void feedfile_eof(InputFile *ipf) {
1429 assert(ipf != main_input_file); /* promised by tailing_try_read */
1430 inputfile_reading_stop(ipf);
1432 if (ipf == flushing_input_file) {
1433 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1434 if (main_input_file) inputfile_reading_start(main_input_file);
1435 statemc_check_flushing_done();
1436 } else if (ipf == backlog_input_file) {
1437 statemc_check_backlog_done();
1439 abort(); /* supposed to wait rather than get EOF on main input file */
1443 static InputFile *open_input_file(const char *path) {
1444 int fd= open(path, O_RDONLY);
1446 if (errno==ENOENT) return 0;
1447 sysfatal("unable to open input file %s", path);
1451 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1452 memset(ipf,0,sizeof(*ipf));
1455 strcpy(ipf->path, path);
1460 static void close_input_file(InputFile *ipf) { /* does not free */
1461 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1462 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1463 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1464 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1465 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1469 /*---------- dealing with articles read in the input file ----------*/
1471 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1472 const char *data, const char *how) {
1473 warn("corrupted file: %s, offset %lu: %s: %s",
1474 ipf->path, (unsigned long)offset, how, sanitise(data));
1475 ipf->readcount_err++;
1476 if (ipf->readcount_err > max_bad_data_initial +
1477 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1478 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1479 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1480 return OOP_CONTINUE;
1483 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1484 oop_rd_event ev, const char *errmsg,
1485 int errnoval, const char *data, size_t recsz,
1487 InputFile *ipf= ipf_v;
1488 assert(ev == OOP_RD_SYSTEM);
1490 sysdie("error reading input file: %s, offset %lu",
1491 ipf->path, (unsigned long)ipf->offset);
1494 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1495 oop_rd_event ev, const char *errmsg,
1496 int errnoval, const char *data, size_t recsz,
1498 InputFile *ipf= ipf_v;
1500 char tokentextbuf[sizeof(TOKEN)*2+3];
1502 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1504 off_t old_offset= ipf->offset;
1505 ipf->offset += recsz + 1;
1507 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1509 if (ev==OOP_RD_PARTREC)
1510 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1511 /* but process it anyway */
1513 if (ipf->skippinglong) {
1514 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1517 if (ev==OOP_RD_LONG) {
1518 ipf->skippinglong= 1;
1519 X_BAD_DATA("overly long line");
1522 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1523 if (!recsz) X_BAD_DATA("empty line");
1526 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1527 ipf->readcount_blank++;
1528 return OOP_CONTINUE;
1531 char *space= strchr(data,' ');
1532 int tokenlen= space-data;
1533 int midlen= (int)recsz-tokenlen-1;
1534 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1535 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1537 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1538 memcpy(tokentextbuf, data, tokenlen);
1539 tokentextbuf[tokenlen]= 0;
1540 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1542 ipf->readcount_ok++;
1544 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1545 art->state= art_Unchecked;
1546 art->midlen= midlen;
1547 art->ipf= ipf; ipf->inprogress++;
1548 art->token= TextToToken(tokentextbuf);
1549 art->offset= ipf->offset;
1550 art->blanklen= recsz;
1551 strcpy(art->messageid, space+1);
1552 LIST_ADDTAIL(queue, art);
1554 if (sms==sm_NORMAL && ipf==main_input_file &&
1555 ipf->offset >= target_max_feedfile_size)
1556 statemc_start_flush("feed file size");
1558 check_assign_articles();
1559 return OOP_CONTINUE;
1562 /*========== tailing input file ==========*/
1564 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1566 InputFile *ipf= user;
1567 return ipf->readable_callback(loop, &ipf->readable,
1568 ipf->readable_callback_user);
1571 static void tailing_on_cancel(struct oop_readable *rable) {
1572 InputFile *ipf= (void*)rable;
1574 if (ipf->filemon) filemon_stop(ipf);
1575 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1576 ipf->readable_callback= 0;
1579 static void tailing_queue_readable(InputFile *ipf) {
1580 /* lifetime of ipf here is OK because destruction will cause
1581 * on_cancel which will cancel this callback */
1582 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1585 static int tailing_on_readable(struct oop_readable *rable,
1586 oop_readable_call *cb, void *user) {
1587 InputFile *ipf= (void*)rable;
1589 tailing_on_cancel(rable);
1590 ipf->readable_callback= cb;
1591 ipf->readable_callback_user= user;
1594 tailing_queue_readable(ipf);
1598 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1600 InputFile *ipf= (void*)rable;
1602 ssize_t r= read(ipf->fd, buffer, length);
1604 if (errno==EINTR) continue;
1608 if (ipf==main_input_file) {
1611 } else if (ipf==flushing_input_file) {
1613 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1614 } else if (ipf==backlog_input_file) {
1624 /*---------- filemon implemented with inotify ----------*/
1626 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1627 #define HAVE_FILEMON
1629 #include <linux/inotify.h>
1631 static int filemon_inotify_fd;
1632 static int filemon_inotify_wdmax;
1633 static InputFile **filemon_inotify_wd2ipf;
1635 struct Filemon_Perfile {
1639 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1640 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1641 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1643 if (wd >= filemon_inotify_wdmax) {
1645 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1646 sizeof(*filemon_inotify_wd2ipf) * newmax);
1647 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1648 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1649 filemon_inotify_wdmax= newmax;
1652 assert(!filemon_inotify_wd2ipf[wd]);
1653 filemon_inotify_wd2ipf[wd]= ipf;
1655 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1656 ipf, wd, filemon_inotify_wdmax);
1661 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1663 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1664 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1665 if (r) sysdie("inotify_rm_watch");
1666 filemon_inotify_wd2ipf[wd]= 0;
1669 static void *filemon_inotify_readable(oop_source *lp, int fd,
1670 oop_event e, void *u) {
1671 struct inotify_event iev;
1673 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1675 if (isewouldblock(errno)) break;
1676 sysdie("read from inotify master");
1677 } else if (r==sizeof(iev)) {
1678 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1680 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1682 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1683 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1684 filemon_callback(ipf);
1686 return OOP_CONTINUE;
1689 static int filemon_method_init(void) {
1690 filemon_inotify_fd= inotify_init();
1691 if (filemon_inotify_fd<0) {
1692 syswarn("could not initialise inotify: inotify_init failed");
1696 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1698 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1702 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1704 /*---------- filemon dummy implementation ----------*/
1706 #if !defined(HAVE_FILEMON)
1708 struct Filemon_Perfile { int dummy; };
1710 static int filemon_method_init(void) { return 0; }
1711 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1712 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1714 #endif /* !HAVE_FILEMON */
1716 /*---------- filemon generic interface ----------*/
1718 static void filemon_start(InputFile *ipf) {
1719 assert(!ipf->filemon);
1721 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1722 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1723 filemon_method_startfile(ipf, ipf->filemon);
1726 static void filemon_stop(InputFile *ipf) {
1727 if (!ipf->filemon) return;
1728 filemon_method_stopfile(ipf, ipf->filemon);
1733 static void filemon_callback(InputFile *ipf) {
1734 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1737 /*---------- interface to start and stop an input file ----------*/
1739 static const oop_rd_style feedfile_rdstyle= {
1740 OOP_RD_DELIM_STRIP, '\n',
1742 OOP_RD_SHORTREC_LONG,
1745 static void inputfile_reading_start(InputFile *ipf) {
1747 ipf->readable.on_readable= tailing_on_readable;
1748 ipf->readable.on_cancel= tailing_on_cancel;
1749 ipf->readable.try_read= tailing_try_read;
1750 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1751 ipf->readable.delete_kill= 0;
1753 ipf->readable_callback= 0;
1754 ipf->readable_callback_user= 0;
1756 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1759 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1760 feedfile_got_article,ipf, feedfile_read_err, ipf);
1761 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1764 static void inputfile_reading_stop(InputFile *ipf) {
1766 oop_rd_cancel(ipf->rd);
1767 oop_rd_delete(ipf->rd);
1769 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1773 /*========== interaction with innd - state machine ==========*/
1775 /* See official state diagram at top of file. We implement
1786 |`---------------------------------------------------.
1788 |`---------------- - - - |
1789 D ENOENT | D EXISTS see OVERALL STATES diagram |
1790 | for full startup logic |
1793 | ============ try to |
1799 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1800 ^ | hardlink F to D |
1803 | | our handle onto F is now onto D |
1806 | |<-------------------<---------------------<---------+
1808 | | spawn inndcomm flush |
1810 | ================== |
1811 | FLUSHING[-ABSENT] |
1813 | main D tail/none |
1814 | ================== |
1816 | | INNDCOMM FLUSH FAILS ^
1817 | |`----------------------->----------. |
1819 | | NO SUCH SITE V |
1820 ^ |`--------------->----. ==================== |
1821 | | \ FLUSHFAILED[-ABSENT] |
1823 | | FLUSH OK \ main D tail/none |
1824 | | open F \ ==================== |
1826 | | \ | TIME TO RETRY |
1827 | |`------->----. ,---<---'\ `----------------'
1828 | | D NONE | | D NONE `----.
1830 | ============= V V ============
1831 | SEPARATED-1 | | DROPPING-1
1832 | flsh->rd!=0 | | flsh->rd!=0
1833 | [Separated] | | [Dropping]
1834 | main F idle | | main none
1835 | old D tail | | old D tail
1836 | ============= | | ============
1838 ^ | EOF ON D | | defer | EOF ON D
1840 | =============== | | ===============
1841 | SEPARATED-2 | | DROPPING-2
1842 | flsh->rd==0 | V flsh->rd==0
1843 | [Finishing] | | [Dropping]
1844 | main F tail | `. main none
1845 | old D closed | `. old D closed
1846 | =============== V `. ===============
1848 | | ALL D PROCESSED `. | ALL D PROCESSED
1849 | V install defer as backlog `. | install defer
1850 ^ | close D `. | close D
1851 | | unlink D `. | unlink D
1854 `----------' ==============
1874 static void startup_set_input_file(InputFile *f) {
1875 assert(!main_input_file);
1877 inputfile_reading_start(f);
1880 static void statemc_init(void) {
1881 struct stat stab, stabf;
1883 path_lock= xasprintf("%s_lock", feedfile);
1884 path_flushing= xasprintf("%s_flushing", feedfile);
1885 path_defer= xasprintf("%s_defer", feedfile);
1886 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1889 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1890 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1893 memset(&fl,0,sizeof(fl));
1895 fl.l_whence= SEEK_SET;
1896 int r= fcntl(lockfd, F_SETLK, &fl);
1898 if (errno==EACCES || isewouldblock(errno)) {
1899 if (quiet_multiple) exit(0);
1900 fatal("another duct holds the lockfile");
1902 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1905 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
1907 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1909 if (!lock_noent && samefile(&stab, &stabf))
1912 xclose(lockfd, "stale lockfile ", path_lock);
1914 debug("startup: locked");
1916 search_backlog_file();
1919 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1921 debug("startup: ductdefer ENOENT");
1923 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1924 switch (stab.st_nlink==1) {
1926 open_defer(); /* so that we will later close it and rename it */
1929 xunlink(path_defer, "stale defer file link"
1930 " (presumably hardlink to backlog file)");
1933 die("defer file %s has unexpected link count %d",
1934 path_defer, stab.st_nlink);
1938 struct stat stab_f, stab_d;
1941 InputFile *file_d= open_input_file(path_flushing);
1942 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
1944 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1946 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1947 debug("startup: F==D => Hardlinked");
1948 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1953 debug("startup: F ENOENT => Moved");
1954 if (file_d) startup_set_input_file(file_d);
1955 spawn_inndcomm_flush("feedfile missing at startup");
1956 /* => Flushing, sms:=FLUSHING */
1959 debug("startup: F!=D => Separated");
1960 startup_set_input_file(file_d);
1961 SMS(SEPARATED, 0, "found both old and current feed files");
1963 debug("startup: F exists, D ENOENT => Normal");
1964 InputFile *file_f= open_input_file(feedfile);
1965 if (!file_f) die("feed file vanished during startup");
1966 startup_set_input_file(file_f);
1967 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1972 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1973 assert(sms == sm_NORMAL);
1975 debug("starting flush (%s) (%lu >?= %lu) (%d)",
1977 (unsigned long)(main_input_file ? main_input_file->offset : 0),
1978 (unsigned long)target_max_feedfile_size,
1981 int r= link(feedfile, path_flushing);
1982 if (r) sysdie("link feedfile %s to flushing file %s",
1983 feedfile, path_flushing);
1986 xunlink(feedfile, "old feedfile link");
1989 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1992 static void statemc_period_poll(void) {
1993 if (!sm_period_counter) return;
1994 sm_period_counter--;
1995 assert(sm_period_counter>=0);
1997 if (sm_period_counter) return;
2000 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2002 case sm_FLUSHFAILED:
2003 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2010 static int inputfile_is_done(InputFile *ipf) {
2012 if (ipf->inprogress) return 0; /* new article in the meantime */
2013 if (ipf->rd) return 0; /* not had EOF */
2017 static void notice_processed(InputFile *ipf, const char *what,
2019 #define RCI_NOTHING(x) /* nothing */
2020 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2021 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2023 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2025 info("processed %s%s read=%d(+%dbl,+%derr)"
2026 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2027 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2030 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2031 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2032 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2033 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2034 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2035 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2041 static void statemc_check_backlog_done(void) {
2042 InputFile *ipf= backlog_input_file;
2043 if (!inputfile_is_done(ipf)) return;
2045 const char *slash= strrchr(ipf->path, '/');
2046 const char *leaf= slash ? slash+1 : ipf->path;
2047 const char *under= strchr(slash, '_');
2048 const char *rest= under ? under+1 : leaf;
2049 if (!strncmp(rest,"backlog",7)) rest += 7;
2050 notice_processed(ipf,"backlog:",rest);
2052 close_input_file(ipf);
2053 if (unlink(ipf->path)) {
2054 if (errno != ENOENT)
2055 sysdie("could not unlink processed backlog file %s", ipf->path);
2056 warn("backlog file %s vanished while we were reading it"
2057 " so we couldn't remove it (but it's done now, anyway)",
2061 backlog_input_file= 0;
2062 search_backlog_file();
2066 static void statemc_check_flushing_done(void) {
2067 InputFile *ipf= flushing_input_file;
2068 if (!inputfile_is_done(ipf)) return;
2070 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2072 notice_processed(ipf,"feedfile",0);
2076 xunlink(path_flushing, "old flushing file");
2078 close_input_file(flushing_input_file);
2079 free(flushing_input_file);
2080 flushing_input_file= 0;
2082 if (sms==sm_SEPARATED) {
2083 notice("flush complete");
2084 SMS(NORMAL, 0, "flush complete");
2085 } else if (sms==sm_DROPPING) {
2086 SMS(DROPPED, 0, "old flush complete");
2087 search_backlog_file();
2088 notice("feed dropped, but will continue until backlog is finished");
2092 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2094 assert(!inputfile_is_done(main_input_file));
2095 statemc_check_flushing_done();
2096 statemc_check_backlog_done();
2097 return OOP_CONTINUE;
2100 static void queue_check_input_done(void) {
2101 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2104 static void statemc_setstate(StateMachineState newsms, int periods,
2105 const char *forlog, const char *why) {
2107 sm_period_counter= periods;
2109 const char *xtra= "";
2111 case sm_FLUSHING: sm_FLUSHFAILED:
2112 if (!main_input_file) xtra= "-ABSENT";
2114 case sm_SEPARATED: case sm_DROPPING:
2115 xtra= flushing_input_file->rd ? "-1" : "-2";
2121 info("%s%s[%d] %s",forlog,xtra,periods,why);
2123 info("%s%s %s",forlog,xtra,why);
2127 /*---------- defer and backlog files ----------*/
2129 static void open_defer(void) {
2134 defer= fopen(path_defer, "a+");
2135 if (!defer) sysfatal("could not open defer file %s", path_defer);
2137 /* truncate away any half-written records */
2139 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2141 if (stab.st_size > LONG_MAX)
2142 die("defer file %s size is far too large", path_defer);
2147 long orgsize= stab.st_size;
2148 long truncto= stab.st_size;
2150 if (!truncto) break; /* was only (if anything) one half-truncated record */
2151 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2152 sysdie("seek in defer file %s while truncating partial", path_defer);
2157 sysdie("failed read from defer file %s", path_defer);
2159 die("defer file %s shrank while we were checking it!", path_defer);
2165 if (stab.st_size != truncto) {
2166 warn("truncating half-record at end of defer file %s -"
2167 " shrinking by %ld bytes from %ld to %ld",
2168 path_defer, orgsize - truncto, orgsize, truncto);
2171 sysfatal("could not flush defer file %s", path_defer);
2172 if (ftruncate(fileno(defer), truncto))
2173 sysdie("could not truncate defer file %s", path_defer);
2176 info("continuing existing defer file %s (%ld bytes)",
2177 path_defer, orgsize);
2179 if (fseek(defer, truncto, SEEK_SET))
2180 sysdie("could not seek to new end of defer file %s", path_defer);
2183 static void close_defer(void) {
2188 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2190 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2193 time_t now= xtime();
2195 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2197 (unsigned long)stab.st_ino);
2198 if (link(path_defer, backlog))
2199 sysfatal("could not install defer file %s as backlog file %s",
2200 path_defer, backlog);
2201 if (unlink(path_defer))
2202 sysdie("could not unlink old defer link %s to backlog file %s",
2203 path_defer, backlog);
2207 if (until_backlog_nextscan < 0 ||
2208 until_backlog_nextscan > backlog_retry_minperiods + 1)
2209 until_backlog_nextscan= backlog_retry_minperiods + 1;
2212 static void poll_backlog_file(void) {
2213 if (until_backlog_nextscan < 0) return;
2214 if (until_backlog_nextscan-- > 0) return;
2215 search_backlog_file();
2218 static void search_backlog_file(void) {
2219 /* returns non-0 iff there are any backlog files */
2224 const char *oldest_path=0;
2225 time_t oldest_mtime, now;
2227 if (backlog_input_file) return;
2231 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2235 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2237 die("out of memory expanding backlog pattern %s", globpat_backlog);
2239 for (i=0; i<gl.gl_pathc; i++) {
2240 const char *path= gl.gl_pathv[i];
2242 if (strchr(path,'#') || strchr(path,'~')) {
2243 debug("backlog file search skipping %s", path);
2246 r= stat(path, &stab);
2248 syswarn("failed to stat backlog file %s", path);
2251 if (!S_ISREG(stab.st_mode)) {
2252 warn("backlog file %s is not a plain file (or link to one)", path);
2255 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2257 oldest_mtime= stab.st_mtime;
2260 case GLOB_NOMATCH: /* fall through */
2263 sysdie("glob expansion of backlog pattern %s gave unexpected"
2264 " nonzero (error?) return value %d", globpat_backlog, r);
2270 debug("backlog scan: none");
2272 if (sms==sm_DROPPED) {
2273 notice("feed dropped and our work is complete");
2274 xunlink(path_lock, "lockfile for old feed");
2277 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2282 double age= difftime(now, oldest_mtime);
2283 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2285 if (age_deficiency <= 0) {
2286 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2287 age, age_deficiency, oldest_path);
2289 backlog_input_file= open_input_file(oldest_path);
2290 if (!backlog_input_file) {
2291 warn("backlog file %s vanished as we opened it", backlog_input_file);
2294 inputfile_reading_start(backlog_input_file);
2295 until_backlog_nextscan= -1;
2299 until_backlog_nextscan= age_deficiency / period_seconds;
2301 if (backlog_spontaneous_rescan_periods >= 0 &&
2302 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2303 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2305 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2306 age, age_deficiency, until_backlog_nextscan, oldest_path);
2310 /*========== flushing the feed ==========*/
2312 static pid_t inndcomm_child;
2313 static int inndcomm_sentinel_fd;
2315 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2316 assert(inndcomm_child);
2317 assert(fd == inndcomm_sentinel_fd);
2318 int status= xwaitpid(&inndcomm_child, "inndcomm");
2319 cancel_fd_read_except(fd);
2320 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2322 assert(!flushing_input_file);
2324 if (WIFEXITED(status)) {
2325 switch (WEXITSTATUS(status)) {
2327 case INNDCOMMCHILD_ESTATUS_FAIL:
2330 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2331 warn("feed has been dropped by innd, finishing up");
2332 flushing_input_file= main_input_file;
2333 tailing_queue_readable(flushing_input_file);
2334 /* we probably previously returned EAGAIN from our fake read method
2335 * when in fact we were at EOF, so signal another readable event
2336 * so we actually see the EOF */
2340 if (flushing_input_file) {
2341 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2344 SMS(DROPPED, 0, "feed dropped by innd");
2345 search_backlog_file();
2347 return OOP_CONTINUE;
2351 flushing_input_file= main_input_file;
2352 tailing_queue_readable(flushing_input_file);
2354 main_input_file= open_input_file(feedfile);
2355 if (!main_input_file)
2356 die("flush succeeded but feedfile %s does not exist!", feedfile);
2358 if (flushing_input_file) {
2359 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2362 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2364 return OOP_CONTINUE;
2367 goto unexpected_exitstatus;
2370 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2371 warn("flush timed out trying to talk to innd");
2374 unexpected_exitstatus:
2375 report_child_status("inndcomm child", status);
2379 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2382 static void inndcommfail(const char *what) {
2383 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2384 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2387 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2390 notice("flushing %s",why);
2392 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2393 assert(!inndcomm_child);
2394 assert(!inndcomm_sentinel_fd);
2396 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2398 inndcomm_child= xfork("inndcomm child");
2400 if (!inndcomm_child) {
2401 const char *flushargv[2]= { sitename, 0 };
2405 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2406 /* parent spots the autoclose of pipefds[1] when we die or exit */
2408 alarm(inndcomm_flush_timeout);
2409 r= ICCopen(); if (r) inndcommfail("connect");
2410 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2411 if (!r) exit(0); /* yay! */
2413 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2414 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2415 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2418 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2419 inndcomm_sentinel_fd= pipefds[0];
2420 assert(inndcomm_sentinel_fd);
2421 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2423 SMS(FLUSHING, 0, why);
2426 /*========== main program ==========*/
2428 static void postfork_inputfile(InputFile *ipf) {
2430 xclose(ipf->fd, "(in child) input file ", ipf->path);
2433 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2434 /* we have no stdio streams that are buffered long-term */
2436 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2439 static void postfork(void) {
2440 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2441 sysdie("(in child) failed to reset SIGPIPE");
2443 postfork_inputfile(main_input_file);
2444 postfork_inputfile(flushing_input_file);
2447 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2448 conn_closefd(conn,"(in child) ");
2450 postfork_stdio(defer, "defer file ", path_defer);
2453 #define EVERY(what, interval_sec, interval_usec, body) \
2454 static struct timeval what##_timeout = { interval_sec, interval_usec }; \
2455 static void what##_schedule(void); \
2456 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2458 what##_schedule(); \
2460 static void what##_schedule(void) { \
2461 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2464 EVERY(filepoll, 5,0, {
2465 if (main_input_file && main_input_file->readable_callback)
2466 filemon_callback(main_input_file);
2469 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s"
2470 #define DEBUG_IPF(wh) \
2471 wh##_input_file, debug_ipf_path(wh##_input_file), \
2472 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2473 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2474 static const char *debug_ipf_path(InputFile *ipf) {
2475 char *slash= strrchr(ipf->path,'/');
2476 return slash ? slash+1 : ipf->path;
2479 EVERY(period, -1,0, {
2481 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2482 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_IPF(flushing)
2483 " children connecting=%ld inndcomm_child"
2485 sms_names[sms], sm_period_counter,
2486 queue.count, conns.count, until_connect,
2487 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2488 (long)connecting_child, (long)inndcomm_child
2491 if (until_connect) until_connect--;
2493 poll_backlog_file();
2494 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2495 statemc_period_poll();
2496 check_assign_articles();
2501 /*========== option parsing ==========*/
2503 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2504 static void vbadusage(const char *fmt, va_list al) {
2505 char *m= xvasprintf(fmt,al);
2506 fprintf(stderr, "bad usage: %s\n%s"
2507 "say --help for help, or read the manpage\n",
2510 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2514 /*---------- generic option parser ----------*/
2516 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2517 static void badusage(const char *fmt, ...) {
2524 of_seconds= 001000u,
2525 of_boolean= 002000u,
2528 typedef struct Option Option;
2529 typedef void OptionParser(const Option*, const char *val);
2533 const char *lng, *formarg;
2539 static void parse_options(const Option *options, char ***argvp) {
2540 /* on return *argvp is first non-option arg; argc is not updated */
2543 const char *arg= *++(*argvp);
2545 if (*arg != '-') break;
2546 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2548 while ((a= *++arg)) {
2552 char *equals= strchr(arg,'=');
2553 int len= equals ? (equals - arg) : strlen(arg);
2554 for (o=options; o->shrt || o->lng; o++)
2555 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2557 badusage("unknown long option --%s",arg);
2560 if (equals) badusage("option --%s does not take a value",o->lng);
2562 } else if (equals) {
2566 if (!arg) badusage("option --%s needs a value for %s",
2567 o->lng, o->formarg);
2570 break; /* eaten the whole argument now */
2572 for (o=options; o->shrt || o->lng; o++)
2575 badusage("unknown short option -%c",a);
2582 if (!arg) badusage("option -%c needs a value for %s",
2583 o->shrt, o->formarg);
2586 break; /* eaten the whole argument now */
2592 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
2594 static void print_options(const Option *options, FILE *f) {
2596 for (o=options; o->shrt || o->lng; o++) {
2597 char shrt[2] = { o->shrt, 0 };
2598 char *optspec= xasprintf("%s%s%s%s%s",
2599 o->shrt ? "-" : "", o->shrt,
2600 o->shrt && o->lng ? "|" : "",
2601 DELIMPERHAPS("--", o->lng));
2602 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
2607 /*---------- specific option types ----------*/
2609 static void op_integer(const Option *o, const char *val) {
2612 unsigned long ul= strtoul(val,&ep,10);
2613 if (*ep || ep==val || errno || ul>INT_MAX)
2614 badusage("bad integer value for %s",o->lng);
2615 int *store= o->store;
2619 static void op_double(const Option *o, const char *val) {
2620 int *store= o->store;
2623 *store= strtod(val, &ep);
2624 if (*ep || ep==val || errno)
2625 badusage("bad floating point value for %s",o->lng);
2628 static void op_string(const Option *o, const char *val) {
2629 const char **store= o->store;
2633 static void op_seconds(const Option *o, const char *val) {
2634 int *store= o->store;
2638 double v= strtod(val,&ep);
2639 if (ep==val) badusage("bad time/duration value for %s",o->lng);
2641 if (!*ep || !strcmp(ep,"s")) unit= 1;
2642 else if (!strcmp(ep,"m")) unit= 60;
2643 else if (!strcmp(ep,"h")) unit= 3600;
2644 else if (!strcmp(ep,"d")) unit= 86400;
2645 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2649 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2653 static void op_periods_rndup(const Option *o, const char *val) {
2654 int *store= o->store;
2656 *store += period_seconds-1;
2657 *store /= period_seconds;
2660 static void op_setint(const Option *o, const char *val) {
2661 int *store= o->store;
2665 /*---------- specific options ----------*/
2667 static void help(const Option *o, const char *val);
2669 static const Option innduct_options[]= {
2670 {'f',"feedfile", "F", &feedfile, op_string },
2671 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
2672 {0,"help", 0, help },
2674 {0,"max-connections", "N", &max_connections, op_integer },
2675 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
2678 {0,"streaming", 0, &try_stream, op_setint, 1 },
2679 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
2680 {'P',"port", "PORT",&port, op_integer },
2681 {0,"inndconf", "F", &inndconffile, op_string },
2682 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
2684 {0,"no-check-proportion","PERCENT", &nocheck_thresh_pct, op_double },
2685 {0,"no-check-filter", "ARTICLES", &nocheck_decay_articles, op_double },
2687 {0,"reconnect-interval", "TIME", &reconnect_delay_periods, op_periods_rndup },
2688 {0,"flush-retry-interval","TIME", &flushfail_retry_periods, op_periods_rndup },
2689 {0,"inndcomm-timeout", "TIME", &inndcomm_flush_timeout, op_seconds },
2693 static void printusage(FILE *f) {
2694 fputs("usage: innduct [options] site [fqdn]\n"
2695 "available options are:\n", f);
2696 print_options(innduct_options, f);
2699 static void help(const Option *o, const char *val) {
2701 if (ferror(stdout) || fflush(stdout)) {
2702 perror("innduct: writing help");
2708 int main(int argc, char **argv) {
2714 parse_options(innduct_options, &argv);
2719 if (!sitename) badusage("need site name argument");
2720 remote_host= *argv++;
2721 if (*argv) badusage("too many non-option arguments");
2725 if (!remote_host) remote_host= sitename;
2727 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2728 badusage("nocheck threshold percentage must be between 0..100");
2729 nocheck_thresh= nocheck_thresh_pct * 0.01;
2731 if (nocheck_decay_articles < 0.1)
2732 badusage("nocheck decay articles must be at least 0.1");
2733 nocheck_decay= 1 - 1/nocheck_decay_articles;
2736 pathoutgoing= innconf->pathoutgoing;
2737 innconf_read(inndconffile);
2740 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2741 else if (!feedfile[0])
2742 badusage("feed filename must be nonempty");
2743 else if (feedfile[strlen(feedfile)-1]=='/')
2744 feedfile= xasprintf("%s%s",feedfile,sitename);
2746 const char *feedfile_forbidden= "?*[~#";
2748 while ((c= *feedfile_forbidden++))
2749 if (strchr(feedfile, c))
2750 badusage("feed filename may not contain metacharacter %c",c);
2754 oop_source_sys *sysloop= oop_sys_new();
2755 if (!sysloop) sysdie("could not create liboop event loop");
2756 loop= (oop_source*)sysloop;
2758 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2759 sysdie("could not ignore SIGPIPE");
2764 if (become_daemon) {
2766 for (i=3; i<255; i++)
2767 /* do this now before we open syslog, etc. */
2769 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2771 int null= open("/dev/null",O_RDWR);
2772 if (null<0) sysdie("failed to open /dev/null");
2776 xclose(null, "/dev/null original fd",0);
2778 pid_t child1= xfork("daemonise first fork");
2779 if (child1) _exit(0);
2781 pid_t sid= setsid();
2782 if (sid != child1) sysdie("setsid failed");
2784 pid_t child2= xfork("daemonise second fork");
2785 if (child2) _exit(0);
2790 if (!filemon_method_init()) {
2791 warn("no file monitoring available, polling");
2792 filepoll_schedule();
2795 period_timeout.tv_sec= period_seconds;
2802 void *r= oop_sys_run(sysloop);
2803 assert(r == OOP_ERROR);
2804 sysdie("event loop failed");