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, *remote_host;
315 static const char *feedfile;
316 static int quiet_multiple=0;
317 static int become_daemon=1;
318 static int try_stream=1;
320 static const char *inndconffile;
322 static int max_connections=10;
323 static int max_queue_per_conn=200;
324 static int target_max_feedfile_size=100000;
325 static int period_seconds=60;
327 static int connection_setup_timeout=200;
328 static int inndcomm_flush_timeout=100;
330 static double nocheck_thresh= 95.0; /* converted from percentage by main */
331 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
333 /* all these are initialised to seconds, and converted to periods in main */
334 static int reconnect_delay_periods=1000;
335 static int flushfail_retry_periods=1000;
336 static int backlog_retry_minperiods=50;
337 static int backlog_spontrescan_periods=300;
338 static int spontaneous_flush_periods=100000;
339 static int need_activity_periods=1000;
341 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
342 static int max_bad_data_initial= 30;
343 /* in one corrupt 4096-byte block the number of newlines has
344 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
347 /*----- statistics -----*/
349 typedef enum { /* in queue in conn->sent */
350 art_Unchecked, /* not checked, not sent checking */
351 art_Wanted, /* checked, wanted sent body as requested */
352 art_Unsolicited, /* - sent body without check */
356 #define RESULT_COUNTS(RCS,RCN) \
364 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
365 #define RCI_TRIPLE_VALS_BASE(counts,x) \
366 counts[art_Unchecked] x \
367 + counts[art_Wanted] x \
368 + counts[art_Unsolicited] x, \
369 counts[art_Unchecked] x \
370 , counts[art_Wanted] x \
371 , counts[art_Unsolicited] x
374 #define RC_INDEX(x) RC_##x,
375 RESULT_COUNTS(RC_INDEX, RC_INDEX)
380 /*----- transmission buffers -----*/
385 xk_Malloc, xk_Const, xk_Artdata
397 /*----- core operational data structure types -----*/
400 /* This is also an instance of struct oop_readable */
401 struct oop_readable readable; /* first */
402 oop_readable_call *readable_callback;
403 void *readable_callback_user;
406 Filemon_Perfile *filemon;
408 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
409 long inprogress; /* no. of articles read but not processed */
413 int counts[art_MaxState][RCI_max];
414 int readcount_ok, readcount_blank, readcount_err;
429 #define SMS_LIST(X) \
437 enum StateMachineState {
438 #define SMS_DEF_ENUM(s) sm_##s,
439 SMS_LIST(SMS_DEF_ENUM)
442 static const char *sms_names[]= {
443 #define SMS_DEF_NAME(s) #s ,
444 SMS_LIST(SMS_DEF_NAME)
450 int fd; /* may be 0, meaning closed (during construction/destruction) */
451 oop_read *rd; /* likewise */
452 int max_queue, stream, quitting;
453 int since_activity; /* periods */
454 ArticleList waiting; /* not yet told peer */
455 ArticleList priority; /* peer says send it now */
456 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
457 struct iovec xmit[CONNIOVS];
458 XmitDetails xmitd[CONNIOVS];
463 /*----- general operational variables -----*/
465 /* main initialises */
466 static oop_source *loop;
467 static ConnList conns;
468 static ArticleList queue;
469 static char *path_lock, *path_flushing, *path_defer, *globpat_backlog;
471 /* statemc_init initialises */
472 static StateMachineState sms;
474 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
475 static int sm_period_counter;
477 /* initialisation to 0 is good */
478 static int until_connect, until_backlog_nextscan;
479 static double accept_proportion;
480 static int nocheck, nocheck_reported;
482 /*========== logging ==========*/
484 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
485 static void logcore(int sysloglevel, const char *fmt, ...) {
488 vsyslog(sysloglevel,fmt,al);
490 vfprintf(stderr,fmt,al);
496 static void logv(int sysloglevel, const char *pfx, int errnoval,
497 const char *fmt, va_list al) PRINTF(5,0);
498 static void logv(int sysloglevel, const char *pfx, int errnoval,
499 const char *fmt, va_list al) {
500 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
501 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
502 msgbuf[sizeof(msgbuf)-1]= 0;
504 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
505 sysloglevel= LOG_ERR; /* run by wrong user, probably */
507 logcore(sysloglevel, "<%s>%s: %s%s%s",
508 sitename, pfx, msgbuf,
509 errnoval>=0 ? ": " : "",
510 errnoval>=0 ? strerror(errnoval) : "");
513 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
514 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
515 static void fn(const char *fmt, ...) { \
517 logv(sysloglevel, pfx, err, fmt, al); \
521 #define logwrap(fn, pfx, sysloglevel, err) \
522 static void fn(const char *fmt, ...) PRINTF(1,2); \
523 static void fn(const char *fmt, ...) { \
525 logv(sysloglevel, pfx, err, fmt, al); \
529 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
530 diewrap(die, " critical", LOG_CRIT, -1, 16);
532 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
533 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
535 logwrap(syswarn, " warning", LOG_WARNING, errno);
536 logwrap(warn, " warning", LOG_WARNING, -1);
538 logwrap(notice, "", LOG_NOTICE, -1);
539 logwrap(info, " info", LOG_INFO, -1);
540 logwrap(debug, " debug", LOG_DEBUG, -1);
543 /*========== utility functions etc. ==========*/
545 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
546 static char *xvasprintf(const char *fmt, va_list al) {
548 int rc= vasprintf(&str,fmt,al);
549 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
552 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
553 static char *xasprintf(const char *fmt, ...) {
555 char *str= xvasprintf(fmt,al);
560 static int close_perhaps(int *fd) {
566 static void xclose(int fd, const char *what, const char *what2) {
568 if (r) sysdie("close %s%s",what,what2?what2:"");
570 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
572 xclose(*fd,what,what2);
576 static pid_t xfork(const char *what) {
580 if (child==-1) sysdie("cannot fork for %s",what);
581 debug("forked %s %ld", what, (unsigned long)child);
582 if (!child) postfork();
586 static void on_fd_read_except(int fd, oop_call_fd callback) {
587 loop->on_fd(loop, fd, OOP_READ, callback, 0);
588 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
590 static void cancel_fd_read_except(int fd) {
591 loop->cancel_fd(loop, fd, OOP_READ);
592 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
595 static void report_child_status(const char *what, int status) {
596 if (WIFEXITED(status)) {
597 int es= WEXITSTATUS(status);
599 warn("%s: child died with error exit status %d", what, es);
600 } else if (WIFSIGNALED(status)) {
601 int sig= WTERMSIG(status);
602 const char *sigstr= strsignal(sig);
603 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
605 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
607 warn("%s: child died due to unknown fatal signal %d%s",
608 what, sig, coredump);
610 warn("%s: child died with unknown wait status %d", what,status);
614 static int xwaitpid(pid_t *pid, const char *what) {
617 int r= kill(*pid, SIGKILL);
618 if (r) sysdie("cannot kill %s child", what);
620 pid_t got= waitpid(*pid, &status, WNOHANG);
621 if (got==-1) sysdie("cannot reap %s child", what);
628 static void xunlink(const char *path, const char *what) {
630 if (r) sysdie("can't unlink %s %s", path, what);
633 static time_t xtime(void) {
635 if (now==-1) sysdie("time(2) failed");
639 static void check_isreg(const struct stat *stab, const char *path,
641 if (!S_ISREG(stab->st_mode))
642 die("%s %s not a plain file (mode 0%lo)",
643 what, path, (unsigned long)stab->st_mode);
646 static void xfstat(int fd, struct stat *stab_r, const char *what) {
647 int r= fstat(fd, stab_r);
648 if (r) sysdie("could not fstat %s", what);
651 static void xfstat_isreg(int fd, struct stat *stab_r,
652 const char *path, const char *what) {
653 xfstat(fd, stab_r, what);
654 check_isreg(stab_r, path, what);
657 static void xlstat_isreg(const char *path, struct stat *stab,
658 int *enoent_r /* 0 means ENOENT is fatal */,
660 int r= lstat(path, stab);
662 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
663 sysdie("could not lstat %s %s", what, path);
665 if (enoent_r) *enoent_r= 0;
666 check_isreg(stab, path, what);
669 static int samefile(const struct stat *a, const struct stat *b) {
670 assert(S_ISREG(a->st_mode));
671 assert(S_ISREG(b->st_mode));
672 return (a->st_ino == b->st_ino &&
673 a->st_dev == b->st_dev);
676 static char *sanitise(const char *input) {
677 static char sanibuf[100]; /* returns pointer to this buffer! */
679 const char *p= input;
683 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
685 if (!c) { *q++= '\''; *q=0; break; }
686 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
687 sprintf(q,"\\x%02x",c);
693 static int isewouldblock(int errnoval) {
694 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
697 /*========== management of connections ==========*/
699 static void conn_closefd(Conn *conn, const char *msgprefix) {
700 int r= close_perhaps(&conn->fd);
701 if (r) info("C%d %serror closing socket: %s",
702 conn->fd, msgprefix, strerror(errno));
705 static void conn_dispose(Conn *conn) {
708 oop_rd_cancel(conn->rd);
709 oop_rd_delete_kill(conn->rd);
713 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
714 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
716 conn_closefd(conn,"");
718 until_connect= reconnect_delay_periods;
721 static void *conn_exception(oop_source *lp, int fd,
722 oop_event ev, void *conn_v) {
725 assert(fd == conn->fd);
726 assert(ev == OOP_EXCEPTION);
727 int r= read(conn->fd, &ch, 1);
728 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
729 else connfail(conn,"exceptional condition on socket (peer sent urgent"
730 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
734 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
735 int requeue[art_MaxState];
738 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
739 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
740 while ((art= LIST_REMHEAD(conn->sent))) {
741 requeue[art->state]++;
742 if (art->state==art_Unsolicited) art->state= art_Unchecked;
743 LIST_ADDTAIL(queue,art);
748 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
751 char *m= xvasprintf(fmt,al);
752 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
753 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
756 LIST_REMOVE(conns,conn);
758 check_assign_articles();
761 static void connfail(Conn *conn, const char *fmt, ...) {
764 vconnfail(conn,fmt,al);
768 static void check_idle_conns(void) {
770 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
771 conn->since_activity++;
773 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
774 if (conn->since_activity <= need_activity_periods) continue;
776 /* We need to shut this down */
778 connfail(conn,"timed out waiting for response to QUIT");
779 else if (conn->sent.count)
780 connfail(conn,"timed out waiting for responses");
781 else if (conn->waiting.count || conn->priority.count)
782 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
783 else if (conn->xmitu)
784 connfail(conn,"peer has been sending responses"
785 " before receiving our commands!");
787 static const char quitcmd[]= "QUIT\r\n";
788 int todo= sizeof(quitcmd)-1;
789 const char *p= quitcmd;
791 int r= write(conn->fd, p, todo);
793 if (isewouldblock(errno))
794 connfail(conn, "blocked writing QUIT to idle connection");
796 connfail(conn, "failed to write QUIT to idle connection: %s",
804 conn->since_activity= 0;
805 debug("C%d is idle, quitting", conn->fd);
814 /*---------- making new connections ----------*/
816 static pid_t connecting_child;
817 static int connecting_fdpass_sock;
819 static void connect_attempt_discard(void) {
820 if (connecting_child) {
821 int r= kill(connecting_child, SIGTERM);
822 if (r) syswarn("failed to kill connecting child");
823 int status= xwaitpid(&connecting_child, "connect");
825 if (!(WIFEXITED(status) ||
826 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
827 report_child_status("connect", status);
829 if (connecting_fdpass_sock) {
830 cancel_fd_read_except(connecting_fdpass_sock);
831 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
835 #define PREP_DECL_MSG_CMSG(msg) \
837 memset(&msg,0,sizeof(msg)); \
838 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
839 msg.msg_control= msg##cbuf; \
840 msg.msg_controllen= sizeof(msg##cbuf);
842 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
845 assert(fd == connecting_fdpass_sock);
847 conn= xmalloc(sizeof(*conn));
848 memset(conn,0,sizeof(*conn));
850 PREP_DECL_MSG_CMSG(msg);
851 struct cmsghdr *h= 0;
852 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
853 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
856 pid_t got= waitpid(connecting_child, &status, WNOHANG);
858 assert(got==connecting_child);
860 if (WIFEXITED(status)) {
861 if (WEXITSTATUS(status) != 0 &&
862 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
863 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
864 /* child already reported the problem */;
866 warn("connect: connection child exited code %d but no cmsg",
867 WEXITSTATUS(status));
868 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
869 warn("connect: connection attempt timed out");
871 report_child_status("connect", status);
874 /* child is still running apparently, report the socket problem */
876 syswarn("connect: read from fdpass socket failed");
877 else if (e == OOP_EXCEPTION)
878 warn("connect: unexpected exception on fdpass socket");
880 warn("connect: unexpected EOF on fdpass socket");
882 fatal("connect: unexpected lack of cmsg from child");
887 #define CHK(field, val) \
888 if (h->cmsg_##field != val) { \
889 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
890 h->cmsg_##field, val); \
893 CHK(level, SOL_SOCKET);
894 CHK(type, SCM_RIGHTS);
895 CHK(len, CMSG_LEN(sizeof(conn->fd)));
898 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
900 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
903 pid_t got= waitpid(connecting_child, &status, 0);
904 if (got==-1) sysdie("connect: real wait for child");
905 assert(got == connecting_child);
908 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
909 int es= WEXITSTATUS(status);
911 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
912 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
914 fatal("connect: child gave unexpected exit status %d", es);
918 LIST_INIT(conn->waiting);
919 LIST_INIT(conn->priority);
920 LIST_INIT(conn->sent);
921 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
923 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
924 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
925 if (!conn->fd) sysdie("oop_rd_new_fd (fd=%d)",conn->fd);
926 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
929 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
931 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
932 LIST_ADDHEAD(conns, conn);
934 connect_attempt_discard();
935 check_assign_articles();
940 connect_attempt_discard();
944 static int allow_connect_start(void) {
945 return conns.count < max_connections
950 static void connect_start(void) {
951 assert(!connecting_child);
952 assert(!connecting_fdpass_sock);
954 notice("starting connection attempt");
957 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
958 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
960 connecting_child= xfork("connection");
962 if (!connecting_child) {
963 FILE *cn_from, *cn_to;
964 char buf[NNTP_STRLEN+100];
965 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
967 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
969 alarm(connection_setup_timeout);
970 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
971 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
972 else sysfatal("connect: connection attempt failed");
974 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
975 sysfatal("connect: authentication failed");
977 if (fputs("MODE STREAM\r\n", cn_to) ||
979 sysfatal("connect: could not send MODE STREAM");
980 buf[sizeof(buf)-1]= 0;
981 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
983 sysfatal("connect: could not read response to MODE STREAM");
985 fatal("connect: connection close in response to MODE STREAM");
990 fatal("connect: response to MODE STREAM is too long: %.100s...",
992 l--; if (l>0 && buf[l-1]=='\r') l--;
995 int rcode= strtoul(buf,&ep,10);
997 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
1001 exitstatus= CONNCHILD_ESTATUS_STREAM;
1007 warn("connect: unexpected response to MODE STREAM: %.50s",
1013 int fd= fileno(cn_from);
1015 PREP_DECL_MSG_CMSG(msg);
1016 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1017 cmsg->cmsg_level= SOL_SOCKET;
1018 cmsg->cmsg_type= SCM_RIGHTS;
1019 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1020 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1022 msg.msg_controllen= cmsg->cmsg_len;
1023 r= sendmsg(socks[1], &msg, 0);
1024 if (r) sysdie("sendmsg failed for new connection");
1029 xclose(socks[1], "connecting fdpass child's socket",0);
1030 connecting_fdpass_sock= socks[0];
1031 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1034 /*---------- assigning articles to conns, and transmitting ----------*/
1036 static void check_assign_articles(void) {
1042 int spare=0, inqueue=0;
1044 /* Find a connection to offer this article. We prefer a busy
1045 * connection to an idle one, provided it's not full. We take the
1046 * first (oldest) and since that's stable, it will mean we fill up
1047 * connections in order. That way if we have too many
1048 * connections, the spare ones will go away eventually.
1050 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1051 if (walk->quitting) continue;
1052 inqueue= walk->sent.count + walk->priority.count
1053 + walk->waiting.count;
1054 spare= walk->max_queue - inqueue;
1055 assert(inqueue <= max_queue_per_conn);
1057 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1058 else if (spare>0) /*working*/ { use= walk; break; }
1061 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1063 Article *art= LIST_REMHEAD(queue);
1064 LIST_ADDTAIL(use->waiting, art);
1067 conn_maybe_write(use);
1068 } else if (allow_connect_start()) {
1069 until_connect= reconnect_delay_periods;
1078 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1079 conn_maybe_write(u);
1080 return OOP_CONTINUE;
1083 static void conn_maybe_write(Conn *conn) {
1085 conn_make_some_xmits(conn);
1087 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1091 void *rp= conn_write_some_xmits(conn);
1092 if (rp==OOP_CONTINUE) {
1093 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1095 } else if (rp==OOP_HALT) {
1098 /* transmitted everything */
1105 /*========== article transmission ==========*/
1107 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1108 XmitKind kind) { /* caller must then fill in details */
1109 struct iovec *v= &conn->xmit[conn->xmitu];
1110 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1111 v->iov_base= (char*)data;
1117 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1118 xmit_core(conn,data,len, xk_Const);
1120 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1122 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1123 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1127 static void xmit_free(XmitDetails *d) {
1129 case xk_Malloc: free(d->info.malloc_tofree); break;
1130 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1131 case xk_Const: break;
1136 static void *conn_write_some_xmits(Conn *conn) {
1138 * 0: nothing more to write, no need to call us again
1139 * OOP_CONTINUE: more to write but fd not writeable
1140 * OOP_HALT: disaster, have destroyed conn
1143 int count= conn->xmitu;
1144 if (!count) return 0;
1146 if (count > IOV_MAX) count= IOV_MAX;
1147 ssize_t rs= writev(conn->fd, conn->xmit, count);
1149 if (isewouldblock(errno)) return OOP_CONTINUE;
1150 connfail(conn, "write failed: %s", strerror(errno));
1156 for (done=0; rs && done<conn->xmitu; done++) {
1157 struct iovec *vp= &conn->xmit[done];
1158 XmitDetails *dp= &conn->xmitd[done];
1159 if (rs > vp->iov_len) {
1163 vp->iov_base= (char*)vp->iov_base + rs;
1167 int newu= conn->xmitu - done;
1168 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1169 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1174 static void conn_make_some_xmits(Conn *conn) {
1176 if (conn->xmitu+5 > CONNIOVS)
1179 Article *art= LIST_REMHEAD(conn->priority);
1180 if (!art) art= LIST_REMHEAD(conn->waiting);
1183 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1184 /* actually send it */
1186 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1190 XMIT_LITERAL("TAKETHIS ");
1191 xmit_noalloc(conn, art->messageid, art->midlen);
1192 XMIT_LITERAL("\r\n");
1193 xmit_artbody(conn, artdata);
1196 /* we got 235 from IHAVE */
1198 xmit_artbody(conn, artdata);
1200 XMIT_LITERAL(".\r\n");
1205 art->state == art_Unchecked ? art_Unsolicited :
1206 art->state == art_Wanted ? art_Wanted :
1208 art->ipf->counts[art->state][RC_sent]++;
1209 LIST_ADDTAIL(conn->sent, art);
1215 XMIT_LITERAL("IHAVE ");
1217 XMIT_LITERAL("CHECK ");
1218 xmit_noalloc(conn, art->messageid, art->midlen);
1219 XMIT_LITERAL("\r\n");
1221 assert(art->state == art_Unchecked);
1222 art->ipf->counts[art->state][RC_sent]++;
1223 LIST_ADDTAIL(conn->sent, art);
1229 /*========== handling responses from peer ==========*/
1231 static const oop_rd_style peer_rd_style= {
1232 OOP_RD_DELIM_STRIP, '\n',
1234 OOP_RD_SHORTREC_FORBID
1237 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1238 const char *errmsg, int errnoval,
1239 const char *data, size_t recsz, void *conn_v) {
1241 connfail(conn, "error receiving from peer: %s", errmsg);
1242 return OOP_CONTINUE;
1245 static Article *article_reply_check(Conn *conn, const char *response,
1246 int code_indicates_streaming,
1248 /* 1:yes, -1:no, 0:dontcare */,
1249 const char *sanitised_response) {
1250 Article *art= LIST_HEAD(conn->sent);
1254 "peer gave unexpected response when no commands outstanding: %s",
1255 sanitised_response);
1259 if (code_indicates_streaming) {
1260 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1261 if (!conn->stream) {
1262 connfail(conn, "peer gave streaming response code "
1263 " to IHAVE or subsequent body: %s", sanitised_response);
1266 const char *got_mid= response+4;
1267 int got_midlen= strcspn(got_mid, " \n\r");
1268 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1269 connfail(conn, "peer gave streaming response with syntactically invalid"
1270 " messageid: %s", sanitised_response);
1273 if (got_midlen != art->midlen ||
1274 memcmp(got_mid, art->messageid, got_midlen)) {
1275 connfail(conn, "peer gave streaming response code to wrong article -"
1276 " probable synchronisation problem; we offered: %s;"
1278 art->messageid, sanitised_response);
1283 connfail(conn, "peer gave non-streaming response code to"
1284 " CHECK/TAKETHIS: %s", sanitised_response);
1289 if (must_have_sent>0 && art->state < art_Wanted) {
1290 connfail(conn, "peer says article accepted but"
1291 " we had not sent the body: %s", sanitised_response);
1294 if (must_have_sent<0 && art->state >= art_Wanted) {
1295 connfail(conn, "peer says please sent the article but we just did: %s",
1296 sanitised_response);
1300 Article *art_again= LIST_REMHEAD(conn->sent);
1301 assert(art_again == art);
1305 static void update_nocheck(int accepted) {
1306 accept_proportion *= nocheck_decay;
1307 accept_proportion += accepted * (1.0 - nocheck_decay);
1308 int new_nocheck= accept_proportion >= nocheck_thresh;
1309 if (new_nocheck && !nocheck_reported) {
1310 notice("entering nocheck mode for the first time");
1311 nocheck_reported= 1;
1312 } else if (new_nocheck != nocheck) {
1313 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1315 nocheck= new_nocheck;
1318 static void article_done(Conn *conn, Article *art, int whichcount) {
1319 art->ipf->counts[art->state][whichcount]++;
1320 if (whichcount == RC_accepted) update_nocheck(1);
1321 else if (whichcount == RC_unwanted) update_nocheck(0);
1323 InputFile *ipf= art->ipf;
1325 while (art->blanklen) {
1326 static const char spaces[]=
1331 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1332 int r= pwrite(ipf->fd, spaces, w, art->offset);
1334 if (errno==EINTR) continue;
1335 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1336 art->messageid, art->blanklen,
1337 (unsigned long)art->offset, ipf->path);
1339 assert(r>=0 && r<=w);
1345 assert(ipf->inprogress >= 0);
1348 if (!ipf->inprogress && ipf != main_input_file)
1349 queue_check_input_done();
1352 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1353 const char *errmsg, int errnoval,
1354 const char *data, size_t recsz, void *conn_v) {
1357 if (ev == OOP_RD_EOF) {
1358 connfail(conn, "unexpected EOF from peer");
1359 return OOP_CONTINUE;
1361 assert(ev == OOP_RD_OK);
1363 char *sani= sanitise(data);
1366 unsigned long code= strtoul(data, &ep, 10);
1367 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1368 connfail(conn, "badly formatted response from peer: %s", sani);
1369 return OOP_CONTINUE;
1372 if (conn->quitting) {
1373 if (code!=205 && code!=503) {
1374 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1376 notice("C%d idle connection closed", conn->fd);
1377 assert(!conn->waiting.count);
1378 assert(!conn->priority.count);
1379 assert(!conn->sent.count);
1380 assert(!conn->xmitu);
1381 LIST_REMOVE(conns,conn);
1384 return OOP_CONTINUE;
1387 conn->since_activity= 0;
1390 #define GET_ARTICLE(musthavesent) \
1391 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1392 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1394 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1395 code_streaming= (streaming); \
1396 GET_ARTICLE(musthavesent); \
1397 article_done(conn, art, RC_##how); break;
1399 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1401 int code_streaming= 0;
1405 case 400: PEERBADMSG("peer stopped accepting articles");
1406 case 503: PEERBADMSG("peer timed us out");
1407 default: PEERBADMSG("peer sent unexpected message");
1409 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1410 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1412 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1413 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1415 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1416 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1418 case 238: /* CHECK says send it */
1420 case 335: /* IHAVE says send it */
1422 assert(art->state == art_Unchecked);
1423 art->ipf->counts[art->state][RC_accepted]++;
1424 art->state= art_Wanted;
1425 LIST_ADDTAIL(conn->priority, art);
1428 case 431: /* CHECK or TAKETHIS says try later */
1430 case 436: /* IHAVE says try later */
1433 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1435 sysfatal("write to defer file %s",path_defer);
1436 article_done(conn, art, RC_deferred);
1441 conn_maybe_write(conn);
1442 check_assign_articles();
1443 return OOP_CONTINUE;
1447 /*========== monitoring of input files ==========*/
1449 static void feedfile_eof(InputFile *ipf) {
1450 assert(ipf != main_input_file); /* promised by tailing_try_read */
1451 inputfile_reading_stop(ipf);
1453 if (ipf == flushing_input_file) {
1454 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1455 if (main_input_file) inputfile_reading_start(main_input_file);
1456 statemc_check_flushing_done();
1457 } else if (ipf == backlog_input_file) {
1458 statemc_check_backlog_done();
1460 abort(); /* supposed to wait rather than get EOF on main input file */
1464 static InputFile *open_input_file(const char *path) {
1465 int fd= open(path, O_RDONLY);
1467 if (errno==ENOENT) return 0;
1468 sysfatal("unable to open input file %s", path);
1472 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1473 memset(ipf,0,sizeof(*ipf));
1476 strcpy(ipf->path, path);
1481 static void close_input_file(InputFile *ipf) { /* does not free */
1482 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1483 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1484 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1485 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1486 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1490 /*---------- dealing with articles read in the input file ----------*/
1492 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1493 const char *data, const char *how) {
1494 warn("corrupted file: %s, offset %lu: %s: %s",
1495 ipf->path, (unsigned long)offset, how, sanitise(data));
1496 ipf->readcount_err++;
1497 if (ipf->readcount_err > max_bad_data_initial +
1498 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1499 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1500 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1501 return OOP_CONTINUE;
1504 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1505 oop_rd_event ev, const char *errmsg,
1506 int errnoval, const char *data, size_t recsz,
1508 InputFile *ipf= ipf_v;
1509 assert(ev == OOP_RD_SYSTEM);
1511 sysdie("error reading input file: %s, offset %lu",
1512 ipf->path, (unsigned long)ipf->offset);
1515 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1516 oop_rd_event ev, const char *errmsg,
1517 int errnoval, const char *data, size_t recsz,
1519 InputFile *ipf= ipf_v;
1521 char tokentextbuf[sizeof(TOKEN)*2+3];
1523 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1525 off_t old_offset= ipf->offset;
1526 ipf->offset += recsz + 1;
1528 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1530 if (ev==OOP_RD_PARTREC)
1531 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1532 /* but process it anyway */
1534 if (ipf->skippinglong) {
1535 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1536 return OOP_CONTINUE;
1538 if (ev==OOP_RD_LONG) {
1539 ipf->skippinglong= 1;
1540 X_BAD_DATA("overly long line");
1543 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1544 if (!recsz) X_BAD_DATA("empty line");
1547 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1548 ipf->readcount_blank++;
1549 return OOP_CONTINUE;
1552 char *space= strchr(data,' ');
1553 int tokenlen= space-data;
1554 int midlen= (int)recsz-tokenlen-1;
1555 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1556 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1558 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1559 memcpy(tokentextbuf, data, tokenlen);
1560 tokentextbuf[tokenlen]= 0;
1561 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1563 ipf->readcount_ok++;
1565 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1566 art->state= art_Unchecked;
1567 art->midlen= midlen;
1568 art->ipf= ipf; ipf->inprogress++;
1569 art->token= TextToToken(tokentextbuf);
1570 art->offset= ipf->offset;
1571 art->blanklen= recsz;
1572 strcpy(art->messageid, space+1);
1573 LIST_ADDTAIL(queue, art);
1575 if (sms==sm_NORMAL && ipf==main_input_file &&
1576 ipf->offset >= target_max_feedfile_size)
1577 statemc_start_flush("feed file size");
1579 check_assign_articles();
1580 return OOP_CONTINUE;
1583 /*========== tailing input file ==========*/
1585 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1587 InputFile *ipf= user;
1588 return ipf->readable_callback(loop, &ipf->readable,
1589 ipf->readable_callback_user);
1592 static void tailing_on_cancel(struct oop_readable *rable) {
1593 InputFile *ipf= (void*)rable;
1595 if (ipf->filemon) filemon_stop(ipf);
1596 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1597 ipf->readable_callback= 0;
1600 static void tailing_queue_readable(InputFile *ipf) {
1601 /* lifetime of ipf here is OK because destruction will cause
1602 * on_cancel which will cancel this callback */
1603 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1606 static int tailing_on_readable(struct oop_readable *rable,
1607 oop_readable_call *cb, void *user) {
1608 InputFile *ipf= (void*)rable;
1610 tailing_on_cancel(rable);
1611 ipf->readable_callback= cb;
1612 ipf->readable_callback_user= user;
1615 tailing_queue_readable(ipf);
1619 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1621 InputFile *ipf= (void*)rable;
1623 ssize_t r= read(ipf->fd, buffer, length);
1625 if (errno==EINTR) continue;
1629 if (ipf==main_input_file) {
1632 } else if (ipf==flushing_input_file) {
1634 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1635 } else if (ipf==backlog_input_file) {
1645 /*---------- filemon implemented with inotify ----------*/
1647 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1648 #define HAVE_FILEMON
1650 #include <linux/inotify.h>
1652 static int filemon_inotify_fd;
1653 static int filemon_inotify_wdmax;
1654 static InputFile **filemon_inotify_wd2ipf;
1656 struct Filemon_Perfile {
1660 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1661 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1662 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1664 if (wd >= filemon_inotify_wdmax) {
1666 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1667 sizeof(*filemon_inotify_wd2ipf) * newmax);
1668 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1669 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1670 filemon_inotify_wdmax= newmax;
1673 assert(!filemon_inotify_wd2ipf[wd]);
1674 filemon_inotify_wd2ipf[wd]= ipf;
1676 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1677 ipf, wd, filemon_inotify_wdmax);
1682 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1684 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1685 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1686 if (r) sysdie("inotify_rm_watch");
1687 filemon_inotify_wd2ipf[wd]= 0;
1690 static void *filemon_inotify_readable(oop_source *lp, int fd,
1691 oop_event e, void *u) {
1692 struct inotify_event iev;
1694 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1696 if (isewouldblock(errno)) break;
1697 sysdie("read from inotify master");
1698 } else if (r==sizeof(iev)) {
1699 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1701 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1703 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1704 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1705 filemon_callback(ipf);
1707 return OOP_CONTINUE;
1710 static int filemon_method_init(void) {
1711 filemon_inotify_fd= inotify_init();
1712 if (filemon_inotify_fd<0) {
1713 syswarn("could not initialise inotify: inotify_init failed");
1717 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1719 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1723 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1725 /*---------- filemon dummy implementation ----------*/
1727 #if !defined(HAVE_FILEMON)
1729 struct Filemon_Perfile { int dummy; };
1731 static int filemon_method_init(void) { return 0; }
1732 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1733 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1735 #endif /* !HAVE_FILEMON */
1737 /*---------- filemon generic interface ----------*/
1739 static void filemon_start(InputFile *ipf) {
1740 assert(!ipf->filemon);
1742 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1743 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1744 filemon_method_startfile(ipf, ipf->filemon);
1747 static void filemon_stop(InputFile *ipf) {
1748 if (!ipf->filemon) return;
1749 filemon_method_stopfile(ipf, ipf->filemon);
1754 static void filemon_callback(InputFile *ipf) {
1755 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1758 /*---------- interface to start and stop an input file ----------*/
1760 static const oop_rd_style feedfile_rdstyle= {
1761 OOP_RD_DELIM_STRIP, '\n',
1763 OOP_RD_SHORTREC_LONG,
1766 static void inputfile_reading_start(InputFile *ipf) {
1768 ipf->readable.on_readable= tailing_on_readable;
1769 ipf->readable.on_cancel= tailing_on_cancel;
1770 ipf->readable.try_read= tailing_try_read;
1771 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1772 ipf->readable.delete_kill= 0;
1774 ipf->readable_callback= 0;
1775 ipf->readable_callback_user= 0;
1777 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1780 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1781 feedfile_got_article,ipf, feedfile_read_err, ipf);
1782 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1785 static void inputfile_reading_stop(InputFile *ipf) {
1787 oop_rd_cancel(ipf->rd);
1788 oop_rd_delete(ipf->rd);
1790 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1794 /*========== interaction with innd - state machine ==========*/
1796 /* See official state diagram at top of file. We implement
1807 |`---------------------------------------------------.
1809 |`---------------- - - - |
1810 D ENOENT | D EXISTS see OVERALL STATES diagram |
1811 | for full startup logic |
1814 | ============ try to |
1820 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1821 ^ | hardlink F to D |
1824 | | our handle onto F is now onto D |
1827 | |<-------------------<---------------------<---------+
1829 | | spawn inndcomm flush |
1831 | ================== |
1832 | FLUSHING[-ABSENT] |
1834 | main D tail/none |
1835 | ================== |
1837 | | INNDCOMM FLUSH FAILS ^
1838 | |`----------------------->----------. |
1840 | | NO SUCH SITE V |
1841 ^ |`--------------->----. ==================== |
1842 | | \ FLUSHFAILED[-ABSENT] |
1844 | | FLUSH OK \ main D tail/none |
1845 | | open F \ ==================== |
1847 | | \ | TIME TO RETRY |
1848 | |`------->----. ,---<---'\ `----------------'
1849 | | D NONE | | D NONE `----.
1851 | ============= V V ============
1852 | SEPARATED-1 | | DROPPING-1
1853 | flsh->rd!=0 | | flsh->rd!=0
1854 | [Separated] | | [Dropping]
1855 | main F idle | | main none
1856 | old D tail | | old D tail
1857 | ============= | | ============
1859 ^ | EOF ON D | | defer | EOF ON D
1861 | =============== | | ===============
1862 | SEPARATED-2 | | DROPPING-2
1863 | flsh->rd==0 | V flsh->rd==0
1864 | [Finishing] | | [Dropping]
1865 | main F tail | `. main none
1866 | old D closed | `. old D closed
1867 | =============== V `. ===============
1869 | | ALL D PROCESSED `. | ALL D PROCESSED
1870 | V install defer as backlog `. | install defer
1871 ^ | close D `. | close D
1872 | | unlink D `. | unlink D
1875 `----------' ==============
1895 static void startup_set_input_file(InputFile *f) {
1896 assert(!main_input_file);
1898 inputfile_reading_start(f);
1901 static void statemc_init(void) {
1902 struct stat stab, stabf;
1904 path_lock= xasprintf("%s_lock", feedfile);
1905 path_flushing= xasprintf("%s_flushing", feedfile);
1906 path_defer= xasprintf("%s_defer", feedfile);
1907 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1910 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1911 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1914 memset(&fl,0,sizeof(fl));
1916 fl.l_whence= SEEK_SET;
1917 int r= fcntl(lockfd, F_SETLK, &fl);
1919 if (errno==EACCES || isewouldblock(errno)) {
1920 if (quiet_multiple) exit(0);
1921 fatal("another duct holds the lockfile");
1923 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1926 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
1928 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1930 if (!lock_noent && samefile(&stab, &stabf))
1933 xclose(lockfd, "stale lockfile ", path_lock);
1935 debug("startup: locked");
1937 search_backlog_file();
1940 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1942 debug("startup: ductdefer ENOENT");
1944 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1945 switch (stab.st_nlink==1) {
1947 open_defer(); /* so that we will later close it and rename it */
1950 xunlink(path_defer, "stale defer file link"
1951 " (presumably hardlink to backlog file)");
1954 die("defer file %s has unexpected link count %d",
1955 path_defer, stab.st_nlink);
1959 struct stat stab_f, stab_d;
1962 InputFile *file_d= open_input_file(path_flushing);
1963 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
1965 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1967 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1968 debug("startup: F==D => Hardlinked");
1969 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1974 debug("startup: F ENOENT => Moved");
1975 if (file_d) startup_set_input_file(file_d);
1976 spawn_inndcomm_flush("feedfile missing at startup");
1977 /* => Flushing, sms:=FLUSHING */
1980 debug("startup: F!=D => Separated");
1981 startup_set_input_file(file_d);
1982 SMS(SEPARATED, 0, "found both old and current feed files");
1984 debug("startup: F exists, D ENOENT => Normal");
1985 InputFile *file_f= open_input_file(feedfile);
1986 if (!file_f) die("feed file vanished during startup");
1987 startup_set_input_file(file_f);
1988 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1993 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1994 assert(sms == sm_NORMAL);
1996 debug("starting flush (%s) (%lu >?= %lu) (%d)",
1998 (unsigned long)(main_input_file ? main_input_file->offset : 0),
1999 (unsigned long)target_max_feedfile_size,
2002 int r= link(feedfile, path_flushing);
2003 if (r) sysdie("link feedfile %s to flushing file %s",
2004 feedfile, path_flushing);
2007 xunlink(feedfile, "old feedfile link");
2010 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2013 static void statemc_period_poll(void) {
2014 if (!sm_period_counter) return;
2015 sm_period_counter--;
2016 assert(sm_period_counter>=0);
2018 if (sm_period_counter) return;
2021 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2023 case sm_FLUSHFAILED:
2024 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2031 static int inputfile_is_done(InputFile *ipf) {
2033 if (ipf->inprogress) return 0; /* new article in the meantime */
2034 if (ipf->rd) return 0; /* not had EOF */
2038 static void notice_processed(InputFile *ipf, const char *what,
2040 #define RCI_NOTHING(x) /* nothing */
2041 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2042 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2044 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2046 info("processed %s%s read=%d(+%dbl,+%derr)"
2047 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2048 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2051 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2052 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2053 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2054 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2055 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2056 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2062 static void statemc_check_backlog_done(void) {
2063 InputFile *ipf= backlog_input_file;
2064 if (!inputfile_is_done(ipf)) return;
2066 const char *slash= strrchr(ipf->path, '/');
2067 const char *leaf= slash ? slash+1 : ipf->path;
2068 const char *under= strchr(slash, '_');
2069 const char *rest= under ? under+1 : leaf;
2070 if (!strncmp(rest,"backlog",7)) rest += 7;
2071 notice_processed(ipf,"backlog:",rest);
2073 close_input_file(ipf);
2074 if (unlink(ipf->path)) {
2075 if (errno != ENOENT)
2076 sysdie("could not unlink processed backlog file %s", ipf->path);
2077 warn("backlog file %s vanished while we were reading it"
2078 " so we couldn't remove it (but it's done now, anyway)",
2082 backlog_input_file= 0;
2083 search_backlog_file();
2087 static void statemc_check_flushing_done(void) {
2088 InputFile *ipf= flushing_input_file;
2089 if (!inputfile_is_done(ipf)) return;
2091 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2093 notice_processed(ipf,"feedfile",0);
2097 xunlink(path_flushing, "old flushing file");
2099 close_input_file(flushing_input_file);
2100 free(flushing_input_file);
2101 flushing_input_file= 0;
2103 if (sms==sm_SEPARATED) {
2104 notice("flush complete");
2105 SMS(NORMAL, 0, "flush complete");
2106 } else if (sms==sm_DROPPING) {
2107 SMS(DROPPED, 0, "old flush complete");
2108 search_backlog_file();
2109 notice("feed dropped, but will continue until backlog is finished");
2113 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2115 assert(!inputfile_is_done(main_input_file));
2116 statemc_check_flushing_done();
2117 statemc_check_backlog_done();
2118 return OOP_CONTINUE;
2121 static void queue_check_input_done(void) {
2122 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2125 static void statemc_setstate(StateMachineState newsms, int periods,
2126 const char *forlog, const char *why) {
2128 sm_period_counter= periods;
2130 const char *xtra= "";
2133 case sm_FLUSHFAILED:
2134 if (!main_input_file) xtra= "-ABSENT";
2138 xtra= flushing_input_file->rd ? "-1" : "-2";
2144 info("%s%s[%d] %s",forlog,xtra,periods,why);
2146 info("%s%s %s",forlog,xtra,why);
2150 /*---------- defer and backlog files ----------*/
2152 static void open_defer(void) {
2157 defer= fopen(path_defer, "a+");
2158 if (!defer) sysfatal("could not open defer file %s", path_defer);
2160 /* truncate away any half-written records */
2162 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2164 if (stab.st_size > LONG_MAX)
2165 die("defer file %s size is far too large", path_defer);
2170 long orgsize= stab.st_size;
2171 long truncto= stab.st_size;
2173 if (!truncto) break; /* was only (if anything) one half-truncated record */
2174 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2175 sysdie("seek in defer file %s while truncating partial", path_defer);
2180 sysdie("failed read from defer file %s", path_defer);
2182 die("defer file %s shrank while we were checking it!", path_defer);
2188 if (stab.st_size != truncto) {
2189 warn("truncating half-record at end of defer file %s -"
2190 " shrinking by %ld bytes from %ld to %ld",
2191 path_defer, orgsize - truncto, orgsize, truncto);
2194 sysfatal("could not flush defer file %s", path_defer);
2195 if (ftruncate(fileno(defer), truncto))
2196 sysdie("could not truncate defer file %s", path_defer);
2199 info("continuing existing defer file %s (%ld bytes)",
2200 path_defer, orgsize);
2202 if (fseek(defer, truncto, SEEK_SET))
2203 sysdie("could not seek to new end of defer file %s", path_defer);
2206 static void close_defer(void) {
2211 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2213 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2216 time_t now= xtime();
2218 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2220 (unsigned long)stab.st_ino);
2221 if (link(path_defer, backlog))
2222 sysfatal("could not install defer file %s as backlog file %s",
2223 path_defer, backlog);
2224 if (unlink(path_defer))
2225 sysdie("could not unlink old defer link %s to backlog file %s",
2226 path_defer, backlog);
2230 if (until_backlog_nextscan < 0 ||
2231 until_backlog_nextscan > backlog_retry_minperiods + 1)
2232 until_backlog_nextscan= backlog_retry_minperiods + 1;
2235 static void poll_backlog_file(void) {
2236 if (until_backlog_nextscan < 0) return;
2237 if (until_backlog_nextscan-- > 0) return;
2238 search_backlog_file();
2241 static void search_backlog_file(void) {
2242 /* returns non-0 iff there are any backlog files */
2247 const char *oldest_path=0;
2248 time_t oldest_mtime=0, now;
2250 if (backlog_input_file) return;
2254 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2258 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2260 die("out of memory expanding backlog pattern %s", globpat_backlog);
2262 for (i=0; i<gl.gl_pathc; i++) {
2263 const char *path= gl.gl_pathv[i];
2265 if (strchr(path,'#') || strchr(path,'~')) {
2266 debug("backlog file search skipping %s", path);
2269 r= stat(path, &stab);
2271 syswarn("failed to stat backlog file %s", path);
2274 if (!S_ISREG(stab.st_mode)) {
2275 warn("backlog file %s is not a plain file (or link to one)", path);
2278 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2280 oldest_mtime= stab.st_mtime;
2283 case GLOB_NOMATCH: /* fall through */
2286 sysdie("glob expansion of backlog pattern %s gave unexpected"
2287 " nonzero (error?) return value %d", globpat_backlog, r);
2291 debug("backlog scan: none");
2293 if (sms==sm_DROPPED) {
2294 notice("feed dropped and our work is complete");
2295 xunlink(path_lock, "lockfile for old feed");
2298 until_backlog_nextscan= backlog_spontrescan_periods;
2303 double age= difftime(now, oldest_mtime);
2304 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2306 if (age_deficiency <= 0) {
2307 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2308 age, age_deficiency, oldest_path);
2310 backlog_input_file= open_input_file(oldest_path);
2311 if (!backlog_input_file) {
2312 warn("backlog file %s vanished as we opened it", oldest_path);
2316 inputfile_reading_start(backlog_input_file);
2317 until_backlog_nextscan= -1;
2321 until_backlog_nextscan= age_deficiency / period_seconds;
2323 if (backlog_spontrescan_periods >= 0 &&
2324 until_backlog_nextscan > backlog_spontrescan_periods)
2325 until_backlog_nextscan= backlog_spontrescan_periods;
2327 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2328 age, age_deficiency, until_backlog_nextscan, oldest_path);
2335 /*========== flushing the feed ==========*/
2337 static pid_t inndcomm_child;
2338 static int inndcomm_sentinel_fd;
2340 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2341 assert(inndcomm_child);
2342 assert(fd == inndcomm_sentinel_fd);
2343 int status= xwaitpid(&inndcomm_child, "inndcomm");
2344 cancel_fd_read_except(fd);
2345 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2347 assert(!flushing_input_file);
2349 if (WIFEXITED(status)) {
2350 switch (WEXITSTATUS(status)) {
2352 case INNDCOMMCHILD_ESTATUS_FAIL:
2355 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2356 warn("feed has been dropped by innd, finishing up");
2357 flushing_input_file= main_input_file;
2358 tailing_queue_readable(flushing_input_file);
2359 /* we probably previously returned EAGAIN from our fake read method
2360 * when in fact we were at EOF, so signal another readable event
2361 * so we actually see the EOF */
2365 if (flushing_input_file) {
2366 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2369 SMS(DROPPED, 0, "feed dropped by innd");
2370 search_backlog_file();
2372 return OOP_CONTINUE;
2376 flushing_input_file= main_input_file;
2377 tailing_queue_readable(flushing_input_file);
2379 main_input_file= open_input_file(feedfile);
2380 if (!main_input_file)
2381 die("flush succeeded but feedfile %s does not exist!", feedfile);
2383 if (flushing_input_file) {
2384 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2387 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2389 return OOP_CONTINUE;
2392 goto unexpected_exitstatus;
2395 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2396 warn("flush timed out trying to talk to innd");
2399 unexpected_exitstatus:
2400 report_child_status("inndcomm child", status);
2404 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2405 return OOP_CONTINUE;
2408 static void inndcommfail(const char *what) {
2409 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2410 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2413 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2416 notice("flushing %s",why);
2418 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2419 assert(!inndcomm_child);
2420 assert(!inndcomm_sentinel_fd);
2422 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2424 inndcomm_child= xfork("inndcomm child");
2426 if (!inndcomm_child) {
2427 const char *flushargv[2]= { sitename, 0 };
2431 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2432 /* parent spots the autoclose of pipefds[1] when we die or exit */
2434 alarm(inndcomm_flush_timeout);
2435 r= ICCopen(); if (r) inndcommfail("connect");
2436 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2437 if (!r) exit(0); /* yay! */
2439 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2440 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2441 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2444 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2445 inndcomm_sentinel_fd= pipefds[0];
2446 assert(inndcomm_sentinel_fd);
2447 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2449 SMS(FLUSHING, 0, why);
2452 /*========== main program ==========*/
2454 static void postfork_inputfile(InputFile *ipf) {
2456 xclose(ipf->fd, "(in child) input file ", ipf->path);
2459 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2460 /* we have no stdio streams that are buffered long-term */
2462 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2465 static void postfork(void) {
2466 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2467 sysdie("(in child) failed to reset SIGPIPE");
2469 postfork_inputfile(main_input_file);
2470 postfork_inputfile(flushing_input_file);
2473 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2474 conn_closefd(conn,"(in child) ");
2476 postfork_stdio(defer, "defer file ", path_defer);
2479 #define EVERY(what, interval_sec, interval_usec, body) \
2480 static struct timeval what##_timeout = { interval_sec, interval_usec }; \
2481 static void what##_schedule(void); \
2482 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2484 what##_schedule(); \
2485 return OOP_CONTINUE; \
2487 static void what##_schedule(void) { \
2488 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2491 EVERY(filepoll, 5,0, ({
2492 if (main_input_file && main_input_file->readable_callback)
2493 filemon_callback(main_input_file);
2496 static char *debug_report_ipf(InputFile *ipf) {
2497 if (!ipf) return xasprintf("-");
2499 const char *slash= strrchr(ipf->path,'/');
2500 const char *path= slash ? slash+1 : ipf->path;
2502 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2504 ipf->inprogress, (long)ipf->offset,
2505 ipf->fd, ipf->rd ? "+" : "");
2508 EVERY(period, -1,0, ({
2509 char *dipf_main= debug_report_ipf(main_input_file);
2510 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2511 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2514 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2515 " input_files main:%s old:%s flushing:%s"
2516 " children connecting=%ld inndcomm_child=%ld"
2518 sms_names[sms], sm_period_counter,
2519 conns.count, queue.count, until_connect,
2520 dipf_main, dipf_flushing, dipf_backlog,
2521 (long)connecting_child, (long)inndcomm_child
2525 free(dipf_flushing);
2528 if (until_connect) until_connect--;
2530 poll_backlog_file();
2531 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2532 statemc_period_poll();
2533 check_assign_articles();
2538 /*========== option parsing ==========*/
2540 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2541 static void vbadusage(const char *fmt, va_list al) {
2542 char *m= xvasprintf(fmt,al);
2543 fprintf(stderr, "bad usage: %s\n"
2544 "say --help for help, or read the manpage\n",
2547 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2551 /*---------- generic option parser ----------*/
2553 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2554 static void badusage(const char *fmt, ...) {
2561 of_seconds= 001000u,
2562 of_boolean= 002000u,
2565 typedef struct Option Option;
2566 typedef void OptionParser(const Option*, const char *val);
2570 const char *lng, *formarg;
2576 static void parse_options(const Option *options, char ***argvp) {
2577 /* on return *argvp is first non-option arg; argc is not updated */
2580 const char *arg= *++(*argvp);
2582 if (*arg != '-') break;
2583 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2585 while ((a= *++arg)) {
2589 char *equals= strchr(arg,'=');
2590 int len= equals ? (equals - arg) : strlen(arg);
2591 for (o=options; o->shrt || o->lng; o++)
2592 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2594 badusage("unknown long option --%s",arg);
2597 if (equals) badusage("option --%s does not take a value",o->lng);
2599 } else if (equals) {
2603 if (!arg) badusage("option --%s needs a value for %s",
2604 o->lng, o->formarg);
2607 break; /* eaten the whole argument now */
2609 for (o=options; o->shrt || o->lng; o++)
2612 badusage("unknown short option -%c",a);
2619 if (!arg) badusage("option -%c needs a value for %s",
2620 o->shrt, o->formarg);
2623 break; /* eaten the whole argument now */
2629 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
2631 static void print_options(const Option *options, FILE *f) {
2633 for (o=options; o->shrt || o->lng; o++) {
2634 char shrt[2] = { o->shrt, 0 };
2635 char *optspec= xasprintf("%s%s%s%s%s",
2636 o->shrt ? "-" : "", shrt,
2637 o->shrt && o->lng ? "|" : "",
2638 DELIMPERHAPS("--", o->lng));
2639 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
2644 /*---------- specific option types ----------*/
2646 static void op_integer(const Option *o, const char *val) {
2649 unsigned long ul= strtoul(val,&ep,10);
2650 if (*ep || ep==val || errno || ul>INT_MAX)
2651 badusage("bad integer value for %s",o->lng);
2652 int *store= o->store;
2656 static void op_double(const Option *o, const char *val) {
2657 int *store= o->store;
2660 *store= strtod(val, &ep);
2661 if (*ep || ep==val || errno)
2662 badusage("bad floating point value for %s",o->lng);
2665 static void op_string(const Option *o, const char *val) {
2666 const char **store= o->store;
2670 static void op_seconds(const Option *o, const char *val) {
2671 int *store= o->store;
2675 double v= strtod(val,&ep);
2676 if (ep==val) badusage("bad time/duration value for %s",o->lng);
2678 if (!*ep || !strcmp(ep,"s")) unit= 1;
2679 else if (!strcmp(ep,"m")) unit= 60;
2680 else if (!strcmp(ep,"h")) unit= 3600;
2681 else if (!strcmp(ep,"d")) unit= 86400;
2682 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2686 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2690 static void op_setint(const Option *o, const char *val) {
2691 int *store= o->store;
2695 /*---------- specific options ----------*/
2697 static void help(const Option *o, const char *val);
2699 static const Option innduct_options[]= {
2700 {'f',"feedfile", "F", &feedfile, op_string },
2701 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
2702 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
2703 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
2704 {0,"inndconf", "F", &inndconffile, op_string },
2705 {'P',"port", "PORT", &port, op_integer },
2706 {0,"help", 0, 0, help },
2708 {0,"max-connections", "N", &max_connections, op_integer },
2709 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
2710 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
2711 {0,"period-interval", "TIME", &period_seconds, op_seconds },
2713 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
2714 {0,"stuck-flush-timeout","TIME", &inndcomm_flush_timeout, op_seconds },
2716 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
2717 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
2719 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
2720 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
2721 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
2722 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
2723 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
2724 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
2726 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
2727 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
2732 static void printusage(FILE *f) {
2733 fputs("usage: innduct [options] site [fqdn]\n"
2734 "available options are:\n", f);
2735 print_options(innduct_options, f);
2738 static void help(const Option *o, const char *val) {
2740 if (ferror(stdout) || fflush(stdout)) {
2741 perror("innduct: writing help");
2747 static void convert_to_periods_rndup(int *store) {
2748 *store += period_seconds-1;
2749 *store /= period_seconds;
2752 int main(int argc, char **argv) {
2758 parse_options(innduct_options, &argv);
2763 if (!sitename) badusage("need site name argument");
2764 remote_host= *argv++;
2765 if (*argv) badusage("too many non-option arguments");
2769 if (!remote_host) remote_host= sitename;
2771 if (nocheck_thresh < 0 || nocheck_thresh > 100)
2772 badusage("nocheck threshold percentage must be between 0..100");
2773 nocheck_thresh *= 0.01;
2775 if (nocheck_decay < 0.1)
2776 badusage("nocheck decay articles must be at least 0.1");
2777 nocheck_decay= 1 - 1.0/nocheck_decay;
2779 convert_to_periods_rndup(&reconnect_delay_periods);
2780 convert_to_periods_rndup(&flushfail_retry_periods);
2781 convert_to_periods_rndup(&backlog_retry_minperiods);
2782 convert_to_periods_rndup(&backlog_spontrescan_periods);
2783 convert_to_periods_rndup(&spontaneous_flush_periods);
2784 convert_to_periods_rndup(&need_activity_periods);
2786 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
2787 badusage("bad input data ratio must be between 0..100");
2788 max_bad_data_ratio *= 0.01;
2791 innconf_read(inndconffile);
2792 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
2793 } else if (!feedfile[0]) {
2794 badusage("feed filename must be nonempty");
2795 } else if (feedfile[strlen(feedfile)-1]=='/') {
2796 feedfile= xasprintf("%s%s",feedfile,sitename);
2799 const char *feedfile_forbidden= "?*[~#";
2801 while ((c= *feedfile_forbidden++))
2802 if (strchr(feedfile, c))
2803 badusage("feed filename may not contain metacharacter %c",c);
2807 oop_source_sys *sysloop= oop_sys_new();
2808 if (!sysloop) sysdie("could not create liboop event loop");
2809 loop= (oop_source*)sysloop;
2811 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2812 sysdie("could not ignore SIGPIPE");
2817 if (become_daemon) {
2819 for (i=3; i<255; i++)
2820 /* do this now before we open syslog, etc. */
2822 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2824 int null= open("/dev/null",O_RDWR);
2825 if (null<0) sysdie("failed to open /dev/null");
2829 xclose(null, "/dev/null original fd",0);
2831 pid_t child1= xfork("daemonise first fork");
2832 if (child1) _exit(0);
2834 pid_t sid= setsid();
2835 if (sid != child1) sysdie("setsid failed");
2837 pid_t child2= xfork("daemonise second fork");
2838 if (child2) _exit(0);
2843 if (!filemon_method_init()) {
2844 warn("no file monitoring available, polling");
2845 filepoll_schedule();
2848 period_timeout.tv_sec= period_seconds;
2855 void *r= oop_sys_run(sysloop);
2856 assert(r == OOP_ERROR);
2857 sysdie("event loop failed");