2 * Newsfeeds file entries should look like this:
3 * host.name.of.site[/exclude,exclude,...]\
4 * :pattern,pattern...[/distribution,distribution...]\
8 * sitename[/exclude,exclude,...]\
9 * :pattern,pattern...[/distribution,distribution...]\
15 * or might be blanked out
16 * <spc><spc><spc><spc>....
18 * F site.name main feed file
19 * opened/created, then written, by innd
22 * tokens blanked out by duct when processed
23 * site.name_lock lock preventing multiple ducts
24 * to hold lock must open,F_SETLK[W]
25 * and then stat to check that locked file
26 * still has name site.name_lock
27 * holder of this lock is "duct"
28 * (only) lockholder may remove the lockfile
29 * D site.name_flushing temporary feed file during flush (or crash)
30 * hardlink created by duct
32 * site.name_defer 431'd articles, still being written,
33 * created, written, used by duct
35 * site.name_backlog.<date>.<inum>
36 * 431'd articles, ready for innxmit or duct
37 * created (link/mv) by duct
38 * site.name_backlog<anything-else> (where <anything-else> does not
39 * contain '#' or '~') eg
40 * site.name_backlog.manual
41 * anything the sysadmin likes (eg, feed files
42 * from old feeds to be merged into this one)
43 * created (link/mv) by admin
44 * may be symlinks (in which case links
45 * may be written through, but only links
48 * It is safe to remove backlog files manually,
49 * if it's desired to throw away the backlog.
51 * Backlog files are also processed by innduct. We find the oldest
52 * backlog file which is at least a certain amount old, and feed it
53 * back into our processing. When every article in it has been read
54 * and processed, we unlink it and look for another backlog file.
56 * If we don't have a backlog file that we're reading, we close the
57 * defer file that we're writing and make it into a backlog file at
58 * the first convenient opportunity.
69 | | <----------------<---------------------------------'|
75 | F: innd writing, duct reading |
78 | | duct decides time to flush |
79 | | duct makes hardlink |
81 | V <------------------------'|
83 | F == D: innd writing, duct reading both exist |
86 | | <-----------<-------------<--'|
90 | V <---------------------. |
93 | D: innd writing, duct reading; or ENOENT | |
95 | | duct requests flush of feed | |
96 | | (others can too, harmlessly) | |
100 | D: innd flushing, duct; or ENOENT | |
102 | | inndcomm flush fails | |
103 | |`-------------------------->------------------' |
105 | | inndcomm reports no such site |
106 | |`---------------------------------------------------- | -.
108 | | innd finishes writing D, creates F | |
109 | | inndcomm reports flush successful | |
112 | Separated <----------------' |
113 | F: innd writing F!=D /
114 | D: duct reading; or ENOENT both exist /
116 | | duct gets to the end of D /
117 | | duct opens F too /
120 | F: innd writing, duct reading |
121 | D: duct finishing V
123 | | duct finishes processing D F: ENOENT
124 | V duct unlinks D D: duct reading
126 `--<--' | duct finishes
136 "duct reading" means innduct is reading the file but also
137 overwriting processed tokens.
141 * rune for printing diagrams:
143 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
148 /*============================== PROGRAM ==============================*/
150 #define _GNU_SOURCE 1
156 #include "inndcomm.h"
158 #include "inn/list.h"
159 #include "inn/innconf.h"
162 #include <sys/types.h>
163 #include <sys/wait.h>
164 #include <sys/stat.h>
165 #include <sys/socket.h>
181 #include <oop-read.h>
183 /*----- general definitions, probably best not changed -----*/
185 #define CONNCHILD_ESTATUS_STREAM 24
186 #define CONNCHILD_ESTATUS_NOSTREAM 25
188 #define INNDCOMMCHILD_ESTATUS_FAIL 26
189 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
191 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
193 #define VA va_list al; va_start(al,fmt)
194 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
195 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
197 /*----- doubly linked lists -----*/
199 #define ISNODE(T) struct node list_node
202 union { struct list li; T *for_type; } u; \
206 #define NODE(n) (assert((void*)&(n)->list_node == &(n)), &(n)->list_node)
208 #define LIST_CHECKCANHAVENODE(l,n) \
209 ((void)((n) == ((l).u.for_type))) /* just for the type check */
211 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
212 ( LIST_CHECKCANHAVENODE(l,n), \
213 list_addsomehow(&(l).u.li, NODE((n))), \
217 #define LIST_REMSOMEHOW(l,list_remsomehow) \
218 ( (typeof((l).u.for_type)) \
221 list_remsomehow(&(l).u.li) ) \
227 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
228 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
229 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
230 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
232 #define LIST_INIT(l) (list_new(&(l).u.li))
233 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
234 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
235 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
237 #define LIST_REMOVE(l,n) \
238 ( LIST_CHECKCANHAVENODE(l,n), \
239 list_remove(NODE((n))), \
243 #define LIST_INSERT(l,n,pred) \
244 ( LIST_CHECKCANHAVENODE(l,n), \
245 LIST_CHECKCANHAVENODE(l,pred), \
246 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
250 /*----- type predeclarations -----*/
252 typedef struct Conn Conn;
253 typedef struct Article Article;
254 typedef struct InputFile InputFile;
255 typedef struct XmitDetails XmitDetails;
256 typedef struct Filemon_Perfile Filemon_Perfile;
257 typedef enum StateMachineState StateMachineState;
262 /*----- function predeclarations -----*/
264 static void conn_maybe_write(Conn *conn);
265 static void conn_make_some_xmits(Conn *conn);
266 static void *conn_write_some_xmits(Conn *conn);
268 static void xmit_free(XmitDetails *d);
270 #define SMS(newstate, periods, why) \
271 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
272 static void statemc_setstate(StateMachineState newsms, int periods,
273 const char *forlog, const char *why);
275 static void statemc_start_flush(const char *why); /* Normal => Flushing */
276 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
278 static void check_assign_articles(void);
279 static void queue_check_input_done(void);
281 static void statemc_check_flushing_done(void);
282 static void statemc_check_backlog_done(void);
284 static void postfork(void);
286 static void open_defer(void);
287 static void close_defer(void);
288 static void search_backlog_file(void);
290 static void inputfile_reading_start(InputFile *ipf);
291 static void inputfile_reading_stop(InputFile *ipf);
293 static void filemon_start(InputFile *ipf);
294 static void filemon_stop(InputFile *ipf);
295 static void filemon_callback(InputFile *ipf);
297 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
298 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
300 static const oop_rd_style peer_rd_style;
301 static oop_rd_call peer_rd_err, peer_rd_ok;
303 /*----- configuration options -----*/
304 /* when changing defaults, remember to update the manpage */
306 static const char *sitename, *remote_host;
307 static const char *feedfile;
308 static int quiet_multiple=0;
309 static int become_daemon=1;
310 static int try_stream=1;
312 static const char *inndconffile;
314 static int max_connections=10;
315 static int max_queue_per_conn=200;
316 static int target_max_feedfile_size=100000;
317 static int period_seconds=60;
319 static int connection_setup_timeout=200;
320 static int inndcomm_flush_timeout=100;
322 static double nocheck_thresh= 95.0; /* converted from percentage by main */
323 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
325 /* all these are initialised to seconds, and converted to periods in main */
326 static int reconnect_delay_periods=1000;
327 static int flushfail_retry_periods=1000;
328 static int backlog_retry_minperiods=50;
329 static int backlog_spontrescan_periods=300;
330 static int spontaneous_flush_periods=100000;
331 static int need_activity_periods=1000;
333 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
334 static int max_bad_data_initial= 30;
335 /* in one corrupt 4096-byte block the number of newlines has
336 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
339 /*----- statistics -----*/
341 typedef enum { /* in queue in conn->sent */
342 art_Unchecked, /* not checked, not sent checking */
343 art_Wanted, /* checked, wanted sent body as requested */
344 art_Unsolicited, /* - sent body without check */
348 #define RESULT_COUNTS(RCS,RCN) \
356 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
357 #define RCI_TRIPLE_VALS_BASE(counts,x) \
358 counts[art_Unchecked] x \
359 + counts[art_Wanted] x \
360 + counts[art_Unsolicited] x, \
361 counts[art_Unchecked] x \
362 , counts[art_Wanted] x \
363 , counts[art_Unsolicited] x
366 #define RC_INDEX(x) RC_##x,
367 RESULT_COUNTS(RC_INDEX, RC_INDEX)
372 /*----- transmission buffers -----*/
377 xk_Malloc, xk_Const, xk_Artdata
389 /*----- core operational data structure types -----*/
392 /* This is also an instance of struct oop_readable */
393 struct oop_readable readable; /* first */
394 oop_readable_call *readable_callback;
395 void *readable_callback_user;
398 Filemon_Perfile *filemon;
400 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
401 long inprogress; /* no. of articles read but not processed */
405 int counts[art_MaxState][RCI_max];
406 int readcount_ok, readcount_blank, readcount_err;
421 #define SMS_LIST(X) \
429 enum StateMachineState {
430 #define SMS_DEF_ENUM(s) sm_##s,
431 SMS_LIST(SMS_DEF_ENUM)
434 static const char *sms_names[]= {
435 #define SMS_DEF_NAME(s) #s ,
436 SMS_LIST(SMS_DEF_NAME)
442 int fd; /* may be 0, meaning closed (during construction/destruction) */
443 oop_read *rd; /* likewise */
444 int max_queue, stream, quitting;
445 int since_activity; /* periods */
446 ArticleList waiting; /* not yet told peer */
447 ArticleList priority; /* peer says send it now */
448 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
449 struct iovec xmit[CONNIOVS];
450 XmitDetails xmitd[CONNIOVS];
455 /*----- general operational variables -----*/
457 /* main initialises */
458 static oop_source *loop;
459 static ConnList conns;
460 static ArticleList queue;
461 static char *path_lock, *path_flushing, *path_defer, *globpat_backlog;
463 /* statemc_init initialises */
464 static StateMachineState sms;
466 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
467 static int sm_period_counter;
469 /* initialisation to 0 is good */
470 static int until_connect, until_backlog_nextscan;
471 static double accept_proportion;
472 static int nocheck, nocheck_reported;
474 /*========== logging ==========*/
476 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
477 static void logcore(int sysloglevel, const char *fmt, ...) {
480 vsyslog(sysloglevel,fmt,al);
482 vfprintf(stderr,fmt,al);
488 static void logv(int sysloglevel, const char *pfx, int errnoval,
489 const char *fmt, va_list al) PRINTF(5,0);
490 static void logv(int sysloglevel, const char *pfx, int errnoval,
491 const char *fmt, va_list al) {
492 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
493 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
494 msgbuf[sizeof(msgbuf)-1]= 0;
496 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
497 sysloglevel= LOG_ERR; /* run by wrong user, probably */
499 logcore(sysloglevel, "<%s>%s: %s%s%s",
500 sitename, pfx, msgbuf,
501 errnoval>=0 ? ": " : "",
502 errnoval>=0 ? strerror(errnoval) : "");
505 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
506 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
507 static void fn(const char *fmt, ...) { \
509 logv(sysloglevel, pfx, err, fmt, al); \
513 #define logwrap(fn, pfx, sysloglevel, err) \
514 static void fn(const char *fmt, ...) PRINTF(1,2); \
515 static void fn(const char *fmt, ...) { \
517 logv(sysloglevel, pfx, err, fmt, al); \
521 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
522 diewrap(die, " critical", LOG_CRIT, -1, 16);
524 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
525 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
527 logwrap(syswarn, " warning", LOG_WARNING, errno);
528 logwrap(warn, " warning", LOG_WARNING, -1);
530 logwrap(notice, "", LOG_NOTICE, -1);
531 logwrap(info, " info", LOG_INFO, -1);
532 logwrap(debug, " debug", LOG_DEBUG, -1);
535 /*========== utility functions etc. ==========*/
537 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
538 static char *xvasprintf(const char *fmt, va_list al) {
540 int rc= vasprintf(&str,fmt,al);
541 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
544 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
545 static char *xasprintf(const char *fmt, ...) {
547 char *str= xvasprintf(fmt,al);
552 static int close_perhaps(int *fd) {
558 static void xclose(int fd, const char *what, const char *what2) {
560 if (r) sysdie("close %s%s",what,what2?what2:"");
562 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
564 xclose(*fd,what,what2);
568 static pid_t xfork(const char *what) {
572 if (child==-1) sysfatal("cannot fork for %s",what);
573 debug("forked %s %ld", what, (unsigned long)child);
574 if (!child) postfork();
578 static void on_fd_read_except(int fd, oop_call_fd callback) {
579 loop->on_fd(loop, fd, OOP_READ, callback, 0);
580 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
582 static void cancel_fd_read_except(int fd) {
583 loop->cancel_fd(loop, fd, OOP_READ);
584 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
587 static void report_child_status(const char *what, int status) {
588 if (WIFEXITED(status)) {
589 int es= WEXITSTATUS(status);
591 warn("%s: child died with error exit status %d", what, es);
592 } else if (WIFSIGNALED(status)) {
593 int sig= WTERMSIG(status);
594 const char *sigstr= strsignal(sig);
595 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
597 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
599 warn("%s: child died due to unknown fatal signal %d%s",
600 what, sig, coredump);
602 warn("%s: child died with unknown wait status %d", what,status);
606 static int xwaitpid(pid_t *pid, const char *what) {
609 int r= kill(*pid, SIGKILL);
610 if (r) sysdie("cannot kill %s child", what);
612 pid_t got= waitpid(*pid, &status, WNOHANG);
613 if (got==-1) sysdie("cannot reap %s child", what);
620 static void xunlink(const char *path, const char *what) {
622 if (r) sysdie("can't unlink %s %s", path, what);
625 static time_t xtime(void) {
627 if (now==-1) sysdie("time(2) failed");
631 static void check_isreg(const struct stat *stab, const char *path,
633 if (!S_ISREG(stab->st_mode))
634 die("%s %s not a plain file (mode 0%lo)",
635 what, path, (unsigned long)stab->st_mode);
638 static void xfstat(int fd, struct stat *stab_r, const char *what) {
639 int r= fstat(fd, stab_r);
640 if (r) sysdie("could not fstat %s", what);
643 static void xfstat_isreg(int fd, struct stat *stab_r,
644 const char *path, const char *what) {
645 xfstat(fd, stab_r, what);
646 check_isreg(stab_r, path, what);
649 static void xlstat_isreg(const char *path, struct stat *stab,
650 int *enoent_r /* 0 means ENOENT is fatal */,
652 int r= lstat(path, stab);
654 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
655 sysdie("could not lstat %s %s", what, path);
657 if (enoent_r) *enoent_r= 0;
658 check_isreg(stab, path, what);
661 static int samefile(const struct stat *a, const struct stat *b) {
662 assert(S_ISREG(a->st_mode));
663 assert(S_ISREG(b->st_mode));
664 return (a->st_ino == b->st_ino &&
665 a->st_dev == b->st_dev);
668 static char *sanitise(const char *input) {
669 static char sanibuf[100]; /* returns pointer to this buffer! */
671 const char *p= input;
675 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
677 if (!c) { *q++= '\''; *q=0; break; }
678 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
679 sprintf(q,"\\x%02x",c);
685 static int isewouldblock(int errnoval) {
686 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
689 /*========== management of connections ==========*/
691 static void conn_closefd(Conn *conn, const char *msgprefix) {
692 int r= close_perhaps(&conn->fd);
693 if (r) info("C%d %serror closing socket: %s",
694 conn->fd, msgprefix, strerror(errno));
697 static void conn_dispose(Conn *conn) {
700 oop_rd_cancel(conn->rd);
701 oop_rd_delete_kill(conn->rd);
705 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
706 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
708 conn_closefd(conn,"");
710 until_connect= reconnect_delay_periods;
713 static void *conn_exception(oop_source *lp, int fd,
714 oop_event ev, void *conn_v) {
717 assert(fd == conn->fd);
718 assert(ev == OOP_EXCEPTION);
719 int r= read(conn->fd, &ch, 1);
720 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
721 else connfail(conn,"exceptional condition on socket (peer sent urgent"
722 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
726 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
727 int requeue[art_MaxState];
730 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
731 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
732 while ((art= LIST_REMHEAD(conn->sent))) {
733 requeue[art->state]++;
734 if (art->state==art_Unsolicited) art->state= art_Unchecked;
735 LIST_ADDTAIL(queue,art);
740 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
743 char *m= xvasprintf(fmt,al);
744 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
745 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
748 LIST_REMOVE(conns,conn);
750 check_assign_articles();
753 static void connfail(Conn *conn, const char *fmt, ...) {
756 vconnfail(conn,fmt,al);
760 static void check_idle_conns(void) {
762 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
763 conn->since_activity++;
765 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
766 if (conn->since_activity <= need_activity_periods) continue;
768 /* We need to shut this down */
770 connfail(conn,"timed out waiting for response to QUIT");
771 else if (conn->sent.count)
772 connfail(conn,"timed out waiting for responses");
773 else if (conn->waiting.count || conn->priority.count)
774 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
775 else if (conn->xmitu)
776 connfail(conn,"peer has been sending responses"
777 " before receiving our commands!");
779 static const char quitcmd[]= "QUIT\r\n";
780 int todo= sizeof(quitcmd)-1;
781 const char *p= quitcmd;
783 int r= write(conn->fd, p, todo);
785 if (isewouldblock(errno))
786 connfail(conn, "blocked writing QUIT to idle connection");
788 connfail(conn, "failed to write QUIT to idle connection: %s",
796 conn->since_activity= 0;
797 debug("C%d is idle, quitting", conn->fd);
806 /*---------- making new connections ----------*/
808 static pid_t connecting_child;
809 static int connecting_fdpass_sock;
811 static void connect_attempt_discard(void) {
812 if (connecting_child) {
813 int r= kill(connecting_child, SIGTERM);
814 if (r) syswarn("failed to kill connecting child");
815 int status= xwaitpid(&connecting_child, "connect");
817 if (!(WIFEXITED(status) ||
818 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
819 report_child_status("connect", status);
821 if (connecting_fdpass_sock) {
822 cancel_fd_read_except(connecting_fdpass_sock);
823 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
827 #define PREP_DECL_MSG_CMSG(msg) \
829 memset(&msg,0,sizeof(msg)); \
830 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
831 msg.msg_control= msg##cbuf; \
832 msg.msg_controllen= sizeof(msg##cbuf);
834 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
837 assert(fd == connecting_fdpass_sock);
839 conn= xmalloc(sizeof(*conn));
840 memset(conn,0,sizeof(*conn));
842 PREP_DECL_MSG_CMSG(msg);
843 struct cmsghdr *h= 0;
844 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
845 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
848 pid_t got= waitpid(connecting_child, &status, WNOHANG);
850 assert(got==connecting_child);
852 if (WIFEXITED(status)) {
853 if (WEXITSTATUS(status) != 0 &&
854 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
855 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
856 /* child already reported the problem */;
858 warn("connect: connection child exited code %d but no cmsg",
859 WEXITSTATUS(status));
860 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
861 warn("connect: connection attempt timed out");
863 report_child_status("connect", status);
866 /* child is still running apparently, report the socket problem */
868 syswarn("connect: read from fdpass socket failed");
869 else if (e == OOP_EXCEPTION)
870 warn("connect: unexpected exception on fdpass socket");
872 warn("connect: unexpected EOF on fdpass socket");
874 fatal("connect: unexpected lack of cmsg from child");
879 #define CHK(field, val) \
880 if (h->cmsg_##field != val) { \
881 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
882 h->cmsg_##field, val); \
885 CHK(level, SOL_SOCKET);
886 CHK(type, SCM_RIGHTS);
887 CHK(len, CMSG_LEN(sizeof(conn->fd)));
890 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
892 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
895 pid_t got= waitpid(connecting_child, &status, 0);
896 if (got==-1) sysdie("connect: real wait for child");
897 assert(got == connecting_child);
900 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
901 int es= WEXITSTATUS(status);
903 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
904 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
906 fatal("connect: child gave unexpected exit status %d", es);
910 LIST_INIT(conn->waiting);
911 LIST_INIT(conn->priority);
912 LIST_INIT(conn->sent);
913 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
915 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
916 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
917 if (!conn->fd) sysdie("oop_rd_new_fd (fd=%d)",conn->fd);
918 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
921 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
923 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
924 LIST_ADDHEAD(conns, conn);
926 connect_attempt_discard();
927 check_assign_articles();
932 connect_attempt_discard();
936 static int allow_connect_start(void) {
937 return conns.count < max_connections
942 static void connect_start(void) {
943 assert(!connecting_child);
944 assert(!connecting_fdpass_sock);
946 notice("starting connection attempt");
949 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
950 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
952 connecting_child= xfork("connection");
954 if (!connecting_child) {
955 FILE *cn_from, *cn_to;
956 char buf[NNTP_STRLEN+100];
957 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
959 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
961 alarm(connection_setup_timeout);
962 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
963 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
964 else sysfatal("connect: connection attempt failed");
966 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
967 sysfatal("connect: authentication failed");
969 if (fputs("MODE STREAM\r\n", cn_to) ||
971 sysfatal("connect: could not send MODE STREAM");
972 buf[sizeof(buf)-1]= 0;
973 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
975 sysfatal("connect: could not read response to MODE STREAM");
977 fatal("connect: connection close in response to MODE STREAM");
982 fatal("connect: response to MODE STREAM is too long: %.100s...",
984 l--; if (l>0 && buf[l-1]=='\r') l--;
987 int rcode= strtoul(buf,&ep,10);
989 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
993 exitstatus= CONNCHILD_ESTATUS_STREAM;
999 warn("connect: unexpected response to MODE STREAM: %.50s",
1005 int fd= fileno(cn_from);
1007 PREP_DECL_MSG_CMSG(msg);
1008 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1009 cmsg->cmsg_level= SOL_SOCKET;
1010 cmsg->cmsg_type= SCM_RIGHTS;
1011 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1012 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1014 msg.msg_controllen= cmsg->cmsg_len;
1015 r= sendmsg(socks[1], &msg, 0);
1016 if (r) sysdie("sendmsg failed for new connection");
1021 xclose(socks[1], "connecting fdpass child's socket",0);
1022 connecting_fdpass_sock= socks[0];
1023 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1026 /*---------- assigning articles to conns, and transmitting ----------*/
1028 static void check_assign_articles(void) {
1034 int spare=0, inqueue=0;
1036 /* Find a connection to offer this article. We prefer a busy
1037 * connection to an idle one, provided it's not full. We take the
1038 * first (oldest) and since that's stable, it will mean we fill up
1039 * connections in order. That way if we have too many
1040 * connections, the spare ones will go away eventually.
1042 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1043 if (walk->quitting) continue;
1044 inqueue= walk->sent.count + walk->priority.count
1045 + walk->waiting.count;
1046 spare= walk->max_queue - inqueue;
1047 assert(inqueue <= max_queue_per_conn);
1049 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1050 else if (spare>0) /*working*/ { use= walk; break; }
1053 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1055 Article *art= LIST_REMHEAD(queue);
1056 LIST_ADDTAIL(use->waiting, art);
1059 conn_maybe_write(use);
1060 } else if (allow_connect_start()) {
1061 until_connect= reconnect_delay_periods;
1070 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1071 conn_maybe_write(u);
1072 return OOP_CONTINUE;
1075 static void conn_maybe_write(Conn *conn) {
1077 conn_make_some_xmits(conn);
1079 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1083 void *rp= conn_write_some_xmits(conn);
1084 if (rp==OOP_CONTINUE) {
1085 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1087 } else if (rp==OOP_HALT) {
1090 /* transmitted everything */
1097 /*========== article transmission ==========*/
1099 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1100 XmitKind kind) { /* caller must then fill in details */
1101 struct iovec *v= &conn->xmit[conn->xmitu];
1102 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1103 v->iov_base= (char*)data;
1109 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1110 xmit_core(conn,data,len, xk_Const);
1112 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1114 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1115 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1119 static void xmit_free(XmitDetails *d) {
1121 case xk_Malloc: free(d->info.malloc_tofree); break;
1122 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1123 case xk_Const: break;
1128 static void *conn_write_some_xmits(Conn *conn) {
1130 * 0: nothing more to write, no need to call us again
1131 * OOP_CONTINUE: more to write but fd not writeable
1132 * OOP_HALT: disaster, have destroyed conn
1135 int count= conn->xmitu;
1136 if (!count) return 0;
1138 if (count > IOV_MAX) count= IOV_MAX;
1139 ssize_t rs= writev(conn->fd, conn->xmit, count);
1141 if (isewouldblock(errno)) return OOP_CONTINUE;
1142 connfail(conn, "write failed: %s", strerror(errno));
1148 for (done=0; rs && done<conn->xmitu; done++) {
1149 struct iovec *vp= &conn->xmit[done];
1150 XmitDetails *dp= &conn->xmitd[done];
1151 if (rs > vp->iov_len) {
1155 vp->iov_base= (char*)vp->iov_base + rs;
1159 int newu= conn->xmitu - done;
1160 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1161 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1166 static void conn_make_some_xmits(Conn *conn) {
1168 if (conn->xmitu+5 > CONNIOVS)
1171 Article *art= LIST_REMHEAD(conn->priority);
1172 if (!art) art= LIST_REMHEAD(conn->waiting);
1175 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1176 /* actually send it */
1178 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1182 XMIT_LITERAL("TAKETHIS ");
1183 xmit_noalloc(conn, art->messageid, art->midlen);
1184 XMIT_LITERAL("\r\n");
1185 xmit_artbody(conn, artdata);
1188 /* we got 235 from IHAVE */
1190 xmit_artbody(conn, artdata);
1192 XMIT_LITERAL(".\r\n");
1197 art->state == art_Unchecked ? art_Unsolicited :
1198 art->state == art_Wanted ? art_Wanted :
1200 art->ipf->counts[art->state][RC_sent]++;
1201 LIST_ADDTAIL(conn->sent, art);
1207 XMIT_LITERAL("IHAVE ");
1209 XMIT_LITERAL("CHECK ");
1210 xmit_noalloc(conn, art->messageid, art->midlen);
1211 XMIT_LITERAL("\r\n");
1213 assert(art->state == art_Unchecked);
1214 art->ipf->counts[art->state][RC_sent]++;
1215 LIST_ADDTAIL(conn->sent, art);
1221 /*========== handling responses from peer ==========*/
1223 static const oop_rd_style peer_rd_style= {
1224 OOP_RD_DELIM_STRIP, '\n',
1226 OOP_RD_SHORTREC_FORBID
1229 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1230 const char *errmsg, int errnoval,
1231 const char *data, size_t recsz, void *conn_v) {
1233 connfail(conn, "error receiving from peer: %s", errmsg);
1234 return OOP_CONTINUE;
1237 static Article *article_reply_check(Conn *conn, const char *response,
1238 int code_indicates_streaming,
1240 /* 1:yes, -1:no, 0:dontcare */,
1241 const char *sanitised_response) {
1242 Article *art= LIST_HEAD(conn->sent);
1246 "peer gave unexpected response when no commands outstanding: %s",
1247 sanitised_response);
1251 if (code_indicates_streaming) {
1252 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1253 if (!conn->stream) {
1254 connfail(conn, "peer gave streaming response code "
1255 " to IHAVE or subsequent body: %s", sanitised_response);
1258 const char *got_mid= response+4;
1259 int got_midlen= strcspn(got_mid, " \n\r");
1260 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1261 connfail(conn, "peer gave streaming response with syntactically invalid"
1262 " messageid: %s", sanitised_response);
1265 if (got_midlen != art->midlen ||
1266 memcmp(got_mid, art->messageid, got_midlen)) {
1267 connfail(conn, "peer gave streaming response code to wrong article -"
1268 " probable synchronisation problem; we offered: %s;"
1270 art->messageid, sanitised_response);
1275 connfail(conn, "peer gave non-streaming response code to"
1276 " CHECK/TAKETHIS: %s", sanitised_response);
1281 if (must_have_sent>0 && art->state < art_Wanted) {
1282 connfail(conn, "peer says article accepted but"
1283 " we had not sent the body: %s", sanitised_response);
1286 if (must_have_sent<0 && art->state >= art_Wanted) {
1287 connfail(conn, "peer says please sent the article but we just did: %s",
1288 sanitised_response);
1292 Article *art_again= LIST_REMHEAD(conn->sent);
1293 assert(art_again == art);
1297 static void update_nocheck(int accepted) {
1298 accept_proportion *= nocheck_decay;
1299 accept_proportion += accepted * (1.0 - nocheck_decay);
1300 int new_nocheck= accept_proportion >= nocheck_thresh;
1301 if (new_nocheck && !nocheck_reported) {
1302 notice("entering nocheck mode for the first time");
1303 nocheck_reported= 1;
1304 } else if (new_nocheck != nocheck) {
1305 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1307 nocheck= new_nocheck;
1310 static void article_done(Conn *conn, Article *art, int whichcount) {
1311 art->ipf->counts[art->state][whichcount]++;
1312 if (whichcount == RC_accepted) update_nocheck(1);
1313 else if (whichcount == RC_unwanted) update_nocheck(0);
1315 InputFile *ipf= art->ipf;
1317 while (art->blanklen) {
1318 static const char spaces[]=
1323 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1324 int r= pwrite(ipf->fd, spaces, w, art->offset);
1326 if (errno==EINTR) continue;
1327 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1328 art->messageid, art->blanklen,
1329 (unsigned long)art->offset, ipf->path);
1331 assert(r>=0 && r<=w);
1337 assert(ipf->inprogress >= 0);
1340 if (!ipf->inprogress && ipf != main_input_file)
1341 queue_check_input_done();
1344 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1345 const char *errmsg, int errnoval,
1346 const char *data, size_t recsz, void *conn_v) {
1349 if (ev == OOP_RD_EOF) {
1350 connfail(conn, "unexpected EOF from peer");
1351 return OOP_CONTINUE;
1353 assert(ev == OOP_RD_OK);
1355 char *sani= sanitise(data);
1358 unsigned long code= strtoul(data, &ep, 10);
1359 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1360 connfail(conn, "badly formatted response from peer: %s", sani);
1361 return OOP_CONTINUE;
1364 if (conn->quitting) {
1365 if (code!=205 && code!=503) {
1366 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1368 notice("C%d idle connection closed", conn->fd);
1369 assert(!conn->waiting.count);
1370 assert(!conn->priority.count);
1371 assert(!conn->sent.count);
1372 assert(!conn->xmitu);
1373 LIST_REMOVE(conns,conn);
1376 return OOP_CONTINUE;
1379 conn->since_activity= 0;
1382 #define GET_ARTICLE(musthavesent) \
1383 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1384 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1386 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1387 code_streaming= (streaming); \
1388 GET_ARTICLE(musthavesent); \
1389 article_done(conn, art, RC_##how); break;
1391 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1393 int code_streaming= 0;
1397 case 400: PEERBADMSG("peer stopped accepting articles");
1398 case 503: PEERBADMSG("peer timed us out");
1399 default: PEERBADMSG("peer sent unexpected message");
1401 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1402 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1404 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1405 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1407 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1408 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1410 case 238: /* CHECK says send it */
1412 case 335: /* IHAVE says send it */
1414 assert(art->state == art_Unchecked);
1415 art->ipf->counts[art->state][RC_accepted]++;
1416 art->state= art_Wanted;
1417 LIST_ADDTAIL(conn->priority, art);
1420 case 431: /* CHECK or TAKETHIS says try later */
1422 case 436: /* IHAVE says try later */
1425 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1427 sysfatal("write to defer file %s",path_defer);
1428 article_done(conn, art, RC_deferred);
1433 conn_maybe_write(conn);
1434 check_assign_articles();
1435 return OOP_CONTINUE;
1439 /*========== monitoring of input files ==========*/
1441 static void feedfile_eof(InputFile *ipf) {
1442 assert(ipf != main_input_file); /* promised by tailing_try_read */
1443 inputfile_reading_stop(ipf);
1445 if (ipf == flushing_input_file) {
1446 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1447 if (main_input_file) inputfile_reading_start(main_input_file);
1448 statemc_check_flushing_done();
1449 } else if (ipf == backlog_input_file) {
1450 statemc_check_backlog_done();
1452 abort(); /* supposed to wait rather than get EOF on main input file */
1456 static InputFile *open_input_file(const char *path) {
1457 int fd= open(path, O_RDONLY);
1459 if (errno==ENOENT) return 0;
1460 sysfatal("unable to open input file %s", path);
1464 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1465 memset(ipf,0,sizeof(*ipf));
1468 strcpy(ipf->path, path);
1473 static void close_input_file(InputFile *ipf) { /* does not free */
1474 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1475 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1476 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1477 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1478 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1482 /*---------- dealing with articles read in the input file ----------*/
1484 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1485 const char *data, const char *how) {
1486 warn("corrupted file: %s, offset %lu: %s: %s",
1487 ipf->path, (unsigned long)offset, how, sanitise(data));
1488 ipf->readcount_err++;
1489 if (ipf->readcount_err > max_bad_data_initial +
1490 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1491 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1492 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1493 return OOP_CONTINUE;
1496 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1497 oop_rd_event ev, const char *errmsg,
1498 int errnoval, const char *data, size_t recsz,
1500 InputFile *ipf= ipf_v;
1501 assert(ev == OOP_RD_SYSTEM);
1503 sysdie("error reading input file: %s, offset %lu",
1504 ipf->path, (unsigned long)ipf->offset);
1507 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1508 oop_rd_event ev, const char *errmsg,
1509 int errnoval, const char *data, size_t recsz,
1511 InputFile *ipf= ipf_v;
1513 char tokentextbuf[sizeof(TOKEN)*2+3];
1515 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1517 off_t old_offset= ipf->offset;
1518 ipf->offset += recsz + 1;
1520 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1522 if (ev==OOP_RD_PARTREC)
1523 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1524 /* but process it anyway */
1526 if (ipf->skippinglong) {
1527 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1528 return OOP_CONTINUE;
1530 if (ev==OOP_RD_LONG) {
1531 ipf->skippinglong= 1;
1532 X_BAD_DATA("overly long line");
1535 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1536 if (!recsz) X_BAD_DATA("empty line");
1539 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1540 ipf->readcount_blank++;
1541 return OOP_CONTINUE;
1544 char *space= strchr(data,' ');
1545 int tokenlen= space-data;
1546 int midlen= (int)recsz-tokenlen-1;
1547 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1548 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1550 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1551 memcpy(tokentextbuf, data, tokenlen);
1552 tokentextbuf[tokenlen]= 0;
1553 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1555 ipf->readcount_ok++;
1557 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1558 art->state= art_Unchecked;
1559 art->midlen= midlen;
1560 art->ipf= ipf; ipf->inprogress++;
1561 art->token= TextToToken(tokentextbuf);
1562 art->offset= ipf->offset;
1563 art->blanklen= recsz;
1564 strcpy(art->messageid, space+1);
1565 LIST_ADDTAIL(queue, art);
1567 if (sms==sm_NORMAL && ipf==main_input_file &&
1568 ipf->offset >= target_max_feedfile_size)
1569 statemc_start_flush("feed file size");
1571 check_assign_articles();
1572 return OOP_CONTINUE;
1575 /*========== tailing input file ==========*/
1577 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1579 InputFile *ipf= user;
1580 return ipf->readable_callback(loop, &ipf->readable,
1581 ipf->readable_callback_user);
1584 static void tailing_on_cancel(struct oop_readable *rable) {
1585 InputFile *ipf= (void*)rable;
1587 if (ipf->filemon) filemon_stop(ipf);
1588 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1589 ipf->readable_callback= 0;
1592 static void tailing_queue_readable(InputFile *ipf) {
1593 /* lifetime of ipf here is OK because destruction will cause
1594 * on_cancel which will cancel this callback */
1595 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1598 static int tailing_on_readable(struct oop_readable *rable,
1599 oop_readable_call *cb, void *user) {
1600 InputFile *ipf= (void*)rable;
1602 tailing_on_cancel(rable);
1603 ipf->readable_callback= cb;
1604 ipf->readable_callback_user= user;
1607 tailing_queue_readable(ipf);
1611 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1613 InputFile *ipf= (void*)rable;
1615 ssize_t r= read(ipf->fd, buffer, length);
1617 if (errno==EINTR) continue;
1621 if (ipf==main_input_file) {
1624 } else if (ipf==flushing_input_file) {
1626 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1627 } else if (ipf==backlog_input_file) {
1637 /*---------- filemon implemented with inotify ----------*/
1639 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1640 #define HAVE_FILEMON
1642 #include <linux/inotify.h>
1644 static int filemon_inotify_fd;
1645 static int filemon_inotify_wdmax;
1646 static InputFile **filemon_inotify_wd2ipf;
1648 struct Filemon_Perfile {
1652 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1653 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1654 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
1656 if (wd >= filemon_inotify_wdmax) {
1658 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1659 sizeof(*filemon_inotify_wd2ipf) * newmax);
1660 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1661 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1662 filemon_inotify_wdmax= newmax;
1665 assert(!filemon_inotify_wd2ipf[wd]);
1666 filemon_inotify_wd2ipf[wd]= ipf;
1668 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1669 ipf, wd, filemon_inotify_wdmax);
1674 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1676 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1677 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1678 if (r) sysdie("inotify_rm_watch");
1679 filemon_inotify_wd2ipf[wd]= 0;
1682 static void *filemon_inotify_readable(oop_source *lp, int fd,
1683 oop_event e, void *u) {
1684 struct inotify_event iev;
1686 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1688 if (isewouldblock(errno)) break;
1689 sysdie("read from inotify master");
1690 } else if (r==sizeof(iev)) {
1691 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1693 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1695 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1696 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1697 filemon_callback(ipf);
1699 return OOP_CONTINUE;
1702 static int filemon_method_init(void) {
1703 filemon_inotify_fd= inotify_init();
1704 if (filemon_inotify_fd<0) {
1705 syswarn("could not initialise inotify: inotify_init failed");
1709 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1711 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1715 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1717 /*---------- filemon dummy implementation ----------*/
1719 #if !defined(HAVE_FILEMON)
1721 struct Filemon_Perfile { int dummy; };
1723 static int filemon_method_init(void) { return 0; }
1724 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1725 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1727 #endif /* !HAVE_FILEMON */
1729 /*---------- filemon generic interface ----------*/
1731 static void filemon_start(InputFile *ipf) {
1732 assert(!ipf->filemon);
1734 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1735 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1736 filemon_method_startfile(ipf, ipf->filemon);
1739 static void filemon_stop(InputFile *ipf) {
1740 if (!ipf->filemon) return;
1741 filemon_method_stopfile(ipf, ipf->filemon);
1746 static void filemon_callback(InputFile *ipf) {
1747 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1750 /*---------- interface to start and stop an input file ----------*/
1752 static const oop_rd_style feedfile_rdstyle= {
1753 OOP_RD_DELIM_STRIP, '\n',
1755 OOP_RD_SHORTREC_LONG,
1758 static void inputfile_reading_start(InputFile *ipf) {
1760 ipf->readable.on_readable= tailing_on_readable;
1761 ipf->readable.on_cancel= tailing_on_cancel;
1762 ipf->readable.try_read= tailing_try_read;
1763 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1764 ipf->readable.delete_kill= 0;
1766 ipf->readable_callback= 0;
1767 ipf->readable_callback_user= 0;
1769 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1772 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1773 feedfile_got_article,ipf, feedfile_read_err, ipf);
1774 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1777 static void inputfile_reading_stop(InputFile *ipf) {
1779 oop_rd_cancel(ipf->rd);
1780 oop_rd_delete(ipf->rd);
1782 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1786 /*========== interaction with innd - state machine ==========*/
1788 /* See official state diagram at top of file. We implement
1799 |`---------------------------------------------------.
1801 |`---------------- - - - |
1802 D ENOENT | D EXISTS see OVERALL STATES diagram |
1803 | for full startup logic |
1806 | ============ try to |
1812 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1813 ^ | hardlink F to D |
1816 | | our handle onto F is now onto D |
1819 | |<-------------------<---------------------<---------+
1821 | | spawn inndcomm flush |
1823 | ================== |
1824 | FLUSHING[-ABSENT] |
1826 | main D tail/none |
1827 | ================== |
1829 | | INNDCOMM FLUSH FAILS ^
1830 | |`----------------------->----------. |
1832 | | NO SUCH SITE V |
1833 ^ |`--------------->----. ==================== |
1834 | | \ FLUSHFAILED[-ABSENT] |
1836 | | FLUSH OK \ main D tail/none |
1837 | | open F \ ==================== |
1839 | | \ | TIME TO RETRY |
1840 | |`------->----. ,---<---'\ `----------------'
1841 | | D NONE | | D NONE `----.
1843 | ============= V V ============
1844 | SEPARATED-1 | | DROPPING-1
1845 | flsh->rd!=0 | | flsh->rd!=0
1846 | [Separated] | | [Dropping]
1847 | main F idle | | main none
1848 | old D tail | | old D tail
1849 | ============= | | ============
1851 ^ | EOF ON D | | defer | EOF ON D
1853 | =============== | | ===============
1854 | SEPARATED-2 | | DROPPING-2
1855 | flsh->rd==0 | V flsh->rd==0
1856 | [Finishing] | | [Dropping]
1857 | main F tail | `. main none
1858 | old D closed | `. old D closed
1859 | =============== V `. ===============
1861 | | ALL D PROCESSED `. | ALL D PROCESSED
1862 | V install defer as backlog `. | install defer
1863 ^ | close D `. | close D
1864 | | unlink D `. | unlink D
1867 `----------' ==============
1887 static void startup_set_input_file(InputFile *f) {
1888 assert(!main_input_file);
1890 inputfile_reading_start(f);
1893 static void statemc_init(void) {
1894 struct stat stab, stabf;
1896 path_lock= xasprintf("%s_lock", feedfile);
1897 path_flushing= xasprintf("%s_flushing", feedfile);
1898 path_defer= xasprintf("%s_defer", feedfile);
1899 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1904 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1905 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1908 memset(&fl,0,sizeof(fl));
1910 fl.l_whence= SEEK_SET;
1911 int r= fcntl(lockfd, F_SETLK, &fl);
1913 if (errno==EACCES || isewouldblock(errno)) {
1914 if (quiet_multiple) exit(0);
1915 fatal("another duct holds the lockfile");
1917 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
1920 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
1922 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1924 if (!lock_noent && samefile(&stab, &stabf))
1927 xclose(lockfd, "stale lockfile ", path_lock);
1929 pid_t self= getpid();
1930 if (self==-1) sysdie("getpid");
1932 FILE *lockfile= fdopen(lockfd, "w");
1933 if (!lockfile) sysdie("fdopen lockfile");
1935 int r= ftruncate(lockfd, 0);
1936 if (r) sysdie("truncate lockfile to write new info");
1938 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
1939 (unsigned long)self, sitename, feedfile, remote_host) == EOF ||
1941 sysfatal("write info to lockfile %s", path_lock);
1943 debug("startup: locked");
1945 search_backlog_file();
1948 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1950 debug("startup: ductdefer ENOENT");
1952 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1953 switch (stab.st_nlink==1) {
1955 open_defer(); /* so that we will later close it and rename it */
1958 xunlink(path_defer, "stale defer file link"
1959 " (presumably hardlink to backlog file)");
1962 die("defer file %s has unexpected link count %d",
1963 path_defer, stab.st_nlink);
1967 struct stat stab_f, stab_d;
1970 InputFile *file_d= open_input_file(path_flushing);
1971 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
1973 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1975 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1976 debug("startup: F==D => Hardlinked");
1977 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1982 debug("startup: F ENOENT => Moved");
1983 if (file_d) startup_set_input_file(file_d);
1984 spawn_inndcomm_flush("feedfile missing at startup");
1985 /* => Flushing, sms:=FLUSHING */
1988 debug("startup: F!=D => Separated");
1989 startup_set_input_file(file_d);
1990 SMS(SEPARATED, 0, "found both old and current feed files");
1992 debug("startup: F exists, D ENOENT => Normal");
1993 InputFile *file_f= open_input_file(feedfile);
1994 if (!file_f) die("feed file vanished during startup");
1995 startup_set_input_file(file_f);
1996 SMS(NORMAL, flushfail_retry_periods, "normal startup");
2001 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2002 assert(sms == sm_NORMAL);
2004 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2006 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2007 (unsigned long)target_max_feedfile_size,
2010 int r= link(feedfile, path_flushing);
2011 if (r) sysfatal("link feedfile %s to flushing file %s",
2012 feedfile, path_flushing);
2015 xunlink(feedfile, "old feedfile link");
2018 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2021 static void statemc_period_poll(void) {
2022 if (!sm_period_counter) return;
2023 sm_period_counter--;
2024 assert(sm_period_counter>=0);
2026 if (sm_period_counter) return;
2029 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2031 case sm_FLUSHFAILED:
2032 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2039 static int inputfile_is_done(InputFile *ipf) {
2041 if (ipf->inprogress) return 0; /* new article in the meantime */
2042 if (ipf->rd) return 0; /* not had EOF */
2046 static void notice_processed(InputFile *ipf, const char *what,
2048 #define RCI_NOTHING(x) /* nothing */
2049 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2050 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2052 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2054 info("processed %s%s read=%d(+%dbl,+%derr)"
2055 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2056 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2059 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2060 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2061 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2062 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2063 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2064 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2070 static void statemc_check_backlog_done(void) {
2071 InputFile *ipf= backlog_input_file;
2072 if (!inputfile_is_done(ipf)) return;
2074 const char *slash= strrchr(ipf->path, '/');
2075 const char *leaf= slash ? slash+1 : ipf->path;
2076 const char *under= strchr(slash, '_');
2077 const char *rest= under ? under+1 : leaf;
2078 if (!strncmp(rest,"backlog",7)) rest += 7;
2079 notice_processed(ipf,"backlog:",rest);
2081 close_input_file(ipf);
2082 if (unlink(ipf->path)) {
2083 if (errno != ENOENT)
2084 sysdie("could not unlink processed backlog file %s", ipf->path);
2085 warn("backlog file %s vanished while we were reading it"
2086 " so we couldn't remove it (but it's done now, anyway)",
2090 backlog_input_file= 0;
2091 search_backlog_file();
2095 static void statemc_check_flushing_done(void) {
2096 InputFile *ipf= flushing_input_file;
2097 if (!inputfile_is_done(ipf)) return;
2099 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2101 notice_processed(ipf,"feedfile",0);
2105 xunlink(path_flushing, "old flushing file");
2107 close_input_file(flushing_input_file);
2108 free(flushing_input_file);
2109 flushing_input_file= 0;
2111 if (sms==sm_SEPARATED) {
2112 notice("flush complete");
2113 SMS(NORMAL, 0, "flush complete");
2114 } else if (sms==sm_DROPPING) {
2115 SMS(DROPPED, 0, "old flush complete");
2116 search_backlog_file();
2117 notice("feed dropped, but will continue until backlog is finished");
2121 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2123 assert(!inputfile_is_done(main_input_file));
2124 statemc_check_flushing_done();
2125 statemc_check_backlog_done();
2126 return OOP_CONTINUE;
2129 static void queue_check_input_done(void) {
2130 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2133 static void statemc_setstate(StateMachineState newsms, int periods,
2134 const char *forlog, const char *why) {
2136 sm_period_counter= periods;
2138 const char *xtra= "";
2141 case sm_FLUSHFAILED:
2142 if (!main_input_file) xtra= "-ABSENT";
2146 xtra= flushing_input_file->rd ? "-1" : "-2";
2152 info("%s%s[%d] %s",forlog,xtra,periods,why);
2154 info("%s%s %s",forlog,xtra,why);
2158 /*---------- defer and backlog files ----------*/
2160 static void open_defer(void) {
2165 defer= fopen(path_defer, "a+");
2166 if (!defer) sysfatal("could not open defer file %s", path_defer);
2168 /* truncate away any half-written records */
2170 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2172 if (stab.st_size > LONG_MAX)
2173 die("defer file %s size is far too large", path_defer);
2178 long orgsize= stab.st_size;
2179 long truncto= stab.st_size;
2181 if (!truncto) break; /* was only (if anything) one half-truncated record */
2182 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2183 sysdie("seek in defer file %s while truncating partial", path_defer);
2188 sysdie("failed read from defer file %s", path_defer);
2190 die("defer file %s shrank while we were checking it!", path_defer);
2196 if (stab.st_size != truncto) {
2197 warn("truncating half-record at end of defer file %s -"
2198 " shrinking by %ld bytes from %ld to %ld",
2199 path_defer, orgsize - truncto, orgsize, truncto);
2202 sysfatal("could not flush defer file %s", path_defer);
2203 if (ftruncate(fileno(defer), truncto))
2204 sysdie("could not truncate defer file %s", path_defer);
2207 info("continuing existing defer file %s (%ld bytes)",
2208 path_defer, orgsize);
2210 if (fseek(defer, truncto, SEEK_SET))
2211 sysdie("could not seek to new end of defer file %s", path_defer);
2214 static void close_defer(void) {
2219 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2221 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2224 time_t now= xtime();
2226 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2228 (unsigned long)stab.st_ino);
2229 if (link(path_defer, backlog))
2230 sysfatal("could not install defer file %s as backlog file %s",
2231 path_defer, backlog);
2232 if (unlink(path_defer))
2233 sysdie("could not unlink old defer link %s to backlog file %s",
2234 path_defer, backlog);
2238 if (until_backlog_nextscan < 0 ||
2239 until_backlog_nextscan > backlog_retry_minperiods + 1)
2240 until_backlog_nextscan= backlog_retry_minperiods + 1;
2243 static void poll_backlog_file(void) {
2244 if (until_backlog_nextscan < 0) return;
2245 if (until_backlog_nextscan-- > 0) return;
2246 search_backlog_file();
2249 static void search_backlog_file(void) {
2250 /* returns non-0 iff there are any backlog files */
2255 const char *oldest_path=0;
2256 time_t oldest_mtime=0, now;
2258 if (backlog_input_file) return;
2262 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2266 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2268 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2270 for (i=0; i<gl.gl_pathc; i++) {
2271 const char *path= gl.gl_pathv[i];
2273 if (strchr(path,'#') || strchr(path,'~')) {
2274 debug("backlog file search skipping %s", path);
2277 r= stat(path, &stab);
2279 syswarn("failed to stat backlog file %s", path);
2282 if (!S_ISREG(stab.st_mode)) {
2283 warn("backlog file %s is not a plain file (or link to one)", path);
2286 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2288 oldest_mtime= stab.st_mtime;
2291 case GLOB_NOMATCH: /* fall through */
2294 sysdie("glob expansion of backlog pattern %s gave unexpected"
2295 " nonzero (error?) return value %d", globpat_backlog, r);
2299 debug("backlog scan: none");
2301 if (sms==sm_DROPPED) {
2302 notice("feed dropped and our work is complete");
2303 xunlink(path_lock, "lockfile for old feed");
2306 until_backlog_nextscan= backlog_spontrescan_periods;
2311 double age= difftime(now, oldest_mtime);
2312 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2314 if (age_deficiency <= 0) {
2315 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2316 age, age_deficiency, oldest_path);
2318 backlog_input_file= open_input_file(oldest_path);
2319 if (!backlog_input_file) {
2320 warn("backlog file %s vanished as we opened it", oldest_path);
2324 inputfile_reading_start(backlog_input_file);
2325 until_backlog_nextscan= -1;
2329 until_backlog_nextscan= age_deficiency / period_seconds;
2331 if (backlog_spontrescan_periods >= 0 &&
2332 until_backlog_nextscan > backlog_spontrescan_periods)
2333 until_backlog_nextscan= backlog_spontrescan_periods;
2335 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2336 age, age_deficiency, until_backlog_nextscan, oldest_path);
2343 /*========== flushing the feed ==========*/
2345 static pid_t inndcomm_child;
2346 static int inndcomm_sentinel_fd;
2348 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2349 assert(inndcomm_child);
2350 assert(fd == inndcomm_sentinel_fd);
2351 int status= xwaitpid(&inndcomm_child, "inndcomm");
2352 cancel_fd_read_except(fd);
2353 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2355 assert(!flushing_input_file);
2357 if (WIFEXITED(status)) {
2358 switch (WEXITSTATUS(status)) {
2360 case INNDCOMMCHILD_ESTATUS_FAIL:
2363 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2364 warn("feed has been dropped by innd, finishing up");
2365 flushing_input_file= main_input_file;
2366 tailing_queue_readable(flushing_input_file);
2367 /* we probably previously returned EAGAIN from our fake read method
2368 * when in fact we were at EOF, so signal another readable event
2369 * so we actually see the EOF */
2373 if (flushing_input_file) {
2374 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2377 SMS(DROPPED, 0, "feed dropped by innd");
2378 search_backlog_file();
2380 return OOP_CONTINUE;
2384 flushing_input_file= main_input_file;
2385 tailing_queue_readable(flushing_input_file);
2387 main_input_file= open_input_file(feedfile);
2388 if (!main_input_file)
2389 die("flush succeeded but feedfile %s does not exist!", feedfile);
2391 if (flushing_input_file) {
2392 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2395 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2397 return OOP_CONTINUE;
2400 goto unexpected_exitstatus;
2403 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2404 warn("flush timed out trying to talk to innd");
2407 unexpected_exitstatus:
2408 report_child_status("inndcomm child", status);
2412 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2413 return OOP_CONTINUE;
2416 static void inndcommfail(const char *what) {
2417 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2418 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2421 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2424 notice("flushing %s",why);
2426 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2427 assert(!inndcomm_child);
2428 assert(!inndcomm_sentinel_fd);
2430 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2432 inndcomm_child= xfork("inndcomm child");
2434 if (!inndcomm_child) {
2435 const char *flushargv[2]= { sitename, 0 };
2439 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2440 /* parent spots the autoclose of pipefds[1] when we die or exit */
2442 alarm(inndcomm_flush_timeout);
2443 r= ICCopen(); if (r) inndcommfail("connect");
2444 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2445 if (!r) exit(0); /* yay! */
2447 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2448 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2449 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2452 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2453 inndcomm_sentinel_fd= pipefds[0];
2454 assert(inndcomm_sentinel_fd);
2455 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2457 SMS(FLUSHING, 0, why);
2460 /*========== main program ==========*/
2462 static void postfork_inputfile(InputFile *ipf) {
2464 xclose(ipf->fd, "(in child) input file ", ipf->path);
2467 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2468 /* we have no stdio streams that are buffered long-term */
2470 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2473 static void postfork(void) {
2474 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2475 sysdie("(in child) failed to reset SIGPIPE");
2477 postfork_inputfile(main_input_file);
2478 postfork_inputfile(flushing_input_file);
2481 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2482 conn_closefd(conn,"(in child) ");
2484 postfork_stdio(defer, "defer file ", path_defer);
2487 #define EVERY(what, interval_sec, interval_usec, body) \
2488 static struct timeval what##_timeout = { interval_sec, interval_usec }; \
2489 static void what##_schedule(void); \
2490 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2492 what##_schedule(); \
2493 return OOP_CONTINUE; \
2495 static void what##_schedule(void) { \
2496 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2499 EVERY(filepoll, 5,0, ({
2500 if (main_input_file && main_input_file->readable_callback)
2501 filemon_callback(main_input_file);
2504 static char *debug_report_ipf(InputFile *ipf) {
2505 if (!ipf) return xasprintf("-");
2507 const char *slash= strrchr(ipf->path,'/');
2508 const char *path= slash ? slash+1 : ipf->path;
2510 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2512 ipf->inprogress, (long)ipf->offset,
2513 ipf->fd, ipf->rd ? "+" : "");
2516 EVERY(period, -1,0, ({
2517 char *dipf_main= debug_report_ipf(main_input_file);
2518 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2519 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2522 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2523 " input_files main:%s old:%s flushing:%s"
2524 " children connecting=%ld inndcomm_child=%ld"
2526 sms_names[sms], sm_period_counter,
2527 conns.count, queue.count, until_connect,
2528 dipf_main, dipf_flushing, dipf_backlog,
2529 (long)connecting_child, (long)inndcomm_child
2533 free(dipf_flushing);
2536 if (until_connect) until_connect--;
2538 poll_backlog_file();
2539 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2540 statemc_period_poll();
2541 check_assign_articles();
2546 /*========== option parsing ==========*/
2548 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2549 static void vbadusage(const char *fmt, va_list al) {
2550 char *m= xvasprintf(fmt,al);
2551 fprintf(stderr, "bad usage: %s\n"
2552 "say --help for help, or read the manpage\n",
2555 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2559 /*---------- generic option parser ----------*/
2561 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2562 static void badusage(const char *fmt, ...) {
2569 of_seconds= 001000u,
2570 of_boolean= 002000u,
2573 typedef struct Option Option;
2574 typedef void OptionParser(const Option*, const char *val);
2578 const char *lng, *formarg;
2584 static void parse_options(const Option *options, char ***argvp) {
2585 /* on return *argvp is first non-option arg; argc is not updated */
2588 const char *arg= *++(*argvp);
2590 if (*arg != '-') break;
2591 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2593 while ((a= *++arg)) {
2597 char *equals= strchr(arg,'=');
2598 int len= equals ? (equals - arg) : strlen(arg);
2599 for (o=options; o->shrt || o->lng; o++)
2600 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2602 badusage("unknown long option --%s",arg);
2605 if (equals) badusage("option --%s does not take a value",o->lng);
2607 } else if (equals) {
2611 if (!arg) badusage("option --%s needs a value for %s",
2612 o->lng, o->formarg);
2615 break; /* eaten the whole argument now */
2617 for (o=options; o->shrt || o->lng; o++)
2620 badusage("unknown short option -%c",a);
2627 if (!arg) badusage("option -%c needs a value for %s",
2628 o->shrt, o->formarg);
2631 break; /* eaten the whole argument now */
2637 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
2639 static void print_options(const Option *options, FILE *f) {
2641 for (o=options; o->shrt || o->lng; o++) {
2642 char shrt[2] = { o->shrt, 0 };
2643 char *optspec= xasprintf("%s%s%s%s%s",
2644 o->shrt ? "-" : "", shrt,
2645 o->shrt && o->lng ? "|" : "",
2646 DELIMPERHAPS("--", o->lng));
2647 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
2652 /*---------- specific option types ----------*/
2654 static void op_integer(const Option *o, const char *val) {
2657 unsigned long ul= strtoul(val,&ep,10);
2658 if (*ep || ep==val || errno || ul>INT_MAX)
2659 badusage("bad integer value for %s",o->lng);
2660 int *store= o->store;
2664 static void op_double(const Option *o, const char *val) {
2665 int *store= o->store;
2668 *store= strtod(val, &ep);
2669 if (*ep || ep==val || errno)
2670 badusage("bad floating point value for %s",o->lng);
2673 static void op_string(const Option *o, const char *val) {
2674 const char **store= o->store;
2678 static void op_seconds(const Option *o, const char *val) {
2679 int *store= o->store;
2683 double v= strtod(val,&ep);
2684 if (ep==val) badusage("bad time/duration value for %s",o->lng);
2686 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
2687 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
2688 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
2689 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
2690 else if (!strcmp(ep,"das")) unit= 10;
2691 else if (!strcmp(ep,"hs")) unit= 100;
2692 else if (!strcmp(ep,"ks")) unit= 1000;
2693 else if (!strcmp(ep,"Ms")) unit= 1000000;
2694 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2698 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2702 static void op_setint(const Option *o, const char *val) {
2703 int *store= o->store;
2707 /*---------- specific options ----------*/
2709 static void help(const Option *o, const char *val);
2711 static const Option innduct_options[]= {
2712 {'f',"feedfile", "F", &feedfile, op_string },
2713 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
2714 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
2715 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
2716 {0,"inndconf", "F", &inndconffile, op_string },
2717 {'P',"port", "PORT", &port, op_integer },
2718 {0,"help", 0, 0, help },
2720 {0,"max-connections", "N", &max_connections, op_integer },
2721 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
2722 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
2723 {0,"period-interval", "TIME", &period_seconds, op_seconds },
2725 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
2726 {0,"stuck-flush-timeout","TIME", &inndcomm_flush_timeout, op_seconds },
2728 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
2729 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
2731 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
2732 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
2733 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
2734 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
2735 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
2736 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
2738 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
2739 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
2744 static void printusage(FILE *f) {
2745 fputs("usage: innduct [options] site [fqdn]\n"
2746 "available options are:\n", f);
2747 print_options(innduct_options, f);
2750 static void help(const Option *o, const char *val) {
2752 if (ferror(stdout) || fflush(stdout)) {
2753 perror("innduct: writing help");
2759 static void convert_to_periods_rndup(int *store) {
2760 *store += period_seconds-1;
2761 *store /= period_seconds;
2764 int main(int argc, char **argv) {
2770 parse_options(innduct_options, &argv);
2775 if (!sitename) badusage("need site name argument");
2776 remote_host= *argv++;
2777 if (*argv) badusage("too many non-option arguments");
2781 if (!remote_host) remote_host= sitename;
2783 if (nocheck_thresh < 0 || nocheck_thresh > 100)
2784 badusage("nocheck threshold percentage must be between 0..100");
2785 nocheck_thresh *= 0.01;
2787 if (nocheck_decay < 0.1)
2788 badusage("nocheck decay articles must be at least 0.1");
2789 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
2791 convert_to_periods_rndup(&reconnect_delay_periods);
2792 convert_to_periods_rndup(&flushfail_retry_periods);
2793 convert_to_periods_rndup(&backlog_retry_minperiods);
2794 convert_to_periods_rndup(&backlog_spontrescan_periods);
2795 convert_to_periods_rndup(&spontaneous_flush_periods);
2796 convert_to_periods_rndup(&need_activity_periods);
2798 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
2799 badusage("bad input data ratio must be between 0..100");
2800 max_bad_data_ratio *= 0.01;
2803 innconf_read(inndconffile);
2804 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
2805 } else if (!feedfile[0]) {
2806 badusage("feed filename must be nonempty");
2807 } else if (feedfile[strlen(feedfile)-1]=='/') {
2808 feedfile= xasprintf("%s%s",feedfile,sitename);
2811 const char *feedfile_forbidden= "?*[~#";
2813 while ((c= *feedfile_forbidden++))
2814 if (strchr(feedfile, c))
2815 badusage("feed filename may not contain metacharacter %c",c);
2819 oop_source_sys *sysloop= oop_sys_new();
2820 if (!sysloop) sysdie("could not create liboop event loop");
2821 loop= (oop_source*)sysloop;
2823 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2824 sysdie("could not ignore SIGPIPE");
2829 if (become_daemon) {
2831 for (i=3; i<255; i++)
2832 /* do this now before we open syslog, etc. */
2834 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2836 int null= open("/dev/null",O_RDWR);
2837 if (null<0) sysfatal("failed to open /dev/null");
2841 xclose(null, "/dev/null original fd",0);
2843 pid_t child1= xfork("daemonise first fork");
2844 if (child1) _exit(0);
2846 pid_t sid= setsid();
2847 if (sid != child1) sysfatal("setsid failed");
2849 pid_t child2= xfork("daemonise second fork");
2850 if (child2) _exit(0);
2855 if (!filemon_method_init()) {
2856 warn("no file monitoring available, polling");
2857 filepoll_schedule();
2860 period_timeout.tv_sec= period_seconds;
2867 void *r= oop_sys_run(sysloop);
2868 assert(r == OOP_ERROR);
2869 sysdie("event loop failed");