5 [740] <sit> info: processed feedfile(null) read=4(+0bl,+6err) offered=5(ch5,nc0) accepted=0(ch0+nc0) unwanted=0(0id+0bd+0nc) rejected=0(0id+0bd+0nc) deferred=0(0id+0bd+0nc) missing=2(0id+2bd+0nc) connretry=0(0id+0bd+0nc)
9 also unwanted should be nonzero I think
11 %d( is too hard to read
13 [740] <sit> warning: corrupted file: /home/ian/things/Innfeed/inn2-2.4.5/fee, offset 349: line partially blanked: in ` @050000002D130000006A0000000000000000@ <mi'..
17 * - actually do something with readable on control master
18 * - option for realsockdir
19 * - option for filepoll
20 * - option for no inotify
21 * - manpage: document control master stuff
22 * - manpage: innconf is used for communicating with innd
24 * build-lfs/backends/innduct --no-daemon -f `pwd`/fee sit dom
28 * Newsfeeds file entries should look like this:
29 * host.name.of.site[/exclude,exclude,...]\
30 * :pattern,pattern...[/distribution,distribution...]\
34 * sitename[/exclude,exclude,...]\
35 * :pattern,pattern...[/distribution,distribution...]\
41 * or might be blanked out
42 * <spc><spc><spc><spc>....
44 * F site.name main feed file
45 * opened/created, then written, by innd
48 * tokens blanked out by duct when processed
49 * site.name_lock lock preventing multiple ducts
50 * to hold lock must open,F_SETLK[W]
51 * and then stat to check that locked file
52 * still has name site.name_lock
53 * holder of this lock is "duct"
54 * (only) lockholder may remove the lockfile
55 * D site.name_flushing temporary feed file during flush (or crash)
56 * hardlink created by duct
58 * site.name_defer 431'd articles, still being written,
59 * created, written, used by duct
61 * site.name_backlog.<date>.<inum>
62 * 431'd articles, ready for innxmit or duct
63 * created (link/mv) by duct
64 * site.name_backlog<anything-else> (where <anything-else> does not
65 * contain '#' or '~') eg
66 * site.name_backlog.manual
67 * anything the sysadmin likes (eg, feed files
68 * from old feeds to be merged into this one)
69 * created (link/mv) by admin
70 * may be symlinks (in which case links
71 * may be written through, but only links
74 * It is safe to remove backlog files manually,
75 * if it's desired to throw away the backlog.
77 * Backlog files are also processed by innduct. We find the oldest
78 * backlog file which is at least a certain amount old, and feed it
79 * back into our processing. When every article in it has been read
80 * and processed, we unlink it and look for another backlog file.
82 * If we don't have a backlog file that we're reading, we close the
83 * defer file that we're writing and make it into a backlog file at
84 * the first convenient opportunity.
95 | | <----------------<---------------------------------'|
101 | F: innd writing, duct reading |
104 | | duct decides time to flush |
105 | | duct makes hardlink |
107 | V <------------------------'|
109 | F == D: innd writing, duct reading both exist |
112 | | <-----------<-------------<--'|
113 | | open D F ENOENT |
116 | V <---------------------. |
119 | D: innd writing, duct reading; or ENOENT | |
121 | | duct requests flush of feed | |
122 | | (others can too, harmlessly) | |
126 | D: innd flushing, duct; or ENOENT | |
128 | | inndcomm flush fails | |
129 | |`-------------------------->------------------' |
131 | | inndcomm reports no such site |
132 | |`---------------------------------------------------- | -.
134 | | innd finishes writing D, creates F | |
135 | | inndcomm reports flush successful | |
138 | Separated <----------------' |
139 | F: innd writing F!=D /
140 | D: duct reading; or ENOENT both exist /
142 | | duct gets to the end of D /
143 | | duct opens F too /
146 | F: innd writing, duct reading |
147 | D: duct finishing V
149 | | duct finishes processing D F: ENOENT
150 | V duct unlinks D D: duct reading
152 `--<--' | duct finishes
162 "duct reading" means innduct is reading the file but also
163 overwriting processed tokens.
167 * rune for printing diagrams:
169 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
174 /*============================== PROGRAM ==============================*/
176 #define _GNU_SOURCE 1
182 #include "inndcomm.h"
184 #include "inn/list.h"
185 #include "inn/innconf.h"
188 #include <sys/types.h>
189 #include <sys/wait.h>
190 #include <sys/stat.h>
191 #include <sys/socket.h>
210 #include <oop-read.h>
212 /*----- general definitions, probably best not changed -----*/
214 #define CONNCHILD_ESTATUS_STREAM 24
215 #define CONNCHILD_ESTATUS_NOSTREAM 25
217 #define INNDCOMMCHILD_ESTATUS_FAIL 26
218 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
220 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
221 #define MAX_CONTROL_COMMAND 1000
223 #define VA va_list al; va_start(al,fmt)
224 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
225 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
227 /*----- doubly linked lists -----*/
229 #define ISNODE(T) struct node list_node
232 union { struct list li; T *for_type; } u; \
236 #define NODE(n) (assert((void*)&(n)->list_node == (n)), &(n)->list_node)
238 #define LIST_CHECKCANHAVENODE(l,n) \
239 ((void)((n) == ((l).u.for_type))) /* just for the type check */
241 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
242 ( LIST_CHECKCANHAVENODE(l,n), \
243 list_addsomehow(&(l).u.li, NODE((n))), \
247 #define LIST_REMSOMEHOW(l,list_remsomehow) \
248 ( (typeof((l).u.for_type)) \
251 list_remsomehow(&(l).u.li) ) \
257 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
258 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
259 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
260 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
262 #define LIST_INIT(l) ((l).count=0, list_new(&(l).u.li))
263 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
264 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
265 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
267 #define LIST_REMOVE(l,n) \
268 ( LIST_CHECKCANHAVENODE(l,n), \
269 list_remove(NODE((n))), \
273 #define LIST_INSERT(l,n,pred) \
274 ( LIST_CHECKCANHAVENODE(l,n), \
275 LIST_CHECKCANHAVENODE(l,pred), \
276 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
280 /*----- type predeclarations -----*/
282 typedef struct Conn Conn;
283 typedef struct Article Article;
284 typedef struct InputFile InputFile;
285 typedef struct XmitDetails XmitDetails;
286 typedef struct Filemon_Perfile Filemon_Perfile;
287 typedef enum StateMachineState StateMachineState;
292 /*----- function predeclarations -----*/
294 static void conn_maybe_write(Conn *conn);
295 static void conn_make_some_xmits(Conn *conn);
296 static void *conn_write_some_xmits(Conn *conn);
298 static void xmit_free(XmitDetails *d);
300 #define SMS(newstate, periods, why) \
301 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
302 static void statemc_setstate(StateMachineState newsms, int periods,
303 const char *forlog, const char *why);
305 static void statemc_start_flush(const char *why); /* Normal => Flushing */
306 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
308 static void article_done(Conn *conn, Article *art, int whichcount);
310 static void check_assign_articles(void);
311 static void queue_check_input_done(void);
313 static void statemc_check_flushing_done(void);
314 static void statemc_check_backlog_done(void);
316 static void postfork(void);
317 static void period(void);
319 static void open_defer(void);
320 static void close_defer(void);
321 static void search_backlog_file(void);
323 static void inputfile_reading_start(InputFile *ipf);
324 static void inputfile_reading_stop(InputFile *ipf);
326 static void filemon_start(InputFile *ipf);
327 static void filemon_stop(InputFile *ipf);
328 static void filemon_callback(InputFile *ipf);
330 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
331 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
333 static const oop_rd_style peer_rd_style;
334 static oop_rd_call peer_rd_err, peer_rd_ok;
336 /*----- configuration options -----*/
337 /* when changing defaults, remember to update the manpage */
339 static const char *sitename, *remote_host;
340 static const char *feedfile, *realsockdir="/tmp/innduct.control";
341 static int quiet_multiple=0;
342 static int become_daemon=1;
343 static int try_stream=1;
345 static const char *inndconffile;
347 static int max_connections=10;
348 static int max_queue_per_conn=200;
349 static int target_max_feedfile_size=100000;
350 static int period_seconds=60;
352 static int connection_setup_timeout=200;
353 static int inndcomm_flush_timeout=100;
355 static double nocheck_thresh= 95.0; /* converted from percentage by main */
356 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
358 /* all these are initialised to seconds, and converted to periods in main */
359 static int reconnect_delay_periods=1000;
360 static int flushfail_retry_periods=1000;
361 static int backlog_retry_minperiods=50;
362 static int backlog_spontrescan_periods=300;
363 static int spontaneous_flush_periods=100000;
364 static int need_activity_periods=1000;
366 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
367 static int max_bad_data_initial= 30;
368 /* in one corrupt 4096-byte block the number of newlines has
369 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
372 /*----- statistics -----*/
374 typedef enum { /* in queue in conn->sent */
375 art_Unchecked, /* not checked, not sent checking */
376 art_Wanted, /* checked, wanted sent body as requested */
377 art_Unsolicited, /* - sent body without check */
381 #define RESULT_COUNTS(RCS,RCN) \
390 #define RCI_TRIPLE_FMT_BASE "%d(%did+%dbd+%dnc)"
391 #define RCI_TRIPLE_VALS_BASE(counts,x) \
392 counts[art_Unchecked] x \
393 + counts[art_Wanted] x \
394 + counts[art_Unsolicited] x, \
395 counts[art_Unchecked] x \
396 , counts[art_Wanted] x \
397 , counts[art_Unsolicited] x
400 #define RC_INDEX(x) RC_##x,
401 RESULT_COUNTS(RC_INDEX, RC_INDEX)
406 /*----- transmission buffers -----*/
411 xk_Malloc, xk_Const, xk_Artdata
423 /*----- core operational data structure types -----*/
426 /* This is also an instance of struct oop_readable */
427 struct oop_readable readable; /* first */
428 oop_readable_call *readable_callback;
429 void *readable_callback_user;
432 Filemon_Perfile *filemon;
434 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
435 long inprogress; /* no. of articles read but not processed */
439 int counts[art_MaxState][RCI_max];
440 int readcount_ok, readcount_blank, readcount_err;
455 #define SMS_LIST(X) \
463 enum StateMachineState {
464 #define SMS_DEF_ENUM(s) sm_##s,
465 SMS_LIST(SMS_DEF_ENUM)
468 static const char *sms_names[]= {
469 #define SMS_DEF_NAME(s) #s ,
470 SMS_LIST(SMS_DEF_NAME)
476 int fd; /* may be 0, meaning closed (during construction/destruction) */
477 oop_read *rd; /* likewise */
478 int max_queue, stream, quitting;
479 int since_activity; /* periods */
480 ArticleList waiting; /* not yet told peer */
481 ArticleList priority; /* peer says send it now */
482 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
483 struct iovec xmit[CONNIOVS];
484 XmitDetails xmitd[CONNIOVS];
489 /*----- general operational variables -----*/
491 /* main initialises */
492 static oop_source *loop;
493 static ConnList conns;
494 static ArticleList queue;
495 static char *path_lock, *path_flushing, *path_defer, *path_control;
496 static char *globpat_backlog;
497 static pid_t self_pid;
499 /* statemc_init initialises */
500 static StateMachineState sms;
502 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
503 static int sm_period_counter;
505 /* initialisation to 0 is good */
506 static int until_connect, until_backlog_nextscan;
507 static double accept_proportion;
508 static int nocheck, nocheck_reported;
510 /* for simulation, debugging, etc. */
511 int simulate_flush= -1;
513 /*========== logging ==========*/
515 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
516 static void logcore(int sysloglevel, const char *fmt, ...) {
519 vsyslog(sysloglevel,fmt,al);
521 if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
522 vfprintf(stderr,fmt,al);
528 static void logv(int sysloglevel, const char *pfx, int errnoval,
529 const char *fmt, va_list al) PRINTF(5,0);
530 static void logv(int sysloglevel, const char *pfx, int errnoval,
531 const char *fmt, va_list al) {
532 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
533 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
534 msgbuf[sizeof(msgbuf)-1]= 0;
536 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
537 sysloglevel= LOG_ERR; /* run by wrong user, probably */
539 logcore(sysloglevel, "<%s>%s: %s%s%s",
540 sitename, pfx, msgbuf,
541 errnoval>=0 ? ": " : "",
542 errnoval>=0 ? strerror(errnoval) : "");
545 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
546 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
547 static void fn(const char *fmt, ...) { \
549 logv(sysloglevel, pfx, err, fmt, al); \
553 #define logwrap(fn, pfx, sysloglevel, err) \
554 static void fn(const char *fmt, ...) PRINTF(1,2); \
555 static void fn(const char *fmt, ...) { \
557 logv(sysloglevel, pfx, err, fmt, al); \
561 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
562 diewrap(die, " critical", LOG_CRIT, -1, 16);
564 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
565 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
567 logwrap(syswarn, " warning", LOG_WARNING, errno);
568 logwrap(warn, " warning", LOG_WARNING, -1);
570 logwrap(notice, " notice", LOG_NOTICE, -1);
571 logwrap(info, " info", LOG_INFO, -1);
572 logwrap(debug, " debug", LOG_DEBUG, -1);
575 /*========== utility functions etc. ==========*/
577 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
578 static char *xvasprintf(const char *fmt, va_list al) {
580 int rc= vasprintf(&str,fmt,al);
581 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
584 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
585 static char *xasprintf(const char *fmt, ...) {
587 char *str= xvasprintf(fmt,al);
592 static int close_perhaps(int *fd) {
593 if (*fd <= 0) return 0;
598 static void xclose(int fd, const char *what, const char *what2) {
600 if (r) sysdie("close %s%s",what,what2?what2:"");
602 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
603 if (*fd <= 0) return;
604 xclose(*fd,what,what2);
608 static pid_t xfork(const char *what) {
612 if (child==-1) sysfatal("cannot fork for %s",what);
613 debug("forked %s %ld", what, (unsigned long)child);
614 if (!child) postfork();
618 static void on_fd_read_except(int fd, oop_call_fd callback) {
619 loop->on_fd(loop, fd, OOP_READ, callback, 0);
620 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
622 static void cancel_fd_read_except(int fd) {
623 loop->cancel_fd(loop, fd, OOP_READ);
624 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
627 static void report_child_status(const char *what, int status) {
628 if (WIFEXITED(status)) {
629 int es= WEXITSTATUS(status);
631 warn("%s: child died with error exit status %d", what, es);
632 } else if (WIFSIGNALED(status)) {
633 int sig= WTERMSIG(status);
634 const char *sigstr= strsignal(sig);
635 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
637 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
639 warn("%s: child died due to unknown fatal signal %d%s",
640 what, sig, coredump);
642 warn("%s: child died with unknown wait status %d", what,status);
646 static int xwaitpid(pid_t *pid, const char *what) {
649 int r= kill(*pid, SIGKILL);
650 if (r) sysdie("cannot kill %s child", what);
652 pid_t got= waitpid(*pid, &status, 0);
653 if (got==-1) sysdie("cannot reap %s child", what);
654 if (got==0) die("cannot reap %s child", what);
661 static void xunlink(const char *path, const char *what) {
663 if (r) sysdie("can't unlink %s %s", path, what);
666 static time_t xtime(void) {
668 if (now==-1) sysdie("time(2) failed");
672 static void xgettimeofday(struct timeval *tv_r) {
673 int r= gettimeofday(tv_r,0);
674 if (r) sysdie("gettimeofday(2) failed");
677 static void xsetnonblock(int fd, int nonblocking) {
678 int errnoval= oop_fd_nonblock(fd, nonblocking);
679 if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
682 static void check_isreg(const struct stat *stab, const char *path,
684 if (!S_ISREG(stab->st_mode))
685 die("%s %s not a plain file (mode 0%lo)",
686 what, path, (unsigned long)stab->st_mode);
689 static void xfstat(int fd, struct stat *stab_r, const char *what) {
690 int r= fstat(fd, stab_r);
691 if (r) sysdie("could not fstat %s", what);
694 static void xfstat_isreg(int fd, struct stat *stab_r,
695 const char *path, const char *what) {
696 xfstat(fd, stab_r, what);
697 check_isreg(stab_r, path, what);
700 static void xlstat_isreg(const char *path, struct stat *stab,
701 int *enoent_r /* 0 means ENOENT is fatal */,
703 int r= lstat(path, stab);
705 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
706 sysdie("could not lstat %s %s", what, path);
708 if (enoent_r) *enoent_r= 0;
709 check_isreg(stab, path, what);
712 static int samefile(const struct stat *a, const struct stat *b) {
713 assert(S_ISREG(a->st_mode));
714 assert(S_ISREG(b->st_mode));
715 return (a->st_ino == b->st_ino &&
716 a->st_dev == b->st_dev);
719 static char *sanitise(const char *input) {
720 static char sanibuf[100]; /* returns pointer to this buffer! */
722 const char *p= input;
726 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
728 if (!c) { *q++= '\''; *q=0; break; }
729 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
730 sprintf(q,"\\x%02x",c);
736 static int isewouldblock(int errnoval) {
737 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
741 /*========== command and control connections ==========*/
743 static int control_master;
745 typedef struct ControlConn ControlConn;
747 void (*destroy)(ControlConn*);
753 struct sockaddr_un un;
758 static const oop_rd_style control_rd_style= {
759 OOP_RD_DELIM_STRIP, '\n',
761 OOP_RD_SHORTREC_FORBID
764 static void control_destroy(ControlConn *cc) {
768 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
769 if (ferror(cc->out) | fflush(cc->out)) {
770 info("CTRL%d write error %s", cc->fd, strerror(errno));
775 static void control_prompt(ControlConn *cc /* may destroy*/) {
776 fprintf(cc->out, "%s| ", sitename);
777 control_checkouterr(cc);
780 typedef struct ControlCommand ControlCommand;
781 struct ControlCommand {
783 void (*f)(ControlConn *cc, const ControlCommand *ccmd,
784 const char *arg, size_t argsz);
789 static const ControlCommand control_commands[];
792 static void ccmd_##wh(ControlConn *cc, const ControlCommand *c, \
793 const char *arg, size_t argsz)
796 fputs("commands:\n", cc->out);
797 const ControlCommand *ccmd;
798 for (ccmd=control_commands; ccmd->cmd; ccmd++)
799 fprintf(cc->out, " %s\n", ccmd->cmd);
802 CCMD(period) { period(); }
803 CCMD(setintarg) { *(int*)c->xdata= atoi(arg); }
804 CCMD(setint) { *(int*)c->xdata= c->xval; }
806 static const ControlCommand control_commands[]= {
808 { "p", ccmd_period },
809 { "pretend flush", ccmd_setintarg, &simulate_flush },
810 { "poke sm", ccmd_setint, &sm_period_counter, 1 },
811 { "poke conn", ccmd_setint, &until_connect, 0 },
812 { "poke blscan", ccmd_setint, &until_backlog_nextscan, 0 },
813 { "wedge blscan", ccmd_setint, &until_backlog_nextscan, -1 },
817 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
818 const char *errmsg, int errnoval,
819 const char *data, size_t recsz, void *cc_v) {
820 ControlConn *cc= cc_v;
823 info("CTRL%d closed", cc->fd);
828 if (recsz == 0) goto prompt;
830 const ControlCommand *ccmd;
831 for (ccmd=control_commands; ccmd->cmd; ccmd++) {
832 int l= strlen(ccmd->cmd);
833 if (recsz < l) continue;
834 if (recsz > l && data[l] != ' ') continue;
835 if (memcmp(data, ccmd->cmd, l)) continue;
837 int argl= (int)recsz - (l+1);
838 ccmd->f(cc, ccmd, argl>=0 ? data+l+1 : 0, argl);
842 fputs("unknown command; h for help\n", cc->out);
849 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
850 const char *errmsg, int errnoval,
851 const char *data, size_t recsz, void *cc_v) {
852 ControlConn *cc= cc_v;
854 info("CTRL%d read error %s", cc->fd, errmsg);
859 static int control_conn_startup(ControlConn *cc /* may destroy*/,
861 cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
862 if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
864 int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
867 if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
869 info("CTRL%d %s ready", cc->fd, how);
874 static void control_stdio_destroy(ControlConn *cc) {
876 oop_rd_cancel(cc->rd);
877 errno= oop_rd_delete_tidy(cc->rd);
878 if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
883 static void control_stdio(void) {
884 ControlConn *cc= xmalloc(sizeof(*cc));
885 memset(cc,0,sizeof(*cc));
886 cc->destroy= control_stdio_destroy;
890 int r= control_conn_startup(cc,"stdio");
891 if (r) cc->destroy(cc);
894 static void control_accepted_destroy(ControlConn *cc) {
896 oop_rd_cancel(cc->rd);
897 oop_rd_delete_kill(cc->rd);
899 if (cc->out) { fclose(cc->out); cc->fd=0; }
900 close_perhaps(&cc->fd);
904 static void *control_master_readable(oop_source *lp, int master,
905 oop_event ev, void *u) {
906 ControlConn *cc= xmalloc(sizeof(*cc));
907 memset(cc,0,sizeof(*cc));
908 cc->destroy= control_accepted_destroy;
910 cc->salen= sizeof(cc->sa);
911 cc->fd= accept(master, &cc->sa.sa, &cc->salen);
912 if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
914 cc->out= fdopen(cc->fd, "w");
915 if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
917 int r= control_conn_startup(cc, "accepted");
927 #define NOCONTROL(...) do{ \
928 syswarn("no control socket, because failed to " __VA_ARGS__); \
932 static void control_init(void) {
937 struct sockaddr_un un;
940 memset(&sa,0,sizeof(sa));
941 int maxlen= sizeof(sa.un.sun_path);
943 int reallen= readlink(path_control, sa.un.sun_path, maxlen);
946 NOCONTROL("readlink control socket symlink path %s", path_control);
948 if (reallen >= maxlen) {
949 debug("control socket symlink path too long (r=%d)",reallen);
950 xunlink(path_control, "old (overlong) control socket symlink");
956 int r= lstat(realsockdir,&stab);
958 if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
960 r= mkdir(realsockdir, 0700);
961 if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
964 uid_t self= geteuid();
965 if (!S_ISDIR(stab.st_mode) ||
966 stab.st_uid != self ||
967 stab.st_mode & 0077) {
968 warn("no control socket, because real socket directory"
969 " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
970 !!S_ISDIR(stab.st_mode),
971 (unsigned long)stab.st_uid, (unsigned long)self,
972 (unsigned long)stab.st_mode & 0777UL);
977 real= xasprintf("%s/s%lx.%lx", realsockdir,
978 (unsigned long)xtime(), (unsigned long)self_pid);
979 int reallen= strlen(real);
981 if (reallen >= maxlen) {
982 warn("no control socket, because tmpnam gave overly-long path"
986 r= symlink(real, path_control);
987 if (r) NOCONTROL("make control socket path %s a symlink to real"
988 " socket path %s", path_control, real);
989 memcpy(sa.un.sun_path, real, reallen);
992 int r= unlink(sa.un.sun_path);
993 if (r && errno!=ENOENT)
994 NOCONTROL("remove old real socket %s", sa.un.sun_path);
996 control_master= socket(PF_UNIX, SOCK_STREAM, 0);
997 if (control_master<0) NOCONTROL("create new control socket");
999 sa.un.sun_family= AF_UNIX;
1000 int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
1001 r= bind(control_master, &sa.sa, sl);
1002 if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
1004 r= listen(control_master, 5);
1005 if (r) NOCONTROL("listen");
1007 xsetnonblock(control_master, 1);
1009 loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
1010 info("control socket ok, real path %s", sa.un.sun_path);
1016 xclose_perhaps(&control_master, "control master",0);
1020 /*========== management of connections ==========*/
1022 static void conn_closefd(Conn *conn, const char *msgprefix) {
1023 int r= close_perhaps(&conn->fd);
1024 if (r) info("C%d %serror closing socket: %s",
1025 conn->fd, msgprefix, strerror(errno));
1028 static void conn_dispose(Conn *conn) {
1031 oop_rd_cancel(conn->rd);
1032 oop_rd_delete_kill(conn->rd);
1036 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1037 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
1039 conn_closefd(conn,"");
1041 until_connect= reconnect_delay_periods;
1044 static void *conn_exception(oop_source *lp, int fd,
1045 oop_event ev, void *conn_v) {
1048 assert(fd == conn->fd);
1049 assert(ev == OOP_EXCEPTION);
1050 int r= read(conn->fd, &ch, 1);
1051 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1052 else connfail(conn,"exceptional condition on socket (peer sent urgent"
1053 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1054 return OOP_CONTINUE;
1057 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1058 int requeue[art_MaxState];
1059 memset(requeue,0,sizeof(requeue));
1062 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1063 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1064 while ((art= LIST_REMHEAD(conn->sent))) {
1065 requeue[art->state]++;
1066 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1067 LIST_ADDTAIL(queue,art);
1072 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1075 char *m= xvasprintf(fmt,al);
1076 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1077 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1080 LIST_REMOVE(conns,conn);
1082 check_assign_articles();
1085 static void connfail(Conn *conn, const char *fmt, ...) {
1088 vconnfail(conn,fmt,al);
1092 static void check_idle_conns(void) {
1094 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
1095 conn->since_activity++;
1097 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
1098 if (conn->since_activity <= need_activity_periods) continue;
1100 /* We need to shut this down */
1102 connfail(conn,"timed out waiting for response to QUIT");
1103 else if (conn->sent.count)
1104 connfail(conn,"timed out waiting for responses");
1105 else if (conn->waiting.count || conn->priority.count)
1106 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1107 else if (conn->xmitu)
1108 connfail(conn,"peer has been sending responses"
1109 " before receiving our commands!");
1111 static const char quitcmd[]= "QUIT\r\n";
1112 int todo= sizeof(quitcmd)-1;
1113 const char *p= quitcmd;
1115 int r= write(conn->fd, p, todo);
1117 if (isewouldblock(errno))
1118 connfail(conn, "blocked writing QUIT to idle connection");
1120 connfail(conn, "failed to write QUIT to idle connection: %s",
1128 conn->since_activity= 0;
1129 debug("C%d is idle, quitting", conn->fd);
1138 /*---------- making new connections ----------*/
1140 static pid_t connecting_child;
1141 static int connecting_fdpass_sock;
1143 static void connect_attempt_discard(void) {
1144 if (connecting_child) {
1145 int status= xwaitpid(&connecting_child, "connect");
1146 if (!(WIFEXITED(status) ||
1147 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1148 report_child_status("connect", status);
1150 if (connecting_fdpass_sock) {
1151 cancel_fd_read_except(connecting_fdpass_sock);
1152 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1156 #define PREP_DECL_MSG_CMSG(msg) \
1158 struct iovec msgiov; \
1159 msgiov.iov_base= &msgbyte; \
1160 msgiov.iov_len= 1; \
1161 struct msghdr msg; \
1162 memset(&msg,0,sizeof(msg)); \
1163 char msg##cbuf[CMSG_SPACE(sizeof(int))]; \
1164 msg.msg_iov= &msgiov; \
1165 msg.msg_iovlen= 1; \
1166 msg.msg_control= msg##cbuf; \
1167 msg.msg_controllen= sizeof(msg##cbuf);
1169 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1172 assert(fd == connecting_fdpass_sock);
1174 PREP_DECL_MSG_CMSG(msg);
1176 ssize_t rs= recvmsg(fd, &msg, 0);
1178 if (isewouldblock(errno)) return OOP_CONTINUE;
1179 syswarn("failed to read socket from connecting child");
1183 conn= xmalloc(sizeof(*conn));
1184 memset(conn,0,sizeof(*conn));
1185 LIST_INIT(conn->waiting);
1186 LIST_INIT(conn->priority);
1187 LIST_INIT(conn->sent);
1189 struct cmsghdr *h= 0;
1190 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1192 int status= xwaitpid(&connecting_child, "connect child (broken)");
1194 if (WIFEXITED(status)) {
1195 if (WEXITSTATUS(status) != 0 &&
1196 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1197 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1198 /* child already reported the problem */;
1200 if (e == OOP_EXCEPTION)
1201 warn("connect: connection child exited code %d but"
1202 " unexpected exception on fdpass socket",
1203 WEXITSTATUS(status));
1205 warn("connect: connection child exited code %d but"
1207 WEXITSTATUS(status), (int)rs);
1209 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1210 warn("connect: connection attempt timed out");
1212 report_child_status("connect", status);
1217 #define CHK(field, val) \
1218 if (h->cmsg_##field != val) { \
1219 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1220 h->cmsg_##field, val); \
1223 CHK(level, SOL_SOCKET);
1224 CHK(type, SCM_RIGHTS);
1225 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1228 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1230 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1233 pid_t got= waitpid(connecting_child, &status, 0);
1234 if (got==-1) sysdie("connect: real wait for child");
1235 assert(got == connecting_child);
1236 connecting_child= 0;
1238 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1239 int es= WEXITSTATUS(status);
1241 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1242 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1244 fatal("connect: child gave unexpected exit status %d", es);
1248 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1250 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1251 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1252 if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1253 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1255 &peer_rd_err, conn);
1256 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1258 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1259 LIST_ADDHEAD(conns, conn);
1261 connect_attempt_discard();
1262 check_assign_articles();
1263 return OOP_CONTINUE;
1267 connect_attempt_discard();
1268 return OOP_CONTINUE;
1271 static int allow_connect_start(void) {
1272 return conns.count < max_connections
1273 && !connecting_child
1277 static void connect_start(void) {
1278 assert(!connecting_child);
1279 assert(!connecting_fdpass_sock);
1281 info("starting connection attempt");
1284 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1285 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1287 connecting_child= xfork("connection");
1289 if (!connecting_child) {
1290 FILE *cn_from, *cn_to;
1291 char buf[NNTP_STRLEN+100];
1292 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1294 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1296 alarm(connection_setup_timeout);
1297 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1301 unsigned char c= buf[l-1];
1302 if (!isspace(c)) break;
1303 if (c=='\n' || c=='\r') stripped=1;
1307 sysfatal("connect: connection attempt failed");
1310 fatal("connect: %s: %s", stripped ? "rejected" : "failed",
1314 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1315 sysfatal("connect: authentication failed");
1317 if (fputs("MODE STREAM\r\n", cn_to)==EOF ||
1319 sysfatal("connect: could not send MODE STREAM");
1320 buf[sizeof(buf)-1]= 0;
1321 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1322 if (ferror(cn_from))
1323 sysfatal("connect: could not read response to MODE STREAM");
1325 fatal("connect: connection close in response to MODE STREAM");
1330 fatal("connect: response to MODE STREAM is too long: %.100s...",
1332 l--; if (l>0 && buf[l-1]=='\r') l--;
1335 int rcode= strtoul(buf,&ep,10);
1337 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
1341 exitstatus= CONNCHILD_ESTATUS_STREAM;
1347 warn("connect: unexpected response to MODE STREAM: %.50s",
1353 int fd= fileno(cn_from);
1355 PREP_DECL_MSG_CMSG(msg);
1356 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1357 cmsg->cmsg_level= SOL_SOCKET;
1358 cmsg->cmsg_type= SCM_RIGHTS;
1359 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1360 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1362 msg.msg_controllen= cmsg->cmsg_len;
1363 r= sendmsg(socks[1], &msg, 0);
1364 if (r<0) sysdie("sendmsg failed for new connection");
1365 if (r!=1) die("sendmsg for new connection gave wrong result %d",r);
1370 xclose(socks[1], "connecting fdpass child's socket",0);
1371 connecting_fdpass_sock= socks[0];
1372 xsetnonblock(connecting_fdpass_sock, 1);
1373 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1376 /*---------- assigning articles to conns, and transmitting ----------*/
1378 static void check_assign_articles(void) {
1384 int spare=0, inqueue=0;
1386 /* Find a connection to offer this article. We prefer a busy
1387 * connection to an idle one, provided it's not full. We take the
1388 * first (oldest) and since that's stable, it will mean we fill up
1389 * connections in order. That way if we have too many
1390 * connections, the spare ones will go away eventually.
1392 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1393 if (walk->quitting) continue;
1394 inqueue= walk->sent.count + walk->priority.count
1395 + walk->waiting.count;
1396 spare= walk->max_queue - inqueue;
1397 assert(inqueue <= max_queue_per_conn);
1399 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1400 else if (spare>0) /*working*/ { use= walk; break; }
1403 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1405 Article *art= LIST_REMHEAD(queue);
1407 LIST_ADDTAIL(use->waiting, art);
1410 conn_maybe_write(use);
1411 } else if (allow_connect_start()) {
1412 until_connect= reconnect_delay_periods;
1421 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1422 conn_maybe_write(u);
1423 return OOP_CONTINUE;
1426 static void conn_maybe_write(Conn *conn) {
1428 conn_make_some_xmits(conn);
1430 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1434 void *rp= conn_write_some_xmits(conn);
1435 if (rp==OOP_CONTINUE) {
1436 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1438 } else if (rp==OOP_HALT) {
1441 /* transmitted everything */
1448 /*========== article transmission ==========*/
1450 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1451 XmitKind kind) { /* caller must then fill in details */
1452 struct iovec *v= &conn->xmit[conn->xmitu];
1453 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1454 v->iov_base= (char*)data;
1460 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1461 xmit_core(conn,data,len, xk_Const);
1463 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1465 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1466 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1470 static void xmit_free(XmitDetails *d) {
1472 case xk_Malloc: free(d->info.malloc_tofree); break;
1473 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1474 case xk_Const: break;
1479 static void *conn_write_some_xmits(Conn *conn) {
1481 * 0: nothing more to write, no need to call us again
1482 * OOP_CONTINUE: more to write but fd not writeable
1483 * OOP_HALT: disaster, have destroyed conn
1486 int count= conn->xmitu;
1487 if (!count) return 0;
1489 if (count > IOV_MAX) count= IOV_MAX;
1490 ssize_t rs= writev(conn->fd, conn->xmit, count);
1492 if (isewouldblock(errno)) return OOP_CONTINUE;
1493 connfail(conn, "write failed: %s", strerror(errno));
1499 for (done=0; rs && done<conn->xmitu; done++) {
1500 struct iovec *vp= &conn->xmit[done];
1501 XmitDetails *dp= &conn->xmitd[done];
1502 if (rs > vp->iov_len) {
1506 vp->iov_base= (char*)vp->iov_base + rs;
1510 int newu= conn->xmitu - done;
1511 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1512 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1517 static void conn_make_some_xmits(Conn *conn) {
1519 if (conn->xmitu+5 > CONNIOVS)
1522 Article *art= LIST_REMHEAD(conn->priority);
1523 if (!art) art= LIST_REMHEAD(conn->waiting);
1526 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1527 /* actually send it */
1529 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1532 art->state == art_Unchecked ? art_Unsolicited :
1533 art->state == art_Wanted ? art_Wanted :
1536 if (!artdata) art->missing= 1;
1537 art->ipf->counts[art->state][ artdata ? RC_sent : RC_missing ]++;
1541 XMIT_LITERAL("TAKETHIS ");
1542 xmit_noalloc(conn, art->messageid, art->midlen);
1543 XMIT_LITERAL("\r\n");
1544 xmit_artbody(conn, artdata);
1546 article_done(conn, art, -1);
1550 /* we got 235 from IHAVE */
1552 xmit_artbody(conn, artdata);
1554 XMIT_LITERAL(".\r\n");
1558 LIST_ADDTAIL(conn->sent, art);
1564 XMIT_LITERAL("CHECK ");
1566 XMIT_LITERAL("IHAVE ");
1567 xmit_noalloc(conn, art->messageid, art->midlen);
1568 XMIT_LITERAL("\r\n");
1570 assert(art->state == art_Unchecked);
1571 art->ipf->counts[art->state][RC_sent]++;
1572 LIST_ADDTAIL(conn->sent, art);
1578 /*========== handling responses from peer ==========*/
1580 static const oop_rd_style peer_rd_style= {
1581 OOP_RD_DELIM_STRIP, '\n',
1583 OOP_RD_SHORTREC_FORBID
1586 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1587 const char *errmsg, int errnoval,
1588 const char *data, size_t recsz, void *conn_v) {
1590 connfail(conn, "error receiving from peer: %s", errmsg);
1591 return OOP_CONTINUE;
1594 static Article *article_reply_check(Conn *conn, const char *response,
1595 int code_indicates_streaming,
1597 /* 1:yes, -1:no, 0:dontcare */,
1598 const char *sanitised_response) {
1599 Article *art= LIST_HEAD(conn->sent);
1603 "peer gave unexpected response when no commands outstanding: %s",
1604 sanitised_response);
1608 if (code_indicates_streaming) {
1609 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1610 if (!conn->stream) {
1611 connfail(conn, "peer gave streaming response code "
1612 " to IHAVE or subsequent body: %s", sanitised_response);
1615 const char *got_mid= response+4;
1616 int got_midlen= strcspn(got_mid, " \n\r");
1617 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1618 connfail(conn, "peer gave streaming response with syntactically invalid"
1619 " messageid: %s", sanitised_response);
1622 if (got_midlen != art->midlen ||
1623 memcmp(got_mid, art->messageid, got_midlen)) {
1624 connfail(conn, "peer gave streaming response code to wrong article -"
1625 " probable synchronisation problem; we offered: %s;"
1627 art->messageid, sanitised_response);
1632 connfail(conn, "peer gave non-streaming response code to"
1633 " CHECK/TAKETHIS: %s", sanitised_response);
1638 if (must_have_sent>0 && art->state < art_Wanted) {
1639 connfail(conn, "peer says article accepted but"
1640 " we had not sent the body: %s", sanitised_response);
1643 if (must_have_sent<0 && art->state >= art_Wanted) {
1644 connfail(conn, "peer says please sent the article but we just did: %s",
1645 sanitised_response);
1649 Article *art_again= LIST_REMHEAD(conn->sent);
1650 assert(art_again == art);
1654 static void update_nocheck(int accepted) {
1655 accept_proportion *= nocheck_decay;
1656 accept_proportion += accepted * (1.0 - nocheck_decay);
1657 int new_nocheck= accept_proportion >= nocheck_thresh;
1658 if (new_nocheck && !nocheck_reported) {
1659 notice("entering nocheck mode for the first time");
1660 nocheck_reported= 1;
1661 } else if (new_nocheck != nocheck) {
1662 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1664 nocheck= new_nocheck;
1667 static void article_done(Conn *conn, Article *art, int whichcount) {
1668 if (!art->missing) art->ipf->counts[art->state][whichcount]++;
1670 if (whichcount == RC_accepted) update_nocheck(1);
1671 else if (whichcount == RC_unwanted) update_nocheck(0);
1673 InputFile *ipf= art->ipf;
1675 while (art->blanklen) {
1676 static const char spaces[]=
1681 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1682 int r= pwrite(ipf->fd, spaces, w, art->offset);
1684 if (errno==EINTR) continue;
1685 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1686 art->messageid, art->blanklen,
1687 (unsigned long)art->offset, ipf->path);
1689 assert(r>=0 && r<=w);
1695 assert(ipf->inprogress >= 0);
1698 if (!ipf->inprogress && ipf != main_input_file)
1699 queue_check_input_done();
1702 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1703 const char *errmsg, int errnoval,
1704 const char *data, size_t recsz, void *conn_v) {
1707 if (ev == OOP_RD_EOF) {
1708 connfail(conn, "unexpected EOF from peer");
1709 return OOP_CONTINUE;
1711 assert(ev == OOP_RD_OK);
1713 char *sani= sanitise(data);
1716 unsigned long code= strtoul(data, &ep, 10);
1717 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1718 connfail(conn, "badly formatted response from peer: %s", sani);
1719 return OOP_CONTINUE;
1722 if (conn->quitting) {
1723 if (code!=205 && code!=503) {
1724 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1726 notice("C%d idle connection closed", conn->fd);
1727 assert(!conn->waiting.count);
1728 assert(!conn->priority.count);
1729 assert(!conn->sent.count);
1730 assert(!conn->xmitu);
1731 LIST_REMOVE(conns,conn);
1734 return OOP_CONTINUE;
1737 conn->since_activity= 0;
1740 #define GET_ARTICLE(musthavesent) \
1741 art= article_reply_check(conn, data, code_streaming, musthavesent, sani); \
1742 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1744 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1745 code_streaming= (streaming); \
1746 GET_ARTICLE(musthavesent); \
1747 article_done(conn, art, RC_##how); break;
1749 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1751 int code_streaming= 0;
1755 case 400: PEERBADMSG("peer stopped accepting articles");
1756 case 503: PEERBADMSG("peer timed us out");
1757 default: PEERBADMSG("peer sent unexpected message");
1759 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1760 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1762 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1763 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1765 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1766 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1768 case 238: /* CHECK says send it */
1770 case 335: /* IHAVE says send it */
1772 assert(art->state == art_Unchecked);
1773 art->ipf->counts[art->state][RC_accepted]++;
1774 art->state= art_Wanted;
1775 LIST_ADDTAIL(conn->priority, art);
1778 case 431: /* CHECK or TAKETHIS says try later */
1780 case 436: /* IHAVE says try later */
1783 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1785 sysfatal("write to defer file %s",path_defer);
1786 article_done(conn, art, RC_deferred);
1791 conn_maybe_write(conn);
1792 check_assign_articles();
1793 return OOP_CONTINUE;
1797 /*========== monitoring of input files ==========*/
1799 static void feedfile_eof(InputFile *ipf) {
1800 assert(ipf != main_input_file); /* promised by tailing_try_read */
1801 inputfile_reading_stop(ipf);
1803 if (ipf == flushing_input_file) {
1804 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1805 if (main_input_file) inputfile_reading_start(main_input_file);
1806 statemc_check_flushing_done();
1807 } else if (ipf == backlog_input_file) {
1808 statemc_check_backlog_done();
1810 abort(); /* supposed to wait rather than get EOF on main input file */
1814 static InputFile *open_input_file(const char *path) {
1815 int fd= open(path, O_RDWR);
1817 if (errno==ENOENT) return 0;
1818 sysfatal("unable to open input file %s", path);
1822 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1823 memset(ipf,0,sizeof(*ipf));
1826 strcpy(ipf->path, path);
1831 static void close_input_file(InputFile *ipf) { /* does not free */
1832 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1833 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1834 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1835 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1836 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1840 /*---------- dealing with articles read in the input file ----------*/
1842 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1843 const char *data, const char *how) {
1844 warn("corrupted file: %s, offset %lu: %s: in %s",
1845 ipf->path, (unsigned long)offset, how, sanitise(data));
1846 ipf->readcount_err++;
1847 if (ipf->readcount_err > max_bad_data_initial +
1848 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1849 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1850 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1851 return OOP_CONTINUE;
1854 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1855 oop_rd_event ev, const char *errmsg,
1856 int errnoval, const char *data, size_t recsz,
1858 InputFile *ipf= ipf_v;
1859 assert(ev == OOP_RD_SYSTEM);
1861 sysdie("error reading input file: %s, offset %lu",
1862 ipf->path, (unsigned long)ipf->offset);
1865 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1866 oop_rd_event ev, const char *errmsg,
1867 int errnoval, const char *data, size_t recsz,
1869 InputFile *ipf= ipf_v;
1871 char tokentextbuf[sizeof(TOKEN)*2+3];
1873 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1875 off_t old_offset= ipf->offset;
1876 ipf->offset += recsz + 1;
1878 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1880 if (ev==OOP_RD_PARTREC)
1881 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1882 /* but process it anyway */
1884 if (ipf->skippinglong) {
1885 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1886 return OOP_CONTINUE;
1888 if (ev==OOP_RD_LONG) {
1889 ipf->skippinglong= 1;
1890 X_BAD_DATA("overly long line");
1893 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1894 if (!recsz) X_BAD_DATA("empty line");
1897 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1898 ipf->readcount_blank++;
1899 return OOP_CONTINUE;
1902 char *space= strchr(data,' ');
1903 int tokenlen= space-data;
1904 int midlen= (int)recsz-tokenlen-1;
1905 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1906 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1908 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1909 memcpy(tokentextbuf, data, tokenlen);
1910 tokentextbuf[tokenlen]= 0;
1911 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1913 ipf->readcount_ok++;
1915 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1916 art->state= art_Unchecked;
1917 art->midlen= midlen;
1918 art->ipf= ipf; ipf->inprogress++;
1919 art->token= TextToToken(tokentextbuf);
1920 art->offset= ipf->offset;
1921 art->blanklen= recsz;
1922 strcpy(art->messageid, space+1);
1923 LIST_ADDTAIL(queue, art);
1925 if (sms==sm_NORMAL && ipf==main_input_file &&
1926 ipf->offset >= target_max_feedfile_size)
1927 statemc_start_flush("feed file size");
1929 check_assign_articles();
1930 return OOP_CONTINUE;
1933 /*========== tailing input file ==========*/
1935 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1937 InputFile *ipf= user;
1938 return ipf->readable_callback(loop, &ipf->readable,
1939 ipf->readable_callback_user);
1942 static void tailing_on_cancel(struct oop_readable *rable) {
1943 InputFile *ipf= (void*)rable;
1945 if (ipf->filemon) filemon_stop(ipf);
1946 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1947 ipf->readable_callback= 0;
1950 static void tailing_queue_readable(InputFile *ipf) {
1951 /* lifetime of ipf here is OK because destruction will cause
1952 * on_cancel which will cancel this callback */
1953 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1956 static int tailing_on_readable(struct oop_readable *rable,
1957 oop_readable_call *cb, void *user) {
1958 InputFile *ipf= (void*)rable;
1960 tailing_on_cancel(rable);
1961 ipf->readable_callback= cb;
1962 ipf->readable_callback_user= user;
1965 tailing_queue_readable(ipf);
1969 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1971 InputFile *ipf= (void*)rable;
1973 ssize_t r= read(ipf->fd, buffer, length);
1975 if (errno==EINTR) continue;
1979 if (ipf==main_input_file) {
1982 } else if (ipf==flushing_input_file) {
1984 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1985 } else if (ipf==backlog_input_file) {
1991 tailing_queue_readable(ipf);
1996 /*---------- filemon implemented with inotify ----------*/
1998 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1999 #define HAVE_FILEMON
2001 #include <linux/inotify.h>
2003 static int filemon_inotify_fd;
2004 static int filemon_inotify_wdmax;
2005 static InputFile **filemon_inotify_wd2ipf;
2007 struct Filemon_Perfile {
2011 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
2012 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
2013 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
2015 if (wd >= filemon_inotify_wdmax) {
2017 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
2018 sizeof(*filemon_inotify_wd2ipf) * newmax);
2019 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
2020 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
2021 filemon_inotify_wdmax= newmax;
2024 assert(!filemon_inotify_wd2ipf[wd]);
2025 filemon_inotify_wd2ipf[wd]= ipf;
2027 debug("filemon inotify startfile %p wd=%d wdmax=%d",
2028 ipf, wd, filemon_inotify_wdmax);
2033 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
2035 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
2036 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
2037 if (r) sysdie("inotify_rm_watch");
2038 filemon_inotify_wd2ipf[wd]= 0;
2041 static void *filemon_inotify_readable(oop_source *lp, int fd,
2042 oop_event e, void *u) {
2043 struct inotify_event iev;
2045 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
2047 if (isewouldblock(errno)) break;
2048 sysdie("read from inotify master");
2049 } else if (r==sizeof(iev)) {
2050 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
2052 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
2054 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
2055 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
2056 filemon_callback(ipf);
2058 return OOP_CONTINUE;
2061 static int filemon_method_init(void) {
2062 filemon_inotify_fd= inotify_init();
2063 if (filemon_inotify_fd<0) {
2064 syswarn("could not initialise inotify: inotify_init failed");
2068 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
2070 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2074 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2076 /*---------- filemon dummy implementation ----------*/
2078 #if !defined(HAVE_FILEMON)
2080 struct Filemon_Perfile { int dummy; };
2082 static int filemon_method_init(void) { return 0; }
2083 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2084 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2086 #endif /* !HAVE_FILEMON */
2088 /*---------- filemon generic interface ----------*/
2090 static void filemon_start(InputFile *ipf) {
2091 assert(!ipf->filemon);
2093 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
2094 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
2095 filemon_method_startfile(ipf, ipf->filemon);
2098 static void filemon_stop(InputFile *ipf) {
2099 if (!ipf->filemon) return;
2100 filemon_method_stopfile(ipf, ipf->filemon);
2105 static void filemon_callback(InputFile *ipf) {
2106 if (ipf && ipf->readable_callback) /* so filepoll() can be naive */
2107 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2110 /*---------- interface to start and stop an input file ----------*/
2112 static const oop_rd_style feedfile_rdstyle= {
2113 OOP_RD_DELIM_STRIP, '\n',
2115 OOP_RD_SHORTREC_LONG,
2118 static void inputfile_reading_start(InputFile *ipf) {
2120 ipf->readable.on_readable= tailing_on_readable;
2121 ipf->readable.on_cancel= tailing_on_cancel;
2122 ipf->readable.try_read= tailing_try_read;
2123 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2124 ipf->readable.delete_kill= 0;
2126 ipf->readable_callback= 0;
2127 ipf->readable_callback_user= 0;
2129 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2132 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2133 feedfile_got_article,ipf, feedfile_read_err, ipf);
2134 if (r) sysdie("unable start reading feedfile %s",ipf->path);
2137 static void inputfile_reading_stop(InputFile *ipf) {
2139 oop_rd_cancel(ipf->rd);
2140 oop_rd_delete(ipf->rd);
2142 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2146 /*========== interaction with innd - state machine ==========*/
2148 /* See official state diagram at top of file. We implement
2159 |`---------------------------------------------------.
2161 |`---------------- - - - |
2162 D ENOENT | D EXISTS see OVERALL STATES diagram |
2163 | for full startup logic |
2166 | ============ try to |
2172 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
2173 ^ | hardlink F to D |
2176 | | our handle onto F is now onto D |
2179 | |<-------------------<---------------------<---------+
2181 | | spawn inndcomm flush |
2183 | ================== |
2184 | FLUSHING[-ABSENT] |
2186 | main D tail/none |
2187 | ================== |
2189 | | INNDCOMM FLUSH FAILS ^
2190 | |`----------------------->----------. |
2192 | | NO SUCH SITE V |
2193 ^ |`--------------->----. ==================== |
2194 | | \ FLUSHFAILED[-ABSENT] |
2196 | | FLUSH OK \ main D tail/none |
2197 | | open F \ ==================== |
2199 | | \ | TIME TO RETRY |
2200 | |`------->----. ,---<---'\ `----------------'
2201 | | D NONE | | D NONE `----.
2203 | ============= V V ============
2204 | SEPARATED-1 | | DROPPING-1
2205 | flsh->rd!=0 | | flsh->rd!=0
2206 | [Separated] | | [Dropping]
2207 | main F idle | | main none
2208 | old D tail | | old D tail
2209 | ============= | | ============
2211 ^ | EOF ON D | | defer | EOF ON D
2213 | =============== | | ===============
2214 | SEPARATED-2 | | DROPPING-2
2215 | flsh->rd==0 | V flsh->rd==0
2216 | [Finishing] | | [Dropping]
2217 | main F tail | `. main none
2218 | old D closed | `. old D closed
2219 | =============== V `. ===============
2221 | | ALL D PROCESSED `. | ALL D PROCESSED
2222 | V install defer as backlog `. | install defer
2223 ^ | close D `. | close D
2224 | | unlink D `. | unlink D
2227 `----------' ==============
2247 static void startup_set_input_file(InputFile *f) {
2248 assert(!main_input_file);
2250 inputfile_reading_start(f);
2253 static void statemc_lock(void) {
2255 struct stat stab, stabf;
2258 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2259 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2262 memset(&fl,0,sizeof(fl));
2264 fl.l_whence= SEEK_SET;
2265 int r= fcntl(lockfd, F_SETLK, &fl);
2267 if (errno==EACCES || isewouldblock(errno)) {
2268 if (quiet_multiple) exit(0);
2269 fatal("another duct holds the lockfile");
2271 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2274 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2276 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2278 if (!lock_noent && samefile(&stab, &stabf))
2281 xclose(lockfd, "stale lockfile ", path_lock);
2284 FILE *lockfile= fdopen(lockfd, "w");
2285 if (!lockfile) sysdie("fdopen lockfile");
2287 int r= ftruncate(lockfd, 0);
2288 if (r) sysdie("truncate lockfile to write new info");
2290 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2291 (unsigned long)self_pid,
2292 sitename, feedfile, remote_host) == EOF ||
2294 sysfatal("write info to lockfile %s", path_lock);
2296 debug("startup: locked");
2299 static void statemc_init(void) {
2300 struct stat stabdefer;
2302 search_backlog_file();
2305 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2307 debug("startup: ductdefer ENOENT");
2309 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2310 switch (stabdefer.st_nlink==1) {
2312 open_defer(); /* so that we will later close it and rename it */
2315 xunlink(path_defer, "stale defer file link"
2316 " (presumably hardlink to backlog file)");
2319 die("defer file %s has unexpected link count %d",
2320 path_defer, stabdefer.st_nlink);
2324 struct stat stab_f, stab_d;
2327 InputFile *file_d= open_input_file(path_flushing);
2328 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2330 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2332 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2333 debug("startup: F==D => Hardlinked");
2334 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2339 debug("startup: F ENOENT => Moved");
2340 if (file_d) startup_set_input_file(file_d);
2341 spawn_inndcomm_flush("feedfile missing at startup");
2342 /* => Flushing, sms:=FLUSHING */
2345 debug("startup: F!=D => Separated");
2346 startup_set_input_file(file_d);
2347 SMS(SEPARATED, 0, "found both old and current feed files");
2349 debug("startup: F exists, D ENOENT => Normal");
2350 InputFile *file_f= open_input_file(feedfile);
2351 if (!file_f) die("feed file vanished during startup");
2352 startup_set_input_file(file_f);
2353 SMS(NORMAL, spontaneous_flush_periods, "normal startup");
2358 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2359 assert(sms == sm_NORMAL);
2361 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2363 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2364 (unsigned long)target_max_feedfile_size,
2367 int r= link(feedfile, path_flushing);
2368 if (r) sysfatal("link feedfile %s to flushing file %s",
2369 feedfile, path_flushing);
2372 xunlink(feedfile, "old feedfile link");
2375 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2378 static void statemc_period_poll(void) {
2379 if (!sm_period_counter) return;
2380 sm_period_counter--;
2381 assert(sm_period_counter>=0);
2383 if (sm_period_counter) return;
2386 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2388 case sm_FLUSHFAILED:
2389 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2396 static int inputfile_is_done(InputFile *ipf) {
2398 if (ipf->inprogress) return 0; /* new article in the meantime */
2399 if (ipf->rd) return 0; /* not had EOF */
2403 static void notice_processed(InputFile *ipf, const char *what,
2405 #define RCI_NOTHING(x) /* nothing */
2406 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2407 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2409 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2411 info("processed %s%s read=%d(+%dbl,+%derr)"
2412 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2413 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2416 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2417 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2418 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2419 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2420 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2421 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2427 static void statemc_check_backlog_done(void) {
2428 InputFile *ipf= backlog_input_file;
2429 if (!inputfile_is_done(ipf)) return;
2431 const char *slash= strrchr(ipf->path, '/');
2432 const char *leaf= slash ? slash+1 : ipf->path;
2433 const char *under= strchr(slash, '_');
2434 const char *rest= under ? under+1 : leaf;
2435 if (!strncmp(rest,"backlog",7)) rest += 7;
2436 notice_processed(ipf,"backlog:",rest);
2438 close_input_file(ipf);
2439 if (unlink(ipf->path)) {
2440 if (errno != ENOENT)
2441 sysdie("could not unlink processed backlog file %s", ipf->path);
2442 warn("backlog file %s vanished while we were reading it"
2443 " so we couldn't remove it (but it's done now, anyway)",
2447 backlog_input_file= 0;
2448 search_backlog_file();
2452 static void statemc_check_flushing_done(void) {
2453 InputFile *ipf= flushing_input_file;
2454 if (!inputfile_is_done(ipf)) return;
2456 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2458 notice_processed(ipf,"feedfile",0);
2462 xunlink(path_flushing, "old flushing file");
2464 close_input_file(flushing_input_file);
2465 free(flushing_input_file);
2466 flushing_input_file= 0;
2468 if (sms==sm_SEPARATED) {
2469 notice("flush complete");
2470 SMS(NORMAL, 0, "flush complete");
2471 } else if (sms==sm_DROPPING) {
2472 SMS(DROPPED, 0, "old flush complete");
2473 search_backlog_file();
2474 notice("feed dropped, but will continue until backlog is finished");
2478 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2480 assert(!inputfile_is_done(main_input_file));
2481 statemc_check_flushing_done();
2482 statemc_check_backlog_done();
2483 return OOP_CONTINUE;
2486 static void queue_check_input_done(void) {
2487 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2490 static void statemc_setstate(StateMachineState newsms, int periods,
2491 const char *forlog, const char *why) {
2493 sm_period_counter= periods;
2495 const char *xtra= "";
2498 case sm_FLUSHFAILED:
2499 if (!main_input_file) xtra= "-ABSENT";
2503 xtra= flushing_input_file->rd ? "-1" : "-2";
2509 info("state %s%s[%d] %s",forlog,xtra,periods,why);
2511 info("state %s%s %s",forlog,xtra,why);
2515 /*---------- defer and backlog files ----------*/
2517 static void open_defer(void) {
2522 defer= fopen(path_defer, "a+");
2523 if (!defer) sysfatal("could not open defer file %s", path_defer);
2525 /* truncate away any half-written records */
2527 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2529 if (stab.st_size > LONG_MAX)
2530 die("defer file %s size is far too large", path_defer);
2535 long orgsize= stab.st_size;
2536 long truncto= stab.st_size;
2538 if (!truncto) break; /* was only (if anything) one half-truncated record */
2539 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2540 sysdie("seek in defer file %s while truncating partial", path_defer);
2545 sysdie("failed read from defer file %s", path_defer);
2547 die("defer file %s shrank while we were checking it!", path_defer);
2553 if (stab.st_size != truncto) {
2554 warn("truncating half-record at end of defer file %s -"
2555 " shrinking by %ld bytes from %ld to %ld",
2556 path_defer, orgsize - truncto, orgsize, truncto);
2559 sysfatal("could not flush defer file %s", path_defer);
2560 if (ftruncate(fileno(defer), truncto))
2561 sysdie("could not truncate defer file %s", path_defer);
2564 info("continuing existing defer file %s (%ld bytes)",
2565 path_defer, orgsize);
2567 if (fseek(defer, truncto, SEEK_SET))
2568 sysdie("could not seek to new end of defer file %s", path_defer);
2571 static void close_defer(void) {
2576 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2578 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2581 time_t now= xtime();
2583 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2585 (unsigned long)stab.st_ino);
2586 if (link(path_defer, backlog))
2587 sysfatal("could not install defer file %s as backlog file %s",
2588 path_defer, backlog);
2589 if (unlink(path_defer))
2590 sysdie("could not unlink old defer link %s to backlog file %s",
2591 path_defer, backlog);
2595 if (until_backlog_nextscan < 0 ||
2596 until_backlog_nextscan > backlog_retry_minperiods + 1)
2597 until_backlog_nextscan= backlog_retry_minperiods + 1;
2600 static void poll_backlog_file(void) {
2601 if (until_backlog_nextscan < 0) return;
2602 if (until_backlog_nextscan-- > 0) return;
2603 search_backlog_file();
2606 static void search_backlog_file(void) {
2607 /* returns non-0 iff there are any backlog files */
2612 const char *oldest_path=0;
2613 time_t oldest_mtime=0, now;
2615 if (backlog_input_file) return;
2619 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2623 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2625 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2627 for (i=0; i<gl.gl_pathc; i++) {
2628 const char *path= gl.gl_pathv[i];
2630 if (strchr(path,'#') || strchr(path,'~')) {
2631 debug("backlog file search skipping %s", path);
2634 r= stat(path, &stab);
2636 syswarn("failed to stat backlog file %s", path);
2639 if (!S_ISREG(stab.st_mode)) {
2640 warn("backlog file %s is not a plain file (or link to one)", path);
2643 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2645 oldest_mtime= stab.st_mtime;
2648 case GLOB_NOMATCH: /* fall through */
2651 sysdie("glob expansion of backlog pattern %s gave unexpected"
2652 " nonzero (error?) return value %d", globpat_backlog, r);
2656 debug("backlog scan: none");
2658 if (sms==sm_DROPPED) {
2659 notice("feed dropped and our work is complete");
2661 int r= unlink(path_control);
2662 if (r && errno!=ENOENT)
2663 syswarn("failed to remove control symlink for old feed");
2665 xunlink(path_lock, "lockfile for old feed");
2668 until_backlog_nextscan= backlog_spontrescan_periods;
2673 double age= difftime(now, oldest_mtime);
2674 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2676 if (age_deficiency <= 0) {
2677 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2678 age, age_deficiency, oldest_path);
2680 backlog_input_file= open_input_file(oldest_path);
2681 if (!backlog_input_file) {
2682 warn("backlog file %s vanished as we opened it", oldest_path);
2686 inputfile_reading_start(backlog_input_file);
2687 until_backlog_nextscan= -1;
2691 until_backlog_nextscan= age_deficiency / period_seconds;
2693 if (backlog_spontrescan_periods >= 0 &&
2694 until_backlog_nextscan > backlog_spontrescan_periods)
2695 until_backlog_nextscan= backlog_spontrescan_periods;
2697 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2698 age, age_deficiency, until_backlog_nextscan, oldest_path);
2705 /*========== flushing the feed ==========*/
2707 static pid_t inndcomm_child;
2708 static int inndcomm_sentinel_fd;
2710 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2711 assert(inndcomm_child);
2712 assert(fd == inndcomm_sentinel_fd);
2713 int status= xwaitpid(&inndcomm_child, "inndcomm");
2716 cancel_fd_read_except(fd);
2717 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2718 inndcomm_sentinel_fd= 0;
2720 assert(!flushing_input_file);
2722 if (WIFEXITED(status)) {
2723 switch (WEXITSTATUS(status)) {
2725 case INNDCOMMCHILD_ESTATUS_FAIL:
2728 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2729 notice("feed has been dropped by innd, finishing up");
2730 flushing_input_file= main_input_file;
2731 tailing_queue_readable(flushing_input_file);
2732 /* we probably previously returned EAGAIN from our fake read method
2733 * when in fact we were at EOF, so signal another readable event
2734 * so we actually see the EOF */
2738 if (flushing_input_file) {
2739 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2742 SMS(DROPPED, 0, "feed dropped by innd");
2743 search_backlog_file();
2745 return OOP_CONTINUE;
2749 flushing_input_file= main_input_file;
2750 tailing_queue_readable(flushing_input_file);
2752 main_input_file= open_input_file(feedfile);
2753 if (!main_input_file)
2754 die("flush succeeded but feedfile %s does not exist!", feedfile);
2756 if (flushing_input_file) {
2757 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2760 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2762 return OOP_CONTINUE;
2765 goto unexpected_exitstatus;
2768 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2769 warn("flush timed out trying to talk to innd");
2772 unexpected_exitstatus:
2773 report_child_status("inndcomm child", status);
2777 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2778 return OOP_CONTINUE;
2781 static void inndcommfail(const char *what) {
2782 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2783 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2786 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2789 notice("flushing %s",why);
2791 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2792 assert(!inndcomm_child);
2793 assert(!inndcomm_sentinel_fd);
2795 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2797 inndcomm_child= xfork("inndcomm child");
2799 if (!inndcomm_child) {
2800 const char *flushargv[2]= { sitename, 0 };
2804 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2805 /* parent spots the autoclose of pipefds[1] when we die or exit */
2807 if (simulate_flush>=0) {
2808 warn("SIMULATING flush child status %d", simulate_flush);
2809 if (simulate_flush>128) raise(simulate_flush-128);
2810 else exit(simulate_flush);
2813 alarm(inndcomm_flush_timeout);
2814 r= ICCopen(); if (r) inndcommfail("connect");
2815 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2816 if (!r) exit(0); /* yay! */
2818 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2819 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2820 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2825 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2826 inndcomm_sentinel_fd= pipefds[0];
2827 assert(inndcomm_sentinel_fd);
2828 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2830 SMS(FLUSHING, 0, why);
2833 /*========== main program ==========*/
2835 static void postfork_inputfile(InputFile *ipf) {
2837 xclose(ipf->fd, "(in child) input file ", ipf->path);
2840 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2841 /* we have no stdio streams that are buffered long-term */
2843 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2846 static void postfork(void) {
2847 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2848 sysdie("(in child) failed to reset SIGPIPE");
2850 postfork_inputfile(main_input_file);
2851 postfork_inputfile(flushing_input_file);
2854 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2855 conn_closefd(conn,"(in child) ");
2857 postfork_stdio(defer, "defer file ", path_defer);
2860 typedef struct Every Every;
2862 struct timeval interval;
2867 static void every_schedule(Every *e, struct timeval base);
2869 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
2872 if (!e->fixed_rate) xgettimeofday(&base);
2873 every_schedule(e, base);
2874 return OOP_CONTINUE;
2877 static void every_schedule(Every *e, struct timeval base) {
2878 struct timeval when;
2879 timeradd(&base, &e->interval, &when);
2880 loop->on_time(loop, when, every_happens, e);
2883 static void every(int interval, int fixed_rate, void (*f)(void)) {
2884 Every *e= xmalloc(sizeof(*e));
2885 e->interval.tv_sec= interval;
2886 e->interval.tv_usec= 0;
2887 e->fixed_rate= fixed_rate;
2890 xgettimeofday(&now);
2891 every_schedule(e, now);
2894 static void filepoll(void) {
2895 filemon_callback(main_input_file);
2896 filemon_callback(flushing_input_file);
2899 static char *debug_report_ipf(InputFile *ipf) {
2900 if (!ipf) return xasprintf("none");
2902 const char *slash= strrchr(ipf->path,'/');
2903 const char *path= slash ? slash+1 : ipf->path;
2905 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2907 ipf->inprogress, (long)ipf->offset,
2908 ipf->fd, ipf->rd ? "+" : "");
2911 static void period(void) {
2912 char *dipf_main= debug_report_ipf(main_input_file);
2913 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2914 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2917 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2918 " input_files main:%s old:%s flushing:%s"
2919 " children connecting=%ld inndcomm=%ld"
2921 sms_names[sms], sm_period_counter,
2922 conns.count, queue.count, until_connect,
2923 dipf_main, dipf_flushing, dipf_backlog,
2924 (long)connecting_child, (long)inndcomm_child
2928 free(dipf_flushing);
2931 if (until_connect) until_connect--;
2933 poll_backlog_file();
2934 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2935 statemc_period_poll();
2936 check_assign_articles();
2941 /*========== option parsing ==========*/
2943 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2944 static void vbadusage(const char *fmt, va_list al) {
2945 char *m= xvasprintf(fmt,al);
2946 fprintf(stderr, "bad usage: %s\n"
2947 "say --help for help, or read the manpage\n",
2950 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2954 /*---------- generic option parser ----------*/
2956 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2957 static void badusage(const char *fmt, ...) {
2964 of_seconds= 001000u,
2965 of_boolean= 002000u,
2968 typedef struct Option Option;
2969 typedef void OptionParser(const Option*, const char *val);
2973 const char *lng, *formarg;
2979 static void parse_options(const Option *options, char ***argvp) {
2980 /* on return *argvp is first non-option arg; argc is not updated */
2983 const char *arg= *++(*argvp);
2985 if (*arg != '-') break;
2986 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2988 while ((a= *++arg)) {
2992 char *equals= strchr(arg,'=');
2993 int len= equals ? (equals - arg) : strlen(arg);
2994 for (o=options; o->shrt || o->lng; o++)
2995 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2997 badusage("unknown long option --%s",arg);
3000 if (equals) badusage("option --%s does not take a value",o->lng);
3002 } else if (equals) {
3006 if (!arg) badusage("option --%s needs a value for %s",
3007 o->lng, o->formarg);
3010 break; /* eaten the whole argument now */
3012 for (o=options; o->shrt || o->lng; o++)
3015 badusage("unknown short option -%c",a);
3022 if (!arg) badusage("option -%c needs a value for %s",
3023 o->shrt, o->formarg);
3026 break; /* eaten the whole argument now */
3032 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
3034 static void print_options(const Option *options, FILE *f) {
3036 for (o=options; o->shrt || o->lng; o++) {
3037 char shrt[2] = { o->shrt, 0 };
3038 char *optspec= xasprintf("%s%s%s%s%s",
3039 o->shrt ? "-" : "", shrt,
3040 o->shrt && o->lng ? "|" : "",
3041 DELIMPERHAPS("--", o->lng));
3042 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
3047 /*---------- specific option types ----------*/
3049 static void op_integer(const Option *o, const char *val) {
3052 unsigned long ul= strtoul(val,&ep,10);
3053 if (*ep || ep==val || errno || ul>INT_MAX)
3054 badusage("bad integer value for %s",o->lng);
3055 int *store= o->store;
3059 static void op_double(const Option *o, const char *val) {
3060 int *store= o->store;
3063 *store= strtod(val, &ep);
3064 if (*ep || ep==val || errno)
3065 badusage("bad floating point value for %s",o->lng);
3068 static void op_string(const Option *o, const char *val) {
3069 const char **store= o->store;
3073 static void op_seconds(const Option *o, const char *val) {
3074 int *store= o->store;
3078 double v= strtod(val,&ep);
3079 if (ep==val) badusage("bad time/duration value for %s",o->lng);
3081 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
3082 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
3083 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
3084 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
3085 else if (!strcmp(ep,"das")) unit= 10;
3086 else if (!strcmp(ep,"hs")) unit= 100;
3087 else if (!strcmp(ep,"ks")) unit= 1000;
3088 else if (!strcmp(ep,"Ms")) unit= 1000000;
3089 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
3093 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
3097 static void op_setint(const Option *o, const char *val) {
3098 int *store= o->store;
3102 /*---------- specific options ----------*/
3104 static void help(const Option *o, const char *val);
3106 static const Option innduct_options[]= {
3107 {'f',"feedfile", "F", &feedfile, op_string },
3108 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
3109 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
3110 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
3111 {'C',"inndconf", "F", &inndconffile, op_string },
3112 {'P',"port", "PORT", &port, op_integer },
3113 {0,"help", 0, 0, help },
3115 {0,"max-connections", "N", &max_connections, op_integer },
3116 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
3117 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
3118 {0,"period-interval", "TIME", &period_seconds, op_seconds },
3120 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
3121 {0,"stuck-flush-timeout","TIME", &inndcomm_flush_timeout, op_seconds },
3123 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
3124 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
3126 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
3127 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
3128 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3129 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3130 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
3131 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
3133 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
3134 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
3139 static void printusage(FILE *f) {
3140 fputs("usage: innduct [options] site [fqdn]\n"
3141 "available options are:\n", f);
3142 print_options(innduct_options, f);
3145 static void help(const Option *o, const char *val) {
3147 if (ferror(stdout) || fflush(stdout)) {
3148 perror("innduct: writing help");
3154 static void convert_to_periods_rndup(int *store) {
3155 *store += period_seconds-1;
3156 *store /= period_seconds;
3159 int main(int argc, char **argv) {
3165 parse_options(innduct_options, &argv);
3170 if (!sitename) badusage("need site name argument");
3171 remote_host= *argv++;
3172 if (*argv) badusage("too many non-option arguments");
3176 int r= innconf_read(inndconffile);
3177 if (!r) badusage("could not read inn.conf (more info on stderr)");
3179 if (!remote_host) remote_host= sitename;
3181 if (nocheck_thresh < 0 || nocheck_thresh > 100)
3182 badusage("nocheck threshold percentage must be between 0..100");
3183 nocheck_thresh *= 0.01;
3185 if (nocheck_decay < 0.1)
3186 badusage("nocheck decay articles must be at least 0.1");
3187 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3189 convert_to_periods_rndup(&reconnect_delay_periods);
3190 convert_to_periods_rndup(&flushfail_retry_periods);
3191 convert_to_periods_rndup(&backlog_retry_minperiods);
3192 convert_to_periods_rndup(&backlog_spontrescan_periods);
3193 convert_to_periods_rndup(&spontaneous_flush_periods);
3194 convert_to_periods_rndup(&need_activity_periods);
3196 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3197 badusage("bad input data ratio must be between 0..100");
3198 max_bad_data_ratio *= 0.01;
3201 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3202 } else if (!feedfile[0]) {
3203 badusage("feed filename must be nonempty");
3204 } else if (feedfile[strlen(feedfile)-1]=='/') {
3205 feedfile= xasprintf("%s%s",feedfile,sitename);
3208 const char *feedfile_forbidden= "?*[~#";
3210 while ((c= *feedfile_forbidden++))
3211 if (strchr(feedfile, c))
3212 badusage("feed filename may not contain metacharacter %c",c);
3216 path_lock= xasprintf("%s_lock", feedfile);
3217 path_flushing= xasprintf("%s_flushing", feedfile);
3218 path_defer= xasprintf("%s_defer", feedfile);
3219 path_control= xasprintf("%s_control", feedfile);
3220 globpat_backlog= xasprintf("%s_backlog*", feedfile);
3222 oop_source_sys *sysloop= oop_sys_new();
3223 if (!sysloop) sysdie("could not create liboop event loop");
3224 loop= (oop_source*)sysloop;
3226 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3227 sysdie("could not ignore SIGPIPE");
3232 if (become_daemon) {
3234 for (i=3; i<255; i++)
3235 /* do this now before we open syslog, etc. */
3237 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3239 int null= open("/dev/null",O_RDWR);
3240 if (null<0) sysfatal("failed to open /dev/null");
3244 xclose(null, "/dev/null original fd",0);
3246 pid_t child1= xfork("daemonise first fork");
3247 if (child1) _exit(0);
3249 pid_t sid= setsid();
3250 if (sid != child1) sysfatal("setsid failed");
3252 pid_t child2= xfork("daemonise second fork");
3253 if (child2) _exit(0);
3257 if (self_pid==-1) sysdie("getpid");
3268 if (!filemon_method_init()) {
3269 warn("no file monitoring available, polling");
3270 every(5,0,filepoll);
3273 every(period_seconds,1,period);
3279 void *run= oop_sys_run(sysloop);
3280 assert(run == OOP_ERROR);
3281 sysdie("event loop failed");