3 * - actually do something with readable on control master
4 * - option for realsockdir
5 * - option for filepoll
6 * - option for no inotify
7 * - manpage: document control master stuff
8 * - manpage: innconf is used for communicating with innd
10 * build-lfs/backends/innduct --no-daemon -f `pwd`/fee sit dom
14 * Newsfeeds file entries should look like this:
15 * host.name.of.site[/exclude,exclude,...]\
16 * :pattern,pattern...[/distribution,distribution...]\
20 * sitename[/exclude,exclude,...]\
21 * :pattern,pattern...[/distribution,distribution...]\
27 * or might be blanked out
28 * <spc><spc><spc><spc>....
30 * F site.name main feed file
31 * opened/created, then written, by innd
34 * tokens blanked out by duct when processed
35 * site.name_lock lock preventing multiple ducts
36 * to hold lock must open,F_SETLK[W]
37 * and then stat to check that locked file
38 * still has name site.name_lock
39 * holder of this lock is "duct"
40 * (only) lockholder may remove the lockfile
41 * D site.name_flushing temporary feed file during flush (or crash)
42 * hardlink created by duct
44 * site.name_defer 431'd articles, still being written,
45 * created, written, used by duct
47 * site.name_backlog.<date>.<inum>
48 * 431'd articles, ready for innxmit or duct
49 * created (link/mv) by duct
50 * site.name_backlog<anything-else> (where <anything-else> does not
51 * contain '#' or '~') eg
52 * site.name_backlog.manual
53 * anything the sysadmin likes (eg, feed files
54 * from old feeds to be merged into this one)
55 * created (link/mv) by admin
56 * may be symlinks (in which case links
57 * may be written through, but only links
60 * It is safe to remove backlog files manually,
61 * if it's desired to throw away the backlog.
63 * Backlog files are also processed by innduct. We find the oldest
64 * backlog file which is at least a certain amount old, and feed it
65 * back into our processing. When every article in it has been read
66 * and processed, we unlink it and look for another backlog file.
68 * If we don't have a backlog file that we're reading, we close the
69 * defer file that we're writing and make it into a backlog file at
70 * the first convenient opportunity.
81 | | <----------------<---------------------------------'|
87 | F: innd writing, duct reading |
90 | | duct decides time to flush |
91 | | duct makes hardlink |
93 | V <------------------------'|
95 | F == D: innd writing, duct reading both exist |
98 | | <-----------<-------------<--'|
102 | V <---------------------. |
105 | D: innd writing, duct reading; or ENOENT | |
107 | | duct requests flush of feed | |
108 | | (others can too, harmlessly) | |
112 | D: innd flushing, duct; or ENOENT | |
114 | | inndcomm flush fails | |
115 | |`-------------------------->------------------' |
117 | | inndcomm reports no such site |
118 | |`---------------------------------------------------- | -.
120 | | innd finishes writing D, creates F | |
121 | | inndcomm reports flush successful | |
124 | Separated <----------------' |
125 | F: innd writing F!=D /
126 | D: duct reading; or ENOENT both exist /
128 | | duct gets to the end of D /
129 | | duct opens F too /
132 | F: innd writing, duct reading |
133 | D: duct finishing V
135 | | duct finishes processing D F: ENOENT
136 | V duct unlinks D D: duct reading
138 `--<--' | duct finishes
148 "duct reading" means innduct is reading the file but also
149 overwriting processed tokens.
153 * rune for printing diagrams:
155 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
160 /*============================== PROGRAM ==============================*/
162 #define _GNU_SOURCE 1
168 #include "inndcomm.h"
170 #include "inn/list.h"
171 #include "inn/innconf.h"
174 #include <sys/types.h>
175 #include <sys/wait.h>
176 #include <sys/stat.h>
177 #include <sys/socket.h>
196 #include <oop-read.h>
198 /*----- general definitions, probably best not changed -----*/
200 #define CONNCHILD_ESTATUS_STREAM 24
201 #define CONNCHILD_ESTATUS_NOSTREAM 25
203 #define INNDCOMMCHILD_ESTATUS_FAIL 26
204 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
206 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
207 #define MAX_CONTROL_COMMAND 1000
209 #define VA va_list al; va_start(al,fmt)
210 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
211 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
213 /*----- doubly linked lists -----*/
215 #define ISNODE(T) struct node list_node
218 union { struct list li; T *for_type; } u; \
222 #define NODE(n) (assert((void*)&(n)->list_node == (n)), &(n)->list_node)
224 #define LIST_CHECKCANHAVENODE(l,n) \
225 ((void)((n) == ((l).u.for_type))) /* just for the type check */
227 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
228 ( LIST_CHECKCANHAVENODE(l,n), \
229 list_addsomehow(&(l).u.li, NODE((n))), \
233 #define LIST_REMSOMEHOW(l,list_remsomehow) \
234 ( (typeof((l).u.for_type)) \
237 list_remsomehow(&(l).u.li) ) \
243 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
244 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
245 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
246 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
248 #define LIST_INIT(l) ((l).count=0, list_new(&(l).u.li))
249 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
250 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
251 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
253 #define LIST_REMOVE(l,n) \
254 ( LIST_CHECKCANHAVENODE(l,n), \
255 list_remove(NODE((n))), \
259 #define LIST_INSERT(l,n,pred) \
260 ( LIST_CHECKCANHAVENODE(l,n), \
261 LIST_CHECKCANHAVENODE(l,pred), \
262 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
266 /*----- type predeclarations -----*/
268 typedef struct Conn Conn;
269 typedef struct Article Article;
270 typedef struct InputFile InputFile;
271 typedef struct XmitDetails XmitDetails;
272 typedef struct Filemon_Perfile Filemon_Perfile;
273 typedef enum StateMachineState StateMachineState;
278 /*----- function predeclarations -----*/
280 static void conn_maybe_write(Conn *conn);
281 static void conn_make_some_xmits(Conn *conn);
282 static void *conn_write_some_xmits(Conn *conn);
284 static void xmit_free(XmitDetails *d);
286 #define SMS(newstate, periods, why) \
287 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
288 static void statemc_setstate(StateMachineState newsms, int periods,
289 const char *forlog, const char *why);
291 static void statemc_start_flush(const char *why); /* Normal => Flushing */
292 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
294 static void article_done(Conn *conn, Article *art, int whichcount);
296 static void check_assign_articles(void);
297 static void queue_check_input_done(void);
299 static void statemc_check_flushing_done(void);
300 static void statemc_check_backlog_done(void);
302 static void postfork(void);
303 static void period(void);
305 static void open_defer(void);
306 static void close_defer(void);
307 static void search_backlog_file(void);
309 static void inputfile_reading_start(InputFile *ipf);
310 static void inputfile_reading_stop(InputFile *ipf);
312 static void filemon_start(InputFile *ipf);
313 static void filemon_stop(InputFile *ipf);
314 static void filemon_callback(InputFile *ipf);
316 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
317 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
319 static const oop_rd_style peer_rd_style;
320 static oop_rd_call peer_rd_err, peer_rd_ok;
322 /*----- configuration options -----*/
323 /* when changing defaults, remember to update the manpage */
325 static const char *sitename, *remote_host;
326 static const char *feedfile, *realsockdir="/tmp/innduct.control";
327 static int quiet_multiple=0;
328 static int become_daemon=1;
329 static int try_stream=1;
331 static const char *inndconffile;
333 static int max_connections=10;
334 static int max_queue_per_conn=200;
335 static int target_max_feedfile_size=100000;
336 static int period_seconds=60;
338 static int connection_setup_timeout=200;
339 static int inndcomm_flush_timeout=100;
341 static double nocheck_thresh= 95.0; /* converted from percentage by main */
342 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
344 /* all these are initialised to seconds, and converted to periods in main */
345 static int reconnect_delay_periods=1000;
346 static int flushfail_retry_periods=1000;
347 static int backlog_retry_minperiods=50;
348 static int backlog_spontrescan_periods=300;
349 static int spontaneous_flush_periods=100000;
350 static int need_activity_periods=1000;
352 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
353 static int max_bad_data_initial= 30;
354 /* in one corrupt 4096-byte block the number of newlines has
355 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
358 /*----- statistics -----*/
360 typedef enum { /* in queue in conn->sent */
361 art_Unchecked, /* not checked, not sent checking */
362 art_Wanted, /* checked, wanted sent body as requested */
363 art_Unsolicited, /* - sent body without check */
367 #define RESULT_COUNTS(RCS,RCN) \
376 #define RCI_TRIPLE_FMT_BASE "%d(%did+%dbd+%dnc)"
377 #define RCI_TRIPLE_VALS_BASE(counts,x) \
378 counts[art_Unchecked] x \
379 + counts[art_Wanted] x \
380 + counts[art_Unsolicited] x, \
381 counts[art_Unchecked] x \
382 , counts[art_Wanted] x \
383 , counts[art_Unsolicited] x
386 #define RC_INDEX(x) RC_##x,
387 RESULT_COUNTS(RC_INDEX, RC_INDEX)
392 /*----- transmission buffers -----*/
397 xk_Malloc, xk_Const, xk_Artdata
409 /*----- core operational data structure types -----*/
412 /* This is also an instance of struct oop_readable */
413 struct oop_readable readable; /* first */
414 oop_readable_call *readable_callback;
415 void *readable_callback_user;
418 Filemon_Perfile *filemon;
420 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
421 long inprogress; /* no. of articles read but not processed */
425 int counts[art_MaxState][RCI_max];
426 int readcount_ok, readcount_blank, readcount_err;
441 #define SMS_LIST(X) \
449 enum StateMachineState {
450 #define SMS_DEF_ENUM(s) sm_##s,
451 SMS_LIST(SMS_DEF_ENUM)
454 static const char *sms_names[]= {
455 #define SMS_DEF_NAME(s) #s ,
456 SMS_LIST(SMS_DEF_NAME)
462 int fd; /* may be 0, meaning closed (during construction/destruction) */
463 oop_read *rd; /* likewise */
464 int max_queue, stream, quitting;
465 int since_activity; /* periods */
466 ArticleList waiting; /* not yet told peer */
467 ArticleList priority; /* peer says send it now */
468 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
469 struct iovec xmit[CONNIOVS];
470 XmitDetails xmitd[CONNIOVS];
475 /*----- general operational variables -----*/
477 /* main initialises */
478 static oop_source *loop;
479 static ConnList conns;
480 static ArticleList queue;
481 static char *path_lock, *path_flushing, *path_defer, *path_control;
482 static char *globpat_backlog;
483 static pid_t self_pid;
485 /* statemc_init initialises */
486 static StateMachineState sms;
488 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
489 static int sm_period_counter;
491 /* initialisation to 0 is good */
492 static int until_connect, until_backlog_nextscan;
493 static double accept_proportion;
494 static int nocheck, nocheck_reported;
496 /* for simulation, debugging, etc. */
497 int simulate_flush= -1;
499 /*========== logging ==========*/
501 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
502 static void logcore(int sysloglevel, const char *fmt, ...) {
505 vsyslog(sysloglevel,fmt,al);
507 if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
508 vfprintf(stderr,fmt,al);
514 static void logv(int sysloglevel, const char *pfx, int errnoval,
515 const char *fmt, va_list al) PRINTF(5,0);
516 static void logv(int sysloglevel, const char *pfx, int errnoval,
517 const char *fmt, va_list al) {
518 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
519 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
520 msgbuf[sizeof(msgbuf)-1]= 0;
522 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
523 sysloglevel= LOG_ERR; /* run by wrong user, probably */
525 logcore(sysloglevel, "<%s>%s: %s%s%s",
526 sitename, pfx, msgbuf,
527 errnoval>=0 ? ": " : "",
528 errnoval>=0 ? strerror(errnoval) : "");
531 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
532 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
533 static void fn(const char *fmt, ...) { \
535 logv(sysloglevel, pfx, err, fmt, al); \
539 #define logwrap(fn, pfx, sysloglevel, err) \
540 static void fn(const char *fmt, ...) PRINTF(1,2); \
541 static void fn(const char *fmt, ...) { \
543 logv(sysloglevel, pfx, err, fmt, al); \
547 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
548 diewrap(die, " critical", LOG_CRIT, -1, 16);
550 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
551 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
553 logwrap(syswarn, " warning", LOG_WARNING, errno);
554 logwrap(warn, " warning", LOG_WARNING, -1);
556 logwrap(notice, " notice", LOG_NOTICE, -1);
557 logwrap(info, " info", LOG_INFO, -1);
558 logwrap(debug, " debug", LOG_DEBUG, -1);
561 /*========== utility functions etc. ==========*/
563 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
564 static char *xvasprintf(const char *fmt, va_list al) {
566 int rc= vasprintf(&str,fmt,al);
567 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
570 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
571 static char *xasprintf(const char *fmt, ...) {
573 char *str= xvasprintf(fmt,al);
578 static int close_perhaps(int *fd) {
579 if (*fd <= 0) return 0;
584 static void xclose(int fd, const char *what, const char *what2) {
586 if (r) sysdie("close %s%s",what,what2?what2:"");
588 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
589 if (*fd <= 0) return;
590 xclose(*fd,what,what2);
594 static pid_t xfork(const char *what) {
598 if (child==-1) sysfatal("cannot fork for %s",what);
599 debug("forked %s %ld", what, (unsigned long)child);
600 if (!child) postfork();
604 static void on_fd_read_except(int fd, oop_call_fd callback) {
605 loop->on_fd(loop, fd, OOP_READ, callback, 0);
606 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
608 static void cancel_fd_read_except(int fd) {
609 loop->cancel_fd(loop, fd, OOP_READ);
610 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
613 static void report_child_status(const char *what, int status) {
614 if (WIFEXITED(status)) {
615 int es= WEXITSTATUS(status);
617 warn("%s: child died with error exit status %d", what, es);
618 } else if (WIFSIGNALED(status)) {
619 int sig= WTERMSIG(status);
620 const char *sigstr= strsignal(sig);
621 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
623 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
625 warn("%s: child died due to unknown fatal signal %d%s",
626 what, sig, coredump);
628 warn("%s: child died with unknown wait status %d", what,status);
632 static int xwaitpid(pid_t *pid, const char *what) {
635 int r= kill(*pid, SIGKILL);
636 if (r) sysdie("cannot kill %s child", what);
638 pid_t got= waitpid(*pid, &status, 0);
639 if (got==-1) sysdie("cannot reap %s child", what);
640 if (got==0) die("cannot reap %s child", what);
647 static void xunlink(const char *path, const char *what) {
649 if (r) sysdie("can't unlink %s %s", path, what);
652 static time_t xtime(void) {
654 if (now==-1) sysdie("time(2) failed");
658 static void xgettimeofday(struct timeval *tv_r) {
659 int r= gettimeofday(tv_r,0);
660 if (r) sysdie("gettimeofday(2) failed");
663 static void xsetnonblock(int fd, int nonblocking) {
664 int errnoval= oop_fd_nonblock(fd, nonblocking);
665 if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
668 static void check_isreg(const struct stat *stab, const char *path,
670 if (!S_ISREG(stab->st_mode))
671 die("%s %s not a plain file (mode 0%lo)",
672 what, path, (unsigned long)stab->st_mode);
675 static void xfstat(int fd, struct stat *stab_r, const char *what) {
676 int r= fstat(fd, stab_r);
677 if (r) sysdie("could not fstat %s", what);
680 static void xfstat_isreg(int fd, struct stat *stab_r,
681 const char *path, const char *what) {
682 xfstat(fd, stab_r, what);
683 check_isreg(stab_r, path, what);
686 static void xlstat_isreg(const char *path, struct stat *stab,
687 int *enoent_r /* 0 means ENOENT is fatal */,
689 int r= lstat(path, stab);
691 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
692 sysdie("could not lstat %s %s", what, path);
694 if (enoent_r) *enoent_r= 0;
695 check_isreg(stab, path, what);
698 static int samefile(const struct stat *a, const struct stat *b) {
699 assert(S_ISREG(a->st_mode));
700 assert(S_ISREG(b->st_mode));
701 return (a->st_ino == b->st_ino &&
702 a->st_dev == b->st_dev);
705 static char *sanitise(const char *input) {
706 static char sanibuf[100]; /* returns pointer to this buffer! */
708 const char *p= input;
712 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
714 if (!c) { *q++= '\''; *q=0; break; }
715 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
716 sprintf(q,"\\x%02x",c);
722 static int isewouldblock(int errnoval) {
723 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
727 /*========== command and control connections ==========*/
729 static int control_master;
731 typedef struct ControlConn ControlConn;
733 void (*destroy)(ControlConn*);
739 struct sockaddr_un un;
744 static const oop_rd_style control_rd_style= {
745 OOP_RD_DELIM_STRIP, '\n',
747 OOP_RD_SHORTREC_FORBID
750 static void control_destroy(ControlConn *cc) {
754 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
755 if (ferror(cc->out) | fflush(cc->out)) {
756 info("CTRL%d write error %s", cc->fd, strerror(errno));
761 static void control_prompt(ControlConn *cc /* may destroy*/) {
762 fprintf(cc->out, "%s| ", sitename);
763 control_checkouterr(cc);
766 typedef struct ControlCommand ControlCommand;
767 struct ControlCommand {
769 void (*f)(ControlConn *cc, const ControlCommand *ccmd,
770 const char *arg, size_t argsz);
775 static const ControlCommand control_commands[];
778 static void ccmd_##wh(ControlConn *cc, const ControlCommand *c, \
779 const char *arg, size_t argsz)
782 fputs("commands:\n", cc->out);
783 const ControlCommand *ccmd;
784 for (ccmd=control_commands; ccmd->cmd; ccmd++)
785 fprintf(cc->out, " %s\n", ccmd->cmd);
788 CCMD(period) { period(); }
789 CCMD(setintarg) { *(int*)c->xdata= atoi(arg); }
790 CCMD(setint) { *(int*)c->xdata= c->xval; }
792 static const ControlCommand control_commands[]= {
794 { "p", ccmd_period },
795 { "pretend flush", ccmd_setintarg, &simulate_flush },
796 { "poke sm", ccmd_setint, &sm_period_counter, 1 },
797 { "poke conn", ccmd_setint, &until_connect, 0 },
798 { "poke blscan", ccmd_setint, &until_backlog_nextscan, 0 },
799 { "wedge blscan", ccmd_setint, &until_backlog_nextscan, -1 },
803 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
804 const char *errmsg, int errnoval,
805 const char *data, size_t recsz, void *cc_v) {
806 ControlConn *cc= cc_v;
809 info("CTRL%d closed", cc->fd);
814 if (recsz == 0) goto prompt;
816 const ControlCommand *ccmd;
817 for (ccmd=control_commands; ccmd->cmd; ccmd++) {
818 int l= strlen(ccmd->cmd);
819 if (recsz < l) continue;
820 if (recsz > l && data[l] != ' ') continue;
821 if (memcmp(data, ccmd->cmd, l)) continue;
823 int argl= (int)recsz - (l+1);
824 ccmd->f(cc, ccmd, argl>=0 ? data+l+1 : 0, argl);
828 fputs("unknown command; h for help\n", cc->out);
835 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
836 const char *errmsg, int errnoval,
837 const char *data, size_t recsz, void *cc_v) {
838 ControlConn *cc= cc_v;
840 info("CTRL%d read error %s", cc->fd, errmsg);
845 static int control_conn_startup(ControlConn *cc /* may destroy*/,
847 cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
848 if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
850 int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
853 if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
855 info("CTRL%d %s ready", cc->fd, how);
860 static void control_stdio_destroy(ControlConn *cc) {
862 oop_rd_cancel(cc->rd);
863 errno= oop_rd_delete_tidy(cc->rd);
864 if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
869 static void control_stdio(void) {
870 ControlConn *cc= xmalloc(sizeof(*cc));
871 memset(cc,0,sizeof(*cc));
872 cc->destroy= control_stdio_destroy;
876 int r= control_conn_startup(cc,"stdio");
877 if (r) cc->destroy(cc);
880 static void control_accepted_destroy(ControlConn *cc) {
882 oop_rd_cancel(cc->rd);
883 oop_rd_delete_kill(cc->rd);
885 if (cc->out) { fclose(cc->out); cc->fd=0; }
886 close_perhaps(&cc->fd);
890 static void *control_master_readable(oop_source *lp, int master,
891 oop_event ev, void *u) {
892 ControlConn *cc= xmalloc(sizeof(*cc));
893 memset(cc,0,sizeof(*cc));
894 cc->destroy= control_accepted_destroy;
896 cc->salen= sizeof(cc->sa);
897 cc->fd= accept(master, &cc->sa.sa, &cc->salen);
898 if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
900 cc->out= fdopen(cc->fd, "w");
901 if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
903 int r= control_conn_startup(cc, "accepted");
913 #define NOCONTROL(...) do{ \
914 syswarn("no control socket, because failed to " __VA_ARGS__); \
918 static void control_init(void) {
923 struct sockaddr_un un;
926 memset(&sa,0,sizeof(sa));
927 int maxlen= sizeof(sa.un.sun_path);
929 int reallen= readlink(path_control, sa.un.sun_path, maxlen);
932 NOCONTROL("readlink control socket symlink path %s", path_control);
934 if (reallen >= maxlen) {
935 debug("control socket symlink path too long (r=%d)",reallen);
936 xunlink(path_control, "old (overlong) control socket symlink");
942 int r= lstat(realsockdir,&stab);
944 if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
946 r= mkdir(realsockdir, 0700);
947 if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
950 uid_t self= geteuid();
951 if (!S_ISDIR(stab.st_mode) ||
952 stab.st_uid != self ||
953 stab.st_mode & 0077) {
954 warn("no control socket, because real socket directory"
955 " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
956 !!S_ISDIR(stab.st_mode),
957 (unsigned long)stab.st_uid, (unsigned long)self,
958 (unsigned long)stab.st_mode & 0777UL);
963 real= xasprintf("%s/s%lx.%lx", realsockdir,
964 (unsigned long)xtime(), (unsigned long)self_pid);
965 int reallen= strlen(real);
967 if (reallen >= maxlen) {
968 warn("no control socket, because tmpnam gave overly-long path"
972 r= symlink(real, path_control);
973 if (r) NOCONTROL("make control socket path %s a symlink to real"
974 " socket path %s", path_control, real);
975 memcpy(sa.un.sun_path, real, reallen);
978 int r= unlink(sa.un.sun_path);
979 if (r && errno!=ENOENT)
980 NOCONTROL("remove old real socket %s", sa.un.sun_path);
982 control_master= socket(PF_UNIX, SOCK_STREAM, 0);
983 if (control_master<0) NOCONTROL("create new control socket");
985 sa.un.sun_family= AF_UNIX;
986 int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
987 r= bind(control_master, &sa.sa, sl);
988 if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
990 r= listen(control_master, 5);
991 if (r) NOCONTROL("listen");
993 xsetnonblock(control_master, 1);
995 loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
996 info("control socket ok, real path %s", sa.un.sun_path);
1002 xclose_perhaps(&control_master, "control master",0);
1006 /*========== management of connections ==========*/
1008 static void conn_closefd(Conn *conn, const char *msgprefix) {
1009 int r= close_perhaps(&conn->fd);
1010 if (r) info("C%d %serror closing socket: %s",
1011 conn->fd, msgprefix, strerror(errno));
1014 static void conn_dispose(Conn *conn) {
1017 oop_rd_cancel(conn->rd);
1018 oop_rd_delete_kill(conn->rd);
1022 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1023 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
1025 conn_closefd(conn,"");
1027 until_connect= reconnect_delay_periods;
1030 static void *conn_exception(oop_source *lp, int fd,
1031 oop_event ev, void *conn_v) {
1034 assert(fd == conn->fd);
1035 assert(ev == OOP_EXCEPTION);
1036 int r= read(conn->fd, &ch, 1);
1037 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1038 else connfail(conn,"exceptional condition on socket (peer sent urgent"
1039 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1040 return OOP_CONTINUE;
1043 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1044 int requeue[art_MaxState];
1045 memset(requeue,0,sizeof(requeue));
1048 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1049 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1050 while ((art= LIST_REMHEAD(conn->sent))) {
1051 requeue[art->state]++;
1052 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1053 LIST_ADDTAIL(queue,art);
1058 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1061 char *m= xvasprintf(fmt,al);
1062 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1063 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1066 LIST_REMOVE(conns,conn);
1068 check_assign_articles();
1071 static void connfail(Conn *conn, const char *fmt, ...) {
1074 vconnfail(conn,fmt,al);
1078 static void check_idle_conns(void) {
1080 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
1081 conn->since_activity++;
1083 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
1084 if (conn->since_activity <= need_activity_periods) continue;
1086 /* We need to shut this down */
1088 connfail(conn,"timed out waiting for response to QUIT");
1089 else if (conn->sent.count)
1090 connfail(conn,"timed out waiting for responses");
1091 else if (conn->waiting.count || conn->priority.count)
1092 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1093 else if (conn->xmitu)
1094 connfail(conn,"peer has been sending responses"
1095 " before receiving our commands!");
1097 static const char quitcmd[]= "QUIT\r\n";
1098 int todo= sizeof(quitcmd)-1;
1099 const char *p= quitcmd;
1101 int r= write(conn->fd, p, todo);
1103 if (isewouldblock(errno))
1104 connfail(conn, "blocked writing QUIT to idle connection");
1106 connfail(conn, "failed to write QUIT to idle connection: %s",
1114 conn->since_activity= 0;
1115 debug("C%d is idle, quitting", conn->fd);
1124 /*---------- making new connections ----------*/
1126 static pid_t connecting_child;
1127 static int connecting_fdpass_sock;
1129 static void connect_attempt_discard(void) {
1130 if (connecting_child) {
1131 int status= xwaitpid(&connecting_child, "connect");
1132 if (!(WIFEXITED(status) ||
1133 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1134 report_child_status("connect", status);
1136 if (connecting_fdpass_sock) {
1137 cancel_fd_read_except(connecting_fdpass_sock);
1138 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1142 #define PREP_DECL_MSG_CMSG(msg) \
1144 struct iovec msgiov; \
1145 msgiov.iov_base= &msgbyte; \
1146 msgiov.iov_len= 1; \
1147 struct msghdr msg; \
1148 memset(&msg,0,sizeof(msg)); \
1149 char msg##cbuf[CMSG_SPACE(sizeof(int))]; \
1150 msg.msg_iov= &msgiov; \
1151 msg.msg_iovlen= 1; \
1152 msg.msg_control= msg##cbuf; \
1153 msg.msg_controllen= sizeof(msg##cbuf);
1155 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1158 assert(fd == connecting_fdpass_sock);
1160 PREP_DECL_MSG_CMSG(msg);
1162 ssize_t rs= recvmsg(fd, &msg, 0);
1164 if (isewouldblock(errno)) return OOP_CONTINUE;
1165 syswarn("failed to read socket from connecting child");
1169 conn= xmalloc(sizeof(*conn));
1170 memset(conn,0,sizeof(*conn));
1171 LIST_INIT(conn->waiting);
1172 LIST_INIT(conn->priority);
1173 LIST_INIT(conn->sent);
1175 struct cmsghdr *h= 0;
1176 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1178 int status= xwaitpid(&connecting_child, "connect child (broken)");
1180 if (WIFEXITED(status)) {
1181 if (WEXITSTATUS(status) != 0 &&
1182 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1183 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1184 /* child already reported the problem */;
1186 if (e == OOP_EXCEPTION)
1187 warn("connect: connection child exited code %d but"
1188 " unexpected exception on fdpass socket",
1189 WEXITSTATUS(status));
1191 warn("connect: connection child exited code %d but"
1193 WEXITSTATUS(status), (int)rs);
1195 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1196 warn("connect: connection attempt timed out");
1198 report_child_status("connect", status);
1203 #define CHK(field, val) \
1204 if (h->cmsg_##field != val) { \
1205 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1206 h->cmsg_##field, val); \
1209 CHK(level, SOL_SOCKET);
1210 CHK(type, SCM_RIGHTS);
1211 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1214 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1216 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1219 pid_t got= waitpid(connecting_child, &status, 0);
1220 if (got==-1) sysdie("connect: real wait for child");
1221 assert(got == connecting_child);
1222 connecting_child= 0;
1224 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1225 int es= WEXITSTATUS(status);
1227 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1228 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1230 fatal("connect: child gave unexpected exit status %d", es);
1234 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1236 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1237 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1238 if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1239 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1241 &peer_rd_err, conn);
1242 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1244 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1245 LIST_ADDHEAD(conns, conn);
1247 connect_attempt_discard();
1248 check_assign_articles();
1249 return OOP_CONTINUE;
1253 connect_attempt_discard();
1254 return OOP_CONTINUE;
1257 static int allow_connect_start(void) {
1258 return conns.count < max_connections
1259 && !connecting_child
1263 static void connect_start(void) {
1264 assert(!connecting_child);
1265 assert(!connecting_fdpass_sock);
1267 info("starting connection attempt");
1270 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1271 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1273 connecting_child= xfork("connection");
1275 if (!connecting_child) {
1276 FILE *cn_from, *cn_to;
1277 char buf[NNTP_STRLEN+100];
1278 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1280 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1282 alarm(connection_setup_timeout);
1283 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1287 unsigned char c= buf[l-1];
1288 if (!isspace(c)) break;
1289 if (c=='\n' || c=='\r') stripped=1;
1293 sysfatal("connect: connection attempt failed");
1296 fatal("connect: %s: %s", stripped ? "rejected" : "failed",
1300 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1301 sysfatal("connect: authentication failed");
1303 if (fputs("MODE STREAM\r\n", cn_to)==EOF ||
1305 sysfatal("connect: could not send MODE STREAM");
1306 buf[sizeof(buf)-1]= 0;
1307 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1308 if (ferror(cn_from))
1309 sysfatal("connect: could not read response to MODE STREAM");
1311 fatal("connect: connection close in response to MODE STREAM");
1316 fatal("connect: response to MODE STREAM is too long: %.100s...",
1318 l--; if (l>0 && buf[l-1]=='\r') l--;
1321 int rcode= strtoul(buf,&ep,10);
1323 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
1327 exitstatus= CONNCHILD_ESTATUS_STREAM;
1333 warn("connect: unexpected response to MODE STREAM: %.50s",
1339 int fd= fileno(cn_from);
1341 PREP_DECL_MSG_CMSG(msg);
1342 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1343 cmsg->cmsg_level= SOL_SOCKET;
1344 cmsg->cmsg_type= SCM_RIGHTS;
1345 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1346 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1348 msg.msg_controllen= cmsg->cmsg_len;
1349 r= sendmsg(socks[1], &msg, 0);
1350 if (r<0) sysdie("sendmsg failed for new connection");
1351 if (r!=1) die("sendmsg for new connection gave wrong result %d",r);
1356 xclose(socks[1], "connecting fdpass child's socket",0);
1357 connecting_fdpass_sock= socks[0];
1358 xsetnonblock(connecting_fdpass_sock, 1);
1359 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1362 /*---------- assigning articles to conns, and transmitting ----------*/
1364 static void check_assign_articles(void) {
1370 int spare=0, inqueue=0;
1372 /* Find a connection to offer this article. We prefer a busy
1373 * connection to an idle one, provided it's not full. We take the
1374 * first (oldest) and since that's stable, it will mean we fill up
1375 * connections in order. That way if we have too many
1376 * connections, the spare ones will go away eventually.
1378 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1379 if (walk->quitting) continue;
1380 inqueue= walk->sent.count + walk->priority.count
1381 + walk->waiting.count;
1382 spare= walk->max_queue - inqueue;
1383 assert(inqueue <= max_queue_per_conn);
1385 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1386 else if (spare>0) /*working*/ { use= walk; break; }
1389 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1391 Article *art= LIST_REMHEAD(queue);
1393 LIST_ADDTAIL(use->waiting, art);
1396 conn_maybe_write(use);
1397 } else if (allow_connect_start()) {
1398 until_connect= reconnect_delay_periods;
1407 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1408 conn_maybe_write(u);
1409 return OOP_CONTINUE;
1412 static void conn_maybe_write(Conn *conn) {
1414 conn_make_some_xmits(conn);
1416 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1420 void *rp= conn_write_some_xmits(conn);
1421 if (rp==OOP_CONTINUE) {
1422 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1424 } else if (rp==OOP_HALT) {
1427 /* transmitted everything */
1434 /*========== article transmission ==========*/
1436 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1437 XmitKind kind) { /* caller must then fill in details */
1438 struct iovec *v= &conn->xmit[conn->xmitu];
1439 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1440 v->iov_base= (char*)data;
1446 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1447 xmit_core(conn,data,len, xk_Const);
1449 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1451 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1452 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1456 static void xmit_free(XmitDetails *d) {
1458 case xk_Malloc: free(d->info.malloc_tofree); break;
1459 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1460 case xk_Const: break;
1465 static void *conn_write_some_xmits(Conn *conn) {
1467 * 0: nothing more to write, no need to call us again
1468 * OOP_CONTINUE: more to write but fd not writeable
1469 * OOP_HALT: disaster, have destroyed conn
1472 int count= conn->xmitu;
1473 if (!count) return 0;
1475 if (count > IOV_MAX) count= IOV_MAX;
1476 ssize_t rs= writev(conn->fd, conn->xmit, count);
1478 if (isewouldblock(errno)) return OOP_CONTINUE;
1479 connfail(conn, "write failed: %s", strerror(errno));
1485 for (done=0; rs && done<conn->xmitu; done++) {
1486 struct iovec *vp= &conn->xmit[done];
1487 XmitDetails *dp= &conn->xmitd[done];
1488 if (rs > vp->iov_len) {
1492 vp->iov_base= (char*)vp->iov_base + rs;
1496 int newu= conn->xmitu - done;
1497 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1498 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1503 static void conn_make_some_xmits(Conn *conn) {
1505 if (conn->xmitu+5 > CONNIOVS)
1508 Article *art= LIST_REMHEAD(conn->priority);
1509 if (!art) art= LIST_REMHEAD(conn->waiting);
1512 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1513 /* actually send it */
1515 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1518 art->state == art_Unchecked ? art_Unsolicited :
1519 art->state == art_Wanted ? art_Wanted :
1522 if (!artdata) art->missing= 1;
1523 art->ipf->counts[art->state][ artdata ? RC_sent : RC_missing ]++;
1527 XMIT_LITERAL("TAKETHIS ");
1528 xmit_noalloc(conn, art->messageid, art->midlen);
1529 XMIT_LITERAL("\r\n");
1530 xmit_artbody(conn, artdata);
1532 article_done(conn, art, -1);
1536 /* we got 235 from IHAVE */
1538 xmit_artbody(conn, artdata);
1540 XMIT_LITERAL(".\r\n");
1544 LIST_ADDTAIL(conn->sent, art);
1550 XMIT_LITERAL("CHECK ");
1552 XMIT_LITERAL("IHAVE ");
1553 xmit_noalloc(conn, art->messageid, art->midlen);
1554 XMIT_LITERAL("\r\n");
1556 assert(art->state == art_Unchecked);
1557 art->ipf->counts[art->state][RC_sent]++;
1558 LIST_ADDTAIL(conn->sent, art);
1564 /*========== handling responses from peer ==========*/
1566 static const oop_rd_style peer_rd_style= {
1567 OOP_RD_DELIM_STRIP, '\n',
1569 OOP_RD_SHORTREC_FORBID
1572 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1573 const char *errmsg, int errnoval,
1574 const char *data, size_t recsz, void *conn_v) {
1576 connfail(conn, "error receiving from peer: %s", errmsg);
1577 return OOP_CONTINUE;
1580 static Article *article_reply_check(Conn *conn, const char *response,
1581 int code_indicates_streaming,
1583 /* 1:yes, -1:no, 0:dontcare */,
1584 const char *sanitised_response) {
1585 Article *art= LIST_HEAD(conn->sent);
1589 "peer gave unexpected response when no commands outstanding: %s",
1590 sanitised_response);
1594 if (code_indicates_streaming) {
1595 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1596 if (!conn->stream) {
1597 connfail(conn, "peer gave streaming response code "
1598 " to IHAVE or subsequent body: %s", sanitised_response);
1601 const char *got_mid= response+4;
1602 int got_midlen= strcspn(got_mid, " \n\r");
1603 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1604 connfail(conn, "peer gave streaming response with syntactically invalid"
1605 " messageid: %s", sanitised_response);
1608 if (got_midlen != art->midlen ||
1609 memcmp(got_mid, art->messageid, got_midlen)) {
1610 connfail(conn, "peer gave streaming response code to wrong article -"
1611 " probable synchronisation problem; we offered: %s;"
1613 art->messageid, sanitised_response);
1618 connfail(conn, "peer gave non-streaming response code to"
1619 " CHECK/TAKETHIS: %s", sanitised_response);
1624 if (must_have_sent>0 && art->state < art_Wanted) {
1625 connfail(conn, "peer says article accepted but"
1626 " we had not sent the body: %s", sanitised_response);
1629 if (must_have_sent<0 && art->state >= art_Wanted) {
1630 connfail(conn, "peer says please sent the article but we just did: %s",
1631 sanitised_response);
1635 Article *art_again= LIST_REMHEAD(conn->sent);
1636 assert(art_again == art);
1640 static void update_nocheck(int accepted) {
1641 accept_proportion *= nocheck_decay;
1642 accept_proportion += accepted * (1.0 - nocheck_decay);
1643 int new_nocheck= accept_proportion >= nocheck_thresh;
1644 if (new_nocheck && !nocheck_reported) {
1645 notice("entering nocheck mode for the first time");
1646 nocheck_reported= 1;
1647 } else if (new_nocheck != nocheck) {
1648 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1650 nocheck= new_nocheck;
1653 static void article_done(Conn *conn, Article *art, int whichcount) {
1654 if (!art->missing) art->ipf->counts[art->state][whichcount]++;
1656 if (whichcount == RC_accepted) update_nocheck(1);
1657 else if (whichcount == RC_unwanted) update_nocheck(0);
1659 InputFile *ipf= art->ipf;
1661 while (art->blanklen) {
1662 static const char spaces[]=
1667 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1668 int r= pwrite(ipf->fd, spaces, w, art->offset);
1670 if (errno==EINTR) continue;
1671 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1672 art->messageid, art->blanklen,
1673 (unsigned long)art->offset, ipf->path);
1675 assert(r>=0 && r<=w);
1681 assert(ipf->inprogress >= 0);
1684 if (!ipf->inprogress && ipf != main_input_file)
1685 queue_check_input_done();
1688 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1689 const char *errmsg, int errnoval,
1690 const char *data, size_t recsz, void *conn_v) {
1693 if (ev == OOP_RD_EOF) {
1694 connfail(conn, "unexpected EOF from peer");
1695 return OOP_CONTINUE;
1697 assert(ev == OOP_RD_OK);
1699 char *sani= sanitise(data);
1702 unsigned long code= strtoul(data, &ep, 10);
1703 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1704 connfail(conn, "badly formatted response from peer: %s", sani);
1705 return OOP_CONTINUE;
1708 if (conn->quitting) {
1709 if (code!=205 && code!=503) {
1710 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1712 notice("C%d idle connection closed", conn->fd);
1713 assert(!conn->waiting.count);
1714 assert(!conn->priority.count);
1715 assert(!conn->sent.count);
1716 assert(!conn->xmitu);
1717 LIST_REMOVE(conns,conn);
1720 return OOP_CONTINUE;
1723 conn->since_activity= 0;
1726 #define GET_ARTICLE(musthavesent) \
1727 art= article_reply_check(conn, data, code_streaming, musthavesent, sani); \
1728 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1730 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1731 code_streaming= (streaming); \
1732 GET_ARTICLE(musthavesent); \
1733 article_done(conn, art, RC_##how); break;
1735 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1737 int code_streaming= 0;
1741 case 400: PEERBADMSG("peer stopped accepting articles");
1742 case 503: PEERBADMSG("peer timed us out");
1743 default: PEERBADMSG("peer sent unexpected message");
1745 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1746 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1748 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1749 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1751 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1752 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1754 case 238: /* CHECK says send it */
1756 case 335: /* IHAVE says send it */
1758 assert(art->state == art_Unchecked);
1759 art->ipf->counts[art->state][RC_accepted]++;
1760 art->state= art_Wanted;
1761 LIST_ADDTAIL(conn->priority, art);
1764 case 431: /* CHECK or TAKETHIS says try later */
1766 case 436: /* IHAVE says try later */
1769 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1771 sysfatal("write to defer file %s",path_defer);
1772 article_done(conn, art, RC_deferred);
1777 conn_maybe_write(conn);
1778 check_assign_articles();
1779 return OOP_CONTINUE;
1783 /*========== monitoring of input files ==========*/
1785 static void feedfile_eof(InputFile *ipf) {
1786 assert(ipf != main_input_file); /* promised by tailing_try_read */
1787 inputfile_reading_stop(ipf);
1789 if (ipf == flushing_input_file) {
1790 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1791 if (main_input_file) inputfile_reading_start(main_input_file);
1792 statemc_check_flushing_done();
1793 } else if (ipf == backlog_input_file) {
1794 statemc_check_backlog_done();
1796 abort(); /* supposed to wait rather than get EOF on main input file */
1800 static InputFile *open_input_file(const char *path) {
1801 int fd= open(path, O_RDONLY);
1803 if (errno==ENOENT) return 0;
1804 sysfatal("unable to open input file %s", path);
1808 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1809 memset(ipf,0,sizeof(*ipf));
1812 strcpy(ipf->path, path);
1817 static void close_input_file(InputFile *ipf) { /* does not free */
1818 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1819 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1820 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1821 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1822 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1826 /*---------- dealing with articles read in the input file ----------*/
1828 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1829 const char *data, const char *how) {
1830 warn("corrupted file: %s, offset %lu: %s: in %s",
1831 ipf->path, (unsigned long)offset, how, sanitise(data));
1832 ipf->readcount_err++;
1833 if (ipf->readcount_err > max_bad_data_initial +
1834 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1835 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1836 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1837 return OOP_CONTINUE;
1840 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1841 oop_rd_event ev, const char *errmsg,
1842 int errnoval, const char *data, size_t recsz,
1844 InputFile *ipf= ipf_v;
1845 assert(ev == OOP_RD_SYSTEM);
1847 sysdie("error reading input file: %s, offset %lu",
1848 ipf->path, (unsigned long)ipf->offset);
1851 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1852 oop_rd_event ev, const char *errmsg,
1853 int errnoval, const char *data, size_t recsz,
1855 InputFile *ipf= ipf_v;
1857 char tokentextbuf[sizeof(TOKEN)*2+3];
1859 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1861 off_t old_offset= ipf->offset;
1862 ipf->offset += recsz + 1;
1864 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1866 if (ev==OOP_RD_PARTREC)
1867 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1868 /* but process it anyway */
1870 if (ipf->skippinglong) {
1871 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1872 return OOP_CONTINUE;
1874 if (ev==OOP_RD_LONG) {
1875 ipf->skippinglong= 1;
1876 X_BAD_DATA("overly long line");
1879 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1880 if (!recsz) X_BAD_DATA("empty line");
1883 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1884 ipf->readcount_blank++;
1885 return OOP_CONTINUE;
1888 char *space= strchr(data,' ');
1889 int tokenlen= space-data;
1890 int midlen= (int)recsz-tokenlen-1;
1891 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1892 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1894 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1895 memcpy(tokentextbuf, data, tokenlen);
1896 tokentextbuf[tokenlen]= 0;
1897 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1899 ipf->readcount_ok++;
1901 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1902 art->state= art_Unchecked;
1903 art->midlen= midlen;
1904 art->ipf= ipf; ipf->inprogress++;
1905 art->token= TextToToken(tokentextbuf);
1906 art->offset= ipf->offset;
1907 art->blanklen= recsz;
1908 strcpy(art->messageid, space+1);
1909 LIST_ADDTAIL(queue, art);
1911 if (sms==sm_NORMAL && ipf==main_input_file &&
1912 ipf->offset >= target_max_feedfile_size)
1913 statemc_start_flush("feed file size");
1915 check_assign_articles();
1916 return OOP_CONTINUE;
1919 /*========== tailing input file ==========*/
1921 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1923 InputFile *ipf= user;
1924 return ipf->readable_callback(loop, &ipf->readable,
1925 ipf->readable_callback_user);
1928 static void tailing_on_cancel(struct oop_readable *rable) {
1929 InputFile *ipf= (void*)rable;
1931 if (ipf->filemon) filemon_stop(ipf);
1932 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1933 ipf->readable_callback= 0;
1936 static void tailing_queue_readable(InputFile *ipf) {
1937 /* lifetime of ipf here is OK because destruction will cause
1938 * on_cancel which will cancel this callback */
1939 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1942 static int tailing_on_readable(struct oop_readable *rable,
1943 oop_readable_call *cb, void *user) {
1944 InputFile *ipf= (void*)rable;
1946 tailing_on_cancel(rable);
1947 ipf->readable_callback= cb;
1948 ipf->readable_callback_user= user;
1951 tailing_queue_readable(ipf);
1955 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1957 InputFile *ipf= (void*)rable;
1959 ssize_t r= read(ipf->fd, buffer, length);
1961 if (errno==EINTR) continue;
1965 if (ipf==main_input_file) {
1968 } else if (ipf==flushing_input_file) {
1970 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1971 } else if (ipf==backlog_input_file) {
1977 tailing_queue_readable(ipf);
1982 /*---------- filemon implemented with inotify ----------*/
1984 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1985 #define HAVE_FILEMON
1987 #include <linux/inotify.h>
1989 static int filemon_inotify_fd;
1990 static int filemon_inotify_wdmax;
1991 static InputFile **filemon_inotify_wd2ipf;
1993 struct Filemon_Perfile {
1997 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1998 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1999 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
2001 if (wd >= filemon_inotify_wdmax) {
2003 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
2004 sizeof(*filemon_inotify_wd2ipf) * newmax);
2005 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
2006 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
2007 filemon_inotify_wdmax= newmax;
2010 assert(!filemon_inotify_wd2ipf[wd]);
2011 filemon_inotify_wd2ipf[wd]= ipf;
2013 debug("filemon inotify startfile %p wd=%d wdmax=%d",
2014 ipf, wd, filemon_inotify_wdmax);
2019 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
2021 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
2022 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
2023 if (r) sysdie("inotify_rm_watch");
2024 filemon_inotify_wd2ipf[wd]= 0;
2027 static void *filemon_inotify_readable(oop_source *lp, int fd,
2028 oop_event e, void *u) {
2029 struct inotify_event iev;
2031 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
2033 if (isewouldblock(errno)) break;
2034 sysdie("read from inotify master");
2035 } else if (r==sizeof(iev)) {
2036 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
2038 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
2040 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
2041 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
2042 filemon_callback(ipf);
2044 return OOP_CONTINUE;
2047 static int filemon_method_init(void) {
2048 filemon_inotify_fd= inotify_init();
2049 if (filemon_inotify_fd<0) {
2050 syswarn("could not initialise inotify: inotify_init failed");
2054 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
2056 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2060 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2062 /*---------- filemon dummy implementation ----------*/
2064 #if !defined(HAVE_FILEMON)
2066 struct Filemon_Perfile { int dummy; };
2068 static int filemon_method_init(void) { return 0; }
2069 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2070 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2072 #endif /* !HAVE_FILEMON */
2074 /*---------- filemon generic interface ----------*/
2076 static void filemon_start(InputFile *ipf) {
2077 assert(!ipf->filemon);
2079 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
2080 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
2081 filemon_method_startfile(ipf, ipf->filemon);
2084 static void filemon_stop(InputFile *ipf) {
2085 if (!ipf->filemon) return;
2086 filemon_method_stopfile(ipf, ipf->filemon);
2091 static void filemon_callback(InputFile *ipf) {
2092 if (ipf && ipf->readable_callback) /* so filepoll() can be naive */
2093 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2096 /*---------- interface to start and stop an input file ----------*/
2098 static const oop_rd_style feedfile_rdstyle= {
2099 OOP_RD_DELIM_STRIP, '\n',
2101 OOP_RD_SHORTREC_LONG,
2104 static void inputfile_reading_start(InputFile *ipf) {
2106 ipf->readable.on_readable= tailing_on_readable;
2107 ipf->readable.on_cancel= tailing_on_cancel;
2108 ipf->readable.try_read= tailing_try_read;
2109 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2110 ipf->readable.delete_kill= 0;
2112 ipf->readable_callback= 0;
2113 ipf->readable_callback_user= 0;
2115 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2118 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2119 feedfile_got_article,ipf, feedfile_read_err, ipf);
2120 if (r) sysdie("unable start reading feedfile %s",ipf->path);
2123 static void inputfile_reading_stop(InputFile *ipf) {
2125 oop_rd_cancel(ipf->rd);
2126 oop_rd_delete(ipf->rd);
2128 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2132 /*========== interaction with innd - state machine ==========*/
2134 /* See official state diagram at top of file. We implement
2145 |`---------------------------------------------------.
2147 |`---------------- - - - |
2148 D ENOENT | D EXISTS see OVERALL STATES diagram |
2149 | for full startup logic |
2152 | ============ try to |
2158 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
2159 ^ | hardlink F to D |
2162 | | our handle onto F is now onto D |
2165 | |<-------------------<---------------------<---------+
2167 | | spawn inndcomm flush |
2169 | ================== |
2170 | FLUSHING[-ABSENT] |
2172 | main D tail/none |
2173 | ================== |
2175 | | INNDCOMM FLUSH FAILS ^
2176 | |`----------------------->----------. |
2178 | | NO SUCH SITE V |
2179 ^ |`--------------->----. ==================== |
2180 | | \ FLUSHFAILED[-ABSENT] |
2182 | | FLUSH OK \ main D tail/none |
2183 | | open F \ ==================== |
2185 | | \ | TIME TO RETRY |
2186 | |`------->----. ,---<---'\ `----------------'
2187 | | D NONE | | D NONE `----.
2189 | ============= V V ============
2190 | SEPARATED-1 | | DROPPING-1
2191 | flsh->rd!=0 | | flsh->rd!=0
2192 | [Separated] | | [Dropping]
2193 | main F idle | | main none
2194 | old D tail | | old D tail
2195 | ============= | | ============
2197 ^ | EOF ON D | | defer | EOF ON D
2199 | =============== | | ===============
2200 | SEPARATED-2 | | DROPPING-2
2201 | flsh->rd==0 | V flsh->rd==0
2202 | [Finishing] | | [Dropping]
2203 | main F tail | `. main none
2204 | old D closed | `. old D closed
2205 | =============== V `. ===============
2207 | | ALL D PROCESSED `. | ALL D PROCESSED
2208 | V install defer as backlog `. | install defer
2209 ^ | close D `. | close D
2210 | | unlink D `. | unlink D
2213 `----------' ==============
2233 static void startup_set_input_file(InputFile *f) {
2234 assert(!main_input_file);
2236 inputfile_reading_start(f);
2239 static void statemc_lock(void) {
2241 struct stat stab, stabf;
2244 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2245 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2248 memset(&fl,0,sizeof(fl));
2250 fl.l_whence= SEEK_SET;
2251 int r= fcntl(lockfd, F_SETLK, &fl);
2253 if (errno==EACCES || isewouldblock(errno)) {
2254 if (quiet_multiple) exit(0);
2255 fatal("another duct holds the lockfile");
2257 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2260 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2262 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2264 if (!lock_noent && samefile(&stab, &stabf))
2267 xclose(lockfd, "stale lockfile ", path_lock);
2270 FILE *lockfile= fdopen(lockfd, "w");
2271 if (!lockfile) sysdie("fdopen lockfile");
2273 int r= ftruncate(lockfd, 0);
2274 if (r) sysdie("truncate lockfile to write new info");
2276 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2277 (unsigned long)self_pid,
2278 sitename, feedfile, remote_host) == EOF ||
2280 sysfatal("write info to lockfile %s", path_lock);
2282 debug("startup: locked");
2285 static void statemc_init(void) {
2286 struct stat stabdefer;
2288 search_backlog_file();
2291 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2293 debug("startup: ductdefer ENOENT");
2295 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2296 switch (stabdefer.st_nlink==1) {
2298 open_defer(); /* so that we will later close it and rename it */
2301 xunlink(path_defer, "stale defer file link"
2302 " (presumably hardlink to backlog file)");
2305 die("defer file %s has unexpected link count %d",
2306 path_defer, stabdefer.st_nlink);
2310 struct stat stab_f, stab_d;
2313 InputFile *file_d= open_input_file(path_flushing);
2314 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2316 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2318 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2319 debug("startup: F==D => Hardlinked");
2320 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2325 debug("startup: F ENOENT => Moved");
2326 if (file_d) startup_set_input_file(file_d);
2327 spawn_inndcomm_flush("feedfile missing at startup");
2328 /* => Flushing, sms:=FLUSHING */
2331 debug("startup: F!=D => Separated");
2332 startup_set_input_file(file_d);
2333 SMS(SEPARATED, 0, "found both old and current feed files");
2335 debug("startup: F exists, D ENOENT => Normal");
2336 InputFile *file_f= open_input_file(feedfile);
2337 if (!file_f) die("feed file vanished during startup");
2338 startup_set_input_file(file_f);
2339 SMS(NORMAL, spontaneous_flush_periods, "normal startup");
2344 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2345 assert(sms == sm_NORMAL);
2347 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2349 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2350 (unsigned long)target_max_feedfile_size,
2353 int r= link(feedfile, path_flushing);
2354 if (r) sysfatal("link feedfile %s to flushing file %s",
2355 feedfile, path_flushing);
2358 xunlink(feedfile, "old feedfile link");
2361 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2364 static void statemc_period_poll(void) {
2365 if (!sm_period_counter) return;
2366 sm_period_counter--;
2367 assert(sm_period_counter>=0);
2369 if (sm_period_counter) return;
2372 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2374 case sm_FLUSHFAILED:
2375 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2382 static int inputfile_is_done(InputFile *ipf) {
2384 if (ipf->inprogress) return 0; /* new article in the meantime */
2385 if (ipf->rd) return 0; /* not had EOF */
2389 static void notice_processed(InputFile *ipf, const char *what,
2391 #define RCI_NOTHING(x) /* nothing */
2392 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2393 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2395 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2397 info("processed %s%s read=%d(+%dbl,+%derr)"
2398 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2399 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2402 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2403 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2404 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2405 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2406 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2407 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2413 static void statemc_check_backlog_done(void) {
2414 InputFile *ipf= backlog_input_file;
2415 if (!inputfile_is_done(ipf)) return;
2417 const char *slash= strrchr(ipf->path, '/');
2418 const char *leaf= slash ? slash+1 : ipf->path;
2419 const char *under= strchr(slash, '_');
2420 const char *rest= under ? under+1 : leaf;
2421 if (!strncmp(rest,"backlog",7)) rest += 7;
2422 notice_processed(ipf,"backlog:",rest);
2424 close_input_file(ipf);
2425 if (unlink(ipf->path)) {
2426 if (errno != ENOENT)
2427 sysdie("could not unlink processed backlog file %s", ipf->path);
2428 warn("backlog file %s vanished while we were reading it"
2429 " so we couldn't remove it (but it's done now, anyway)",
2433 backlog_input_file= 0;
2434 search_backlog_file();
2438 static void statemc_check_flushing_done(void) {
2439 InputFile *ipf= flushing_input_file;
2440 if (!inputfile_is_done(ipf)) return;
2442 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2444 notice_processed(ipf,"feedfile",0);
2448 xunlink(path_flushing, "old flushing file");
2450 close_input_file(flushing_input_file);
2451 free(flushing_input_file);
2452 flushing_input_file= 0;
2454 if (sms==sm_SEPARATED) {
2455 notice("flush complete");
2456 SMS(NORMAL, 0, "flush complete");
2457 } else if (sms==sm_DROPPING) {
2458 SMS(DROPPED, 0, "old flush complete");
2459 search_backlog_file();
2460 notice("feed dropped, but will continue until backlog is finished");
2464 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2466 assert(!inputfile_is_done(main_input_file));
2467 statemc_check_flushing_done();
2468 statemc_check_backlog_done();
2469 return OOP_CONTINUE;
2472 static void queue_check_input_done(void) {
2473 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2476 static void statemc_setstate(StateMachineState newsms, int periods,
2477 const char *forlog, const char *why) {
2479 sm_period_counter= periods;
2481 const char *xtra= "";
2484 case sm_FLUSHFAILED:
2485 if (!main_input_file) xtra= "-ABSENT";
2489 xtra= flushing_input_file->rd ? "-1" : "-2";
2495 info("state %s%s[%d] %s",forlog,xtra,periods,why);
2497 info("state %s%s %s",forlog,xtra,why);
2501 /*---------- defer and backlog files ----------*/
2503 static void open_defer(void) {
2508 defer= fopen(path_defer, "a+");
2509 if (!defer) sysfatal("could not open defer file %s", path_defer);
2511 /* truncate away any half-written records */
2513 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2515 if (stab.st_size > LONG_MAX)
2516 die("defer file %s size is far too large", path_defer);
2521 long orgsize= stab.st_size;
2522 long truncto= stab.st_size;
2524 if (!truncto) break; /* was only (if anything) one half-truncated record */
2525 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2526 sysdie("seek in defer file %s while truncating partial", path_defer);
2531 sysdie("failed read from defer file %s", path_defer);
2533 die("defer file %s shrank while we were checking it!", path_defer);
2539 if (stab.st_size != truncto) {
2540 warn("truncating half-record at end of defer file %s -"
2541 " shrinking by %ld bytes from %ld to %ld",
2542 path_defer, orgsize - truncto, orgsize, truncto);
2545 sysfatal("could not flush defer file %s", path_defer);
2546 if (ftruncate(fileno(defer), truncto))
2547 sysdie("could not truncate defer file %s", path_defer);
2550 info("continuing existing defer file %s (%ld bytes)",
2551 path_defer, orgsize);
2553 if (fseek(defer, truncto, SEEK_SET))
2554 sysdie("could not seek to new end of defer file %s", path_defer);
2557 static void close_defer(void) {
2562 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2564 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2567 time_t now= xtime();
2569 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2571 (unsigned long)stab.st_ino);
2572 if (link(path_defer, backlog))
2573 sysfatal("could not install defer file %s as backlog file %s",
2574 path_defer, backlog);
2575 if (unlink(path_defer))
2576 sysdie("could not unlink old defer link %s to backlog file %s",
2577 path_defer, backlog);
2581 if (until_backlog_nextscan < 0 ||
2582 until_backlog_nextscan > backlog_retry_minperiods + 1)
2583 until_backlog_nextscan= backlog_retry_minperiods + 1;
2586 static void poll_backlog_file(void) {
2587 if (until_backlog_nextscan < 0) return;
2588 if (until_backlog_nextscan-- > 0) return;
2589 search_backlog_file();
2592 static void search_backlog_file(void) {
2593 /* returns non-0 iff there are any backlog files */
2598 const char *oldest_path=0;
2599 time_t oldest_mtime=0, now;
2601 if (backlog_input_file) return;
2605 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2609 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2611 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2613 for (i=0; i<gl.gl_pathc; i++) {
2614 const char *path= gl.gl_pathv[i];
2616 if (strchr(path,'#') || strchr(path,'~')) {
2617 debug("backlog file search skipping %s", path);
2620 r= stat(path, &stab);
2622 syswarn("failed to stat backlog file %s", path);
2625 if (!S_ISREG(stab.st_mode)) {
2626 warn("backlog file %s is not a plain file (or link to one)", path);
2629 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2631 oldest_mtime= stab.st_mtime;
2634 case GLOB_NOMATCH: /* fall through */
2637 sysdie("glob expansion of backlog pattern %s gave unexpected"
2638 " nonzero (error?) return value %d", globpat_backlog, r);
2642 debug("backlog scan: none");
2644 if (sms==sm_DROPPED) {
2645 notice("feed dropped and our work is complete");
2647 int r= unlink(path_control);
2648 if (r && errno!=ENOENT)
2649 syswarn("failed to remove control symlink for old feed");
2651 xunlink(path_lock, "lockfile for old feed");
2654 until_backlog_nextscan= backlog_spontrescan_periods;
2659 double age= difftime(now, oldest_mtime);
2660 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2662 if (age_deficiency <= 0) {
2663 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2664 age, age_deficiency, oldest_path);
2666 backlog_input_file= open_input_file(oldest_path);
2667 if (!backlog_input_file) {
2668 warn("backlog file %s vanished as we opened it", oldest_path);
2672 inputfile_reading_start(backlog_input_file);
2673 until_backlog_nextscan= -1;
2677 until_backlog_nextscan= age_deficiency / period_seconds;
2679 if (backlog_spontrescan_periods >= 0 &&
2680 until_backlog_nextscan > backlog_spontrescan_periods)
2681 until_backlog_nextscan= backlog_spontrescan_periods;
2683 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2684 age, age_deficiency, until_backlog_nextscan, oldest_path);
2691 /*========== flushing the feed ==========*/
2693 static pid_t inndcomm_child;
2694 static int inndcomm_sentinel_fd;
2696 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2697 assert(inndcomm_child);
2698 assert(fd == inndcomm_sentinel_fd);
2699 int status= xwaitpid(&inndcomm_child, "inndcomm");
2702 cancel_fd_read_except(fd);
2703 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2704 inndcomm_sentinel_fd= 0;
2706 assert(!flushing_input_file);
2708 if (WIFEXITED(status)) {
2709 switch (WEXITSTATUS(status)) {
2711 case INNDCOMMCHILD_ESTATUS_FAIL:
2714 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2715 notice("feed has been dropped by innd, finishing up");
2716 flushing_input_file= main_input_file;
2717 tailing_queue_readable(flushing_input_file);
2718 /* we probably previously returned EAGAIN from our fake read method
2719 * when in fact we were at EOF, so signal another readable event
2720 * so we actually see the EOF */
2724 if (flushing_input_file) {
2725 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2728 SMS(DROPPED, 0, "feed dropped by innd");
2729 search_backlog_file();
2731 return OOP_CONTINUE;
2735 flushing_input_file= main_input_file;
2736 tailing_queue_readable(flushing_input_file);
2738 main_input_file= open_input_file(feedfile);
2739 if (!main_input_file)
2740 die("flush succeeded but feedfile %s does not exist!", feedfile);
2742 if (flushing_input_file) {
2743 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2746 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2748 return OOP_CONTINUE;
2751 goto unexpected_exitstatus;
2754 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2755 warn("flush timed out trying to talk to innd");
2758 unexpected_exitstatus:
2759 report_child_status("inndcomm child", status);
2763 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2764 return OOP_CONTINUE;
2767 static void inndcommfail(const char *what) {
2768 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2769 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2772 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2775 notice("flushing %s",why);
2777 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2778 assert(!inndcomm_child);
2779 assert(!inndcomm_sentinel_fd);
2781 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2783 inndcomm_child= xfork("inndcomm child");
2785 if (!inndcomm_child) {
2786 const char *flushargv[2]= { sitename, 0 };
2790 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2791 /* parent spots the autoclose of pipefds[1] when we die or exit */
2793 if (simulate_flush>=0) {
2794 warn("SIMULATING flush child status %d", simulate_flush);
2795 if (simulate_flush>128) raise(simulate_flush-128);
2796 else exit(simulate_flush);
2799 alarm(inndcomm_flush_timeout);
2800 r= ICCopen(); if (r) inndcommfail("connect");
2801 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2802 if (!r) exit(0); /* yay! */
2804 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2805 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2806 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2811 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2812 inndcomm_sentinel_fd= pipefds[0];
2813 assert(inndcomm_sentinel_fd);
2814 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2816 SMS(FLUSHING, 0, why);
2819 /*========== main program ==========*/
2821 static void postfork_inputfile(InputFile *ipf) {
2823 xclose(ipf->fd, "(in child) input file ", ipf->path);
2826 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2827 /* we have no stdio streams that are buffered long-term */
2829 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2832 static void postfork(void) {
2833 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2834 sysdie("(in child) failed to reset SIGPIPE");
2836 postfork_inputfile(main_input_file);
2837 postfork_inputfile(flushing_input_file);
2840 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2841 conn_closefd(conn,"(in child) ");
2843 postfork_stdio(defer, "defer file ", path_defer);
2846 typedef struct Every Every;
2848 struct timeval interval;
2853 static void every_schedule(Every *e, struct timeval base);
2855 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
2858 if (!e->fixed_rate) xgettimeofday(&base);
2859 every_schedule(e, base);
2860 return OOP_CONTINUE;
2863 static void every_schedule(Every *e, struct timeval base) {
2864 struct timeval when;
2865 timeradd(&base, &e->interval, &when);
2866 loop->on_time(loop, when, every_happens, e);
2869 static void every(int interval, int fixed_rate, void (*f)(void)) {
2870 Every *e= xmalloc(sizeof(*e));
2871 e->interval.tv_sec= interval;
2872 e->interval.tv_usec= 0;
2873 e->fixed_rate= fixed_rate;
2876 xgettimeofday(&now);
2877 every_schedule(e, now);
2880 static void filepoll(void) {
2881 filemon_callback(main_input_file);
2882 filemon_callback(flushing_input_file);
2885 static char *debug_report_ipf(InputFile *ipf) {
2886 if (!ipf) return xasprintf("none");
2888 const char *slash= strrchr(ipf->path,'/');
2889 const char *path= slash ? slash+1 : ipf->path;
2891 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2893 ipf->inprogress, (long)ipf->offset,
2894 ipf->fd, ipf->rd ? "+" : "");
2897 static void period(void) {
2898 char *dipf_main= debug_report_ipf(main_input_file);
2899 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2900 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2903 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2904 " input_files main:%s old:%s flushing:%s"
2905 " children connecting=%ld inndcomm=%ld"
2907 sms_names[sms], sm_period_counter,
2908 conns.count, queue.count, until_connect,
2909 dipf_main, dipf_flushing, dipf_backlog,
2910 (long)connecting_child, (long)inndcomm_child
2914 free(dipf_flushing);
2917 if (until_connect) until_connect--;
2919 poll_backlog_file();
2920 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2921 statemc_period_poll();
2922 check_assign_articles();
2927 /*========== option parsing ==========*/
2929 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2930 static void vbadusage(const char *fmt, va_list al) {
2931 char *m= xvasprintf(fmt,al);
2932 fprintf(stderr, "bad usage: %s\n"
2933 "say --help for help, or read the manpage\n",
2936 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2940 /*---------- generic option parser ----------*/
2942 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2943 static void badusage(const char *fmt, ...) {
2950 of_seconds= 001000u,
2951 of_boolean= 002000u,
2954 typedef struct Option Option;
2955 typedef void OptionParser(const Option*, const char *val);
2959 const char *lng, *formarg;
2965 static void parse_options(const Option *options, char ***argvp) {
2966 /* on return *argvp is first non-option arg; argc is not updated */
2969 const char *arg= *++(*argvp);
2971 if (*arg != '-') break;
2972 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2974 while ((a= *++arg)) {
2978 char *equals= strchr(arg,'=');
2979 int len= equals ? (equals - arg) : strlen(arg);
2980 for (o=options; o->shrt || o->lng; o++)
2981 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2983 badusage("unknown long option --%s",arg);
2986 if (equals) badusage("option --%s does not take a value",o->lng);
2988 } else if (equals) {
2992 if (!arg) badusage("option --%s needs a value for %s",
2993 o->lng, o->formarg);
2996 break; /* eaten the whole argument now */
2998 for (o=options; o->shrt || o->lng; o++)
3001 badusage("unknown short option -%c",a);
3008 if (!arg) badusage("option -%c needs a value for %s",
3009 o->shrt, o->formarg);
3012 break; /* eaten the whole argument now */
3018 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
3020 static void print_options(const Option *options, FILE *f) {
3022 for (o=options; o->shrt || o->lng; o++) {
3023 char shrt[2] = { o->shrt, 0 };
3024 char *optspec= xasprintf("%s%s%s%s%s",
3025 o->shrt ? "-" : "", shrt,
3026 o->shrt && o->lng ? "|" : "",
3027 DELIMPERHAPS("--", o->lng));
3028 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
3033 /*---------- specific option types ----------*/
3035 static void op_integer(const Option *o, const char *val) {
3038 unsigned long ul= strtoul(val,&ep,10);
3039 if (*ep || ep==val || errno || ul>INT_MAX)
3040 badusage("bad integer value for %s",o->lng);
3041 int *store= o->store;
3045 static void op_double(const Option *o, const char *val) {
3046 int *store= o->store;
3049 *store= strtod(val, &ep);
3050 if (*ep || ep==val || errno)
3051 badusage("bad floating point value for %s",o->lng);
3054 static void op_string(const Option *o, const char *val) {
3055 const char **store= o->store;
3059 static void op_seconds(const Option *o, const char *val) {
3060 int *store= o->store;
3064 double v= strtod(val,&ep);
3065 if (ep==val) badusage("bad time/duration value for %s",o->lng);
3067 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
3068 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
3069 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
3070 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
3071 else if (!strcmp(ep,"das")) unit= 10;
3072 else if (!strcmp(ep,"hs")) unit= 100;
3073 else if (!strcmp(ep,"ks")) unit= 1000;
3074 else if (!strcmp(ep,"Ms")) unit= 1000000;
3075 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
3079 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
3083 static void op_setint(const Option *o, const char *val) {
3084 int *store= o->store;
3088 /*---------- specific options ----------*/
3090 static void help(const Option *o, const char *val);
3092 static const Option innduct_options[]= {
3093 {'f',"feedfile", "F", &feedfile, op_string },
3094 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
3095 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
3096 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
3097 {'C',"inndconf", "F", &inndconffile, op_string },
3098 {'P',"port", "PORT", &port, op_integer },
3099 {0,"help", 0, 0, help },
3101 {0,"max-connections", "N", &max_connections, op_integer },
3102 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
3103 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
3104 {0,"period-interval", "TIME", &period_seconds, op_seconds },
3106 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
3107 {0,"stuck-flush-timeout","TIME", &inndcomm_flush_timeout, op_seconds },
3109 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
3110 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
3112 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
3113 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
3114 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3115 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3116 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
3117 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
3119 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
3120 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
3125 static void printusage(FILE *f) {
3126 fputs("usage: innduct [options] site [fqdn]\n"
3127 "available options are:\n", f);
3128 print_options(innduct_options, f);
3131 static void help(const Option *o, const char *val) {
3133 if (ferror(stdout) || fflush(stdout)) {
3134 perror("innduct: writing help");
3140 static void convert_to_periods_rndup(int *store) {
3141 *store += period_seconds-1;
3142 *store /= period_seconds;
3145 int main(int argc, char **argv) {
3151 parse_options(innduct_options, &argv);
3156 if (!sitename) badusage("need site name argument");
3157 remote_host= *argv++;
3158 if (*argv) badusage("too many non-option arguments");
3162 int r= innconf_read(inndconffile);
3163 if (!r) badusage("could not read inn.conf (more info on stderr)");
3165 if (!remote_host) remote_host= sitename;
3167 if (nocheck_thresh < 0 || nocheck_thresh > 100)
3168 badusage("nocheck threshold percentage must be between 0..100");
3169 nocheck_thresh *= 0.01;
3171 if (nocheck_decay < 0.1)
3172 badusage("nocheck decay articles must be at least 0.1");
3173 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3175 convert_to_periods_rndup(&reconnect_delay_periods);
3176 convert_to_periods_rndup(&flushfail_retry_periods);
3177 convert_to_periods_rndup(&backlog_retry_minperiods);
3178 convert_to_periods_rndup(&backlog_spontrescan_periods);
3179 convert_to_periods_rndup(&spontaneous_flush_periods);
3180 convert_to_periods_rndup(&need_activity_periods);
3182 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3183 badusage("bad input data ratio must be between 0..100");
3184 max_bad_data_ratio *= 0.01;
3187 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3188 } else if (!feedfile[0]) {
3189 badusage("feed filename must be nonempty");
3190 } else if (feedfile[strlen(feedfile)-1]=='/') {
3191 feedfile= xasprintf("%s%s",feedfile,sitename);
3194 const char *feedfile_forbidden= "?*[~#";
3196 while ((c= *feedfile_forbidden++))
3197 if (strchr(feedfile, c))
3198 badusage("feed filename may not contain metacharacter %c",c);
3202 path_lock= xasprintf("%s_lock", feedfile);
3203 path_flushing= xasprintf("%s_flushing", feedfile);
3204 path_defer= xasprintf("%s_defer", feedfile);
3205 path_control= xasprintf("%s_control", feedfile);
3206 globpat_backlog= xasprintf("%s_backlog*", feedfile);
3208 oop_source_sys *sysloop= oop_sys_new();
3209 if (!sysloop) sysdie("could not create liboop event loop");
3210 loop= (oop_source*)sysloop;
3212 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3213 sysdie("could not ignore SIGPIPE");
3218 if (become_daemon) {
3220 for (i=3; i<255; i++)
3221 /* do this now before we open syslog, etc. */
3223 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3225 int null= open("/dev/null",O_RDWR);
3226 if (null<0) sysfatal("failed to open /dev/null");
3230 xclose(null, "/dev/null original fd",0);
3232 pid_t child1= xfork("daemonise first fork");
3233 if (child1) _exit(0);
3235 pid_t sid= setsid();
3236 if (sid != child1) sysfatal("setsid failed");
3238 pid_t child2= xfork("daemonise second fork");
3239 if (child2) _exit(0);
3243 if (self_pid==-1) sysdie("getpid");
3254 if (!filemon_method_init()) {
3255 warn("no file monitoring available, polling");
3256 every(5,0,filepoll);
3259 every(period_seconds,1,period);
3265 void *run= oop_sys_run(sysloop);
3266 assert(run == OOP_ERROR);
3267 sysdie("event loop failed");