3 * - actually do something with readable on control master
4 * - option for realsockdir
5 * - manpage: document control master stuff
6 * - manpage: innconf is used for communicating with innd
8 * build-lfs/backends/innduct --no-daemon -f `pwd`/fee sit dom
12 * Newsfeeds file entries should look like this:
13 * host.name.of.site[/exclude,exclude,...]\
14 * :pattern,pattern...[/distribution,distribution...]\
18 * sitename[/exclude,exclude,...]\
19 * :pattern,pattern...[/distribution,distribution...]\
25 * or might be blanked out
26 * <spc><spc><spc><spc>....
28 * F site.name main feed file
29 * opened/created, then written, by innd
32 * tokens blanked out by duct when processed
33 * site.name_lock lock preventing multiple ducts
34 * to hold lock must open,F_SETLK[W]
35 * and then stat to check that locked file
36 * still has name site.name_lock
37 * holder of this lock is "duct"
38 * (only) lockholder may remove the lockfile
39 * D site.name_flushing temporary feed file during flush (or crash)
40 * hardlink created by duct
42 * site.name_defer 431'd articles, still being written,
43 * created, written, used by duct
45 * site.name_backlog.<date>.<inum>
46 * 431'd articles, ready for innxmit or duct
47 * created (link/mv) by duct
48 * site.name_backlog<anything-else> (where <anything-else> does not
49 * contain '#' or '~') eg
50 * site.name_backlog.manual
51 * anything the sysadmin likes (eg, feed files
52 * from old feeds to be merged into this one)
53 * created (link/mv) by admin
54 * may be symlinks (in which case links
55 * may be written through, but only links
58 * It is safe to remove backlog files manually,
59 * if it's desired to throw away the backlog.
61 * Backlog files are also processed by innduct. We find the oldest
62 * backlog file which is at least a certain amount old, and feed it
63 * back into our processing. When every article in it has been read
64 * and processed, we unlink it and look for another backlog file.
66 * If we don't have a backlog file that we're reading, we close the
67 * defer file that we're writing and make it into a backlog file at
68 * the first convenient opportunity.
79 | | <----------------<---------------------------------'|
85 | F: innd writing, duct reading |
88 | | duct decides time to flush |
89 | | duct makes hardlink |
91 | V <------------------------'|
93 | F == D: innd writing, duct reading both exist |
96 | | <-----------<-------------<--'|
100 | V <---------------------. |
103 | D: innd writing, duct reading; or ENOENT | |
105 | | duct requests flush of feed | |
106 | | (others can too, harmlessly) | |
110 | D: innd flushing, duct; or ENOENT | |
112 | | inndcomm flush fails | |
113 | |`-------------------------->------------------' |
115 | | inndcomm reports no such site |
116 | |`---------------------------------------------------- | -.
118 | | innd finishes writing D, creates F | |
119 | | inndcomm reports flush successful | |
122 | Separated <----------------' |
123 | F: innd writing F!=D /
124 | D: duct reading; or ENOENT both exist /
126 | | duct gets to the end of D /
127 | | duct opens F too /
130 | F: innd writing, duct reading |
131 | D: duct finishing V
133 | | duct finishes processing D F: ENOENT
134 | V duct unlinks D D: duct reading
136 `--<--' | duct finishes
146 "duct reading" means innduct is reading the file but also
147 overwriting processed tokens.
151 * rune for printing diagrams:
153 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
158 /*============================== PROGRAM ==============================*/
160 #define _GNU_SOURCE 1
166 #include "inndcomm.h"
168 #include "inn/list.h"
169 #include "inn/innconf.h"
172 #include <sys/types.h>
173 #include <sys/wait.h>
174 #include <sys/stat.h>
175 #include <sys/socket.h>
193 #include <oop-read.h>
195 /*----- general definitions, probably best not changed -----*/
197 #define CONNCHILD_ESTATUS_STREAM 24
198 #define CONNCHILD_ESTATUS_NOSTREAM 25
200 #define INNDCOMMCHILD_ESTATUS_FAIL 26
201 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
203 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
205 #define VA va_list al; va_start(al,fmt)
206 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
207 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
209 /*----- doubly linked lists -----*/
211 #define ISNODE(T) struct node list_node
214 union { struct list li; T *for_type; } u; \
218 #define NODE(n) (assert((void*)&(n)->list_node == &(n)), &(n)->list_node)
220 #define LIST_CHECKCANHAVENODE(l,n) \
221 ((void)((n) == ((l).u.for_type))) /* just for the type check */
223 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
224 ( LIST_CHECKCANHAVENODE(l,n), \
225 list_addsomehow(&(l).u.li, NODE((n))), \
229 #define LIST_REMSOMEHOW(l,list_remsomehow) \
230 ( (typeof((l).u.for_type)) \
233 list_remsomehow(&(l).u.li) ) \
239 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
240 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
241 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
242 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
244 #define LIST_INIT(l) (list_new(&(l).u.li))
245 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
246 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
247 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
249 #define LIST_REMOVE(l,n) \
250 ( LIST_CHECKCANHAVENODE(l,n), \
251 list_remove(NODE((n))), \
255 #define LIST_INSERT(l,n,pred) \
256 ( LIST_CHECKCANHAVENODE(l,n), \
257 LIST_CHECKCANHAVENODE(l,pred), \
258 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
262 /*----- type predeclarations -----*/
264 typedef struct Conn Conn;
265 typedef struct Article Article;
266 typedef struct InputFile InputFile;
267 typedef struct XmitDetails XmitDetails;
268 typedef struct Filemon_Perfile Filemon_Perfile;
269 typedef enum StateMachineState StateMachineState;
274 /*----- function predeclarations -----*/
276 static void conn_maybe_write(Conn *conn);
277 static void conn_make_some_xmits(Conn *conn);
278 static void *conn_write_some_xmits(Conn *conn);
280 static void xmit_free(XmitDetails *d);
282 #define SMS(newstate, periods, why) \
283 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
284 static void statemc_setstate(StateMachineState newsms, int periods,
285 const char *forlog, const char *why);
287 static void statemc_start_flush(const char *why); /* Normal => Flushing */
288 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
290 static void check_assign_articles(void);
291 static void queue_check_input_done(void);
293 static void statemc_check_flushing_done(void);
294 static void statemc_check_backlog_done(void);
296 static void postfork(void);
298 static void open_defer(void);
299 static void close_defer(void);
300 static void search_backlog_file(void);
302 static void inputfile_reading_start(InputFile *ipf);
303 static void inputfile_reading_stop(InputFile *ipf);
305 static void filemon_start(InputFile *ipf);
306 static void filemon_stop(InputFile *ipf);
307 static void filemon_callback(InputFile *ipf);
309 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
310 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
312 static const oop_rd_style peer_rd_style;
313 static oop_rd_call peer_rd_err, peer_rd_ok;
315 /*----- configuration options -----*/
316 /* when changing defaults, remember to update the manpage */
318 static const char *sitename, *remote_host;
319 static const char *feedfile, *realsockdir="/tmp/innduct.control";
320 static int quiet_multiple=0;
321 static int become_daemon=1;
322 static int try_stream=1;
324 static const char *inndconffile;
326 static int max_connections=10;
327 static int max_queue_per_conn=200;
328 static int target_max_feedfile_size=100000;
329 static int period_seconds=60;
331 static int connection_setup_timeout=200;
332 static int inndcomm_flush_timeout=100;
334 static double nocheck_thresh= 95.0; /* converted from percentage by main */
335 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
337 /* all these are initialised to seconds, and converted to periods in main */
338 static int reconnect_delay_periods=1000;
339 static int flushfail_retry_periods=1000;
340 static int backlog_retry_minperiods=50;
341 static int backlog_spontrescan_periods=300;
342 static int spontaneous_flush_periods=100000;
343 static int need_activity_periods=1000;
345 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
346 static int max_bad_data_initial= 30;
347 /* in one corrupt 4096-byte block the number of newlines has
348 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
351 /*----- statistics -----*/
353 typedef enum { /* in queue in conn->sent */
354 art_Unchecked, /* not checked, not sent checking */
355 art_Wanted, /* checked, wanted sent body as requested */
356 art_Unsolicited, /* - sent body without check */
360 #define RESULT_COUNTS(RCS,RCN) \
368 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
369 #define RCI_TRIPLE_VALS_BASE(counts,x) \
370 counts[art_Unchecked] x \
371 + counts[art_Wanted] x \
372 + counts[art_Unsolicited] x, \
373 counts[art_Unchecked] x \
374 , counts[art_Wanted] x \
375 , counts[art_Unsolicited] x
378 #define RC_INDEX(x) RC_##x,
379 RESULT_COUNTS(RC_INDEX, RC_INDEX)
384 /*----- transmission buffers -----*/
389 xk_Malloc, xk_Const, xk_Artdata
401 /*----- core operational data structure types -----*/
404 /* This is also an instance of struct oop_readable */
405 struct oop_readable readable; /* first */
406 oop_readable_call *readable_callback;
407 void *readable_callback_user;
410 Filemon_Perfile *filemon;
412 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
413 long inprogress; /* no. of articles read but not processed */
417 int counts[art_MaxState][RCI_max];
418 int readcount_ok, readcount_blank, readcount_err;
433 #define SMS_LIST(X) \
441 enum StateMachineState {
442 #define SMS_DEF_ENUM(s) sm_##s,
443 SMS_LIST(SMS_DEF_ENUM)
446 static const char *sms_names[]= {
447 #define SMS_DEF_NAME(s) #s ,
448 SMS_LIST(SMS_DEF_NAME)
454 int fd; /* may be 0, meaning closed (during construction/destruction) */
455 oop_read *rd; /* likewise */
456 int max_queue, stream, quitting;
457 int since_activity; /* periods */
458 ArticleList waiting; /* not yet told peer */
459 ArticleList priority; /* peer says send it now */
460 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
461 struct iovec xmit[CONNIOVS];
462 XmitDetails xmitd[CONNIOVS];
467 /*----- general operational variables -----*/
469 /* main initialises */
470 static oop_source *loop;
471 static ConnList conns;
472 static ArticleList queue;
473 static char *path_lock, *path_flushing, *path_defer, *path_control;
474 static char *globpat_backlog;
475 static pid_t self_pid;
477 /* statemc_init initialises */
478 static StateMachineState sms;
480 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
481 static int sm_period_counter;
483 /* control_init initialises */
484 static int control_master;
486 /* initialisation to 0 is good */
487 static int until_connect, until_backlog_nextscan;
488 static double accept_proportion;
489 static int nocheck, nocheck_reported;
491 /*========== logging ==========*/
493 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
494 static void logcore(int sysloglevel, const char *fmt, ...) {
497 vsyslog(sysloglevel,fmt,al);
499 if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
500 vfprintf(stderr,fmt,al);
506 static void logv(int sysloglevel, const char *pfx, int errnoval,
507 const char *fmt, va_list al) PRINTF(5,0);
508 static void logv(int sysloglevel, const char *pfx, int errnoval,
509 const char *fmt, va_list al) {
510 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
511 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
512 msgbuf[sizeof(msgbuf)-1]= 0;
514 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
515 sysloglevel= LOG_ERR; /* run by wrong user, probably */
517 logcore(sysloglevel, "<%s>%s: %s%s%s",
518 sitename, pfx, msgbuf,
519 errnoval>=0 ? ": " : "",
520 errnoval>=0 ? strerror(errnoval) : "");
523 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
524 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
525 static void fn(const char *fmt, ...) { \
527 logv(sysloglevel, pfx, err, fmt, al); \
531 #define logwrap(fn, pfx, sysloglevel, err) \
532 static void fn(const char *fmt, ...) PRINTF(1,2); \
533 static void fn(const char *fmt, ...) { \
535 logv(sysloglevel, pfx, err, fmt, al); \
539 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
540 diewrap(die, " critical", LOG_CRIT, -1, 16);
542 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
543 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
545 logwrap(syswarn, " warning", LOG_WARNING, errno);
546 logwrap(warn, " warning", LOG_WARNING, -1);
548 logwrap(notice, " notice", LOG_NOTICE, -1);
549 logwrap(info, " info", LOG_INFO, -1);
550 logwrap(debug, " debug", LOG_DEBUG, -1);
553 /*========== utility functions etc. ==========*/
555 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
556 static char *xvasprintf(const char *fmt, va_list al) {
558 int rc= vasprintf(&str,fmt,al);
559 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
562 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
563 static char *xasprintf(const char *fmt, ...) {
565 char *str= xvasprintf(fmt,al);
570 static int close_perhaps(int *fd) {
576 static void xclose(int fd, const char *what, const char *what2) {
578 if (r) sysdie("close %s%s",what,what2?what2:"");
580 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
582 xclose(*fd,what,what2);
586 static pid_t xfork(const char *what) {
590 if (child==-1) sysfatal("cannot fork for %s",what);
591 debug("forked %s %ld", what, (unsigned long)child);
592 if (!child) postfork();
596 static void on_fd_read_except(int fd, oop_call_fd callback) {
597 loop->on_fd(loop, fd, OOP_READ, callback, 0);
598 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
600 static void cancel_fd_read_except(int fd) {
601 loop->cancel_fd(loop, fd, OOP_READ);
602 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
605 static void report_child_status(const char *what, int status) {
606 if (WIFEXITED(status)) {
607 int es= WEXITSTATUS(status);
609 warn("%s: child died with error exit status %d", what, es);
610 } else if (WIFSIGNALED(status)) {
611 int sig= WTERMSIG(status);
612 const char *sigstr= strsignal(sig);
613 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
615 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
617 warn("%s: child died due to unknown fatal signal %d%s",
618 what, sig, coredump);
620 warn("%s: child died with unknown wait status %d", what,status);
624 static int xwaitpid(pid_t *pid, const char *what) {
627 int r= kill(*pid, SIGKILL);
628 if (r) sysdie("cannot kill %s child", what);
630 pid_t got= waitpid(*pid, &status, WNOHANG);
631 if (got==-1) sysdie("cannot reap %s child", what);
638 static void xunlink(const char *path, const char *what) {
640 if (r) sysdie("can't unlink %s %s", path, what);
643 static time_t xtime(void) {
645 if (now==-1) sysdie("time(2) failed");
649 static void check_isreg(const struct stat *stab, const char *path,
651 if (!S_ISREG(stab->st_mode))
652 die("%s %s not a plain file (mode 0%lo)",
653 what, path, (unsigned long)stab->st_mode);
656 static void xfstat(int fd, struct stat *stab_r, const char *what) {
657 int r= fstat(fd, stab_r);
658 if (r) sysdie("could not fstat %s", what);
661 static void xfstat_isreg(int fd, struct stat *stab_r,
662 const char *path, const char *what) {
663 xfstat(fd, stab_r, what);
664 check_isreg(stab_r, path, what);
667 static void xlstat_isreg(const char *path, struct stat *stab,
668 int *enoent_r /* 0 means ENOENT is fatal */,
670 int r= lstat(path, stab);
672 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
673 sysdie("could not lstat %s %s", what, path);
675 if (enoent_r) *enoent_r= 0;
676 check_isreg(stab, path, what);
679 static int samefile(const struct stat *a, const struct stat *b) {
680 assert(S_ISREG(a->st_mode));
681 assert(S_ISREG(b->st_mode));
682 return (a->st_ino == b->st_ino &&
683 a->st_dev == b->st_dev);
686 static char *sanitise(const char *input) {
687 static char sanibuf[100]; /* returns pointer to this buffer! */
689 const char *p= input;
693 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
695 if (!c) { *q++= '\''; *q=0; break; }
696 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
697 sprintf(q,"\\x%02x",c);
703 static int isewouldblock(int errnoval) {
704 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
708 /*========== command and control connections ==========*/
710 #define NOCONTROL(...) do{ \
711 syswarn("no control socket, because failed to " __VA_ARGS__); \
715 static void control_init(void) {
720 struct sockaddr_un un;
723 memset(&sa,0,sizeof(sa));
724 int maxlen= sizeof(sa.un.sun_path);
726 int reallen= readlink(path_control, sa.un.sun_path, maxlen);
729 NOCONTROL("readlink control socket symlink path %s", path_control);
731 if (reallen >= maxlen) {
732 debug("control socket symlink path too long (r=%d)",reallen);
733 xunlink(path_control, "old (overlong) control socket symlink");
739 int r= lstat(realsockdir,&stab);
741 if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
743 r= mkdir(realsockdir, 0700);
744 if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
747 uid_t self= geteuid();
748 if (!S_ISDIR(stab.st_mode) ||
749 stab.st_uid != self ||
750 stab.st_mode & 0077) {
751 warn("no control socket, because real socket directory"
752 " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
753 !!S_ISDIR(stab.st_mode),
754 (unsigned long)stab.st_uid, (unsigned long)self,
755 (unsigned long)stab.st_mode & 0777UL);
760 real= xasprintf("%s/s%lx.%lx", realsockdir,
761 (unsigned long)xtime(), (unsigned long)self_pid);
762 int reallen= strlen(real);
764 if (reallen >= maxlen) {
765 warn("no control socket, because tmpnam gave overly-long path"
769 r= symlink(real, path_control);
770 if (r) NOCONTROL("make control socket path %s a symlink to real"
771 " socket path %s", path_control, real);
772 memcpy(sa.un.sun_path, real, reallen);
775 int r= unlink(sa.un.sun_path);
776 if (r && errno!=ENOENT)
777 NOCONTROL("remove old real socket %s", sa.un.sun_path);
779 control_master= socket(PF_UNIX, SOCK_STREAM, 0);
780 if (control_master<0) NOCONTROL("create new control socket");
782 sa.un.sun_family= AF_UNIX;
783 int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
784 r= bind(control_master, &sa.sa, sl);
785 if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
787 r= listen(control_master, 5);
788 if (r) NOCONTROL("listen");
790 //loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
791 info("control socket ok, real path %s", sa.un.sun_path);
797 xclose_perhaps(&control_master, "control master",0);
801 /*========== management of connections ==========*/
803 static void conn_closefd(Conn *conn, const char *msgprefix) {
804 int r= close_perhaps(&conn->fd);
805 if (r) info("C%d %serror closing socket: %s",
806 conn->fd, msgprefix, strerror(errno));
809 static void conn_dispose(Conn *conn) {
812 oop_rd_cancel(conn->rd);
813 oop_rd_delete_kill(conn->rd);
817 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
818 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
820 conn_closefd(conn,"");
822 until_connect= reconnect_delay_periods;
825 static void *conn_exception(oop_source *lp, int fd,
826 oop_event ev, void *conn_v) {
829 assert(fd == conn->fd);
830 assert(ev == OOP_EXCEPTION);
831 int r= read(conn->fd, &ch, 1);
832 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
833 else connfail(conn,"exceptional condition on socket (peer sent urgent"
834 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
838 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
839 int requeue[art_MaxState];
842 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
843 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
844 while ((art= LIST_REMHEAD(conn->sent))) {
845 requeue[art->state]++;
846 if (art->state==art_Unsolicited) art->state= art_Unchecked;
847 LIST_ADDTAIL(queue,art);
852 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
855 char *m= xvasprintf(fmt,al);
856 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
857 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
860 LIST_REMOVE(conns,conn);
862 check_assign_articles();
865 static void connfail(Conn *conn, const char *fmt, ...) {
868 vconnfail(conn,fmt,al);
872 static void check_idle_conns(void) {
874 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
875 conn->since_activity++;
877 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
878 if (conn->since_activity <= need_activity_periods) continue;
880 /* We need to shut this down */
882 connfail(conn,"timed out waiting for response to QUIT");
883 else if (conn->sent.count)
884 connfail(conn,"timed out waiting for responses");
885 else if (conn->waiting.count || conn->priority.count)
886 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
887 else if (conn->xmitu)
888 connfail(conn,"peer has been sending responses"
889 " before receiving our commands!");
891 static const char quitcmd[]= "QUIT\r\n";
892 int todo= sizeof(quitcmd)-1;
893 const char *p= quitcmd;
895 int r= write(conn->fd, p, todo);
897 if (isewouldblock(errno))
898 connfail(conn, "blocked writing QUIT to idle connection");
900 connfail(conn, "failed to write QUIT to idle connection: %s",
908 conn->since_activity= 0;
909 debug("C%d is idle, quitting", conn->fd);
918 /*---------- making new connections ----------*/
920 static pid_t connecting_child;
921 static int connecting_fdpass_sock;
923 static void connect_attempt_discard(void) {
924 if (connecting_child) {
925 int r= kill(connecting_child, SIGTERM);
926 if (r) syswarn("failed to kill connecting child");
927 int status= xwaitpid(&connecting_child, "connect");
929 if (!(WIFEXITED(status) ||
930 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
931 report_child_status("connect", status);
933 if (connecting_fdpass_sock) {
934 cancel_fd_read_except(connecting_fdpass_sock);
935 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
939 #define PREP_DECL_MSG_CMSG(msg) \
941 memset(&msg,0,sizeof(msg)); \
942 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
943 msg.msg_control= msg##cbuf; \
944 msg.msg_controllen= sizeof(msg##cbuf);
946 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
949 assert(fd == connecting_fdpass_sock);
951 conn= xmalloc(sizeof(*conn));
952 memset(conn,0,sizeof(*conn));
954 PREP_DECL_MSG_CMSG(msg);
955 struct cmsghdr *h= 0;
956 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
957 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
960 pid_t got= waitpid(connecting_child, &status, WNOHANG);
962 assert(got==connecting_child);
964 if (WIFEXITED(status)) {
965 if (WEXITSTATUS(status) != 0 &&
966 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
967 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
968 /* child already reported the problem */;
970 warn("connect: connection child exited code %d but no cmsg",
971 WEXITSTATUS(status));
972 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
973 warn("connect: connection attempt timed out");
975 report_child_status("connect", status);
978 /* child is still running apparently, report the socket problem */
980 syswarn("connect: read from fdpass socket failed");
981 else if (e == OOP_EXCEPTION)
982 warn("connect: unexpected exception on fdpass socket");
984 warn("connect: unexpected EOF on fdpass socket");
986 fatal("connect: unexpected lack of cmsg from child");
991 #define CHK(field, val) \
992 if (h->cmsg_##field != val) { \
993 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
994 h->cmsg_##field, val); \
997 CHK(level, SOL_SOCKET);
998 CHK(type, SCM_RIGHTS);
999 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1002 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1004 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1007 pid_t got= waitpid(connecting_child, &status, 0);
1008 if (got==-1) sysdie("connect: real wait for child");
1009 assert(got == connecting_child);
1010 connecting_child= 0;
1012 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1013 int es= WEXITSTATUS(status);
1015 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1016 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1018 fatal("connect: child gave unexpected exit status %d", es);
1022 LIST_INIT(conn->waiting);
1023 LIST_INIT(conn->priority);
1024 LIST_INIT(conn->sent);
1025 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1027 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1028 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1029 if (!conn->fd) sysdie("oop_rd_new_fd (fd=%d)",conn->fd);
1030 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1032 &peer_rd_err, conn);
1033 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1035 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1036 LIST_ADDHEAD(conns, conn);
1038 connect_attempt_discard();
1039 check_assign_articles();
1044 connect_attempt_discard();
1045 return OOP_CONTINUE;
1048 static int allow_connect_start(void) {
1049 return conns.count < max_connections
1050 && !connecting_child
1054 static void connect_start(void) {
1055 assert(!connecting_child);
1056 assert(!connecting_fdpass_sock);
1058 notice("starting connection attempt");
1061 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1062 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1064 connecting_child= xfork("connection");
1066 if (!connecting_child) {
1067 FILE *cn_from, *cn_to;
1068 char buf[NNTP_STRLEN+100];
1069 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1071 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1073 alarm(connection_setup_timeout);
1074 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1075 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
1076 else sysfatal("connect: connection attempt failed");
1078 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1079 sysfatal("connect: authentication failed");
1081 if (fputs("MODE STREAM\r\n", cn_to) ||
1083 sysfatal("connect: could not send MODE STREAM");
1084 buf[sizeof(buf)-1]= 0;
1085 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1086 if (ferror(cn_from))
1087 sysfatal("connect: could not read response to MODE STREAM");
1089 fatal("connect: connection close in response to MODE STREAM");
1094 fatal("connect: response to MODE STREAM is too long: %.100s...",
1096 l--; if (l>0 && buf[l-1]=='\r') l--;
1099 int rcode= strtoul(buf,&ep,10);
1101 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
1105 exitstatus= CONNCHILD_ESTATUS_STREAM;
1111 warn("connect: unexpected response to MODE STREAM: %.50s",
1117 int fd= fileno(cn_from);
1119 PREP_DECL_MSG_CMSG(msg);
1120 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1121 cmsg->cmsg_level= SOL_SOCKET;
1122 cmsg->cmsg_type= SCM_RIGHTS;
1123 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1124 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1126 msg.msg_controllen= cmsg->cmsg_len;
1127 r= sendmsg(socks[1], &msg, 0);
1128 if (r) sysdie("sendmsg failed for new connection");
1133 xclose(socks[1], "connecting fdpass child's socket",0);
1134 connecting_fdpass_sock= socks[0];
1135 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1138 /*---------- assigning articles to conns, and transmitting ----------*/
1140 static void check_assign_articles(void) {
1146 int spare=0, inqueue=0;
1148 /* Find a connection to offer this article. We prefer a busy
1149 * connection to an idle one, provided it's not full. We take the
1150 * first (oldest) and since that's stable, it will mean we fill up
1151 * connections in order. That way if we have too many
1152 * connections, the spare ones will go away eventually.
1154 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1155 if (walk->quitting) continue;
1156 inqueue= walk->sent.count + walk->priority.count
1157 + walk->waiting.count;
1158 spare= walk->max_queue - inqueue;
1159 assert(inqueue <= max_queue_per_conn);
1161 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1162 else if (spare>0) /*working*/ { use= walk; break; }
1165 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1167 Article *art= LIST_REMHEAD(queue);
1168 LIST_ADDTAIL(use->waiting, art);
1171 conn_maybe_write(use);
1172 } else if (allow_connect_start()) {
1173 until_connect= reconnect_delay_periods;
1182 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1183 conn_maybe_write(u);
1184 return OOP_CONTINUE;
1187 static void conn_maybe_write(Conn *conn) {
1189 conn_make_some_xmits(conn);
1191 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1195 void *rp= conn_write_some_xmits(conn);
1196 if (rp==OOP_CONTINUE) {
1197 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1199 } else if (rp==OOP_HALT) {
1202 /* transmitted everything */
1209 /*========== article transmission ==========*/
1211 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1212 XmitKind kind) { /* caller must then fill in details */
1213 struct iovec *v= &conn->xmit[conn->xmitu];
1214 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1215 v->iov_base= (char*)data;
1221 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1222 xmit_core(conn,data,len, xk_Const);
1224 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1226 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1227 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1231 static void xmit_free(XmitDetails *d) {
1233 case xk_Malloc: free(d->info.malloc_tofree); break;
1234 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1235 case xk_Const: break;
1240 static void *conn_write_some_xmits(Conn *conn) {
1242 * 0: nothing more to write, no need to call us again
1243 * OOP_CONTINUE: more to write but fd not writeable
1244 * OOP_HALT: disaster, have destroyed conn
1247 int count= conn->xmitu;
1248 if (!count) return 0;
1250 if (count > IOV_MAX) count= IOV_MAX;
1251 ssize_t rs= writev(conn->fd, conn->xmit, count);
1253 if (isewouldblock(errno)) return OOP_CONTINUE;
1254 connfail(conn, "write failed: %s", strerror(errno));
1260 for (done=0; rs && done<conn->xmitu; done++) {
1261 struct iovec *vp= &conn->xmit[done];
1262 XmitDetails *dp= &conn->xmitd[done];
1263 if (rs > vp->iov_len) {
1267 vp->iov_base= (char*)vp->iov_base + rs;
1271 int newu= conn->xmitu - done;
1272 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1273 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1278 static void conn_make_some_xmits(Conn *conn) {
1280 if (conn->xmitu+5 > CONNIOVS)
1283 Article *art= LIST_REMHEAD(conn->priority);
1284 if (!art) art= LIST_REMHEAD(conn->waiting);
1287 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1288 /* actually send it */
1290 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1294 XMIT_LITERAL("TAKETHIS ");
1295 xmit_noalloc(conn, art->messageid, art->midlen);
1296 XMIT_LITERAL("\r\n");
1297 xmit_artbody(conn, artdata);
1300 /* we got 235 from IHAVE */
1302 xmit_artbody(conn, artdata);
1304 XMIT_LITERAL(".\r\n");
1309 art->state == art_Unchecked ? art_Unsolicited :
1310 art->state == art_Wanted ? art_Wanted :
1312 art->ipf->counts[art->state][RC_sent]++;
1313 LIST_ADDTAIL(conn->sent, art);
1319 XMIT_LITERAL("IHAVE ");
1321 XMIT_LITERAL("CHECK ");
1322 xmit_noalloc(conn, art->messageid, art->midlen);
1323 XMIT_LITERAL("\r\n");
1325 assert(art->state == art_Unchecked);
1326 art->ipf->counts[art->state][RC_sent]++;
1327 LIST_ADDTAIL(conn->sent, art);
1333 /*========== handling responses from peer ==========*/
1335 static const oop_rd_style peer_rd_style= {
1336 OOP_RD_DELIM_STRIP, '\n',
1338 OOP_RD_SHORTREC_FORBID
1341 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1342 const char *errmsg, int errnoval,
1343 const char *data, size_t recsz, void *conn_v) {
1345 connfail(conn, "error receiving from peer: %s", errmsg);
1346 return OOP_CONTINUE;
1349 static Article *article_reply_check(Conn *conn, const char *response,
1350 int code_indicates_streaming,
1352 /* 1:yes, -1:no, 0:dontcare */,
1353 const char *sanitised_response) {
1354 Article *art= LIST_HEAD(conn->sent);
1358 "peer gave unexpected response when no commands outstanding: %s",
1359 sanitised_response);
1363 if (code_indicates_streaming) {
1364 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1365 if (!conn->stream) {
1366 connfail(conn, "peer gave streaming response code "
1367 " to IHAVE or subsequent body: %s", sanitised_response);
1370 const char *got_mid= response+4;
1371 int got_midlen= strcspn(got_mid, " \n\r");
1372 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1373 connfail(conn, "peer gave streaming response with syntactically invalid"
1374 " messageid: %s", sanitised_response);
1377 if (got_midlen != art->midlen ||
1378 memcmp(got_mid, art->messageid, got_midlen)) {
1379 connfail(conn, "peer gave streaming response code to wrong article -"
1380 " probable synchronisation problem; we offered: %s;"
1382 art->messageid, sanitised_response);
1387 connfail(conn, "peer gave non-streaming response code to"
1388 " CHECK/TAKETHIS: %s", sanitised_response);
1393 if (must_have_sent>0 && art->state < art_Wanted) {
1394 connfail(conn, "peer says article accepted but"
1395 " we had not sent the body: %s", sanitised_response);
1398 if (must_have_sent<0 && art->state >= art_Wanted) {
1399 connfail(conn, "peer says please sent the article but we just did: %s",
1400 sanitised_response);
1404 Article *art_again= LIST_REMHEAD(conn->sent);
1405 assert(art_again == art);
1409 static void update_nocheck(int accepted) {
1410 accept_proportion *= nocheck_decay;
1411 accept_proportion += accepted * (1.0 - nocheck_decay);
1412 int new_nocheck= accept_proportion >= nocheck_thresh;
1413 if (new_nocheck && !nocheck_reported) {
1414 notice("entering nocheck mode for the first time");
1415 nocheck_reported= 1;
1416 } else if (new_nocheck != nocheck) {
1417 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1419 nocheck= new_nocheck;
1422 static void article_done(Conn *conn, Article *art, int whichcount) {
1423 art->ipf->counts[art->state][whichcount]++;
1424 if (whichcount == RC_accepted) update_nocheck(1);
1425 else if (whichcount == RC_unwanted) update_nocheck(0);
1427 InputFile *ipf= art->ipf;
1429 while (art->blanklen) {
1430 static const char spaces[]=
1435 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1436 int r= pwrite(ipf->fd, spaces, w, art->offset);
1438 if (errno==EINTR) continue;
1439 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1440 art->messageid, art->blanklen,
1441 (unsigned long)art->offset, ipf->path);
1443 assert(r>=0 && r<=w);
1449 assert(ipf->inprogress >= 0);
1452 if (!ipf->inprogress && ipf != main_input_file)
1453 queue_check_input_done();
1456 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1457 const char *errmsg, int errnoval,
1458 const char *data, size_t recsz, void *conn_v) {
1461 if (ev == OOP_RD_EOF) {
1462 connfail(conn, "unexpected EOF from peer");
1463 return OOP_CONTINUE;
1465 assert(ev == OOP_RD_OK);
1467 char *sani= sanitise(data);
1470 unsigned long code= strtoul(data, &ep, 10);
1471 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1472 connfail(conn, "badly formatted response from peer: %s", sani);
1473 return OOP_CONTINUE;
1476 if (conn->quitting) {
1477 if (code!=205 && code!=503) {
1478 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1480 notice("C%d idle connection closed", conn->fd);
1481 assert(!conn->waiting.count);
1482 assert(!conn->priority.count);
1483 assert(!conn->sent.count);
1484 assert(!conn->xmitu);
1485 LIST_REMOVE(conns,conn);
1488 return OOP_CONTINUE;
1491 conn->since_activity= 0;
1494 #define GET_ARTICLE(musthavesent) \
1495 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1496 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1498 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1499 code_streaming= (streaming); \
1500 GET_ARTICLE(musthavesent); \
1501 article_done(conn, art, RC_##how); break;
1503 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1505 int code_streaming= 0;
1509 case 400: PEERBADMSG("peer stopped accepting articles");
1510 case 503: PEERBADMSG("peer timed us out");
1511 default: PEERBADMSG("peer sent unexpected message");
1513 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1514 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1516 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1517 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1519 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1520 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1522 case 238: /* CHECK says send it */
1524 case 335: /* IHAVE says send it */
1526 assert(art->state == art_Unchecked);
1527 art->ipf->counts[art->state][RC_accepted]++;
1528 art->state= art_Wanted;
1529 LIST_ADDTAIL(conn->priority, art);
1532 case 431: /* CHECK or TAKETHIS says try later */
1534 case 436: /* IHAVE says try later */
1537 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1539 sysfatal("write to defer file %s",path_defer);
1540 article_done(conn, art, RC_deferred);
1545 conn_maybe_write(conn);
1546 check_assign_articles();
1547 return OOP_CONTINUE;
1551 /*========== monitoring of input files ==========*/
1553 static void feedfile_eof(InputFile *ipf) {
1554 assert(ipf != main_input_file); /* promised by tailing_try_read */
1555 inputfile_reading_stop(ipf);
1557 if (ipf == flushing_input_file) {
1558 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1559 if (main_input_file) inputfile_reading_start(main_input_file);
1560 statemc_check_flushing_done();
1561 } else if (ipf == backlog_input_file) {
1562 statemc_check_backlog_done();
1564 abort(); /* supposed to wait rather than get EOF on main input file */
1568 static InputFile *open_input_file(const char *path) {
1569 int fd= open(path, O_RDONLY);
1571 if (errno==ENOENT) return 0;
1572 sysfatal("unable to open input file %s", path);
1576 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1577 memset(ipf,0,sizeof(*ipf));
1580 strcpy(ipf->path, path);
1585 static void close_input_file(InputFile *ipf) { /* does not free */
1586 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1587 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1588 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1589 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1590 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1594 /*---------- dealing with articles read in the input file ----------*/
1596 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1597 const char *data, const char *how) {
1598 warn("corrupted file: %s, offset %lu: %s: %s",
1599 ipf->path, (unsigned long)offset, how, sanitise(data));
1600 ipf->readcount_err++;
1601 if (ipf->readcount_err > max_bad_data_initial +
1602 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1603 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1604 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1605 return OOP_CONTINUE;
1608 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1609 oop_rd_event ev, const char *errmsg,
1610 int errnoval, const char *data, size_t recsz,
1612 InputFile *ipf= ipf_v;
1613 assert(ev == OOP_RD_SYSTEM);
1615 sysdie("error reading input file: %s, offset %lu",
1616 ipf->path, (unsigned long)ipf->offset);
1619 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1620 oop_rd_event ev, const char *errmsg,
1621 int errnoval, const char *data, size_t recsz,
1623 InputFile *ipf= ipf_v;
1625 char tokentextbuf[sizeof(TOKEN)*2+3];
1627 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1629 off_t old_offset= ipf->offset;
1630 ipf->offset += recsz + 1;
1632 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1634 if (ev==OOP_RD_PARTREC)
1635 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1636 /* but process it anyway */
1638 if (ipf->skippinglong) {
1639 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1640 return OOP_CONTINUE;
1642 if (ev==OOP_RD_LONG) {
1643 ipf->skippinglong= 1;
1644 X_BAD_DATA("overly long line");
1647 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1648 if (!recsz) X_BAD_DATA("empty line");
1651 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1652 ipf->readcount_blank++;
1653 return OOP_CONTINUE;
1656 char *space= strchr(data,' ');
1657 int tokenlen= space-data;
1658 int midlen= (int)recsz-tokenlen-1;
1659 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1660 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1662 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1663 memcpy(tokentextbuf, data, tokenlen);
1664 tokentextbuf[tokenlen]= 0;
1665 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1667 ipf->readcount_ok++;
1669 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1670 art->state= art_Unchecked;
1671 art->midlen= midlen;
1672 art->ipf= ipf; ipf->inprogress++;
1673 art->token= TextToToken(tokentextbuf);
1674 art->offset= ipf->offset;
1675 art->blanklen= recsz;
1676 strcpy(art->messageid, space+1);
1677 LIST_ADDTAIL(queue, art);
1679 if (sms==sm_NORMAL && ipf==main_input_file &&
1680 ipf->offset >= target_max_feedfile_size)
1681 statemc_start_flush("feed file size");
1683 check_assign_articles();
1684 return OOP_CONTINUE;
1687 /*========== tailing input file ==========*/
1689 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1691 InputFile *ipf= user;
1692 return ipf->readable_callback(loop, &ipf->readable,
1693 ipf->readable_callback_user);
1696 static void tailing_on_cancel(struct oop_readable *rable) {
1697 InputFile *ipf= (void*)rable;
1699 if (ipf->filemon) filemon_stop(ipf);
1700 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1701 ipf->readable_callback= 0;
1704 static void tailing_queue_readable(InputFile *ipf) {
1705 /* lifetime of ipf here is OK because destruction will cause
1706 * on_cancel which will cancel this callback */
1707 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1710 static int tailing_on_readable(struct oop_readable *rable,
1711 oop_readable_call *cb, void *user) {
1712 InputFile *ipf= (void*)rable;
1714 tailing_on_cancel(rable);
1715 ipf->readable_callback= cb;
1716 ipf->readable_callback_user= user;
1719 tailing_queue_readable(ipf);
1723 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1725 InputFile *ipf= (void*)rable;
1727 ssize_t r= read(ipf->fd, buffer, length);
1729 if (errno==EINTR) continue;
1733 if (ipf==main_input_file) {
1736 } else if (ipf==flushing_input_file) {
1738 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1739 } else if (ipf==backlog_input_file) {
1749 /*---------- filemon implemented with inotify ----------*/
1751 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1752 #define HAVE_FILEMON
1754 #include <linux/inotify.h>
1756 static int filemon_inotify_fd;
1757 static int filemon_inotify_wdmax;
1758 static InputFile **filemon_inotify_wd2ipf;
1760 struct Filemon_Perfile {
1764 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1765 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1766 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
1768 if (wd >= filemon_inotify_wdmax) {
1770 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1771 sizeof(*filemon_inotify_wd2ipf) * newmax);
1772 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1773 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1774 filemon_inotify_wdmax= newmax;
1777 assert(!filemon_inotify_wd2ipf[wd]);
1778 filemon_inotify_wd2ipf[wd]= ipf;
1780 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1781 ipf, wd, filemon_inotify_wdmax);
1786 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1788 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1789 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1790 if (r) sysdie("inotify_rm_watch");
1791 filemon_inotify_wd2ipf[wd]= 0;
1794 static void *filemon_inotify_readable(oop_source *lp, int fd,
1795 oop_event e, void *u) {
1796 struct inotify_event iev;
1798 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1800 if (isewouldblock(errno)) break;
1801 sysdie("read from inotify master");
1802 } else if (r==sizeof(iev)) {
1803 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1805 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1807 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1808 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1809 filemon_callback(ipf);
1811 return OOP_CONTINUE;
1814 static int filemon_method_init(void) {
1815 filemon_inotify_fd= inotify_init();
1816 if (filemon_inotify_fd<0) {
1817 syswarn("could not initialise inotify: inotify_init failed");
1821 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1823 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1827 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1829 /*---------- filemon dummy implementation ----------*/
1831 #if !defined(HAVE_FILEMON)
1833 struct Filemon_Perfile { int dummy; };
1835 static int filemon_method_init(void) { return 0; }
1836 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1837 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1839 #endif /* !HAVE_FILEMON */
1841 /*---------- filemon generic interface ----------*/
1843 static void filemon_start(InputFile *ipf) {
1844 assert(!ipf->filemon);
1846 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1847 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1848 filemon_method_startfile(ipf, ipf->filemon);
1851 static void filemon_stop(InputFile *ipf) {
1852 if (!ipf->filemon) return;
1853 filemon_method_stopfile(ipf, ipf->filemon);
1858 static void filemon_callback(InputFile *ipf) {
1859 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1862 /*---------- interface to start and stop an input file ----------*/
1864 static const oop_rd_style feedfile_rdstyle= {
1865 OOP_RD_DELIM_STRIP, '\n',
1867 OOP_RD_SHORTREC_LONG,
1870 static void inputfile_reading_start(InputFile *ipf) {
1872 ipf->readable.on_readable= tailing_on_readable;
1873 ipf->readable.on_cancel= tailing_on_cancel;
1874 ipf->readable.try_read= tailing_try_read;
1875 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1876 ipf->readable.delete_kill= 0;
1878 ipf->readable_callback= 0;
1879 ipf->readable_callback_user= 0;
1881 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1884 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1885 feedfile_got_article,ipf, feedfile_read_err, ipf);
1886 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1889 static void inputfile_reading_stop(InputFile *ipf) {
1891 oop_rd_cancel(ipf->rd);
1892 oop_rd_delete(ipf->rd);
1894 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1898 /*========== interaction with innd - state machine ==========*/
1900 /* See official state diagram at top of file. We implement
1911 |`---------------------------------------------------.
1913 |`---------------- - - - |
1914 D ENOENT | D EXISTS see OVERALL STATES diagram |
1915 | for full startup logic |
1918 | ============ try to |
1924 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1925 ^ | hardlink F to D |
1928 | | our handle onto F is now onto D |
1931 | |<-------------------<---------------------<---------+
1933 | | spawn inndcomm flush |
1935 | ================== |
1936 | FLUSHING[-ABSENT] |
1938 | main D tail/none |
1939 | ================== |
1941 | | INNDCOMM FLUSH FAILS ^
1942 | |`----------------------->----------. |
1944 | | NO SUCH SITE V |
1945 ^ |`--------------->----. ==================== |
1946 | | \ FLUSHFAILED[-ABSENT] |
1948 | | FLUSH OK \ main D tail/none |
1949 | | open F \ ==================== |
1951 | | \ | TIME TO RETRY |
1952 | |`------->----. ,---<---'\ `----------------'
1953 | | D NONE | | D NONE `----.
1955 | ============= V V ============
1956 | SEPARATED-1 | | DROPPING-1
1957 | flsh->rd!=0 | | flsh->rd!=0
1958 | [Separated] | | [Dropping]
1959 | main F idle | | main none
1960 | old D tail | | old D tail
1961 | ============= | | ============
1963 ^ | EOF ON D | | defer | EOF ON D
1965 | =============== | | ===============
1966 | SEPARATED-2 | | DROPPING-2
1967 | flsh->rd==0 | V flsh->rd==0
1968 | [Finishing] | | [Dropping]
1969 | main F tail | `. main none
1970 | old D closed | `. old D closed
1971 | =============== V `. ===============
1973 | | ALL D PROCESSED `. | ALL D PROCESSED
1974 | V install defer as backlog `. | install defer
1975 ^ | close D `. | close D
1976 | | unlink D `. | unlink D
1979 `----------' ==============
1999 static void startup_set_input_file(InputFile *f) {
2000 assert(!main_input_file);
2002 inputfile_reading_start(f);
2005 static void statemc_lock(void) {
2007 struct stat stab, stabf;
2010 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2011 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2014 memset(&fl,0,sizeof(fl));
2016 fl.l_whence= SEEK_SET;
2017 int r= fcntl(lockfd, F_SETLK, &fl);
2019 if (errno==EACCES || isewouldblock(errno)) {
2020 if (quiet_multiple) exit(0);
2021 fatal("another duct holds the lockfile");
2023 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2026 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2028 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2030 if (!lock_noent && samefile(&stab, &stabf))
2033 xclose(lockfd, "stale lockfile ", path_lock);
2036 FILE *lockfile= fdopen(lockfd, "w");
2037 if (!lockfile) sysdie("fdopen lockfile");
2039 int r= ftruncate(lockfd, 0);
2040 if (r) sysdie("truncate lockfile to write new info");
2042 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2043 (unsigned long)self_pid,
2044 sitename, feedfile, remote_host) == EOF ||
2046 sysfatal("write info to lockfile %s", path_lock);
2048 debug("startup: locked");
2051 static void statemc_init(void) {
2052 struct stat stabdefer;
2054 search_backlog_file();
2057 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2059 debug("startup: ductdefer ENOENT");
2061 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2062 switch (stabdefer.st_nlink==1) {
2064 open_defer(); /* so that we will later close it and rename it */
2067 xunlink(path_defer, "stale defer file link"
2068 " (presumably hardlink to backlog file)");
2071 die("defer file %s has unexpected link count %d",
2072 path_defer, stabdefer.st_nlink);
2076 struct stat stab_f, stab_d;
2079 InputFile *file_d= open_input_file(path_flushing);
2080 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2082 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2084 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2085 debug("startup: F==D => Hardlinked");
2086 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2091 debug("startup: F ENOENT => Moved");
2092 if (file_d) startup_set_input_file(file_d);
2093 spawn_inndcomm_flush("feedfile missing at startup");
2094 /* => Flushing, sms:=FLUSHING */
2097 debug("startup: F!=D => Separated");
2098 startup_set_input_file(file_d);
2099 SMS(SEPARATED, 0, "found both old and current feed files");
2101 debug("startup: F exists, D ENOENT => Normal");
2102 InputFile *file_f= open_input_file(feedfile);
2103 if (!file_f) die("feed file vanished during startup");
2104 startup_set_input_file(file_f);
2105 SMS(NORMAL, flushfail_retry_periods, "normal startup");
2110 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2111 assert(sms == sm_NORMAL);
2113 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2115 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2116 (unsigned long)target_max_feedfile_size,
2119 int r= link(feedfile, path_flushing);
2120 if (r) sysfatal("link feedfile %s to flushing file %s",
2121 feedfile, path_flushing);
2124 xunlink(feedfile, "old feedfile link");
2127 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2130 static void statemc_period_poll(void) {
2131 if (!sm_period_counter) return;
2132 sm_period_counter--;
2133 assert(sm_period_counter>=0);
2135 if (sm_period_counter) return;
2138 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2140 case sm_FLUSHFAILED:
2141 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2148 static int inputfile_is_done(InputFile *ipf) {
2150 if (ipf->inprogress) return 0; /* new article in the meantime */
2151 if (ipf->rd) return 0; /* not had EOF */
2155 static void notice_processed(InputFile *ipf, const char *what,
2157 #define RCI_NOTHING(x) /* nothing */
2158 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2159 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2161 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2163 info("processed %s%s read=%d(+%dbl,+%derr)"
2164 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2165 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2168 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2169 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2170 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2171 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2172 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2173 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2179 static void statemc_check_backlog_done(void) {
2180 InputFile *ipf= backlog_input_file;
2181 if (!inputfile_is_done(ipf)) return;
2183 const char *slash= strrchr(ipf->path, '/');
2184 const char *leaf= slash ? slash+1 : ipf->path;
2185 const char *under= strchr(slash, '_');
2186 const char *rest= under ? under+1 : leaf;
2187 if (!strncmp(rest,"backlog",7)) rest += 7;
2188 notice_processed(ipf,"backlog:",rest);
2190 close_input_file(ipf);
2191 if (unlink(ipf->path)) {
2192 if (errno != ENOENT)
2193 sysdie("could not unlink processed backlog file %s", ipf->path);
2194 warn("backlog file %s vanished while we were reading it"
2195 " so we couldn't remove it (but it's done now, anyway)",
2199 backlog_input_file= 0;
2200 search_backlog_file();
2204 static void statemc_check_flushing_done(void) {
2205 InputFile *ipf= flushing_input_file;
2206 if (!inputfile_is_done(ipf)) return;
2208 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2210 notice_processed(ipf,"feedfile",0);
2214 xunlink(path_flushing, "old flushing file");
2216 close_input_file(flushing_input_file);
2217 free(flushing_input_file);
2218 flushing_input_file= 0;
2220 if (sms==sm_SEPARATED) {
2221 notice("flush complete");
2222 SMS(NORMAL, 0, "flush complete");
2223 } else if (sms==sm_DROPPING) {
2224 SMS(DROPPED, 0, "old flush complete");
2225 search_backlog_file();
2226 notice("feed dropped, but will continue until backlog is finished");
2230 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2232 assert(!inputfile_is_done(main_input_file));
2233 statemc_check_flushing_done();
2234 statemc_check_backlog_done();
2235 return OOP_CONTINUE;
2238 static void queue_check_input_done(void) {
2239 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2242 static void statemc_setstate(StateMachineState newsms, int periods,
2243 const char *forlog, const char *why) {
2245 sm_period_counter= periods;
2247 const char *xtra= "";
2250 case sm_FLUSHFAILED:
2251 if (!main_input_file) xtra= "-ABSENT";
2255 xtra= flushing_input_file->rd ? "-1" : "-2";
2261 info("%s%s[%d] %s",forlog,xtra,periods,why);
2263 info("%s%s %s",forlog,xtra,why);
2267 /*---------- defer and backlog files ----------*/
2269 static void open_defer(void) {
2274 defer= fopen(path_defer, "a+");
2275 if (!defer) sysfatal("could not open defer file %s", path_defer);
2277 /* truncate away any half-written records */
2279 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2281 if (stab.st_size > LONG_MAX)
2282 die("defer file %s size is far too large", path_defer);
2287 long orgsize= stab.st_size;
2288 long truncto= stab.st_size;
2290 if (!truncto) break; /* was only (if anything) one half-truncated record */
2291 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2292 sysdie("seek in defer file %s while truncating partial", path_defer);
2297 sysdie("failed read from defer file %s", path_defer);
2299 die("defer file %s shrank while we were checking it!", path_defer);
2305 if (stab.st_size != truncto) {
2306 warn("truncating half-record at end of defer file %s -"
2307 " shrinking by %ld bytes from %ld to %ld",
2308 path_defer, orgsize - truncto, orgsize, truncto);
2311 sysfatal("could not flush defer file %s", path_defer);
2312 if (ftruncate(fileno(defer), truncto))
2313 sysdie("could not truncate defer file %s", path_defer);
2316 info("continuing existing defer file %s (%ld bytes)",
2317 path_defer, orgsize);
2319 if (fseek(defer, truncto, SEEK_SET))
2320 sysdie("could not seek to new end of defer file %s", path_defer);
2323 static void close_defer(void) {
2328 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2330 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2333 time_t now= xtime();
2335 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2337 (unsigned long)stab.st_ino);
2338 if (link(path_defer, backlog))
2339 sysfatal("could not install defer file %s as backlog file %s",
2340 path_defer, backlog);
2341 if (unlink(path_defer))
2342 sysdie("could not unlink old defer link %s to backlog file %s",
2343 path_defer, backlog);
2347 if (until_backlog_nextscan < 0 ||
2348 until_backlog_nextscan > backlog_retry_minperiods + 1)
2349 until_backlog_nextscan= backlog_retry_minperiods + 1;
2352 static void poll_backlog_file(void) {
2353 if (until_backlog_nextscan < 0) return;
2354 if (until_backlog_nextscan-- > 0) return;
2355 search_backlog_file();
2358 static void search_backlog_file(void) {
2359 /* returns non-0 iff there are any backlog files */
2364 const char *oldest_path=0;
2365 time_t oldest_mtime=0, now;
2367 if (backlog_input_file) return;
2371 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2375 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2377 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2379 for (i=0; i<gl.gl_pathc; i++) {
2380 const char *path= gl.gl_pathv[i];
2382 if (strchr(path,'#') || strchr(path,'~')) {
2383 debug("backlog file search skipping %s", path);
2386 r= stat(path, &stab);
2388 syswarn("failed to stat backlog file %s", path);
2391 if (!S_ISREG(stab.st_mode)) {
2392 warn("backlog file %s is not a plain file (or link to one)", path);
2395 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2397 oldest_mtime= stab.st_mtime;
2400 case GLOB_NOMATCH: /* fall through */
2403 sysdie("glob expansion of backlog pattern %s gave unexpected"
2404 " nonzero (error?) return value %d", globpat_backlog, r);
2408 debug("backlog scan: none");
2410 if (sms==sm_DROPPED) {
2411 notice("feed dropped and our work is complete");
2412 xunlink(path_lock, "lockfile for old feed");
2415 until_backlog_nextscan= backlog_spontrescan_periods;
2420 double age= difftime(now, oldest_mtime);
2421 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2423 if (age_deficiency <= 0) {
2424 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2425 age, age_deficiency, oldest_path);
2427 backlog_input_file= open_input_file(oldest_path);
2428 if (!backlog_input_file) {
2429 warn("backlog file %s vanished as we opened it", oldest_path);
2433 inputfile_reading_start(backlog_input_file);
2434 until_backlog_nextscan= -1;
2438 until_backlog_nextscan= age_deficiency / period_seconds;
2440 if (backlog_spontrescan_periods >= 0 &&
2441 until_backlog_nextscan > backlog_spontrescan_periods)
2442 until_backlog_nextscan= backlog_spontrescan_periods;
2444 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2445 age, age_deficiency, until_backlog_nextscan, oldest_path);
2452 /*========== flushing the feed ==========*/
2454 static pid_t inndcomm_child;
2455 static int inndcomm_sentinel_fd;
2457 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2458 assert(inndcomm_child);
2459 assert(fd == inndcomm_sentinel_fd);
2460 int status= xwaitpid(&inndcomm_child, "inndcomm");
2461 cancel_fd_read_except(fd);
2462 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2464 assert(!flushing_input_file);
2466 if (WIFEXITED(status)) {
2467 switch (WEXITSTATUS(status)) {
2469 case INNDCOMMCHILD_ESTATUS_FAIL:
2472 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2473 warn("feed has been dropped by innd, finishing up");
2474 flushing_input_file= main_input_file;
2475 tailing_queue_readable(flushing_input_file);
2476 /* we probably previously returned EAGAIN from our fake read method
2477 * when in fact we were at EOF, so signal another readable event
2478 * so we actually see the EOF */
2482 if (flushing_input_file) {
2483 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2486 SMS(DROPPED, 0, "feed dropped by innd");
2487 search_backlog_file();
2489 return OOP_CONTINUE;
2493 flushing_input_file= main_input_file;
2494 tailing_queue_readable(flushing_input_file);
2496 main_input_file= open_input_file(feedfile);
2497 if (!main_input_file)
2498 die("flush succeeded but feedfile %s does not exist!", feedfile);
2500 if (flushing_input_file) {
2501 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2504 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2506 return OOP_CONTINUE;
2509 goto unexpected_exitstatus;
2512 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2513 warn("flush timed out trying to talk to innd");
2516 unexpected_exitstatus:
2517 report_child_status("inndcomm child", status);
2521 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2522 return OOP_CONTINUE;
2525 static void inndcommfail(const char *what) {
2526 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2527 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2530 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2533 notice("flushing %s",why);
2535 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2536 assert(!inndcomm_child);
2537 assert(!inndcomm_sentinel_fd);
2539 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2541 inndcomm_child= xfork("inndcomm child");
2543 if (!inndcomm_child) {
2544 const char *flushargv[2]= { sitename, 0 };
2548 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2549 /* parent spots the autoclose of pipefds[1] when we die or exit */
2551 alarm(inndcomm_flush_timeout);
2552 r= ICCopen(); if (r) inndcommfail("connect");
2553 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2554 if (!r) exit(0); /* yay! */
2556 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2557 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2558 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2561 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2562 inndcomm_sentinel_fd= pipefds[0];
2563 assert(inndcomm_sentinel_fd);
2564 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2566 SMS(FLUSHING, 0, why);
2569 /*========== main program ==========*/
2571 static void postfork_inputfile(InputFile *ipf) {
2573 xclose(ipf->fd, "(in child) input file ", ipf->path);
2576 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2577 /* we have no stdio streams that are buffered long-term */
2579 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2582 static void postfork(void) {
2583 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2584 sysdie("(in child) failed to reset SIGPIPE");
2586 postfork_inputfile(main_input_file);
2587 postfork_inputfile(flushing_input_file);
2590 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2591 conn_closefd(conn,"(in child) ");
2593 postfork_stdio(defer, "defer file ", path_defer);
2596 #define EVERY(what, interval_sec, interval_usec, body) \
2597 static struct timeval what##_timeout = { interval_sec, interval_usec }; \
2598 static void what##_schedule(void); \
2599 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2601 what##_schedule(); \
2602 return OOP_CONTINUE; \
2604 static void what##_schedule(void) { \
2605 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2608 EVERY(filepoll, 5,0, ({
2609 if (main_input_file && main_input_file->readable_callback)
2610 filemon_callback(main_input_file);
2613 static char *debug_report_ipf(InputFile *ipf) {
2614 if (!ipf) return xasprintf("none");
2616 const char *slash= strrchr(ipf->path,'/');
2617 const char *path= slash ? slash+1 : ipf->path;
2619 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2621 ipf->inprogress, (long)ipf->offset,
2622 ipf->fd, ipf->rd ? "+" : "");
2625 EVERY(period, -1,0, ({
2626 char *dipf_main= debug_report_ipf(main_input_file);
2627 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2628 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2631 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2632 " input_files main:%s old:%s flushing:%s"
2633 " children connecting=%ld inndcomm=%ld"
2635 sms_names[sms], sm_period_counter,
2636 conns.count, queue.count, until_connect,
2637 dipf_main, dipf_flushing, dipf_backlog,
2638 (long)connecting_child, (long)inndcomm_child
2642 free(dipf_flushing);
2645 if (until_connect) until_connect--;
2647 poll_backlog_file();
2648 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2649 statemc_period_poll();
2650 check_assign_articles();
2655 /*========== option parsing ==========*/
2657 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2658 static void vbadusage(const char *fmt, va_list al) {
2659 char *m= xvasprintf(fmt,al);
2660 fprintf(stderr, "bad usage: %s\n"
2661 "say --help for help, or read the manpage\n",
2664 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2668 /*---------- generic option parser ----------*/
2670 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2671 static void badusage(const char *fmt, ...) {
2678 of_seconds= 001000u,
2679 of_boolean= 002000u,
2682 typedef struct Option Option;
2683 typedef void OptionParser(const Option*, const char *val);
2687 const char *lng, *formarg;
2693 static void parse_options(const Option *options, char ***argvp) {
2694 /* on return *argvp is first non-option arg; argc is not updated */
2697 const char *arg= *++(*argvp);
2699 if (*arg != '-') break;
2700 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2702 while ((a= *++arg)) {
2706 char *equals= strchr(arg,'=');
2707 int len= equals ? (equals - arg) : strlen(arg);
2708 for (o=options; o->shrt || o->lng; o++)
2709 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2711 badusage("unknown long option --%s",arg);
2714 if (equals) badusage("option --%s does not take a value",o->lng);
2716 } else if (equals) {
2720 if (!arg) badusage("option --%s needs a value for %s",
2721 o->lng, o->formarg);
2724 break; /* eaten the whole argument now */
2726 for (o=options; o->shrt || o->lng; o++)
2729 badusage("unknown short option -%c",a);
2736 if (!arg) badusage("option -%c needs a value for %s",
2737 o->shrt, o->formarg);
2740 break; /* eaten the whole argument now */
2746 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
2748 static void print_options(const Option *options, FILE *f) {
2750 for (o=options; o->shrt || o->lng; o++) {
2751 char shrt[2] = { o->shrt, 0 };
2752 char *optspec= xasprintf("%s%s%s%s%s",
2753 o->shrt ? "-" : "", shrt,
2754 o->shrt && o->lng ? "|" : "",
2755 DELIMPERHAPS("--", o->lng));
2756 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
2761 /*---------- specific option types ----------*/
2763 static void op_integer(const Option *o, const char *val) {
2766 unsigned long ul= strtoul(val,&ep,10);
2767 if (*ep || ep==val || errno || ul>INT_MAX)
2768 badusage("bad integer value for %s",o->lng);
2769 int *store= o->store;
2773 static void op_double(const Option *o, const char *val) {
2774 int *store= o->store;
2777 *store= strtod(val, &ep);
2778 if (*ep || ep==val || errno)
2779 badusage("bad floating point value for %s",o->lng);
2782 static void op_string(const Option *o, const char *val) {
2783 const char **store= o->store;
2787 static void op_seconds(const Option *o, const char *val) {
2788 int *store= o->store;
2792 double v= strtod(val,&ep);
2793 if (ep==val) badusage("bad time/duration value for %s",o->lng);
2795 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
2796 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
2797 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
2798 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
2799 else if (!strcmp(ep,"das")) unit= 10;
2800 else if (!strcmp(ep,"hs")) unit= 100;
2801 else if (!strcmp(ep,"ks")) unit= 1000;
2802 else if (!strcmp(ep,"Ms")) unit= 1000000;
2803 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2807 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2811 static void op_setint(const Option *o, const char *val) {
2812 int *store= o->store;
2816 /*---------- specific options ----------*/
2818 static void help(const Option *o, const char *val);
2820 static const Option innduct_options[]= {
2821 {'f',"feedfile", "F", &feedfile, op_string },
2822 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
2823 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
2824 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
2825 {0,"inndconf", "F", &inndconffile, op_string },
2826 {'P',"port", "PORT", &port, op_integer },
2827 {0,"help", 0, 0, help },
2829 {0,"max-connections", "N", &max_connections, op_integer },
2830 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
2831 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
2832 {0,"period-interval", "TIME", &period_seconds, op_seconds },
2834 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
2835 {0,"stuck-flush-timeout","TIME", &inndcomm_flush_timeout, op_seconds },
2837 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
2838 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
2840 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
2841 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
2842 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
2843 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
2844 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
2845 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
2847 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
2848 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
2853 static void printusage(FILE *f) {
2854 fputs("usage: innduct [options] site [fqdn]\n"
2855 "available options are:\n", f);
2856 print_options(innduct_options, f);
2859 static void help(const Option *o, const char *val) {
2861 if (ferror(stdout) || fflush(stdout)) {
2862 perror("innduct: writing help");
2868 static void convert_to_periods_rndup(int *store) {
2869 *store += period_seconds-1;
2870 *store /= period_seconds;
2873 int main(int argc, char **argv) {
2879 parse_options(innduct_options, &argv);
2884 if (!sitename) badusage("need site name argument");
2885 remote_host= *argv++;
2886 if (*argv) badusage("too many non-option arguments");
2890 if (!remote_host) remote_host= sitename;
2892 if (nocheck_thresh < 0 || nocheck_thresh > 100)
2893 badusage("nocheck threshold percentage must be between 0..100");
2894 nocheck_thresh *= 0.01;
2896 if (nocheck_decay < 0.1)
2897 badusage("nocheck decay articles must be at least 0.1");
2898 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
2900 convert_to_periods_rndup(&reconnect_delay_periods);
2901 convert_to_periods_rndup(&flushfail_retry_periods);
2902 convert_to_periods_rndup(&backlog_retry_minperiods);
2903 convert_to_periods_rndup(&backlog_spontrescan_periods);
2904 convert_to_periods_rndup(&spontaneous_flush_periods);
2905 convert_to_periods_rndup(&need_activity_periods);
2907 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
2908 badusage("bad input data ratio must be between 0..100");
2909 max_bad_data_ratio *= 0.01;
2912 innconf_read(inndconffile);
2913 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
2914 } else if (!feedfile[0]) {
2915 badusage("feed filename must be nonempty");
2916 } else if (feedfile[strlen(feedfile)-1]=='/') {
2917 feedfile= xasprintf("%s%s",feedfile,sitename);
2920 const char *feedfile_forbidden= "?*[~#";
2922 while ((c= *feedfile_forbidden++))
2923 if (strchr(feedfile, c))
2924 badusage("feed filename may not contain metacharacter %c",c);
2928 path_lock= xasprintf("%s_lock", feedfile);
2929 path_flushing= xasprintf("%s_flushing", feedfile);
2930 path_defer= xasprintf("%s_defer", feedfile);
2931 path_control= xasprintf("%s_control", feedfile);
2932 globpat_backlog= xasprintf("%s_backlog*", feedfile);
2934 oop_source_sys *sysloop= oop_sys_new();
2935 if (!sysloop) sysdie("could not create liboop event loop");
2936 loop= (oop_source*)sysloop;
2938 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2939 sysdie("could not ignore SIGPIPE");
2944 if (become_daemon) {
2946 for (i=3; i<255; i++)
2947 /* do this now before we open syslog, etc. */
2949 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2951 int null= open("/dev/null",O_RDWR);
2952 if (null<0) sysfatal("failed to open /dev/null");
2956 xclose(null, "/dev/null original fd",0);
2958 pid_t child1= xfork("daemonise first fork");
2959 if (child1) _exit(0);
2961 pid_t sid= setsid();
2962 if (sid != child1) sysfatal("setsid failed");
2964 pid_t child2= xfork("daemonise second fork");
2965 if (child2) _exit(0);
2969 if (self_pid==-1) sysdie("getpid");
2977 if (!filemon_method_init()) {
2978 warn("no file monitoring available, polling");
2979 filepoll_schedule();
2982 period_timeout.tv_sec= period_seconds;
2989 void *r= oop_sys_run(sysloop);
2990 assert(r == OOP_ERROR);
2991 sysdie("event loop failed");