2 * warning if no inotify
3 * inotify not working ?
4 * some per-conn info thing for control
8 * - actually do something with readable on control master
9 * - option for realsockdir
10 * - option for filepoll
11 * - option for no inotify
12 * - manpage: document control master stuff
13 * - manpage: innconf is used for communicating with innd
15 * build-lfs/backends/innduct --no-daemon -f `pwd`/fee sit dom
19 * Newsfeeds file entries should look like this:
20 * host.name.of.site[/exclude,exclude,...]\
21 * :pattern,pattern...[/distribution,distribution...]\
25 * sitename[/exclude,exclude,...]\
26 * :pattern,pattern...[/distribution,distribution...]\
32 * or might be blanked out
33 * <spc><spc><spc><spc>....
35 * F site.name main feed file
36 * opened/created, then written, by innd
39 * tokens blanked out by duct when processed
40 * site.name_lock lock preventing multiple ducts
41 * to hold lock must open,F_SETLK[W]
42 * and then stat to check that locked file
43 * still has name site.name_lock
44 * holder of this lock is "duct"
45 * (only) lockholder may remove the lockfile
46 * D site.name_flushing temporary feed file during flush (or crash)
47 * hardlink created by duct
49 * site.name_defer 431'd articles, still being written,
50 * created, written, used by duct
52 * site.name_backlog.<date>.<inum>
53 * 431'd articles, ready for innxmit or duct
54 * created (link/mv) by duct
55 * site.name_backlog<anything-else> (where <anything-else> does not
56 * contain '#' or '~') eg
57 * site.name_backlog.manual
58 * anything the sysadmin likes (eg, feed files
59 * from old feeds to be merged into this one)
60 * created (link/mv) by admin
61 * may be symlinks (in which case links
62 * may be written through, but only links
65 * It is safe to remove backlog files manually,
66 * if it's desired to throw away the backlog.
68 * Backlog files are also processed by innduct. We find the oldest
69 * backlog file which is at least a certain amount old, and feed it
70 * back into our processing. When every article in it has been read
71 * and processed, we unlink it and look for another backlog file.
73 * If we don't have a backlog file that we're reading, we close the
74 * defer file that we're writing and make it into a backlog file at
75 * the first convenient opportunity.
86 | | <----------------<---------------------------------'|
92 | F: innd writing, duct reading |
95 | | duct decides time to flush |
96 | | duct makes hardlink |
98 | V <------------------------'|
100 | F == D: innd writing, duct reading both exist |
103 | | <-----------<-------------<--'|
104 | | open D F ENOENT |
107 | V <---------------------. |
110 | D: innd writing, duct reading; or ENOENT | |
112 | | duct requests flush of feed | |
113 | | (others can too, harmlessly) | |
117 | D: innd flushing, duct; or ENOENT | |
119 | | inndcomm flush fails | |
120 | |`-------------------------->------------------' |
122 | | inndcomm reports no such site |
123 | |`---------------------------------------------------- | -.
125 | | innd finishes writing D, creates F | |
126 | | inndcomm reports flush successful | |
129 | Separated <----------------' |
130 | F: innd writing F!=D /
131 | D: duct reading; or ENOENT both exist /
133 | | duct gets to the end of D /
134 | | duct opens F too /
137 | F: innd writing, duct reading |
138 | D: duct finishing V
140 | | duct finishes processing D F: ENOENT
141 | V duct unlinks D D: duct reading
143 `--<--' | duct finishes
153 "duct reading" means innduct is reading the file but also
154 overwriting processed tokens.
158 * rune for printing diagrams:
160 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
165 /*============================== PROGRAM ==============================*/
167 #define _GNU_SOURCE 1
173 #include "inndcomm.h"
175 #include "inn/list.h"
176 #include "inn/innconf.h"
179 #include <sys/types.h>
180 #include <sys/wait.h>
181 #include <sys/stat.h>
182 #include <sys/socket.h>
201 #include <oop-read.h>
203 /*----- general definitions, probably best not changed -----*/
205 #define CONNCHILD_ESTATUS_STREAM 24
206 #define CONNCHILD_ESTATUS_NOSTREAM 25
208 #define INNDCOMMCHILD_ESTATUS_FAIL 26
209 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
211 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
212 #define MAX_CONTROL_COMMAND 1000
214 #define VA va_list al; va_start(al,fmt)
215 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
216 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
218 /*----- doubly linked lists -----*/
220 #define ISNODE(T) struct node list_node
223 union { struct list li; T *for_type; } u; \
227 #define NODE(n) (assert((void*)&(n)->list_node == (n)), &(n)->list_node)
229 #define LIST_CHECKCANHAVENODE(l,n) \
230 ((void)((n) == ((l).u.for_type))) /* just for the type check */
232 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
233 ( LIST_CHECKCANHAVENODE(l,n), \
234 list_addsomehow(&(l).u.li, NODE((n))), \
238 #define LIST_REMSOMEHOW(l,list_remsomehow) \
239 ( (typeof((l).u.for_type)) \
242 list_remsomehow(&(l).u.li) ) \
248 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
249 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
250 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
251 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
253 #define LIST_INIT(l) ((l).count=0, list_new(&(l).u.li))
254 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
255 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
256 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
258 #define LIST_REMOVE(l,n) \
259 ( LIST_CHECKCANHAVENODE(l,n), \
260 list_remove(NODE((n))), \
264 #define LIST_INSERT(l,n,pred) \
265 ( LIST_CHECKCANHAVENODE(l,n), \
266 LIST_CHECKCANHAVENODE(l,pred), \
267 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
271 /*----- type predeclarations -----*/
273 typedef struct Conn Conn;
274 typedef struct Article Article;
275 typedef struct InputFile InputFile;
276 typedef struct XmitDetails XmitDetails;
277 typedef struct Filemon_Perfile Filemon_Perfile;
278 typedef enum StateMachineState StateMachineState;
283 /*----- function predeclarations -----*/
285 static void conn_maybe_write(Conn *conn);
286 static void conn_make_some_xmits(Conn *conn);
287 static void *conn_write_some_xmits(Conn *conn);
289 static void xmit_free(XmitDetails *d);
291 #define SMS(newstate, periods, why) \
292 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
293 static void statemc_setstate(StateMachineState newsms, int periods,
294 const char *forlog, const char *why);
296 static void statemc_start_flush(const char *why); /* Normal => Flushing */
297 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
299 static void article_done(Conn *conn, Article *art, int whichcount);
301 static void check_assign_articles(void);
302 static void queue_check_input_done(void);
304 static void statemc_check_flushing_done(void);
305 static void statemc_check_backlog_done(void);
307 static void postfork(void);
308 static void period(void);
310 static void open_defer(void);
311 static void close_defer(void);
312 static void search_backlog_file(void);
314 static void inputfile_reading_start(InputFile *ipf);
315 static void inputfile_reading_stop(InputFile *ipf);
317 static void filemon_start(InputFile *ipf);
318 static void filemon_stop(InputFile *ipf);
319 static void filemon_callback(InputFile *ipf);
321 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
322 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
324 static const oop_rd_style peer_rd_style;
325 static oop_rd_call peer_rd_err, peer_rd_ok;
327 /*----- configuration options -----*/
328 /* when changing defaults, remember to update the manpage */
330 static const char *sitename, *remote_host;
331 static const char *feedfile, *realsockdir="/tmp/innduct.control";
332 static int quiet_multiple=0;
333 static int become_daemon=1;
334 static int try_stream=1;
336 static const char *inndconffile;
338 static int max_connections=10;
339 static int max_queue_per_conn=200;
340 static int target_max_feedfile_size=100000;
341 static int period_seconds=60;
343 static int connection_setup_timeout=200;
344 static int inndcomm_flush_timeout=100;
346 static double nocheck_thresh= 95.0; /* converted from percentage by main */
347 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
349 /* all these are initialised to seconds, and converted to periods in main */
350 static int reconnect_delay_periods=1000;
351 static int flushfail_retry_periods=1000;
352 static int backlog_retry_minperiods=50;
353 static int backlog_spontrescan_periods=300;
354 static int spontaneous_flush_periods=100000;
355 static int need_activity_periods=1000;
357 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
358 static int max_bad_data_initial= 30;
359 /* in one corrupt 4096-byte block the number of newlines has
360 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
363 /*----- statistics -----*/
365 typedef enum { /* in queue in conn->sent */
366 art_Unchecked, /* not checked, not sent checking */
367 art_Wanted, /* checked, wanted sent body as requested */
368 art_Unsolicited, /* - sent body without check */
372 #define RESULT_COUNTS(RCS,RCN) \
381 #define RCI_TRIPLE_FMT_BASE "%d (id=%d,bod=%d,nc=%d)"
382 #define RCI_TRIPLE_VALS_BASE(counts,x) \
383 counts[art_Unchecked] x \
384 + counts[art_Wanted] x \
385 + counts[art_Unsolicited] x, \
386 counts[art_Unchecked] x \
387 , counts[art_Wanted] x \
388 , counts[art_Unsolicited] x
391 #define RC_INDEX(x) RC_##x,
392 RESULT_COUNTS(RC_INDEX, RC_INDEX)
397 /*----- transmission buffers -----*/
402 xk_Malloc, xk_Const, xk_Artdata
414 /*----- core operational data structure types -----*/
417 /* This is also an instance of struct oop_readable */
418 struct oop_readable readable; /* first */
419 oop_readable_call *readable_callback;
420 void *readable_callback_user;
423 Filemon_Perfile *filemon;
425 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
426 long inprogress; /* no. of articles read but not processed */
430 int counts[art_MaxState][RCI_max];
431 int readcount_ok, readcount_blank, readcount_err;
446 #define SMS_LIST(X) \
454 enum StateMachineState {
455 #define SMS_DEF_ENUM(s) sm_##s,
456 SMS_LIST(SMS_DEF_ENUM)
459 static const char *sms_names[]= {
460 #define SMS_DEF_NAME(s) #s ,
461 SMS_LIST(SMS_DEF_NAME)
467 int fd; /* may be 0, meaning closed (during construction/destruction) */
468 oop_read *rd; /* likewise */
469 int max_queue, stream, quitting;
470 int since_activity; /* periods */
471 ArticleList waiting; /* not yet told peer */
472 ArticleList priority; /* peer says send it now */
473 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
474 struct iovec xmit[CONNIOVS];
475 XmitDetails xmitd[CONNIOVS];
480 /*----- general operational variables -----*/
482 /* main initialises */
483 static oop_source *loop;
484 static ConnList conns;
485 static ArticleList queue;
486 static char *path_lock, *path_flushing, *path_defer, *path_control;
487 static char *globpat_backlog;
488 static pid_t self_pid;
490 /* statemc_init initialises */
491 static StateMachineState sms;
493 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
494 static int sm_period_counter;
496 /* initialisation to 0 is good */
497 static int until_connect, until_backlog_nextscan;
498 static double accept_proportion;
499 static int nocheck, nocheck_reported;
501 /* for simulation, debugging, etc. */
502 int simulate_flush= -1;
504 /*========== logging ==========*/
506 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
507 static void logcore(int sysloglevel, const char *fmt, ...) {
510 vsyslog(sysloglevel,fmt,al);
512 if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
513 vfprintf(stderr,fmt,al);
519 static void logv(int sysloglevel, const char *pfx, int errnoval,
520 const char *fmt, va_list al) PRINTF(5,0);
521 static void logv(int sysloglevel, const char *pfx, int errnoval,
522 const char *fmt, va_list al) {
523 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
524 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
525 msgbuf[sizeof(msgbuf)-1]= 0;
527 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
528 sysloglevel= LOG_ERR; /* run by wrong user, probably */
530 logcore(sysloglevel, "<%s>%s: %s%s%s",
531 sitename, pfx, msgbuf,
532 errnoval>=0 ? ": " : "",
533 errnoval>=0 ? strerror(errnoval) : "");
536 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
537 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
538 static void fn(const char *fmt, ...) { \
540 logv(sysloglevel, pfx, err, fmt, al); \
544 #define logwrap(fn, pfx, sysloglevel, err) \
545 static void fn(const char *fmt, ...) PRINTF(1,2); \
546 static void fn(const char *fmt, ...) { \
548 logv(sysloglevel, pfx, err, fmt, al); \
552 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
553 diewrap(die, " critical", LOG_CRIT, -1, 16);
555 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
556 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
558 logwrap(syswarn, " warning", LOG_WARNING, errno);
559 logwrap(warn, " warning", LOG_WARNING, -1);
561 logwrap(notice, " notice", LOG_NOTICE, -1);
562 logwrap(info, " info", LOG_INFO, -1);
563 logwrap(debug, " debug", LOG_DEBUG, -1);
566 /*========== utility functions etc. ==========*/
568 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
569 static char *xvasprintf(const char *fmt, va_list al) {
571 int rc= vasprintf(&str,fmt,al);
572 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
575 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
576 static char *xasprintf(const char *fmt, ...) {
578 char *str= xvasprintf(fmt,al);
583 static int close_perhaps(int *fd) {
584 if (*fd <= 0) return 0;
589 static void xclose(int fd, const char *what, const char *what2) {
591 if (r) sysdie("close %s%s",what,what2?what2:"");
593 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
594 if (*fd <= 0) return;
595 xclose(*fd,what,what2);
599 static pid_t xfork(const char *what) {
603 if (child==-1) sysfatal("cannot fork for %s",what);
604 debug("forked %s %ld", what, (unsigned long)child);
605 if (!child) postfork();
609 static void on_fd_read_except(int fd, oop_call_fd callback) {
610 loop->on_fd(loop, fd, OOP_READ, callback, 0);
611 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
613 static void cancel_fd_read_except(int fd) {
614 loop->cancel_fd(loop, fd, OOP_READ);
615 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
618 static void report_child_status(const char *what, int status) {
619 if (WIFEXITED(status)) {
620 int es= WEXITSTATUS(status);
622 warn("%s: child died with error exit status %d", what, es);
623 } else if (WIFSIGNALED(status)) {
624 int sig= WTERMSIG(status);
625 const char *sigstr= strsignal(sig);
626 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
628 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
630 warn("%s: child died due to unknown fatal signal %d%s",
631 what, sig, coredump);
633 warn("%s: child died with unknown wait status %d", what,status);
637 static int xwaitpid(pid_t *pid, const char *what) {
640 int r= kill(*pid, SIGKILL);
641 if (r) sysdie("cannot kill %s child", what);
643 pid_t got= waitpid(*pid, &status, 0);
644 if (got==-1) sysdie("cannot reap %s child", what);
645 if (got==0) die("cannot reap %s child", what);
652 static void xunlink(const char *path, const char *what) {
654 if (r) sysdie("can't unlink %s %s", path, what);
657 static time_t xtime(void) {
659 if (now==-1) sysdie("time(2) failed");
663 static void xgettimeofday(struct timeval *tv_r) {
664 int r= gettimeofday(tv_r,0);
665 if (r) sysdie("gettimeofday(2) failed");
668 static void xsetnonblock(int fd, int nonblocking) {
669 int errnoval= oop_fd_nonblock(fd, nonblocking);
670 if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
673 static void check_isreg(const struct stat *stab, const char *path,
675 if (!S_ISREG(stab->st_mode))
676 die("%s %s not a plain file (mode 0%lo)",
677 what, path, (unsigned long)stab->st_mode);
680 static void xfstat(int fd, struct stat *stab_r, const char *what) {
681 int r= fstat(fd, stab_r);
682 if (r) sysdie("could not fstat %s", what);
685 static void xfstat_isreg(int fd, struct stat *stab_r,
686 const char *path, const char *what) {
687 xfstat(fd, stab_r, what);
688 check_isreg(stab_r, path, what);
691 static void xlstat_isreg(const char *path, struct stat *stab,
692 int *enoent_r /* 0 means ENOENT is fatal */,
694 int r= lstat(path, stab);
696 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
697 sysdie("could not lstat %s %s", what, path);
699 if (enoent_r) *enoent_r= 0;
700 check_isreg(stab, path, what);
703 static int samefile(const struct stat *a, const struct stat *b) {
704 assert(S_ISREG(a->st_mode));
705 assert(S_ISREG(b->st_mode));
706 return (a->st_ino == b->st_ino &&
707 a->st_dev == b->st_dev);
710 static char *sanitise(const char *input) {
711 static char sanibuf[100]; /* returns pointer to this buffer! */
713 const char *p= input;
717 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
719 if (!c) { *q++= '\''; *q=0; break; }
720 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
721 sprintf(q,"\\x%02x",c);
727 static int isewouldblock(int errnoval) {
728 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
732 /*========== command and control connections ==========*/
734 static int control_master;
736 typedef struct ControlConn ControlConn;
738 void (*destroy)(ControlConn*);
744 struct sockaddr_un un;
749 static const oop_rd_style control_rd_style= {
750 OOP_RD_DELIM_STRIP, '\n',
752 OOP_RD_SHORTREC_FORBID
755 static void control_destroy(ControlConn *cc) {
759 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
760 if (ferror(cc->out) | fflush(cc->out)) {
761 info("CTRL%d write error %s", cc->fd, strerror(errno));
766 static void control_prompt(ControlConn *cc /* may destroy*/) {
767 fprintf(cc->out, "%s| ", sitename);
768 control_checkouterr(cc);
771 typedef struct ControlCommand ControlCommand;
772 struct ControlCommand {
774 void (*f)(ControlConn *cc, const ControlCommand *ccmd,
775 const char *arg, size_t argsz);
780 static const ControlCommand control_commands[];
783 static void ccmd_##wh(ControlConn *cc, const ControlCommand *c, \
784 const char *arg, size_t argsz)
787 fputs("commands:\n", cc->out);
788 const ControlCommand *ccmd;
789 for (ccmd=control_commands; ccmd->cmd; ccmd++)
790 fprintf(cc->out, " %s\n", ccmd->cmd);
793 CCMD(period) { period(); }
794 CCMD(setintarg) { *(int*)c->xdata= atoi(arg); }
795 CCMD(setint) { *(int*)c->xdata= c->xval; }
797 static const ControlCommand control_commands[]= {
799 { "p", ccmd_period },
800 { "pretend flush", ccmd_setintarg, &simulate_flush },
801 { "poke sm", ccmd_setint, &sm_period_counter, 1 },
802 { "poke conn", ccmd_setint, &until_connect, 0 },
803 { "poke blscan", ccmd_setint, &until_backlog_nextscan, 0 },
804 { "wedge blscan", ccmd_setint, &until_backlog_nextscan, -1 },
808 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
809 const char *errmsg, int errnoval,
810 const char *data, size_t recsz, void *cc_v) {
811 ControlConn *cc= cc_v;
814 info("CTRL%d closed", cc->fd);
819 if (recsz == 0) goto prompt;
821 const ControlCommand *ccmd;
822 for (ccmd=control_commands; ccmd->cmd; ccmd++) {
823 int l= strlen(ccmd->cmd);
824 if (recsz < l) continue;
825 if (recsz > l && data[l] != ' ') continue;
826 if (memcmp(data, ccmd->cmd, l)) continue;
828 int argl= (int)recsz - (l+1);
829 ccmd->f(cc, ccmd, argl>=0 ? data+l+1 : 0, argl);
833 fputs("unknown command; h for help\n", cc->out);
840 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
841 const char *errmsg, int errnoval,
842 const char *data, size_t recsz, void *cc_v) {
843 ControlConn *cc= cc_v;
845 info("CTRL%d read error %s", cc->fd, errmsg);
850 static int control_conn_startup(ControlConn *cc /* may destroy*/,
852 cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
853 if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
855 int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
858 if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
860 info("CTRL%d %s ready", cc->fd, how);
865 static void control_stdio_destroy(ControlConn *cc) {
867 oop_rd_cancel(cc->rd);
868 errno= oop_rd_delete_tidy(cc->rd);
869 if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
874 static void control_stdio(void) {
875 ControlConn *cc= xmalloc(sizeof(*cc));
876 memset(cc,0,sizeof(*cc));
877 cc->destroy= control_stdio_destroy;
881 int r= control_conn_startup(cc,"stdio");
882 if (r) cc->destroy(cc);
885 static void control_accepted_destroy(ControlConn *cc) {
887 oop_rd_cancel(cc->rd);
888 oop_rd_delete_kill(cc->rd);
890 if (cc->out) { fclose(cc->out); cc->fd=0; }
891 close_perhaps(&cc->fd);
895 static void *control_master_readable(oop_source *lp, int master,
896 oop_event ev, void *u) {
897 ControlConn *cc= xmalloc(sizeof(*cc));
898 memset(cc,0,sizeof(*cc));
899 cc->destroy= control_accepted_destroy;
901 cc->salen= sizeof(cc->sa);
902 cc->fd= accept(master, &cc->sa.sa, &cc->salen);
903 if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
905 cc->out= fdopen(cc->fd, "w");
906 if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
908 int r= control_conn_startup(cc, "accepted");
918 #define NOCONTROL(...) do{ \
919 syswarn("no control socket, because failed to " __VA_ARGS__); \
923 static void control_init(void) {
928 struct sockaddr_un un;
931 memset(&sa,0,sizeof(sa));
932 int maxlen= sizeof(sa.un.sun_path);
934 int reallen= readlink(path_control, sa.un.sun_path, maxlen);
937 NOCONTROL("readlink control socket symlink path %s", path_control);
939 if (reallen >= maxlen) {
940 debug("control socket symlink path too long (r=%d)",reallen);
941 xunlink(path_control, "old (overlong) control socket symlink");
947 int r= lstat(realsockdir,&stab);
949 if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
951 r= mkdir(realsockdir, 0700);
952 if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
955 uid_t self= geteuid();
956 if (!S_ISDIR(stab.st_mode) ||
957 stab.st_uid != self ||
958 stab.st_mode & 0077) {
959 warn("no control socket, because real socket directory"
960 " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
961 !!S_ISDIR(stab.st_mode),
962 (unsigned long)stab.st_uid, (unsigned long)self,
963 (unsigned long)stab.st_mode & 0777UL);
968 real= xasprintf("%s/s%lx.%lx", realsockdir,
969 (unsigned long)xtime(), (unsigned long)self_pid);
970 int reallen= strlen(real);
972 if (reallen >= maxlen) {
973 warn("no control socket, because tmpnam gave overly-long path"
977 r= symlink(real, path_control);
978 if (r) NOCONTROL("make control socket path %s a symlink to real"
979 " socket path %s", path_control, real);
980 memcpy(sa.un.sun_path, real, reallen);
983 int r= unlink(sa.un.sun_path);
984 if (r && errno!=ENOENT)
985 NOCONTROL("remove old real socket %s", sa.un.sun_path);
987 control_master= socket(PF_UNIX, SOCK_STREAM, 0);
988 if (control_master<0) NOCONTROL("create new control socket");
990 sa.un.sun_family= AF_UNIX;
991 int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
992 r= bind(control_master, &sa.sa, sl);
993 if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
995 r= listen(control_master, 5);
996 if (r) NOCONTROL("listen");
998 xsetnonblock(control_master, 1);
1000 loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
1001 info("control socket ok, real path %s", sa.un.sun_path);
1007 xclose_perhaps(&control_master, "control master",0);
1011 /*========== management of connections ==========*/
1013 static void conn_closefd(Conn *conn, const char *msgprefix) {
1014 int r= close_perhaps(&conn->fd);
1015 if (r) info("C%d %serror closing socket: %s",
1016 conn->fd, msgprefix, strerror(errno));
1019 static void conn_dispose(Conn *conn) {
1022 oop_rd_cancel(conn->rd);
1023 oop_rd_delete_kill(conn->rd);
1027 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1028 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
1030 conn_closefd(conn,"");
1032 until_connect= reconnect_delay_periods;
1035 static void *conn_exception(oop_source *lp, int fd,
1036 oop_event ev, void *conn_v) {
1039 assert(fd == conn->fd);
1040 assert(ev == OOP_EXCEPTION);
1041 int r= read(conn->fd, &ch, 1);
1042 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1043 else connfail(conn,"exceptional condition on socket (peer sent urgent"
1044 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1045 return OOP_CONTINUE;
1048 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1049 int requeue[art_MaxState];
1050 memset(requeue,0,sizeof(requeue));
1053 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1054 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1055 while ((art= LIST_REMHEAD(conn->sent))) {
1056 requeue[art->state]++;
1057 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1058 LIST_ADDTAIL(queue,art);
1063 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1066 char *m= xvasprintf(fmt,al);
1067 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1068 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1071 LIST_REMOVE(conns,conn);
1073 check_assign_articles();
1076 static void connfail(Conn *conn, const char *fmt, ...) {
1079 vconnfail(conn,fmt,al);
1083 static void check_idle_conns(void) {
1085 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
1086 conn->since_activity++;
1088 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
1089 if (conn->since_activity <= need_activity_periods) continue;
1091 /* We need to shut this down */
1093 connfail(conn,"timed out waiting for response to QUIT");
1094 else if (conn->sent.count)
1095 connfail(conn,"timed out waiting for responses");
1096 else if (conn->waiting.count || conn->priority.count)
1097 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1098 else if (conn->xmitu)
1099 connfail(conn,"peer has been sending responses"
1100 " before receiving our commands!");
1102 static const char quitcmd[]= "QUIT\r\n";
1103 int todo= sizeof(quitcmd)-1;
1104 const char *p= quitcmd;
1106 int r= write(conn->fd, p, todo);
1108 if (isewouldblock(errno))
1109 connfail(conn, "blocked writing QUIT to idle connection");
1111 connfail(conn, "failed to write QUIT to idle connection: %s",
1119 conn->since_activity= 0;
1120 debug("C%d is idle, quitting", conn->fd);
1129 /*---------- making new connections ----------*/
1131 static pid_t connecting_child;
1132 static int connecting_fdpass_sock;
1134 static void connect_attempt_discard(void) {
1135 if (connecting_child) {
1136 int status= xwaitpid(&connecting_child, "connect");
1137 if (!(WIFEXITED(status) ||
1138 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1139 report_child_status("connect", status);
1141 if (connecting_fdpass_sock) {
1142 cancel_fd_read_except(connecting_fdpass_sock);
1143 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1147 #define PREP_DECL_MSG_CMSG(msg) \
1149 struct iovec msgiov; \
1150 msgiov.iov_base= &msgbyte; \
1151 msgiov.iov_len= 1; \
1152 struct msghdr msg; \
1153 memset(&msg,0,sizeof(msg)); \
1154 char msg##cbuf[CMSG_SPACE(sizeof(int))]; \
1155 msg.msg_iov= &msgiov; \
1156 msg.msg_iovlen= 1; \
1157 msg.msg_control= msg##cbuf; \
1158 msg.msg_controllen= sizeof(msg##cbuf);
1160 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1163 assert(fd == connecting_fdpass_sock);
1165 PREP_DECL_MSG_CMSG(msg);
1167 ssize_t rs= recvmsg(fd, &msg, 0);
1169 if (isewouldblock(errno)) return OOP_CONTINUE;
1170 syswarn("failed to read socket from connecting child");
1174 conn= xmalloc(sizeof(*conn));
1175 memset(conn,0,sizeof(*conn));
1176 LIST_INIT(conn->waiting);
1177 LIST_INIT(conn->priority);
1178 LIST_INIT(conn->sent);
1180 struct cmsghdr *h= 0;
1181 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1183 int status= xwaitpid(&connecting_child, "connect child (broken)");
1185 if (WIFEXITED(status)) {
1186 if (WEXITSTATUS(status) != 0 &&
1187 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1188 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1189 /* child already reported the problem */;
1191 if (e == OOP_EXCEPTION)
1192 warn("connect: connection child exited code %d but"
1193 " unexpected exception on fdpass socket",
1194 WEXITSTATUS(status));
1196 warn("connect: connection child exited code %d but"
1198 WEXITSTATUS(status), (int)rs);
1200 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1201 warn("connect: connection attempt timed out");
1203 report_child_status("connect", status);
1208 #define CHK(field, val) \
1209 if (h->cmsg_##field != val) { \
1210 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1211 h->cmsg_##field, val); \
1214 CHK(level, SOL_SOCKET);
1215 CHK(type, SCM_RIGHTS);
1216 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1219 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1221 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1224 pid_t got= waitpid(connecting_child, &status, 0);
1225 if (got==-1) sysdie("connect: real wait for child");
1226 assert(got == connecting_child);
1227 connecting_child= 0;
1229 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1230 int es= WEXITSTATUS(status);
1232 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1233 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1235 fatal("connect: child gave unexpected exit status %d", es);
1239 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1241 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1242 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1243 if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1244 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1246 &peer_rd_err, conn);
1247 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1249 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1250 LIST_ADDHEAD(conns, conn);
1252 connect_attempt_discard();
1253 check_assign_articles();
1254 return OOP_CONTINUE;
1258 connect_attempt_discard();
1259 return OOP_CONTINUE;
1262 static int allow_connect_start(void) {
1263 return conns.count < max_connections
1264 && !connecting_child
1268 static void connect_start(void) {
1269 assert(!connecting_child);
1270 assert(!connecting_fdpass_sock);
1272 info("starting connection attempt");
1275 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1276 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1278 connecting_child= xfork("connection");
1280 if (!connecting_child) {
1281 FILE *cn_from, *cn_to;
1282 char buf[NNTP_STRLEN+100];
1283 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1285 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1287 alarm(connection_setup_timeout);
1288 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1292 unsigned char c= buf[l-1];
1293 if (!isspace(c)) break;
1294 if (c=='\n' || c=='\r') stripped=1;
1298 sysfatal("connect: connection attempt failed");
1301 fatal("connect: %s: %s", stripped ? "rejected" : "failed",
1305 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1306 sysfatal("connect: authentication failed");
1308 if (fputs("MODE STREAM\r\n", cn_to)==EOF ||
1310 sysfatal("connect: could not send MODE STREAM");
1311 buf[sizeof(buf)-1]= 0;
1312 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1313 if (ferror(cn_from))
1314 sysfatal("connect: could not read response to MODE STREAM");
1316 fatal("connect: connection close in response to MODE STREAM");
1321 fatal("connect: response to MODE STREAM is too long: %.100s...",
1323 l--; if (l>0 && buf[l-1]=='\r') l--;
1326 int rcode= strtoul(buf,&ep,10);
1328 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
1332 exitstatus= CONNCHILD_ESTATUS_STREAM;
1338 warn("connect: unexpected response to MODE STREAM: %.50s",
1344 int fd= fileno(cn_from);
1346 PREP_DECL_MSG_CMSG(msg);
1347 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1348 cmsg->cmsg_level= SOL_SOCKET;
1349 cmsg->cmsg_type= SCM_RIGHTS;
1350 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1351 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1353 msg.msg_controllen= cmsg->cmsg_len;
1354 r= sendmsg(socks[1], &msg, 0);
1355 if (r<0) sysdie("sendmsg failed for new connection");
1356 if (r!=1) die("sendmsg for new connection gave wrong result %d",r);
1361 xclose(socks[1], "connecting fdpass child's socket",0);
1362 connecting_fdpass_sock= socks[0];
1363 xsetnonblock(connecting_fdpass_sock, 1);
1364 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1367 /*---------- assigning articles to conns, and transmitting ----------*/
1369 static void check_assign_articles(void) {
1375 int spare=0, inqueue=0;
1377 /* Find a connection to offer this article. We prefer a busy
1378 * connection to an idle one, provided it's not full. We take the
1379 * first (oldest) and since that's stable, it will mean we fill up
1380 * connections in order. That way if we have too many
1381 * connections, the spare ones will go away eventually.
1383 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1384 if (walk->quitting) continue;
1385 inqueue= walk->sent.count + walk->priority.count
1386 + walk->waiting.count;
1387 spare= walk->max_queue - inqueue;
1388 assert(inqueue <= max_queue_per_conn);
1390 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1391 else if (spare>0) /*working*/ { use= walk; break; }
1394 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1396 Article *art= LIST_REMHEAD(queue);
1398 LIST_ADDTAIL(use->waiting, art);
1401 conn_maybe_write(use);
1402 } else if (allow_connect_start()) {
1403 until_connect= reconnect_delay_periods;
1412 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1413 conn_maybe_write(u);
1414 return OOP_CONTINUE;
1417 static void conn_maybe_write(Conn *conn) {
1419 conn_make_some_xmits(conn);
1421 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1425 void *rp= conn_write_some_xmits(conn);
1426 if (rp==OOP_CONTINUE) {
1427 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1429 } else if (rp==OOP_HALT) {
1432 /* transmitted everything */
1439 /*========== article transmission ==========*/
1441 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1442 XmitKind kind) { /* caller must then fill in details */
1443 struct iovec *v= &conn->xmit[conn->xmitu];
1444 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1445 v->iov_base= (char*)data;
1451 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1452 xmit_core(conn,data,len, xk_Const);
1454 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1456 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1457 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1461 static void xmit_free(XmitDetails *d) {
1463 case xk_Malloc: free(d->info.malloc_tofree); break;
1464 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1465 case xk_Const: break;
1470 static void *conn_write_some_xmits(Conn *conn) {
1472 * 0: nothing more to write, no need to call us again
1473 * OOP_CONTINUE: more to write but fd not writeable
1474 * OOP_HALT: disaster, have destroyed conn
1477 int count= conn->xmitu;
1478 if (!count) return 0;
1480 if (count > IOV_MAX) count= IOV_MAX;
1481 ssize_t rs= writev(conn->fd, conn->xmit, count);
1483 if (isewouldblock(errno)) return OOP_CONTINUE;
1484 connfail(conn, "write failed: %s", strerror(errno));
1490 for (done=0; rs && done<conn->xmitu; done++) {
1491 struct iovec *vp= &conn->xmit[done];
1492 XmitDetails *dp= &conn->xmitd[done];
1493 if (rs > vp->iov_len) {
1497 vp->iov_base= (char*)vp->iov_base + rs;
1501 int newu= conn->xmitu - done;
1502 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1503 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1508 static void conn_make_some_xmits(Conn *conn) {
1510 if (conn->xmitu+5 > CONNIOVS)
1513 Article *art= LIST_REMHEAD(conn->priority);
1514 if (!art) art= LIST_REMHEAD(conn->waiting);
1517 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1518 /* actually send it */
1520 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1523 art->state == art_Unchecked ? art_Unsolicited :
1524 art->state == art_Wanted ? art_Wanted :
1527 if (!artdata) art->missing= 1;
1528 art->ipf->counts[art->state][ artdata ? RC_sent : RC_missing ]++;
1532 XMIT_LITERAL("TAKETHIS ");
1533 xmit_noalloc(conn, art->messageid, art->midlen);
1534 XMIT_LITERAL("\r\n");
1535 xmit_artbody(conn, artdata);
1537 article_done(conn, art, -1);
1541 /* we got 235 from IHAVE */
1543 xmit_artbody(conn, artdata);
1545 XMIT_LITERAL(".\r\n");
1549 LIST_ADDTAIL(conn->sent, art);
1555 XMIT_LITERAL("CHECK ");
1557 XMIT_LITERAL("IHAVE ");
1558 xmit_noalloc(conn, art->messageid, art->midlen);
1559 XMIT_LITERAL("\r\n");
1561 assert(art->state == art_Unchecked);
1562 art->ipf->counts[art->state][RC_sent]++;
1563 LIST_ADDTAIL(conn->sent, art);
1569 /*========== handling responses from peer ==========*/
1571 static const oop_rd_style peer_rd_style= {
1572 OOP_RD_DELIM_STRIP, '\n',
1574 OOP_RD_SHORTREC_FORBID
1577 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1578 const char *errmsg, int errnoval,
1579 const char *data, size_t recsz, void *conn_v) {
1581 connfail(conn, "error receiving from peer: %s", errmsg);
1582 return OOP_CONTINUE;
1585 static Article *article_reply_check(Conn *conn, const char *response,
1586 int code_indicates_streaming,
1588 /* 1:yes, -1:no, 0:dontcare */,
1589 const char *sanitised_response) {
1590 Article *art= LIST_HEAD(conn->sent);
1594 "peer gave unexpected response when no commands outstanding: %s",
1595 sanitised_response);
1599 if (code_indicates_streaming) {
1600 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1601 if (!conn->stream) {
1602 connfail(conn, "peer gave streaming response code "
1603 " to IHAVE or subsequent body: %s", sanitised_response);
1606 const char *got_mid= response+4;
1607 int got_midlen= strcspn(got_mid, " \n\r");
1608 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1609 connfail(conn, "peer gave streaming response with syntactically invalid"
1610 " messageid: %s", sanitised_response);
1613 if (got_midlen != art->midlen ||
1614 memcmp(got_mid, art->messageid, got_midlen)) {
1615 connfail(conn, "peer gave streaming response code to wrong article -"
1616 " probable synchronisation problem; we offered: %s;"
1618 art->messageid, sanitised_response);
1623 connfail(conn, "peer gave non-streaming response code to"
1624 " CHECK/TAKETHIS: %s", sanitised_response);
1629 if (must_have_sent>0 && art->state < art_Wanted) {
1630 connfail(conn, "peer says article accepted but"
1631 " we had not sent the body: %s", sanitised_response);
1634 if (must_have_sent<0 && art->state >= art_Wanted) {
1635 connfail(conn, "peer says please sent the article but we just did: %s",
1636 sanitised_response);
1640 Article *art_again= LIST_REMHEAD(conn->sent);
1641 assert(art_again == art);
1645 static void update_nocheck(int accepted) {
1646 accept_proportion *= nocheck_decay;
1647 accept_proportion += accepted * (1.0 - nocheck_decay);
1648 int new_nocheck= accept_proportion >= nocheck_thresh;
1649 if (new_nocheck && !nocheck_reported) {
1650 notice("entering nocheck mode for the first time");
1651 nocheck_reported= 1;
1652 } else if (new_nocheck != nocheck) {
1653 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1655 nocheck= new_nocheck;
1658 static void article_done(Conn *conn, Article *art, int whichcount) {
1659 if (!art->missing) art->ipf->counts[art->state][whichcount]++;
1661 if (whichcount == RC_accepted) update_nocheck(1);
1662 else if (whichcount == RC_unwanted) update_nocheck(0);
1664 InputFile *ipf= art->ipf;
1666 while (art->blanklen) {
1667 static const char spaces[]=
1677 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1678 int r= pwrite(ipf->fd, spaces, w, art->offset);
1680 if (errno==EINTR) continue;
1681 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1682 art->messageid, art->blanklen,
1683 (unsigned long)art->offset, ipf->path);
1685 assert(r>=0 && r<=w);
1691 assert(ipf->inprogress >= 0);
1694 if (!ipf->inprogress && ipf != main_input_file)
1695 queue_check_input_done();
1698 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1699 const char *errmsg, int errnoval,
1700 const char *data, size_t recsz, void *conn_v) {
1703 if (ev == OOP_RD_EOF) {
1704 connfail(conn, "unexpected EOF from peer");
1705 return OOP_CONTINUE;
1707 assert(ev == OOP_RD_OK);
1709 char *sani= sanitise(data);
1712 unsigned long code= strtoul(data, &ep, 10);
1713 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1714 connfail(conn, "badly formatted response from peer: %s", sani);
1715 return OOP_CONTINUE;
1718 if (conn->quitting) {
1719 if (code!=205 && code!=503) {
1720 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1722 notice("C%d idle connection closed", conn->fd);
1723 assert(!conn->waiting.count);
1724 assert(!conn->priority.count);
1725 assert(!conn->sent.count);
1726 assert(!conn->xmitu);
1727 LIST_REMOVE(conns,conn);
1730 return OOP_CONTINUE;
1733 conn->since_activity= 0;
1736 #define GET_ARTICLE(musthavesent) \
1737 art= article_reply_check(conn, data, code_streaming, musthavesent, sani); \
1738 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1740 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1741 code_streaming= (streaming); \
1742 GET_ARTICLE(musthavesent); \
1743 article_done(conn, art, RC_##how); break;
1745 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1747 int code_streaming= 0;
1751 case 400: PEERBADMSG("peer stopped accepting articles");
1752 case 503: PEERBADMSG("peer timed us out");
1753 default: PEERBADMSG("peer sent unexpected message");
1755 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1756 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1758 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1759 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1761 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1762 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1764 case 238: /* CHECK says send it */
1766 case 335: /* IHAVE says send it */
1768 assert(art->state == art_Unchecked);
1769 art->ipf->counts[art->state][RC_accepted]++;
1770 art->state= art_Wanted;
1771 LIST_ADDTAIL(conn->priority, art);
1774 case 431: /* CHECK or TAKETHIS says try later */
1776 case 436: /* IHAVE says try later */
1779 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1781 sysfatal("write to defer file %s",path_defer);
1782 article_done(conn, art, RC_deferred);
1787 conn_maybe_write(conn);
1788 check_assign_articles();
1789 return OOP_CONTINUE;
1793 /*========== monitoring of input files ==========*/
1795 static void feedfile_eof(InputFile *ipf) {
1796 assert(ipf != main_input_file); /* promised by tailing_try_read */
1797 inputfile_reading_stop(ipf);
1799 if (ipf == flushing_input_file) {
1800 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1801 if (main_input_file) inputfile_reading_start(main_input_file);
1802 statemc_check_flushing_done();
1803 } else if (ipf == backlog_input_file) {
1804 statemc_check_backlog_done();
1806 abort(); /* supposed to wait rather than get EOF on main input file */
1810 static InputFile *open_input_file(const char *path) {
1811 int fd= open(path, O_RDWR);
1813 if (errno==ENOENT) return 0;
1814 sysfatal("unable to open input file %s", path);
1818 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1819 memset(ipf,0,sizeof(*ipf));
1822 strcpy(ipf->path, path);
1827 static void close_input_file(InputFile *ipf) { /* does not free */
1828 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1829 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1830 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1831 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1832 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1836 /*---------- dealing with articles read in the input file ----------*/
1838 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1839 const char *data, const char *how) {
1840 warn("corrupted file: %s, offset %lu: %s: in %s",
1841 ipf->path, (unsigned long)offset, how, sanitise(data));
1842 ipf->readcount_err++;
1843 if (ipf->readcount_err > max_bad_data_initial +
1844 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1845 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1846 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1847 return OOP_CONTINUE;
1850 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1851 oop_rd_event ev, const char *errmsg,
1852 int errnoval, const char *data, size_t recsz,
1854 InputFile *ipf= ipf_v;
1855 assert(ev == OOP_RD_SYSTEM);
1857 sysdie("error reading input file: %s, offset %lu",
1858 ipf->path, (unsigned long)ipf->offset);
1861 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1862 oop_rd_event ev, const char *errmsg,
1863 int errnoval, const char *data, size_t recsz,
1865 InputFile *ipf= ipf_v;
1867 char tokentextbuf[sizeof(TOKEN)*2+3];
1869 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1871 off_t old_offset= ipf->offset;
1872 ipf->offset += recsz + 1;
1874 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1876 if (ev==OOP_RD_PARTREC)
1877 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1878 /* but process it anyway */
1880 if (ipf->skippinglong) {
1881 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1882 return OOP_CONTINUE;
1884 if (ev==OOP_RD_LONG) {
1885 ipf->skippinglong= 1;
1886 X_BAD_DATA("overly long line");
1889 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1890 if (!recsz) X_BAD_DATA("empty line");
1893 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1894 ipf->readcount_blank++;
1895 return OOP_CONTINUE;
1898 char *space= strchr(data,' ');
1899 int tokenlen= space-data;
1900 int midlen= (int)recsz-tokenlen-1;
1901 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1902 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1904 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1905 memcpy(tokentextbuf, data, tokenlen);
1906 tokentextbuf[tokenlen]= 0;
1907 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1909 ipf->readcount_ok++;
1911 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1912 art->state= art_Unchecked;
1913 art->midlen= midlen;
1914 art->ipf= ipf; ipf->inprogress++;
1915 art->token= TextToToken(tokentextbuf);
1916 art->offset= old_offset;
1917 art->blanklen= recsz;
1918 strcpy(art->messageid, space+1);
1919 LIST_ADDTAIL(queue, art);
1921 if (sms==sm_NORMAL && ipf==main_input_file &&
1922 ipf->offset >= target_max_feedfile_size)
1923 statemc_start_flush("feed file size");
1925 check_assign_articles();
1926 return OOP_CONTINUE;
1929 /*========== tailing input file ==========*/
1931 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1933 InputFile *ipf= user;
1934 return ipf->readable_callback(loop, &ipf->readable,
1935 ipf->readable_callback_user);
1938 static void tailing_on_cancel(struct oop_readable *rable) {
1939 InputFile *ipf= (void*)rable;
1941 if (ipf->filemon) filemon_stop(ipf);
1942 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1943 ipf->readable_callback= 0;
1946 static void tailing_queue_readable(InputFile *ipf) {
1947 /* lifetime of ipf here is OK because destruction will cause
1948 * on_cancel which will cancel this callback */
1949 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1952 static int tailing_on_readable(struct oop_readable *rable,
1953 oop_readable_call *cb, void *user) {
1954 InputFile *ipf= (void*)rable;
1956 tailing_on_cancel(rable);
1957 ipf->readable_callback= cb;
1958 ipf->readable_callback_user= user;
1961 tailing_queue_readable(ipf);
1965 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1967 InputFile *ipf= (void*)rable;
1969 ssize_t r= read(ipf->fd, buffer, length);
1971 if (errno==EINTR) continue;
1975 if (ipf==main_input_file) {
1978 } else if (ipf==flushing_input_file) {
1980 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1981 } else if (ipf==backlog_input_file) {
1987 tailing_queue_readable(ipf);
1992 /*---------- filemon implemented with inotify ----------*/
1994 #if defined(HAVE_SYS_INOTIFY_H) && !defined(HAVE_FILEMON)
1995 #define HAVE_FILEMON
1997 #include <sys/inotify.h>
1999 static int filemon_inotify_fd;
2000 static int filemon_inotify_wdmax;
2001 static InputFile **filemon_inotify_wd2ipf;
2003 struct Filemon_Perfile {
2007 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
2008 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
2009 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
2011 if (wd >= filemon_inotify_wdmax) {
2013 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
2014 sizeof(*filemon_inotify_wd2ipf) * newmax);
2015 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
2016 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
2017 filemon_inotify_wdmax= newmax;
2020 assert(!filemon_inotify_wd2ipf[wd]);
2021 filemon_inotify_wd2ipf[wd]= ipf;
2023 debug("filemon inotify startfile %p wd=%d wdmax=%d",
2024 ipf, wd, filemon_inotify_wdmax);
2029 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
2031 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
2032 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
2033 if (r) sysdie("inotify_rm_watch");
2034 filemon_inotify_wd2ipf[wd]= 0;
2037 static void *filemon_inotify_readable(oop_source *lp, int fd,
2038 oop_event e, void *u) {
2039 struct inotify_event iev;
2041 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
2043 if (isewouldblock(errno)) break;
2044 sysdie("read from inotify master");
2045 } else if (r==sizeof(iev)) {
2046 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
2048 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
2050 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
2051 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
2052 filemon_callback(ipf);
2054 return OOP_CONTINUE;
2057 static int filemon_method_init(void) {
2058 filemon_inotify_fd= inotify_init();
2059 if (filemon_inotify_fd<0) {
2060 syswarn("filemon/inotify: inotify_init failed");
2064 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
2066 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2070 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2072 /*---------- filemon dummy implementation ----------*/
2074 #if !defined(HAVE_FILEMON)
2076 struct Filemon_Perfile { int dummy; };
2078 static int filemon_method_init(void) {
2079 warn("filemon/dummy: no filemon method compiled in");
2082 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2083 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2085 #endif /* !HAVE_FILEMON */
2087 /*---------- filemon generic interface ----------*/
2089 static void filemon_start(InputFile *ipf) {
2090 assert(!ipf->filemon);
2092 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
2093 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
2094 filemon_method_startfile(ipf, ipf->filemon);
2097 static void filemon_stop(InputFile *ipf) {
2098 if (!ipf->filemon) return;
2099 filemon_method_stopfile(ipf, ipf->filemon);
2104 static void filemon_callback(InputFile *ipf) {
2105 if (ipf && ipf->readable_callback) /* so filepoll() can be naive */
2106 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2109 /*---------- interface to start and stop an input file ----------*/
2111 static const oop_rd_style feedfile_rdstyle= {
2112 OOP_RD_DELIM_STRIP, '\n',
2114 OOP_RD_SHORTREC_LONG,
2117 static void inputfile_reading_start(InputFile *ipf) {
2119 ipf->readable.on_readable= tailing_on_readable;
2120 ipf->readable.on_cancel= tailing_on_cancel;
2121 ipf->readable.try_read= tailing_try_read;
2122 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2123 ipf->readable.delete_kill= 0;
2125 ipf->readable_callback= 0;
2126 ipf->readable_callback_user= 0;
2128 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2131 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2132 feedfile_got_article,ipf, feedfile_read_err, ipf);
2133 if (r) sysdie("unable start reading feedfile %s",ipf->path);
2136 static void inputfile_reading_stop(InputFile *ipf) {
2138 oop_rd_cancel(ipf->rd);
2139 oop_rd_delete(ipf->rd);
2141 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2145 /*========== interaction with innd - state machine ==========*/
2147 /* See official state diagram at top of file. We implement
2158 |`---------------------------------------------------.
2160 |`---------------- - - - |
2161 D ENOENT | D EXISTS see OVERALL STATES diagram |
2162 | for full startup logic |
2165 | ============ try to |
2171 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
2172 ^ | hardlink F to D |
2175 | | our handle onto F is now onto D |
2178 | |<-------------------<---------------------<---------+
2180 | | spawn inndcomm flush |
2182 | ================== |
2183 | FLUSHING[-ABSENT] |
2185 | main D tail/none |
2186 | ================== |
2188 | | INNDCOMM FLUSH FAILS ^
2189 | |`----------------------->----------. |
2191 | | NO SUCH SITE V |
2192 ^ |`--------------->----. ==================== |
2193 | | \ FLUSHFAILED[-ABSENT] |
2195 | | FLUSH OK \ main D tail/none |
2196 | | open F \ ==================== |
2198 | | \ | TIME TO RETRY |
2199 | |`------->----. ,---<---'\ `----------------'
2200 | | D NONE | | D NONE `----.
2202 | ============= V V ============
2203 | SEPARATED-1 | | DROPPING-1
2204 | flsh->rd!=0 | | flsh->rd!=0
2205 | [Separated] | | [Dropping]
2206 | main F idle | | main none
2207 | old D tail | | old D tail
2208 | ============= | | ============
2210 ^ | EOF ON D | | defer | EOF ON D
2212 | =============== | | ===============
2213 | SEPARATED-2 | | DROPPING-2
2214 | flsh->rd==0 | V flsh->rd==0
2215 | [Finishing] | | [Dropping]
2216 | main F tail | `. main none
2217 | old D closed | `. old D closed
2218 | =============== V `. ===============
2220 | | ALL D PROCESSED `. | ALL D PROCESSED
2221 | V install defer as backlog `. | install defer
2222 ^ | close D `. | close D
2223 | | unlink D `. | unlink D
2226 `----------' ==============
2246 static void startup_set_input_file(InputFile *f) {
2247 assert(!main_input_file);
2249 inputfile_reading_start(f);
2252 static void statemc_lock(void) {
2254 struct stat stab, stabf;
2257 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2258 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2261 memset(&fl,0,sizeof(fl));
2263 fl.l_whence= SEEK_SET;
2264 int r= fcntl(lockfd, F_SETLK, &fl);
2266 if (errno==EACCES || isewouldblock(errno)) {
2267 if (quiet_multiple) exit(0);
2268 fatal("another duct holds the lockfile");
2270 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2273 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2275 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2277 if (!lock_noent && samefile(&stab, &stabf))
2280 xclose(lockfd, "stale lockfile ", path_lock);
2283 FILE *lockfile= fdopen(lockfd, "w");
2284 if (!lockfile) sysdie("fdopen lockfile");
2286 int r= ftruncate(lockfd, 0);
2287 if (r) sysdie("truncate lockfile to write new info");
2289 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2290 (unsigned long)self_pid,
2291 sitename, feedfile, remote_host) == EOF ||
2293 sysfatal("write info to lockfile %s", path_lock);
2295 debug("startup: locked");
2298 static void statemc_init(void) {
2299 struct stat stabdefer;
2301 search_backlog_file();
2304 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2306 debug("startup: ductdefer ENOENT");
2308 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2309 switch (stabdefer.st_nlink==1) {
2311 open_defer(); /* so that we will later close it and rename it */
2314 xunlink(path_defer, "stale defer file link"
2315 " (presumably hardlink to backlog file)");
2318 die("defer file %s has unexpected link count %d",
2319 path_defer, stabdefer.st_nlink);
2323 struct stat stab_f, stab_d;
2326 InputFile *file_d= open_input_file(path_flushing);
2327 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2329 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2331 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2332 debug("startup: F==D => Hardlinked");
2333 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2338 debug("startup: F ENOENT => Moved");
2339 if (file_d) startup_set_input_file(file_d);
2340 spawn_inndcomm_flush("feedfile missing at startup");
2341 /* => Flushing, sms:=FLUSHING */
2344 debug("startup: F!=D => Separated");
2345 startup_set_input_file(file_d);
2346 SMS(SEPARATED, 0, "found both old and current feed files");
2348 debug("startup: F exists, D ENOENT => Normal");
2349 InputFile *file_f= open_input_file(feedfile);
2350 if (!file_f) die("feed file vanished during startup");
2351 startup_set_input_file(file_f);
2352 SMS(NORMAL, spontaneous_flush_periods, "normal startup");
2357 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2358 assert(sms == sm_NORMAL);
2360 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2362 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2363 (unsigned long)target_max_feedfile_size,
2366 int r= link(feedfile, path_flushing);
2367 if (r) sysfatal("link feedfile %s to flushing file %s",
2368 feedfile, path_flushing);
2371 xunlink(feedfile, "old feedfile link");
2374 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2377 static void statemc_period_poll(void) {
2378 if (!sm_period_counter) return;
2379 sm_period_counter--;
2380 assert(sm_period_counter>=0);
2382 if (sm_period_counter) return;
2385 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2387 case sm_FLUSHFAILED:
2388 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2395 static int inputfile_is_done(InputFile *ipf) {
2397 if (ipf->inprogress) return 0; /* new article in the meantime */
2398 if (ipf->rd) return 0; /* not had EOF */
2402 static void notice_processed(InputFile *ipf, const char *what,
2404 #define RCI_NOTHING(x) /* nothing */
2405 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2406 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2408 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2410 info("processed %s%s read=%d (+bl=%d,+err=%d)"
2411 " offered=%d (ch=%d,nc=%d) accepted=%d (ch=%d,nc=%d)"
2412 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2415 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2416 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2417 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2418 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2419 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2420 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2426 static void statemc_check_backlog_done(void) {
2427 InputFile *ipf= backlog_input_file;
2428 if (!inputfile_is_done(ipf)) return;
2430 const char *slash= strrchr(ipf->path, '/');
2431 const char *leaf= slash ? slash+1 : ipf->path;
2432 const char *under= strchr(slash, '_');
2433 const char *rest= under ? under+1 : leaf;
2434 if (!strncmp(rest,"backlog",7)) rest += 7;
2435 notice_processed(ipf,"backlog ",rest);
2437 close_input_file(ipf);
2438 if (unlink(ipf->path)) {
2439 if (errno != ENOENT)
2440 sysdie("could not unlink processed backlog file %s", ipf->path);
2441 warn("backlog file %s vanished while we were reading it"
2442 " so we couldn't remove it (but it's done now, anyway)",
2446 backlog_input_file= 0;
2447 search_backlog_file();
2451 static void statemc_check_flushing_done(void) {
2452 InputFile *ipf= flushing_input_file;
2453 if (!inputfile_is_done(ipf)) return;
2455 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2457 notice_processed(ipf,"feedfile","");
2461 xunlink(path_flushing, "old flushing file");
2463 close_input_file(flushing_input_file);
2464 free(flushing_input_file);
2465 flushing_input_file= 0;
2467 if (sms==sm_SEPARATED) {
2468 notice("flush complete");
2469 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2470 } else if (sms==sm_DROPPING) {
2471 SMS(DROPPED, 0, "old flush complete");
2472 search_backlog_file();
2473 notice("feed dropped, but will continue until backlog is finished");
2477 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2479 assert(!inputfile_is_done(main_input_file));
2480 statemc_check_flushing_done();
2481 statemc_check_backlog_done();
2482 return OOP_CONTINUE;
2485 static void queue_check_input_done(void) {
2486 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2489 static void statemc_setstate(StateMachineState newsms, int periods,
2490 const char *forlog, const char *why) {
2492 sm_period_counter= periods;
2494 const char *xtra= "";
2497 case sm_FLUSHFAILED:
2498 if (!main_input_file) xtra= "-ABSENT";
2502 xtra= flushing_input_file->rd ? "-1" : "-2";
2508 info("state %s%s[%d] %s",forlog,xtra,periods,why);
2510 info("state %s%s %s",forlog,xtra,why);
2514 /*---------- defer and backlog files ----------*/
2516 static void open_defer(void) {
2521 defer= fopen(path_defer, "a+");
2522 if (!defer) sysfatal("could not open defer file %s", path_defer);
2524 /* truncate away any half-written records */
2526 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2528 if (stab.st_size > LONG_MAX)
2529 die("defer file %s size is far too large", path_defer);
2534 long orgsize= stab.st_size;
2535 long truncto= stab.st_size;
2537 if (!truncto) break; /* was only (if anything) one half-truncated record */
2538 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2539 sysdie("seek in defer file %s while truncating partial", path_defer);
2544 sysdie("failed read from defer file %s", path_defer);
2546 die("defer file %s shrank while we were checking it!", path_defer);
2552 if (stab.st_size != truncto) {
2553 warn("truncating half-record at end of defer file %s -"
2554 " shrinking by %ld bytes from %ld to %ld",
2555 path_defer, orgsize - truncto, orgsize, truncto);
2558 sysfatal("could not flush defer file %s", path_defer);
2559 if (ftruncate(fileno(defer), truncto))
2560 sysdie("could not truncate defer file %s", path_defer);
2563 info("continuing existing defer file %s (%ld bytes)",
2564 path_defer, orgsize);
2566 if (fseek(defer, truncto, SEEK_SET))
2567 sysdie("could not seek to new end of defer file %s", path_defer);
2570 static void close_defer(void) {
2575 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2577 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2580 time_t now= xtime();
2582 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2584 (unsigned long)stab.st_ino);
2585 if (link(path_defer, backlog))
2586 sysfatal("could not install defer file %s as backlog file %s",
2587 path_defer, backlog);
2588 if (unlink(path_defer))
2589 sysdie("could not unlink old defer link %s to backlog file %s",
2590 path_defer, backlog);
2594 if (until_backlog_nextscan < 0 ||
2595 until_backlog_nextscan > backlog_retry_minperiods + 1)
2596 until_backlog_nextscan= backlog_retry_minperiods + 1;
2599 static void poll_backlog_file(void) {
2600 if (until_backlog_nextscan < 0) return;
2601 if (until_backlog_nextscan-- > 0) return;
2602 search_backlog_file();
2605 static void search_backlog_file(void) {
2606 /* returns non-0 iff there are any backlog files */
2611 const char *oldest_path=0;
2612 time_t oldest_mtime=0, now;
2614 if (backlog_input_file) return;
2618 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2622 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2624 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2626 for (i=0; i<gl.gl_pathc; i++) {
2627 const char *path= gl.gl_pathv[i];
2629 if (strchr(path,'#') || strchr(path,'~')) {
2630 debug("backlog file search skipping %s", path);
2633 r= stat(path, &stab);
2635 syswarn("failed to stat backlog file %s", path);
2638 if (!S_ISREG(stab.st_mode)) {
2639 warn("backlog file %s is not a plain file (or link to one)", path);
2642 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2644 oldest_mtime= stab.st_mtime;
2647 case GLOB_NOMATCH: /* fall through */
2650 sysdie("glob expansion of backlog pattern %s gave unexpected"
2651 " nonzero (error?) return value %d", globpat_backlog, r);
2655 debug("backlog scan: none");
2657 if (sms==sm_DROPPED) {
2658 notice("feed dropped and our work is complete");
2660 int r= unlink(path_control);
2661 if (r && errno!=ENOENT)
2662 syswarn("failed to remove control symlink for old feed");
2664 xunlink(path_lock, "lockfile for old feed");
2667 until_backlog_nextscan= backlog_spontrescan_periods;
2672 double age= difftime(now, oldest_mtime);
2673 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2675 if (age_deficiency <= 0) {
2676 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2677 age, age_deficiency, oldest_path);
2679 backlog_input_file= open_input_file(oldest_path);
2680 if (!backlog_input_file) {
2681 warn("backlog file %s vanished as we opened it", oldest_path);
2685 inputfile_reading_start(backlog_input_file);
2686 until_backlog_nextscan= -1;
2690 until_backlog_nextscan= age_deficiency / period_seconds;
2692 if (backlog_spontrescan_periods >= 0 &&
2693 until_backlog_nextscan > backlog_spontrescan_periods)
2694 until_backlog_nextscan= backlog_spontrescan_periods;
2696 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2697 age, age_deficiency, until_backlog_nextscan, oldest_path);
2704 /*========== flushing the feed ==========*/
2706 static pid_t inndcomm_child;
2707 static int inndcomm_sentinel_fd;
2709 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2710 assert(inndcomm_child);
2711 assert(fd == inndcomm_sentinel_fd);
2712 int status= xwaitpid(&inndcomm_child, "inndcomm");
2715 cancel_fd_read_except(fd);
2716 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2717 inndcomm_sentinel_fd= 0;
2719 assert(!flushing_input_file);
2721 if (WIFEXITED(status)) {
2722 switch (WEXITSTATUS(status)) {
2724 case INNDCOMMCHILD_ESTATUS_FAIL:
2727 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2728 notice("feed has been dropped by innd, finishing up");
2729 flushing_input_file= main_input_file;
2730 tailing_queue_readable(flushing_input_file);
2731 /* we probably previously returned EAGAIN from our fake read method
2732 * when in fact we were at EOF, so signal another readable event
2733 * so we actually see the EOF */
2737 if (flushing_input_file) {
2738 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2741 SMS(DROPPED, 0, "feed dropped by innd");
2742 search_backlog_file();
2744 return OOP_CONTINUE;
2748 flushing_input_file= main_input_file;
2749 tailing_queue_readable(flushing_input_file);
2751 main_input_file= open_input_file(feedfile);
2752 if (!main_input_file)
2753 die("flush succeeded but feedfile %s does not exist!", feedfile);
2755 if (flushing_input_file) {
2756 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2759 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2761 return OOP_CONTINUE;
2764 goto unexpected_exitstatus;
2767 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2768 warn("flush timed out trying to talk to innd");
2771 unexpected_exitstatus:
2772 report_child_status("inndcomm child", status);
2776 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2777 return OOP_CONTINUE;
2780 static void inndcommfail(const char *what) {
2781 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2782 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2785 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2788 notice("flushing %s",why);
2790 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2791 assert(!inndcomm_child);
2792 assert(!inndcomm_sentinel_fd);
2794 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2796 inndcomm_child= xfork("inndcomm child");
2798 if (!inndcomm_child) {
2799 const char *flushargv[2]= { sitename, 0 };
2803 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2804 /* parent spots the autoclose of pipefds[1] when we die or exit */
2806 if (simulate_flush>=0) {
2807 warn("SIMULATING flush child status %d", simulate_flush);
2808 if (simulate_flush>128) raise(simulate_flush-128);
2809 else exit(simulate_flush);
2812 alarm(inndcomm_flush_timeout);
2813 r= ICCopen(); if (r) inndcommfail("connect");
2814 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2815 if (!r) exit(0); /* yay! */
2817 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2818 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2819 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2824 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2825 inndcomm_sentinel_fd= pipefds[0];
2826 assert(inndcomm_sentinel_fd);
2827 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2829 SMS(FLUSHING, 0, why);
2832 /*========== main program ==========*/
2834 static void postfork_inputfile(InputFile *ipf) {
2836 xclose(ipf->fd, "(in child) input file ", ipf->path);
2839 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2840 /* we have no stdio streams that are buffered long-term */
2842 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2845 static void postfork(void) {
2846 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2847 sysdie("(in child) failed to reset SIGPIPE");
2849 postfork_inputfile(main_input_file);
2850 postfork_inputfile(flushing_input_file);
2853 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2854 conn_closefd(conn,"(in child) ");
2856 postfork_stdio(defer, "defer file ", path_defer);
2859 typedef struct Every Every;
2861 struct timeval interval;
2866 static void every_schedule(Every *e, struct timeval base);
2868 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
2871 if (!e->fixed_rate) xgettimeofday(&base);
2872 every_schedule(e, base);
2873 return OOP_CONTINUE;
2876 static void every_schedule(Every *e, struct timeval base) {
2877 struct timeval when;
2878 timeradd(&base, &e->interval, &when);
2879 loop->on_time(loop, when, every_happens, e);
2882 static void every(int interval, int fixed_rate, void (*f)(void)) {
2883 Every *e= xmalloc(sizeof(*e));
2884 e->interval.tv_sec= interval;
2885 e->interval.tv_usec= 0;
2886 e->fixed_rate= fixed_rate;
2889 xgettimeofday(&now);
2890 every_schedule(e, now);
2893 static void filepoll(void) {
2894 filemon_callback(main_input_file);
2895 filemon_callback(flushing_input_file);
2898 static char *debug_report_ipf(InputFile *ipf) {
2899 if (!ipf) return xasprintf("none");
2901 const char *slash= strrchr(ipf->path,'/');
2902 const char *path= slash ? slash+1 : ipf->path;
2904 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2906 ipf->inprogress, (long)ipf->offset,
2907 ipf->fd, ipf->rd ? "" : ",!rd");
2910 static void period(void) {
2911 char *dipf_main= debug_report_ipf(main_input_file);
2912 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2913 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2916 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2917 " input_files main:%s flushing:%s backlog:%s"
2918 " children connecting=%ld inndcomm=%ld"
2920 sms_names[sms], sm_period_counter,
2921 conns.count, queue.count, until_connect,
2922 dipf_main, dipf_flushing, dipf_backlog,
2923 (long)connecting_child, (long)inndcomm_child
2927 free(dipf_flushing);
2930 if (until_connect) until_connect--;
2932 poll_backlog_file();
2933 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2934 statemc_period_poll();
2935 check_assign_articles();
2940 /*========== option parsing ==========*/
2942 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2943 static void vbadusage(const char *fmt, va_list al) {
2944 char *m= xvasprintf(fmt,al);
2945 fprintf(stderr, "bad usage: %s\n"
2946 "say --help for help, or read the manpage\n",
2949 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2953 /*---------- generic option parser ----------*/
2955 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2956 static void badusage(const char *fmt, ...) {
2963 of_seconds= 001000u,
2964 of_boolean= 002000u,
2967 typedef struct Option Option;
2968 typedef void OptionParser(const Option*, const char *val);
2972 const char *lng, *formarg;
2978 static void parse_options(const Option *options, char ***argvp) {
2979 /* on return *argvp is first non-option arg; argc is not updated */
2982 const char *arg= *++(*argvp);
2984 if (*arg != '-') break;
2985 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2987 while ((a= *++arg)) {
2991 char *equals= strchr(arg,'=');
2992 int len= equals ? (equals - arg) : strlen(arg);
2993 for (o=options; o->shrt || o->lng; o++)
2994 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2996 badusage("unknown long option --%s",arg);
2999 if (equals) badusage("option --%s does not take a value",o->lng);
3001 } else if (equals) {
3005 if (!arg) badusage("option --%s needs a value for %s",
3006 o->lng, o->formarg);
3009 break; /* eaten the whole argument now */
3011 for (o=options; o->shrt || o->lng; o++)
3014 badusage("unknown short option -%c",a);
3021 if (!arg) badusage("option -%c needs a value for %s",
3022 o->shrt, o->formarg);
3025 break; /* eaten the whole argument now */
3031 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
3033 static void print_options(const Option *options, FILE *f) {
3035 for (o=options; o->shrt || o->lng; o++) {
3036 char shrt[2] = { o->shrt, 0 };
3037 char *optspec= xasprintf("%s%s%s%s%s",
3038 o->shrt ? "-" : "", shrt,
3039 o->shrt && o->lng ? "|" : "",
3040 DELIMPERHAPS("--", o->lng));
3041 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
3046 /*---------- specific option types ----------*/
3048 static void op_integer(const Option *o, const char *val) {
3051 unsigned long ul= strtoul(val,&ep,10);
3052 if (*ep || ep==val || errno || ul>INT_MAX)
3053 badusage("bad integer value for %s",o->lng);
3054 int *store= o->store;
3058 static void op_double(const Option *o, const char *val) {
3059 int *store= o->store;
3062 *store= strtod(val, &ep);
3063 if (*ep || ep==val || errno)
3064 badusage("bad floating point value for %s",o->lng);
3067 static void op_string(const Option *o, const char *val) {
3068 const char **store= o->store;
3072 static void op_seconds(const Option *o, const char *val) {
3073 int *store= o->store;
3077 double v= strtod(val,&ep);
3078 if (ep==val) badusage("bad time/duration value for %s",o->lng);
3080 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
3081 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
3082 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
3083 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
3084 else if (!strcmp(ep,"das")) unit= 10;
3085 else if (!strcmp(ep,"hs")) unit= 100;
3086 else if (!strcmp(ep,"ks")) unit= 1000;
3087 else if (!strcmp(ep,"Ms")) unit= 1000000;
3088 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
3092 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
3096 static void op_setint(const Option *o, const char *val) {
3097 int *store= o->store;
3101 /*---------- specific options ----------*/
3103 static void help(const Option *o, const char *val);
3105 static const Option innduct_options[]= {
3106 {'f',"feedfile", "F", &feedfile, op_string },
3107 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
3108 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
3109 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
3110 {'C',"inndconf", "F", &inndconffile, op_string },
3111 {'P',"port", "PORT", &port, op_integer },
3112 {0,"help", 0, 0, help },
3114 {0,"max-connections", "N", &max_connections, op_integer },
3115 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
3116 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
3117 {0,"period-interval", "TIME", &period_seconds, op_seconds },
3119 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
3120 {0,"stuck-flush-timeout","TIME", &inndcomm_flush_timeout, op_seconds },
3122 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
3123 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
3125 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
3126 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
3127 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3128 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3129 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
3130 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
3132 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
3133 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
3138 static void printusage(FILE *f) {
3139 fputs("usage: innduct [options] site [fqdn]\n"
3140 "available options are:\n", f);
3141 print_options(innduct_options, f);
3144 static void help(const Option *o, const char *val) {
3146 if (ferror(stdout) || fflush(stdout)) {
3147 perror("innduct: writing help");
3153 static void convert_to_periods_rndup(int *store) {
3154 *store += period_seconds-1;
3155 *store /= period_seconds;
3158 int main(int argc, char **argv) {
3164 parse_options(innduct_options, &argv);
3169 if (!sitename) badusage("need site name argument");
3170 remote_host= *argv++;
3171 if (*argv) badusage("too many non-option arguments");
3175 int r= innconf_read(inndconffile);
3176 if (!r) badusage("could not read inn.conf (more info on stderr)");
3178 if (!remote_host) remote_host= sitename;
3180 if (nocheck_thresh < 0 || nocheck_thresh > 100)
3181 badusage("nocheck threshold percentage must be between 0..100");
3182 nocheck_thresh *= 0.01;
3184 if (nocheck_decay < 0.1)
3185 badusage("nocheck decay articles must be at least 0.1");
3186 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3188 convert_to_periods_rndup(&reconnect_delay_periods);
3189 convert_to_periods_rndup(&flushfail_retry_periods);
3190 convert_to_periods_rndup(&backlog_retry_minperiods);
3191 convert_to_periods_rndup(&backlog_spontrescan_periods);
3192 convert_to_periods_rndup(&spontaneous_flush_periods);
3193 convert_to_periods_rndup(&need_activity_periods);
3195 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3196 badusage("bad input data ratio must be between 0..100");
3197 max_bad_data_ratio *= 0.01;
3200 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3201 } else if (!feedfile[0]) {
3202 badusage("feed filename must be nonempty");
3203 } else if (feedfile[strlen(feedfile)-1]=='/') {
3204 feedfile= xasprintf("%s%s",feedfile,sitename);
3207 const char *feedfile_forbidden= "?*[~#";
3209 while ((c= *feedfile_forbidden++))
3210 if (strchr(feedfile, c))
3211 badusage("feed filename may not contain metacharacter %c",c);
3215 path_lock= xasprintf("%s_lock", feedfile);
3216 path_flushing= xasprintf("%s_flushing", feedfile);
3217 path_defer= xasprintf("%s_defer", feedfile);
3218 path_control= xasprintf("%s_control", feedfile);
3219 globpat_backlog= xasprintf("%s_backlog*", feedfile);
3221 oop_source_sys *sysloop= oop_sys_new();
3222 if (!sysloop) sysdie("could not create liboop event loop");
3223 loop= (oop_source*)sysloop;
3225 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3226 sysdie("could not ignore SIGPIPE");
3231 if (become_daemon) {
3233 for (i=3; i<255; i++)
3234 /* do this now before we open syslog, etc. */
3236 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3238 int null= open("/dev/null",O_RDWR);
3239 if (null<0) sysfatal("failed to open /dev/null");
3243 xclose(null, "/dev/null original fd",0);
3245 pid_t child1= xfork("daemonise first fork");
3246 if (child1) _exit(0);
3248 pid_t sid= setsid();
3249 if (sid != child1) sysfatal("setsid failed");
3251 pid_t child2= xfork("daemonise second fork");
3252 if (child2) _exit(0);
3256 if (self_pid==-1) sysdie("getpid");
3267 if (!filemon_method_init()) {
3268 warn("filemon: no file monitoring available, polling");
3269 every(5,0,filepoll);
3272 every(period_seconds,1,period);
3278 void *run= oop_sys_run(sysloop);
3279 assert(run == OOP_ERROR);
3280 sysdie("event loop failed");