3 * - pid, sitename, hostname in lockfile
7 * Newsfeeds file entries should look like this:
8 * host.name.of.site[/exclude,exclude,...]\
9 * :pattern,pattern...[/distribution,distribution...]\
13 * sitename[/exclude,exclude,...]\
14 * :pattern,pattern...[/distribution,distribution...]\
20 * or might be blanked out
21 * <spc><spc><spc><spc>....
23 * F site.name main feed file
24 * opened/created, then written, by innd
27 * tokens blanked out by duct when processed
28 * site.name_lock lock preventing multiple ducts
29 * to hold lock must open,F_SETLK[W]
30 * and then stat to check that locked file
31 * still has name site.name_lock
32 * holder of this lock is "duct"
33 * (only) lockholder may remove the lockfile
34 * D site.name_flushing temporary feed file during flush (or crash)
35 * hardlink created by duct
37 * site.name_defer 431'd articles, still being written,
38 * created, written, used by duct
40 * site.name_backlog.<date>.<inum>
41 * 431'd articles, ready for innxmit or duct
42 * created (link/mv) by duct
43 * site.name_backlog<anything-else> (where <anything-else> does not
44 * contain '#' or '~') eg
45 * site.name_backlog.manual
46 * anything the sysadmin likes (eg, feed files
47 * from old feeds to be merged into this one)
48 * created (link/mv) by admin
49 * may be symlinks (in which case links
50 * may be written through, but only links
53 * It is safe to remove backlog files manually,
54 * if it's desired to throw away the backlog.
56 * Backlog files are also processed by innduct. We find the oldest
57 * backlog file which is at least a certain amount old, and feed it
58 * back into our processing. When every article in it has been read
59 * and processed, we unlink it and look for another backlog file.
61 * If we don't have a backlog file that we're reading, we close the
62 * defer file that we're writing and make it into a backlog file at
63 * the first convenient opportunity.
74 | | <----------------<---------------------------------'|
80 | F: innd writing, duct reading |
83 | | duct decides time to flush |
84 | | duct makes hardlink |
86 | V <------------------------'|
88 | F == D: innd writing, duct reading both exist |
91 | | <-----------<-------------<--'|
95 | V <---------------------. |
98 | D: innd writing, duct reading; or ENOENT | |
100 | | duct requests flush of feed | |
101 | | (others can too, harmlessly) | |
105 | D: innd flushing, duct; or ENOENT | |
107 | | inndcomm flush fails | |
108 | |`-------------------------->------------------' |
110 | | inndcomm reports no such site |
111 | |`---------------------------------------------------- | -.
113 | | innd finishes writing D, creates F | |
114 | | inndcomm reports flush successful | |
117 | Separated <----------------' |
118 | F: innd writing F!=D /
119 | D: duct reading; or ENOENT both exist /
121 | | duct gets to the end of D /
122 | | duct opens F too /
125 | F: innd writing, duct reading |
126 | D: duct finishing V
128 | | duct finishes processing D F: ENOENT
129 | V duct unlinks D D: duct reading
131 `--<--' | duct finishes
141 "duct reading" means innduct is reading the file but also
142 overwriting processed tokens.
146 * rune for printing diagrams:
148 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
153 /*============================== PROGRAM ==============================*/
155 #define _GNU_SOURCE 1
161 #include "inndcomm.h"
163 #include "inn/list.h"
164 #include "inn/innconf.h"
167 #include <sys/types.h>
168 #include <sys/wait.h>
169 #include <sys/stat.h>
170 #include <sys/socket.h>
186 #include <oop-read.h>
188 /*----- general definitions, probably best not changed -----*/
190 #define CONNCHILD_ESTATUS_STREAM 24
191 #define CONNCHILD_ESTATUS_NOSTREAM 25
193 #define INNDCOMMCHILD_ESTATUS_FAIL 26
194 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
196 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
198 #define VA va_list al; va_start(al,fmt)
199 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
200 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
202 /*----- doubly linked lists -----*/
204 #define ISNODE(T) struct node list_node
207 union { struct list li; T *for_type; } u; \
211 #define NODE(n) (assert((void*)&(n)->list_node == &(n)), &(n)->list_node)
213 #define LIST_CHECKCANHAVENODE(l,n) \
214 ((void)((n) == ((l).u.for_type))) /* just for the type check */
216 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
217 ( LIST_CHECKCANHAVENODE(l,n), \
218 list_addsomehow(&(l).u.li, NODE((n))), \
222 #define LIST_REMSOMEHOW(l,list_remsomehow) \
223 ( (typeof((l).u.for_type)) \
226 list_remsomehow(&(l).u.li) ) \
232 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
233 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
234 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
235 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
237 #define LIST_INIT(l) (list_new(&(l).u.li))
238 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
239 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
240 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
242 #define LIST_REMOVE(l,n) \
243 ( LIST_CHECKCANHAVENODE(l,n), \
244 list_remove(NODE((n))), \
248 #define LIST_INSERT(l,n,pred) \
249 ( LIST_CHECKCANHAVENODE(l,n), \
250 LIST_CHECKCANHAVENODE(l,pred), \
251 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
255 /*----- type predeclarations -----*/
257 typedef struct Conn Conn;
258 typedef struct Article Article;
259 typedef struct InputFile InputFile;
260 typedef struct XmitDetails XmitDetails;
261 typedef struct Filemon_Perfile Filemon_Perfile;
262 typedef enum StateMachineState StateMachineState;
267 /*----- function predeclarations -----*/
269 static void conn_maybe_write(Conn *conn);
270 static void conn_make_some_xmits(Conn *conn);
271 static void *conn_write_some_xmits(Conn *conn);
273 static void xmit_free(XmitDetails *d);
275 #define SMS(newstate, periods, why) \
276 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
277 static void statemc_setstate(StateMachineState newsms, int periods,
278 const char *forlog, const char *why);
280 static void statemc_start_flush(const char *why); /* Normal => Flushing */
281 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
283 static void check_assign_articles(void);
284 static void queue_check_input_done(void);
286 static void statemc_check_flushing_done(void);
287 static void statemc_check_backlog_done(void);
289 static void postfork(void);
291 static void open_defer(void);
292 static void close_defer(void);
293 static void search_backlog_file(void);
295 static void inputfile_reading_start(InputFile *ipf);
296 static void inputfile_reading_stop(InputFile *ipf);
298 static void filemon_start(InputFile *ipf);
299 static void filemon_stop(InputFile *ipf);
300 static void filemon_callback(InputFile *ipf);
302 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
303 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
305 static const oop_rd_style peer_rd_style;
306 static oop_rd_call peer_rd_err, peer_rd_ok;
308 /*----- configuration options -----*/
309 /* when changing defaults, remember to update the manpage */
311 static const char *sitename, *remote_host;
312 static const char *feedfile;
313 static int quiet_multiple=0;
314 static int become_daemon=1;
315 static int try_stream=1;
317 static const char *inndconffile;
319 static int max_connections=10;
320 static int max_queue_per_conn=200;
321 static int target_max_feedfile_size=100000;
322 static int period_seconds=60;
324 static int connection_setup_timeout=200;
325 static int inndcomm_flush_timeout=100;
327 static double nocheck_thresh= 95.0; /* converted from percentage by main */
328 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
330 /* all these are initialised to seconds, and converted to periods in main */
331 static int reconnect_delay_periods=1000;
332 static int flushfail_retry_periods=1000;
333 static int backlog_retry_minperiods=50;
334 static int backlog_spontrescan_periods=300;
335 static int spontaneous_flush_periods=100000;
336 static int need_activity_periods=1000;
338 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
339 static int max_bad_data_initial= 30;
340 /* in one corrupt 4096-byte block the number of newlines has
341 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
344 /*----- statistics -----*/
346 typedef enum { /* in queue in conn->sent */
347 art_Unchecked, /* not checked, not sent checking */
348 art_Wanted, /* checked, wanted sent body as requested */
349 art_Unsolicited, /* - sent body without check */
353 #define RESULT_COUNTS(RCS,RCN) \
361 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
362 #define RCI_TRIPLE_VALS_BASE(counts,x) \
363 counts[art_Unchecked] x \
364 + counts[art_Wanted] x \
365 + counts[art_Unsolicited] x, \
366 counts[art_Unchecked] x \
367 , counts[art_Wanted] x \
368 , counts[art_Unsolicited] x
371 #define RC_INDEX(x) RC_##x,
372 RESULT_COUNTS(RC_INDEX, RC_INDEX)
377 /*----- transmission buffers -----*/
382 xk_Malloc, xk_Const, xk_Artdata
394 /*----- core operational data structure types -----*/
397 /* This is also an instance of struct oop_readable */
398 struct oop_readable readable; /* first */
399 oop_readable_call *readable_callback;
400 void *readable_callback_user;
403 Filemon_Perfile *filemon;
405 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
406 long inprogress; /* no. of articles read but not processed */
410 int counts[art_MaxState][RCI_max];
411 int readcount_ok, readcount_blank, readcount_err;
426 #define SMS_LIST(X) \
434 enum StateMachineState {
435 #define SMS_DEF_ENUM(s) sm_##s,
436 SMS_LIST(SMS_DEF_ENUM)
439 static const char *sms_names[]= {
440 #define SMS_DEF_NAME(s) #s ,
441 SMS_LIST(SMS_DEF_NAME)
447 int fd; /* may be 0, meaning closed (during construction/destruction) */
448 oop_read *rd; /* likewise */
449 int max_queue, stream, quitting;
450 int since_activity; /* periods */
451 ArticleList waiting; /* not yet told peer */
452 ArticleList priority; /* peer says send it now */
453 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
454 struct iovec xmit[CONNIOVS];
455 XmitDetails xmitd[CONNIOVS];
460 /*----- general operational variables -----*/
462 /* main initialises */
463 static oop_source *loop;
464 static ConnList conns;
465 static ArticleList queue;
466 static char *path_lock, *path_flushing, *path_defer, *globpat_backlog;
468 /* statemc_init initialises */
469 static StateMachineState sms;
471 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
472 static int sm_period_counter;
474 /* initialisation to 0 is good */
475 static int until_connect, until_backlog_nextscan;
476 static double accept_proportion;
477 static int nocheck, nocheck_reported;
479 /*========== logging ==========*/
481 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
482 static void logcore(int sysloglevel, const char *fmt, ...) {
485 vsyslog(sysloglevel,fmt,al);
487 vfprintf(stderr,fmt,al);
493 static void logv(int sysloglevel, const char *pfx, int errnoval,
494 const char *fmt, va_list al) PRINTF(5,0);
495 static void logv(int sysloglevel, const char *pfx, int errnoval,
496 const char *fmt, va_list al) {
497 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
498 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
499 msgbuf[sizeof(msgbuf)-1]= 0;
501 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
502 sysloglevel= LOG_ERR; /* run by wrong user, probably */
504 logcore(sysloglevel, "<%s>%s: %s%s%s",
505 sitename, pfx, msgbuf,
506 errnoval>=0 ? ": " : "",
507 errnoval>=0 ? strerror(errnoval) : "");
510 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
511 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
512 static void fn(const char *fmt, ...) { \
514 logv(sysloglevel, pfx, err, fmt, al); \
518 #define logwrap(fn, pfx, sysloglevel, err) \
519 static void fn(const char *fmt, ...) PRINTF(1,2); \
520 static void fn(const char *fmt, ...) { \
522 logv(sysloglevel, pfx, err, fmt, al); \
526 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
527 diewrap(die, " critical", LOG_CRIT, -1, 16);
529 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
530 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
532 logwrap(syswarn, " warning", LOG_WARNING, errno);
533 logwrap(warn, " warning", LOG_WARNING, -1);
535 logwrap(notice, "", LOG_NOTICE, -1);
536 logwrap(info, " info", LOG_INFO, -1);
537 logwrap(debug, " debug", LOG_DEBUG, -1);
540 /*========== utility functions etc. ==========*/
542 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
543 static char *xvasprintf(const char *fmt, va_list al) {
545 int rc= vasprintf(&str,fmt,al);
546 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
549 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
550 static char *xasprintf(const char *fmt, ...) {
552 char *str= xvasprintf(fmt,al);
557 static int close_perhaps(int *fd) {
563 static void xclose(int fd, const char *what, const char *what2) {
565 if (r) sysdie("close %s%s",what,what2?what2:"");
567 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
569 xclose(*fd,what,what2);
573 static pid_t xfork(const char *what) {
577 if (child==-1) sysfatal("cannot fork for %s",what);
578 debug("forked %s %ld", what, (unsigned long)child);
579 if (!child) postfork();
583 static void on_fd_read_except(int fd, oop_call_fd callback) {
584 loop->on_fd(loop, fd, OOP_READ, callback, 0);
585 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
587 static void cancel_fd_read_except(int fd) {
588 loop->cancel_fd(loop, fd, OOP_READ);
589 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
592 static void report_child_status(const char *what, int status) {
593 if (WIFEXITED(status)) {
594 int es= WEXITSTATUS(status);
596 warn("%s: child died with error exit status %d", what, es);
597 } else if (WIFSIGNALED(status)) {
598 int sig= WTERMSIG(status);
599 const char *sigstr= strsignal(sig);
600 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
602 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
604 warn("%s: child died due to unknown fatal signal %d%s",
605 what, sig, coredump);
607 warn("%s: child died with unknown wait status %d", what,status);
611 static int xwaitpid(pid_t *pid, const char *what) {
614 int r= kill(*pid, SIGKILL);
615 if (r) sysdie("cannot kill %s child", what);
617 pid_t got= waitpid(*pid, &status, WNOHANG);
618 if (got==-1) sysdie("cannot reap %s child", what);
625 static void xunlink(const char *path, const char *what) {
627 if (r) sysdie("can't unlink %s %s", path, what);
630 static time_t xtime(void) {
632 if (now==-1) sysdie("time(2) failed");
636 static void check_isreg(const struct stat *stab, const char *path,
638 if (!S_ISREG(stab->st_mode))
639 die("%s %s not a plain file (mode 0%lo)",
640 what, path, (unsigned long)stab->st_mode);
643 static void xfstat(int fd, struct stat *stab_r, const char *what) {
644 int r= fstat(fd, stab_r);
645 if (r) sysdie("could not fstat %s", what);
648 static void xfstat_isreg(int fd, struct stat *stab_r,
649 const char *path, const char *what) {
650 xfstat(fd, stab_r, what);
651 check_isreg(stab_r, path, what);
654 static void xlstat_isreg(const char *path, struct stat *stab,
655 int *enoent_r /* 0 means ENOENT is fatal */,
657 int r= lstat(path, stab);
659 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
660 sysdie("could not lstat %s %s", what, path);
662 if (enoent_r) *enoent_r= 0;
663 check_isreg(stab, path, what);
666 static int samefile(const struct stat *a, const struct stat *b) {
667 assert(S_ISREG(a->st_mode));
668 assert(S_ISREG(b->st_mode));
669 return (a->st_ino == b->st_ino &&
670 a->st_dev == b->st_dev);
673 static char *sanitise(const char *input) {
674 static char sanibuf[100]; /* returns pointer to this buffer! */
676 const char *p= input;
680 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
682 if (!c) { *q++= '\''; *q=0; break; }
683 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
684 sprintf(q,"\\x%02x",c);
690 static int isewouldblock(int errnoval) {
691 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
694 /*========== management of connections ==========*/
696 static void conn_closefd(Conn *conn, const char *msgprefix) {
697 int r= close_perhaps(&conn->fd);
698 if (r) info("C%d %serror closing socket: %s",
699 conn->fd, msgprefix, strerror(errno));
702 static void conn_dispose(Conn *conn) {
705 oop_rd_cancel(conn->rd);
706 oop_rd_delete_kill(conn->rd);
710 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
711 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
713 conn_closefd(conn,"");
715 until_connect= reconnect_delay_periods;
718 static void *conn_exception(oop_source *lp, int fd,
719 oop_event ev, void *conn_v) {
722 assert(fd == conn->fd);
723 assert(ev == OOP_EXCEPTION);
724 int r= read(conn->fd, &ch, 1);
725 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
726 else connfail(conn,"exceptional condition on socket (peer sent urgent"
727 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
731 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
732 int requeue[art_MaxState];
735 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
736 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
737 while ((art= LIST_REMHEAD(conn->sent))) {
738 requeue[art->state]++;
739 if (art->state==art_Unsolicited) art->state= art_Unchecked;
740 LIST_ADDTAIL(queue,art);
745 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
748 char *m= xvasprintf(fmt,al);
749 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
750 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
753 LIST_REMOVE(conns,conn);
755 check_assign_articles();
758 static void connfail(Conn *conn, const char *fmt, ...) {
761 vconnfail(conn,fmt,al);
765 static void check_idle_conns(void) {
767 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
768 conn->since_activity++;
770 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
771 if (conn->since_activity <= need_activity_periods) continue;
773 /* We need to shut this down */
775 connfail(conn,"timed out waiting for response to QUIT");
776 else if (conn->sent.count)
777 connfail(conn,"timed out waiting for responses");
778 else if (conn->waiting.count || conn->priority.count)
779 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
780 else if (conn->xmitu)
781 connfail(conn,"peer has been sending responses"
782 " before receiving our commands!");
784 static const char quitcmd[]= "QUIT\r\n";
785 int todo= sizeof(quitcmd)-1;
786 const char *p= quitcmd;
788 int r= write(conn->fd, p, todo);
790 if (isewouldblock(errno))
791 connfail(conn, "blocked writing QUIT to idle connection");
793 connfail(conn, "failed to write QUIT to idle connection: %s",
801 conn->since_activity= 0;
802 debug("C%d is idle, quitting", conn->fd);
811 /*---------- making new connections ----------*/
813 static pid_t connecting_child;
814 static int connecting_fdpass_sock;
816 static void connect_attempt_discard(void) {
817 if (connecting_child) {
818 int r= kill(connecting_child, SIGTERM);
819 if (r) syswarn("failed to kill connecting child");
820 int status= xwaitpid(&connecting_child, "connect");
822 if (!(WIFEXITED(status) ||
823 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
824 report_child_status("connect", status);
826 if (connecting_fdpass_sock) {
827 cancel_fd_read_except(connecting_fdpass_sock);
828 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
832 #define PREP_DECL_MSG_CMSG(msg) \
834 memset(&msg,0,sizeof(msg)); \
835 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
836 msg.msg_control= msg##cbuf; \
837 msg.msg_controllen= sizeof(msg##cbuf);
839 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
842 assert(fd == connecting_fdpass_sock);
844 conn= xmalloc(sizeof(*conn));
845 memset(conn,0,sizeof(*conn));
847 PREP_DECL_MSG_CMSG(msg);
848 struct cmsghdr *h= 0;
849 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
850 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
853 pid_t got= waitpid(connecting_child, &status, WNOHANG);
855 assert(got==connecting_child);
857 if (WIFEXITED(status)) {
858 if (WEXITSTATUS(status) != 0 &&
859 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
860 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
861 /* child already reported the problem */;
863 warn("connect: connection child exited code %d but no cmsg",
864 WEXITSTATUS(status));
865 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
866 warn("connect: connection attempt timed out");
868 report_child_status("connect", status);
871 /* child is still running apparently, report the socket problem */
873 syswarn("connect: read from fdpass socket failed");
874 else if (e == OOP_EXCEPTION)
875 warn("connect: unexpected exception on fdpass socket");
877 warn("connect: unexpected EOF on fdpass socket");
879 fatal("connect: unexpected lack of cmsg from child");
884 #define CHK(field, val) \
885 if (h->cmsg_##field != val) { \
886 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
887 h->cmsg_##field, val); \
890 CHK(level, SOL_SOCKET);
891 CHK(type, SCM_RIGHTS);
892 CHK(len, CMSG_LEN(sizeof(conn->fd)));
895 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
897 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
900 pid_t got= waitpid(connecting_child, &status, 0);
901 if (got==-1) sysdie("connect: real wait for child");
902 assert(got == connecting_child);
905 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
906 int es= WEXITSTATUS(status);
908 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
909 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
911 fatal("connect: child gave unexpected exit status %d", es);
915 LIST_INIT(conn->waiting);
916 LIST_INIT(conn->priority);
917 LIST_INIT(conn->sent);
918 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
920 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
921 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
922 if (!conn->fd) sysdie("oop_rd_new_fd (fd=%d)",conn->fd);
923 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
926 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
928 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
929 LIST_ADDHEAD(conns, conn);
931 connect_attempt_discard();
932 check_assign_articles();
937 connect_attempt_discard();
941 static int allow_connect_start(void) {
942 return conns.count < max_connections
947 static void connect_start(void) {
948 assert(!connecting_child);
949 assert(!connecting_fdpass_sock);
951 notice("starting connection attempt");
954 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
955 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
957 connecting_child= xfork("connection");
959 if (!connecting_child) {
960 FILE *cn_from, *cn_to;
961 char buf[NNTP_STRLEN+100];
962 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
964 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
966 alarm(connection_setup_timeout);
967 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
968 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
969 else sysfatal("connect: connection attempt failed");
971 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
972 sysfatal("connect: authentication failed");
974 if (fputs("MODE STREAM\r\n", cn_to) ||
976 sysfatal("connect: could not send MODE STREAM");
977 buf[sizeof(buf)-1]= 0;
978 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
980 sysfatal("connect: could not read response to MODE STREAM");
982 fatal("connect: connection close in response to MODE STREAM");
987 fatal("connect: response to MODE STREAM is too long: %.100s...",
989 l--; if (l>0 && buf[l-1]=='\r') l--;
992 int rcode= strtoul(buf,&ep,10);
994 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
998 exitstatus= CONNCHILD_ESTATUS_STREAM;
1004 warn("connect: unexpected response to MODE STREAM: %.50s",
1010 int fd= fileno(cn_from);
1012 PREP_DECL_MSG_CMSG(msg);
1013 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1014 cmsg->cmsg_level= SOL_SOCKET;
1015 cmsg->cmsg_type= SCM_RIGHTS;
1016 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1017 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1019 msg.msg_controllen= cmsg->cmsg_len;
1020 r= sendmsg(socks[1], &msg, 0);
1021 if (r) sysdie("sendmsg failed for new connection");
1026 xclose(socks[1], "connecting fdpass child's socket",0);
1027 connecting_fdpass_sock= socks[0];
1028 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1031 /*---------- assigning articles to conns, and transmitting ----------*/
1033 static void check_assign_articles(void) {
1039 int spare=0, inqueue=0;
1041 /* Find a connection to offer this article. We prefer a busy
1042 * connection to an idle one, provided it's not full. We take the
1043 * first (oldest) and since that's stable, it will mean we fill up
1044 * connections in order. That way if we have too many
1045 * connections, the spare ones will go away eventually.
1047 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1048 if (walk->quitting) continue;
1049 inqueue= walk->sent.count + walk->priority.count
1050 + walk->waiting.count;
1051 spare= walk->max_queue - inqueue;
1052 assert(inqueue <= max_queue_per_conn);
1054 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1055 else if (spare>0) /*working*/ { use= walk; break; }
1058 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1060 Article *art= LIST_REMHEAD(queue);
1061 LIST_ADDTAIL(use->waiting, art);
1064 conn_maybe_write(use);
1065 } else if (allow_connect_start()) {
1066 until_connect= reconnect_delay_periods;
1075 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1076 conn_maybe_write(u);
1077 return OOP_CONTINUE;
1080 static void conn_maybe_write(Conn *conn) {
1082 conn_make_some_xmits(conn);
1084 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1088 void *rp= conn_write_some_xmits(conn);
1089 if (rp==OOP_CONTINUE) {
1090 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1092 } else if (rp==OOP_HALT) {
1095 /* transmitted everything */
1102 /*========== article transmission ==========*/
1104 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1105 XmitKind kind) { /* caller must then fill in details */
1106 struct iovec *v= &conn->xmit[conn->xmitu];
1107 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1108 v->iov_base= (char*)data;
1114 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1115 xmit_core(conn,data,len, xk_Const);
1117 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1119 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1120 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1124 static void xmit_free(XmitDetails *d) {
1126 case xk_Malloc: free(d->info.malloc_tofree); break;
1127 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1128 case xk_Const: break;
1133 static void *conn_write_some_xmits(Conn *conn) {
1135 * 0: nothing more to write, no need to call us again
1136 * OOP_CONTINUE: more to write but fd not writeable
1137 * OOP_HALT: disaster, have destroyed conn
1140 int count= conn->xmitu;
1141 if (!count) return 0;
1143 if (count > IOV_MAX) count= IOV_MAX;
1144 ssize_t rs= writev(conn->fd, conn->xmit, count);
1146 if (isewouldblock(errno)) return OOP_CONTINUE;
1147 connfail(conn, "write failed: %s", strerror(errno));
1153 for (done=0; rs && done<conn->xmitu; done++) {
1154 struct iovec *vp= &conn->xmit[done];
1155 XmitDetails *dp= &conn->xmitd[done];
1156 if (rs > vp->iov_len) {
1160 vp->iov_base= (char*)vp->iov_base + rs;
1164 int newu= conn->xmitu - done;
1165 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1166 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1171 static void conn_make_some_xmits(Conn *conn) {
1173 if (conn->xmitu+5 > CONNIOVS)
1176 Article *art= LIST_REMHEAD(conn->priority);
1177 if (!art) art= LIST_REMHEAD(conn->waiting);
1180 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1181 /* actually send it */
1183 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1187 XMIT_LITERAL("TAKETHIS ");
1188 xmit_noalloc(conn, art->messageid, art->midlen);
1189 XMIT_LITERAL("\r\n");
1190 xmit_artbody(conn, artdata);
1193 /* we got 235 from IHAVE */
1195 xmit_artbody(conn, artdata);
1197 XMIT_LITERAL(".\r\n");
1202 art->state == art_Unchecked ? art_Unsolicited :
1203 art->state == art_Wanted ? art_Wanted :
1205 art->ipf->counts[art->state][RC_sent]++;
1206 LIST_ADDTAIL(conn->sent, art);
1212 XMIT_LITERAL("IHAVE ");
1214 XMIT_LITERAL("CHECK ");
1215 xmit_noalloc(conn, art->messageid, art->midlen);
1216 XMIT_LITERAL("\r\n");
1218 assert(art->state == art_Unchecked);
1219 art->ipf->counts[art->state][RC_sent]++;
1220 LIST_ADDTAIL(conn->sent, art);
1226 /*========== handling responses from peer ==========*/
1228 static const oop_rd_style peer_rd_style= {
1229 OOP_RD_DELIM_STRIP, '\n',
1231 OOP_RD_SHORTREC_FORBID
1234 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1235 const char *errmsg, int errnoval,
1236 const char *data, size_t recsz, void *conn_v) {
1238 connfail(conn, "error receiving from peer: %s", errmsg);
1239 return OOP_CONTINUE;
1242 static Article *article_reply_check(Conn *conn, const char *response,
1243 int code_indicates_streaming,
1245 /* 1:yes, -1:no, 0:dontcare */,
1246 const char *sanitised_response) {
1247 Article *art= LIST_HEAD(conn->sent);
1251 "peer gave unexpected response when no commands outstanding: %s",
1252 sanitised_response);
1256 if (code_indicates_streaming) {
1257 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1258 if (!conn->stream) {
1259 connfail(conn, "peer gave streaming response code "
1260 " to IHAVE or subsequent body: %s", sanitised_response);
1263 const char *got_mid= response+4;
1264 int got_midlen= strcspn(got_mid, " \n\r");
1265 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1266 connfail(conn, "peer gave streaming response with syntactically invalid"
1267 " messageid: %s", sanitised_response);
1270 if (got_midlen != art->midlen ||
1271 memcmp(got_mid, art->messageid, got_midlen)) {
1272 connfail(conn, "peer gave streaming response code to wrong article -"
1273 " probable synchronisation problem; we offered: %s;"
1275 art->messageid, sanitised_response);
1280 connfail(conn, "peer gave non-streaming response code to"
1281 " CHECK/TAKETHIS: %s", sanitised_response);
1286 if (must_have_sent>0 && art->state < art_Wanted) {
1287 connfail(conn, "peer says article accepted but"
1288 " we had not sent the body: %s", sanitised_response);
1291 if (must_have_sent<0 && art->state >= art_Wanted) {
1292 connfail(conn, "peer says please sent the article but we just did: %s",
1293 sanitised_response);
1297 Article *art_again= LIST_REMHEAD(conn->sent);
1298 assert(art_again == art);
1302 static void update_nocheck(int accepted) {
1303 accept_proportion *= nocheck_decay;
1304 accept_proportion += accepted * (1.0 - nocheck_decay);
1305 int new_nocheck= accept_proportion >= nocheck_thresh;
1306 if (new_nocheck && !nocheck_reported) {
1307 notice("entering nocheck mode for the first time");
1308 nocheck_reported= 1;
1309 } else if (new_nocheck != nocheck) {
1310 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1312 nocheck= new_nocheck;
1315 static void article_done(Conn *conn, Article *art, int whichcount) {
1316 art->ipf->counts[art->state][whichcount]++;
1317 if (whichcount == RC_accepted) update_nocheck(1);
1318 else if (whichcount == RC_unwanted) update_nocheck(0);
1320 InputFile *ipf= art->ipf;
1322 while (art->blanklen) {
1323 static const char spaces[]=
1328 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1329 int r= pwrite(ipf->fd, spaces, w, art->offset);
1331 if (errno==EINTR) continue;
1332 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1333 art->messageid, art->blanklen,
1334 (unsigned long)art->offset, ipf->path);
1336 assert(r>=0 && r<=w);
1342 assert(ipf->inprogress >= 0);
1345 if (!ipf->inprogress && ipf != main_input_file)
1346 queue_check_input_done();
1349 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1350 const char *errmsg, int errnoval,
1351 const char *data, size_t recsz, void *conn_v) {
1354 if (ev == OOP_RD_EOF) {
1355 connfail(conn, "unexpected EOF from peer");
1356 return OOP_CONTINUE;
1358 assert(ev == OOP_RD_OK);
1360 char *sani= sanitise(data);
1363 unsigned long code= strtoul(data, &ep, 10);
1364 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1365 connfail(conn, "badly formatted response from peer: %s", sani);
1366 return OOP_CONTINUE;
1369 if (conn->quitting) {
1370 if (code!=205 && code!=503) {
1371 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1373 notice("C%d idle connection closed", conn->fd);
1374 assert(!conn->waiting.count);
1375 assert(!conn->priority.count);
1376 assert(!conn->sent.count);
1377 assert(!conn->xmitu);
1378 LIST_REMOVE(conns,conn);
1381 return OOP_CONTINUE;
1384 conn->since_activity= 0;
1387 #define GET_ARTICLE(musthavesent) \
1388 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1389 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1391 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1392 code_streaming= (streaming); \
1393 GET_ARTICLE(musthavesent); \
1394 article_done(conn, art, RC_##how); break;
1396 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1398 int code_streaming= 0;
1402 case 400: PEERBADMSG("peer stopped accepting articles");
1403 case 503: PEERBADMSG("peer timed us out");
1404 default: PEERBADMSG("peer sent unexpected message");
1406 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1407 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1409 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1410 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1412 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1413 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1415 case 238: /* CHECK says send it */
1417 case 335: /* IHAVE says send it */
1419 assert(art->state == art_Unchecked);
1420 art->ipf->counts[art->state][RC_accepted]++;
1421 art->state= art_Wanted;
1422 LIST_ADDTAIL(conn->priority, art);
1425 case 431: /* CHECK or TAKETHIS says try later */
1427 case 436: /* IHAVE says try later */
1430 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1432 sysfatal("write to defer file %s",path_defer);
1433 article_done(conn, art, RC_deferred);
1438 conn_maybe_write(conn);
1439 check_assign_articles();
1440 return OOP_CONTINUE;
1444 /*========== monitoring of input files ==========*/
1446 static void feedfile_eof(InputFile *ipf) {
1447 assert(ipf != main_input_file); /* promised by tailing_try_read */
1448 inputfile_reading_stop(ipf);
1450 if (ipf == flushing_input_file) {
1451 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1452 if (main_input_file) inputfile_reading_start(main_input_file);
1453 statemc_check_flushing_done();
1454 } else if (ipf == backlog_input_file) {
1455 statemc_check_backlog_done();
1457 abort(); /* supposed to wait rather than get EOF on main input file */
1461 static InputFile *open_input_file(const char *path) {
1462 int fd= open(path, O_RDONLY);
1464 if (errno==ENOENT) return 0;
1465 sysfatal("unable to open input file %s", path);
1469 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1470 memset(ipf,0,sizeof(*ipf));
1473 strcpy(ipf->path, path);
1478 static void close_input_file(InputFile *ipf) { /* does not free */
1479 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1480 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1481 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1482 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1483 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1487 /*---------- dealing with articles read in the input file ----------*/
1489 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1490 const char *data, const char *how) {
1491 warn("corrupted file: %s, offset %lu: %s: %s",
1492 ipf->path, (unsigned long)offset, how, sanitise(data));
1493 ipf->readcount_err++;
1494 if (ipf->readcount_err > max_bad_data_initial +
1495 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1496 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1497 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1498 return OOP_CONTINUE;
1501 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1502 oop_rd_event ev, const char *errmsg,
1503 int errnoval, const char *data, size_t recsz,
1505 InputFile *ipf= ipf_v;
1506 assert(ev == OOP_RD_SYSTEM);
1508 sysdie("error reading input file: %s, offset %lu",
1509 ipf->path, (unsigned long)ipf->offset);
1512 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1513 oop_rd_event ev, const char *errmsg,
1514 int errnoval, const char *data, size_t recsz,
1516 InputFile *ipf= ipf_v;
1518 char tokentextbuf[sizeof(TOKEN)*2+3];
1520 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1522 off_t old_offset= ipf->offset;
1523 ipf->offset += recsz + 1;
1525 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1527 if (ev==OOP_RD_PARTREC)
1528 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1529 /* but process it anyway */
1531 if (ipf->skippinglong) {
1532 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1533 return OOP_CONTINUE;
1535 if (ev==OOP_RD_LONG) {
1536 ipf->skippinglong= 1;
1537 X_BAD_DATA("overly long line");
1540 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1541 if (!recsz) X_BAD_DATA("empty line");
1544 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1545 ipf->readcount_blank++;
1546 return OOP_CONTINUE;
1549 char *space= strchr(data,' ');
1550 int tokenlen= space-data;
1551 int midlen= (int)recsz-tokenlen-1;
1552 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1553 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1555 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1556 memcpy(tokentextbuf, data, tokenlen);
1557 tokentextbuf[tokenlen]= 0;
1558 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1560 ipf->readcount_ok++;
1562 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1563 art->state= art_Unchecked;
1564 art->midlen= midlen;
1565 art->ipf= ipf; ipf->inprogress++;
1566 art->token= TextToToken(tokentextbuf);
1567 art->offset= ipf->offset;
1568 art->blanklen= recsz;
1569 strcpy(art->messageid, space+1);
1570 LIST_ADDTAIL(queue, art);
1572 if (sms==sm_NORMAL && ipf==main_input_file &&
1573 ipf->offset >= target_max_feedfile_size)
1574 statemc_start_flush("feed file size");
1576 check_assign_articles();
1577 return OOP_CONTINUE;
1580 /*========== tailing input file ==========*/
1582 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1584 InputFile *ipf= user;
1585 return ipf->readable_callback(loop, &ipf->readable,
1586 ipf->readable_callback_user);
1589 static void tailing_on_cancel(struct oop_readable *rable) {
1590 InputFile *ipf= (void*)rable;
1592 if (ipf->filemon) filemon_stop(ipf);
1593 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1594 ipf->readable_callback= 0;
1597 static void tailing_queue_readable(InputFile *ipf) {
1598 /* lifetime of ipf here is OK because destruction will cause
1599 * on_cancel which will cancel this callback */
1600 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1603 static int tailing_on_readable(struct oop_readable *rable,
1604 oop_readable_call *cb, void *user) {
1605 InputFile *ipf= (void*)rable;
1607 tailing_on_cancel(rable);
1608 ipf->readable_callback= cb;
1609 ipf->readable_callback_user= user;
1612 tailing_queue_readable(ipf);
1616 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1618 InputFile *ipf= (void*)rable;
1620 ssize_t r= read(ipf->fd, buffer, length);
1622 if (errno==EINTR) continue;
1626 if (ipf==main_input_file) {
1629 } else if (ipf==flushing_input_file) {
1631 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1632 } else if (ipf==backlog_input_file) {
1642 /*---------- filemon implemented with inotify ----------*/
1644 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1645 #define HAVE_FILEMON
1647 #include <linux/inotify.h>
1649 static int filemon_inotify_fd;
1650 static int filemon_inotify_wdmax;
1651 static InputFile **filemon_inotify_wd2ipf;
1653 struct Filemon_Perfile {
1657 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1658 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1659 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
1661 if (wd >= filemon_inotify_wdmax) {
1663 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1664 sizeof(*filemon_inotify_wd2ipf) * newmax);
1665 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1666 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1667 filemon_inotify_wdmax= newmax;
1670 assert(!filemon_inotify_wd2ipf[wd]);
1671 filemon_inotify_wd2ipf[wd]= ipf;
1673 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1674 ipf, wd, filemon_inotify_wdmax);
1679 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1681 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1682 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1683 if (r) sysdie("inotify_rm_watch");
1684 filemon_inotify_wd2ipf[wd]= 0;
1687 static void *filemon_inotify_readable(oop_source *lp, int fd,
1688 oop_event e, void *u) {
1689 struct inotify_event iev;
1691 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1693 if (isewouldblock(errno)) break;
1694 sysdie("read from inotify master");
1695 } else if (r==sizeof(iev)) {
1696 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1698 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1700 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1701 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1702 filemon_callback(ipf);
1704 return OOP_CONTINUE;
1707 static int filemon_method_init(void) {
1708 filemon_inotify_fd= inotify_init();
1709 if (filemon_inotify_fd<0) {
1710 syswarn("could not initialise inotify: inotify_init failed");
1714 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1716 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1720 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1722 /*---------- filemon dummy implementation ----------*/
1724 #if !defined(HAVE_FILEMON)
1726 struct Filemon_Perfile { int dummy; };
1728 static int filemon_method_init(void) { return 0; }
1729 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1730 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1732 #endif /* !HAVE_FILEMON */
1734 /*---------- filemon generic interface ----------*/
1736 static void filemon_start(InputFile *ipf) {
1737 assert(!ipf->filemon);
1739 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1740 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1741 filemon_method_startfile(ipf, ipf->filemon);
1744 static void filemon_stop(InputFile *ipf) {
1745 if (!ipf->filemon) return;
1746 filemon_method_stopfile(ipf, ipf->filemon);
1751 static void filemon_callback(InputFile *ipf) {
1752 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1755 /*---------- interface to start and stop an input file ----------*/
1757 static const oop_rd_style feedfile_rdstyle= {
1758 OOP_RD_DELIM_STRIP, '\n',
1760 OOP_RD_SHORTREC_LONG,
1763 static void inputfile_reading_start(InputFile *ipf) {
1765 ipf->readable.on_readable= tailing_on_readable;
1766 ipf->readable.on_cancel= tailing_on_cancel;
1767 ipf->readable.try_read= tailing_try_read;
1768 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1769 ipf->readable.delete_kill= 0;
1771 ipf->readable_callback= 0;
1772 ipf->readable_callback_user= 0;
1774 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1777 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1778 feedfile_got_article,ipf, feedfile_read_err, ipf);
1779 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1782 static void inputfile_reading_stop(InputFile *ipf) {
1784 oop_rd_cancel(ipf->rd);
1785 oop_rd_delete(ipf->rd);
1787 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1791 /*========== interaction with innd - state machine ==========*/
1793 /* See official state diagram at top of file. We implement
1804 |`---------------------------------------------------.
1806 |`---------------- - - - |
1807 D ENOENT | D EXISTS see OVERALL STATES diagram |
1808 | for full startup logic |
1811 | ============ try to |
1817 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1818 ^ | hardlink F to D |
1821 | | our handle onto F is now onto D |
1824 | |<-------------------<---------------------<---------+
1826 | | spawn inndcomm flush |
1828 | ================== |
1829 | FLUSHING[-ABSENT] |
1831 | main D tail/none |
1832 | ================== |
1834 | | INNDCOMM FLUSH FAILS ^
1835 | |`----------------------->----------. |
1837 | | NO SUCH SITE V |
1838 ^ |`--------------->----. ==================== |
1839 | | \ FLUSHFAILED[-ABSENT] |
1841 | | FLUSH OK \ main D tail/none |
1842 | | open F \ ==================== |
1844 | | \ | TIME TO RETRY |
1845 | |`------->----. ,---<---'\ `----------------'
1846 | | D NONE | | D NONE `----.
1848 | ============= V V ============
1849 | SEPARATED-1 | | DROPPING-1
1850 | flsh->rd!=0 | | flsh->rd!=0
1851 | [Separated] | | [Dropping]
1852 | main F idle | | main none
1853 | old D tail | | old D tail
1854 | ============= | | ============
1856 ^ | EOF ON D | | defer | EOF ON D
1858 | =============== | | ===============
1859 | SEPARATED-2 | | DROPPING-2
1860 | flsh->rd==0 | V flsh->rd==0
1861 | [Finishing] | | [Dropping]
1862 | main F tail | `. main none
1863 | old D closed | `. old D closed
1864 | =============== V `. ===============
1866 | | ALL D PROCESSED `. | ALL D PROCESSED
1867 | V install defer as backlog `. | install defer
1868 ^ | close D `. | close D
1869 | | unlink D `. | unlink D
1872 `----------' ==============
1892 static void startup_set_input_file(InputFile *f) {
1893 assert(!main_input_file);
1895 inputfile_reading_start(f);
1898 static void statemc_init(void) {
1899 struct stat stab, stabf;
1901 path_lock= xasprintf("%s_lock", feedfile);
1902 path_flushing= xasprintf("%s_flushing", feedfile);
1903 path_defer= xasprintf("%s_defer", feedfile);
1904 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1909 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1910 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1913 memset(&fl,0,sizeof(fl));
1915 fl.l_whence= SEEK_SET;
1916 int r= fcntl(lockfd, F_SETLK, &fl);
1918 if (errno==EACCES || isewouldblock(errno)) {
1919 if (quiet_multiple) exit(0);
1920 fatal("another duct holds the lockfile");
1922 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
1925 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
1927 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1929 if (!lock_noent && samefile(&stab, &stabf))
1932 xclose(lockfd, "stale lockfile ", path_lock);
1934 pid_t self= getpid();
1935 if (self==-1) sysdie("getpid");
1937 FILE *lockfile= fdopen(lockfd, "w");
1938 if (!lockfile) sysdie("fdopen lockfile");
1940 int r= ftruncate(lockfd, 0);
1941 if (r) sysdie("truncate lockfile to write new info");
1943 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
1944 (unsigned long)self, sitename, feedfile, remote_host) == EOF ||
1946 sysfatal("write info to lockfile %s", path_lock);
1948 debug("startup: locked");
1950 search_backlog_file();
1953 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1955 debug("startup: ductdefer ENOENT");
1957 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1958 switch (stab.st_nlink==1) {
1960 open_defer(); /* so that we will later close it and rename it */
1963 xunlink(path_defer, "stale defer file link"
1964 " (presumably hardlink to backlog file)");
1967 die("defer file %s has unexpected link count %d",
1968 path_defer, stab.st_nlink);
1972 struct stat stab_f, stab_d;
1975 InputFile *file_d= open_input_file(path_flushing);
1976 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
1978 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1980 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1981 debug("startup: F==D => Hardlinked");
1982 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1987 debug("startup: F ENOENT => Moved");
1988 if (file_d) startup_set_input_file(file_d);
1989 spawn_inndcomm_flush("feedfile missing at startup");
1990 /* => Flushing, sms:=FLUSHING */
1993 debug("startup: F!=D => Separated");
1994 startup_set_input_file(file_d);
1995 SMS(SEPARATED, 0, "found both old and current feed files");
1997 debug("startup: F exists, D ENOENT => Normal");
1998 InputFile *file_f= open_input_file(feedfile);
1999 if (!file_f) die("feed file vanished during startup");
2000 startup_set_input_file(file_f);
2001 SMS(NORMAL, flushfail_retry_periods, "normal startup");
2006 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2007 assert(sms == sm_NORMAL);
2009 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2011 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2012 (unsigned long)target_max_feedfile_size,
2015 int r= link(feedfile, path_flushing);
2016 if (r) sysfatal("link feedfile %s to flushing file %s",
2017 feedfile, path_flushing);
2020 xunlink(feedfile, "old feedfile link");
2023 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2026 static void statemc_period_poll(void) {
2027 if (!sm_period_counter) return;
2028 sm_period_counter--;
2029 assert(sm_period_counter>=0);
2031 if (sm_period_counter) return;
2034 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2036 case sm_FLUSHFAILED:
2037 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2044 static int inputfile_is_done(InputFile *ipf) {
2046 if (ipf->inprogress) return 0; /* new article in the meantime */
2047 if (ipf->rd) return 0; /* not had EOF */
2051 static void notice_processed(InputFile *ipf, const char *what,
2053 #define RCI_NOTHING(x) /* nothing */
2054 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2055 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2057 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2059 info("processed %s%s read=%d(+%dbl,+%derr)"
2060 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2061 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2064 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2065 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2066 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2067 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2068 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2069 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2075 static void statemc_check_backlog_done(void) {
2076 InputFile *ipf= backlog_input_file;
2077 if (!inputfile_is_done(ipf)) return;
2079 const char *slash= strrchr(ipf->path, '/');
2080 const char *leaf= slash ? slash+1 : ipf->path;
2081 const char *under= strchr(slash, '_');
2082 const char *rest= under ? under+1 : leaf;
2083 if (!strncmp(rest,"backlog",7)) rest += 7;
2084 notice_processed(ipf,"backlog:",rest);
2086 close_input_file(ipf);
2087 if (unlink(ipf->path)) {
2088 if (errno != ENOENT)
2089 sysdie("could not unlink processed backlog file %s", ipf->path);
2090 warn("backlog file %s vanished while we were reading it"
2091 " so we couldn't remove it (but it's done now, anyway)",
2095 backlog_input_file= 0;
2096 search_backlog_file();
2100 static void statemc_check_flushing_done(void) {
2101 InputFile *ipf= flushing_input_file;
2102 if (!inputfile_is_done(ipf)) return;
2104 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2106 notice_processed(ipf,"feedfile",0);
2110 xunlink(path_flushing, "old flushing file");
2112 close_input_file(flushing_input_file);
2113 free(flushing_input_file);
2114 flushing_input_file= 0;
2116 if (sms==sm_SEPARATED) {
2117 notice("flush complete");
2118 SMS(NORMAL, 0, "flush complete");
2119 } else if (sms==sm_DROPPING) {
2120 SMS(DROPPED, 0, "old flush complete");
2121 search_backlog_file();
2122 notice("feed dropped, but will continue until backlog is finished");
2126 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2128 assert(!inputfile_is_done(main_input_file));
2129 statemc_check_flushing_done();
2130 statemc_check_backlog_done();
2131 return OOP_CONTINUE;
2134 static void queue_check_input_done(void) {
2135 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2138 static void statemc_setstate(StateMachineState newsms, int periods,
2139 const char *forlog, const char *why) {
2141 sm_period_counter= periods;
2143 const char *xtra= "";
2146 case sm_FLUSHFAILED:
2147 if (!main_input_file) xtra= "-ABSENT";
2151 xtra= flushing_input_file->rd ? "-1" : "-2";
2157 info("%s%s[%d] %s",forlog,xtra,periods,why);
2159 info("%s%s %s",forlog,xtra,why);
2163 /*---------- defer and backlog files ----------*/
2165 static void open_defer(void) {
2170 defer= fopen(path_defer, "a+");
2171 if (!defer) sysfatal("could not open defer file %s", path_defer);
2173 /* truncate away any half-written records */
2175 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2177 if (stab.st_size > LONG_MAX)
2178 die("defer file %s size is far too large", path_defer);
2183 long orgsize= stab.st_size;
2184 long truncto= stab.st_size;
2186 if (!truncto) break; /* was only (if anything) one half-truncated record */
2187 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2188 sysdie("seek in defer file %s while truncating partial", path_defer);
2193 sysdie("failed read from defer file %s", path_defer);
2195 die("defer file %s shrank while we were checking it!", path_defer);
2201 if (stab.st_size != truncto) {
2202 warn("truncating half-record at end of defer file %s -"
2203 " shrinking by %ld bytes from %ld to %ld",
2204 path_defer, orgsize - truncto, orgsize, truncto);
2207 sysfatal("could not flush defer file %s", path_defer);
2208 if (ftruncate(fileno(defer), truncto))
2209 sysdie("could not truncate defer file %s", path_defer);
2212 info("continuing existing defer file %s (%ld bytes)",
2213 path_defer, orgsize);
2215 if (fseek(defer, truncto, SEEK_SET))
2216 sysdie("could not seek to new end of defer file %s", path_defer);
2219 static void close_defer(void) {
2224 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2226 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2229 time_t now= xtime();
2231 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2233 (unsigned long)stab.st_ino);
2234 if (link(path_defer, backlog))
2235 sysfatal("could not install defer file %s as backlog file %s",
2236 path_defer, backlog);
2237 if (unlink(path_defer))
2238 sysdie("could not unlink old defer link %s to backlog file %s",
2239 path_defer, backlog);
2243 if (until_backlog_nextscan < 0 ||
2244 until_backlog_nextscan > backlog_retry_minperiods + 1)
2245 until_backlog_nextscan= backlog_retry_minperiods + 1;
2248 static void poll_backlog_file(void) {
2249 if (until_backlog_nextscan < 0) return;
2250 if (until_backlog_nextscan-- > 0) return;
2251 search_backlog_file();
2254 static void search_backlog_file(void) {
2255 /* returns non-0 iff there are any backlog files */
2260 const char *oldest_path=0;
2261 time_t oldest_mtime=0, now;
2263 if (backlog_input_file) return;
2267 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2271 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2273 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2275 for (i=0; i<gl.gl_pathc; i++) {
2276 const char *path= gl.gl_pathv[i];
2278 if (strchr(path,'#') || strchr(path,'~')) {
2279 debug("backlog file search skipping %s", path);
2282 r= stat(path, &stab);
2284 syswarn("failed to stat backlog file %s", path);
2287 if (!S_ISREG(stab.st_mode)) {
2288 warn("backlog file %s is not a plain file (or link to one)", path);
2291 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2293 oldest_mtime= stab.st_mtime;
2296 case GLOB_NOMATCH: /* fall through */
2299 sysdie("glob expansion of backlog pattern %s gave unexpected"
2300 " nonzero (error?) return value %d", globpat_backlog, r);
2304 debug("backlog scan: none");
2306 if (sms==sm_DROPPED) {
2307 notice("feed dropped and our work is complete");
2308 xunlink(path_lock, "lockfile for old feed");
2311 until_backlog_nextscan= backlog_spontrescan_periods;
2316 double age= difftime(now, oldest_mtime);
2317 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2319 if (age_deficiency <= 0) {
2320 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2321 age, age_deficiency, oldest_path);
2323 backlog_input_file= open_input_file(oldest_path);
2324 if (!backlog_input_file) {
2325 warn("backlog file %s vanished as we opened it", oldest_path);
2329 inputfile_reading_start(backlog_input_file);
2330 until_backlog_nextscan= -1;
2334 until_backlog_nextscan= age_deficiency / period_seconds;
2336 if (backlog_spontrescan_periods >= 0 &&
2337 until_backlog_nextscan > backlog_spontrescan_periods)
2338 until_backlog_nextscan= backlog_spontrescan_periods;
2340 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2341 age, age_deficiency, until_backlog_nextscan, oldest_path);
2348 /*========== flushing the feed ==========*/
2350 static pid_t inndcomm_child;
2351 static int inndcomm_sentinel_fd;
2353 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2354 assert(inndcomm_child);
2355 assert(fd == inndcomm_sentinel_fd);
2356 int status= xwaitpid(&inndcomm_child, "inndcomm");
2357 cancel_fd_read_except(fd);
2358 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2360 assert(!flushing_input_file);
2362 if (WIFEXITED(status)) {
2363 switch (WEXITSTATUS(status)) {
2365 case INNDCOMMCHILD_ESTATUS_FAIL:
2368 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2369 warn("feed has been dropped by innd, finishing up");
2370 flushing_input_file= main_input_file;
2371 tailing_queue_readable(flushing_input_file);
2372 /* we probably previously returned EAGAIN from our fake read method
2373 * when in fact we were at EOF, so signal another readable event
2374 * so we actually see the EOF */
2378 if (flushing_input_file) {
2379 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2382 SMS(DROPPED, 0, "feed dropped by innd");
2383 search_backlog_file();
2385 return OOP_CONTINUE;
2389 flushing_input_file= main_input_file;
2390 tailing_queue_readable(flushing_input_file);
2392 main_input_file= open_input_file(feedfile);
2393 if (!main_input_file)
2394 die("flush succeeded but feedfile %s does not exist!", feedfile);
2396 if (flushing_input_file) {
2397 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2400 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2402 return OOP_CONTINUE;
2405 goto unexpected_exitstatus;
2408 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2409 warn("flush timed out trying to talk to innd");
2412 unexpected_exitstatus:
2413 report_child_status("inndcomm child", status);
2417 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2418 return OOP_CONTINUE;
2421 static void inndcommfail(const char *what) {
2422 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2423 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2426 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2429 notice("flushing %s",why);
2431 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2432 assert(!inndcomm_child);
2433 assert(!inndcomm_sentinel_fd);
2435 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2437 inndcomm_child= xfork("inndcomm child");
2439 if (!inndcomm_child) {
2440 const char *flushargv[2]= { sitename, 0 };
2444 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2445 /* parent spots the autoclose of pipefds[1] when we die or exit */
2447 alarm(inndcomm_flush_timeout);
2448 r= ICCopen(); if (r) inndcommfail("connect");
2449 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2450 if (!r) exit(0); /* yay! */
2452 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2453 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2454 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2457 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2458 inndcomm_sentinel_fd= pipefds[0];
2459 assert(inndcomm_sentinel_fd);
2460 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2462 SMS(FLUSHING, 0, why);
2465 /*========== main program ==========*/
2467 static void postfork_inputfile(InputFile *ipf) {
2469 xclose(ipf->fd, "(in child) input file ", ipf->path);
2472 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2473 /* we have no stdio streams that are buffered long-term */
2475 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2478 static void postfork(void) {
2479 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2480 sysdie("(in child) failed to reset SIGPIPE");
2482 postfork_inputfile(main_input_file);
2483 postfork_inputfile(flushing_input_file);
2486 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2487 conn_closefd(conn,"(in child) ");
2489 postfork_stdio(defer, "defer file ", path_defer);
2492 #define EVERY(what, interval_sec, interval_usec, body) \
2493 static struct timeval what##_timeout = { interval_sec, interval_usec }; \
2494 static void what##_schedule(void); \
2495 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2497 what##_schedule(); \
2498 return OOP_CONTINUE; \
2500 static void what##_schedule(void) { \
2501 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2504 EVERY(filepoll, 5,0, ({
2505 if (main_input_file && main_input_file->readable_callback)
2506 filemon_callback(main_input_file);
2509 static char *debug_report_ipf(InputFile *ipf) {
2510 if (!ipf) return xasprintf("-");
2512 const char *slash= strrchr(ipf->path,'/');
2513 const char *path= slash ? slash+1 : ipf->path;
2515 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2517 ipf->inprogress, (long)ipf->offset,
2518 ipf->fd, ipf->rd ? "+" : "");
2521 EVERY(period, -1,0, ({
2522 char *dipf_main= debug_report_ipf(main_input_file);
2523 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2524 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2527 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2528 " input_files main:%s old:%s flushing:%s"
2529 " children connecting=%ld inndcomm_child=%ld"
2531 sms_names[sms], sm_period_counter,
2532 conns.count, queue.count, until_connect,
2533 dipf_main, dipf_flushing, dipf_backlog,
2534 (long)connecting_child, (long)inndcomm_child
2538 free(dipf_flushing);
2541 if (until_connect) until_connect--;
2543 poll_backlog_file();
2544 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2545 statemc_period_poll();
2546 check_assign_articles();
2551 /*========== option parsing ==========*/
2553 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2554 static void vbadusage(const char *fmt, va_list al) {
2555 char *m= xvasprintf(fmt,al);
2556 fprintf(stderr, "bad usage: %s\n"
2557 "say --help for help, or read the manpage\n",
2560 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2564 /*---------- generic option parser ----------*/
2566 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2567 static void badusage(const char *fmt, ...) {
2574 of_seconds= 001000u,
2575 of_boolean= 002000u,
2578 typedef struct Option Option;
2579 typedef void OptionParser(const Option*, const char *val);
2583 const char *lng, *formarg;
2589 static void parse_options(const Option *options, char ***argvp) {
2590 /* on return *argvp is first non-option arg; argc is not updated */
2593 const char *arg= *++(*argvp);
2595 if (*arg != '-') break;
2596 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2598 while ((a= *++arg)) {
2602 char *equals= strchr(arg,'=');
2603 int len= equals ? (equals - arg) : strlen(arg);
2604 for (o=options; o->shrt || o->lng; o++)
2605 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2607 badusage("unknown long option --%s",arg);
2610 if (equals) badusage("option --%s does not take a value",o->lng);
2612 } else if (equals) {
2616 if (!arg) badusage("option --%s needs a value for %s",
2617 o->lng, o->formarg);
2620 break; /* eaten the whole argument now */
2622 for (o=options; o->shrt || o->lng; o++)
2625 badusage("unknown short option -%c",a);
2632 if (!arg) badusage("option -%c needs a value for %s",
2633 o->shrt, o->formarg);
2636 break; /* eaten the whole argument now */
2642 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
2644 static void print_options(const Option *options, FILE *f) {
2646 for (o=options; o->shrt || o->lng; o++) {
2647 char shrt[2] = { o->shrt, 0 };
2648 char *optspec= xasprintf("%s%s%s%s%s",
2649 o->shrt ? "-" : "", shrt,
2650 o->shrt && o->lng ? "|" : "",
2651 DELIMPERHAPS("--", o->lng));
2652 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
2657 /*---------- specific option types ----------*/
2659 static void op_integer(const Option *o, const char *val) {
2662 unsigned long ul= strtoul(val,&ep,10);
2663 if (*ep || ep==val || errno || ul>INT_MAX)
2664 badusage("bad integer value for %s",o->lng);
2665 int *store= o->store;
2669 static void op_double(const Option *o, const char *val) {
2670 int *store= o->store;
2673 *store= strtod(val, &ep);
2674 if (*ep || ep==val || errno)
2675 badusage("bad floating point value for %s",o->lng);
2678 static void op_string(const Option *o, const char *val) {
2679 const char **store= o->store;
2683 static void op_seconds(const Option *o, const char *val) {
2684 int *store= o->store;
2688 double v= strtod(val,&ep);
2689 if (ep==val) badusage("bad time/duration value for %s",o->lng);
2691 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
2692 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
2693 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
2694 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
2695 else if (!strcmp(ep,"das")) unit= 10;
2696 else if (!strcmp(ep,"hs")) unit= 100;
2697 else if (!strcmp(ep,"ks")) unit= 1000;
2698 else if (!strcmp(ep,"Ms")) unit= 1000000;
2699 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2703 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2707 static void op_setint(const Option *o, const char *val) {
2708 int *store= o->store;
2712 /*---------- specific options ----------*/
2714 static void help(const Option *o, const char *val);
2716 static const Option innduct_options[]= {
2717 {'f',"feedfile", "F", &feedfile, op_string },
2718 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
2719 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
2720 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
2721 {0,"inndconf", "F", &inndconffile, op_string },
2722 {'P',"port", "PORT", &port, op_integer },
2723 {0,"help", 0, 0, help },
2725 {0,"max-connections", "N", &max_connections, op_integer },
2726 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
2727 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
2728 {0,"period-interval", "TIME", &period_seconds, op_seconds },
2730 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
2731 {0,"stuck-flush-timeout","TIME", &inndcomm_flush_timeout, op_seconds },
2733 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
2734 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
2736 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
2737 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
2738 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
2739 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
2740 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
2741 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
2743 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
2744 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
2749 static void printusage(FILE *f) {
2750 fputs("usage: innduct [options] site [fqdn]\n"
2751 "available options are:\n", f);
2752 print_options(innduct_options, f);
2755 static void help(const Option *o, const char *val) {
2757 if (ferror(stdout) || fflush(stdout)) {
2758 perror("innduct: writing help");
2764 static void convert_to_periods_rndup(int *store) {
2765 *store += period_seconds-1;
2766 *store /= period_seconds;
2769 int main(int argc, char **argv) {
2775 parse_options(innduct_options, &argv);
2780 if (!sitename) badusage("need site name argument");
2781 remote_host= *argv++;
2782 if (*argv) badusage("too many non-option arguments");
2786 if (!remote_host) remote_host= sitename;
2788 if (nocheck_thresh < 0 || nocheck_thresh > 100)
2789 badusage("nocheck threshold percentage must be between 0..100");
2790 nocheck_thresh *= 0.01;
2792 if (nocheck_decay < 0.1)
2793 badusage("nocheck decay articles must be at least 0.1");
2794 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
2796 convert_to_periods_rndup(&reconnect_delay_periods);
2797 convert_to_periods_rndup(&flushfail_retry_periods);
2798 convert_to_periods_rndup(&backlog_retry_minperiods);
2799 convert_to_periods_rndup(&backlog_spontrescan_periods);
2800 convert_to_periods_rndup(&spontaneous_flush_periods);
2801 convert_to_periods_rndup(&need_activity_periods);
2803 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
2804 badusage("bad input data ratio must be between 0..100");
2805 max_bad_data_ratio *= 0.01;
2808 innconf_read(inndconffile);
2809 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
2810 } else if (!feedfile[0]) {
2811 badusage("feed filename must be nonempty");
2812 } else if (feedfile[strlen(feedfile)-1]=='/') {
2813 feedfile= xasprintf("%s%s",feedfile,sitename);
2816 const char *feedfile_forbidden= "?*[~#";
2818 while ((c= *feedfile_forbidden++))
2819 if (strchr(feedfile, c))
2820 badusage("feed filename may not contain metacharacter %c",c);
2824 oop_source_sys *sysloop= oop_sys_new();
2825 if (!sysloop) sysdie("could not create liboop event loop");
2826 loop= (oop_source*)sysloop;
2828 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2829 sysdie("could not ignore SIGPIPE");
2834 if (become_daemon) {
2836 for (i=3; i<255; i++)
2837 /* do this now before we open syslog, etc. */
2839 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2841 int null= open("/dev/null",O_RDWR);
2842 if (null<0) sysfatal("failed to open /dev/null");
2846 xclose(null, "/dev/null original fd",0);
2848 pid_t child1= xfork("daemonise first fork");
2849 if (child1) _exit(0);
2851 pid_t sid= setsid();
2852 if (sid != child1) sysfatal("setsid failed");
2854 pid_t child2= xfork("daemonise second fork");
2855 if (child2) _exit(0);
2860 if (!filemon_method_init()) {
2861 warn("no file monitoring available, polling");
2862 filepoll_schedule();
2865 period_timeout.tv_sec= period_seconds;
2872 void *r= oop_sys_run(sysloop);
2873 assert(r == OOP_ERROR);
2874 sysdie("event loop failed");