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 node list_node
211 union { struct list li; T *for_type; } u; \
215 #define NODE(n) (assert((void*)&(n)->list_node == &(n)), &(n)->list_node)
217 #define LIST_CHECKCANHAVENODE(l,n) \
218 ((void)((n) == ((l).u.for_type))) /* just for the type check */
220 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
221 ( LIST_CHECKCANHAVENODE(l,n), \
222 list_addsomehow(&(l).u.li, NODE((n))), \
226 #define LIST_REMSOMEHOW(l,list_remsomehow) \
227 ( (typeof((l).u.for_type)) \
230 list_remsomehow(&(l).u.li) ) \
236 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
237 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
238 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
239 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
241 #define LIST_INIT(l) (list_new(&(l).u.li))
242 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
243 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
244 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
246 #define LIST_REMOVE(l,n) \
247 ( LIST_CHECKCANHAVENODE(l,n), \
248 list_remove(NODE((n))), \
252 #define LIST_INSERT(l,n,pred) \
253 ( LIST_CHECKCANHAVENODE(l,n), \
254 LIST_CHECKCANHAVENODE(l,pred), \
255 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
259 /*----- type predeclarations -----*/
261 typedef struct Conn Conn;
262 typedef struct Article Article;
263 typedef struct InputFile InputFile;
264 typedef struct XmitDetails XmitDetails;
265 typedef struct Filemon_Perfile Filemon_Perfile;
266 typedef enum StateMachineState StateMachineState;
271 /*----- function predeclarations -----*/
273 static void conn_maybe_write(Conn *conn);
274 static void conn_make_some_xmits(Conn *conn);
275 static void *conn_write_some_xmits(Conn *conn);
277 static void xmit_free(XmitDetails *d);
279 #define SMS(newstate, periods, why) \
280 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
281 static void statemc_setstate(StateMachineState newsms, int periods,
282 const char *forlog, const char *why);
284 static void statemc_start_flush(const char *why); /* Normal => Flushing */
285 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
287 static void check_assign_articles(void);
288 static void queue_check_input_done(void);
290 static void statemc_check_flushing_done(void);
291 static void statemc_check_backlog_done(void);
293 static void postfork(void);
295 static void open_defer(void);
296 static void close_defer(void);
297 static void search_backlog_file(void);
299 static void inputfile_reading_start(InputFile *ipf);
300 static void inputfile_reading_stop(InputFile *ipf);
302 static void filemon_start(InputFile *ipf);
303 static void filemon_stop(InputFile *ipf);
304 static void filemon_callback(InputFile *ipf);
306 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
307 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
309 static const oop_rd_style peer_rd_style;
310 static oop_rd_call peer_rd_err, peer_rd_ok;
312 /*----- configuration options -----*/
314 static const char *sitename, *feedfile, *pathoutgoing;
315 static const char *remote_host;
316 static int quiet_multiple=0, become_daemon=1;
318 static int max_connections=10, max_queue_per_conn=200;
319 static int target_max_feedfile_size=100000;
321 static int period_seconds=60;
323 static double max_bad_data_ratio= 0.01;
324 static int max_bad_data_initial= 30;
325 /* in one corrupt 4096-byte block the number of newlines has
326 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
328 static int connection_setup_timeout=200, port=119, try_stream=1;
329 static int inndcomm_flush_timeout=100;
330 static int reconnect_delay_periods, flushfail_retry_periods;
331 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
332 static int spontaneous_flush_periods, need_activity_periods;
333 static const char *inndconffile;
335 static double nocheck_thresh_pct= 95.0;
336 static double nocheck_thresh; /* computed in main from _pct */
337 static double nocheck_decay_articles= 100; /* converted to _decay */
338 static double nocheck_decay; /* computed in main from _articles */
341 /*----- statistics -----*/
343 typedef enum { /* in queue in conn->sent */
344 art_Unchecked, /* not checked, not sent checking */
345 art_Wanted, /* checked, wanted sent body as requested */
346 art_Unsolicited, /* - sent body without check */
350 #define RESULT_COUNTS(RCS,RCN) \
358 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
359 #define RCI_TRIPLE_VALS_BASE(counts,x) \
360 counts[art_Unchecked] x \
361 + counts[art_Wanted] x \
362 + counts[art_Unsolicited] x, \
363 counts[art_Unchecked] x \
364 , counts[art_Wanted] x \
365 , counts[art_Unsolicited] x
368 #define RC_INDEX(x) RC_##x,
369 RESULT_COUNTS(RC_INDEX, RC_INDEX)
374 /*----- transmission buffers -----*/
379 xk_Malloc, xk_Const, xk_Artdata
391 /*----- core operational data structure types -----*/
394 /* This is also an instance of struct oop_readable */
395 struct oop_readable readable; /* first */
396 oop_readable_call *readable_callback;
397 void *readable_callback_user;
400 Filemon_Perfile *filemon;
402 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
403 long inprogress; /* no. of articles read but not processed */
407 int counts[art_MaxState][RCI_max];
408 int readcount_ok, readcount_blank, readcount_err;
423 #define SMS_LIST(X) \
431 enum StateMachineState {
432 #define SMS_DEF_ENUM(s) sm_##s,
433 SMS_LIST(SMS_DEF_ENUM)
436 static const char *sms_names[]= {
437 #define SMS_DEF_NAME(s) #s ,
438 SMS_LIST(SMS_DEF_NAME)
444 int fd; /* may be 0, meaning closed (during construction/destruction) */
445 oop_read *rd; /* likewise */
446 int max_queue, stream, quitting;
447 int since_activity; /* periods */
448 ArticleList waiting; /* not yet told peer */
449 ArticleList priority; /* peer says send it now */
450 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
451 struct iovec xmit[CONNIOVS];
452 XmitDetails xmitd[CONNIOVS];
457 /*----- general operational variables -----*/
459 /* main initialises */
460 static oop_source *loop;
461 static ConnList conns;
462 static ArticleList queue;
463 static char *path_lock, *path_flushing, *path_defer, *globpat_backlog;
465 /* statemc_init initialises */
466 static StateMachineState sms;
468 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
469 static int sm_period_counter;
471 /* initialisation to 0 is good */
472 static int until_connect, until_backlog_nextscan;
473 static double accept_proportion;
474 static int nocheck, nocheck_reported;
476 /*========== logging ==========*/
478 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
479 static void logcore(int sysloglevel, const char *fmt, ...) {
482 vsyslog(sysloglevel,fmt,al);
484 vfprintf(stderr,fmt,al);
490 static void logv(int sysloglevel, const char *pfx, int errnoval,
491 const char *fmt, va_list al) PRINTF(5,0);
492 static void logv(int sysloglevel, const char *pfx, int errnoval,
493 const char *fmt, va_list al) {
494 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
495 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
496 msgbuf[sizeof(msgbuf)-1]= 0;
498 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
499 sysloglevel= LOG_ERR; /* run by wrong user, probably */
501 logcore(sysloglevel, "<%s>%s: %s%s%s",
502 sitename, pfx, msgbuf,
503 errnoval>=0 ? ": " : "",
504 errnoval>=0 ? strerror(errnoval) : "");
507 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
508 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
509 static void fn(const char *fmt, ...) { \
511 logv(sysloglevel, pfx, err, fmt, al); \
515 #define logwrap(fn, pfx, sysloglevel, err) \
516 static void fn(const char *fmt, ...) PRINTF(1,2); \
517 static void fn(const char *fmt, ...) { \
519 logv(sysloglevel, pfx, err, fmt, al); \
523 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
524 diewrap(die, " critical", LOG_CRIT, -1, 16);
526 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
527 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
529 logwrap(syswarn, " warning", LOG_WARNING, errno);
530 logwrap(warn, " warning", LOG_WARNING, -1);
532 logwrap(notice, "", LOG_NOTICE, -1);
533 logwrap(info, " info", LOG_INFO, -1);
534 logwrap(debug, " debug", LOG_DEBUG, -1);
537 /*========== utility functions etc. ==========*/
539 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
540 static char *xvasprintf(const char *fmt, va_list al) {
542 int rc= vasprintf(&str,fmt,al);
543 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
546 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
547 static char *xasprintf(const char *fmt, ...) {
549 char *str= xvasprintf(fmt,al);
554 static int close_perhaps(int *fd) {
560 static void xclose(int fd, const char *what, const char *what2) {
562 if (r) sysdie("close %s%s",what,what2?what2:"");
564 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
566 xclose(*fd,what,what2);
570 static pid_t xfork(const char *what) {
574 if (child==-1) sysdie("cannot fork for %s",what);
575 debug("forked %s %ld", what, (unsigned long)child);
576 if (!child) postfork();
580 static void on_fd_read_except(int fd, oop_call_fd callback) {
581 loop->on_fd(loop, fd, OOP_READ, callback, 0);
582 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
584 static void cancel_fd_read_except(int fd) {
585 loop->cancel_fd(loop, fd, OOP_READ);
586 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
589 static void report_child_status(const char *what, int status) {
590 if (WIFEXITED(status)) {
591 int es= WEXITSTATUS(status);
593 warn("%s: child died with error exit status %d", what, es);
594 } else if (WIFSIGNALED(status)) {
595 int sig= WTERMSIG(status);
596 const char *sigstr= strsignal(sig);
597 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
599 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
601 warn("%s: child died due to unknown fatal signal %d%s",
602 what, sig, coredump);
604 warn("%s: child died with unknown wait status %d", what,status);
608 static int xwaitpid(pid_t *pid, const char *what) {
611 int r= kill(*pid, SIGKILL);
612 if (r) sysdie("cannot kill %s child", what);
614 pid_t got= waitpid(*pid, &status, WNOHANG);
615 if (got==-1) sysdie("cannot reap %s child", what);
622 static void xunlink(const char *path, const char *what) {
624 if (r) sysdie("can't unlink %s %s", path, what);
627 static time_t xtime(void) {
629 if (now==-1) sysdie("time(2) failed");
633 static void check_isreg(const struct stat *stab, const char *path,
635 if (!S_ISREG(stab->st_mode))
636 die("%s %s not a plain file (mode 0%lo)",
637 what, path, (unsigned long)stab->st_mode);
640 static void xfstat(int fd, struct stat *stab_r, const char *what) {
641 int r= fstat(fd, stab_r);
642 if (r) sysdie("could not fstat %s", what);
645 static void xfstat_isreg(int fd, struct stat *stab_r,
646 const char *path, const char *what) {
647 xfstat(fd, stab_r, what);
648 check_isreg(stab_r, path, what);
651 static void xlstat_isreg(const char *path, struct stat *stab,
652 int *enoent_r /* 0 means ENOENT is fatal */,
654 int r= lstat(path, stab);
656 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
657 sysdie("could not lstat %s %s", what, path);
659 if (enoent_r) *enoent_r= 0;
660 check_isreg(stab, path, what);
663 static int samefile(const struct stat *a, const struct stat *b) {
664 assert(S_ISREG(a->st_mode));
665 assert(S_ISREG(b->st_mode));
666 return (a->st_ino == b->st_ino &&
667 a->st_dev == b->st_dev);
670 static char *sanitise(const char *input) {
671 static char sanibuf[100]; /* returns pointer to this buffer! */
673 const char *p= input;
677 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
679 if (!c) { *q++= '\''; *q=0; break; }
680 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
681 sprintf(q,"\\x%02x",c);
687 static int isewouldblock(int errnoval) {
688 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
691 /*========== management of connections ==========*/
693 static void conn_closefd(Conn *conn, const char *msgprefix) {
694 int r= close_perhaps(&conn->fd);
695 if (r) info("C%d %serror closing socket: %s",
696 conn->fd, msgprefix, strerror(errno));
699 static void conn_dispose(Conn *conn) {
702 oop_rd_cancel(conn->rd);
703 oop_rd_delete_kill(conn->rd);
707 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
708 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
710 conn_closefd(conn,"");
712 until_connect= reconnect_delay_periods;
715 static void *conn_exception(oop_source *lp, int fd,
716 oop_event ev, void *conn_v) {
719 assert(fd == conn->fd);
720 assert(ev == OOP_EXCEPTION);
721 int r= read(conn->fd, &ch, 1);
722 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
723 else connfail(conn,"exceptional condition on socket (peer sent urgent"
724 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
728 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
729 int requeue[art_MaxState];
732 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
733 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
734 while ((art= LIST_REMHEAD(conn->sent))) {
735 requeue[art->state]++;
736 if (art->state==art_Unsolicited) art->state= art_Unchecked;
737 LIST_ADDTAIL(queue,art);
742 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
745 char *m= xvasprintf(fmt,al);
746 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
747 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
750 LIST_REMOVE(conns,conn);
752 check_assign_articles();
755 static void connfail(Conn *conn, const char *fmt, ...) {
758 vconnfail(conn,fmt,al);
762 static void check_idle_conns(void) {
764 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
765 conn->since_activity++;
767 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
768 if (conn->since_activity <= need_activity_periods) continue;
770 /* We need to shut this down */
772 connfail(conn,"timed out waiting for response to QUIT");
773 else if (conn->sent.count)
774 connfail(conn,"timed out waiting for responses");
775 else if (conn->waiting.count || conn->priority.count)
776 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
777 else if (conn->xmitu)
778 connfail(conn,"peer has been sending responses"
779 " before receiving our commands!");
781 static const char quitcmd[]= "QUIT\r\n";
782 int todo= sizeof(quitcmd)-1;
783 const char *p= quitcmd;
785 int r= write(conn->fd, p, todo);
787 if (isewouldblock(errno))
788 connfail(conn, "blocked writing QUIT to idle connection");
790 connfail(conn, "failed to write QUIT to idle connection: %s",
798 conn->since_activity= 0;
799 debug("C%d is idle, quitting", conn->fd);
808 /*---------- making new connections ----------*/
810 static pid_t connecting_child;
811 static int connecting_fdpass_sock;
813 static void connect_attempt_discard(void) {
814 if (connecting_child) {
815 int r= kill(connecting_child, SIGTERM);
816 if (r) syswarn("failed to kill connecting child");
817 int status= xwaitpid(&connecting_child, "connect");
819 if (!(WIFEXITED(status) ||
820 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
821 report_child_status("connect", status);
823 if (connecting_fdpass_sock) {
824 cancel_fd_read_except(connecting_fdpass_sock);
825 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
829 #define PREP_DECL_MSG_CMSG(msg) \
831 memset(&msg,0,sizeof(msg)); \
832 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
833 msg.msg_control= msg##cbuf; \
834 msg.msg_controllen= sizeof(msg##cbuf);
836 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
839 assert(fd == connecting_fdpass_sock);
841 conn= xmalloc(sizeof(*conn));
842 memset(conn,0,sizeof(*conn));
844 PREP_DECL_MSG_CMSG(msg);
845 struct cmsghdr *h= 0;
846 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
847 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
850 pid_t got= waitpid(connecting_child, &status, WNOHANG);
852 assert(got==connecting_child);
854 if (WIFEXITED(status)) {
855 if (WEXITSTATUS(status) != 0 &&
856 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
857 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
858 /* child already reported the problem */;
860 warn("connect: connection child exited code %d but no cmsg",
861 WEXITSTATUS(status));
862 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
863 warn("connect: connection attempt timed out");
865 report_child_status("connect", status);
868 /* child is still running apparently, report the socket problem */
870 syswarn("connect: read from fdpass socket failed");
871 else if (e == OOP_EXCEPTION)
872 warn("connect: unexpected exception on fdpass socket");
874 warn("connect: unexpected EOF on fdpass socket");
876 fatal("connect: unexpected lack of cmsg from child");
881 #define CHK(field, val) \
882 if (h->cmsg_##field != val) { \
883 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
884 h->cmsg_##field, val); \
887 CHK(level, SOL_SOCKET);
888 CHK(type, SCM_RIGHTS);
889 CHK(len, CMSG_LEN(sizeof(conn->fd)));
892 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
894 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
897 pid_t got= waitpid(connecting_child, &status, 0);
898 if (got==-1) sysdie("connect: real wait for child");
899 assert(got == connecting_child);
902 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
903 int es= WEXITSTATUS(status);
905 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
906 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
908 fatal("connect: child gave unexpected exit status %d", es);
912 LIST_INIT(conn->waiting);
913 LIST_INIT(conn->priority);
914 LIST_INIT(conn->sent);
915 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
917 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
918 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
919 if (!conn->fd) sysdie("oop_rd_new_fd (fd=%d)",conn->fd);
920 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
923 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
925 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
926 LIST_ADDHEAD(conns, conn);
928 connect_attempt_discard();
929 check_assign_articles();
934 connect_attempt_discard();
938 static int allow_connect_start(void) {
939 return conns.count < max_connections
944 static void connect_start(void) {
945 assert(!connecting_child);
946 assert(!connecting_fdpass_sock);
948 notice("starting connection attempt");
951 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
952 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
954 connecting_child= xfork("connection");
956 if (!connecting_child) {
957 FILE *cn_from, *cn_to;
958 char buf[NNTP_STRLEN+100];
959 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
961 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
963 alarm(connection_setup_timeout);
964 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
965 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
966 else sysfatal("connect: connection attempt failed");
968 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
969 sysfatal("connect: authentication failed");
971 if (fputs("MODE STREAM\r\n", cn_to) ||
973 sysfatal("connect: could not send MODE STREAM");
974 buf[sizeof(buf)-1]= 0;
975 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
977 sysfatal("connect: could not read response to MODE STREAM");
979 fatal("connect: connection close in response to MODE STREAM");
984 fatal("connect: response to MODE STREAM is too long: %.100s...",
986 l--; if (l>0 && buf[l-1]=='\r') l--;
989 int rcode= strtoul(buf,&ep,10);
991 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
995 exitstatus= CONNCHILD_ESTATUS_STREAM;
1001 warn("connect: unexpected response to MODE STREAM: %.50s",
1007 int fd= fileno(cn_from);
1009 PREP_DECL_MSG_CMSG(msg);
1010 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1011 cmsg->cmsg_level= SOL_SOCKET;
1012 cmsg->cmsg_type= SCM_RIGHTS;
1013 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1014 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1016 msg.msg_controllen= cmsg->cmsg_len;
1017 r= sendmsg(socks[1], &msg, 0);
1018 if (r) sysdie("sendmsg failed for new connection");
1023 xclose(socks[1], "connecting fdpass child's socket",0);
1024 connecting_fdpass_sock= socks[0];
1025 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1028 /*---------- assigning articles to conns, and transmitting ----------*/
1030 static void check_assign_articles(void) {
1036 int spare=0, inqueue=0;
1038 /* Find a connection to offer this article. We prefer a busy
1039 * connection to an idle one, provided it's not full. We take the
1040 * first (oldest) and since that's stable, it will mean we fill up
1041 * connections in order. That way if we have too many
1042 * connections, the spare ones will go away eventually.
1044 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1045 if (walk->quitting) continue;
1046 inqueue= walk->sent.count + walk->priority.count
1047 + walk->waiting.count;
1048 spare= walk->max_queue - inqueue;
1049 assert(inqueue <= max_queue_per_conn);
1051 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1052 else if (spare>0) /*working*/ { use= walk; break; }
1055 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1057 Article *art= LIST_REMHEAD(queue);
1058 LIST_ADDTAIL(use->waiting, art);
1061 conn_maybe_write(use);
1062 } else if (allow_connect_start()) {
1063 until_connect= reconnect_delay_periods;
1072 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1073 conn_maybe_write(u);
1074 return OOP_CONTINUE;
1077 static void conn_maybe_write(Conn *conn) {
1079 conn_make_some_xmits(conn);
1081 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1085 void *rp= conn_write_some_xmits(conn);
1086 if (rp==OOP_CONTINUE) {
1087 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1089 } else if (rp==OOP_HALT) {
1092 /* transmitted everything */
1099 /*========== article transmission ==========*/
1101 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1102 XmitKind kind) { /* caller must then fill in details */
1103 struct iovec *v= &conn->xmit[conn->xmitu];
1104 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1105 v->iov_base= (char*)data;
1111 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1112 xmit_core(conn,data,len, xk_Const);
1114 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1116 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1117 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1121 static void xmit_free(XmitDetails *d) {
1123 case xk_Malloc: free(d->info.malloc_tofree); break;
1124 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1125 case xk_Const: break;
1130 static void *conn_write_some_xmits(Conn *conn) {
1132 * 0: nothing more to write, no need to call us again
1133 * OOP_CONTINUE: more to write but fd not writeable
1134 * OOP_HALT: disaster, have destroyed conn
1137 int count= conn->xmitu;
1138 if (!count) return 0;
1140 if (count > IOV_MAX) count= IOV_MAX;
1141 ssize_t rs= writev(conn->fd, conn->xmit, count);
1143 if (isewouldblock(errno)) return OOP_CONTINUE;
1144 connfail(conn, "write failed: %s", strerror(errno));
1150 for (done=0; rs && done<conn->xmitu; done++) {
1151 struct iovec *vp= &conn->xmit[done];
1152 XmitDetails *dp= &conn->xmitd[done];
1153 if (rs > vp->iov_len) {
1157 vp->iov_base= (char*)vp->iov_base + rs;
1161 int newu= conn->xmitu - done;
1162 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1163 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1168 static void conn_make_some_xmits(Conn *conn) {
1170 if (conn->xmitu+5 > CONNIOVS)
1173 Article *art= LIST_REMHEAD(conn->priority);
1174 if (!art) art= LIST_REMHEAD(conn->waiting);
1177 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1178 /* actually send it */
1180 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1184 XMIT_LITERAL("TAKETHIS ");
1185 xmit_noalloc(conn, art->messageid, art->midlen);
1186 XMIT_LITERAL("\r\n");
1187 xmit_artbody(conn, artdata);
1190 /* we got 235 from IHAVE */
1192 xmit_artbody(conn, artdata);
1194 XMIT_LITERAL(".\r\n");
1199 art->state == art_Unchecked ? art_Unsolicited :
1200 art->state == art_Wanted ? art_Wanted :
1202 art->ipf->counts[art->state][RC_sent]++;
1203 LIST_ADDTAIL(conn->sent, art);
1209 XMIT_LITERAL("IHAVE ");
1211 XMIT_LITERAL("CHECK ");
1212 xmit_noalloc(conn, art->messageid, art->midlen);
1213 XMIT_LITERAL("\r\n");
1215 assert(art->state == art_Unchecked);
1216 art->ipf->counts[art->state][RC_sent]++;
1217 LIST_ADDTAIL(conn->sent, art);
1223 /*========== handling responses from peer ==========*/
1225 static const oop_rd_style peer_rd_style= {
1226 OOP_RD_DELIM_STRIP, '\n',
1228 OOP_RD_SHORTREC_FORBID
1231 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1232 const char *errmsg, int errnoval,
1233 const char *data, size_t recsz, void *conn_v) {
1235 connfail(conn, "error receiving from peer: %s", errmsg);
1236 return OOP_CONTINUE;
1239 static Article *article_reply_check(Conn *conn, const char *response,
1240 int code_indicates_streaming,
1242 /* 1:yes, -1:no, 0:dontcare */,
1243 const char *sanitised_response) {
1244 Article *art= LIST_HEAD(conn->sent);
1248 "peer gave unexpected response when no commands outstanding: %s",
1249 sanitised_response);
1253 if (code_indicates_streaming) {
1254 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1255 if (!conn->stream) {
1256 connfail(conn, "peer gave streaming response code "
1257 " to IHAVE or subsequent body: %s", sanitised_response);
1260 const char *got_mid= response+4;
1261 int got_midlen= strcspn(got_mid, " \n\r");
1262 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1263 connfail(conn, "peer gave streaming response with syntactically invalid"
1264 " messageid: %s", sanitised_response);
1267 if (got_midlen != art->midlen ||
1268 memcmp(got_mid, art->messageid, got_midlen)) {
1269 connfail(conn, "peer gave streaming response code to wrong article -"
1270 " probable synchronisation problem; we offered: %s;"
1272 art->messageid, sanitised_response);
1277 connfail(conn, "peer gave non-streaming response code to"
1278 " CHECK/TAKETHIS: %s", sanitised_response);
1283 if (must_have_sent>0 && art->state < art_Wanted) {
1284 connfail(conn, "peer says article accepted but"
1285 " we had not sent the body: %s", sanitised_response);
1288 if (must_have_sent<0 && art->state >= art_Wanted) {
1289 connfail(conn, "peer says please sent the article but we just did: %s",
1290 sanitised_response);
1294 Article *art_again= LIST_REMHEAD(conn->sent);
1295 assert(art_again == art);
1299 static void update_nocheck(int accepted) {
1300 accept_proportion *= nocheck_decay;
1301 accept_proportion += accepted * (1.0 - nocheck_decay);
1302 int new_nocheck= accept_proportion >= nocheck_thresh;
1303 if (new_nocheck && !nocheck_reported) {
1304 notice("entering nocheck mode for the first time");
1305 nocheck_reported= 1;
1306 } else if (new_nocheck != nocheck) {
1307 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1309 nocheck= new_nocheck;
1312 static void article_done(Conn *conn, Article *art, int whichcount) {
1313 art->ipf->counts[art->state][whichcount]++;
1314 if (whichcount == RC_accepted) update_nocheck(1);
1315 else if (whichcount == RC_unwanted) update_nocheck(0);
1317 InputFile *ipf= art->ipf;
1319 while (art->blanklen) {
1320 static const char spaces[]=
1325 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1326 int r= pwrite(ipf->fd, spaces, w, art->offset);
1328 if (errno==EINTR) continue;
1329 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1330 art->messageid, art->blanklen,
1331 (unsigned long)art->offset, ipf->path);
1333 assert(r>=0 && r<=w);
1339 assert(ipf->inprogress >= 0);
1342 if (!ipf->inprogress && ipf != main_input_file)
1343 queue_check_input_done();
1346 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1347 const char *errmsg, int errnoval,
1348 const char *data, size_t recsz, void *conn_v) {
1351 if (ev == OOP_RD_EOF) {
1352 connfail(conn, "unexpected EOF from peer");
1353 return OOP_CONTINUE;
1355 assert(ev == OOP_RD_OK);
1357 char *sani= sanitise(data);
1360 unsigned long code= strtoul(data, &ep, 10);
1361 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1362 connfail(conn, "badly formatted response from peer: %s", sani);
1363 return OOP_CONTINUE;
1366 if (conn->quitting) {
1367 if (code!=205 && code!=503) {
1368 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1370 notice("C%d idle connection closed", conn->fd);
1371 assert(!conn->waiting.count);
1372 assert(!conn->priority.count);
1373 assert(!conn->sent.count);
1374 assert(!conn->xmitu);
1375 LIST_REMOVE(conns,conn);
1378 return OOP_CONTINUE;
1381 conn->since_activity= 0;
1384 #define GET_ARTICLE(musthavesent) \
1385 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1386 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1388 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1389 code_streaming= (streaming); \
1390 GET_ARTICLE(musthavesent); \
1391 article_done(conn, art, RC_##how); break;
1393 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1395 int code_streaming= 0;
1399 case 400: PEERBADMSG("peer stopped accepting articles");
1400 case 503: PEERBADMSG("peer timed us out");
1401 default: PEERBADMSG("peer sent unexpected message");
1403 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1404 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1406 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1407 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1409 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1410 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1412 case 238: /* CHECK says send it */
1414 case 335: /* IHAVE says send it */
1416 assert(art->state == art_Unchecked);
1417 art->ipf->counts[art->state][RC_accepted]++;
1418 art->state= art_Wanted;
1419 LIST_ADDTAIL(conn->priority, art);
1422 case 431: /* CHECK or TAKETHIS says try later */
1424 case 436: /* IHAVE says try later */
1427 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1429 sysfatal("write to defer file %s",path_defer);
1430 article_done(conn, art, RC_deferred);
1435 conn_maybe_write(conn);
1436 check_assign_articles();
1437 return OOP_CONTINUE;
1441 /*========== monitoring of input files ==========*/
1443 static void feedfile_eof(InputFile *ipf) {
1444 assert(ipf != main_input_file); /* promised by tailing_try_read */
1445 inputfile_reading_stop(ipf);
1447 if (ipf == flushing_input_file) {
1448 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1449 if (main_input_file) inputfile_reading_start(main_input_file);
1450 statemc_check_flushing_done();
1451 } else if (ipf == backlog_input_file) {
1452 statemc_check_backlog_done();
1454 abort(); /* supposed to wait rather than get EOF on main input file */
1458 static InputFile *open_input_file(const char *path) {
1459 int fd= open(path, O_RDONLY);
1461 if (errno==ENOENT) return 0;
1462 sysfatal("unable to open input file %s", path);
1466 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1467 memset(ipf,0,sizeof(*ipf));
1470 strcpy(ipf->path, path);
1475 static void close_input_file(InputFile *ipf) { /* does not free */
1476 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1477 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1478 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1479 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1480 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1484 /*---------- dealing with articles read in the input file ----------*/
1486 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1487 const char *data, const char *how) {
1488 warn("corrupted file: %s, offset %lu: %s: %s",
1489 ipf->path, (unsigned long)offset, how, sanitise(data));
1490 ipf->readcount_err++;
1491 if (ipf->readcount_err > max_bad_data_initial +
1492 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1493 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1494 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1495 return OOP_CONTINUE;
1498 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1499 oop_rd_event ev, const char *errmsg,
1500 int errnoval, const char *data, size_t recsz,
1502 InputFile *ipf= ipf_v;
1503 assert(ev == OOP_RD_SYSTEM);
1505 sysdie("error reading input file: %s, offset %lu",
1506 ipf->path, (unsigned long)ipf->offset);
1509 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1510 oop_rd_event ev, const char *errmsg,
1511 int errnoval, const char *data, size_t recsz,
1513 InputFile *ipf= ipf_v;
1515 char tokentextbuf[sizeof(TOKEN)*2+3];
1517 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1519 off_t old_offset= ipf->offset;
1520 ipf->offset += recsz + 1;
1522 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1524 if (ev==OOP_RD_PARTREC)
1525 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1526 /* but process it anyway */
1528 if (ipf->skippinglong) {
1529 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1530 return OOP_CONTINUE;
1532 if (ev==OOP_RD_LONG) {
1533 ipf->skippinglong= 1;
1534 X_BAD_DATA("overly long line");
1537 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1538 if (!recsz) X_BAD_DATA("empty line");
1541 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1542 ipf->readcount_blank++;
1543 return OOP_CONTINUE;
1546 char *space= strchr(data,' ');
1547 int tokenlen= space-data;
1548 int midlen= (int)recsz-tokenlen-1;
1549 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1550 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1552 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1553 memcpy(tokentextbuf, data, tokenlen);
1554 tokentextbuf[tokenlen]= 0;
1555 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1557 ipf->readcount_ok++;
1559 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1560 art->state= art_Unchecked;
1561 art->midlen= midlen;
1562 art->ipf= ipf; ipf->inprogress++;
1563 art->token= TextToToken(tokentextbuf);
1564 art->offset= ipf->offset;
1565 art->blanklen= recsz;
1566 strcpy(art->messageid, space+1);
1567 LIST_ADDTAIL(queue, art);
1569 if (sms==sm_NORMAL && ipf==main_input_file &&
1570 ipf->offset >= target_max_feedfile_size)
1571 statemc_start_flush("feed file size");
1573 check_assign_articles();
1574 return OOP_CONTINUE;
1577 /*========== tailing input file ==========*/
1579 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1581 InputFile *ipf= user;
1582 return ipf->readable_callback(loop, &ipf->readable,
1583 ipf->readable_callback_user);
1586 static void tailing_on_cancel(struct oop_readable *rable) {
1587 InputFile *ipf= (void*)rable;
1589 if (ipf->filemon) filemon_stop(ipf);
1590 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1591 ipf->readable_callback= 0;
1594 static void tailing_queue_readable(InputFile *ipf) {
1595 /* lifetime of ipf here is OK because destruction will cause
1596 * on_cancel which will cancel this callback */
1597 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1600 static int tailing_on_readable(struct oop_readable *rable,
1601 oop_readable_call *cb, void *user) {
1602 InputFile *ipf= (void*)rable;
1604 tailing_on_cancel(rable);
1605 ipf->readable_callback= cb;
1606 ipf->readable_callback_user= user;
1609 tailing_queue_readable(ipf);
1613 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1615 InputFile *ipf= (void*)rable;
1617 ssize_t r= read(ipf->fd, buffer, length);
1619 if (errno==EINTR) continue;
1623 if (ipf==main_input_file) {
1626 } else if (ipf==flushing_input_file) {
1628 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1629 } else if (ipf==backlog_input_file) {
1639 /*---------- filemon implemented with inotify ----------*/
1641 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1642 #define HAVE_FILEMON
1644 #include <linux/inotify.h>
1646 static int filemon_inotify_fd;
1647 static int filemon_inotify_wdmax;
1648 static InputFile **filemon_inotify_wd2ipf;
1650 struct Filemon_Perfile {
1654 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1655 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1656 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1658 if (wd >= filemon_inotify_wdmax) {
1660 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1661 sizeof(*filemon_inotify_wd2ipf) * newmax);
1662 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1663 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1664 filemon_inotify_wdmax= newmax;
1667 assert(!filemon_inotify_wd2ipf[wd]);
1668 filemon_inotify_wd2ipf[wd]= ipf;
1670 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1671 ipf, wd, filemon_inotify_wdmax);
1676 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1678 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1679 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1680 if (r) sysdie("inotify_rm_watch");
1681 filemon_inotify_wd2ipf[wd]= 0;
1684 static void *filemon_inotify_readable(oop_source *lp, int fd,
1685 oop_event e, void *u) {
1686 struct inotify_event iev;
1688 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1690 if (isewouldblock(errno)) break;
1691 sysdie("read from inotify master");
1692 } else if (r==sizeof(iev)) {
1693 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1695 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1697 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1698 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1699 filemon_callback(ipf);
1701 return OOP_CONTINUE;
1704 static int filemon_method_init(void) {
1705 filemon_inotify_fd= inotify_init();
1706 if (filemon_inotify_fd<0) {
1707 syswarn("could not initialise inotify: inotify_init failed");
1711 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1713 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1717 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1719 /*---------- filemon dummy implementation ----------*/
1721 #if !defined(HAVE_FILEMON)
1723 struct Filemon_Perfile { int dummy; };
1725 static int filemon_method_init(void) { return 0; }
1726 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1727 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1729 #endif /* !HAVE_FILEMON */
1731 /*---------- filemon generic interface ----------*/
1733 static void filemon_start(InputFile *ipf) {
1734 assert(!ipf->filemon);
1736 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1737 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1738 filemon_method_startfile(ipf, ipf->filemon);
1741 static void filemon_stop(InputFile *ipf) {
1742 if (!ipf->filemon) return;
1743 filemon_method_stopfile(ipf, ipf->filemon);
1748 static void filemon_callback(InputFile *ipf) {
1749 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1752 /*---------- interface to start and stop an input file ----------*/
1754 static const oop_rd_style feedfile_rdstyle= {
1755 OOP_RD_DELIM_STRIP, '\n',
1757 OOP_RD_SHORTREC_LONG,
1760 static void inputfile_reading_start(InputFile *ipf) {
1762 ipf->readable.on_readable= tailing_on_readable;
1763 ipf->readable.on_cancel= tailing_on_cancel;
1764 ipf->readable.try_read= tailing_try_read;
1765 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1766 ipf->readable.delete_kill= 0;
1768 ipf->readable_callback= 0;
1769 ipf->readable_callback_user= 0;
1771 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1774 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1775 feedfile_got_article,ipf, feedfile_read_err, ipf);
1776 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1779 static void inputfile_reading_stop(InputFile *ipf) {
1781 oop_rd_cancel(ipf->rd);
1782 oop_rd_delete(ipf->rd);
1784 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1788 /*========== interaction with innd - state machine ==========*/
1790 /* See official state diagram at top of file. We implement
1801 |`---------------------------------------------------.
1803 |`---------------- - - - |
1804 D ENOENT | D EXISTS see OVERALL STATES diagram |
1805 | for full startup logic |
1808 | ============ try to |
1814 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1815 ^ | hardlink F to D |
1818 | | our handle onto F is now onto D |
1821 | |<-------------------<---------------------<---------+
1823 | | spawn inndcomm flush |
1825 | ================== |
1826 | FLUSHING[-ABSENT] |
1828 | main D tail/none |
1829 | ================== |
1831 | | INNDCOMM FLUSH FAILS ^
1832 | |`----------------------->----------. |
1834 | | NO SUCH SITE V |
1835 ^ |`--------------->----. ==================== |
1836 | | \ FLUSHFAILED[-ABSENT] |
1838 | | FLUSH OK \ main D tail/none |
1839 | | open F \ ==================== |
1841 | | \ | TIME TO RETRY |
1842 | |`------->----. ,---<---'\ `----------------'
1843 | | D NONE | | D NONE `----.
1845 | ============= V V ============
1846 | SEPARATED-1 | | DROPPING-1
1847 | flsh->rd!=0 | | flsh->rd!=0
1848 | [Separated] | | [Dropping]
1849 | main F idle | | main none
1850 | old D tail | | old D tail
1851 | ============= | | ============
1853 ^ | EOF ON D | | defer | EOF ON D
1855 | =============== | | ===============
1856 | SEPARATED-2 | | DROPPING-2
1857 | flsh->rd==0 | V flsh->rd==0
1858 | [Finishing] | | [Dropping]
1859 | main F tail | `. main none
1860 | old D closed | `. old D closed
1861 | =============== V `. ===============
1863 | | ALL D PROCESSED `. | ALL D PROCESSED
1864 | V install defer as backlog `. | install defer
1865 ^ | close D `. | close D
1866 | | unlink D `. | unlink D
1869 `----------' ==============
1889 static void startup_set_input_file(InputFile *f) {
1890 assert(!main_input_file);
1892 inputfile_reading_start(f);
1895 static void statemc_init(void) {
1896 struct stat stab, stabf;
1898 path_lock= xasprintf("%s_lock", feedfile);
1899 path_flushing= xasprintf("%s_flushing", feedfile);
1900 path_defer= xasprintf("%s_defer", feedfile);
1901 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1904 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1905 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1908 memset(&fl,0,sizeof(fl));
1910 fl.l_whence= SEEK_SET;
1911 int r= fcntl(lockfd, F_SETLK, &fl);
1913 if (errno==EACCES || isewouldblock(errno)) {
1914 if (quiet_multiple) exit(0);
1915 fatal("another duct holds the lockfile");
1917 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1920 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
1922 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1924 if (!lock_noent && samefile(&stab, &stabf))
1927 xclose(lockfd, "stale lockfile ", path_lock);
1929 debug("startup: locked");
1931 search_backlog_file();
1934 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1936 debug("startup: ductdefer ENOENT");
1938 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1939 switch (stab.st_nlink==1) {
1941 open_defer(); /* so that we will later close it and rename it */
1944 xunlink(path_defer, "stale defer file link"
1945 " (presumably hardlink to backlog file)");
1948 die("defer file %s has unexpected link count %d",
1949 path_defer, stab.st_nlink);
1953 struct stat stab_f, stab_d;
1956 InputFile *file_d= open_input_file(path_flushing);
1957 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
1959 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1961 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1962 debug("startup: F==D => Hardlinked");
1963 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1968 debug("startup: F ENOENT => Moved");
1969 if (file_d) startup_set_input_file(file_d);
1970 spawn_inndcomm_flush("feedfile missing at startup");
1971 /* => Flushing, sms:=FLUSHING */
1974 debug("startup: F!=D => Separated");
1975 startup_set_input_file(file_d);
1976 SMS(SEPARATED, 0, "found both old and current feed files");
1978 debug("startup: F exists, D ENOENT => Normal");
1979 InputFile *file_f= open_input_file(feedfile);
1980 if (!file_f) die("feed file vanished during startup");
1981 startup_set_input_file(file_f);
1982 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1987 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1988 assert(sms == sm_NORMAL);
1990 debug("starting flush (%s) (%lu >?= %lu) (%d)",
1992 (unsigned long)(main_input_file ? main_input_file->offset : 0),
1993 (unsigned long)target_max_feedfile_size,
1996 int r= link(feedfile, path_flushing);
1997 if (r) sysdie("link feedfile %s to flushing file %s",
1998 feedfile, path_flushing);
2001 xunlink(feedfile, "old feedfile link");
2004 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2007 static void statemc_period_poll(void) {
2008 if (!sm_period_counter) return;
2009 sm_period_counter--;
2010 assert(sm_period_counter>=0);
2012 if (sm_period_counter) return;
2015 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2017 case sm_FLUSHFAILED:
2018 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2025 static int inputfile_is_done(InputFile *ipf) {
2027 if (ipf->inprogress) return 0; /* new article in the meantime */
2028 if (ipf->rd) return 0; /* not had EOF */
2032 static void notice_processed(InputFile *ipf, const char *what,
2034 #define RCI_NOTHING(x) /* nothing */
2035 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2036 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2038 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2040 info("processed %s%s read=%d(+%dbl,+%derr)"
2041 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2042 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2045 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2046 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2047 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2048 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2049 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2050 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2056 static void statemc_check_backlog_done(void) {
2057 InputFile *ipf= backlog_input_file;
2058 if (!inputfile_is_done(ipf)) return;
2060 const char *slash= strrchr(ipf->path, '/');
2061 const char *leaf= slash ? slash+1 : ipf->path;
2062 const char *under= strchr(slash, '_');
2063 const char *rest= under ? under+1 : leaf;
2064 if (!strncmp(rest,"backlog",7)) rest += 7;
2065 notice_processed(ipf,"backlog:",rest);
2067 close_input_file(ipf);
2068 if (unlink(ipf->path)) {
2069 if (errno != ENOENT)
2070 sysdie("could not unlink processed backlog file %s", ipf->path);
2071 warn("backlog file %s vanished while we were reading it"
2072 " so we couldn't remove it (but it's done now, anyway)",
2076 backlog_input_file= 0;
2077 search_backlog_file();
2081 static void statemc_check_flushing_done(void) {
2082 InputFile *ipf= flushing_input_file;
2083 if (!inputfile_is_done(ipf)) return;
2085 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2087 notice_processed(ipf,"feedfile",0);
2091 xunlink(path_flushing, "old flushing file");
2093 close_input_file(flushing_input_file);
2094 free(flushing_input_file);
2095 flushing_input_file= 0;
2097 if (sms==sm_SEPARATED) {
2098 notice("flush complete");
2099 SMS(NORMAL, 0, "flush complete");
2100 } else if (sms==sm_DROPPING) {
2101 SMS(DROPPED, 0, "old flush complete");
2102 search_backlog_file();
2103 notice("feed dropped, but will continue until backlog is finished");
2107 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2109 assert(!inputfile_is_done(main_input_file));
2110 statemc_check_flushing_done();
2111 statemc_check_backlog_done();
2112 return OOP_CONTINUE;
2115 static void queue_check_input_done(void) {
2116 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2119 static void statemc_setstate(StateMachineState newsms, int periods,
2120 const char *forlog, const char *why) {
2122 sm_period_counter= periods;
2124 const char *xtra= "";
2127 case sm_FLUSHFAILED:
2128 if (!main_input_file) xtra= "-ABSENT";
2132 xtra= flushing_input_file->rd ? "-1" : "-2";
2138 info("%s%s[%d] %s",forlog,xtra,periods,why);
2140 info("%s%s %s",forlog,xtra,why);
2144 /*---------- defer and backlog files ----------*/
2146 static void open_defer(void) {
2151 defer= fopen(path_defer, "a+");
2152 if (!defer) sysfatal("could not open defer file %s", path_defer);
2154 /* truncate away any half-written records */
2156 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2158 if (stab.st_size > LONG_MAX)
2159 die("defer file %s size is far too large", path_defer);
2164 long orgsize= stab.st_size;
2165 long truncto= stab.st_size;
2167 if (!truncto) break; /* was only (if anything) one half-truncated record */
2168 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2169 sysdie("seek in defer file %s while truncating partial", path_defer);
2174 sysdie("failed read from defer file %s", path_defer);
2176 die("defer file %s shrank while we were checking it!", path_defer);
2182 if (stab.st_size != truncto) {
2183 warn("truncating half-record at end of defer file %s -"
2184 " shrinking by %ld bytes from %ld to %ld",
2185 path_defer, orgsize - truncto, orgsize, truncto);
2188 sysfatal("could not flush defer file %s", path_defer);
2189 if (ftruncate(fileno(defer), truncto))
2190 sysdie("could not truncate defer file %s", path_defer);
2193 info("continuing existing defer file %s (%ld bytes)",
2194 path_defer, orgsize);
2196 if (fseek(defer, truncto, SEEK_SET))
2197 sysdie("could not seek to new end of defer file %s", path_defer);
2200 static void close_defer(void) {
2205 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2207 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2210 time_t now= xtime();
2212 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2214 (unsigned long)stab.st_ino);
2215 if (link(path_defer, backlog))
2216 sysfatal("could not install defer file %s as backlog file %s",
2217 path_defer, backlog);
2218 if (unlink(path_defer))
2219 sysdie("could not unlink old defer link %s to backlog file %s",
2220 path_defer, backlog);
2224 if (until_backlog_nextscan < 0 ||
2225 until_backlog_nextscan > backlog_retry_minperiods + 1)
2226 until_backlog_nextscan= backlog_retry_minperiods + 1;
2229 static void poll_backlog_file(void) {
2230 if (until_backlog_nextscan < 0) return;
2231 if (until_backlog_nextscan-- > 0) return;
2232 search_backlog_file();
2235 static void search_backlog_file(void) {
2236 /* returns non-0 iff there are any backlog files */
2241 const char *oldest_path=0;
2242 time_t oldest_mtime=0, now;
2244 if (backlog_input_file) return;
2248 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2252 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2254 die("out of memory expanding backlog pattern %s", globpat_backlog);
2256 for (i=0; i<gl.gl_pathc; i++) {
2257 const char *path= gl.gl_pathv[i];
2259 if (strchr(path,'#') || strchr(path,'~')) {
2260 debug("backlog file search skipping %s", path);
2263 r= stat(path, &stab);
2265 syswarn("failed to stat backlog file %s", path);
2268 if (!S_ISREG(stab.st_mode)) {
2269 warn("backlog file %s is not a plain file (or link to one)", path);
2272 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2274 oldest_mtime= stab.st_mtime;
2277 case GLOB_NOMATCH: /* fall through */
2280 sysdie("glob expansion of backlog pattern %s gave unexpected"
2281 " nonzero (error?) return value %d", globpat_backlog, r);
2285 debug("backlog scan: none");
2287 if (sms==sm_DROPPED) {
2288 notice("feed dropped and our work is complete");
2289 xunlink(path_lock, "lockfile for old feed");
2292 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2297 double age= difftime(now, oldest_mtime);
2298 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2300 if (age_deficiency <= 0) {
2301 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2302 age, age_deficiency, oldest_path);
2304 backlog_input_file= open_input_file(oldest_path);
2305 if (!backlog_input_file) {
2306 warn("backlog file %s vanished as we opened it", oldest_path);
2310 inputfile_reading_start(backlog_input_file);
2311 until_backlog_nextscan= -1;
2315 until_backlog_nextscan= age_deficiency / period_seconds;
2317 if (backlog_spontaneous_rescan_periods >= 0 &&
2318 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2319 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2321 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2322 age, age_deficiency, until_backlog_nextscan, oldest_path);
2329 /*========== flushing the feed ==========*/
2331 static pid_t inndcomm_child;
2332 static int inndcomm_sentinel_fd;
2334 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2335 assert(inndcomm_child);
2336 assert(fd == inndcomm_sentinel_fd);
2337 int status= xwaitpid(&inndcomm_child, "inndcomm");
2338 cancel_fd_read_except(fd);
2339 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2341 assert(!flushing_input_file);
2343 if (WIFEXITED(status)) {
2344 switch (WEXITSTATUS(status)) {
2346 case INNDCOMMCHILD_ESTATUS_FAIL:
2349 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2350 warn("feed has been dropped by innd, finishing up");
2351 flushing_input_file= main_input_file;
2352 tailing_queue_readable(flushing_input_file);
2353 /* we probably previously returned EAGAIN from our fake read method
2354 * when in fact we were at EOF, so signal another readable event
2355 * so we actually see the EOF */
2359 if (flushing_input_file) {
2360 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2363 SMS(DROPPED, 0, "feed dropped by innd");
2364 search_backlog_file();
2366 return OOP_CONTINUE;
2370 flushing_input_file= main_input_file;
2371 tailing_queue_readable(flushing_input_file);
2373 main_input_file= open_input_file(feedfile);
2374 if (!main_input_file)
2375 die("flush succeeded but feedfile %s does not exist!", feedfile);
2377 if (flushing_input_file) {
2378 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2381 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2383 return OOP_CONTINUE;
2386 goto unexpected_exitstatus;
2389 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2390 warn("flush timed out trying to talk to innd");
2393 unexpected_exitstatus:
2394 report_child_status("inndcomm child", status);
2398 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2399 return OOP_CONTINUE;
2402 static void inndcommfail(const char *what) {
2403 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2404 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2407 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2410 notice("flushing %s",why);
2412 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2413 assert(!inndcomm_child);
2414 assert(!inndcomm_sentinel_fd);
2416 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2418 inndcomm_child= xfork("inndcomm child");
2420 if (!inndcomm_child) {
2421 const char *flushargv[2]= { sitename, 0 };
2425 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2426 /* parent spots the autoclose of pipefds[1] when we die or exit */
2428 alarm(inndcomm_flush_timeout);
2429 r= ICCopen(); if (r) inndcommfail("connect");
2430 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2431 if (!r) exit(0); /* yay! */
2433 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2434 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2435 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2438 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2439 inndcomm_sentinel_fd= pipefds[0];
2440 assert(inndcomm_sentinel_fd);
2441 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2443 SMS(FLUSHING, 0, why);
2446 /*========== main program ==========*/
2448 static void postfork_inputfile(InputFile *ipf) {
2450 xclose(ipf->fd, "(in child) input file ", ipf->path);
2453 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2454 /* we have no stdio streams that are buffered long-term */
2456 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2459 static void postfork(void) {
2460 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2461 sysdie("(in child) failed to reset SIGPIPE");
2463 postfork_inputfile(main_input_file);
2464 postfork_inputfile(flushing_input_file);
2467 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2468 conn_closefd(conn,"(in child) ");
2470 postfork_stdio(defer, "defer file ", path_defer);
2473 #define EVERY(what, interval_sec, interval_usec, body) \
2474 static struct timeval what##_timeout = { interval_sec, interval_usec }; \
2475 static void what##_schedule(void); \
2476 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2478 what##_schedule(); \
2479 return OOP_CONTINUE; \
2481 static void what##_schedule(void) { \
2482 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2485 EVERY(filepoll, 5,0, ({
2486 if (main_input_file && main_input_file->readable_callback)
2487 filemon_callback(main_input_file);
2490 static char *debug_report_ipf(InputFile *ipf) {
2491 if (!ipf) return xasprintf("-");
2493 const char *slash= strrchr(ipf->path,'/');
2494 const char *path= slash ? slash+1 : ipf->path;
2496 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2498 ipf->inprogress, (long)ipf->offset,
2499 ipf->fd, ipf->rd ? "+" : "");
2502 EVERY(period, -1,0, ({
2503 char *dipf_main= debug_report_ipf(main_input_file);
2504 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2505 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2508 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2509 " input_files main:%s old:%s flushing:%s"
2510 " children connecting=%ld inndcomm_child=%ld"
2512 sms_names[sms], sm_period_counter,
2513 conns.count, queue.count, until_connect,
2514 dipf_main, dipf_flushing, dipf_backlog,
2515 (long)connecting_child, (long)inndcomm_child
2519 free(dipf_flushing);
2522 if (until_connect) until_connect--;
2524 poll_backlog_file();
2525 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2526 statemc_period_poll();
2527 check_assign_articles();
2532 /*========== option parsing ==========*/
2534 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2535 static void vbadusage(const char *fmt, va_list al) {
2536 char *m= xvasprintf(fmt,al);
2537 fprintf(stderr, "bad usage: %s\n"
2538 "say --help for help, or read the manpage\n",
2541 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2545 /*---------- generic option parser ----------*/
2547 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2548 static void badusage(const char *fmt, ...) {
2555 of_seconds= 001000u,
2556 of_boolean= 002000u,
2559 typedef struct Option Option;
2560 typedef void OptionParser(const Option*, const char *val);
2564 const char *lng, *formarg;
2570 static void parse_options(const Option *options, char ***argvp) {
2571 /* on return *argvp is first non-option arg; argc is not updated */
2574 const char *arg= *++(*argvp);
2576 if (*arg != '-') break;
2577 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2579 while ((a= *++arg)) {
2583 char *equals= strchr(arg,'=');
2584 int len= equals ? (equals - arg) : strlen(arg);
2585 for (o=options; o->shrt || o->lng; o++)
2586 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2588 badusage("unknown long option --%s",arg);
2591 if (equals) badusage("option --%s does not take a value",o->lng);
2593 } else if (equals) {
2597 if (!arg) badusage("option --%s needs a value for %s",
2598 o->lng, o->formarg);
2601 break; /* eaten the whole argument now */
2603 for (o=options; o->shrt || o->lng; o++)
2606 badusage("unknown short option -%c",a);
2613 if (!arg) badusage("option -%c needs a value for %s",
2614 o->shrt, o->formarg);
2617 break; /* eaten the whole argument now */
2623 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
2625 static void print_options(const Option *options, FILE *f) {
2627 for (o=options; o->shrt || o->lng; o++) {
2628 char shrt[2] = { o->shrt, 0 };
2629 char *optspec= xasprintf("%s%s%s%s%s",
2630 o->shrt ? "-" : "", shrt,
2631 o->shrt && o->lng ? "|" : "",
2632 DELIMPERHAPS("--", o->lng));
2633 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
2638 /*---------- specific option types ----------*/
2640 static void op_integer(const Option *o, const char *val) {
2643 unsigned long ul= strtoul(val,&ep,10);
2644 if (*ep || ep==val || errno || ul>INT_MAX)
2645 badusage("bad integer value for %s",o->lng);
2646 int *store= o->store;
2650 static void op_double(const Option *o, const char *val) {
2651 int *store= o->store;
2654 *store= strtod(val, &ep);
2655 if (*ep || ep==val || errno)
2656 badusage("bad floating point value for %s",o->lng);
2659 static void op_string(const Option *o, const char *val) {
2660 const char **store= o->store;
2664 static void op_seconds(const Option *o, const char *val) {
2665 int *store= o->store;
2669 double v= strtod(val,&ep);
2670 if (ep==val) badusage("bad time/duration value for %s",o->lng);
2672 if (!*ep || !strcmp(ep,"s")) unit= 1;
2673 else if (!strcmp(ep,"m")) unit= 60;
2674 else if (!strcmp(ep,"h")) unit= 3600;
2675 else if (!strcmp(ep,"d")) unit= 86400;
2676 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2680 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2684 static void op_periods_rndup(const Option *o, const char *val) {
2685 int *store= o->store;
2687 *store += period_seconds-1;
2688 *store /= period_seconds;
2691 static void op_setint(const Option *o, const char *val) {
2692 int *store= o->store;
2696 /*---------- specific options ----------*/
2698 static void help(const Option *o, const char *val);
2700 static const Option innduct_options[]= {
2701 {'f',"feedfile", "F", &feedfile, op_string },
2702 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
2703 {0,"help", 0, help },
2705 {0,"max-connections", "N", &max_connections, op_integer },
2706 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
2709 {0,"streaming", 0, &try_stream, op_setint, 1 },
2710 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
2711 {'P',"port", "PORT",&port, op_integer },
2712 {0,"inndconf", "F", &inndconffile, op_string },
2713 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
2715 {0,"no-check-proportion","PERCENT", &nocheck_thresh_pct, op_double },
2716 {0,"no-check-filter", "ARTICLES", &nocheck_decay_articles, op_double },
2718 {0,"reconnect-interval", "TIME", &reconnect_delay_periods, op_periods_rndup },
2719 {0,"flush-retry-interval","TIME", &flushfail_retry_periods, op_periods_rndup },
2720 {0,"inndcomm-timeout", "TIME", &inndcomm_flush_timeout, op_seconds },
2724 static void printusage(FILE *f) {
2725 fputs("usage: innduct [options] site [fqdn]\n"
2726 "available options are:\n", f);
2727 print_options(innduct_options, f);
2730 static void help(const Option *o, const char *val) {
2732 if (ferror(stdout) || fflush(stdout)) {
2733 perror("innduct: writing help");
2739 int main(int argc, char **argv) {
2745 parse_options(innduct_options, &argv);
2750 if (!sitename) badusage("need site name argument");
2751 remote_host= *argv++;
2752 if (*argv) badusage("too many non-option arguments");
2756 if (!remote_host) remote_host= sitename;
2758 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2759 badusage("nocheck threshold percentage must be between 0..100");
2760 nocheck_thresh= nocheck_thresh_pct * 0.01;
2762 if (nocheck_decay_articles < 0.1)
2763 badusage("nocheck decay articles must be at least 0.1");
2764 nocheck_decay= 1 - 1/nocheck_decay_articles;
2767 pathoutgoing= innconf->pathoutgoing;
2768 innconf_read(inndconffile);
2771 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2772 else if (!feedfile[0])
2773 badusage("feed filename must be nonempty");
2774 else if (feedfile[strlen(feedfile)-1]=='/')
2775 feedfile= xasprintf("%s%s",feedfile,sitename);
2777 const char *feedfile_forbidden= "?*[~#";
2779 while ((c= *feedfile_forbidden++))
2780 if (strchr(feedfile, c))
2781 badusage("feed filename may not contain metacharacter %c",c);
2785 oop_source_sys *sysloop= oop_sys_new();
2786 if (!sysloop) sysdie("could not create liboop event loop");
2787 loop= (oop_source*)sysloop;
2789 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2790 sysdie("could not ignore SIGPIPE");
2795 if (become_daemon) {
2797 for (i=3; i<255; i++)
2798 /* do this now before we open syslog, etc. */
2800 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2802 int null= open("/dev/null",O_RDWR);
2803 if (null<0) sysdie("failed to open /dev/null");
2807 xclose(null, "/dev/null original fd",0);
2809 pid_t child1= xfork("daemonise first fork");
2810 if (child1) _exit(0);
2812 pid_t sid= setsid();
2813 if (sid != child1) sysdie("setsid failed");
2815 pid_t child2= xfork("daemonise second fork");
2816 if (child2) _exit(0);
2821 if (!filemon_method_init()) {
2822 warn("no file monitoring available, polling");
2823 filepoll_schedule();
2826 period_timeout.tv_sec= period_seconds;
2833 void *r= oop_sys_run(sysloop);
2834 assert(r == OOP_ERROR);
2835 sysdie("event loop failed");