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, WNOHANG);
635 if (got==-1) sysdie("cannot reap %s child", what);
642 static void xunlink(const char *path, const char *what) {
644 if (r) sysdie("can't unlink %s %s", path, what);
647 static time_t xtime(void) {
649 if (now==-1) sysdie("time(2) failed");
653 static void xgettimeofday(struct timeval *tv_r) {
654 int r= gettimeofday(tv_r,0);
655 if (r) sysdie("gettimeofday(2) failed");
658 static void xsetnonblock(int fd, int nonblocking) {
659 int errnoval= oop_fd_nonblock(fd, nonblocking);
660 if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
663 static void check_isreg(const struct stat *stab, const char *path,
665 if (!S_ISREG(stab->st_mode))
666 die("%s %s not a plain file (mode 0%lo)",
667 what, path, (unsigned long)stab->st_mode);
670 static void xfstat(int fd, struct stat *stab_r, const char *what) {
671 int r= fstat(fd, stab_r);
672 if (r) sysdie("could not fstat %s", what);
675 static void xfstat_isreg(int fd, struct stat *stab_r,
676 const char *path, const char *what) {
677 xfstat(fd, stab_r, what);
678 check_isreg(stab_r, path, what);
681 static void xlstat_isreg(const char *path, struct stat *stab,
682 int *enoent_r /* 0 means ENOENT is fatal */,
684 int r= lstat(path, stab);
686 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
687 sysdie("could not lstat %s %s", what, path);
689 if (enoent_r) *enoent_r= 0;
690 check_isreg(stab, path, what);
693 static int samefile(const struct stat *a, const struct stat *b) {
694 assert(S_ISREG(a->st_mode));
695 assert(S_ISREG(b->st_mode));
696 return (a->st_ino == b->st_ino &&
697 a->st_dev == b->st_dev);
700 static char *sanitise(const char *input) {
701 static char sanibuf[100]; /* returns pointer to this buffer! */
703 const char *p= input;
707 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
709 if (!c) { *q++= '\''; *q=0; break; }
710 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
711 sprintf(q,"\\x%02x",c);
717 static int isewouldblock(int errnoval) {
718 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
722 /*========== command and control connections ==========*/
724 static int control_master;
726 typedef struct ControlConn ControlConn;
728 void (*destroy)(ControlConn*);
734 struct sockaddr_un un;
739 static const oop_rd_style control_rd_style= {
740 OOP_RD_DELIM_STRIP, '\n',
742 OOP_RD_SHORTREC_FORBID
745 static void control_destroy(ControlConn *cc) {
749 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
750 if (ferror(cc->out) | fflush(cc->out)) {
751 info("CTRL%d write error %s", cc->fd, strerror(errno));
756 static void control_prompt(ControlConn *cc /* may destroy*/) {
757 fprintf(cc->out, "%s| ", sitename);
758 control_checkouterr(cc);
761 typedef struct ControlCommand ControlCommand;
762 struct ControlCommand {
764 void (*f)(ControlConn *cc, const ControlCommand *ccmd,
765 const char *arg, size_t argsz);
770 static const ControlCommand control_commands[];
773 static void ccmd_##wh(ControlConn *cc, const ControlCommand *c, \
774 const char *arg, size_t argsz)
777 fputs("commands:\n", cc->out);
778 const ControlCommand *ccmd;
779 for (ccmd=control_commands; ccmd->cmd; ccmd++)
780 fprintf(cc->out, " %s\n", ccmd->cmd);
783 CCMD(period) { period(); }
784 CCMD(setintarg) { *(int*)c->xdata= atoi(arg); }
785 CCMD(setint) { *(int*)c->xdata= c->xval; }
787 static const ControlCommand control_commands[]= {
789 { "p", ccmd_period },
790 { "pretend flush", ccmd_setintarg, &simulate_flush },
791 { "poke sm", ccmd_setint, &sm_period_counter, 1 },
792 { "poke conn", ccmd_setint, &until_connect, 0 },
793 { "poke blscan", ccmd_setint, &until_backlog_nextscan, 0 },
794 { "wedge blscan", ccmd_setint, &until_backlog_nextscan, -1 },
798 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
799 const char *errmsg, int errnoval,
800 const char *data, size_t recsz, void *cc_v) {
801 ControlConn *cc= cc_v;
804 info("CTRL%d closed", cc->fd);
809 if (recsz == 0) goto prompt;
811 const ControlCommand *ccmd;
812 for (ccmd=control_commands; ccmd->cmd; ccmd++) {
813 int l= strlen(ccmd->cmd);
814 if (recsz < l) continue;
815 if (recsz > l && data[l] != ' ') continue;
816 if (memcmp(data, ccmd->cmd, l)) continue;
818 int argl= (int)recsz - (l+1);
819 ccmd->f(cc, ccmd, argl>=0 ? data+l+1 : 0, argl);
823 fputs("unknown command; h for help\n", cc->out);
830 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
831 const char *errmsg, int errnoval,
832 const char *data, size_t recsz, void *cc_v) {
833 ControlConn *cc= cc_v;
835 info("CTRL%d read error %s", cc->fd, errmsg);
840 static int control_conn_startup(ControlConn *cc /* may destroy*/,
842 cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
843 if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
845 int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
848 if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
850 info("CTRL%d %s ready", cc->fd, how);
855 static void control_stdio_destroy(ControlConn *cc) {
857 oop_rd_cancel(cc->rd);
858 errno= oop_rd_delete_tidy(cc->rd);
859 if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
864 static void control_stdio(void) {
865 ControlConn *cc= xmalloc(sizeof(*cc));
866 memset(cc,0,sizeof(*cc));
867 cc->destroy= control_stdio_destroy;
871 int r= control_conn_startup(cc,"stdio");
872 if (r) cc->destroy(cc);
875 static void control_accepted_destroy(ControlConn *cc) {
877 oop_rd_cancel(cc->rd);
878 oop_rd_delete_kill(cc->rd);
880 if (cc->out) { fclose(cc->out); cc->fd=0; }
881 close_perhaps(&cc->fd);
885 static void *control_master_readable(oop_source *lp, int master,
886 oop_event ev, void *u) {
887 ControlConn *cc= xmalloc(sizeof(*cc));
888 memset(cc,0,sizeof(*cc));
889 cc->destroy= control_accepted_destroy;
891 cc->salen= sizeof(cc->sa);
892 cc->fd= accept(master, &cc->sa.sa, &cc->salen);
893 if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
895 cc->out= fdopen(cc->fd, "w");
896 if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
898 int r= control_conn_startup(cc, "accepted");
908 #define NOCONTROL(...) do{ \
909 syswarn("no control socket, because failed to " __VA_ARGS__); \
913 static void control_init(void) {
918 struct sockaddr_un un;
921 memset(&sa,0,sizeof(sa));
922 int maxlen= sizeof(sa.un.sun_path);
924 int reallen= readlink(path_control, sa.un.sun_path, maxlen);
927 NOCONTROL("readlink control socket symlink path %s", path_control);
929 if (reallen >= maxlen) {
930 debug("control socket symlink path too long (r=%d)",reallen);
931 xunlink(path_control, "old (overlong) control socket symlink");
937 int r= lstat(realsockdir,&stab);
939 if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
941 r= mkdir(realsockdir, 0700);
942 if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
945 uid_t self= geteuid();
946 if (!S_ISDIR(stab.st_mode) ||
947 stab.st_uid != self ||
948 stab.st_mode & 0077) {
949 warn("no control socket, because real socket directory"
950 " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
951 !!S_ISDIR(stab.st_mode),
952 (unsigned long)stab.st_uid, (unsigned long)self,
953 (unsigned long)stab.st_mode & 0777UL);
958 real= xasprintf("%s/s%lx.%lx", realsockdir,
959 (unsigned long)xtime(), (unsigned long)self_pid);
960 int reallen= strlen(real);
962 if (reallen >= maxlen) {
963 warn("no control socket, because tmpnam gave overly-long path"
967 r= symlink(real, path_control);
968 if (r) NOCONTROL("make control socket path %s a symlink to real"
969 " socket path %s", path_control, real);
970 memcpy(sa.un.sun_path, real, reallen);
973 int r= unlink(sa.un.sun_path);
974 if (r && errno!=ENOENT)
975 NOCONTROL("remove old real socket %s", sa.un.sun_path);
977 control_master= socket(PF_UNIX, SOCK_STREAM, 0);
978 if (control_master<0) NOCONTROL("create new control socket");
980 sa.un.sun_family= AF_UNIX;
981 int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
982 r= bind(control_master, &sa.sa, sl);
983 if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
985 r= listen(control_master, 5);
986 if (r) NOCONTROL("listen");
988 xsetnonblock(control_master, 1);
990 loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
991 info("control socket ok, real path %s", sa.un.sun_path);
997 xclose_perhaps(&control_master, "control master",0);
1001 /*========== management of connections ==========*/
1003 static void conn_closefd(Conn *conn, const char *msgprefix) {
1004 int r= close_perhaps(&conn->fd);
1005 if (r) info("C%d %serror closing socket: %s",
1006 conn->fd, msgprefix, strerror(errno));
1009 static void conn_dispose(Conn *conn) {
1012 oop_rd_cancel(conn->rd);
1013 oop_rd_delete_kill(conn->rd);
1017 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1018 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
1020 conn_closefd(conn,"");
1022 until_connect= reconnect_delay_periods;
1025 static void *conn_exception(oop_source *lp, int fd,
1026 oop_event ev, void *conn_v) {
1029 assert(fd == conn->fd);
1030 assert(ev == OOP_EXCEPTION);
1031 int r= read(conn->fd, &ch, 1);
1032 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1033 else connfail(conn,"exceptional condition on socket (peer sent urgent"
1034 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1035 return OOP_CONTINUE;
1038 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1039 int requeue[art_MaxState];
1042 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1043 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1044 while ((art= LIST_REMHEAD(conn->sent))) {
1045 requeue[art->state]++;
1046 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1047 LIST_ADDTAIL(queue,art);
1052 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1055 char *m= xvasprintf(fmt,al);
1056 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1057 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1060 LIST_REMOVE(conns,conn);
1062 check_assign_articles();
1065 static void connfail(Conn *conn, const char *fmt, ...) {
1068 vconnfail(conn,fmt,al);
1072 static void check_idle_conns(void) {
1074 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
1075 conn->since_activity++;
1077 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
1078 if (conn->since_activity <= need_activity_periods) continue;
1080 /* We need to shut this down */
1082 connfail(conn,"timed out waiting for response to QUIT");
1083 else if (conn->sent.count)
1084 connfail(conn,"timed out waiting for responses");
1085 else if (conn->waiting.count || conn->priority.count)
1086 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1087 else if (conn->xmitu)
1088 connfail(conn,"peer has been sending responses"
1089 " before receiving our commands!");
1091 static const char quitcmd[]= "QUIT\r\n";
1092 int todo= sizeof(quitcmd)-1;
1093 const char *p= quitcmd;
1095 int r= write(conn->fd, p, todo);
1097 if (isewouldblock(errno))
1098 connfail(conn, "blocked writing QUIT to idle connection");
1100 connfail(conn, "failed to write QUIT to idle connection: %s",
1108 conn->since_activity= 0;
1109 debug("C%d is idle, quitting", conn->fd);
1118 /*---------- making new connections ----------*/
1120 static pid_t connecting_child;
1121 static int connecting_fdpass_sock;
1123 static void connect_attempt_discard(void) {
1124 if (connecting_child) {
1125 int r= kill(connecting_child, SIGTERM);
1126 if (r) syswarn("failed to kill connecting child");
1127 int status= xwaitpid(&connecting_child, "connect");
1129 if (!(WIFEXITED(status) ||
1130 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1131 report_child_status("connect", status);
1133 if (connecting_fdpass_sock) {
1134 cancel_fd_read_except(connecting_fdpass_sock);
1135 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1139 #define PREP_DECL_MSG_CMSG(msg) \
1140 struct msghdr msg; \
1141 memset(&msg,0,sizeof(msg)); \
1142 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
1143 msg.msg_control= msg##cbuf; \
1144 msg.msg_controllen= sizeof(msg##cbuf);
1146 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1149 assert(fd == connecting_fdpass_sock);
1151 conn= xmalloc(sizeof(*conn));
1152 memset(conn,0,sizeof(*conn));
1154 PREP_DECL_MSG_CMSG(msg);
1155 struct cmsghdr *h= 0;
1156 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
1157 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1160 pid_t got= waitpid(connecting_child, &status, WNOHANG);
1162 assert(got==connecting_child);
1163 connecting_child= 0;
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 warn("connect: connection child exited code %d but no cmsg",
1171 WEXITSTATUS(status));
1172 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1173 warn("connect: connection attempt timed out");
1175 report_child_status("connect", status);
1178 /* child is still running apparently, report the socket problem */
1180 syswarn("connect: read from fdpass socket failed");
1181 else if (e == OOP_EXCEPTION)
1182 warn("connect: unexpected exception on fdpass socket");
1184 warn("connect: unexpected EOF on fdpass socket");
1186 fatal("connect: unexpected lack of cmsg from child");
1191 #define CHK(field, val) \
1192 if (h->cmsg_##field != val) { \
1193 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1194 h->cmsg_##field, val); \
1197 CHK(level, SOL_SOCKET);
1198 CHK(type, SCM_RIGHTS);
1199 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1202 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1204 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1207 pid_t got= waitpid(connecting_child, &status, 0);
1208 if (got==-1) sysdie("connect: real wait for child");
1209 assert(got == connecting_child);
1210 connecting_child= 0;
1212 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1213 int es= WEXITSTATUS(status);
1215 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1216 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1218 fatal("connect: child gave unexpected exit status %d", es);
1222 LIST_INIT(conn->waiting);
1223 LIST_INIT(conn->priority);
1224 LIST_INIT(conn->sent);
1225 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1227 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1228 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1229 if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1230 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1232 &peer_rd_err, conn);
1233 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1235 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1236 LIST_ADDHEAD(conns, conn);
1238 connect_attempt_discard();
1239 check_assign_articles();
1244 connect_attempt_discard();
1245 return OOP_CONTINUE;
1248 static int allow_connect_start(void) {
1249 return conns.count < max_connections
1250 && !connecting_child
1254 static void connect_start(void) {
1255 assert(!connecting_child);
1256 assert(!connecting_fdpass_sock);
1258 notice("starting connection attempt");
1261 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1262 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1264 connecting_child= xfork("connection");
1266 if (!connecting_child) {
1267 FILE *cn_from, *cn_to;
1268 char buf[NNTP_STRLEN+100];
1269 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1271 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1273 alarm(connection_setup_timeout);
1274 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1275 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
1276 else sysfatal("connect: connection attempt failed");
1278 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1279 sysfatal("connect: authentication failed");
1281 if (fputs("MODE STREAM\r\n", cn_to) ||
1283 sysfatal("connect: could not send MODE STREAM");
1284 buf[sizeof(buf)-1]= 0;
1285 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1286 if (ferror(cn_from))
1287 sysfatal("connect: could not read response to MODE STREAM");
1289 fatal("connect: connection close in response to MODE STREAM");
1294 fatal("connect: response to MODE STREAM is too long: %.100s...",
1296 l--; if (l>0 && buf[l-1]=='\r') l--;
1299 int rcode= strtoul(buf,&ep,10);
1301 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
1305 exitstatus= CONNCHILD_ESTATUS_STREAM;
1311 warn("connect: unexpected response to MODE STREAM: %.50s",
1317 int fd= fileno(cn_from);
1319 PREP_DECL_MSG_CMSG(msg);
1320 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1321 cmsg->cmsg_level= SOL_SOCKET;
1322 cmsg->cmsg_type= SCM_RIGHTS;
1323 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1324 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1326 msg.msg_controllen= cmsg->cmsg_len;
1327 r= sendmsg(socks[1], &msg, 0);
1328 if (r) sysdie("sendmsg failed for new connection");
1333 xclose(socks[1], "connecting fdpass child's socket",0);
1334 connecting_fdpass_sock= socks[0];
1335 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1338 /*---------- assigning articles to conns, and transmitting ----------*/
1340 static void check_assign_articles(void) {
1346 int spare=0, inqueue=0;
1348 /* Find a connection to offer this article. We prefer a busy
1349 * connection to an idle one, provided it's not full. We take the
1350 * first (oldest) and since that's stable, it will mean we fill up
1351 * connections in order. That way if we have too many
1352 * connections, the spare ones will go away eventually.
1354 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1355 if (walk->quitting) continue;
1356 inqueue= walk->sent.count + walk->priority.count
1357 + walk->waiting.count;
1358 spare= walk->max_queue - inqueue;
1359 assert(inqueue <= max_queue_per_conn);
1361 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1362 else if (spare>0) /*working*/ { use= walk; break; }
1365 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1367 Article *art= LIST_REMHEAD(queue);
1368 LIST_ADDTAIL(use->waiting, art);
1371 conn_maybe_write(use);
1372 } else if (allow_connect_start()) {
1373 until_connect= reconnect_delay_periods;
1382 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1383 conn_maybe_write(u);
1384 return OOP_CONTINUE;
1387 static void conn_maybe_write(Conn *conn) {
1389 conn_make_some_xmits(conn);
1391 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1395 void *rp= conn_write_some_xmits(conn);
1396 if (rp==OOP_CONTINUE) {
1397 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1399 } else if (rp==OOP_HALT) {
1402 /* transmitted everything */
1409 /*========== article transmission ==========*/
1411 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1412 XmitKind kind) { /* caller must then fill in details */
1413 struct iovec *v= &conn->xmit[conn->xmitu];
1414 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1415 v->iov_base= (char*)data;
1421 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1422 xmit_core(conn,data,len, xk_Const);
1424 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1426 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1427 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1431 static void xmit_free(XmitDetails *d) {
1433 case xk_Malloc: free(d->info.malloc_tofree); break;
1434 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1435 case xk_Const: break;
1440 static void *conn_write_some_xmits(Conn *conn) {
1442 * 0: nothing more to write, no need to call us again
1443 * OOP_CONTINUE: more to write but fd not writeable
1444 * OOP_HALT: disaster, have destroyed conn
1447 int count= conn->xmitu;
1448 if (!count) return 0;
1450 if (count > IOV_MAX) count= IOV_MAX;
1451 ssize_t rs= writev(conn->fd, conn->xmit, count);
1453 if (isewouldblock(errno)) return OOP_CONTINUE;
1454 connfail(conn, "write failed: %s", strerror(errno));
1460 for (done=0; rs && done<conn->xmitu; done++) {
1461 struct iovec *vp= &conn->xmit[done];
1462 XmitDetails *dp= &conn->xmitd[done];
1463 if (rs > vp->iov_len) {
1467 vp->iov_base= (char*)vp->iov_base + rs;
1471 int newu= conn->xmitu - done;
1472 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1473 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1478 static void conn_make_some_xmits(Conn *conn) {
1480 if (conn->xmitu+5 > CONNIOVS)
1483 Article *art= LIST_REMHEAD(conn->priority);
1484 if (!art) art= LIST_REMHEAD(conn->waiting);
1487 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1488 /* actually send it */
1490 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1494 XMIT_LITERAL("TAKETHIS ");
1495 xmit_noalloc(conn, art->messageid, art->midlen);
1496 XMIT_LITERAL("\r\n");
1497 xmit_artbody(conn, artdata);
1500 /* we got 235 from IHAVE */
1502 xmit_artbody(conn, artdata);
1504 XMIT_LITERAL(".\r\n");
1509 art->state == art_Unchecked ? art_Unsolicited :
1510 art->state == art_Wanted ? art_Wanted :
1512 art->ipf->counts[art->state][RC_sent]++;
1513 LIST_ADDTAIL(conn->sent, art);
1519 XMIT_LITERAL("IHAVE ");
1521 XMIT_LITERAL("CHECK ");
1522 xmit_noalloc(conn, art->messageid, art->midlen);
1523 XMIT_LITERAL("\r\n");
1525 assert(art->state == art_Unchecked);
1526 art->ipf->counts[art->state][RC_sent]++;
1527 LIST_ADDTAIL(conn->sent, art);
1533 /*========== handling responses from peer ==========*/
1535 static const oop_rd_style peer_rd_style= {
1536 OOP_RD_DELIM_STRIP, '\n',
1538 OOP_RD_SHORTREC_FORBID
1541 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1542 const char *errmsg, int errnoval,
1543 const char *data, size_t recsz, void *conn_v) {
1545 connfail(conn, "error receiving from peer: %s", errmsg);
1546 return OOP_CONTINUE;
1549 static Article *article_reply_check(Conn *conn, const char *response,
1550 int code_indicates_streaming,
1552 /* 1:yes, -1:no, 0:dontcare */,
1553 const char *sanitised_response) {
1554 Article *art= LIST_HEAD(conn->sent);
1558 "peer gave unexpected response when no commands outstanding: %s",
1559 sanitised_response);
1563 if (code_indicates_streaming) {
1564 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1565 if (!conn->stream) {
1566 connfail(conn, "peer gave streaming response code "
1567 " to IHAVE or subsequent body: %s", sanitised_response);
1570 const char *got_mid= response+4;
1571 int got_midlen= strcspn(got_mid, " \n\r");
1572 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1573 connfail(conn, "peer gave streaming response with syntactically invalid"
1574 " messageid: %s", sanitised_response);
1577 if (got_midlen != art->midlen ||
1578 memcmp(got_mid, art->messageid, got_midlen)) {
1579 connfail(conn, "peer gave streaming response code to wrong article -"
1580 " probable synchronisation problem; we offered: %s;"
1582 art->messageid, sanitised_response);
1587 connfail(conn, "peer gave non-streaming response code to"
1588 " CHECK/TAKETHIS: %s", sanitised_response);
1593 if (must_have_sent>0 && art->state < art_Wanted) {
1594 connfail(conn, "peer says article accepted but"
1595 " we had not sent the body: %s", sanitised_response);
1598 if (must_have_sent<0 && art->state >= art_Wanted) {
1599 connfail(conn, "peer says please sent the article but we just did: %s",
1600 sanitised_response);
1604 Article *art_again= LIST_REMHEAD(conn->sent);
1605 assert(art_again == art);
1609 static void update_nocheck(int accepted) {
1610 accept_proportion *= nocheck_decay;
1611 accept_proportion += accepted * (1.0 - nocheck_decay);
1612 int new_nocheck= accept_proportion >= nocheck_thresh;
1613 if (new_nocheck && !nocheck_reported) {
1614 notice("entering nocheck mode for the first time");
1615 nocheck_reported= 1;
1616 } else if (new_nocheck != nocheck) {
1617 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1619 nocheck= new_nocheck;
1622 static void article_done(Conn *conn, Article *art, int whichcount) {
1623 art->ipf->counts[art->state][whichcount]++;
1624 if (whichcount == RC_accepted) update_nocheck(1);
1625 else if (whichcount == RC_unwanted) update_nocheck(0);
1627 InputFile *ipf= art->ipf;
1629 while (art->blanklen) {
1630 static const char spaces[]=
1635 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1636 int r= pwrite(ipf->fd, spaces, w, art->offset);
1638 if (errno==EINTR) continue;
1639 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1640 art->messageid, art->blanklen,
1641 (unsigned long)art->offset, ipf->path);
1643 assert(r>=0 && r<=w);
1649 assert(ipf->inprogress >= 0);
1652 if (!ipf->inprogress && ipf != main_input_file)
1653 queue_check_input_done();
1656 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1657 const char *errmsg, int errnoval,
1658 const char *data, size_t recsz, void *conn_v) {
1661 if (ev == OOP_RD_EOF) {
1662 connfail(conn, "unexpected EOF from peer");
1663 return OOP_CONTINUE;
1665 assert(ev == OOP_RD_OK);
1667 char *sani= sanitise(data);
1670 unsigned long code= strtoul(data, &ep, 10);
1671 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1672 connfail(conn, "badly formatted response from peer: %s", sani);
1673 return OOP_CONTINUE;
1676 if (conn->quitting) {
1677 if (code!=205 && code!=503) {
1678 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1680 notice("C%d idle connection closed", conn->fd);
1681 assert(!conn->waiting.count);
1682 assert(!conn->priority.count);
1683 assert(!conn->sent.count);
1684 assert(!conn->xmitu);
1685 LIST_REMOVE(conns,conn);
1688 return OOP_CONTINUE;
1691 conn->since_activity= 0;
1694 #define GET_ARTICLE(musthavesent) \
1695 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1696 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1698 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1699 code_streaming= (streaming); \
1700 GET_ARTICLE(musthavesent); \
1701 article_done(conn, art, RC_##how); break;
1703 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1705 int code_streaming= 0;
1709 case 400: PEERBADMSG("peer stopped accepting articles");
1710 case 503: PEERBADMSG("peer timed us out");
1711 default: PEERBADMSG("peer sent unexpected message");
1713 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1714 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1716 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1717 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1719 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1720 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1722 case 238: /* CHECK says send it */
1724 case 335: /* IHAVE says send it */
1726 assert(art->state == art_Unchecked);
1727 art->ipf->counts[art->state][RC_accepted]++;
1728 art->state= art_Wanted;
1729 LIST_ADDTAIL(conn->priority, art);
1732 case 431: /* CHECK or TAKETHIS says try later */
1734 case 436: /* IHAVE says try later */
1737 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1739 sysfatal("write to defer file %s",path_defer);
1740 article_done(conn, art, RC_deferred);
1745 conn_maybe_write(conn);
1746 check_assign_articles();
1747 return OOP_CONTINUE;
1751 /*========== monitoring of input files ==========*/
1753 static void feedfile_eof(InputFile *ipf) {
1754 assert(ipf != main_input_file); /* promised by tailing_try_read */
1755 inputfile_reading_stop(ipf);
1757 if (ipf == flushing_input_file) {
1758 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1759 if (main_input_file) inputfile_reading_start(main_input_file);
1760 statemc_check_flushing_done();
1761 } else if (ipf == backlog_input_file) {
1762 statemc_check_backlog_done();
1764 abort(); /* supposed to wait rather than get EOF on main input file */
1768 static InputFile *open_input_file(const char *path) {
1769 int fd= open(path, O_RDONLY);
1771 if (errno==ENOENT) return 0;
1772 sysfatal("unable to open input file %s", path);
1776 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1777 memset(ipf,0,sizeof(*ipf));
1780 strcpy(ipf->path, path);
1785 static void close_input_file(InputFile *ipf) { /* does not free */
1786 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1787 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1788 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1789 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1790 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1794 /*---------- dealing with articles read in the input file ----------*/
1796 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1797 const char *data, const char *how) {
1798 warn("corrupted file: %s, offset %lu: %s: in %s",
1799 ipf->path, (unsigned long)offset, how, sanitise(data));
1800 ipf->readcount_err++;
1801 if (ipf->readcount_err > max_bad_data_initial +
1802 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1803 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1804 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1805 return OOP_CONTINUE;
1808 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1809 oop_rd_event ev, const char *errmsg,
1810 int errnoval, const char *data, size_t recsz,
1812 InputFile *ipf= ipf_v;
1813 assert(ev == OOP_RD_SYSTEM);
1815 sysdie("error reading input file: %s, offset %lu",
1816 ipf->path, (unsigned long)ipf->offset);
1819 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1820 oop_rd_event ev, const char *errmsg,
1821 int errnoval, const char *data, size_t recsz,
1823 InputFile *ipf= ipf_v;
1825 char tokentextbuf[sizeof(TOKEN)*2+3];
1827 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1829 off_t old_offset= ipf->offset;
1830 ipf->offset += recsz + 1;
1832 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1834 if (ev==OOP_RD_PARTREC)
1835 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1836 /* but process it anyway */
1838 if (ipf->skippinglong) {
1839 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1840 return OOP_CONTINUE;
1842 if (ev==OOP_RD_LONG) {
1843 ipf->skippinglong= 1;
1844 X_BAD_DATA("overly long line");
1847 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1848 if (!recsz) X_BAD_DATA("empty line");
1851 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1852 ipf->readcount_blank++;
1853 return OOP_CONTINUE;
1856 char *space= strchr(data,' ');
1857 int tokenlen= space-data;
1858 int midlen= (int)recsz-tokenlen-1;
1859 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1860 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1862 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1863 memcpy(tokentextbuf, data, tokenlen);
1864 tokentextbuf[tokenlen]= 0;
1865 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1867 ipf->readcount_ok++;
1869 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1870 art->state= art_Unchecked;
1871 art->midlen= midlen;
1872 art->ipf= ipf; ipf->inprogress++;
1873 art->token= TextToToken(tokentextbuf);
1874 art->offset= ipf->offset;
1875 art->blanklen= recsz;
1876 strcpy(art->messageid, space+1);
1877 LIST_ADDTAIL(queue, art);
1879 if (sms==sm_NORMAL && ipf==main_input_file &&
1880 ipf->offset >= target_max_feedfile_size)
1881 statemc_start_flush("feed file size");
1883 check_assign_articles();
1884 return OOP_CONTINUE;
1887 /*========== tailing input file ==========*/
1889 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1891 InputFile *ipf= user;
1892 return ipf->readable_callback(loop, &ipf->readable,
1893 ipf->readable_callback_user);
1896 static void tailing_on_cancel(struct oop_readable *rable) {
1897 InputFile *ipf= (void*)rable;
1899 if (ipf->filemon) filemon_stop(ipf);
1900 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1901 ipf->readable_callback= 0;
1904 static void tailing_queue_readable(InputFile *ipf) {
1905 /* lifetime of ipf here is OK because destruction will cause
1906 * on_cancel which will cancel this callback */
1907 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1910 static int tailing_on_readable(struct oop_readable *rable,
1911 oop_readable_call *cb, void *user) {
1912 InputFile *ipf= (void*)rable;
1914 tailing_on_cancel(rable);
1915 ipf->readable_callback= cb;
1916 ipf->readable_callback_user= user;
1919 tailing_queue_readable(ipf);
1923 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1925 InputFile *ipf= (void*)rable;
1927 ssize_t r= read(ipf->fd, buffer, length);
1929 if (errno==EINTR) continue;
1933 if (ipf==main_input_file) {
1936 } else if (ipf==flushing_input_file) {
1938 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1939 } else if (ipf==backlog_input_file) {
1945 tailing_queue_readable(ipf);
1950 /*---------- filemon implemented with inotify ----------*/
1952 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1953 #define HAVE_FILEMON
1955 #include <linux/inotify.h>
1957 static int filemon_inotify_fd;
1958 static int filemon_inotify_wdmax;
1959 static InputFile **filemon_inotify_wd2ipf;
1961 struct Filemon_Perfile {
1965 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1966 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1967 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
1969 if (wd >= filemon_inotify_wdmax) {
1971 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1972 sizeof(*filemon_inotify_wd2ipf) * newmax);
1973 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1974 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1975 filemon_inotify_wdmax= newmax;
1978 assert(!filemon_inotify_wd2ipf[wd]);
1979 filemon_inotify_wd2ipf[wd]= ipf;
1981 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1982 ipf, wd, filemon_inotify_wdmax);
1987 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1989 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1990 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1991 if (r) sysdie("inotify_rm_watch");
1992 filemon_inotify_wd2ipf[wd]= 0;
1995 static void *filemon_inotify_readable(oop_source *lp, int fd,
1996 oop_event e, void *u) {
1997 struct inotify_event iev;
1999 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
2001 if (isewouldblock(errno)) break;
2002 sysdie("read from inotify master");
2003 } else if (r==sizeof(iev)) {
2004 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
2006 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
2008 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
2009 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
2010 filemon_callback(ipf);
2012 return OOP_CONTINUE;
2015 static int filemon_method_init(void) {
2016 filemon_inotify_fd= inotify_init();
2017 if (filemon_inotify_fd<0) {
2018 syswarn("could not initialise inotify: inotify_init failed");
2022 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
2024 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2028 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2030 /*---------- filemon dummy implementation ----------*/
2032 #if !defined(HAVE_FILEMON)
2034 struct Filemon_Perfile { int dummy; };
2036 static int filemon_method_init(void) { return 0; }
2037 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2038 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2040 #endif /* !HAVE_FILEMON */
2042 /*---------- filemon generic interface ----------*/
2044 static void filemon_start(InputFile *ipf) {
2045 assert(!ipf->filemon);
2047 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
2048 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
2049 filemon_method_startfile(ipf, ipf->filemon);
2052 static void filemon_stop(InputFile *ipf) {
2053 if (!ipf->filemon) return;
2054 filemon_method_stopfile(ipf, ipf->filemon);
2059 static void filemon_callback(InputFile *ipf) {
2060 if (ipf && ipf->readable_callback) /* so filepoll() can be naive */
2061 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2064 /*---------- interface to start and stop an input file ----------*/
2066 static const oop_rd_style feedfile_rdstyle= {
2067 OOP_RD_DELIM_STRIP, '\n',
2069 OOP_RD_SHORTREC_LONG,
2072 static void inputfile_reading_start(InputFile *ipf) {
2074 ipf->readable.on_readable= tailing_on_readable;
2075 ipf->readable.on_cancel= tailing_on_cancel;
2076 ipf->readable.try_read= tailing_try_read;
2077 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2078 ipf->readable.delete_kill= 0;
2080 ipf->readable_callback= 0;
2081 ipf->readable_callback_user= 0;
2083 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2086 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2087 feedfile_got_article,ipf, feedfile_read_err, ipf);
2088 if (r) sysdie("unable start reading feedfile %s",ipf->path);
2091 static void inputfile_reading_stop(InputFile *ipf) {
2093 oop_rd_cancel(ipf->rd);
2094 oop_rd_delete(ipf->rd);
2096 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2100 /*========== interaction with innd - state machine ==========*/
2102 /* See official state diagram at top of file. We implement
2113 |`---------------------------------------------------.
2115 |`---------------- - - - |
2116 D ENOENT | D EXISTS see OVERALL STATES diagram |
2117 | for full startup logic |
2120 | ============ try to |
2126 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
2127 ^ | hardlink F to D |
2130 | | our handle onto F is now onto D |
2133 | |<-------------------<---------------------<---------+
2135 | | spawn inndcomm flush |
2137 | ================== |
2138 | FLUSHING[-ABSENT] |
2140 | main D tail/none |
2141 | ================== |
2143 | | INNDCOMM FLUSH FAILS ^
2144 | |`----------------------->----------. |
2146 | | NO SUCH SITE V |
2147 ^ |`--------------->----. ==================== |
2148 | | \ FLUSHFAILED[-ABSENT] |
2150 | | FLUSH OK \ main D tail/none |
2151 | | open F \ ==================== |
2153 | | \ | TIME TO RETRY |
2154 | |`------->----. ,---<---'\ `----------------'
2155 | | D NONE | | D NONE `----.
2157 | ============= V V ============
2158 | SEPARATED-1 | | DROPPING-1
2159 | flsh->rd!=0 | | flsh->rd!=0
2160 | [Separated] | | [Dropping]
2161 | main F idle | | main none
2162 | old D tail | | old D tail
2163 | ============= | | ============
2165 ^ | EOF ON D | | defer | EOF ON D
2167 | =============== | | ===============
2168 | SEPARATED-2 | | DROPPING-2
2169 | flsh->rd==0 | V flsh->rd==0
2170 | [Finishing] | | [Dropping]
2171 | main F tail | `. main none
2172 | old D closed | `. old D closed
2173 | =============== V `. ===============
2175 | | ALL D PROCESSED `. | ALL D PROCESSED
2176 | V install defer as backlog `. | install defer
2177 ^ | close D `. | close D
2178 | | unlink D `. | unlink D
2181 `----------' ==============
2201 static void startup_set_input_file(InputFile *f) {
2202 assert(!main_input_file);
2204 inputfile_reading_start(f);
2207 static void statemc_lock(void) {
2209 struct stat stab, stabf;
2212 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2213 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2216 memset(&fl,0,sizeof(fl));
2218 fl.l_whence= SEEK_SET;
2219 int r= fcntl(lockfd, F_SETLK, &fl);
2221 if (errno==EACCES || isewouldblock(errno)) {
2222 if (quiet_multiple) exit(0);
2223 fatal("another duct holds the lockfile");
2225 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2228 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2230 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2232 if (!lock_noent && samefile(&stab, &stabf))
2235 xclose(lockfd, "stale lockfile ", path_lock);
2238 FILE *lockfile= fdopen(lockfd, "w");
2239 if (!lockfile) sysdie("fdopen lockfile");
2241 int r= ftruncate(lockfd, 0);
2242 if (r) sysdie("truncate lockfile to write new info");
2244 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2245 (unsigned long)self_pid,
2246 sitename, feedfile, remote_host) == EOF ||
2248 sysfatal("write info to lockfile %s", path_lock);
2250 debug("startup: locked");
2253 static void statemc_init(void) {
2254 struct stat stabdefer;
2256 search_backlog_file();
2259 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2261 debug("startup: ductdefer ENOENT");
2263 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2264 switch (stabdefer.st_nlink==1) {
2266 open_defer(); /* so that we will later close it and rename it */
2269 xunlink(path_defer, "stale defer file link"
2270 " (presumably hardlink to backlog file)");
2273 die("defer file %s has unexpected link count %d",
2274 path_defer, stabdefer.st_nlink);
2278 struct stat stab_f, stab_d;
2281 InputFile *file_d= open_input_file(path_flushing);
2282 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2284 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2286 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2287 debug("startup: F==D => Hardlinked");
2288 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2293 debug("startup: F ENOENT => Moved");
2294 if (file_d) startup_set_input_file(file_d);
2295 spawn_inndcomm_flush("feedfile missing at startup");
2296 /* => Flushing, sms:=FLUSHING */
2299 debug("startup: F!=D => Separated");
2300 startup_set_input_file(file_d);
2301 SMS(SEPARATED, 0, "found both old and current feed files");
2303 debug("startup: F exists, D ENOENT => Normal");
2304 InputFile *file_f= open_input_file(feedfile);
2305 if (!file_f) die("feed file vanished during startup");
2306 startup_set_input_file(file_f);
2307 SMS(NORMAL, spontaneous_flush_periods, "normal startup");
2312 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2313 assert(sms == sm_NORMAL);
2315 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2317 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2318 (unsigned long)target_max_feedfile_size,
2321 int r= link(feedfile, path_flushing);
2322 if (r) sysfatal("link feedfile %s to flushing file %s",
2323 feedfile, path_flushing);
2326 xunlink(feedfile, "old feedfile link");
2329 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2332 static void statemc_period_poll(void) {
2333 if (!sm_period_counter) return;
2334 sm_period_counter--;
2335 assert(sm_period_counter>=0);
2337 if (sm_period_counter) return;
2340 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2342 case sm_FLUSHFAILED:
2343 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2350 static int inputfile_is_done(InputFile *ipf) {
2352 if (ipf->inprogress) return 0; /* new article in the meantime */
2353 if (ipf->rd) return 0; /* not had EOF */
2357 static void notice_processed(InputFile *ipf, const char *what,
2359 #define RCI_NOTHING(x) /* nothing */
2360 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2361 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2363 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2365 info("processed %s%s read=%d(+%dbl,+%derr)"
2366 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2367 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2370 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2371 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2372 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2373 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2374 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2375 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2381 static void statemc_check_backlog_done(void) {
2382 InputFile *ipf= backlog_input_file;
2383 if (!inputfile_is_done(ipf)) return;
2385 const char *slash= strrchr(ipf->path, '/');
2386 const char *leaf= slash ? slash+1 : ipf->path;
2387 const char *under= strchr(slash, '_');
2388 const char *rest= under ? under+1 : leaf;
2389 if (!strncmp(rest,"backlog",7)) rest += 7;
2390 notice_processed(ipf,"backlog:",rest);
2392 close_input_file(ipf);
2393 if (unlink(ipf->path)) {
2394 if (errno != ENOENT)
2395 sysdie("could not unlink processed backlog file %s", ipf->path);
2396 warn("backlog file %s vanished while we were reading it"
2397 " so we couldn't remove it (but it's done now, anyway)",
2401 backlog_input_file= 0;
2402 search_backlog_file();
2406 static void statemc_check_flushing_done(void) {
2407 InputFile *ipf= flushing_input_file;
2408 if (!inputfile_is_done(ipf)) return;
2410 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2412 notice_processed(ipf,"feedfile",0);
2416 xunlink(path_flushing, "old flushing file");
2418 close_input_file(flushing_input_file);
2419 free(flushing_input_file);
2420 flushing_input_file= 0;
2422 if (sms==sm_SEPARATED) {
2423 notice("flush complete");
2424 SMS(NORMAL, 0, "flush complete");
2425 } else if (sms==sm_DROPPING) {
2426 SMS(DROPPED, 0, "old flush complete");
2427 search_backlog_file();
2428 notice("feed dropped, but will continue until backlog is finished");
2432 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2434 assert(!inputfile_is_done(main_input_file));
2435 statemc_check_flushing_done();
2436 statemc_check_backlog_done();
2437 return OOP_CONTINUE;
2440 static void queue_check_input_done(void) {
2441 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2444 static void statemc_setstate(StateMachineState newsms, int periods,
2445 const char *forlog, const char *why) {
2447 sm_period_counter= periods;
2449 const char *xtra= "";
2452 case sm_FLUSHFAILED:
2453 if (!main_input_file) xtra= "-ABSENT";
2457 xtra= flushing_input_file->rd ? "-1" : "-2";
2463 info("state %s%s[%d] %s",forlog,xtra,periods,why);
2465 info("state %s%s %s",forlog,xtra,why);
2469 /*---------- defer and backlog files ----------*/
2471 static void open_defer(void) {
2476 defer= fopen(path_defer, "a+");
2477 if (!defer) sysfatal("could not open defer file %s", path_defer);
2479 /* truncate away any half-written records */
2481 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2483 if (stab.st_size > LONG_MAX)
2484 die("defer file %s size is far too large", path_defer);
2489 long orgsize= stab.st_size;
2490 long truncto= stab.st_size;
2492 if (!truncto) break; /* was only (if anything) one half-truncated record */
2493 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2494 sysdie("seek in defer file %s while truncating partial", path_defer);
2499 sysdie("failed read from defer file %s", path_defer);
2501 die("defer file %s shrank while we were checking it!", path_defer);
2507 if (stab.st_size != truncto) {
2508 warn("truncating half-record at end of defer file %s -"
2509 " shrinking by %ld bytes from %ld to %ld",
2510 path_defer, orgsize - truncto, orgsize, truncto);
2513 sysfatal("could not flush defer file %s", path_defer);
2514 if (ftruncate(fileno(defer), truncto))
2515 sysdie("could not truncate defer file %s", path_defer);
2518 info("continuing existing defer file %s (%ld bytes)",
2519 path_defer, orgsize);
2521 if (fseek(defer, truncto, SEEK_SET))
2522 sysdie("could not seek to new end of defer file %s", path_defer);
2525 static void close_defer(void) {
2530 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2532 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2535 time_t now= xtime();
2537 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2539 (unsigned long)stab.st_ino);
2540 if (link(path_defer, backlog))
2541 sysfatal("could not install defer file %s as backlog file %s",
2542 path_defer, backlog);
2543 if (unlink(path_defer))
2544 sysdie("could not unlink old defer link %s to backlog file %s",
2545 path_defer, backlog);
2549 if (until_backlog_nextscan < 0 ||
2550 until_backlog_nextscan > backlog_retry_minperiods + 1)
2551 until_backlog_nextscan= backlog_retry_minperiods + 1;
2554 static void poll_backlog_file(void) {
2555 if (until_backlog_nextscan < 0) return;
2556 if (until_backlog_nextscan-- > 0) return;
2557 search_backlog_file();
2560 static void search_backlog_file(void) {
2561 /* returns non-0 iff there are any backlog files */
2566 const char *oldest_path=0;
2567 time_t oldest_mtime=0, now;
2569 if (backlog_input_file) return;
2573 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2577 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2579 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2581 for (i=0; i<gl.gl_pathc; i++) {
2582 const char *path= gl.gl_pathv[i];
2584 if (strchr(path,'#') || strchr(path,'~')) {
2585 debug("backlog file search skipping %s", path);
2588 r= stat(path, &stab);
2590 syswarn("failed to stat backlog file %s", path);
2593 if (!S_ISREG(stab.st_mode)) {
2594 warn("backlog file %s is not a plain file (or link to one)", path);
2597 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2599 oldest_mtime= stab.st_mtime;
2602 case GLOB_NOMATCH: /* fall through */
2605 sysdie("glob expansion of backlog pattern %s gave unexpected"
2606 " nonzero (error?) return value %d", globpat_backlog, r);
2610 debug("backlog scan: none");
2612 if (sms==sm_DROPPED) {
2613 notice("feed dropped and our work is complete");
2615 int r= unlink(path_control);
2616 if (r && errno!=ENOENT)
2617 syswarn("failed to remove control symlink for old feed");
2619 xunlink(path_lock, "lockfile for old feed");
2622 until_backlog_nextscan= backlog_spontrescan_periods;
2627 double age= difftime(now, oldest_mtime);
2628 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2630 if (age_deficiency <= 0) {
2631 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2632 age, age_deficiency, oldest_path);
2634 backlog_input_file= open_input_file(oldest_path);
2635 if (!backlog_input_file) {
2636 warn("backlog file %s vanished as we opened it", oldest_path);
2640 inputfile_reading_start(backlog_input_file);
2641 until_backlog_nextscan= -1;
2645 until_backlog_nextscan= age_deficiency / period_seconds;
2647 if (backlog_spontrescan_periods >= 0 &&
2648 until_backlog_nextscan > backlog_spontrescan_periods)
2649 until_backlog_nextscan= backlog_spontrescan_periods;
2651 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2652 age, age_deficiency, until_backlog_nextscan, oldest_path);
2659 /*========== flushing the feed ==========*/
2661 static pid_t inndcomm_child;
2662 static int inndcomm_sentinel_fd;
2664 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2665 assert(inndcomm_child);
2666 assert(fd == inndcomm_sentinel_fd);
2667 int status= xwaitpid(&inndcomm_child, "inndcomm");
2670 cancel_fd_read_except(fd);
2671 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2672 inndcomm_sentinel_fd= 0;
2674 assert(!flushing_input_file);
2676 if (WIFEXITED(status)) {
2677 switch (WEXITSTATUS(status)) {
2679 case INNDCOMMCHILD_ESTATUS_FAIL:
2682 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2683 notice("feed has been dropped by innd, finishing up");
2684 flushing_input_file= main_input_file;
2685 tailing_queue_readable(flushing_input_file);
2686 /* we probably previously returned EAGAIN from our fake read method
2687 * when in fact we were at EOF, so signal another readable event
2688 * so we actually see the EOF */
2692 if (flushing_input_file) {
2693 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2696 SMS(DROPPED, 0, "feed dropped by innd");
2697 search_backlog_file();
2699 return OOP_CONTINUE;
2703 flushing_input_file= main_input_file;
2704 tailing_queue_readable(flushing_input_file);
2706 main_input_file= open_input_file(feedfile);
2707 if (!main_input_file)
2708 die("flush succeeded but feedfile %s does not exist!", feedfile);
2710 if (flushing_input_file) {
2711 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2714 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2716 return OOP_CONTINUE;
2719 goto unexpected_exitstatus;
2722 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2723 warn("flush timed out trying to talk to innd");
2726 unexpected_exitstatus:
2727 report_child_status("inndcomm child", status);
2731 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2732 return OOP_CONTINUE;
2735 static void inndcommfail(const char *what) {
2736 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2737 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2740 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2743 notice("flushing %s",why);
2745 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2746 assert(!inndcomm_child);
2747 assert(!inndcomm_sentinel_fd);
2749 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2751 inndcomm_child= xfork("inndcomm child");
2753 if (!inndcomm_child) {
2754 const char *flushargv[2]= { sitename, 0 };
2758 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2759 /* parent spots the autoclose of pipefds[1] when we die or exit */
2761 if (simulate_flush>=0) {
2762 warn("SIMULATING flush child status %d", simulate_flush);
2763 if (simulate_flush>128) raise(simulate_flush-128);
2764 else exit(simulate_flush);
2767 alarm(inndcomm_flush_timeout);
2768 r= ICCopen(); if (r) inndcommfail("connect");
2769 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2770 if (!r) exit(0); /* yay! */
2772 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2773 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2774 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2779 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2780 inndcomm_sentinel_fd= pipefds[0];
2781 assert(inndcomm_sentinel_fd);
2782 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2784 SMS(FLUSHING, 0, why);
2787 /*========== main program ==========*/
2789 static void postfork_inputfile(InputFile *ipf) {
2791 xclose(ipf->fd, "(in child) input file ", ipf->path);
2794 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2795 /* we have no stdio streams that are buffered long-term */
2797 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2800 static void postfork(void) {
2801 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2802 sysdie("(in child) failed to reset SIGPIPE");
2804 postfork_inputfile(main_input_file);
2805 postfork_inputfile(flushing_input_file);
2808 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2809 conn_closefd(conn,"(in child) ");
2811 postfork_stdio(defer, "defer file ", path_defer);
2814 typedef struct Every Every;
2816 struct timeval interval;
2821 static void every_schedule(Every *e, struct timeval base);
2823 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
2826 if (!e->fixed_rate) xgettimeofday(&base);
2827 every_schedule(e, base);
2828 return OOP_CONTINUE;
2831 static void every_schedule(Every *e, struct timeval base) {
2832 struct timeval when;
2833 timeradd(&base, &e->interval, &when);
2834 loop->on_time(loop, when, every_happens, e);
2837 static void every(int interval, int fixed_rate, void (*f)(void)) {
2838 Every *e= xmalloc(sizeof(*e));
2839 e->interval.tv_sec= interval;
2840 e->interval.tv_usec= 0;
2841 e->fixed_rate= fixed_rate;
2844 xgettimeofday(&now);
2845 every_schedule(e, now);
2848 static void filepoll(void) {
2849 filemon_callback(main_input_file);
2850 filemon_callback(flushing_input_file);
2853 static char *debug_report_ipf(InputFile *ipf) {
2854 if (!ipf) return xasprintf("none");
2856 const char *slash= strrchr(ipf->path,'/');
2857 const char *path= slash ? slash+1 : ipf->path;
2859 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2861 ipf->inprogress, (long)ipf->offset,
2862 ipf->fd, ipf->rd ? "+" : "");
2865 static void period(void) {
2866 char *dipf_main= debug_report_ipf(main_input_file);
2867 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2868 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2871 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2872 " input_files main:%s old:%s flushing:%s"
2873 " children connecting=%ld inndcomm=%ld"
2875 sms_names[sms], sm_period_counter,
2876 conns.count, queue.count, until_connect,
2877 dipf_main, dipf_flushing, dipf_backlog,
2878 (long)connecting_child, (long)inndcomm_child
2882 free(dipf_flushing);
2885 if (until_connect) until_connect--;
2887 poll_backlog_file();
2888 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2889 statemc_period_poll();
2890 check_assign_articles();
2895 /*========== option parsing ==========*/
2897 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2898 static void vbadusage(const char *fmt, va_list al) {
2899 char *m= xvasprintf(fmt,al);
2900 fprintf(stderr, "bad usage: %s\n"
2901 "say --help for help, or read the manpage\n",
2904 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2908 /*---------- generic option parser ----------*/
2910 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2911 static void badusage(const char *fmt, ...) {
2918 of_seconds= 001000u,
2919 of_boolean= 002000u,
2922 typedef struct Option Option;
2923 typedef void OptionParser(const Option*, const char *val);
2927 const char *lng, *formarg;
2933 static void parse_options(const Option *options, char ***argvp) {
2934 /* on return *argvp is first non-option arg; argc is not updated */
2937 const char *arg= *++(*argvp);
2939 if (*arg != '-') break;
2940 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2942 while ((a= *++arg)) {
2946 char *equals= strchr(arg,'=');
2947 int len= equals ? (equals - arg) : strlen(arg);
2948 for (o=options; o->shrt || o->lng; o++)
2949 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2951 badusage("unknown long option --%s",arg);
2954 if (equals) badusage("option --%s does not take a value",o->lng);
2956 } else if (equals) {
2960 if (!arg) badusage("option --%s needs a value for %s",
2961 o->lng, o->formarg);
2964 break; /* eaten the whole argument now */
2966 for (o=options; o->shrt || o->lng; o++)
2969 badusage("unknown short option -%c",a);
2976 if (!arg) badusage("option -%c needs a value for %s",
2977 o->shrt, o->formarg);
2980 break; /* eaten the whole argument now */
2986 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
2988 static void print_options(const Option *options, FILE *f) {
2990 for (o=options; o->shrt || o->lng; o++) {
2991 char shrt[2] = { o->shrt, 0 };
2992 char *optspec= xasprintf("%s%s%s%s%s",
2993 o->shrt ? "-" : "", shrt,
2994 o->shrt && o->lng ? "|" : "",
2995 DELIMPERHAPS("--", o->lng));
2996 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
3001 /*---------- specific option types ----------*/
3003 static void op_integer(const Option *o, const char *val) {
3006 unsigned long ul= strtoul(val,&ep,10);
3007 if (*ep || ep==val || errno || ul>INT_MAX)
3008 badusage("bad integer value for %s",o->lng);
3009 int *store= o->store;
3013 static void op_double(const Option *o, const char *val) {
3014 int *store= o->store;
3017 *store= strtod(val, &ep);
3018 if (*ep || ep==val || errno)
3019 badusage("bad floating point value for %s",o->lng);
3022 static void op_string(const Option *o, const char *val) {
3023 const char **store= o->store;
3027 static void op_seconds(const Option *o, const char *val) {
3028 int *store= o->store;
3032 double v= strtod(val,&ep);
3033 if (ep==val) badusage("bad time/duration value for %s",o->lng);
3035 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
3036 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
3037 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
3038 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
3039 else if (!strcmp(ep,"das")) unit= 10;
3040 else if (!strcmp(ep,"hs")) unit= 100;
3041 else if (!strcmp(ep,"ks")) unit= 1000;
3042 else if (!strcmp(ep,"Ms")) unit= 1000000;
3043 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
3047 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
3051 static void op_setint(const Option *o, const char *val) {
3052 int *store= o->store;
3056 /*---------- specific options ----------*/
3058 static void help(const Option *o, const char *val);
3060 static const Option innduct_options[]= {
3061 {'f',"feedfile", "F", &feedfile, op_string },
3062 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
3063 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
3064 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
3065 {0,"inndconf", "F", &inndconffile, op_string },
3066 {'P',"port", "PORT", &port, op_integer },
3067 {0,"help", 0, 0, help },
3069 {0,"max-connections", "N", &max_connections, op_integer },
3070 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
3071 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
3072 {0,"period-interval", "TIME", &period_seconds, op_seconds },
3074 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
3075 {0,"stuck-flush-timeout","TIME", &inndcomm_flush_timeout, op_seconds },
3077 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
3078 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
3080 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
3081 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
3082 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3083 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3084 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
3085 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
3087 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
3088 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
3093 static void printusage(FILE *f) {
3094 fputs("usage: innduct [options] site [fqdn]\n"
3095 "available options are:\n", f);
3096 print_options(innduct_options, f);
3099 static void help(const Option *o, const char *val) {
3101 if (ferror(stdout) || fflush(stdout)) {
3102 perror("innduct: writing help");
3108 static void convert_to_periods_rndup(int *store) {
3109 *store += period_seconds-1;
3110 *store /= period_seconds;
3113 int main(int argc, char **argv) {
3119 parse_options(innduct_options, &argv);
3124 if (!sitename) badusage("need site name argument");
3125 remote_host= *argv++;
3126 if (*argv) badusage("too many non-option arguments");
3130 if (!remote_host) remote_host= sitename;
3132 if (nocheck_thresh < 0 || nocheck_thresh > 100)
3133 badusage("nocheck threshold percentage must be between 0..100");
3134 nocheck_thresh *= 0.01;
3136 if (nocheck_decay < 0.1)
3137 badusage("nocheck decay articles must be at least 0.1");
3138 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3140 convert_to_periods_rndup(&reconnect_delay_periods);
3141 convert_to_periods_rndup(&flushfail_retry_periods);
3142 convert_to_periods_rndup(&backlog_retry_minperiods);
3143 convert_to_periods_rndup(&backlog_spontrescan_periods);
3144 convert_to_periods_rndup(&spontaneous_flush_periods);
3145 convert_to_periods_rndup(&need_activity_periods);
3147 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3148 badusage("bad input data ratio must be between 0..100");
3149 max_bad_data_ratio *= 0.01;
3152 innconf_read(inndconffile);
3153 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3154 } else if (!feedfile[0]) {
3155 badusage("feed filename must be nonempty");
3156 } else if (feedfile[strlen(feedfile)-1]=='/') {
3157 feedfile= xasprintf("%s%s",feedfile,sitename);
3160 const char *feedfile_forbidden= "?*[~#";
3162 while ((c= *feedfile_forbidden++))
3163 if (strchr(feedfile, c))
3164 badusage("feed filename may not contain metacharacter %c",c);
3168 path_lock= xasprintf("%s_lock", feedfile);
3169 path_flushing= xasprintf("%s_flushing", feedfile);
3170 path_defer= xasprintf("%s_defer", feedfile);
3171 path_control= xasprintf("%s_control", feedfile);
3172 globpat_backlog= xasprintf("%s_backlog*", feedfile);
3174 oop_source_sys *sysloop= oop_sys_new();
3175 if (!sysloop) sysdie("could not create liboop event loop");
3176 loop= (oop_source*)sysloop;
3178 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3179 sysdie("could not ignore SIGPIPE");
3184 if (become_daemon) {
3186 for (i=3; i<255; i++)
3187 /* do this now before we open syslog, etc. */
3189 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3191 int null= open("/dev/null",O_RDWR);
3192 if (null<0) sysfatal("failed to open /dev/null");
3196 xclose(null, "/dev/null original fd",0);
3198 pid_t child1= xfork("daemonise first fork");
3199 if (child1) _exit(0);
3201 pid_t sid= setsid();
3202 if (sid != child1) sysfatal("setsid failed");
3204 pid_t child2= xfork("daemonise second fork");
3205 if (child2) _exit(0);
3209 if (self_pid==-1) sysdie("getpid");
3220 if (!filemon_method_init()) {
3221 warn("no file monitoring available, polling");
3222 every(5,0,filepoll);
3225 every(period_seconds,1,period);
3231 void *r= oop_sys_run(sysloop);
3232 assert(r == OOP_ERROR);
3233 sysdie("event loop failed");