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 /*----- configuration options -----*/
311 static const char *sitename, *feedfile, *pathoutgoing;
312 static const char *remote_host;
313 static int quiet_multiple=0, become_daemon=1;
315 static int max_connections=10, max_queue_per_conn=200;
316 static int target_max_feedfile_size=100000;
318 static int period_seconds=60;
320 static double max_bad_data_ratio= 0.01;
321 static int max_bad_data_initial= 30;
322 /* in one corrupt 4096-byte block the number of newlines has
323 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
325 static int connection_setup_timeout=200, port=119, try_stream=1;
326 static int inndcomm_flush_timeout=100;
327 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
328 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
329 static int spontaneous_flush_periods, need_activity_periods;
330 static const char *inndconffile;
332 static double nocheck_thresh_pct= 95.0;
333 static double nocheck_thresh; /* computed in main from _pct */
334 static double nocheck_decay_articles= 100; /* converted to _decay */
335 static double nocheck_decay; /* computed in main from _articles */
338 /*----- statistics -----*/
340 typedef enum { /* in queue in conn->sent */
341 art_Unchecked, /* not checked, not sent checking */
342 art_Wanted, /* checked, wanted sent body as requested */
343 art_Unsolicited, /* - sent body without check */
347 #define RESULT_COUNTS(RCS,RCN) \
355 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
356 #define RCI_TRIPLE_VALS_BASE(counts,x) \
357 counts[art_Unchecked] x \
358 + counts[art_Wanted] x \
359 + counts[art_Unsolicited] x, \
360 counts[art_Unchecked] x \
361 , counts[art_Wanted] x \
362 , counts[art_Unsolicited] x
365 #define RC_INDEX(x) RC_##x,
366 RESULT_COUNTS(RC_INDEX, RC_INDEX)
371 /*----- transmission buffers -----*/
376 xk_Malloc, xk_Const, xk_Artdata
388 /*----- core operational data structure types -----*/
391 /* This is also an instance of struct oop_readable */
392 struct oop_readable readable; /* first */
393 oop_readable_call *readable_callback;
394 void *readable_callback_user;
397 Filemon_Perfile *filemon;
399 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
400 long inprogress; /* no. of articles read but not processed */
404 int counts[art_MaxState][RCI_max];
405 int readcount_ok, readcount_blank, readcount_err;
420 #define SMS_LIST(X) \
428 enum StateMachineState {
429 #define SMS_DEF_ENUM(s) sm_##s,
430 SMS_LIST(SMS_DEF_ENUM)
433 static const char *sms_names[]= {
434 #define SMS_DEF_NAME(s) #s ,
435 SMS_LIST(SMS_DEF_NAME)
441 int fd; /* may be 0, meaning closed (during construction/destruction) */
442 int max_queue, stream, quitting;
443 int since_activity; /* periods */
444 ArticleList waiting; /* not yet told peer */
445 ArticleList priority; /* peer says send it now */
446 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
447 struct iovec xmit[CONNIOVS];
448 XmitDetails xmitd[CONNIOVS];
453 /*----- general operational variables -----*/
455 /* main initialises */
456 static oop_source *loop;
457 static ConnList conns;
458 static ArticleList queue;
459 static char *path_lock, *path_flushing, *path_defer, *globpat_backlog;
461 /* statemc_init initialises */
462 static StateMachineState sms;
464 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
465 static int sm_period_counter;
467 /* initialisation to 0 is good */
468 static int until_connect, until_backlog_nextscan;
469 static double accept_proportion;
470 static int nocheck, nocheck_reported;
472 /*========== logging ==========*/
474 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
475 static void logcore(int sysloglevel, const char *fmt, ...) {
478 vsyslog(sysloglevel,fmt,al);
480 vfprintf(stderr,fmt,al);
486 static void logv(int sysloglevel, const char *pfx, int errnoval,
487 const char *fmt, va_list al) PRINTF(5,0);
488 static void logv(int sysloglevel, const char *pfx, int errnoval,
489 const char *fmt, va_list al) {
490 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
491 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
492 msgbuf[sizeof(msgbuf)-1]= 0;
494 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
495 sysloglevel= LOG_ERR; /* run by wrong user, probably */
497 logcore(sysloglevel, "<%s>%s: %s%s%s",
498 sitename, pfx, msgbuf,
499 errnoval>=0 ? ": " : "",
500 errnoval>=0 ? strerror(errnoval) : "");
503 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
504 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
505 static void fn(const char *fmt, ...) { \
507 logv(sysloglevel, pfx, err, fmt, al); \
511 #define logwrap(fn, pfx, sysloglevel, err) \
512 static void fn(const char *fmt, ...) PRINTF(1,2); \
513 static void fn(const char *fmt, ...) { \
515 logv(sysloglevel, pfx, err, fmt, al); \
519 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
520 diewrap(die, " critical", LOG_CRIT, -1, 16);
522 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
523 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
525 logwrap(syswarn, " warning", LOG_WARNING, errno);
526 logwrap(warn, " warning", LOG_WARNING, -1);
528 logwrap(notice, "", LOG_NOTICE, -1);
529 logwrap(info, " info", LOG_INFO, -1);
530 logwrap(debug, " debug", LOG_DEBUG, -1);
533 /*========== utility functions etc. ==========*/
535 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
536 static char *xvasprintf(const char *fmt, va_list al) {
538 int rc= vasprintf(&str,fmt,al);
539 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
542 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
543 static char *xasprintf(const char *fmt, ...) {
545 char *str= xvasprintf(fmt,al);
550 static int close_perhaps(int *fd) {
556 static void xclose(int fd, const char *what, const char *what2) {
558 if (r) sysdie("close %s%s",what,what2?what2:"");
560 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
562 xclose(*fd,what,what2);
566 static pid_t xfork(const char *what) {
570 if (child==-1) sysdie("cannot fork for %s",what);
571 debug("forked %s %ld", what, (unsigned long)child);
572 if (!child) postfork();
576 static void on_fd_read_except(int fd, oop_call_fd callback) {
577 loop->on_fd(loop, fd, OOP_READ, callback, 0);
578 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
580 static void cancel_fd_read_except(int fd) {
581 loop->cancel_fd(loop, fd, OOP_READ);
582 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
585 static void report_child_status(const char *what, int status) {
586 if (WIFEXITED(status)) {
587 int es= WEXITSTATUS(status);
589 warn("%s: child died with error exit status %d", what, es);
590 } else if (WIFSIGNALED(status)) {
591 int sig= WTERMSIG(status);
592 const char *sigstr= strsignal(sig);
593 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
595 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
597 warn("%s: child died due to unknown fatal signal %d%s",
598 what, sig, coredump);
600 warn("%s: child died with unknown wait status %d", what,status);
604 static int xwaitpid(pid_t *pid, const char *what) {
607 int r= kill(*pid, SIGKILL);
608 if (r) sysdie("cannot kill %s child", what);
610 pid_t got= waitpid(*pid, &status, WNOHANG);
611 if (got==-1) sysdie("cannot reap %s child", what);
618 static void xunlink(const char *path, const char *what) {
620 if (r) sysdie("can't unlink %s %s", path, what);
623 static time_t xtime(void) {
625 if (now==-1) sysdie("time(2) failed");
628 static void check_isreg(const struct stat *stab, const char *path,
630 if (!S_ISREG(stab->st_mode))
631 die("%s %s not a plain file (mode 0%lo)",
632 what, path, (unsigned long)stab->st_mode);
635 static void xfstat(int fd, struct stat *stab_r, const char *what) {
636 int r= fstat(fd, stab_r);
637 if (r) sysdie("could not fstat %s", what);
640 static void xfstat_isreg(int fd, struct stat *stab_r,
641 const char *path, const char *what) {
642 xfstat(fd, stab_r, what);
643 check_isreg(stab_r, path, what);
646 static void xlstat_isreg(const char *path, struct stat *stab,
647 int *enoent_r /* 0 means ENOENT is fatal */,
649 int r= lstat(path, stab);
651 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
652 sysdie("could not lstat %s %s", what, path);
654 if (enoent_r) *enoent_r= 0;
655 check_isreg(stab, path, what);
658 static void setnonblock(int fd, int nonblocking) {
659 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
660 if (nonblocking) r |= O_NONBLOCK;
661 else r &= ~O_NONBLOCK;
662 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
665 static int samefile(const struct stat *a, const struct stat *b) {
666 assert(S_ISREG(a->st_mode));
667 assert(S_ISREG(b->st_mode));
668 return (a->st_ino == b->st_ino &&
669 a->st_dev == b->st_dev);
672 static char *sanitise(const char *input) {
673 static char sanibuf[100]; /* returns pointer to this buffer! */
675 const char *p= input;
679 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
681 if (!c) { *q++= '\''; *q=0; break; }
682 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
683 sprintf(q,"\\x%02x",c);
689 static int isewouldblock(int errnoval) {
690 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
693 /*========== management of connections ==========*/
695 static void conn_closefd(Conn *conn, const char *msgprefix) {
696 int r= close_perhaps(&conn->fd);
697 if (r) info("C%d %serror closing socket: %s",
698 conn->fd, msgprefix, strerror(errno));
701 static void conn_dispose(Conn *conn) {
704 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
705 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
707 conn_closefd(conn,"");
709 until_connect= reconnect_delay_periods;
712 static void *conn_exception(oop_source *lp, int fd,
713 oop_event ev, void *conn_v) {
716 assert(fd == conn->fd);
717 assert(ev == OOP_EXCEPTION);
718 int r= read(conn->fd, &ch, 1);
719 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
720 else connfail(conn,"exceptional condition on socket (peer sent urgent"
721 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
725 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
726 int requeue[art_MaxState];
729 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
730 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
731 while ((art= LIST_REMHEAD(conn->sent))) {
732 requeue[art->state]++;
733 if (art->state==art_Unsolicited) art->state= art_Unchecked;
734 LIST_ADDTAIL(queue,art);
739 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
742 char *m= xvasprintf(fmt,al);
743 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
744 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
747 LIST_REMOVE(conns,conn);
749 check_assign_articles();
752 static void connfail(Conn *conn, const char *fmt, ...) {
755 vconnfail(conn,fmt,al);
759 static void check_idle_conns(void) {
761 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
762 conn->since_activity++;
764 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
765 if (conn->since_activity <= need_activity_periods) continue;
767 /* We need to shut this down */
769 connfail(conn,"timed out waiting for response to QUIT");
770 else if (conn->sent.count)
771 connfail(conn,"timed out waiting for responses");
772 else if (conn->waiting.count || conn->priority.count)
773 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
774 else if (conn->xmitu)
775 connfail(conn,"peer has been sending responses"
776 " before receiving our commands!");
778 static const char quitcmd[]= "QUIT\r\n";
779 int todo= sizeof(quitcmd)-1;
780 const char *p= quitcmd;
782 int r= write(conn->fd, p, todo);
784 if (isewouldblock(errno))
785 connfail(conn, "blocked writing QUIT to idle connection");
787 connfail(conn, "failed to write QUIT to idle connection: %s",
795 conn->since_activity= 0;
796 debug("C%d is idle, quitting", conn->fd);
805 /*---------- making new connections ----------*/
807 static pid_t connecting_child;
808 static int connecting_fdpass_sock;
810 static void connect_attempt_discard(void) {
811 if (connecting_child) {
812 int r= kill(connecting_child, SIGTERM);
813 if (r) syswarn("failed to kill connecting child");
814 int status= xwaitpid(&connecting_child, "connect");
816 if (!(WIFEXITED(status) ||
817 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
818 report_child_status("connect", status);
820 if (connecting_fdpass_sock) {
821 cancel_fd_read_except(connecting_fdpass_sock);
822 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
826 #define PREP_DECL_MSG_CMSG(msg) \
828 memset(&msg,0,sizeof(msg)); \
829 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
830 msg.msg_control= msg##cbuf; \
831 msg.msg_controllen= sizeof(msg##cbuf);
833 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
836 assert(fd == connecting_fdpass_sock);
838 conn= xmalloc(sizeof(*conn));
839 memset(conn,0,sizeof(*conn));
841 PREP_DECL_MSG_CMSG(msg);
842 struct cmsghdr *h= 0;
843 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
844 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
847 pid_t got= waitpid(connecting_child, &status, WNOHANG);
849 assert(got==connecting_child);
851 if (WIFEXITED(status)) {
852 if (WEXITSTATUS(status) != 0 &&
853 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
854 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
855 /* child already reported the problem */;
857 warn("connect: connection child exited code %d but no cmsg",
858 WEXITSTATUS(status));
859 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
860 warn("connect: connection attempt timed out");
862 report_child_status("connect", status);
865 /* child is still running apparently, report the socket problem */
867 syswarn("connect: read from fdpass socket failed");
868 else if (e == OOP_EXCEPTION)
869 warn("connect: unexpected exception on fdpass socket");
871 warn("connect: unexpected EOF on fdpass socket");
873 fatal("connect: unexpected lack of cmsg from child");
878 #define CHK(field, val) \
879 if (h->cmsg_##field != val) { \
880 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
883 CHK(level, SOL_SOCKET);
884 CHK(type, SCM_RIGHTS);
885 CHK(len, CMSG_LEN(sizeof(conn->fd)));
888 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
890 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
891 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
894 pid_t got= waitpid(connecting_child, &status, 0);
895 if (got==-1) sysdie("connect: real wait for child");
896 assert(got == connecting_child);
899 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
900 int es= WEXITSTATUS(status);
902 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
903 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
905 fatal("connect: child gave unexpected exit status %d", es);
909 LIST_INIT(conn->waiting);
910 LIST_INIT(conn->priority);
911 LIST_INIT(conn->sent);
912 setnonblock(conn->fd, 1);
913 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
914 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
915 LIST_ADDHEAD(conns, conn);
917 connect_attempt_discard();
918 check_assign_articles();
923 connect_attempt_discard();
926 static int allow_connect_start(void) {
927 return conns.count < max_connections
932 static void connect_start(void) {
933 assert(!connecting_child);
934 assert(!connecting_fdpass_sock);
936 notice("starting connection attempt");
939 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
940 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
942 connecting_child= xfork("connection");
944 if (!connecting_child) {
945 FILE *cn_from, *cn_to;
946 char buf[NNTP_STRLEN+100];
947 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
949 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
951 alarm(connection_setup_timeout);
952 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
953 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
954 else sysfatal("connect: connection attempt failed");
956 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
957 sysfatal("connect: authentication failed");
959 if (fputs("MODE STREAM\r\n", cn_to) ||
961 sysfatal("connect: could not send MODE STREAM");
962 buf[sizeof(buf)-1]= 0;
963 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
965 sysfatal("connect: could not read response to MODE STREAM");
967 fatal("connect: connection close in response to MODE STREAM");
972 fatal("connect: response to MODE STREAM is too long: %.100s...",
973 remote_host, sanitise(buf));
974 l--; if (l>0 && buf[l-1]=='\r') l--;
977 int rcode= strtoul(buf,&ep,10);
979 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
983 exitstatus= CONNCHILD_ESTATUS_STREAM;
989 warn("connect: unexpected response to MODE STREAM: %.50s",
995 int fd= fileno(cn_from);
997 PREP_DECL_MSG_CMSG(msg);
998 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
999 cmsg->cmsg_level= SOL_SOCKET;
1000 cmsg->cmsg_type= SCM_RIGHTS;
1001 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1002 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1004 msg.msg_controllen= cmsg->cmsg_len;
1005 r= sendmsg(socks[1], &msg, 0);
1006 if (r) sysdie("sendmsg failed for new connection");
1011 xclose(socks[1], "connecting fdpass child's socket",0);
1012 connecting_fdpass_sock= socks[0];
1013 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1016 /*---------- assigning articles to conns, and transmitting ----------*/
1018 static void check_assign_articles(void) {
1026 /* Find a connection to offer this article. We prefer a busy
1027 * connection to an idle one, provided it's not full. We take the
1028 * first (oldest) and since that's stable, it will mean we fill up
1029 * connections in order. That way if we have too many
1030 * connections, the spare ones will go away eventually.
1032 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1033 if (walk->quitting) continue;
1034 inqueue= walk->sent.count + walk->priority.count
1035 + walk->waiting.count;
1036 spare= walk->max_queue - inqueue;
1037 assert(inqueue <= max_queue_per_conn);
1039 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1040 else if (spare>0) /*working*/ { use= walk; break; }
1043 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1045 Article *art= LIST_REMHEAD(queue);
1046 LIST_ADDTAIL(use->waiting, art);
1049 conn_maybe_write(use);
1050 } else if (allow_connect_start()) {
1051 until_connect= reconnect_delay_periods;
1060 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1061 conn_maybe_write(u);
1062 return OOP_CONTINUE;
1065 static void conn_maybe_write(Conn *conn) {
1068 conn_make_some_xmits(conn);
1070 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1074 void *rp= conn_write_some_xmits(conn);
1075 if (rp==OOP_CONTINUE) {
1076 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1078 } else if (rp==OOP_HALT) {
1081 /* transmitted everything */
1088 /*========== article transmission ==========*/
1090 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1091 XmitKind kind) { /* caller must then fill in details */
1092 struct iovec *v= &conn->xmit[conn->xmitu];
1093 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1094 v->iov_base= (char*)data;
1100 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1101 xmit_core(conn,data,len, xk_Const);
1103 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1105 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1106 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1110 static void xmit_free(XmitDetails *d) {
1112 case xk_Malloc: free(d->info.malloc_tofree); break;
1113 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1114 case xk_Const: break;
1119 static void *conn_write_some_xmits(Conn *conn) {
1121 * 0: nothing more to write, no need to call us again
1122 * OOP_CONTINUE: more to write but fd not writeable
1123 * OOP_HALT: disaster, have destroyed conn
1126 int count= conn->xmitu;
1127 if (!count) return 0;
1129 if (count > IOV_MAX) count= IOV_MAX;
1130 ssize_t rs= writev(conn->fd, conn->xmit, count);
1132 if (isewouldblock(errno)) return OOP_CONTINUE;
1133 connfail(conn, "write failed: %s", strerror(errno));
1139 for (done=0; rs && done<conn->xmitu; done++) {
1140 struct iovec *vp= &conn->xmit[done];
1141 XmitDetails *dp= &conn->xmitd[done];
1142 if (rs > vp->iov_len) {
1150 int newu= conn->xmitu - done;
1151 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1152 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1157 static void conn_make_some_xmits(Conn *conn) {
1159 if (conn->xmitu+5 > CONNIOVS)
1162 Article *art= LIST_REMHEAD(conn->priority);
1163 if (!art) art= LIST_REMHEAD(conn->waiting);
1166 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1167 /* actually send it */
1169 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1173 XMIT_LITERAL("TAKETHIS ");
1174 xmit_noalloc(conn, art->messageid, art->midlen);
1175 XMIT_LITERAL("\r\n");
1176 xmit_artbody(conn, artdata);
1179 /* we got 235 from IHAVE */
1181 xmit_artbody(conn, artdata);
1183 XMIT_LITERAL(".\r\n");
1188 art->state == art_Unchecked ? art_Unsolicited :
1189 art->state == art_Wanted ? art_Wanted :
1191 art->ipf->counts[art->state][RC_sent]++;
1192 LIST_ADDTAIL(conn->sent, art);
1198 XMIT_LITERAL("IHAVE ");
1200 XMIT_LITERAL("CHECK ");
1201 xmit_noalloc(conn, art->messageid, art->midlen);
1202 XMIT_LITERAL("\r\n");
1204 assert(art->state == art_Unchecked);
1205 art->ipf->counts[art->state][RC_sent]++;
1206 LIST_ADDTAIL(conn->sent, art);
1212 /*========== handling responses from peer ==========*/
1214 static const oop_rd_style peer_rd_style= {
1215 OOP_RD_DELIM_STRIP, '\n',
1217 OOP_RD_SHORTREC_FORBID
1220 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1221 const char *errmsg, int errnoval,
1222 const char *data, size_t recsz, void *conn_v) {
1224 connfail(conn, "error receiving from peer: %s", errmsg);
1225 return OOP_CONTINUE;
1228 static Article *article_reply_check(Conn *conn, const char *response,
1229 int code_indicates_streaming,
1231 /* 1:yes, -1:no, 0:dontcare */,
1232 const char *sanitised_response) {
1233 Article *art= LIST_HEAD(conn->sent);
1237 "peer gave unexpected response when no commands outstanding: %s",
1238 sanitised_response);
1242 if (code_indicates_streaming) {
1243 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1244 if (!conn->stream) {
1245 connfail(conn, "peer gave streaming response code "
1246 " to IHAVE or subsequent body: %s", sanitised_response);
1249 const char *got_mid= response+4;
1250 int got_midlen= strcspn(got_mid, " \n\r");
1251 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1252 connfail(conn, "peer gave streaming response with syntactically invalid"
1253 " messageid: %s", sanitised_response);
1256 if (got_midlen != art->midlen ||
1257 memcmp(got_mid, art->messageid, got_midlen)) {
1258 connfail(conn, "peer gave streaming response code to wrong article -"
1259 " probable synchronisation problem; we offered: %s;"
1261 art->messageid, sanitised_response);
1266 connfail(conn, "peer gave non-streaming response code to"
1267 " CHECK/TAKETHIS: %s", sanitised_response);
1272 if (must_have_sent>0 && art->state < art_Wanted) {
1273 connfail(conn, "peer says article accepted but"
1274 " we had not sent the body: %s", sanitised_response);
1277 if (must_have_sent<0 && art->state >= art_Wanted) {
1278 connfail(conn, "peer says please sent the article but we just did: %s",
1279 sanitised_response);
1283 Article *art_again= LIST_REMHEAD(conn->sent);
1284 assert(art_again == art);
1288 static void update_nocheck(int accepted) {
1289 accept_proportion *= nocheck_decay;
1290 accept_proportion += accepted * (1.0 - nocheck_decay);
1291 int new_nocheck= accept_proportion >= nocheck_thresh;
1292 if (new_nocheck && !nocheck_reported) {
1293 notice("entering nocheck mode for the first time");
1294 nocheck_reported= 1;
1295 } else if (new_nocheck != nocheck) {
1296 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1298 nocheck= new_nocheck;
1301 static void article_done(Conn *conn, Article *art, int whichcount) {
1302 art->ipf->counts[art->state][whichcount]++;
1303 if (whichcount == RC_accepted) update_nocheck(1);
1304 else if (whichcount == RC_unwanted) update_nocheck(0);
1306 InputFile *ipf= art->ipf;
1308 while (art->blanklen) {
1309 static const char spaces[]=
1314 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1315 int r= pwrite(ipf->fd, spaces, w, art->offset);
1317 if (errno==EINTR) continue;
1318 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1319 art->messageid, art->blanklen, art->offset, ipf->path);
1321 assert(r>=0 && r<=w);
1327 assert(ipf->inprogress >= 0);
1330 if (!ipf->inprogress && ipf != main_input_file)
1331 queue_check_input_done();
1334 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1335 const char *errmsg, int errnoval,
1336 const char *data, size_t recsz, void *conn_v) {
1339 if (ev == OOP_RD_EOF) {
1340 connfail(conn, "unexpected EOF from peer");
1341 return OOP_CONTINUE;
1343 assert(ev == OOP_RD_OK);
1345 char *sani= sanitise(data);
1348 unsigned long code= strtoul(data, &ep, 10);
1349 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1350 connfail(conn, "badly formatted response from peer: %s", sani);
1351 return OOP_CONTINUE;
1354 if (conn->quitting) {
1355 if (code!=205 && code!=503) {
1356 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1358 notice("C%d idle connection closed", conn->fd);
1359 assert(!conn->waiting.count);
1360 assert(!conn->priority.count);
1361 assert(!conn->sent.count);
1362 assert(!conn->xmitu);
1363 LIST_REMOVE(conns,conn);
1366 return OOP_CONTINUE;
1369 conn->since_activity= 0;
1372 #define GET_ARTICLE(musthavesent) \
1373 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1374 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1376 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1377 code_streaming= (streaming); \
1378 GET_ARTICLE(musthavesent); \
1379 article_done(conn, art, RC_##how); break;
1381 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1383 int code_streaming= 0;
1387 case 400: PEERBADMSG("peer stopped accepting articles");
1388 case 503: PEERBADMSG("peer timed us out");
1389 default: PEERBADMSG("peer sent unexpected message");
1391 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1392 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1394 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1395 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1397 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1398 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1400 case 238: /* CHECK says send it */
1402 case 335: /* IHAVE says send it */
1404 assert(art->state == art_Unchecked);
1405 art->ipf->counts[art->state][RC_accepted]++;
1406 art->state= art_Wanted;
1407 LIST_ADDTAIL(conn->priority, art);
1410 case 431: /* CHECK or TAKETHIS says try later */
1412 case 436: /* IHAVE says try later */
1415 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1417 sysfatal("write to defer file %s",path_defer);
1418 article_done(conn, art, RC_deferred);
1423 conn_maybe_write(conn);
1424 check_assign_articles();
1425 return OOP_CONTINUE;
1429 /*========== monitoring of input files ==========*/
1431 static void feedfile_eof(InputFile *ipf) {
1432 assert(ipf != main_input_file); /* promised by tailing_try_read */
1433 inputfile_reading_stop(ipf);
1435 if (ipf == flushing_input_file) {
1436 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1437 if (main_input_file) inputfile_reading_start(main_input_file);
1438 statemc_check_flushing_done();
1439 } else if (ipf == backlog_input_file) {
1440 statemc_check_backlog_done();
1442 abort(); /* supposed to wait rather than get EOF on main input file */
1446 static InputFile *open_input_file(const char *path) {
1447 int fd= open(path, O_RDONLY);
1449 if (errno==ENOENT) return 0;
1450 sysfatal("unable to open input file %s", path);
1454 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1455 memset(ipf,0,sizeof(*ipf));
1458 strcpy(ipf->path, path);
1463 static void close_input_file(InputFile *ipf) { /* does not free */
1464 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1465 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1466 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1467 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1468 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1472 /*---------- dealing with articles read in the input file ----------*/
1474 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1475 const char *data, const char *how) {
1476 warn("corrupted file: %s, offset %lu: %s: %s",
1477 ipf->path, (unsigned long)offset, how, sanitise(data));
1478 ipf->readcount_err++;
1479 if (ipf->readcount_err > max_bad_data_initial +
1480 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1481 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1482 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1483 return OOP_CONTINUE;
1486 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1487 oop_rd_event ev, const char *errmsg,
1488 int errnoval, const char *data, size_t recsz,
1490 InputFile *ipf= ipf_v;
1491 assert(ev == OOP_RD_SYSTEM);
1493 sysdie("error reading input file: %s, offset %lu",
1494 ipf->path, (unsigned long)ipf->offset);
1497 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1498 oop_rd_event ev, const char *errmsg,
1499 int errnoval, const char *data, size_t recsz,
1501 InputFile *ipf= ipf_v;
1503 char tokentextbuf[sizeof(TOKEN)*2+3];
1505 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1507 off_t old_offset= ipf->offset;
1508 ipf->offset += recsz + 1;
1510 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1512 if (ev==OOP_RD_PARTREC)
1513 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1514 /* but process it anyway */
1516 if (ipf->skippinglong) {
1517 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1520 if (ev==OOP_RD_LONG) {
1521 ipf->skippinglong= 1;
1522 X_BAD_DATA("overly long line");
1525 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1526 if (!recsz) X_BAD_DATA("empty line");
1529 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1530 ipf->readcount_blank++;
1531 return OOP_CONTINUE;
1534 char *space= strchr(data,' ');
1535 int tokenlen= space-data;
1536 int midlen= (int)recsz-tokenlen-1;
1537 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1538 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1540 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1541 memcpy(tokentextbuf, data, tokenlen);
1542 tokentextbuf[tokenlen]= 0;
1543 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1545 ipf->readcount_ok++;
1547 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1548 art->state= art_Unchecked;
1549 art->midlen= midlen;
1550 art->ipf= ipf; ipf->inprogress++;
1551 art->token= TextToToken(tokentextbuf);
1552 art->offset= ipf->offset;
1553 art->blanklen= recsz;
1554 strcpy(art->messageid, space+1);
1555 LIST_ADDTAIL(queue, art);
1557 if (sms==sm_NORMAL && ipf==main_input_file &&
1558 ipf->offset >= target_max_feedfile_size)
1559 statemc_start_flush("feed file size");
1561 check_assign_articles();
1562 return OOP_CONTINUE;
1565 /*========== tailing input file ==========*/
1567 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1569 InputFile *ipf= user;
1570 return ipf->readable_callback(loop, &ipf->readable,
1571 ipf->readable_callback_user);
1574 static void tailing_on_cancel(struct oop_readable *rable) {
1575 InputFile *ipf= (void*)rable;
1577 if (ipf->filemon) filemon_stop(ipf);
1578 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1579 ipf->readable_callback= 0;
1582 static void tailing_queue_readable(InputFile *ipf) {
1583 /* lifetime of ipf here is OK because destruction will cause
1584 * on_cancel which will cancel this callback */
1585 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1588 static int tailing_on_readable(struct oop_readable *rable,
1589 oop_readable_call *cb, void *user) {
1590 InputFile *ipf= (void*)rable;
1592 tailing_on_cancel(rable);
1593 ipf->readable_callback= cb;
1594 ipf->readable_callback_user= user;
1597 tailing_queue_readable(ipf);
1601 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1603 InputFile *ipf= (void*)rable;
1605 ssize_t r= read(ipf->fd, buffer, length);
1607 if (errno==EINTR) continue;
1611 if (ipf==main_input_file) {
1614 } else if (ipf==flushing_input_file) {
1616 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1617 } else if (ipf==backlog_input_file) {
1627 /*---------- filemon implemented with inotify ----------*/
1629 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1630 #define HAVE_FILEMON
1632 #include <linux/inotify.h>
1634 static int filemon_inotify_fd;
1635 static int filemon_inotify_wdmax;
1636 static InputFile **filemon_inotify_wd2ipf;
1638 struct Filemon_Perfile {
1642 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1643 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1644 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1646 if (wd >= filemon_inotify_wdmax) {
1648 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1649 sizeof(*filemon_inotify_wd2ipf) * newmax);
1650 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1651 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1652 filemon_inotify_wdmax= newmax;
1655 assert(!filemon_inotify_wd2ipf[wd]);
1656 filemon_inotify_wd2ipf[wd]= ipf;
1658 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1659 ipf, wd, filemon_inotify_wdmax);
1664 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1666 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1667 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1668 if (r) sysdie("inotify_rm_watch");
1669 filemon_inotify_wd2ipf[wd]= 0;
1672 static void *filemon_inotify_readable(oop_source *lp, int fd,
1673 oop_event e, void *u) {
1674 struct inotify_event iev;
1676 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1678 if (isewouldblock(errno)) break;
1679 sysdie("read from inotify master");
1680 } else if (r==sizeof(iev)) {
1681 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1683 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1685 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1686 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1687 filemon_callback(ipf);
1689 return OOP_CONTINUE;
1692 static int filemon_method_init(void) {
1693 filemon_inotify_fd= inotify_init();
1694 if (filemon_inotify_fd<0) {
1695 syswarn("could not initialise inotify: inotify_init failed");
1699 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1701 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1705 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1707 /*---------- filemon dummy implementation ----------*/
1709 #if !defined(HAVE_FILEMON)
1711 struct Filemon_Perfile { int dummy; };
1713 static int filemon_method_init(void) { return 0; }
1714 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1715 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1717 #endif /* !HAVE_FILEMON */
1719 /*---------- filemon generic interface ----------*/
1721 static void filemon_start(InputFile *ipf) {
1722 assert(!ipf->filemon);
1724 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1725 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1726 filemon_method_startfile(ipf, ipf->filemon);
1729 static void filemon_stop(InputFile *ipf) {
1730 if (!ipf->filemon) return;
1731 filemon_method_stopfile(ipf, ipf->filemon);
1736 static void filemon_callback(InputFile *ipf) {
1737 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1740 /*---------- interface to start and stop an input file ----------*/
1742 static const oop_rd_style feedfile_rdstyle= {
1743 OOP_RD_DELIM_STRIP, '\n',
1745 OOP_RD_SHORTREC_LONG,
1748 static void inputfile_reading_start(InputFile *ipf) {
1750 ipf->readable.on_readable= tailing_on_readable;
1751 ipf->readable.on_cancel= tailing_on_cancel;
1752 ipf->readable.try_read= tailing_try_read;
1753 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1754 ipf->readable.delete_kill= 0;
1756 ipf->readable_callback= 0;
1757 ipf->readable_callback_user= 0;
1759 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1762 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1763 feedfile_got_article,ipf, feedfile_read_err, ipf);
1764 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1767 static void inputfile_reading_stop(InputFile *ipf) {
1769 oop_rd_cancel(ipf->rd);
1770 oop_rd_delete(ipf->rd);
1772 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1776 /*========== interaction with innd - state machine ==========*/
1778 /* See official state diagram at top of file. We implement
1789 |`---------------------------------------------------.
1791 |`---------------- - - - |
1792 D ENOENT | D EXISTS see OVERALL STATES diagram |
1793 | for full startup logic |
1796 | ============ try to |
1802 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1803 ^ | hardlink F to D |
1806 | | our handle onto F is now onto D |
1809 | |<-------------------<---------------------<---------+
1811 | | spawn inndcomm flush |
1813 | ================== |
1814 | FLUSHING[-ABSENT] |
1816 | main D tail/none |
1817 | ================== |
1819 | | INNDCOMM FLUSH FAILS ^
1820 | |`----------------------->----------. |
1822 | | NO SUCH SITE V |
1823 ^ |`--------------->----. ==================== |
1824 | | \ FLUSHFAILED[-ABSENT] |
1826 | | FLUSH OK \ main D tail/none |
1827 | | open F \ ==================== |
1829 | | \ | TIME TO RETRY |
1830 | |`------->----. ,---<---'\ `----------------'
1831 | | D NONE | | D NONE `----.
1833 | ============= V V ============
1834 | SEPARATED-1 | | DROPPING-1
1835 | flsh->rd!=0 | | flsh->rd!=0
1836 | [Separated] | | [Dropping]
1837 | main F idle | | main none
1838 | old D tail | | old D tail
1839 | ============= | | ============
1841 ^ | EOF ON D | | defer | EOF ON D
1843 | =============== | | ===============
1844 | SEPARATED-2 | | DROPPING-2
1845 | flsh->rd==0 | V flsh->rd==0
1846 | [Finishing] | | [Dropping]
1847 | main F tail | `. main none
1848 | old D closed | `. old D closed
1849 | =============== V `. ===============
1851 | | ALL D PROCESSED `. | ALL D PROCESSED
1852 | V install defer as backlog `. | install defer
1853 ^ | close D `. | close D
1854 | | unlink D `. | unlink D
1857 `----------' ==============
1877 static void startup_set_input_file(InputFile *f) {
1878 assert(!main_input_file);
1880 inputfile_reading_start(f);
1883 static void statemc_init(void) {
1884 struct stat stab, stabf;
1886 path_lock= xasprintf("%s_lock", feedfile);
1887 path_flushing= xasprintf("%s_flushing", feedfile);
1888 path_defer= xasprintf("%s_defer", feedfile);
1889 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1892 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1893 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1896 memset(&fl,0,sizeof(fl));
1898 fl.l_whence= SEEK_SET;
1899 int r= fcntl(lockfd, F_SETLK, &fl);
1901 if (errno==EACCES || isewouldblock(errno)) {
1902 if (quiet_multiple) exit(0);
1903 fatal("another duct holds the lockfile");
1905 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1908 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
1910 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1912 if (!lock_noent && samefile(&stab, &stabf))
1915 xclose(lockfd, "stale lockfile ", path_lock);
1917 debug("startup: locked");
1919 search_backlog_file();
1922 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1924 debug("startup: ductdefer ENOENT");
1926 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1927 switch (stab.st_nlink==1) {
1929 open_defer(); /* so that we will later close it and rename it */
1932 xunlink(path_defer, "stale defer file link"
1933 " (presumably hardlink to backlog file)");
1936 die("defer file %s has unexpected link count %d",
1937 path_defer, stab.st_nlink);
1941 struct stat stab_f, stab_d;
1944 InputFile *file_d= open_input_file(path_flushing);
1945 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
1947 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1949 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1950 debug("startup: F==D => Hardlinked");
1951 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1956 debug("startup: F ENOENT => Moved");
1957 if (file_d) startup_set_input_file(file_d);
1958 spawn_inndcomm_flush("feedfile missing at startup");
1959 /* => Flushing, sms:=FLUSHING */
1962 debug("startup: F!=D => Separated");
1963 startup_set_input_file(file_d);
1964 SMS(SEPARATED, 0, "found both old and current feed files");
1966 debug("startup: F exists, D ENOENT => Normal");
1967 InputFile *file_f= open_input_file(feedfile);
1968 if (!file_f) die("feed file vanished during startup");
1969 startup_set_input_file(file_f);
1970 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1975 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1976 assert(sms == sm_NORMAL);
1978 debug("starting flush (%s) (%lu >?= %lu) (%d)",
1980 (unsigned long)(main_input_file ? main_input_file->offset : 0),
1981 (unsigned long)target_max_feedfile_size,
1984 int r= link(feedfile, path_flushing);
1985 if (r) sysdie("link feedfile %s to flushing file %s",
1986 feedfile, path_flushing);
1989 xunlink(feedfile, "old feedfile link");
1992 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1995 static void statemc_period_poll(void) {
1996 if (!sm_period_counter) return;
1997 sm_period_counter--;
1998 assert(sm_period_counter>=0);
2000 if (sm_period_counter) return;
2003 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2005 case sm_FLUSHFAILED:
2006 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2013 static int inputfile_is_done(InputFile *ipf) {
2015 if (ipf->inprogress) return 0; /* new article in the meantime */
2016 if (ipf->rd) return 0; /* not had EOF */
2020 static void notice_processed(InputFile *ipf, const char *what,
2022 #define RCI_NOTHING(x) /* nothing */
2023 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2024 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2026 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2028 info("processed %s%s read=%d(+%dbl,+%derr)"
2029 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2030 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2033 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2034 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2035 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2036 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2037 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2038 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2044 static void statemc_check_backlog_done(void) {
2045 InputFile *ipf= backlog_input_file;
2046 if (!inputfile_is_done(ipf)) return;
2048 const char *slash= strrchr(ipf->path, '/');
2049 const char *leaf= slash ? slash+1 : ipf->path;
2050 const char *under= strchr(slash, '_');
2051 const char *rest= under ? under+1 : leaf;
2052 if (!strncmp(rest,"backlog",7)) rest += 7;
2053 notice_processed(ipf,"backlog:",rest);
2055 close_input_file(ipf);
2056 if (unlink(ipf->path)) {
2057 if (errno != ENOENT)
2058 sysdie("could not unlink processed backlog file %s", ipf->path);
2059 warn("backlog file %s vanished while we were reading it"
2060 " so we couldn't remove it (but it's done now, anyway)",
2064 backlog_input_file= 0;
2065 search_backlog_file();
2069 static void statemc_check_flushing_done(void) {
2070 InputFile *ipf= flushing_input_file;
2071 if (!inputfile_is_done(ipf)) return;
2073 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2075 notice_processed(ipf,"feedfile",0);
2079 xunlink(path_flushing, "old flushing file");
2081 close_input_file(flushing_input_file);
2082 free(flushing_input_file);
2083 flushing_input_file= 0;
2085 if (sms==sm_SEPARATED) {
2086 notice("flush complete");
2087 SMS(NORMAL, 0, "flush complete");
2088 } else if (sms==sm_DROPPING) {
2089 SMS(DROPPED, 0, "old flush complete");
2090 search_backlog_file();
2091 notice("feed dropped, but will continue until backlog is finished");
2095 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2097 assert(!inputfile_is_done(main_input_file));
2098 statemc_check_flushing_done();
2099 statemc_check_backlog_done();
2100 return OOP_CONTINUE;
2103 static void queue_check_input_done(void) {
2104 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2107 static void statemc_setstate(StateMachineState newsms, int periods,
2108 const char *forlog, const char *why) {
2110 sm_period_counter= periods;
2112 const char *xtra= "";
2114 case sm_FLUSHING: sm_FLUSHFAILED:
2115 if (!main_input_file) xtra= "-ABSENT";
2117 case sm_SEPARATED: case sm_DROPPING:
2118 xtra= flushing_input_file->rd ? "-1" : "-2";
2124 info("%s%s[%d] %s",forlog,xtra,periods,why);
2126 info("%s%s %s",forlog,xtra,why);
2130 /*---------- defer and backlog files ----------*/
2132 static void open_defer(void) {
2137 defer= fopen(path_defer, "a+");
2138 if (!defer) sysfatal("could not open defer file %s", path_defer);
2140 /* truncate away any half-written records */
2142 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2144 if (stab.st_size > LONG_MAX)
2145 die("defer file %s size is far too large", path_defer);
2150 long orgsize= stab.st_size;
2151 long truncto= stab.st_size;
2153 if (!truncto) break; /* was only (if anything) one half-truncated record */
2154 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2155 sysdie("seek in defer file %s while truncating partial", path_defer);
2160 sysdie("failed read from defer file %s", path_defer);
2162 die("defer file %s shrank while we were checking it!", path_defer);
2168 if (stab.st_size != truncto) {
2169 warn("truncating half-record at end of defer file %s -"
2170 " shrinking by %ld bytes from %ld to %ld",
2171 path_defer, orgsize - truncto, orgsize, truncto);
2174 sysfatal("could not flush defer file %s", path_defer);
2175 if (ftruncate(fileno(defer), truncto))
2176 sysdie("could not truncate defer file %s", path_defer);
2179 info("continuing existing defer file %s (%ld bytes)",
2180 path_defer, orgsize);
2182 if (fseek(defer, truncto, SEEK_SET))
2183 sysdie("could not seek to new end of defer file %s", path_defer);
2186 static void close_defer(void) {
2191 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2193 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2196 time_t now= xtime();
2198 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2200 (unsigned long)stab.st_ino);
2201 if (link(path_defer, backlog))
2202 sysfatal("could not install defer file %s as backlog file %s",
2203 path_defer, backlog);
2204 if (unlink(path_defer))
2205 sysdie("could not unlink old defer link %s to backlog file %s",
2206 path_defer, backlog);
2210 if (until_backlog_nextscan < 0 ||
2211 until_backlog_nextscan > backlog_retry_minperiods + 1)
2212 until_backlog_nextscan= backlog_retry_minperiods + 1;
2215 static void poll_backlog_file(void) {
2216 if (until_backlog_nextscan < 0) return;
2217 if (until_backlog_nextscan-- > 0) return;
2218 search_backlog_file();
2221 static void search_backlog_file(void) {
2222 /* returns non-0 iff there are any backlog files */
2227 const char *oldest_path=0;
2228 time_t oldest_mtime, now;
2230 if (backlog_input_file) return;
2234 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2238 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2240 die("out of memory expanding backlog pattern %s", globpat_backlog);
2242 for (i=0; i<gl.gl_pathc; i++) {
2243 const char *path= gl.gl_pathv[i];
2245 if (strchr(path,'#') || strchr(path,'~')) {
2246 debug("backlog file search skipping %s", path);
2249 r= stat(path, &stab);
2251 syswarn("failed to stat backlog file %s", path);
2254 if (!S_ISREG(stab.st_mode)) {
2255 warn("backlog file %s is not a plain file (or link to one)", path);
2258 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2260 oldest_mtime= stab.st_mtime;
2263 case GLOB_NOMATCH: /* fall through */
2266 sysdie("glob expansion of backlog pattern %s gave unexpected"
2267 " nonzero (error?) return value %d", globpat_backlog, r);
2273 debug("backlog scan: none");
2275 if (sms==sm_DROPPED) {
2276 notice("feed dropped and our work is complete");
2277 xunlink(path_lock, "lockfile for old feed");
2280 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2285 double age= difftime(now, oldest_mtime);
2286 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2288 if (age_deficiency <= 0) {
2289 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2290 age, age_deficiency, oldest_path);
2292 backlog_input_file= open_input_file(oldest_path);
2293 if (!backlog_input_file) {
2294 warn("backlog file %s vanished as we opened it", backlog_input_file);
2297 inputfile_reading_start(backlog_input_file);
2298 until_backlog_nextscan= -1;
2302 until_backlog_nextscan= age_deficiency / period_seconds;
2304 if (backlog_spontaneous_rescan_periods >= 0 &&
2305 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2306 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2308 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2309 age, age_deficiency, until_backlog_nextscan, oldest_path);
2313 /*========== flushing the feed ==========*/
2315 static pid_t inndcomm_child;
2316 static int inndcomm_sentinel_fd;
2318 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2319 assert(inndcomm_child);
2320 assert(fd == inndcomm_sentinel_fd);
2321 int status= xwaitpid(&inndcomm_child, "inndcomm");
2322 cancel_fd_read_except(fd);
2323 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2325 assert(!flushing_input_file);
2327 if (WIFEXITED(status)) {
2328 switch (WEXITSTATUS(status)) {
2330 case INNDCOMMCHILD_ESTATUS_FAIL:
2333 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2334 warn("feed has been dropped by innd, finishing up");
2335 flushing_input_file= main_input_file;
2336 tailing_queue_readable(flushing_input_file);
2337 /* we probably previously returned EAGAIN from our fake read method
2338 * when in fact we were at EOF, so signal another readable event
2339 * so we actually see the EOF */
2343 if (flushing_input_file) {
2344 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2347 SMS(DROPPED, 0, "feed dropped by innd");
2348 search_backlog_file();
2350 return OOP_CONTINUE;
2354 flushing_input_file= main_input_file;
2355 tailing_queue_readable(flushing_input_file);
2357 main_input_file= open_input_file(feedfile);
2358 if (!main_input_file)
2359 die("flush succeeded but feedfile %s does not exist!", feedfile);
2361 if (flushing_input_file) {
2362 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2365 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2367 return OOP_CONTINUE;
2370 goto unexpected_exitstatus;
2373 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2374 warn("flush timed out trying to talk to innd");
2377 unexpected_exitstatus:
2378 report_child_status("inndcomm child", status);
2382 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2385 static void inndcommfail(const char *what) {
2386 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2387 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2390 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2393 notice("flushing %s",why);
2395 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2396 assert(!inndcomm_child);
2397 assert(!inndcomm_sentinel_fd);
2399 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2401 inndcomm_child= xfork("inndcomm child");
2403 if (!inndcomm_child) {
2404 const char *flushargv[2]= { sitename, 0 };
2408 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2409 /* parent spots the autoclose of pipefds[1] when we die or exit */
2411 alarm(inndcomm_flush_timeout);
2412 r= ICCopen(); if (r) inndcommfail("connect");
2413 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2414 if (!r) exit(0); /* yay! */
2416 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2417 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2418 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2421 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2422 inndcomm_sentinel_fd= pipefds[0];
2423 assert(inndcomm_sentinel_fd);
2424 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2426 SMS(FLUSHING, 0, why);
2429 /*========== main program ==========*/
2431 static void postfork_inputfile(InputFile *ipf) {
2433 xclose(ipf->fd, "(in child) input file ", ipf->path);
2436 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2437 /* we have no stdio streams that are buffered long-term */
2439 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2442 static void postfork(void) {
2443 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2444 sysdie("(in child) failed to reset SIGPIPE");
2446 postfork_inputfile(main_input_file);
2447 postfork_inputfile(flushing_input_file);
2450 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2451 conn_closefd(conn,"(in child) ");
2453 postfork_stdio(defer, "defer file ", path_defer);
2456 #define EVERY(what, interval_sec, interval_usec, body) \
2457 static struct timeval what##_timeout = { interval_sec, interval_usec }; \
2458 static void what##_schedule(void); \
2459 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2461 what##_schedule(); \
2463 static void what##_schedule(void) { \
2464 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2467 EVERY(filepoll, 5,0, {
2468 if (main_input_file && main_input_file->readable_callback)
2469 filemon_callback(main_input_file);
2472 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s"
2473 #define DEBUG_IPF(wh) \
2474 wh##_input_file, debug_ipf_path(wh##_input_file), \
2475 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2476 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2477 static const char *debug_ipf_path(InputFile *ipf) {
2478 char *slash= strrchr(ipf->path,'/');
2479 return slash ? slash+1 : ipf->path;
2482 EVERY(period, -1,0, {
2484 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2485 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_IPF(flushing)
2486 " children connecting=%ld inndcomm_child"
2488 sms_names[sms], sm_period_counter,
2489 queue.count, conns.count, until_connect,
2490 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2491 (long)connecting_child, (long)inndcomm_child
2494 if (until_connect) until_connect--;
2496 poll_backlog_file();
2497 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2498 statemc_period_poll();
2499 check_assign_articles();
2504 /*========== option parsing ==========*/
2506 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2507 static void vbadusage(const char *fmt, va_list al) {
2508 char *m= xvasprintf(fmt,al);
2509 fprintf(stderr, "bad usage: %s\n%s"
2510 "say --help for help, or read the manpage\n",
2513 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2517 /*---------- generic option parser ----------*/
2519 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2520 static void badusage(const char *fmt, ...) {
2527 of_seconds= 001000u,
2528 of_boolean= 002000u,
2531 typedef struct Option Option;
2532 typedef void OptionParser(const Option*, const char *val);
2536 const char *lng, *formarg;
2542 static void parse_options(const Option *options, char ***argvp) {
2543 /* on return *argvp is first non-option arg; argc is not updated */
2546 const char *arg= *++(*argvp);
2548 if (*arg != '-') break;
2549 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2551 while ((a= *++arg)) {
2555 char *equals= strchr(arg,'=');
2556 int len= equals ? (equals - arg) : strlen(arg);
2557 for (o=options; o->shrt || o->lng; o++)
2558 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2560 badusage("unknown long option --%s",arg);
2563 if (equals) badusage("option --%s does not take a value",o->lng);
2565 } else if (equals) {
2569 if (!arg) badusage("option --%s needs a value for %s",
2570 o->lng, o->formarg);
2573 break; /* eaten the whole argument now */
2575 for (o=options; o->shrt || o->lng; o++)
2578 badusage("unknown short option -%c",a);
2585 if (!arg) badusage("option -%c needs a value for %s",
2586 o->shrt, o->formarg);
2589 break; /* eaten the whole argument now */
2595 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
2597 static void print_options(const Option *options, FILE *f) {
2599 for (o=options; o->shrt || o->lng; o++) {
2600 char shrt[2] = { o->shrt, 0 };
2601 char *optspec= xasprintf("%s%s%s%s%s",
2602 o->shrt ? "-" : "", o->shrt,
2603 o->shrt && o->lng ? "|" : "",
2604 DELIMPERHAPS("--", o->lng));
2605 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
2610 /*---------- specific option types ----------*/
2612 static void op_integer(const Option *o, const char *val) {
2615 unsigned long ul= strtoul(val,&ep,10);
2616 if (*ep || ep==val || errno || ul>INT_MAX)
2617 badusage("bad integer value for %s",o->lng);
2618 int *store= o->store;
2622 static void op_double(const Option *o, const char *val) {
2623 int *store= o->store;
2626 *store= strtod(val, &ep);
2627 if (*ep || ep==val || errno)
2628 badusage("bad floating point value for %s",o->lng);
2631 static void op_string(const Option *o, const char *val) {
2632 const char **store= o->store;
2636 static void op_seconds(const Option *o, const char *val) {
2637 int *store= o->store;
2641 double v= strtod(val,&ep);
2642 if (ep==val) badusage("bad time/duration value for %s",o->lng);
2644 if (!*ep || !strcmp(ep,"s")) unit= 1;
2645 else if (!strcmp(ep,"m")) unit= 60;
2646 else if (!strcmp(ep,"h")) unit= 3600;
2647 else if (!strcmp(ep,"d")) unit= 86400;
2648 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2652 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2656 static void op_periods_rndup(const Option *o, const char *val) {
2657 int *store= o->store;
2659 *store += period_seconds-1;
2660 *store /= period_seconds;
2663 static void op_setint(const Option *o, const char *val) {
2664 int *store= o->store;
2668 /*---------- specific options ----------*/
2670 static void help(const Option *o, const char *val);
2672 static const Option innduct_options[]= {
2673 {'f',"feedfile", "F", &feedfile, op_string },
2674 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
2675 {0,"help", 0, help },
2677 {0,"max-connections", "N", &max_connections, op_integer },
2678 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
2681 {0,"streaming", 0, &try_stream, op_setint, 1 },
2682 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
2683 {'P',"port", "PORT",&port, op_integer },
2684 {0,"inndconf", "F", &inndconffile, op_string },
2685 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
2687 {0,"no-check-proportion","PERCENT", &nocheck_thresh_pct, op_double },
2688 {0,"no-check-filter", "ARTICLES", &nocheck_decay_articles, op_double },
2690 {0,"reconnect-interval", "TIME", &reconnect_delay_periods, op_periods_rndup },
2691 {0,"flush-retry-interval","TIME", &flushfail_retry_periods, op_periods_rndup },
2692 {0,"inndcomm-timeout", "TIME", &inndcomm_flush_timeout, op_seconds },
2696 static void printusage(FILE *f) {
2697 fputs("usage: innduct [options] site [fqdn]\n"
2698 "available options are:\n", f);
2699 print_options(innduct_options, f);
2702 static void help(const Option *o, const char *val) {
2704 if (ferror(stdout) || fflush(stdout)) {
2705 perror("innduct: writing help");
2711 int main(int argc, char **argv) {
2717 parse_options(innduct_options, &argv);
2722 if (!sitename) badusage("need site name argument");
2723 remote_host= *argv++;
2724 if (*argv) badusage("too many non-option arguments");
2728 if (!remote_host) remote_host= sitename;
2730 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2731 badusage("nocheck threshold percentage must be between 0..100");
2732 nocheck_thresh= nocheck_thresh_pct * 0.01;
2734 if (nocheck_decay_articles < 0.1)
2735 badusage("nocheck decay articles must be at least 0.1");
2736 nocheck_decay= 1 - 1/nocheck_decay_articles;
2739 pathoutgoing= innconf->pathoutgoing;
2740 innconf_read(inndconffile);
2743 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2744 else if (!feedfile[0])
2745 badusage("feed filename must be nonempty");
2746 else if (feedfile[strlen(feedfile)-1]=='/')
2747 feedfile= xasprintf("%s%s",feedfile,sitename);
2749 const char *feedfile_forbidden= "?*[~#";
2751 while ((c= *feedfile_forbidden++))
2752 if (strchr(feedfile, c))
2753 badusage("feed filename may not contain metacharacter %c",c);
2757 oop_source_sys *sysloop= oop_sys_new();
2758 if (!sysloop) sysdie("could not create liboop event loop");
2759 loop= (oop_source*)sysloop;
2761 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2762 sysdie("could not ignore SIGPIPE");
2767 if (become_daemon) {
2769 for (i=3; i<255; i++)
2770 /* do this now before we open syslog, etc. */
2772 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2774 int null= open("/dev/null",O_RDWR);
2775 if (null<0) sysdie("failed to open /dev/null");
2779 xclose(null, "/dev/null original fd",0);
2781 pid_t child1= xfork("daemonise first fork");
2782 if (child1) _exit(0);
2784 pid_t sid= setsid();
2785 if (sid != child1) sysdie("setsid failed");
2787 pid_t child2= xfork("daemonise second fork");
2788 if (child2) _exit(0);
2793 if (!filemon_method_init()) {
2794 warn("no file monitoring available, polling");
2795 filepoll_schedule();
2798 period_timeout.tv_sec= period_seconds;
2805 void *r= oop_sys_run(sysloop);
2806 assert(r == OOP_ERROR);
2807 sysdie("event loop failed");