3 * - actually do something with readable on control master
4 * - option for realsockdir
5 * - option for filepoll
6 * - option for no inotify
7 * - manpage: document control master stuff
8 * - manpage: innconf is used for communicating with innd
10 * build-lfs/backends/innduct --no-daemon -f `pwd`/fee sit dom
14 * Newsfeeds file entries should look like this:
15 * host.name.of.site[/exclude,exclude,...]\
16 * :pattern,pattern...[/distribution,distribution...]\
20 * sitename[/exclude,exclude,...]\
21 * :pattern,pattern...[/distribution,distribution...]\
27 * or might be blanked out
28 * <spc><spc><spc><spc>....
30 * F site.name main feed file
31 * opened/created, then written, by innd
34 * tokens blanked out by duct when processed
35 * site.name_lock lock preventing multiple ducts
36 * to hold lock must open,F_SETLK[W]
37 * and then stat to check that locked file
38 * still has name site.name_lock
39 * holder of this lock is "duct"
40 * (only) lockholder may remove the lockfile
41 * D site.name_flushing temporary feed file during flush (or crash)
42 * hardlink created by duct
44 * site.name_defer 431'd articles, still being written,
45 * created, written, used by duct
47 * site.name_backlog.<date>.<inum>
48 * 431'd articles, ready for innxmit or duct
49 * created (link/mv) by duct
50 * site.name_backlog<anything-else> (where <anything-else> does not
51 * contain '#' or '~') eg
52 * site.name_backlog.manual
53 * anything the sysadmin likes (eg, feed files
54 * from old feeds to be merged into this one)
55 * created (link/mv) by admin
56 * may be symlinks (in which case links
57 * may be written through, but only links
60 * It is safe to remove backlog files manually,
61 * if it's desired to throw away the backlog.
63 * Backlog files are also processed by innduct. We find the oldest
64 * backlog file which is at least a certain amount old, and feed it
65 * back into our processing. When every article in it has been read
66 * and processed, we unlink it and look for another backlog file.
68 * If we don't have a backlog file that we're reading, we close the
69 * defer file that we're writing and make it into a backlog file at
70 * the first convenient opportunity.
81 | | <----------------<---------------------------------'|
87 | F: innd writing, duct reading |
90 | | duct decides time to flush |
91 | | duct makes hardlink |
93 | V <------------------------'|
95 | F == D: innd writing, duct reading both exist |
98 | | <-----------<-------------<--'|
102 | V <---------------------. |
105 | D: innd writing, duct reading; or ENOENT | |
107 | | duct requests flush of feed | |
108 | | (others can too, harmlessly) | |
112 | D: innd flushing, duct; or ENOENT | |
114 | | inndcomm flush fails | |
115 | |`-------------------------->------------------' |
117 | | inndcomm reports no such site |
118 | |`---------------------------------------------------- | -.
120 | | innd finishes writing D, creates F | |
121 | | inndcomm reports flush successful | |
124 | Separated <----------------' |
125 | F: innd writing F!=D /
126 | D: duct reading; or ENOENT both exist /
128 | | duct gets to the end of D /
129 | | duct opens F too /
132 | F: innd writing, duct reading |
133 | D: duct finishing V
135 | | duct finishes processing D F: ENOENT
136 | V duct unlinks D D: duct reading
138 `--<--' | duct finishes
148 "duct reading" means innduct is reading the file but also
149 overwriting processed tokens.
153 * rune for printing diagrams:
155 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
160 /*============================== PROGRAM ==============================*/
162 #define _GNU_SOURCE 1
168 #include "inndcomm.h"
170 #include "inn/list.h"
171 #include "inn/innconf.h"
174 #include <sys/types.h>
175 #include <sys/wait.h>
176 #include <sys/stat.h>
177 #include <sys/socket.h>
195 #include <oop-read.h>
197 /*----- general definitions, probably best not changed -----*/
199 #define CONNCHILD_ESTATUS_STREAM 24
200 #define CONNCHILD_ESTATUS_NOSTREAM 25
202 #define INNDCOMMCHILD_ESTATUS_FAIL 26
203 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
205 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
206 #define MAX_CONTROL_COMMAND 1000
208 #define VA va_list al; va_start(al,fmt)
209 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
210 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
212 /*----- doubly linked lists -----*/
214 #define ISNODE(T) struct node list_node
217 union { struct list li; T *for_type; } u; \
221 #define NODE(n) (assert((void*)&(n)->list_node == (n)), &(n)->list_node)
223 #define LIST_CHECKCANHAVENODE(l,n) \
224 ((void)((n) == ((l).u.for_type))) /* just for the type check */
226 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
227 ( LIST_CHECKCANHAVENODE(l,n), \
228 list_addsomehow(&(l).u.li, NODE((n))), \
232 #define LIST_REMSOMEHOW(l,list_remsomehow) \
233 ( (typeof((l).u.for_type)) \
236 list_remsomehow(&(l).u.li) ) \
242 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
243 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
244 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
245 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
247 #define LIST_INIT(l) (list_new(&(l).u.li))
248 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
249 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
250 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
252 #define LIST_REMOVE(l,n) \
253 ( LIST_CHECKCANHAVENODE(l,n), \
254 list_remove(NODE((n))), \
258 #define LIST_INSERT(l,n,pred) \
259 ( LIST_CHECKCANHAVENODE(l,n), \
260 LIST_CHECKCANHAVENODE(l,pred), \
261 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
265 /*----- type predeclarations -----*/
267 typedef struct Conn Conn;
268 typedef struct Article Article;
269 typedef struct InputFile InputFile;
270 typedef struct XmitDetails XmitDetails;
271 typedef struct Filemon_Perfile Filemon_Perfile;
272 typedef enum StateMachineState StateMachineState;
277 /*----- function predeclarations -----*/
279 static void conn_maybe_write(Conn *conn);
280 static void conn_make_some_xmits(Conn *conn);
281 static void *conn_write_some_xmits(Conn *conn);
283 static void xmit_free(XmitDetails *d);
285 #define SMS(newstate, periods, why) \
286 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
287 static void statemc_setstate(StateMachineState newsms, int periods,
288 const char *forlog, const char *why);
290 static void statemc_start_flush(const char *why); /* Normal => Flushing */
291 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
293 static void check_assign_articles(void);
294 static void queue_check_input_done(void);
296 static void statemc_check_flushing_done(void);
297 static void statemc_check_backlog_done(void);
299 static void postfork(void);
300 static void period(void);
302 static void open_defer(void);
303 static void close_defer(void);
304 static void search_backlog_file(void);
306 static void inputfile_reading_start(InputFile *ipf);
307 static void inputfile_reading_stop(InputFile *ipf);
309 static void filemon_start(InputFile *ipf);
310 static void filemon_stop(InputFile *ipf);
311 static void filemon_callback(InputFile *ipf);
313 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
314 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
316 static const oop_rd_style peer_rd_style;
317 static oop_rd_call peer_rd_err, peer_rd_ok;
319 /*----- configuration options -----*/
320 /* when changing defaults, remember to update the manpage */
322 static const char *sitename, *remote_host;
323 static const char *feedfile, *realsockdir="/tmp/innduct.control";
324 static int quiet_multiple=0;
325 static int become_daemon=1;
326 static int try_stream=1;
328 static const char *inndconffile;
330 static int max_connections=10;
331 static int max_queue_per_conn=200;
332 static int target_max_feedfile_size=100000;
333 static int period_seconds=60;
335 static int connection_setup_timeout=200;
336 static int inndcomm_flush_timeout=100;
338 static double nocheck_thresh= 95.0; /* converted from percentage by main */
339 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
341 /* all these are initialised to seconds, and converted to periods in main */
342 static int reconnect_delay_periods=1000;
343 static int flushfail_retry_periods=1000;
344 static int backlog_retry_minperiods=50;
345 static int backlog_spontrescan_periods=300;
346 static int spontaneous_flush_periods=100000;
347 static int need_activity_periods=1000;
349 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
350 static int max_bad_data_initial= 30;
351 /* in one corrupt 4096-byte block the number of newlines has
352 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
355 /*----- statistics -----*/
357 typedef enum { /* in queue in conn->sent */
358 art_Unchecked, /* not checked, not sent checking */
359 art_Wanted, /* checked, wanted sent body as requested */
360 art_Unsolicited, /* - sent body without check */
364 #define RESULT_COUNTS(RCS,RCN) \
372 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
373 #define RCI_TRIPLE_VALS_BASE(counts,x) \
374 counts[art_Unchecked] x \
375 + counts[art_Wanted] x \
376 + counts[art_Unsolicited] x, \
377 counts[art_Unchecked] x \
378 , counts[art_Wanted] x \
379 , counts[art_Unsolicited] x
382 #define RC_INDEX(x) RC_##x,
383 RESULT_COUNTS(RC_INDEX, RC_INDEX)
388 /*----- transmission buffers -----*/
393 xk_Malloc, xk_Const, xk_Artdata
405 /*----- core operational data structure types -----*/
408 /* This is also an instance of struct oop_readable */
409 struct oop_readable readable; /* first */
410 oop_readable_call *readable_callback;
411 void *readable_callback_user;
414 Filemon_Perfile *filemon;
416 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
417 long inprogress; /* no. of articles read but not processed */
421 int counts[art_MaxState][RCI_max];
422 int readcount_ok, readcount_blank, readcount_err;
437 #define SMS_LIST(X) \
445 enum StateMachineState {
446 #define SMS_DEF_ENUM(s) sm_##s,
447 SMS_LIST(SMS_DEF_ENUM)
450 static const char *sms_names[]= {
451 #define SMS_DEF_NAME(s) #s ,
452 SMS_LIST(SMS_DEF_NAME)
458 int fd; /* may be 0, meaning closed (during construction/destruction) */
459 oop_read *rd; /* likewise */
460 int max_queue, stream, quitting;
461 int since_activity; /* periods */
462 ArticleList waiting; /* not yet told peer */
463 ArticleList priority; /* peer says send it now */
464 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
465 struct iovec xmit[CONNIOVS];
466 XmitDetails xmitd[CONNIOVS];
471 /*----- general operational variables -----*/
473 /* main initialises */
474 static oop_source *loop;
475 static ConnList conns;
476 static ArticleList queue;
477 static char *path_lock, *path_flushing, *path_defer, *path_control;
478 static char *globpat_backlog;
479 static pid_t self_pid;
481 /* statemc_init initialises */
482 static StateMachineState sms;
484 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
485 static int sm_period_counter;
487 /* initialisation to 0 is good */
488 static int until_connect, until_backlog_nextscan;
489 static double accept_proportion;
490 static int nocheck, nocheck_reported;
492 /* for simulation, debugging, etc. */
493 int simulate_flush= -1;
495 /*========== logging ==========*/
497 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
498 static void logcore(int sysloglevel, const char *fmt, ...) {
501 vsyslog(sysloglevel,fmt,al);
503 if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
504 vfprintf(stderr,fmt,al);
510 static void logv(int sysloglevel, const char *pfx, int errnoval,
511 const char *fmt, va_list al) PRINTF(5,0);
512 static void logv(int sysloglevel, const char *pfx, int errnoval,
513 const char *fmt, va_list al) {
514 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
515 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
516 msgbuf[sizeof(msgbuf)-1]= 0;
518 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
519 sysloglevel= LOG_ERR; /* run by wrong user, probably */
521 logcore(sysloglevel, "<%s>%s: %s%s%s",
522 sitename, pfx, msgbuf,
523 errnoval>=0 ? ": " : "",
524 errnoval>=0 ? strerror(errnoval) : "");
527 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
528 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
529 static void fn(const char *fmt, ...) { \
531 logv(sysloglevel, pfx, err, fmt, al); \
535 #define logwrap(fn, pfx, sysloglevel, err) \
536 static void fn(const char *fmt, ...) PRINTF(1,2); \
537 static void fn(const char *fmt, ...) { \
539 logv(sysloglevel, pfx, err, fmt, al); \
543 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
544 diewrap(die, " critical", LOG_CRIT, -1, 16);
546 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
547 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
549 logwrap(syswarn, " warning", LOG_WARNING, errno);
550 logwrap(warn, " warning", LOG_WARNING, -1);
552 logwrap(notice, " notice", LOG_NOTICE, -1);
553 logwrap(info, " info", LOG_INFO, -1);
554 logwrap(debug, " debug", LOG_DEBUG, -1);
557 /*========== utility functions etc. ==========*/
559 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
560 static char *xvasprintf(const char *fmt, va_list al) {
562 int rc= vasprintf(&str,fmt,al);
563 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
566 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
567 static char *xasprintf(const char *fmt, ...) {
569 char *str= xvasprintf(fmt,al);
574 static int close_perhaps(int *fd) {
575 if (*fd <= 0) return 0;
580 static void xclose(int fd, const char *what, const char *what2) {
582 if (r) sysdie("close %s%s",what,what2?what2:"");
584 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
585 if (*fd <= 0) return;
586 xclose(*fd,what,what2);
590 static pid_t xfork(const char *what) {
594 if (child==-1) sysfatal("cannot fork for %s",what);
595 debug("forked %s %ld", what, (unsigned long)child);
596 if (!child) postfork();
600 static void on_fd_read_except(int fd, oop_call_fd callback) {
601 loop->on_fd(loop, fd, OOP_READ, callback, 0);
602 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
604 static void cancel_fd_read_except(int fd) {
605 loop->cancel_fd(loop, fd, OOP_READ);
606 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
609 static void report_child_status(const char *what, int status) {
610 if (WIFEXITED(status)) {
611 int es= WEXITSTATUS(status);
613 warn("%s: child died with error exit status %d", what, es);
614 } else if (WIFSIGNALED(status)) {
615 int sig= WTERMSIG(status);
616 const char *sigstr= strsignal(sig);
617 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
619 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
621 warn("%s: child died due to unknown fatal signal %d%s",
622 what, sig, coredump);
624 warn("%s: child died with unknown wait status %d", what,status);
628 static int xwaitpid(pid_t *pid, const char *what) {
631 int r= kill(*pid, SIGKILL);
632 if (r) sysdie("cannot kill %s child", what);
634 pid_t got= waitpid(*pid, &status, 0);
635 if (got==-1) sysdie("cannot reap %s child", what);
636 if (got==0) die("cannot reap %s child", what);
643 static void xunlink(const char *path, const char *what) {
645 if (r) sysdie("can't unlink %s %s", path, what);
648 static time_t xtime(void) {
650 if (now==-1) sysdie("time(2) failed");
654 static void xgettimeofday(struct timeval *tv_r) {
655 int r= gettimeofday(tv_r,0);
656 if (r) sysdie("gettimeofday(2) failed");
659 static void xsetnonblock(int fd, int nonblocking) {
660 int errnoval= oop_fd_nonblock(fd, nonblocking);
661 if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
664 static void check_isreg(const struct stat *stab, const char *path,
666 if (!S_ISREG(stab->st_mode))
667 die("%s %s not a plain file (mode 0%lo)",
668 what, path, (unsigned long)stab->st_mode);
671 static void xfstat(int fd, struct stat *stab_r, const char *what) {
672 int r= fstat(fd, stab_r);
673 if (r) sysdie("could not fstat %s", what);
676 static void xfstat_isreg(int fd, struct stat *stab_r,
677 const char *path, const char *what) {
678 xfstat(fd, stab_r, what);
679 check_isreg(stab_r, path, what);
682 static void xlstat_isreg(const char *path, struct stat *stab,
683 int *enoent_r /* 0 means ENOENT is fatal */,
685 int r= lstat(path, stab);
687 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
688 sysdie("could not lstat %s %s", what, path);
690 if (enoent_r) *enoent_r= 0;
691 check_isreg(stab, path, what);
694 static int samefile(const struct stat *a, const struct stat *b) {
695 assert(S_ISREG(a->st_mode));
696 assert(S_ISREG(b->st_mode));
697 return (a->st_ino == b->st_ino &&
698 a->st_dev == b->st_dev);
701 static char *sanitise(const char *input) {
702 static char sanibuf[100]; /* returns pointer to this buffer! */
704 const char *p= input;
708 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
710 if (!c) { *q++= '\''; *q=0; break; }
711 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
712 sprintf(q,"\\x%02x",c);
718 static int isewouldblock(int errnoval) {
719 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
723 /*========== command and control connections ==========*/
725 static int control_master;
727 typedef struct ControlConn ControlConn;
729 void (*destroy)(ControlConn*);
735 struct sockaddr_un un;
740 static const oop_rd_style control_rd_style= {
741 OOP_RD_DELIM_STRIP, '\n',
743 OOP_RD_SHORTREC_FORBID
746 static void control_destroy(ControlConn *cc) {
750 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
751 if (ferror(cc->out) | fflush(cc->out)) {
752 info("CTRL%d write error %s", cc->fd, strerror(errno));
757 static void control_prompt(ControlConn *cc /* may destroy*/) {
758 fprintf(cc->out, "%s| ", sitename);
759 control_checkouterr(cc);
762 typedef struct ControlCommand ControlCommand;
763 struct ControlCommand {
765 void (*f)(ControlConn *cc, const ControlCommand *ccmd,
766 const char *arg, size_t argsz);
771 static const ControlCommand control_commands[];
774 static void ccmd_##wh(ControlConn *cc, const ControlCommand *c, \
775 const char *arg, size_t argsz)
778 fputs("commands:\n", cc->out);
779 const ControlCommand *ccmd;
780 for (ccmd=control_commands; ccmd->cmd; ccmd++)
781 fprintf(cc->out, " %s\n", ccmd->cmd);
784 CCMD(period) { period(); }
785 CCMD(setintarg) { *(int*)c->xdata= atoi(arg); }
786 CCMD(setint) { *(int*)c->xdata= c->xval; }
788 static const ControlCommand control_commands[]= {
790 { "p", ccmd_period },
791 { "pretend flush", ccmd_setintarg, &simulate_flush },
792 { "poke sm", ccmd_setint, &sm_period_counter, 1 },
793 { "poke conn", ccmd_setint, &until_connect, 0 },
794 { "poke blscan", ccmd_setint, &until_backlog_nextscan, 0 },
795 { "wedge blscan", ccmd_setint, &until_backlog_nextscan, -1 },
799 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
800 const char *errmsg, int errnoval,
801 const char *data, size_t recsz, void *cc_v) {
802 ControlConn *cc= cc_v;
805 info("CTRL%d closed", cc->fd);
810 if (recsz == 0) goto prompt;
812 const ControlCommand *ccmd;
813 for (ccmd=control_commands; ccmd->cmd; ccmd++) {
814 int l= strlen(ccmd->cmd);
815 if (recsz < l) continue;
816 if (recsz > l && data[l] != ' ') continue;
817 if (memcmp(data, ccmd->cmd, l)) continue;
819 int argl= (int)recsz - (l+1);
820 ccmd->f(cc, ccmd, argl>=0 ? data+l+1 : 0, argl);
824 fputs("unknown command; h for help\n", cc->out);
831 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
832 const char *errmsg, int errnoval,
833 const char *data, size_t recsz, void *cc_v) {
834 ControlConn *cc= cc_v;
836 info("CTRL%d read error %s", cc->fd, errmsg);
841 static int control_conn_startup(ControlConn *cc /* may destroy*/,
843 cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
844 if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
846 int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
849 if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
851 info("CTRL%d %s ready", cc->fd, how);
856 static void control_stdio_destroy(ControlConn *cc) {
858 oop_rd_cancel(cc->rd);
859 errno= oop_rd_delete_tidy(cc->rd);
860 if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
865 static void control_stdio(void) {
866 ControlConn *cc= xmalloc(sizeof(*cc));
867 memset(cc,0,sizeof(*cc));
868 cc->destroy= control_stdio_destroy;
872 int r= control_conn_startup(cc,"stdio");
873 if (r) cc->destroy(cc);
876 static void control_accepted_destroy(ControlConn *cc) {
878 oop_rd_cancel(cc->rd);
879 oop_rd_delete_kill(cc->rd);
881 if (cc->out) { fclose(cc->out); cc->fd=0; }
882 close_perhaps(&cc->fd);
886 static void *control_master_readable(oop_source *lp, int master,
887 oop_event ev, void *u) {
888 ControlConn *cc= xmalloc(sizeof(*cc));
889 memset(cc,0,sizeof(*cc));
890 cc->destroy= control_accepted_destroy;
892 cc->salen= sizeof(cc->sa);
893 cc->fd= accept(master, &cc->sa.sa, &cc->salen);
894 if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
896 cc->out= fdopen(cc->fd, "w");
897 if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
899 int r= control_conn_startup(cc, "accepted");
909 #define NOCONTROL(...) do{ \
910 syswarn("no control socket, because failed to " __VA_ARGS__); \
914 static void control_init(void) {
919 struct sockaddr_un un;
922 memset(&sa,0,sizeof(sa));
923 int maxlen= sizeof(sa.un.sun_path);
925 int reallen= readlink(path_control, sa.un.sun_path, maxlen);
928 NOCONTROL("readlink control socket symlink path %s", path_control);
930 if (reallen >= maxlen) {
931 debug("control socket symlink path too long (r=%d)",reallen);
932 xunlink(path_control, "old (overlong) control socket symlink");
938 int r= lstat(realsockdir,&stab);
940 if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
942 r= mkdir(realsockdir, 0700);
943 if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
946 uid_t self= geteuid();
947 if (!S_ISDIR(stab.st_mode) ||
948 stab.st_uid != self ||
949 stab.st_mode & 0077) {
950 warn("no control socket, because real socket directory"
951 " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
952 !!S_ISDIR(stab.st_mode),
953 (unsigned long)stab.st_uid, (unsigned long)self,
954 (unsigned long)stab.st_mode & 0777UL);
959 real= xasprintf("%s/s%lx.%lx", realsockdir,
960 (unsigned long)xtime(), (unsigned long)self_pid);
961 int reallen= strlen(real);
963 if (reallen >= maxlen) {
964 warn("no control socket, because tmpnam gave overly-long path"
968 r= symlink(real, path_control);
969 if (r) NOCONTROL("make control socket path %s a symlink to real"
970 " socket path %s", path_control, real);
971 memcpy(sa.un.sun_path, real, reallen);
974 int r= unlink(sa.un.sun_path);
975 if (r && errno!=ENOENT)
976 NOCONTROL("remove old real socket %s", sa.un.sun_path);
978 control_master= socket(PF_UNIX, SOCK_STREAM, 0);
979 if (control_master<0) NOCONTROL("create new control socket");
981 sa.un.sun_family= AF_UNIX;
982 int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
983 r= bind(control_master, &sa.sa, sl);
984 if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
986 r= listen(control_master, 5);
987 if (r) NOCONTROL("listen");
989 xsetnonblock(control_master, 1);
991 loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
992 info("control socket ok, real path %s", sa.un.sun_path);
998 xclose_perhaps(&control_master, "control master",0);
1002 /*========== management of connections ==========*/
1004 static void conn_closefd(Conn *conn, const char *msgprefix) {
1005 int r= close_perhaps(&conn->fd);
1006 if (r) info("C%d %serror closing socket: %s",
1007 conn->fd, msgprefix, strerror(errno));
1010 static void conn_dispose(Conn *conn) {
1013 oop_rd_cancel(conn->rd);
1014 oop_rd_delete_kill(conn->rd);
1018 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1019 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
1021 conn_closefd(conn,"");
1023 until_connect= reconnect_delay_periods;
1026 static void *conn_exception(oop_source *lp, int fd,
1027 oop_event ev, void *conn_v) {
1030 assert(fd == conn->fd);
1031 assert(ev == OOP_EXCEPTION);
1032 int r= read(conn->fd, &ch, 1);
1033 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1034 else connfail(conn,"exceptional condition on socket (peer sent urgent"
1035 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1036 return OOP_CONTINUE;
1039 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1040 int requeue[art_MaxState];
1043 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1044 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1045 while ((art= LIST_REMHEAD(conn->sent))) {
1046 requeue[art->state]++;
1047 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1048 LIST_ADDTAIL(queue,art);
1053 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1056 char *m= xvasprintf(fmt,al);
1057 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1058 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1061 LIST_REMOVE(conns,conn);
1063 check_assign_articles();
1066 static void connfail(Conn *conn, const char *fmt, ...) {
1069 vconnfail(conn,fmt,al);
1073 static void check_idle_conns(void) {
1075 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
1076 conn->since_activity++;
1078 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
1079 if (conn->since_activity <= need_activity_periods) continue;
1081 /* We need to shut this down */
1083 connfail(conn,"timed out waiting for response to QUIT");
1084 else if (conn->sent.count)
1085 connfail(conn,"timed out waiting for responses");
1086 else if (conn->waiting.count || conn->priority.count)
1087 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1088 else if (conn->xmitu)
1089 connfail(conn,"peer has been sending responses"
1090 " before receiving our commands!");
1092 static const char quitcmd[]= "QUIT\r\n";
1093 int todo= sizeof(quitcmd)-1;
1094 const char *p= quitcmd;
1096 int r= write(conn->fd, p, todo);
1098 if (isewouldblock(errno))
1099 connfail(conn, "blocked writing QUIT to idle connection");
1101 connfail(conn, "failed to write QUIT to idle connection: %s",
1109 conn->since_activity= 0;
1110 debug("C%d is idle, quitting", conn->fd);
1119 /*---------- making new connections ----------*/
1121 static pid_t connecting_child;
1122 static int connecting_fdpass_sock;
1124 static void connect_attempt_discard(void) {
1125 if (connecting_child) {
1126 int status= xwaitpid(&connecting_child, "connect");
1127 if (!(WIFEXITED(status) ||
1128 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1129 report_child_status("connect", status);
1131 if (connecting_fdpass_sock) {
1132 cancel_fd_read_except(connecting_fdpass_sock);
1133 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1137 #define PREP_DECL_MSG_CMSG(msg) \
1138 struct msghdr msg; \
1139 memset(&msg,0,sizeof(msg)); \
1140 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
1141 msg.msg_control= msg##cbuf; \
1142 msg.msg_controllen= sizeof(msg##cbuf);
1144 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1147 assert(fd == connecting_fdpass_sock);
1148 PREP_DECL_MSG_CMSG(msg);
1149 ssize_t rs= recvmsg(fd, &msg, 0);
1151 if (isewouldblock(errno)) return OOP_CONTINUE;
1152 syswarn("failed to read socket from connecting child");
1156 conn= xmalloc(sizeof(*conn));
1157 memset(conn,0,sizeof(*conn));
1159 struct cmsghdr *h= 0;
1160 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1162 int status= xwaitpid(&connecting_child, "connect child (broken)");
1164 if (WIFEXITED(status)) {
1165 if (WEXITSTATUS(status) != 0 &&
1166 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1167 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1168 /* child already reported the problem */;
1170 if (e == OOP_EXCEPTION)
1171 warn("connect: connection child exited code %d but"
1172 " unexpected exception on fdpass socket",
1173 WEXITSTATUS(status));
1175 warn("connect: connection child exited code %d but"
1177 WEXITSTATUS(status), (int)rs);
1179 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1180 warn("connect: connection attempt timed out");
1182 report_child_status("connect", status);
1187 #define CHK(field, val) \
1188 if (h->cmsg_##field != val) { \
1189 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1190 h->cmsg_##field, val); \
1193 CHK(level, SOL_SOCKET);
1194 CHK(type, SCM_RIGHTS);
1195 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1198 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1200 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1203 pid_t got= waitpid(connecting_child, &status, 0);
1204 if (got==-1) sysdie("connect: real wait for child");
1205 assert(got == connecting_child);
1206 connecting_child= 0;
1208 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1209 int es= WEXITSTATUS(status);
1211 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1212 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1214 fatal("connect: child gave unexpected exit status %d", es);
1218 LIST_INIT(conn->waiting);
1219 LIST_INIT(conn->priority);
1220 LIST_INIT(conn->sent);
1221 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1223 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1224 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1225 if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1226 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1228 &peer_rd_err, conn);
1229 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1231 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1232 LIST_ADDHEAD(conns, conn);
1234 connect_attempt_discard();
1235 check_assign_articles();
1240 connect_attempt_discard();
1241 return OOP_CONTINUE;
1244 static int allow_connect_start(void) {
1245 return conns.count < max_connections
1246 && !connecting_child
1250 static void connect_start(void) {
1251 assert(!connecting_child);
1252 assert(!connecting_fdpass_sock);
1254 notice("starting connection attempt");
1257 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1258 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1260 connecting_child= xfork("connection");
1262 if (!connecting_child) {
1263 FILE *cn_from, *cn_to;
1264 char buf[NNTP_STRLEN+100];
1265 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1267 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1269 alarm(connection_setup_timeout);
1270 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1271 if (buf[0]) fatal("connect: failed: %s", sanitise(buf));
1272 else sysfatal("connect: connection attempt failed");
1274 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1275 sysfatal("connect: authentication failed");
1277 if (fputs("MODE STREAM\r\n", cn_to) ||
1279 sysfatal("connect: could not send MODE STREAM");
1280 buf[sizeof(buf)-1]= 0;
1281 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1282 if (ferror(cn_from))
1283 sysfatal("connect: could not read response to MODE STREAM");
1285 fatal("connect: connection close in response to MODE STREAM");
1290 fatal("connect: response to MODE STREAM is too long: %.100s...",
1292 l--; if (l>0 && buf[l-1]=='\r') l--;
1295 int rcode= strtoul(buf,&ep,10);
1297 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
1301 exitstatus= CONNCHILD_ESTATUS_STREAM;
1307 warn("connect: unexpected response to MODE STREAM: %.50s",
1313 int fd= fileno(cn_from);
1315 PREP_DECL_MSG_CMSG(msg);
1316 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1317 cmsg->cmsg_level= SOL_SOCKET;
1318 cmsg->cmsg_type= SCM_RIGHTS;
1319 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1320 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1322 msg.msg_controllen= cmsg->cmsg_len;
1323 r= sendmsg(socks[1], &msg, 0);
1324 if (r) sysdie("sendmsg failed for new connection");
1329 xclose(socks[1], "connecting fdpass child's socket",0);
1330 connecting_fdpass_sock= socks[0];
1331 xsetnonblock(connecting_fdpass_sock, 1);
1332 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1335 /*---------- assigning articles to conns, and transmitting ----------*/
1337 static void check_assign_articles(void) {
1343 int spare=0, inqueue=0;
1345 /* Find a connection to offer this article. We prefer a busy
1346 * connection to an idle one, provided it's not full. We take the
1347 * first (oldest) and since that's stable, it will mean we fill up
1348 * connections in order. That way if we have too many
1349 * connections, the spare ones will go away eventually.
1351 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1352 if (walk->quitting) continue;
1353 inqueue= walk->sent.count + walk->priority.count
1354 + walk->waiting.count;
1355 spare= walk->max_queue - inqueue;
1356 assert(inqueue <= max_queue_per_conn);
1358 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1359 else if (spare>0) /*working*/ { use= walk; break; }
1362 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1364 Article *art= LIST_REMHEAD(queue);
1365 LIST_ADDTAIL(use->waiting, art);
1368 conn_maybe_write(use);
1369 } else if (allow_connect_start()) {
1370 until_connect= reconnect_delay_periods;
1379 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1380 conn_maybe_write(u);
1381 return OOP_CONTINUE;
1384 static void conn_maybe_write(Conn *conn) {
1386 conn_make_some_xmits(conn);
1388 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1392 void *rp= conn_write_some_xmits(conn);
1393 if (rp==OOP_CONTINUE) {
1394 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1396 } else if (rp==OOP_HALT) {
1399 /* transmitted everything */
1406 /*========== article transmission ==========*/
1408 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1409 XmitKind kind) { /* caller must then fill in details */
1410 struct iovec *v= &conn->xmit[conn->xmitu];
1411 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1412 v->iov_base= (char*)data;
1418 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1419 xmit_core(conn,data,len, xk_Const);
1421 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1423 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1424 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1428 static void xmit_free(XmitDetails *d) {
1430 case xk_Malloc: free(d->info.malloc_tofree); break;
1431 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1432 case xk_Const: break;
1437 static void *conn_write_some_xmits(Conn *conn) {
1439 * 0: nothing more to write, no need to call us again
1440 * OOP_CONTINUE: more to write but fd not writeable
1441 * OOP_HALT: disaster, have destroyed conn
1444 int count= conn->xmitu;
1445 if (!count) return 0;
1447 if (count > IOV_MAX) count= IOV_MAX;
1448 ssize_t rs= writev(conn->fd, conn->xmit, count);
1450 if (isewouldblock(errno)) return OOP_CONTINUE;
1451 connfail(conn, "write failed: %s", strerror(errno));
1457 for (done=0; rs && done<conn->xmitu; done++) {
1458 struct iovec *vp= &conn->xmit[done];
1459 XmitDetails *dp= &conn->xmitd[done];
1460 if (rs > vp->iov_len) {
1464 vp->iov_base= (char*)vp->iov_base + rs;
1468 int newu= conn->xmitu - done;
1469 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1470 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1475 static void conn_make_some_xmits(Conn *conn) {
1477 if (conn->xmitu+5 > CONNIOVS)
1480 Article *art= LIST_REMHEAD(conn->priority);
1481 if (!art) art= LIST_REMHEAD(conn->waiting);
1484 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1485 /* actually send it */
1487 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1491 XMIT_LITERAL("TAKETHIS ");
1492 xmit_noalloc(conn, art->messageid, art->midlen);
1493 XMIT_LITERAL("\r\n");
1494 xmit_artbody(conn, artdata);
1497 /* we got 235 from IHAVE */
1499 xmit_artbody(conn, artdata);
1501 XMIT_LITERAL(".\r\n");
1506 art->state == art_Unchecked ? art_Unsolicited :
1507 art->state == art_Wanted ? art_Wanted :
1509 art->ipf->counts[art->state][RC_sent]++;
1510 LIST_ADDTAIL(conn->sent, art);
1516 XMIT_LITERAL("IHAVE ");
1518 XMIT_LITERAL("CHECK ");
1519 xmit_noalloc(conn, art->messageid, art->midlen);
1520 XMIT_LITERAL("\r\n");
1522 assert(art->state == art_Unchecked);
1523 art->ipf->counts[art->state][RC_sent]++;
1524 LIST_ADDTAIL(conn->sent, art);
1530 /*========== handling responses from peer ==========*/
1532 static const oop_rd_style peer_rd_style= {
1533 OOP_RD_DELIM_STRIP, '\n',
1535 OOP_RD_SHORTREC_FORBID
1538 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1539 const char *errmsg, int errnoval,
1540 const char *data, size_t recsz, void *conn_v) {
1542 connfail(conn, "error receiving from peer: %s", errmsg);
1543 return OOP_CONTINUE;
1546 static Article *article_reply_check(Conn *conn, const char *response,
1547 int code_indicates_streaming,
1549 /* 1:yes, -1:no, 0:dontcare */,
1550 const char *sanitised_response) {
1551 Article *art= LIST_HEAD(conn->sent);
1555 "peer gave unexpected response when no commands outstanding: %s",
1556 sanitised_response);
1560 if (code_indicates_streaming) {
1561 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1562 if (!conn->stream) {
1563 connfail(conn, "peer gave streaming response code "
1564 " to IHAVE or subsequent body: %s", sanitised_response);
1567 const char *got_mid= response+4;
1568 int got_midlen= strcspn(got_mid, " \n\r");
1569 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1570 connfail(conn, "peer gave streaming response with syntactically invalid"
1571 " messageid: %s", sanitised_response);
1574 if (got_midlen != art->midlen ||
1575 memcmp(got_mid, art->messageid, got_midlen)) {
1576 connfail(conn, "peer gave streaming response code to wrong article -"
1577 " probable synchronisation problem; we offered: %s;"
1579 art->messageid, sanitised_response);
1584 connfail(conn, "peer gave non-streaming response code to"
1585 " CHECK/TAKETHIS: %s", sanitised_response);
1590 if (must_have_sent>0 && art->state < art_Wanted) {
1591 connfail(conn, "peer says article accepted but"
1592 " we had not sent the body: %s", sanitised_response);
1595 if (must_have_sent<0 && art->state >= art_Wanted) {
1596 connfail(conn, "peer says please sent the article but we just did: %s",
1597 sanitised_response);
1601 Article *art_again= LIST_REMHEAD(conn->sent);
1602 assert(art_again == art);
1606 static void update_nocheck(int accepted) {
1607 accept_proportion *= nocheck_decay;
1608 accept_proportion += accepted * (1.0 - nocheck_decay);
1609 int new_nocheck= accept_proportion >= nocheck_thresh;
1610 if (new_nocheck && !nocheck_reported) {
1611 notice("entering nocheck mode for the first time");
1612 nocheck_reported= 1;
1613 } else if (new_nocheck != nocheck) {
1614 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1616 nocheck= new_nocheck;
1619 static void article_done(Conn *conn, Article *art, int whichcount) {
1620 art->ipf->counts[art->state][whichcount]++;
1621 if (whichcount == RC_accepted) update_nocheck(1);
1622 else if (whichcount == RC_unwanted) update_nocheck(0);
1624 InputFile *ipf= art->ipf;
1626 while (art->blanklen) {
1627 static const char spaces[]=
1632 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1633 int r= pwrite(ipf->fd, spaces, w, art->offset);
1635 if (errno==EINTR) continue;
1636 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1637 art->messageid, art->blanklen,
1638 (unsigned long)art->offset, ipf->path);
1640 assert(r>=0 && r<=w);
1646 assert(ipf->inprogress >= 0);
1649 if (!ipf->inprogress && ipf != main_input_file)
1650 queue_check_input_done();
1653 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1654 const char *errmsg, int errnoval,
1655 const char *data, size_t recsz, void *conn_v) {
1658 if (ev == OOP_RD_EOF) {
1659 connfail(conn, "unexpected EOF from peer");
1660 return OOP_CONTINUE;
1662 assert(ev == OOP_RD_OK);
1664 char *sani= sanitise(data);
1667 unsigned long code= strtoul(data, &ep, 10);
1668 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1669 connfail(conn, "badly formatted response from peer: %s", sani);
1670 return OOP_CONTINUE;
1673 if (conn->quitting) {
1674 if (code!=205 && code!=503) {
1675 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1677 notice("C%d idle connection closed", conn->fd);
1678 assert(!conn->waiting.count);
1679 assert(!conn->priority.count);
1680 assert(!conn->sent.count);
1681 assert(!conn->xmitu);
1682 LIST_REMOVE(conns,conn);
1685 return OOP_CONTINUE;
1688 conn->since_activity= 0;
1691 #define GET_ARTICLE(musthavesent) \
1692 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1693 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1695 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1696 code_streaming= (streaming); \
1697 GET_ARTICLE(musthavesent); \
1698 article_done(conn, art, RC_##how); break;
1700 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1702 int code_streaming= 0;
1706 case 400: PEERBADMSG("peer stopped accepting articles");
1707 case 503: PEERBADMSG("peer timed us out");
1708 default: PEERBADMSG("peer sent unexpected message");
1710 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1711 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1713 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1714 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1716 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1717 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1719 case 238: /* CHECK says send it */
1721 case 335: /* IHAVE says send it */
1723 assert(art->state == art_Unchecked);
1724 art->ipf->counts[art->state][RC_accepted]++;
1725 art->state= art_Wanted;
1726 LIST_ADDTAIL(conn->priority, art);
1729 case 431: /* CHECK or TAKETHIS says try later */
1731 case 436: /* IHAVE says try later */
1734 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1736 sysfatal("write to defer file %s",path_defer);
1737 article_done(conn, art, RC_deferred);
1742 conn_maybe_write(conn);
1743 check_assign_articles();
1744 return OOP_CONTINUE;
1748 /*========== monitoring of input files ==========*/
1750 static void feedfile_eof(InputFile *ipf) {
1751 assert(ipf != main_input_file); /* promised by tailing_try_read */
1752 inputfile_reading_stop(ipf);
1754 if (ipf == flushing_input_file) {
1755 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1756 if (main_input_file) inputfile_reading_start(main_input_file);
1757 statemc_check_flushing_done();
1758 } else if (ipf == backlog_input_file) {
1759 statemc_check_backlog_done();
1761 abort(); /* supposed to wait rather than get EOF on main input file */
1765 static InputFile *open_input_file(const char *path) {
1766 int fd= open(path, O_RDONLY);
1768 if (errno==ENOENT) return 0;
1769 sysfatal("unable to open input file %s", path);
1773 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1774 memset(ipf,0,sizeof(*ipf));
1777 strcpy(ipf->path, path);
1782 static void close_input_file(InputFile *ipf) { /* does not free */
1783 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1784 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1785 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1786 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1787 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1791 /*---------- dealing with articles read in the input file ----------*/
1793 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1794 const char *data, const char *how) {
1795 warn("corrupted file: %s, offset %lu: %s: in %s",
1796 ipf->path, (unsigned long)offset, how, sanitise(data));
1797 ipf->readcount_err++;
1798 if (ipf->readcount_err > max_bad_data_initial +
1799 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1800 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1801 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1802 return OOP_CONTINUE;
1805 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1806 oop_rd_event ev, const char *errmsg,
1807 int errnoval, const char *data, size_t recsz,
1809 InputFile *ipf= ipf_v;
1810 assert(ev == OOP_RD_SYSTEM);
1812 sysdie("error reading input file: %s, offset %lu",
1813 ipf->path, (unsigned long)ipf->offset);
1816 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1817 oop_rd_event ev, const char *errmsg,
1818 int errnoval, const char *data, size_t recsz,
1820 InputFile *ipf= ipf_v;
1822 char tokentextbuf[sizeof(TOKEN)*2+3];
1824 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1826 off_t old_offset= ipf->offset;
1827 ipf->offset += recsz + 1;
1829 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1831 if (ev==OOP_RD_PARTREC)
1832 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1833 /* but process it anyway */
1835 if (ipf->skippinglong) {
1836 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1837 return OOP_CONTINUE;
1839 if (ev==OOP_RD_LONG) {
1840 ipf->skippinglong= 1;
1841 X_BAD_DATA("overly long line");
1844 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1845 if (!recsz) X_BAD_DATA("empty line");
1848 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1849 ipf->readcount_blank++;
1850 return OOP_CONTINUE;
1853 char *space= strchr(data,' ');
1854 int tokenlen= space-data;
1855 int midlen= (int)recsz-tokenlen-1;
1856 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1857 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1859 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1860 memcpy(tokentextbuf, data, tokenlen);
1861 tokentextbuf[tokenlen]= 0;
1862 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1864 ipf->readcount_ok++;
1866 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1867 art->state= art_Unchecked;
1868 art->midlen= midlen;
1869 art->ipf= ipf; ipf->inprogress++;
1870 art->token= TextToToken(tokentextbuf);
1871 art->offset= ipf->offset;
1872 art->blanklen= recsz;
1873 strcpy(art->messageid, space+1);
1874 LIST_ADDTAIL(queue, art);
1876 if (sms==sm_NORMAL && ipf==main_input_file &&
1877 ipf->offset >= target_max_feedfile_size)
1878 statemc_start_flush("feed file size");
1880 check_assign_articles();
1881 return OOP_CONTINUE;
1884 /*========== tailing input file ==========*/
1886 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1888 InputFile *ipf= user;
1889 return ipf->readable_callback(loop, &ipf->readable,
1890 ipf->readable_callback_user);
1893 static void tailing_on_cancel(struct oop_readable *rable) {
1894 InputFile *ipf= (void*)rable;
1896 if (ipf->filemon) filemon_stop(ipf);
1897 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1898 ipf->readable_callback= 0;
1901 static void tailing_queue_readable(InputFile *ipf) {
1902 /* lifetime of ipf here is OK because destruction will cause
1903 * on_cancel which will cancel this callback */
1904 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1907 static int tailing_on_readable(struct oop_readable *rable,
1908 oop_readable_call *cb, void *user) {
1909 InputFile *ipf= (void*)rable;
1911 tailing_on_cancel(rable);
1912 ipf->readable_callback= cb;
1913 ipf->readable_callback_user= user;
1916 tailing_queue_readable(ipf);
1920 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1922 InputFile *ipf= (void*)rable;
1924 ssize_t r= read(ipf->fd, buffer, length);
1926 if (errno==EINTR) continue;
1930 if (ipf==main_input_file) {
1933 } else if (ipf==flushing_input_file) {
1935 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1936 } else if (ipf==backlog_input_file) {
1942 tailing_queue_readable(ipf);
1947 /*---------- filemon implemented with inotify ----------*/
1949 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1950 #define HAVE_FILEMON
1952 #include <linux/inotify.h>
1954 static int filemon_inotify_fd;
1955 static int filemon_inotify_wdmax;
1956 static InputFile **filemon_inotify_wd2ipf;
1958 struct Filemon_Perfile {
1962 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1963 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1964 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
1966 if (wd >= filemon_inotify_wdmax) {
1968 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1969 sizeof(*filemon_inotify_wd2ipf) * newmax);
1970 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1971 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1972 filemon_inotify_wdmax= newmax;
1975 assert(!filemon_inotify_wd2ipf[wd]);
1976 filemon_inotify_wd2ipf[wd]= ipf;
1978 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1979 ipf, wd, filemon_inotify_wdmax);
1984 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1986 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1987 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1988 if (r) sysdie("inotify_rm_watch");
1989 filemon_inotify_wd2ipf[wd]= 0;
1992 static void *filemon_inotify_readable(oop_source *lp, int fd,
1993 oop_event e, void *u) {
1994 struct inotify_event iev;
1996 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1998 if (isewouldblock(errno)) break;
1999 sysdie("read from inotify master");
2000 } else if (r==sizeof(iev)) {
2001 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
2003 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
2005 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
2006 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
2007 filemon_callback(ipf);
2009 return OOP_CONTINUE;
2012 static int filemon_method_init(void) {
2013 filemon_inotify_fd= inotify_init();
2014 if (filemon_inotify_fd<0) {
2015 syswarn("could not initialise inotify: inotify_init failed");
2019 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
2021 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2025 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2027 /*---------- filemon dummy implementation ----------*/
2029 #if !defined(HAVE_FILEMON)
2031 struct Filemon_Perfile { int dummy; };
2033 static int filemon_method_init(void) { return 0; }
2034 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2035 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2037 #endif /* !HAVE_FILEMON */
2039 /*---------- filemon generic interface ----------*/
2041 static void filemon_start(InputFile *ipf) {
2042 assert(!ipf->filemon);
2044 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
2045 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
2046 filemon_method_startfile(ipf, ipf->filemon);
2049 static void filemon_stop(InputFile *ipf) {
2050 if (!ipf->filemon) return;
2051 filemon_method_stopfile(ipf, ipf->filemon);
2056 static void filemon_callback(InputFile *ipf) {
2057 if (ipf && ipf->readable_callback) /* so filepoll() can be naive */
2058 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2061 /*---------- interface to start and stop an input file ----------*/
2063 static const oop_rd_style feedfile_rdstyle= {
2064 OOP_RD_DELIM_STRIP, '\n',
2066 OOP_RD_SHORTREC_LONG,
2069 static void inputfile_reading_start(InputFile *ipf) {
2071 ipf->readable.on_readable= tailing_on_readable;
2072 ipf->readable.on_cancel= tailing_on_cancel;
2073 ipf->readable.try_read= tailing_try_read;
2074 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2075 ipf->readable.delete_kill= 0;
2077 ipf->readable_callback= 0;
2078 ipf->readable_callback_user= 0;
2080 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2083 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2084 feedfile_got_article,ipf, feedfile_read_err, ipf);
2085 if (r) sysdie("unable start reading feedfile %s",ipf->path);
2088 static void inputfile_reading_stop(InputFile *ipf) {
2090 oop_rd_cancel(ipf->rd);
2091 oop_rd_delete(ipf->rd);
2093 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2097 /*========== interaction with innd - state machine ==========*/
2099 /* See official state diagram at top of file. We implement
2110 |`---------------------------------------------------.
2112 |`---------------- - - - |
2113 D ENOENT | D EXISTS see OVERALL STATES diagram |
2114 | for full startup logic |
2117 | ============ try to |
2123 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
2124 ^ | hardlink F to D |
2127 | | our handle onto F is now onto D |
2130 | |<-------------------<---------------------<---------+
2132 | | spawn inndcomm flush |
2134 | ================== |
2135 | FLUSHING[-ABSENT] |
2137 | main D tail/none |
2138 | ================== |
2140 | | INNDCOMM FLUSH FAILS ^
2141 | |`----------------------->----------. |
2143 | | NO SUCH SITE V |
2144 ^ |`--------------->----. ==================== |
2145 | | \ FLUSHFAILED[-ABSENT] |
2147 | | FLUSH OK \ main D tail/none |
2148 | | open F \ ==================== |
2150 | | \ | TIME TO RETRY |
2151 | |`------->----. ,---<---'\ `----------------'
2152 | | D NONE | | D NONE `----.
2154 | ============= V V ============
2155 | SEPARATED-1 | | DROPPING-1
2156 | flsh->rd!=0 | | flsh->rd!=0
2157 | [Separated] | | [Dropping]
2158 | main F idle | | main none
2159 | old D tail | | old D tail
2160 | ============= | | ============
2162 ^ | EOF ON D | | defer | EOF ON D
2164 | =============== | | ===============
2165 | SEPARATED-2 | | DROPPING-2
2166 | flsh->rd==0 | V flsh->rd==0
2167 | [Finishing] | | [Dropping]
2168 | main F tail | `. main none
2169 | old D closed | `. old D closed
2170 | =============== V `. ===============
2172 | | ALL D PROCESSED `. | ALL D PROCESSED
2173 | V install defer as backlog `. | install defer
2174 ^ | close D `. | close D
2175 | | unlink D `. | unlink D
2178 `----------' ==============
2198 static void startup_set_input_file(InputFile *f) {
2199 assert(!main_input_file);
2201 inputfile_reading_start(f);
2204 static void statemc_lock(void) {
2206 struct stat stab, stabf;
2209 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2210 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2213 memset(&fl,0,sizeof(fl));
2215 fl.l_whence= SEEK_SET;
2216 int r= fcntl(lockfd, F_SETLK, &fl);
2218 if (errno==EACCES || isewouldblock(errno)) {
2219 if (quiet_multiple) exit(0);
2220 fatal("another duct holds the lockfile");
2222 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2225 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2227 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2229 if (!lock_noent && samefile(&stab, &stabf))
2232 xclose(lockfd, "stale lockfile ", path_lock);
2235 FILE *lockfile= fdopen(lockfd, "w");
2236 if (!lockfile) sysdie("fdopen lockfile");
2238 int r= ftruncate(lockfd, 0);
2239 if (r) sysdie("truncate lockfile to write new info");
2241 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2242 (unsigned long)self_pid,
2243 sitename, feedfile, remote_host) == EOF ||
2245 sysfatal("write info to lockfile %s", path_lock);
2247 debug("startup: locked");
2250 static void statemc_init(void) {
2251 struct stat stabdefer;
2253 search_backlog_file();
2256 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2258 debug("startup: ductdefer ENOENT");
2260 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2261 switch (stabdefer.st_nlink==1) {
2263 open_defer(); /* so that we will later close it and rename it */
2266 xunlink(path_defer, "stale defer file link"
2267 " (presumably hardlink to backlog file)");
2270 die("defer file %s has unexpected link count %d",
2271 path_defer, stabdefer.st_nlink);
2275 struct stat stab_f, stab_d;
2278 InputFile *file_d= open_input_file(path_flushing);
2279 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2281 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2283 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2284 debug("startup: F==D => Hardlinked");
2285 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2290 debug("startup: F ENOENT => Moved");
2291 if (file_d) startup_set_input_file(file_d);
2292 spawn_inndcomm_flush("feedfile missing at startup");
2293 /* => Flushing, sms:=FLUSHING */
2296 debug("startup: F!=D => Separated");
2297 startup_set_input_file(file_d);
2298 SMS(SEPARATED, 0, "found both old and current feed files");
2300 debug("startup: F exists, D ENOENT => Normal");
2301 InputFile *file_f= open_input_file(feedfile);
2302 if (!file_f) die("feed file vanished during startup");
2303 startup_set_input_file(file_f);
2304 SMS(NORMAL, spontaneous_flush_periods, "normal startup");
2309 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2310 assert(sms == sm_NORMAL);
2312 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2314 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2315 (unsigned long)target_max_feedfile_size,
2318 int r= link(feedfile, path_flushing);
2319 if (r) sysfatal("link feedfile %s to flushing file %s",
2320 feedfile, path_flushing);
2323 xunlink(feedfile, "old feedfile link");
2326 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2329 static void statemc_period_poll(void) {
2330 if (!sm_period_counter) return;
2331 sm_period_counter--;
2332 assert(sm_period_counter>=0);
2334 if (sm_period_counter) return;
2337 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2339 case sm_FLUSHFAILED:
2340 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2347 static int inputfile_is_done(InputFile *ipf) {
2349 if (ipf->inprogress) return 0; /* new article in the meantime */
2350 if (ipf->rd) return 0; /* not had EOF */
2354 static void notice_processed(InputFile *ipf, const char *what,
2356 #define RCI_NOTHING(x) /* nothing */
2357 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2358 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2360 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2362 info("processed %s%s read=%d(+%dbl,+%derr)"
2363 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2364 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2367 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2368 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2369 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2370 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2371 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2372 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2378 static void statemc_check_backlog_done(void) {
2379 InputFile *ipf= backlog_input_file;
2380 if (!inputfile_is_done(ipf)) return;
2382 const char *slash= strrchr(ipf->path, '/');
2383 const char *leaf= slash ? slash+1 : ipf->path;
2384 const char *under= strchr(slash, '_');
2385 const char *rest= under ? under+1 : leaf;
2386 if (!strncmp(rest,"backlog",7)) rest += 7;
2387 notice_processed(ipf,"backlog:",rest);
2389 close_input_file(ipf);
2390 if (unlink(ipf->path)) {
2391 if (errno != ENOENT)
2392 sysdie("could not unlink processed backlog file %s", ipf->path);
2393 warn("backlog file %s vanished while we were reading it"
2394 " so we couldn't remove it (but it's done now, anyway)",
2398 backlog_input_file= 0;
2399 search_backlog_file();
2403 static void statemc_check_flushing_done(void) {
2404 InputFile *ipf= flushing_input_file;
2405 if (!inputfile_is_done(ipf)) return;
2407 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2409 notice_processed(ipf,"feedfile",0);
2413 xunlink(path_flushing, "old flushing file");
2415 close_input_file(flushing_input_file);
2416 free(flushing_input_file);
2417 flushing_input_file= 0;
2419 if (sms==sm_SEPARATED) {
2420 notice("flush complete");
2421 SMS(NORMAL, 0, "flush complete");
2422 } else if (sms==sm_DROPPING) {
2423 SMS(DROPPED, 0, "old flush complete");
2424 search_backlog_file();
2425 notice("feed dropped, but will continue until backlog is finished");
2429 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2431 assert(!inputfile_is_done(main_input_file));
2432 statemc_check_flushing_done();
2433 statemc_check_backlog_done();
2434 return OOP_CONTINUE;
2437 static void queue_check_input_done(void) {
2438 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2441 static void statemc_setstate(StateMachineState newsms, int periods,
2442 const char *forlog, const char *why) {
2444 sm_period_counter= periods;
2446 const char *xtra= "";
2449 case sm_FLUSHFAILED:
2450 if (!main_input_file) xtra= "-ABSENT";
2454 xtra= flushing_input_file->rd ? "-1" : "-2";
2460 info("state %s%s[%d] %s",forlog,xtra,periods,why);
2462 info("state %s%s %s",forlog,xtra,why);
2466 /*---------- defer and backlog files ----------*/
2468 static void open_defer(void) {
2473 defer= fopen(path_defer, "a+");
2474 if (!defer) sysfatal("could not open defer file %s", path_defer);
2476 /* truncate away any half-written records */
2478 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2480 if (stab.st_size > LONG_MAX)
2481 die("defer file %s size is far too large", path_defer);
2486 long orgsize= stab.st_size;
2487 long truncto= stab.st_size;
2489 if (!truncto) break; /* was only (if anything) one half-truncated record */
2490 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2491 sysdie("seek in defer file %s while truncating partial", path_defer);
2496 sysdie("failed read from defer file %s", path_defer);
2498 die("defer file %s shrank while we were checking it!", path_defer);
2504 if (stab.st_size != truncto) {
2505 warn("truncating half-record at end of defer file %s -"
2506 " shrinking by %ld bytes from %ld to %ld",
2507 path_defer, orgsize - truncto, orgsize, truncto);
2510 sysfatal("could not flush defer file %s", path_defer);
2511 if (ftruncate(fileno(defer), truncto))
2512 sysdie("could not truncate defer file %s", path_defer);
2515 info("continuing existing defer file %s (%ld bytes)",
2516 path_defer, orgsize);
2518 if (fseek(defer, truncto, SEEK_SET))
2519 sysdie("could not seek to new end of defer file %s", path_defer);
2522 static void close_defer(void) {
2527 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2529 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2532 time_t now= xtime();
2534 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2536 (unsigned long)stab.st_ino);
2537 if (link(path_defer, backlog))
2538 sysfatal("could not install defer file %s as backlog file %s",
2539 path_defer, backlog);
2540 if (unlink(path_defer))
2541 sysdie("could not unlink old defer link %s to backlog file %s",
2542 path_defer, backlog);
2546 if (until_backlog_nextscan < 0 ||
2547 until_backlog_nextscan > backlog_retry_minperiods + 1)
2548 until_backlog_nextscan= backlog_retry_minperiods + 1;
2551 static void poll_backlog_file(void) {
2552 if (until_backlog_nextscan < 0) return;
2553 if (until_backlog_nextscan-- > 0) return;
2554 search_backlog_file();
2557 static void search_backlog_file(void) {
2558 /* returns non-0 iff there are any backlog files */
2563 const char *oldest_path=0;
2564 time_t oldest_mtime=0, now;
2566 if (backlog_input_file) return;
2570 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2574 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2576 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2578 for (i=0; i<gl.gl_pathc; i++) {
2579 const char *path= gl.gl_pathv[i];
2581 if (strchr(path,'#') || strchr(path,'~')) {
2582 debug("backlog file search skipping %s", path);
2585 r= stat(path, &stab);
2587 syswarn("failed to stat backlog file %s", path);
2590 if (!S_ISREG(stab.st_mode)) {
2591 warn("backlog file %s is not a plain file (or link to one)", path);
2594 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2596 oldest_mtime= stab.st_mtime;
2599 case GLOB_NOMATCH: /* fall through */
2602 sysdie("glob expansion of backlog pattern %s gave unexpected"
2603 " nonzero (error?) return value %d", globpat_backlog, r);
2607 debug("backlog scan: none");
2609 if (sms==sm_DROPPED) {
2610 notice("feed dropped and our work is complete");
2612 int r= unlink(path_control);
2613 if (r && errno!=ENOENT)
2614 syswarn("failed to remove control symlink for old feed");
2616 xunlink(path_lock, "lockfile for old feed");
2619 until_backlog_nextscan= backlog_spontrescan_periods;
2624 double age= difftime(now, oldest_mtime);
2625 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2627 if (age_deficiency <= 0) {
2628 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2629 age, age_deficiency, oldest_path);
2631 backlog_input_file= open_input_file(oldest_path);
2632 if (!backlog_input_file) {
2633 warn("backlog file %s vanished as we opened it", oldest_path);
2637 inputfile_reading_start(backlog_input_file);
2638 until_backlog_nextscan= -1;
2642 until_backlog_nextscan= age_deficiency / period_seconds;
2644 if (backlog_spontrescan_periods >= 0 &&
2645 until_backlog_nextscan > backlog_spontrescan_periods)
2646 until_backlog_nextscan= backlog_spontrescan_periods;
2648 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2649 age, age_deficiency, until_backlog_nextscan, oldest_path);
2656 /*========== flushing the feed ==========*/
2658 static pid_t inndcomm_child;
2659 static int inndcomm_sentinel_fd;
2661 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2662 assert(inndcomm_child);
2663 assert(fd == inndcomm_sentinel_fd);
2664 int status= xwaitpid(&inndcomm_child, "inndcomm");
2667 cancel_fd_read_except(fd);
2668 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2669 inndcomm_sentinel_fd= 0;
2671 assert(!flushing_input_file);
2673 if (WIFEXITED(status)) {
2674 switch (WEXITSTATUS(status)) {
2676 case INNDCOMMCHILD_ESTATUS_FAIL:
2679 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2680 notice("feed has been dropped by innd, finishing up");
2681 flushing_input_file= main_input_file;
2682 tailing_queue_readable(flushing_input_file);
2683 /* we probably previously returned EAGAIN from our fake read method
2684 * when in fact we were at EOF, so signal another readable event
2685 * so we actually see the EOF */
2689 if (flushing_input_file) {
2690 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2693 SMS(DROPPED, 0, "feed dropped by innd");
2694 search_backlog_file();
2696 return OOP_CONTINUE;
2700 flushing_input_file= main_input_file;
2701 tailing_queue_readable(flushing_input_file);
2703 main_input_file= open_input_file(feedfile);
2704 if (!main_input_file)
2705 die("flush succeeded but feedfile %s does not exist!", feedfile);
2707 if (flushing_input_file) {
2708 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2711 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2713 return OOP_CONTINUE;
2716 goto unexpected_exitstatus;
2719 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2720 warn("flush timed out trying to talk to innd");
2723 unexpected_exitstatus:
2724 report_child_status("inndcomm child", status);
2728 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2729 return OOP_CONTINUE;
2732 static void inndcommfail(const char *what) {
2733 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2734 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2737 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2740 notice("flushing %s",why);
2742 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2743 assert(!inndcomm_child);
2744 assert(!inndcomm_sentinel_fd);
2746 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2748 inndcomm_child= xfork("inndcomm child");
2750 if (!inndcomm_child) {
2751 const char *flushargv[2]= { sitename, 0 };
2755 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2756 /* parent spots the autoclose of pipefds[1] when we die or exit */
2758 if (simulate_flush>=0) {
2759 warn("SIMULATING flush child status %d", simulate_flush);
2760 if (simulate_flush>128) raise(simulate_flush-128);
2761 else exit(simulate_flush);
2764 alarm(inndcomm_flush_timeout);
2765 r= ICCopen(); if (r) inndcommfail("connect");
2766 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2767 if (!r) exit(0); /* yay! */
2769 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2770 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2771 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2776 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2777 inndcomm_sentinel_fd= pipefds[0];
2778 assert(inndcomm_sentinel_fd);
2779 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2781 SMS(FLUSHING, 0, why);
2784 /*========== main program ==========*/
2786 static void postfork_inputfile(InputFile *ipf) {
2788 xclose(ipf->fd, "(in child) input file ", ipf->path);
2791 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2792 /* we have no stdio streams that are buffered long-term */
2794 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2797 static void postfork(void) {
2798 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2799 sysdie("(in child) failed to reset SIGPIPE");
2801 postfork_inputfile(main_input_file);
2802 postfork_inputfile(flushing_input_file);
2805 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2806 conn_closefd(conn,"(in child) ");
2808 postfork_stdio(defer, "defer file ", path_defer);
2811 typedef struct Every Every;
2813 struct timeval interval;
2818 static void every_schedule(Every *e, struct timeval base);
2820 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
2823 if (!e->fixed_rate) xgettimeofday(&base);
2824 every_schedule(e, base);
2825 return OOP_CONTINUE;
2828 static void every_schedule(Every *e, struct timeval base) {
2829 struct timeval when;
2830 timeradd(&base, &e->interval, &when);
2831 loop->on_time(loop, when, every_happens, e);
2834 static void every(int interval, int fixed_rate, void (*f)(void)) {
2835 Every *e= xmalloc(sizeof(*e));
2836 e->interval.tv_sec= interval;
2837 e->interval.tv_usec= 0;
2838 e->fixed_rate= fixed_rate;
2841 xgettimeofday(&now);
2842 every_schedule(e, now);
2845 static void filepoll(void) {
2846 filemon_callback(main_input_file);
2847 filemon_callback(flushing_input_file);
2850 static char *debug_report_ipf(InputFile *ipf) {
2851 if (!ipf) return xasprintf("none");
2853 const char *slash= strrchr(ipf->path,'/');
2854 const char *path= slash ? slash+1 : ipf->path;
2856 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2858 ipf->inprogress, (long)ipf->offset,
2859 ipf->fd, ipf->rd ? "+" : "");
2862 static void period(void) {
2863 char *dipf_main= debug_report_ipf(main_input_file);
2864 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2865 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2868 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2869 " input_files main:%s old:%s flushing:%s"
2870 " children connecting=%ld inndcomm=%ld"
2872 sms_names[sms], sm_period_counter,
2873 conns.count, queue.count, until_connect,
2874 dipf_main, dipf_flushing, dipf_backlog,
2875 (long)connecting_child, (long)inndcomm_child
2879 free(dipf_flushing);
2882 if (until_connect) until_connect--;
2884 poll_backlog_file();
2885 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2886 statemc_period_poll();
2887 check_assign_articles();
2892 /*========== option parsing ==========*/
2894 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2895 static void vbadusage(const char *fmt, va_list al) {
2896 char *m= xvasprintf(fmt,al);
2897 fprintf(stderr, "bad usage: %s\n"
2898 "say --help for help, or read the manpage\n",
2901 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2905 /*---------- generic option parser ----------*/
2907 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2908 static void badusage(const char *fmt, ...) {
2915 of_seconds= 001000u,
2916 of_boolean= 002000u,
2919 typedef struct Option Option;
2920 typedef void OptionParser(const Option*, const char *val);
2924 const char *lng, *formarg;
2930 static void parse_options(const Option *options, char ***argvp) {
2931 /* on return *argvp is first non-option arg; argc is not updated */
2934 const char *arg= *++(*argvp);
2936 if (*arg != '-') break;
2937 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2939 while ((a= *++arg)) {
2943 char *equals= strchr(arg,'=');
2944 int len= equals ? (equals - arg) : strlen(arg);
2945 for (o=options; o->shrt || o->lng; o++)
2946 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2948 badusage("unknown long option --%s",arg);
2951 if (equals) badusage("option --%s does not take a value",o->lng);
2953 } else if (equals) {
2957 if (!arg) badusage("option --%s needs a value for %s",
2958 o->lng, o->formarg);
2961 break; /* eaten the whole argument now */
2963 for (o=options; o->shrt || o->lng; o++)
2966 badusage("unknown short option -%c",a);
2973 if (!arg) badusage("option -%c needs a value for %s",
2974 o->shrt, o->formarg);
2977 break; /* eaten the whole argument now */
2983 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
2985 static void print_options(const Option *options, FILE *f) {
2987 for (o=options; o->shrt || o->lng; o++) {
2988 char shrt[2] = { o->shrt, 0 };
2989 char *optspec= xasprintf("%s%s%s%s%s",
2990 o->shrt ? "-" : "", shrt,
2991 o->shrt && o->lng ? "|" : "",
2992 DELIMPERHAPS("--", o->lng));
2993 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
2998 /*---------- specific option types ----------*/
3000 static void op_integer(const Option *o, const char *val) {
3003 unsigned long ul= strtoul(val,&ep,10);
3004 if (*ep || ep==val || errno || ul>INT_MAX)
3005 badusage("bad integer value for %s",o->lng);
3006 int *store= o->store;
3010 static void op_double(const Option *o, const char *val) {
3011 int *store= o->store;
3014 *store= strtod(val, &ep);
3015 if (*ep || ep==val || errno)
3016 badusage("bad floating point value for %s",o->lng);
3019 static void op_string(const Option *o, const char *val) {
3020 const char **store= o->store;
3024 static void op_seconds(const Option *o, const char *val) {
3025 int *store= o->store;
3029 double v= strtod(val,&ep);
3030 if (ep==val) badusage("bad time/duration value for %s",o->lng);
3032 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
3033 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
3034 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
3035 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
3036 else if (!strcmp(ep,"das")) unit= 10;
3037 else if (!strcmp(ep,"hs")) unit= 100;
3038 else if (!strcmp(ep,"ks")) unit= 1000;
3039 else if (!strcmp(ep,"Ms")) unit= 1000000;
3040 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
3044 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
3048 static void op_setint(const Option *o, const char *val) {
3049 int *store= o->store;
3053 /*---------- specific options ----------*/
3055 static void help(const Option *o, const char *val);
3057 static const Option innduct_options[]= {
3058 {'f',"feedfile", "F", &feedfile, op_string },
3059 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
3060 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
3061 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
3062 {0,"inndconf", "F", &inndconffile, op_string },
3063 {'P',"port", "PORT", &port, op_integer },
3064 {0,"help", 0, 0, help },
3066 {0,"max-connections", "N", &max_connections, op_integer },
3067 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
3068 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
3069 {0,"period-interval", "TIME", &period_seconds, op_seconds },
3071 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
3072 {0,"stuck-flush-timeout","TIME", &inndcomm_flush_timeout, op_seconds },
3074 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
3075 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
3077 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
3078 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
3079 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3080 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3081 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
3082 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
3084 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
3085 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
3090 static void printusage(FILE *f) {
3091 fputs("usage: innduct [options] site [fqdn]\n"
3092 "available options are:\n", f);
3093 print_options(innduct_options, f);
3096 static void help(const Option *o, const char *val) {
3098 if (ferror(stdout) || fflush(stdout)) {
3099 perror("innduct: writing help");
3105 static void convert_to_periods_rndup(int *store) {
3106 *store += period_seconds-1;
3107 *store /= period_seconds;
3110 int main(int argc, char **argv) {
3116 parse_options(innduct_options, &argv);
3121 if (!sitename) badusage("need site name argument");
3122 remote_host= *argv++;
3123 if (*argv) badusage("too many non-option arguments");
3127 if (!remote_host) remote_host= sitename;
3129 if (nocheck_thresh < 0 || nocheck_thresh > 100)
3130 badusage("nocheck threshold percentage must be between 0..100");
3131 nocheck_thresh *= 0.01;
3133 if (nocheck_decay < 0.1)
3134 badusage("nocheck decay articles must be at least 0.1");
3135 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3137 convert_to_periods_rndup(&reconnect_delay_periods);
3138 convert_to_periods_rndup(&flushfail_retry_periods);
3139 convert_to_periods_rndup(&backlog_retry_minperiods);
3140 convert_to_periods_rndup(&backlog_spontrescan_periods);
3141 convert_to_periods_rndup(&spontaneous_flush_periods);
3142 convert_to_periods_rndup(&need_activity_periods);
3144 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3145 badusage("bad input data ratio must be between 0..100");
3146 max_bad_data_ratio *= 0.01;
3149 innconf_read(inndconffile);
3150 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3151 } else if (!feedfile[0]) {
3152 badusage("feed filename must be nonempty");
3153 } else if (feedfile[strlen(feedfile)-1]=='/') {
3154 feedfile= xasprintf("%s%s",feedfile,sitename);
3157 const char *feedfile_forbidden= "?*[~#";
3159 while ((c= *feedfile_forbidden++))
3160 if (strchr(feedfile, c))
3161 badusage("feed filename may not contain metacharacter %c",c);
3165 path_lock= xasprintf("%s_lock", feedfile);
3166 path_flushing= xasprintf("%s_flushing", feedfile);
3167 path_defer= xasprintf("%s_defer", feedfile);
3168 path_control= xasprintf("%s_control", feedfile);
3169 globpat_backlog= xasprintf("%s_backlog*", feedfile);
3171 oop_source_sys *sysloop= oop_sys_new();
3172 if (!sysloop) sysdie("could not create liboop event loop");
3173 loop= (oop_source*)sysloop;
3175 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3176 sysdie("could not ignore SIGPIPE");
3181 if (become_daemon) {
3183 for (i=3; i<255; i++)
3184 /* do this now before we open syslog, etc. */
3186 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3188 int null= open("/dev/null",O_RDWR);
3189 if (null<0) sysfatal("failed to open /dev/null");
3193 xclose(null, "/dev/null original fd",0);
3195 pid_t child1= xfork("daemonise first fork");
3196 if (child1) _exit(0);
3198 pid_t sid= setsid();
3199 if (sid != child1) sysfatal("setsid failed");
3201 pid_t child2= xfork("daemonise second fork");
3202 if (child2) _exit(0);
3206 if (self_pid==-1) sysdie("getpid");
3217 if (!filemon_method_init()) {
3218 warn("no file monitoring available, polling");
3219 every(5,0,filepoll);
3222 every(period_seconds,1,period);
3228 void *r= oop_sys_run(sysloop);
3229 assert(r == OOP_ERROR);
3230 sysdie("event loop failed");