5 [740] <sit> warning: corrupted file: /home/ian/things/Innfeed/inn2-2.4.5/fee, offset 349: line partially blanked: in ` @050000002D130000006A0000000000000000@ <mi'..
9 * some per-conn info thing for control
12 * - actually do something with readable on control master
13 * - option for realsockdir
14 * - option for filepoll
15 * - option for no inotify
16 * - manpage: document control master stuff
17 * - manpage: innconf is used for communicating with innd
19 * build-lfs/backends/innduct --no-daemon -f `pwd`/fee sit dom
23 * Newsfeeds file entries should look like this:
24 * host.name.of.site[/exclude,exclude,...]\
25 * :pattern,pattern...[/distribution,distribution...]\
29 * sitename[/exclude,exclude,...]\
30 * :pattern,pattern...[/distribution,distribution...]\
36 * or might be blanked out
37 * <spc><spc><spc><spc>....
39 * F site.name main feed file
40 * opened/created, then written, by innd
43 * tokens blanked out by duct when processed
44 * site.name_lock lock preventing multiple ducts
45 * to hold lock must open,F_SETLK[W]
46 * and then stat to check that locked file
47 * still has name site.name_lock
48 * holder of this lock is "duct"
49 * (only) lockholder may remove the lockfile
50 * D site.name_flushing temporary feed file during flush (or crash)
51 * hardlink created by duct
53 * site.name_defer 431'd articles, still being written,
54 * created, written, used by duct
56 * site.name_backlog.<date>.<inum>
57 * 431'd articles, ready for innxmit or duct
58 * created (link/mv) by duct
59 * site.name_backlog<anything-else> (where <anything-else> does not
60 * contain '#' or '~') eg
61 * site.name_backlog.manual
62 * anything the sysadmin likes (eg, feed files
63 * from old feeds to be merged into this one)
64 * created (link/mv) by admin
65 * may be symlinks (in which case links
66 * may be written through, but only links
69 * It is safe to remove backlog files manually,
70 * if it's desired to throw away the backlog.
72 * Backlog files are also processed by innduct. We find the oldest
73 * backlog file which is at least a certain amount old, and feed it
74 * back into our processing. When every article in it has been read
75 * and processed, we unlink it and look for another backlog file.
77 * If we don't have a backlog file that we're reading, we close the
78 * defer file that we're writing and make it into a backlog file at
79 * the first convenient opportunity.
90 | | <----------------<---------------------------------'|
96 | F: innd writing, duct reading |
99 | | duct decides time to flush |
100 | | duct makes hardlink |
102 | V <------------------------'|
104 | F == D: innd writing, duct reading both exist |
107 | | <-----------<-------------<--'|
108 | | open D F ENOENT |
111 | V <---------------------. |
114 | D: innd writing, duct reading; or ENOENT | |
116 | | duct requests flush of feed | |
117 | | (others can too, harmlessly) | |
121 | D: innd flushing, duct; or ENOENT | |
123 | | inndcomm flush fails | |
124 | |`-------------------------->------------------' |
126 | | inndcomm reports no such site |
127 | |`---------------------------------------------------- | -.
129 | | innd finishes writing D, creates F | |
130 | | inndcomm reports flush successful | |
133 | Separated <----------------' |
134 | F: innd writing F!=D /
135 | D: duct reading; or ENOENT both exist /
137 | | duct gets to the end of D /
138 | | duct opens F too /
141 | F: innd writing, duct reading |
142 | D: duct finishing V
144 | | duct finishes processing D F: ENOENT
145 | V duct unlinks D D: duct reading
147 `--<--' | duct finishes
157 "duct reading" means innduct is reading the file but also
158 overwriting processed tokens.
162 * rune for printing diagrams:
164 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
169 /*============================== PROGRAM ==============================*/
171 #define _GNU_SOURCE 1
177 #include "inndcomm.h"
179 #include "inn/list.h"
180 #include "inn/innconf.h"
183 #include <sys/types.h>
184 #include <sys/wait.h>
185 #include <sys/stat.h>
186 #include <sys/socket.h>
205 #include <oop-read.h>
207 /*----- general definitions, probably best not changed -----*/
209 #define CONNCHILD_ESTATUS_STREAM 24
210 #define CONNCHILD_ESTATUS_NOSTREAM 25
212 #define INNDCOMMCHILD_ESTATUS_FAIL 26
213 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
215 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
216 #define MAX_CONTROL_COMMAND 1000
218 #define VA va_list al; va_start(al,fmt)
219 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
220 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
222 /*----- doubly linked lists -----*/
224 #define ISNODE(T) struct node list_node
227 union { struct list li; T *for_type; } u; \
231 #define NODE(n) (assert((void*)&(n)->list_node == (n)), &(n)->list_node)
233 #define LIST_CHECKCANHAVENODE(l,n) \
234 ((void)((n) == ((l).u.for_type))) /* just for the type check */
236 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
237 ( LIST_CHECKCANHAVENODE(l,n), \
238 list_addsomehow(&(l).u.li, NODE((n))), \
242 #define LIST_REMSOMEHOW(l,list_remsomehow) \
243 ( (typeof((l).u.for_type)) \
246 list_remsomehow(&(l).u.li) ) \
252 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
253 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
254 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
255 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
257 #define LIST_INIT(l) ((l).count=0, list_new(&(l).u.li))
258 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
259 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
260 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
262 #define LIST_REMOVE(l,n) \
263 ( LIST_CHECKCANHAVENODE(l,n), \
264 list_remove(NODE((n))), \
268 #define LIST_INSERT(l,n,pred) \
269 ( LIST_CHECKCANHAVENODE(l,n), \
270 LIST_CHECKCANHAVENODE(l,pred), \
271 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
275 /*----- type predeclarations -----*/
277 typedef struct Conn Conn;
278 typedef struct Article Article;
279 typedef struct InputFile InputFile;
280 typedef struct XmitDetails XmitDetails;
281 typedef struct Filemon_Perfile Filemon_Perfile;
282 typedef enum StateMachineState StateMachineState;
287 /*----- function predeclarations -----*/
289 static void conn_maybe_write(Conn *conn);
290 static void conn_make_some_xmits(Conn *conn);
291 static void *conn_write_some_xmits(Conn *conn);
293 static void xmit_free(XmitDetails *d);
295 #define SMS(newstate, periods, why) \
296 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
297 static void statemc_setstate(StateMachineState newsms, int periods,
298 const char *forlog, const char *why);
300 static void statemc_start_flush(const char *why); /* Normal => Flushing */
301 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
303 static void article_done(Conn *conn, Article *art, int whichcount);
305 static void check_assign_articles(void);
306 static void queue_check_input_done(void);
308 static void statemc_check_flushing_done(void);
309 static void statemc_check_backlog_done(void);
311 static void postfork(void);
312 static void period(void);
314 static void open_defer(void);
315 static void close_defer(void);
316 static void search_backlog_file(void);
318 static void inputfile_reading_start(InputFile *ipf);
319 static void inputfile_reading_stop(InputFile *ipf);
321 static void filemon_start(InputFile *ipf);
322 static void filemon_stop(InputFile *ipf);
323 static void filemon_callback(InputFile *ipf);
325 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
326 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
328 static const oop_rd_style peer_rd_style;
329 static oop_rd_call peer_rd_err, peer_rd_ok;
331 /*----- configuration options -----*/
332 /* when changing defaults, remember to update the manpage */
334 static const char *sitename, *remote_host;
335 static const char *feedfile, *realsockdir="/tmp/innduct.control";
336 static int quiet_multiple=0;
337 static int become_daemon=1;
338 static int try_stream=1;
340 static const char *inndconffile;
342 static int max_connections=10;
343 static int max_queue_per_conn=200;
344 static int target_max_feedfile_size=100000;
345 static int period_seconds=60;
347 static int connection_setup_timeout=200;
348 static int inndcomm_flush_timeout=100;
350 static double nocheck_thresh= 95.0; /* converted from percentage by main */
351 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
353 /* all these are initialised to seconds, and converted to periods in main */
354 static int reconnect_delay_periods=1000;
355 static int flushfail_retry_periods=1000;
356 static int backlog_retry_minperiods=50;
357 static int backlog_spontrescan_periods=300;
358 static int spontaneous_flush_periods=100000;
359 static int need_activity_periods=1000;
361 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
362 static int max_bad_data_initial= 30;
363 /* in one corrupt 4096-byte block the number of newlines has
364 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
367 /*----- statistics -----*/
369 typedef enum { /* in queue in conn->sent */
370 art_Unchecked, /* not checked, not sent checking */
371 art_Wanted, /* checked, wanted sent body as requested */
372 art_Unsolicited, /* - sent body without check */
376 #define RESULT_COUNTS(RCS,RCN) \
385 #define RCI_TRIPLE_FMT_BASE "%d (id=%d,bod=%d,nc=%d)"
386 #define RCI_TRIPLE_VALS_BASE(counts,x) \
387 counts[art_Unchecked] x \
388 + counts[art_Wanted] x \
389 + counts[art_Unsolicited] x, \
390 counts[art_Unchecked] x \
391 , counts[art_Wanted] x \
392 , counts[art_Unsolicited] x
395 #define RC_INDEX(x) RC_##x,
396 RESULT_COUNTS(RC_INDEX, RC_INDEX)
401 /*----- transmission buffers -----*/
406 xk_Malloc, xk_Const, xk_Artdata
418 /*----- core operational data structure types -----*/
421 /* This is also an instance of struct oop_readable */
422 struct oop_readable readable; /* first */
423 oop_readable_call *readable_callback;
424 void *readable_callback_user;
427 Filemon_Perfile *filemon;
429 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
430 long inprogress; /* no. of articles read but not processed */
434 int counts[art_MaxState][RCI_max];
435 int readcount_ok, readcount_blank, readcount_err;
450 #define SMS_LIST(X) \
458 enum StateMachineState {
459 #define SMS_DEF_ENUM(s) sm_##s,
460 SMS_LIST(SMS_DEF_ENUM)
463 static const char *sms_names[]= {
464 #define SMS_DEF_NAME(s) #s ,
465 SMS_LIST(SMS_DEF_NAME)
471 int fd; /* may be 0, meaning closed (during construction/destruction) */
472 oop_read *rd; /* likewise */
473 int max_queue, stream, quitting;
474 int since_activity; /* periods */
475 ArticleList waiting; /* not yet told peer */
476 ArticleList priority; /* peer says send it now */
477 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
478 struct iovec xmit[CONNIOVS];
479 XmitDetails xmitd[CONNIOVS];
484 /*----- general operational variables -----*/
486 /* main initialises */
487 static oop_source *loop;
488 static ConnList conns;
489 static ArticleList queue;
490 static char *path_lock, *path_flushing, *path_defer, *path_control;
491 static char *globpat_backlog;
492 static pid_t self_pid;
494 /* statemc_init initialises */
495 static StateMachineState sms;
497 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
498 static int sm_period_counter;
500 /* initialisation to 0 is good */
501 static int until_connect, until_backlog_nextscan;
502 static double accept_proportion;
503 static int nocheck, nocheck_reported;
505 /* for simulation, debugging, etc. */
506 int simulate_flush= -1;
508 /*========== logging ==========*/
510 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
511 static void logcore(int sysloglevel, const char *fmt, ...) {
514 vsyslog(sysloglevel,fmt,al);
516 if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
517 vfprintf(stderr,fmt,al);
523 static void logv(int sysloglevel, const char *pfx, int errnoval,
524 const char *fmt, va_list al) PRINTF(5,0);
525 static void logv(int sysloglevel, const char *pfx, int errnoval,
526 const char *fmt, va_list al) {
527 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
528 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
529 msgbuf[sizeof(msgbuf)-1]= 0;
531 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
532 sysloglevel= LOG_ERR; /* run by wrong user, probably */
534 logcore(sysloglevel, "<%s>%s: %s%s%s",
535 sitename, pfx, msgbuf,
536 errnoval>=0 ? ": " : "",
537 errnoval>=0 ? strerror(errnoval) : "");
540 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
541 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
542 static void fn(const char *fmt, ...) { \
544 logv(sysloglevel, pfx, err, fmt, al); \
548 #define logwrap(fn, pfx, sysloglevel, err) \
549 static void fn(const char *fmt, ...) PRINTF(1,2); \
550 static void fn(const char *fmt, ...) { \
552 logv(sysloglevel, pfx, err, fmt, al); \
556 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
557 diewrap(die, " critical", LOG_CRIT, -1, 16);
559 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
560 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
562 logwrap(syswarn, " warning", LOG_WARNING, errno);
563 logwrap(warn, " warning", LOG_WARNING, -1);
565 logwrap(notice, " notice", LOG_NOTICE, -1);
566 logwrap(info, " info", LOG_INFO, -1);
567 logwrap(debug, " debug", LOG_DEBUG, -1);
570 /*========== utility functions etc. ==========*/
572 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
573 static char *xvasprintf(const char *fmt, va_list al) {
575 int rc= vasprintf(&str,fmt,al);
576 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
579 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
580 static char *xasprintf(const char *fmt, ...) {
582 char *str= xvasprintf(fmt,al);
587 static int close_perhaps(int *fd) {
588 if (*fd <= 0) return 0;
593 static void xclose(int fd, const char *what, const char *what2) {
595 if (r) sysdie("close %s%s",what,what2?what2:"");
597 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
598 if (*fd <= 0) return;
599 xclose(*fd,what,what2);
603 static pid_t xfork(const char *what) {
607 if (child==-1) sysfatal("cannot fork for %s",what);
608 debug("forked %s %ld", what, (unsigned long)child);
609 if (!child) postfork();
613 static void on_fd_read_except(int fd, oop_call_fd callback) {
614 loop->on_fd(loop, fd, OOP_READ, callback, 0);
615 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
617 static void cancel_fd_read_except(int fd) {
618 loop->cancel_fd(loop, fd, OOP_READ);
619 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
622 static void report_child_status(const char *what, int status) {
623 if (WIFEXITED(status)) {
624 int es= WEXITSTATUS(status);
626 warn("%s: child died with error exit status %d", what, es);
627 } else if (WIFSIGNALED(status)) {
628 int sig= WTERMSIG(status);
629 const char *sigstr= strsignal(sig);
630 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
632 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
634 warn("%s: child died due to unknown fatal signal %d%s",
635 what, sig, coredump);
637 warn("%s: child died with unknown wait status %d", what,status);
641 static int xwaitpid(pid_t *pid, const char *what) {
644 int r= kill(*pid, SIGKILL);
645 if (r) sysdie("cannot kill %s child", what);
647 pid_t got= waitpid(*pid, &status, 0);
648 if (got==-1) sysdie("cannot reap %s child", what);
649 if (got==0) die("cannot reap %s child", what);
656 static void xunlink(const char *path, const char *what) {
658 if (r) sysdie("can't unlink %s %s", path, what);
661 static time_t xtime(void) {
663 if (now==-1) sysdie("time(2) failed");
667 static void xgettimeofday(struct timeval *tv_r) {
668 int r= gettimeofday(tv_r,0);
669 if (r) sysdie("gettimeofday(2) failed");
672 static void xsetnonblock(int fd, int nonblocking) {
673 int errnoval= oop_fd_nonblock(fd, nonblocking);
674 if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
677 static void check_isreg(const struct stat *stab, const char *path,
679 if (!S_ISREG(stab->st_mode))
680 die("%s %s not a plain file (mode 0%lo)",
681 what, path, (unsigned long)stab->st_mode);
684 static void xfstat(int fd, struct stat *stab_r, const char *what) {
685 int r= fstat(fd, stab_r);
686 if (r) sysdie("could not fstat %s", what);
689 static void xfstat_isreg(int fd, struct stat *stab_r,
690 const char *path, const char *what) {
691 xfstat(fd, stab_r, what);
692 check_isreg(stab_r, path, what);
695 static void xlstat_isreg(const char *path, struct stat *stab,
696 int *enoent_r /* 0 means ENOENT is fatal */,
698 int r= lstat(path, stab);
700 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
701 sysdie("could not lstat %s %s", what, path);
703 if (enoent_r) *enoent_r= 0;
704 check_isreg(stab, path, what);
707 static int samefile(const struct stat *a, const struct stat *b) {
708 assert(S_ISREG(a->st_mode));
709 assert(S_ISREG(b->st_mode));
710 return (a->st_ino == b->st_ino &&
711 a->st_dev == b->st_dev);
714 static char *sanitise(const char *input) {
715 static char sanibuf[100]; /* returns pointer to this buffer! */
717 const char *p= input;
721 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
723 if (!c) { *q++= '\''; *q=0; break; }
724 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
725 sprintf(q,"\\x%02x",c);
731 static int isewouldblock(int errnoval) {
732 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
736 /*========== command and control connections ==========*/
738 static int control_master;
740 typedef struct ControlConn ControlConn;
742 void (*destroy)(ControlConn*);
748 struct sockaddr_un un;
753 static const oop_rd_style control_rd_style= {
754 OOP_RD_DELIM_STRIP, '\n',
756 OOP_RD_SHORTREC_FORBID
759 static void control_destroy(ControlConn *cc) {
763 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
764 if (ferror(cc->out) | fflush(cc->out)) {
765 info("CTRL%d write error %s", cc->fd, strerror(errno));
770 static void control_prompt(ControlConn *cc /* may destroy*/) {
771 fprintf(cc->out, "%s| ", sitename);
772 control_checkouterr(cc);
775 typedef struct ControlCommand ControlCommand;
776 struct ControlCommand {
778 void (*f)(ControlConn *cc, const ControlCommand *ccmd,
779 const char *arg, size_t argsz);
784 static const ControlCommand control_commands[];
787 static void ccmd_##wh(ControlConn *cc, const ControlCommand *c, \
788 const char *arg, size_t argsz)
791 fputs("commands:\n", cc->out);
792 const ControlCommand *ccmd;
793 for (ccmd=control_commands; ccmd->cmd; ccmd++)
794 fprintf(cc->out, " %s\n", ccmd->cmd);
797 CCMD(period) { period(); }
798 CCMD(setintarg) { *(int*)c->xdata= atoi(arg); }
799 CCMD(setint) { *(int*)c->xdata= c->xval; }
801 static const ControlCommand control_commands[]= {
803 { "p", ccmd_period },
804 { "pretend flush", ccmd_setintarg, &simulate_flush },
805 { "poke sm", ccmd_setint, &sm_period_counter, 1 },
806 { "poke conn", ccmd_setint, &until_connect, 0 },
807 { "poke blscan", ccmd_setint, &until_backlog_nextscan, 0 },
808 { "wedge blscan", ccmd_setint, &until_backlog_nextscan, -1 },
812 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
813 const char *errmsg, int errnoval,
814 const char *data, size_t recsz, void *cc_v) {
815 ControlConn *cc= cc_v;
818 info("CTRL%d closed", cc->fd);
823 if (recsz == 0) goto prompt;
825 const ControlCommand *ccmd;
826 for (ccmd=control_commands; ccmd->cmd; ccmd++) {
827 int l= strlen(ccmd->cmd);
828 if (recsz < l) continue;
829 if (recsz > l && data[l] != ' ') continue;
830 if (memcmp(data, ccmd->cmd, l)) continue;
832 int argl= (int)recsz - (l+1);
833 ccmd->f(cc, ccmd, argl>=0 ? data+l+1 : 0, argl);
837 fputs("unknown command; h for help\n", cc->out);
844 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
845 const char *errmsg, int errnoval,
846 const char *data, size_t recsz, void *cc_v) {
847 ControlConn *cc= cc_v;
849 info("CTRL%d read error %s", cc->fd, errmsg);
854 static int control_conn_startup(ControlConn *cc /* may destroy*/,
856 cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
857 if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
859 int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
862 if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
864 info("CTRL%d %s ready", cc->fd, how);
869 static void control_stdio_destroy(ControlConn *cc) {
871 oop_rd_cancel(cc->rd);
872 errno= oop_rd_delete_tidy(cc->rd);
873 if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
878 static void control_stdio(void) {
879 ControlConn *cc= xmalloc(sizeof(*cc));
880 memset(cc,0,sizeof(*cc));
881 cc->destroy= control_stdio_destroy;
885 int r= control_conn_startup(cc,"stdio");
886 if (r) cc->destroy(cc);
889 static void control_accepted_destroy(ControlConn *cc) {
891 oop_rd_cancel(cc->rd);
892 oop_rd_delete_kill(cc->rd);
894 if (cc->out) { fclose(cc->out); cc->fd=0; }
895 close_perhaps(&cc->fd);
899 static void *control_master_readable(oop_source *lp, int master,
900 oop_event ev, void *u) {
901 ControlConn *cc= xmalloc(sizeof(*cc));
902 memset(cc,0,sizeof(*cc));
903 cc->destroy= control_accepted_destroy;
905 cc->salen= sizeof(cc->sa);
906 cc->fd= accept(master, &cc->sa.sa, &cc->salen);
907 if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
909 cc->out= fdopen(cc->fd, "w");
910 if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
912 int r= control_conn_startup(cc, "accepted");
922 #define NOCONTROL(...) do{ \
923 syswarn("no control socket, because failed to " __VA_ARGS__); \
927 static void control_init(void) {
932 struct sockaddr_un un;
935 memset(&sa,0,sizeof(sa));
936 int maxlen= sizeof(sa.un.sun_path);
938 int reallen= readlink(path_control, sa.un.sun_path, maxlen);
941 NOCONTROL("readlink control socket symlink path %s", path_control);
943 if (reallen >= maxlen) {
944 debug("control socket symlink path too long (r=%d)",reallen);
945 xunlink(path_control, "old (overlong) control socket symlink");
951 int r= lstat(realsockdir,&stab);
953 if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
955 r= mkdir(realsockdir, 0700);
956 if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
959 uid_t self= geteuid();
960 if (!S_ISDIR(stab.st_mode) ||
961 stab.st_uid != self ||
962 stab.st_mode & 0077) {
963 warn("no control socket, because real socket directory"
964 " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
965 !!S_ISDIR(stab.st_mode),
966 (unsigned long)stab.st_uid, (unsigned long)self,
967 (unsigned long)stab.st_mode & 0777UL);
972 real= xasprintf("%s/s%lx.%lx", realsockdir,
973 (unsigned long)xtime(), (unsigned long)self_pid);
974 int reallen= strlen(real);
976 if (reallen >= maxlen) {
977 warn("no control socket, because tmpnam gave overly-long path"
981 r= symlink(real, path_control);
982 if (r) NOCONTROL("make control socket path %s a symlink to real"
983 " socket path %s", path_control, real);
984 memcpy(sa.un.sun_path, real, reallen);
987 int r= unlink(sa.un.sun_path);
988 if (r && errno!=ENOENT)
989 NOCONTROL("remove old real socket %s", sa.un.sun_path);
991 control_master= socket(PF_UNIX, SOCK_STREAM, 0);
992 if (control_master<0) NOCONTROL("create new control socket");
994 sa.un.sun_family= AF_UNIX;
995 int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
996 r= bind(control_master, &sa.sa, sl);
997 if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
999 r= listen(control_master, 5);
1000 if (r) NOCONTROL("listen");
1002 xsetnonblock(control_master, 1);
1004 loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
1005 info("control socket ok, real path %s", sa.un.sun_path);
1011 xclose_perhaps(&control_master, "control master",0);
1015 /*========== management of connections ==========*/
1017 static void conn_closefd(Conn *conn, const char *msgprefix) {
1018 int r= close_perhaps(&conn->fd);
1019 if (r) info("C%d %serror closing socket: %s",
1020 conn->fd, msgprefix, strerror(errno));
1023 static void conn_dispose(Conn *conn) {
1026 oop_rd_cancel(conn->rd);
1027 oop_rd_delete_kill(conn->rd);
1031 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1032 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
1034 conn_closefd(conn,"");
1036 until_connect= reconnect_delay_periods;
1039 static void *conn_exception(oop_source *lp, int fd,
1040 oop_event ev, void *conn_v) {
1043 assert(fd == conn->fd);
1044 assert(ev == OOP_EXCEPTION);
1045 int r= read(conn->fd, &ch, 1);
1046 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1047 else connfail(conn,"exceptional condition on socket (peer sent urgent"
1048 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1049 return OOP_CONTINUE;
1052 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1053 int requeue[art_MaxState];
1054 memset(requeue,0,sizeof(requeue));
1057 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1058 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1059 while ((art= LIST_REMHEAD(conn->sent))) {
1060 requeue[art->state]++;
1061 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1062 LIST_ADDTAIL(queue,art);
1067 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1070 char *m= xvasprintf(fmt,al);
1071 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1072 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1075 LIST_REMOVE(conns,conn);
1077 check_assign_articles();
1080 static void connfail(Conn *conn, const char *fmt, ...) {
1083 vconnfail(conn,fmt,al);
1087 static void check_idle_conns(void) {
1089 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
1090 conn->since_activity++;
1092 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
1093 if (conn->since_activity <= need_activity_periods) continue;
1095 /* We need to shut this down */
1097 connfail(conn,"timed out waiting for response to QUIT");
1098 else if (conn->sent.count)
1099 connfail(conn,"timed out waiting for responses");
1100 else if (conn->waiting.count || conn->priority.count)
1101 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1102 else if (conn->xmitu)
1103 connfail(conn,"peer has been sending responses"
1104 " before receiving our commands!");
1106 static const char quitcmd[]= "QUIT\r\n";
1107 int todo= sizeof(quitcmd)-1;
1108 const char *p= quitcmd;
1110 int r= write(conn->fd, p, todo);
1112 if (isewouldblock(errno))
1113 connfail(conn, "blocked writing QUIT to idle connection");
1115 connfail(conn, "failed to write QUIT to idle connection: %s",
1123 conn->since_activity= 0;
1124 debug("C%d is idle, quitting", conn->fd);
1133 /*---------- making new connections ----------*/
1135 static pid_t connecting_child;
1136 static int connecting_fdpass_sock;
1138 static void connect_attempt_discard(void) {
1139 if (connecting_child) {
1140 int status= xwaitpid(&connecting_child, "connect");
1141 if (!(WIFEXITED(status) ||
1142 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1143 report_child_status("connect", status);
1145 if (connecting_fdpass_sock) {
1146 cancel_fd_read_except(connecting_fdpass_sock);
1147 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1151 #define PREP_DECL_MSG_CMSG(msg) \
1153 struct iovec msgiov; \
1154 msgiov.iov_base= &msgbyte; \
1155 msgiov.iov_len= 1; \
1156 struct msghdr msg; \
1157 memset(&msg,0,sizeof(msg)); \
1158 char msg##cbuf[CMSG_SPACE(sizeof(int))]; \
1159 msg.msg_iov= &msgiov; \
1160 msg.msg_iovlen= 1; \
1161 msg.msg_control= msg##cbuf; \
1162 msg.msg_controllen= sizeof(msg##cbuf);
1164 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1167 assert(fd == connecting_fdpass_sock);
1169 PREP_DECL_MSG_CMSG(msg);
1171 ssize_t rs= recvmsg(fd, &msg, 0);
1173 if (isewouldblock(errno)) return OOP_CONTINUE;
1174 syswarn("failed to read socket from connecting child");
1178 conn= xmalloc(sizeof(*conn));
1179 memset(conn,0,sizeof(*conn));
1180 LIST_INIT(conn->waiting);
1181 LIST_INIT(conn->priority);
1182 LIST_INIT(conn->sent);
1184 struct cmsghdr *h= 0;
1185 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1187 int status= xwaitpid(&connecting_child, "connect child (broken)");
1189 if (WIFEXITED(status)) {
1190 if (WEXITSTATUS(status) != 0 &&
1191 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1192 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1193 /* child already reported the problem */;
1195 if (e == OOP_EXCEPTION)
1196 warn("connect: connection child exited code %d but"
1197 " unexpected exception on fdpass socket",
1198 WEXITSTATUS(status));
1200 warn("connect: connection child exited code %d but"
1202 WEXITSTATUS(status), (int)rs);
1204 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1205 warn("connect: connection attempt timed out");
1207 report_child_status("connect", status);
1212 #define CHK(field, val) \
1213 if (h->cmsg_##field != val) { \
1214 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1215 h->cmsg_##field, val); \
1218 CHK(level, SOL_SOCKET);
1219 CHK(type, SCM_RIGHTS);
1220 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1223 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1225 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1228 pid_t got= waitpid(connecting_child, &status, 0);
1229 if (got==-1) sysdie("connect: real wait for child");
1230 assert(got == connecting_child);
1231 connecting_child= 0;
1233 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1234 int es= WEXITSTATUS(status);
1236 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1237 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1239 fatal("connect: child gave unexpected exit status %d", es);
1243 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1245 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1246 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1247 if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1248 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1250 &peer_rd_err, conn);
1251 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1253 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1254 LIST_ADDHEAD(conns, conn);
1256 connect_attempt_discard();
1257 check_assign_articles();
1258 return OOP_CONTINUE;
1262 connect_attempt_discard();
1263 return OOP_CONTINUE;
1266 static int allow_connect_start(void) {
1267 return conns.count < max_connections
1268 && !connecting_child
1272 static void connect_start(void) {
1273 assert(!connecting_child);
1274 assert(!connecting_fdpass_sock);
1276 info("starting connection attempt");
1279 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1280 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1282 connecting_child= xfork("connection");
1284 if (!connecting_child) {
1285 FILE *cn_from, *cn_to;
1286 char buf[NNTP_STRLEN+100];
1287 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1289 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1291 alarm(connection_setup_timeout);
1292 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1296 unsigned char c= buf[l-1];
1297 if (!isspace(c)) break;
1298 if (c=='\n' || c=='\r') stripped=1;
1302 sysfatal("connect: connection attempt failed");
1305 fatal("connect: %s: %s", stripped ? "rejected" : "failed",
1309 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1310 sysfatal("connect: authentication failed");
1312 if (fputs("MODE STREAM\r\n", cn_to)==EOF ||
1314 sysfatal("connect: could not send MODE STREAM");
1315 buf[sizeof(buf)-1]= 0;
1316 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1317 if (ferror(cn_from))
1318 sysfatal("connect: could not read response to MODE STREAM");
1320 fatal("connect: connection close in response to MODE STREAM");
1325 fatal("connect: response to MODE STREAM is too long: %.100s...",
1327 l--; if (l>0 && buf[l-1]=='\r') l--;
1330 int rcode= strtoul(buf,&ep,10);
1332 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
1336 exitstatus= CONNCHILD_ESTATUS_STREAM;
1342 warn("connect: unexpected response to MODE STREAM: %.50s",
1348 int fd= fileno(cn_from);
1350 PREP_DECL_MSG_CMSG(msg);
1351 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1352 cmsg->cmsg_level= SOL_SOCKET;
1353 cmsg->cmsg_type= SCM_RIGHTS;
1354 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1355 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1357 msg.msg_controllen= cmsg->cmsg_len;
1358 r= sendmsg(socks[1], &msg, 0);
1359 if (r<0) sysdie("sendmsg failed for new connection");
1360 if (r!=1) die("sendmsg for new connection gave wrong result %d",r);
1365 xclose(socks[1], "connecting fdpass child's socket",0);
1366 connecting_fdpass_sock= socks[0];
1367 xsetnonblock(connecting_fdpass_sock, 1);
1368 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1371 /*---------- assigning articles to conns, and transmitting ----------*/
1373 static void check_assign_articles(void) {
1379 int spare=0, inqueue=0;
1381 /* Find a connection to offer this article. We prefer a busy
1382 * connection to an idle one, provided it's not full. We take the
1383 * first (oldest) and since that's stable, it will mean we fill up
1384 * connections in order. That way if we have too many
1385 * connections, the spare ones will go away eventually.
1387 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1388 if (walk->quitting) continue;
1389 inqueue= walk->sent.count + walk->priority.count
1390 + walk->waiting.count;
1391 spare= walk->max_queue - inqueue;
1392 assert(inqueue <= max_queue_per_conn);
1394 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1395 else if (spare>0) /*working*/ { use= walk; break; }
1398 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1400 Article *art= LIST_REMHEAD(queue);
1402 LIST_ADDTAIL(use->waiting, art);
1405 conn_maybe_write(use);
1406 } else if (allow_connect_start()) {
1407 until_connect= reconnect_delay_periods;
1416 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1417 conn_maybe_write(u);
1418 return OOP_CONTINUE;
1421 static void conn_maybe_write(Conn *conn) {
1423 conn_make_some_xmits(conn);
1425 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1429 void *rp= conn_write_some_xmits(conn);
1430 if (rp==OOP_CONTINUE) {
1431 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1433 } else if (rp==OOP_HALT) {
1436 /* transmitted everything */
1443 /*========== article transmission ==========*/
1445 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1446 XmitKind kind) { /* caller must then fill in details */
1447 struct iovec *v= &conn->xmit[conn->xmitu];
1448 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1449 v->iov_base= (char*)data;
1455 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1456 xmit_core(conn,data,len, xk_Const);
1458 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1460 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1461 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1465 static void xmit_free(XmitDetails *d) {
1467 case xk_Malloc: free(d->info.malloc_tofree); break;
1468 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1469 case xk_Const: break;
1474 static void *conn_write_some_xmits(Conn *conn) {
1476 * 0: nothing more to write, no need to call us again
1477 * OOP_CONTINUE: more to write but fd not writeable
1478 * OOP_HALT: disaster, have destroyed conn
1481 int count= conn->xmitu;
1482 if (!count) return 0;
1484 if (count > IOV_MAX) count= IOV_MAX;
1485 ssize_t rs= writev(conn->fd, conn->xmit, count);
1487 if (isewouldblock(errno)) return OOP_CONTINUE;
1488 connfail(conn, "write failed: %s", strerror(errno));
1494 for (done=0; rs && done<conn->xmitu; done++) {
1495 struct iovec *vp= &conn->xmit[done];
1496 XmitDetails *dp= &conn->xmitd[done];
1497 if (rs > vp->iov_len) {
1501 vp->iov_base= (char*)vp->iov_base + rs;
1505 int newu= conn->xmitu - done;
1506 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1507 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1512 static void conn_make_some_xmits(Conn *conn) {
1514 if (conn->xmitu+5 > CONNIOVS)
1517 Article *art= LIST_REMHEAD(conn->priority);
1518 if (!art) art= LIST_REMHEAD(conn->waiting);
1521 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1522 /* actually send it */
1524 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1527 art->state == art_Unchecked ? art_Unsolicited :
1528 art->state == art_Wanted ? art_Wanted :
1531 if (!artdata) art->missing= 1;
1532 art->ipf->counts[art->state][ artdata ? RC_sent : RC_missing ]++;
1536 XMIT_LITERAL("TAKETHIS ");
1537 xmit_noalloc(conn, art->messageid, art->midlen);
1538 XMIT_LITERAL("\r\n");
1539 xmit_artbody(conn, artdata);
1541 article_done(conn, art, -1);
1545 /* we got 235 from IHAVE */
1547 xmit_artbody(conn, artdata);
1549 XMIT_LITERAL(".\r\n");
1553 LIST_ADDTAIL(conn->sent, art);
1559 XMIT_LITERAL("CHECK ");
1561 XMIT_LITERAL("IHAVE ");
1562 xmit_noalloc(conn, art->messageid, art->midlen);
1563 XMIT_LITERAL("\r\n");
1565 assert(art->state == art_Unchecked);
1566 art->ipf->counts[art->state][RC_sent]++;
1567 LIST_ADDTAIL(conn->sent, art);
1573 /*========== handling responses from peer ==========*/
1575 static const oop_rd_style peer_rd_style= {
1576 OOP_RD_DELIM_STRIP, '\n',
1578 OOP_RD_SHORTREC_FORBID
1581 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1582 const char *errmsg, int errnoval,
1583 const char *data, size_t recsz, void *conn_v) {
1585 connfail(conn, "error receiving from peer: %s", errmsg);
1586 return OOP_CONTINUE;
1589 static Article *article_reply_check(Conn *conn, const char *response,
1590 int code_indicates_streaming,
1592 /* 1:yes, -1:no, 0:dontcare */,
1593 const char *sanitised_response) {
1594 Article *art= LIST_HEAD(conn->sent);
1598 "peer gave unexpected response when no commands outstanding: %s",
1599 sanitised_response);
1603 if (code_indicates_streaming) {
1604 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1605 if (!conn->stream) {
1606 connfail(conn, "peer gave streaming response code "
1607 " to IHAVE or subsequent body: %s", sanitised_response);
1610 const char *got_mid= response+4;
1611 int got_midlen= strcspn(got_mid, " \n\r");
1612 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1613 connfail(conn, "peer gave streaming response with syntactically invalid"
1614 " messageid: %s", sanitised_response);
1617 if (got_midlen != art->midlen ||
1618 memcmp(got_mid, art->messageid, got_midlen)) {
1619 connfail(conn, "peer gave streaming response code to wrong article -"
1620 " probable synchronisation problem; we offered: %s;"
1622 art->messageid, sanitised_response);
1627 connfail(conn, "peer gave non-streaming response code to"
1628 " CHECK/TAKETHIS: %s", sanitised_response);
1633 if (must_have_sent>0 && art->state < art_Wanted) {
1634 connfail(conn, "peer says article accepted but"
1635 " we had not sent the body: %s", sanitised_response);
1638 if (must_have_sent<0 && art->state >= art_Wanted) {
1639 connfail(conn, "peer says please sent the article but we just did: %s",
1640 sanitised_response);
1644 Article *art_again= LIST_REMHEAD(conn->sent);
1645 assert(art_again == art);
1649 static void update_nocheck(int accepted) {
1650 accept_proportion *= nocheck_decay;
1651 accept_proportion += accepted * (1.0 - nocheck_decay);
1652 int new_nocheck= accept_proportion >= nocheck_thresh;
1653 if (new_nocheck && !nocheck_reported) {
1654 notice("entering nocheck mode for the first time");
1655 nocheck_reported= 1;
1656 } else if (new_nocheck != nocheck) {
1657 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1659 nocheck= new_nocheck;
1662 static void article_done(Conn *conn, Article *art, int whichcount) {
1663 if (!art->missing) art->ipf->counts[art->state][whichcount]++;
1665 if (whichcount == RC_accepted) update_nocheck(1);
1666 else if (whichcount == RC_unwanted) update_nocheck(0);
1668 InputFile *ipf= art->ipf;
1670 while (art->blanklen) {
1671 static const char spaces[]=
1681 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1682 int r= pwrite(ipf->fd, spaces, w, art->offset);
1684 if (errno==EINTR) continue;
1685 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1686 art->messageid, art->blanklen,
1687 (unsigned long)art->offset, ipf->path);
1689 assert(r>=0 && r<=w);
1695 assert(ipf->inprogress >= 0);
1698 if (!ipf->inprogress && ipf != main_input_file)
1699 queue_check_input_done();
1702 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1703 const char *errmsg, int errnoval,
1704 const char *data, size_t recsz, void *conn_v) {
1707 if (ev == OOP_RD_EOF) {
1708 connfail(conn, "unexpected EOF from peer");
1709 return OOP_CONTINUE;
1711 assert(ev == OOP_RD_OK);
1713 char *sani= sanitise(data);
1716 unsigned long code= strtoul(data, &ep, 10);
1717 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1718 connfail(conn, "badly formatted response from peer: %s", sani);
1719 return OOP_CONTINUE;
1722 if (conn->quitting) {
1723 if (code!=205 && code!=503) {
1724 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1726 notice("C%d idle connection closed", conn->fd);
1727 assert(!conn->waiting.count);
1728 assert(!conn->priority.count);
1729 assert(!conn->sent.count);
1730 assert(!conn->xmitu);
1731 LIST_REMOVE(conns,conn);
1734 return OOP_CONTINUE;
1737 conn->since_activity= 0;
1740 #define GET_ARTICLE(musthavesent) \
1741 art= article_reply_check(conn, data, code_streaming, musthavesent, sani); \
1742 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1744 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1745 code_streaming= (streaming); \
1746 GET_ARTICLE(musthavesent); \
1747 article_done(conn, art, RC_##how); break;
1749 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1751 int code_streaming= 0;
1755 case 400: PEERBADMSG("peer stopped accepting articles");
1756 case 503: PEERBADMSG("peer timed us out");
1757 default: PEERBADMSG("peer sent unexpected message");
1759 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1760 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1762 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1763 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1765 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1766 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1768 case 238: /* CHECK says send it */
1770 case 335: /* IHAVE says send it */
1772 assert(art->state == art_Unchecked);
1773 art->ipf->counts[art->state][RC_accepted]++;
1774 art->state= art_Wanted;
1775 LIST_ADDTAIL(conn->priority, art);
1778 case 431: /* CHECK or TAKETHIS says try later */
1780 case 436: /* IHAVE says try later */
1783 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1785 sysfatal("write to defer file %s",path_defer);
1786 article_done(conn, art, RC_deferred);
1791 conn_maybe_write(conn);
1792 check_assign_articles();
1793 return OOP_CONTINUE;
1797 /*========== monitoring of input files ==========*/
1799 static void feedfile_eof(InputFile *ipf) {
1800 assert(ipf != main_input_file); /* promised by tailing_try_read */
1801 inputfile_reading_stop(ipf);
1803 if (ipf == flushing_input_file) {
1804 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1805 if (main_input_file) inputfile_reading_start(main_input_file);
1806 statemc_check_flushing_done();
1807 } else if (ipf == backlog_input_file) {
1808 statemc_check_backlog_done();
1810 abort(); /* supposed to wait rather than get EOF on main input file */
1814 static InputFile *open_input_file(const char *path) {
1815 int fd= open(path, O_RDWR);
1817 if (errno==ENOENT) return 0;
1818 sysfatal("unable to open input file %s", path);
1822 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1823 memset(ipf,0,sizeof(*ipf));
1826 strcpy(ipf->path, path);
1831 static void close_input_file(InputFile *ipf) { /* does not free */
1832 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1833 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1834 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1835 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1836 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1840 /*---------- dealing with articles read in the input file ----------*/
1842 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1843 const char *data, const char *how) {
1844 warn("corrupted file: %s, offset %lu: %s: in %s",
1845 ipf->path, (unsigned long)offset, how, sanitise(data));
1846 ipf->readcount_err++;
1847 if (ipf->readcount_err > max_bad_data_initial +
1848 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1849 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1850 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1851 return OOP_CONTINUE;
1854 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1855 oop_rd_event ev, const char *errmsg,
1856 int errnoval, const char *data, size_t recsz,
1858 InputFile *ipf= ipf_v;
1859 assert(ev == OOP_RD_SYSTEM);
1861 sysdie("error reading input file: %s, offset %lu",
1862 ipf->path, (unsigned long)ipf->offset);
1865 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1866 oop_rd_event ev, const char *errmsg,
1867 int errnoval, const char *data, size_t recsz,
1869 InputFile *ipf= ipf_v;
1871 char tokentextbuf[sizeof(TOKEN)*2+3];
1873 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1875 off_t old_offset= ipf->offset;
1876 ipf->offset += recsz + 1;
1878 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1880 if (ev==OOP_RD_PARTREC)
1881 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1882 /* but process it anyway */
1884 if (ipf->skippinglong) {
1885 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1886 return OOP_CONTINUE;
1888 if (ev==OOP_RD_LONG) {
1889 ipf->skippinglong= 1;
1890 X_BAD_DATA("overly long line");
1893 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1894 if (!recsz) X_BAD_DATA("empty line");
1897 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1898 ipf->readcount_blank++;
1899 return OOP_CONTINUE;
1902 char *space= strchr(data,' ');
1903 int tokenlen= space-data;
1904 int midlen= (int)recsz-tokenlen-1;
1905 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1906 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1908 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1909 memcpy(tokentextbuf, data, tokenlen);
1910 tokentextbuf[tokenlen]= 0;
1911 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1913 ipf->readcount_ok++;
1915 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1916 art->state= art_Unchecked;
1917 art->midlen= midlen;
1918 art->ipf= ipf; ipf->inprogress++;
1919 art->token= TextToToken(tokentextbuf);
1920 art->offset= ipf->offset;
1921 art->blanklen= recsz;
1922 strcpy(art->messageid, space+1);
1923 LIST_ADDTAIL(queue, art);
1925 if (sms==sm_NORMAL && ipf==main_input_file &&
1926 ipf->offset >= target_max_feedfile_size)
1927 statemc_start_flush("feed file size");
1929 check_assign_articles();
1930 return OOP_CONTINUE;
1933 /*========== tailing input file ==========*/
1935 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1937 InputFile *ipf= user;
1938 return ipf->readable_callback(loop, &ipf->readable,
1939 ipf->readable_callback_user);
1942 static void tailing_on_cancel(struct oop_readable *rable) {
1943 InputFile *ipf= (void*)rable;
1945 if (ipf->filemon) filemon_stop(ipf);
1946 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1947 ipf->readable_callback= 0;
1950 static void tailing_queue_readable(InputFile *ipf) {
1951 /* lifetime of ipf here is OK because destruction will cause
1952 * on_cancel which will cancel this callback */
1953 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1956 static int tailing_on_readable(struct oop_readable *rable,
1957 oop_readable_call *cb, void *user) {
1958 InputFile *ipf= (void*)rable;
1960 tailing_on_cancel(rable);
1961 ipf->readable_callback= cb;
1962 ipf->readable_callback_user= user;
1965 tailing_queue_readable(ipf);
1969 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1971 InputFile *ipf= (void*)rable;
1973 ssize_t r= read(ipf->fd, buffer, length);
1975 if (errno==EINTR) continue;
1979 if (ipf==main_input_file) {
1982 } else if (ipf==flushing_input_file) {
1984 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1985 } else if (ipf==backlog_input_file) {
1991 tailing_queue_readable(ipf);
1996 /*---------- filemon implemented with inotify ----------*/
1998 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1999 #define HAVE_FILEMON
2001 #include <linux/inotify.h>
2003 static int filemon_inotify_fd;
2004 static int filemon_inotify_wdmax;
2005 static InputFile **filemon_inotify_wd2ipf;
2007 struct Filemon_Perfile {
2011 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
2012 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
2013 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
2015 if (wd >= filemon_inotify_wdmax) {
2017 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
2018 sizeof(*filemon_inotify_wd2ipf) * newmax);
2019 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
2020 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
2021 filemon_inotify_wdmax= newmax;
2024 assert(!filemon_inotify_wd2ipf[wd]);
2025 filemon_inotify_wd2ipf[wd]= ipf;
2027 debug("filemon inotify startfile %p wd=%d wdmax=%d",
2028 ipf, wd, filemon_inotify_wdmax);
2033 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
2035 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
2036 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
2037 if (r) sysdie("inotify_rm_watch");
2038 filemon_inotify_wd2ipf[wd]= 0;
2041 static void *filemon_inotify_readable(oop_source *lp, int fd,
2042 oop_event e, void *u) {
2043 struct inotify_event iev;
2045 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
2047 if (isewouldblock(errno)) break;
2048 sysdie("read from inotify master");
2049 } else if (r==sizeof(iev)) {
2050 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
2052 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
2054 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
2055 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
2056 filemon_callback(ipf);
2058 return OOP_CONTINUE;
2061 static int filemon_method_init(void) {
2062 filemon_inotify_fd= inotify_init();
2063 if (filemon_inotify_fd<0) {
2064 syswarn("could not initialise inotify: inotify_init failed");
2068 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
2070 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2074 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2076 /*---------- filemon dummy implementation ----------*/
2078 #if !defined(HAVE_FILEMON)
2080 struct Filemon_Perfile { int dummy; };
2082 static int filemon_method_init(void) { return 0; }
2083 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2084 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2086 #endif /* !HAVE_FILEMON */
2088 /*---------- filemon generic interface ----------*/
2090 static void filemon_start(InputFile *ipf) {
2091 assert(!ipf->filemon);
2093 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
2094 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
2095 filemon_method_startfile(ipf, ipf->filemon);
2098 static void filemon_stop(InputFile *ipf) {
2099 if (!ipf->filemon) return;
2100 filemon_method_stopfile(ipf, ipf->filemon);
2105 static void filemon_callback(InputFile *ipf) {
2106 if (ipf && ipf->readable_callback) /* so filepoll() can be naive */
2107 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2110 /*---------- interface to start and stop an input file ----------*/
2112 static const oop_rd_style feedfile_rdstyle= {
2113 OOP_RD_DELIM_STRIP, '\n',
2115 OOP_RD_SHORTREC_LONG,
2118 static void inputfile_reading_start(InputFile *ipf) {
2120 ipf->readable.on_readable= tailing_on_readable;
2121 ipf->readable.on_cancel= tailing_on_cancel;
2122 ipf->readable.try_read= tailing_try_read;
2123 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2124 ipf->readable.delete_kill= 0;
2126 ipf->readable_callback= 0;
2127 ipf->readable_callback_user= 0;
2129 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2132 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2133 feedfile_got_article,ipf, feedfile_read_err, ipf);
2134 if (r) sysdie("unable start reading feedfile %s",ipf->path);
2137 static void inputfile_reading_stop(InputFile *ipf) {
2139 oop_rd_cancel(ipf->rd);
2140 oop_rd_delete(ipf->rd);
2142 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2146 /*========== interaction with innd - state machine ==========*/
2148 /* See official state diagram at top of file. We implement
2159 |`---------------------------------------------------.
2161 |`---------------- - - - |
2162 D ENOENT | D EXISTS see OVERALL STATES diagram |
2163 | for full startup logic |
2166 | ============ try to |
2172 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
2173 ^ | hardlink F to D |
2176 | | our handle onto F is now onto D |
2179 | |<-------------------<---------------------<---------+
2181 | | spawn inndcomm flush |
2183 | ================== |
2184 | FLUSHING[-ABSENT] |
2186 | main D tail/none |
2187 | ================== |
2189 | | INNDCOMM FLUSH FAILS ^
2190 | |`----------------------->----------. |
2192 | | NO SUCH SITE V |
2193 ^ |`--------------->----. ==================== |
2194 | | \ FLUSHFAILED[-ABSENT] |
2196 | | FLUSH OK \ main D tail/none |
2197 | | open F \ ==================== |
2199 | | \ | TIME TO RETRY |
2200 | |`------->----. ,---<---'\ `----------------'
2201 | | D NONE | | D NONE `----.
2203 | ============= V V ============
2204 | SEPARATED-1 | | DROPPING-1
2205 | flsh->rd!=0 | | flsh->rd!=0
2206 | [Separated] | | [Dropping]
2207 | main F idle | | main none
2208 | old D tail | | old D tail
2209 | ============= | | ============
2211 ^ | EOF ON D | | defer | EOF ON D
2213 | =============== | | ===============
2214 | SEPARATED-2 | | DROPPING-2
2215 | flsh->rd==0 | V flsh->rd==0
2216 | [Finishing] | | [Dropping]
2217 | main F tail | `. main none
2218 | old D closed | `. old D closed
2219 | =============== V `. ===============
2221 | | ALL D PROCESSED `. | ALL D PROCESSED
2222 | V install defer as backlog `. | install defer
2223 ^ | close D `. | close D
2224 | | unlink D `. | unlink D
2227 `----------' ==============
2247 static void startup_set_input_file(InputFile *f) {
2248 assert(!main_input_file);
2250 inputfile_reading_start(f);
2253 static void statemc_lock(void) {
2255 struct stat stab, stabf;
2258 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2259 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2262 memset(&fl,0,sizeof(fl));
2264 fl.l_whence= SEEK_SET;
2265 int r= fcntl(lockfd, F_SETLK, &fl);
2267 if (errno==EACCES || isewouldblock(errno)) {
2268 if (quiet_multiple) exit(0);
2269 fatal("another duct holds the lockfile");
2271 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2274 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2276 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2278 if (!lock_noent && samefile(&stab, &stabf))
2281 xclose(lockfd, "stale lockfile ", path_lock);
2284 FILE *lockfile= fdopen(lockfd, "w");
2285 if (!lockfile) sysdie("fdopen lockfile");
2287 int r= ftruncate(lockfd, 0);
2288 if (r) sysdie("truncate lockfile to write new info");
2290 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2291 (unsigned long)self_pid,
2292 sitename, feedfile, remote_host) == EOF ||
2294 sysfatal("write info to lockfile %s", path_lock);
2296 debug("startup: locked");
2299 static void statemc_init(void) {
2300 struct stat stabdefer;
2302 search_backlog_file();
2305 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2307 debug("startup: ductdefer ENOENT");
2309 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2310 switch (stabdefer.st_nlink==1) {
2312 open_defer(); /* so that we will later close it and rename it */
2315 xunlink(path_defer, "stale defer file link"
2316 " (presumably hardlink to backlog file)");
2319 die("defer file %s has unexpected link count %d",
2320 path_defer, stabdefer.st_nlink);
2324 struct stat stab_f, stab_d;
2327 InputFile *file_d= open_input_file(path_flushing);
2328 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2330 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2332 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2333 debug("startup: F==D => Hardlinked");
2334 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2339 debug("startup: F ENOENT => Moved");
2340 if (file_d) startup_set_input_file(file_d);
2341 spawn_inndcomm_flush("feedfile missing at startup");
2342 /* => Flushing, sms:=FLUSHING */
2345 debug("startup: F!=D => Separated");
2346 startup_set_input_file(file_d);
2347 SMS(SEPARATED, 0, "found both old and current feed files");
2349 debug("startup: F exists, D ENOENT => Normal");
2350 InputFile *file_f= open_input_file(feedfile);
2351 if (!file_f) die("feed file vanished during startup");
2352 startup_set_input_file(file_f);
2353 SMS(NORMAL, spontaneous_flush_periods, "normal startup");
2358 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2359 assert(sms == sm_NORMAL);
2361 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2363 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2364 (unsigned long)target_max_feedfile_size,
2367 int r= link(feedfile, path_flushing);
2368 if (r) sysfatal("link feedfile %s to flushing file %s",
2369 feedfile, path_flushing);
2372 xunlink(feedfile, "old feedfile link");
2375 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2378 static void statemc_period_poll(void) {
2379 if (!sm_period_counter) return;
2380 sm_period_counter--;
2381 assert(sm_period_counter>=0);
2383 if (sm_period_counter) return;
2386 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2388 case sm_FLUSHFAILED:
2389 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2396 static int inputfile_is_done(InputFile *ipf) {
2398 if (ipf->inprogress) return 0; /* new article in the meantime */
2399 if (ipf->rd) return 0; /* not had EOF */
2403 static void notice_processed(InputFile *ipf, const char *what,
2405 #define RCI_NOTHING(x) /* nothing */
2406 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2407 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2409 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2411 info("processed %s%s read=%d (+bl=%d,+err=%d)"
2412 " offered=%d (ch=%d,nc=%d) accepted=%d (ch=%d,nc=%d)"
2413 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2416 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2417 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2418 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2419 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2420 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2421 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2427 static void statemc_check_backlog_done(void) {
2428 InputFile *ipf= backlog_input_file;
2429 if (!inputfile_is_done(ipf)) return;
2431 const char *slash= strrchr(ipf->path, '/');
2432 const char *leaf= slash ? slash+1 : ipf->path;
2433 const char *under= strchr(slash, '_');
2434 const char *rest= under ? under+1 : leaf;
2435 if (!strncmp(rest,"backlog",7)) rest += 7;
2436 notice_processed(ipf,"backlog ",rest);
2438 close_input_file(ipf);
2439 if (unlink(ipf->path)) {
2440 if (errno != ENOENT)
2441 sysdie("could not unlink processed backlog file %s", ipf->path);
2442 warn("backlog file %s vanished while we were reading it"
2443 " so we couldn't remove it (but it's done now, anyway)",
2447 backlog_input_file= 0;
2448 search_backlog_file();
2452 static void statemc_check_flushing_done(void) {
2453 InputFile *ipf= flushing_input_file;
2454 if (!inputfile_is_done(ipf)) return;
2456 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2458 notice_processed(ipf,"feedfile","");
2462 xunlink(path_flushing, "old flushing file");
2464 close_input_file(flushing_input_file);
2465 free(flushing_input_file);
2466 flushing_input_file= 0;
2468 if (sms==sm_SEPARATED) {
2469 notice("flush complete");
2470 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2471 } else if (sms==sm_DROPPING) {
2472 SMS(DROPPED, 0, "old flush complete");
2473 search_backlog_file();
2474 notice("feed dropped, but will continue until backlog is finished");
2478 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2480 assert(!inputfile_is_done(main_input_file));
2481 statemc_check_flushing_done();
2482 statemc_check_backlog_done();
2483 return OOP_CONTINUE;
2486 static void queue_check_input_done(void) {
2487 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2490 static void statemc_setstate(StateMachineState newsms, int periods,
2491 const char *forlog, const char *why) {
2493 sm_period_counter= periods;
2495 const char *xtra= "";
2498 case sm_FLUSHFAILED:
2499 if (!main_input_file) xtra= "-ABSENT";
2503 xtra= flushing_input_file->rd ? "-1" : "-2";
2509 info("state %s%s[%d] %s",forlog,xtra,periods,why);
2511 info("state %s%s %s",forlog,xtra,why);
2515 /*---------- defer and backlog files ----------*/
2517 static void open_defer(void) {
2522 defer= fopen(path_defer, "a+");
2523 if (!defer) sysfatal("could not open defer file %s", path_defer);
2525 /* truncate away any half-written records */
2527 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2529 if (stab.st_size > LONG_MAX)
2530 die("defer file %s size is far too large", path_defer);
2535 long orgsize= stab.st_size;
2536 long truncto= stab.st_size;
2538 if (!truncto) break; /* was only (if anything) one half-truncated record */
2539 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2540 sysdie("seek in defer file %s while truncating partial", path_defer);
2545 sysdie("failed read from defer file %s", path_defer);
2547 die("defer file %s shrank while we were checking it!", path_defer);
2553 if (stab.st_size != truncto) {
2554 warn("truncating half-record at end of defer file %s -"
2555 " shrinking by %ld bytes from %ld to %ld",
2556 path_defer, orgsize - truncto, orgsize, truncto);
2559 sysfatal("could not flush defer file %s", path_defer);
2560 if (ftruncate(fileno(defer), truncto))
2561 sysdie("could not truncate defer file %s", path_defer);
2564 info("continuing existing defer file %s (%ld bytes)",
2565 path_defer, orgsize);
2567 if (fseek(defer, truncto, SEEK_SET))
2568 sysdie("could not seek to new end of defer file %s", path_defer);
2571 static void close_defer(void) {
2576 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2578 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2581 time_t now= xtime();
2583 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2585 (unsigned long)stab.st_ino);
2586 if (link(path_defer, backlog))
2587 sysfatal("could not install defer file %s as backlog file %s",
2588 path_defer, backlog);
2589 if (unlink(path_defer))
2590 sysdie("could not unlink old defer link %s to backlog file %s",
2591 path_defer, backlog);
2595 if (until_backlog_nextscan < 0 ||
2596 until_backlog_nextscan > backlog_retry_minperiods + 1)
2597 until_backlog_nextscan= backlog_retry_minperiods + 1;
2600 static void poll_backlog_file(void) {
2601 if (until_backlog_nextscan < 0) return;
2602 if (until_backlog_nextscan-- > 0) return;
2603 search_backlog_file();
2606 static void search_backlog_file(void) {
2607 /* returns non-0 iff there are any backlog files */
2612 const char *oldest_path=0;
2613 time_t oldest_mtime=0, now;
2615 if (backlog_input_file) return;
2619 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2623 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2625 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2627 for (i=0; i<gl.gl_pathc; i++) {
2628 const char *path= gl.gl_pathv[i];
2630 if (strchr(path,'#') || strchr(path,'~')) {
2631 debug("backlog file search skipping %s", path);
2634 r= stat(path, &stab);
2636 syswarn("failed to stat backlog file %s", path);
2639 if (!S_ISREG(stab.st_mode)) {
2640 warn("backlog file %s is not a plain file (or link to one)", path);
2643 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2645 oldest_mtime= stab.st_mtime;
2648 case GLOB_NOMATCH: /* fall through */
2651 sysdie("glob expansion of backlog pattern %s gave unexpected"
2652 " nonzero (error?) return value %d", globpat_backlog, r);
2656 debug("backlog scan: none");
2658 if (sms==sm_DROPPED) {
2659 notice("feed dropped and our work is complete");
2661 int r= unlink(path_control);
2662 if (r && errno!=ENOENT)
2663 syswarn("failed to remove control symlink for old feed");
2665 xunlink(path_lock, "lockfile for old feed");
2668 until_backlog_nextscan= backlog_spontrescan_periods;
2673 double age= difftime(now, oldest_mtime);
2674 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2676 if (age_deficiency <= 0) {
2677 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2678 age, age_deficiency, oldest_path);
2680 backlog_input_file= open_input_file(oldest_path);
2681 if (!backlog_input_file) {
2682 warn("backlog file %s vanished as we opened it", oldest_path);
2686 inputfile_reading_start(backlog_input_file);
2687 until_backlog_nextscan= -1;
2691 until_backlog_nextscan= age_deficiency / period_seconds;
2693 if (backlog_spontrescan_periods >= 0 &&
2694 until_backlog_nextscan > backlog_spontrescan_periods)
2695 until_backlog_nextscan= backlog_spontrescan_periods;
2697 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2698 age, age_deficiency, until_backlog_nextscan, oldest_path);
2705 /*========== flushing the feed ==========*/
2707 static pid_t inndcomm_child;
2708 static int inndcomm_sentinel_fd;
2710 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2711 assert(inndcomm_child);
2712 assert(fd == inndcomm_sentinel_fd);
2713 int status= xwaitpid(&inndcomm_child, "inndcomm");
2716 cancel_fd_read_except(fd);
2717 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2718 inndcomm_sentinel_fd= 0;
2720 assert(!flushing_input_file);
2722 if (WIFEXITED(status)) {
2723 switch (WEXITSTATUS(status)) {
2725 case INNDCOMMCHILD_ESTATUS_FAIL:
2728 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2729 notice("feed has been dropped by innd, finishing up");
2730 flushing_input_file= main_input_file;
2731 tailing_queue_readable(flushing_input_file);
2732 /* we probably previously returned EAGAIN from our fake read method
2733 * when in fact we were at EOF, so signal another readable event
2734 * so we actually see the EOF */
2738 if (flushing_input_file) {
2739 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2742 SMS(DROPPED, 0, "feed dropped by innd");
2743 search_backlog_file();
2745 return OOP_CONTINUE;
2749 flushing_input_file= main_input_file;
2750 tailing_queue_readable(flushing_input_file);
2752 main_input_file= open_input_file(feedfile);
2753 if (!main_input_file)
2754 die("flush succeeded but feedfile %s does not exist!", feedfile);
2756 if (flushing_input_file) {
2757 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2760 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2762 return OOP_CONTINUE;
2765 goto unexpected_exitstatus;
2768 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2769 warn("flush timed out trying to talk to innd");
2772 unexpected_exitstatus:
2773 report_child_status("inndcomm child", status);
2777 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2778 return OOP_CONTINUE;
2781 static void inndcommfail(const char *what) {
2782 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2783 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2786 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2789 notice("flushing %s",why);
2791 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2792 assert(!inndcomm_child);
2793 assert(!inndcomm_sentinel_fd);
2795 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2797 inndcomm_child= xfork("inndcomm child");
2799 if (!inndcomm_child) {
2800 const char *flushargv[2]= { sitename, 0 };
2804 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2805 /* parent spots the autoclose of pipefds[1] when we die or exit */
2807 if (simulate_flush>=0) {
2808 warn("SIMULATING flush child status %d", simulate_flush);
2809 if (simulate_flush>128) raise(simulate_flush-128);
2810 else exit(simulate_flush);
2813 alarm(inndcomm_flush_timeout);
2814 r= ICCopen(); if (r) inndcommfail("connect");
2815 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2816 if (!r) exit(0); /* yay! */
2818 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2819 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2820 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2825 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2826 inndcomm_sentinel_fd= pipefds[0];
2827 assert(inndcomm_sentinel_fd);
2828 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2830 SMS(FLUSHING, 0, why);
2833 /*========== main program ==========*/
2835 static void postfork_inputfile(InputFile *ipf) {
2837 xclose(ipf->fd, "(in child) input file ", ipf->path);
2840 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2841 /* we have no stdio streams that are buffered long-term */
2843 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2846 static void postfork(void) {
2847 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2848 sysdie("(in child) failed to reset SIGPIPE");
2850 postfork_inputfile(main_input_file);
2851 postfork_inputfile(flushing_input_file);
2854 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2855 conn_closefd(conn,"(in child) ");
2857 postfork_stdio(defer, "defer file ", path_defer);
2860 typedef struct Every Every;
2862 struct timeval interval;
2867 static void every_schedule(Every *e, struct timeval base);
2869 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
2872 if (!e->fixed_rate) xgettimeofday(&base);
2873 every_schedule(e, base);
2874 return OOP_CONTINUE;
2877 static void every_schedule(Every *e, struct timeval base) {
2878 struct timeval when;
2879 timeradd(&base, &e->interval, &when);
2880 loop->on_time(loop, when, every_happens, e);
2883 static void every(int interval, int fixed_rate, void (*f)(void)) {
2884 Every *e= xmalloc(sizeof(*e));
2885 e->interval.tv_sec= interval;
2886 e->interval.tv_usec= 0;
2887 e->fixed_rate= fixed_rate;
2890 xgettimeofday(&now);
2891 every_schedule(e, now);
2894 static void filepoll(void) {
2895 filemon_callback(main_input_file);
2896 filemon_callback(flushing_input_file);
2899 static char *debug_report_ipf(InputFile *ipf) {
2900 if (!ipf) return xasprintf("none");
2902 const char *slash= strrchr(ipf->path,'/');
2903 const char *path= slash ? slash+1 : ipf->path;
2905 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2907 ipf->inprogress, (long)ipf->offset,
2908 ipf->fd, ipf->rd ? "" : ",!rd");
2911 static void period(void) {
2912 char *dipf_main= debug_report_ipf(main_input_file);
2913 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2914 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2917 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2918 " input_files main:%s flushing:%s backlog:%s"
2919 " children connecting=%ld inndcomm=%ld"
2921 sms_names[sms], sm_period_counter,
2922 conns.count, queue.count, until_connect,
2923 dipf_main, dipf_flushing, dipf_backlog,
2924 (long)connecting_child, (long)inndcomm_child
2928 free(dipf_flushing);
2931 if (until_connect) until_connect--;
2933 poll_backlog_file();
2934 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2935 statemc_period_poll();
2936 check_assign_articles();
2941 /*========== option parsing ==========*/
2943 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2944 static void vbadusage(const char *fmt, va_list al) {
2945 char *m= xvasprintf(fmt,al);
2946 fprintf(stderr, "bad usage: %s\n"
2947 "say --help for help, or read the manpage\n",
2950 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2954 /*---------- generic option parser ----------*/
2956 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2957 static void badusage(const char *fmt, ...) {
2964 of_seconds= 001000u,
2965 of_boolean= 002000u,
2968 typedef struct Option Option;
2969 typedef void OptionParser(const Option*, const char *val);
2973 const char *lng, *formarg;
2979 static void parse_options(const Option *options, char ***argvp) {
2980 /* on return *argvp is first non-option arg; argc is not updated */
2983 const char *arg= *++(*argvp);
2985 if (*arg != '-') break;
2986 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2988 while ((a= *++arg)) {
2992 char *equals= strchr(arg,'=');
2993 int len= equals ? (equals - arg) : strlen(arg);
2994 for (o=options; o->shrt || o->lng; o++)
2995 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2997 badusage("unknown long option --%s",arg);
3000 if (equals) badusage("option --%s does not take a value",o->lng);
3002 } else if (equals) {
3006 if (!arg) badusage("option --%s needs a value for %s",
3007 o->lng, o->formarg);
3010 break; /* eaten the whole argument now */
3012 for (o=options; o->shrt || o->lng; o++)
3015 badusage("unknown short option -%c",a);
3022 if (!arg) badusage("option -%c needs a value for %s",
3023 o->shrt, o->formarg);
3026 break; /* eaten the whole argument now */
3032 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
3034 static void print_options(const Option *options, FILE *f) {
3036 for (o=options; o->shrt || o->lng; o++) {
3037 char shrt[2] = { o->shrt, 0 };
3038 char *optspec= xasprintf("%s%s%s%s%s",
3039 o->shrt ? "-" : "", shrt,
3040 o->shrt && o->lng ? "|" : "",
3041 DELIMPERHAPS("--", o->lng));
3042 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
3047 /*---------- specific option types ----------*/
3049 static void op_integer(const Option *o, const char *val) {
3052 unsigned long ul= strtoul(val,&ep,10);
3053 if (*ep || ep==val || errno || ul>INT_MAX)
3054 badusage("bad integer value for %s",o->lng);
3055 int *store= o->store;
3059 static void op_double(const Option *o, const char *val) {
3060 int *store= o->store;
3063 *store= strtod(val, &ep);
3064 if (*ep || ep==val || errno)
3065 badusage("bad floating point value for %s",o->lng);
3068 static void op_string(const Option *o, const char *val) {
3069 const char **store= o->store;
3073 static void op_seconds(const Option *o, const char *val) {
3074 int *store= o->store;
3078 double v= strtod(val,&ep);
3079 if (ep==val) badusage("bad time/duration value for %s",o->lng);
3081 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
3082 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
3083 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
3084 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
3085 else if (!strcmp(ep,"das")) unit= 10;
3086 else if (!strcmp(ep,"hs")) unit= 100;
3087 else if (!strcmp(ep,"ks")) unit= 1000;
3088 else if (!strcmp(ep,"Ms")) unit= 1000000;
3089 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
3093 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
3097 static void op_setint(const Option *o, const char *val) {
3098 int *store= o->store;
3102 /*---------- specific options ----------*/
3104 static void help(const Option *o, const char *val);
3106 static const Option innduct_options[]= {
3107 {'f',"feedfile", "F", &feedfile, op_string },
3108 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
3109 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
3110 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
3111 {'C',"inndconf", "F", &inndconffile, op_string },
3112 {'P',"port", "PORT", &port, op_integer },
3113 {0,"help", 0, 0, help },
3115 {0,"max-connections", "N", &max_connections, op_integer },
3116 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
3117 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
3118 {0,"period-interval", "TIME", &period_seconds, op_seconds },
3120 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
3121 {0,"stuck-flush-timeout","TIME", &inndcomm_flush_timeout, op_seconds },
3123 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
3124 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
3126 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
3127 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
3128 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3129 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3130 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
3131 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
3133 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
3134 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
3139 static void printusage(FILE *f) {
3140 fputs("usage: innduct [options] site [fqdn]\n"
3141 "available options are:\n", f);
3142 print_options(innduct_options, f);
3145 static void help(const Option *o, const char *val) {
3147 if (ferror(stdout) || fflush(stdout)) {
3148 perror("innduct: writing help");
3154 static void convert_to_periods_rndup(int *store) {
3155 *store += period_seconds-1;
3156 *store /= period_seconds;
3159 int main(int argc, char **argv) {
3165 parse_options(innduct_options, &argv);
3170 if (!sitename) badusage("need site name argument");
3171 remote_host= *argv++;
3172 if (*argv) badusage("too many non-option arguments");
3176 int r= innconf_read(inndconffile);
3177 if (!r) badusage("could not read inn.conf (more info on stderr)");
3179 if (!remote_host) remote_host= sitename;
3181 if (nocheck_thresh < 0 || nocheck_thresh > 100)
3182 badusage("nocheck threshold percentage must be between 0..100");
3183 nocheck_thresh *= 0.01;
3185 if (nocheck_decay < 0.1)
3186 badusage("nocheck decay articles must be at least 0.1");
3187 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3189 convert_to_periods_rndup(&reconnect_delay_periods);
3190 convert_to_periods_rndup(&flushfail_retry_periods);
3191 convert_to_periods_rndup(&backlog_retry_minperiods);
3192 convert_to_periods_rndup(&backlog_spontrescan_periods);
3193 convert_to_periods_rndup(&spontaneous_flush_periods);
3194 convert_to_periods_rndup(&need_activity_periods);
3196 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3197 badusage("bad input data ratio must be between 0..100");
3198 max_bad_data_ratio *= 0.01;
3201 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3202 } else if (!feedfile[0]) {
3203 badusage("feed filename must be nonempty");
3204 } else if (feedfile[strlen(feedfile)-1]=='/') {
3205 feedfile= xasprintf("%s%s",feedfile,sitename);
3208 const char *feedfile_forbidden= "?*[~#";
3210 while ((c= *feedfile_forbidden++))
3211 if (strchr(feedfile, c))
3212 badusage("feed filename may not contain metacharacter %c",c);
3216 path_lock= xasprintf("%s_lock", feedfile);
3217 path_flushing= xasprintf("%s_flushing", feedfile);
3218 path_defer= xasprintf("%s_defer", feedfile);
3219 path_control= xasprintf("%s_control", feedfile);
3220 globpat_backlog= xasprintf("%s_backlog*", feedfile);
3222 oop_source_sys *sysloop= oop_sys_new();
3223 if (!sysloop) sysdie("could not create liboop event loop");
3224 loop= (oop_source*)sysloop;
3226 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3227 sysdie("could not ignore SIGPIPE");
3232 if (become_daemon) {
3234 for (i=3; i<255; i++)
3235 /* do this now before we open syslog, etc. */
3237 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3239 int null= open("/dev/null",O_RDWR);
3240 if (null<0) sysfatal("failed to open /dev/null");
3244 xclose(null, "/dev/null original fd",0);
3246 pid_t child1= xfork("daemonise first fork");
3247 if (child1) _exit(0);
3249 pid_t sid= setsid();
3250 if (sid != child1) sysfatal("setsid failed");
3252 pid_t child2= xfork("daemonise second fork");
3253 if (child2) _exit(0);
3257 if (self_pid==-1) sysdie("getpid");
3268 if (!filemon_method_init()) {
3269 warn("no file monitoring available, polling");
3270 every(5,0,filepoll);
3273 every(period_seconds,1,period);
3279 void *run= oop_sys_run(sysloop);
3280 assert(run == OOP_ERROR);
3281 sysdie("event loop failed");