3 * tailing reliable realtime streaming feeder for inn
5 * Copyright (C) 2010 Ian Jackson <ijackson@chiark.greenend.org.uk>
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * (I believe that when you compile and link this as part of the inn2
21 * build, with the Makefile runes I have provided, all the libraries
22 * and files which end up included in innduct are licence-compatible
23 * with GPLv3. If not then please let me know. -Ian Jackson.)
29 * don't mind reconnecting if we just disconnected due to idle
30 * some weird disconnection event still investigating
34 * Newsfeeds file entries should look like this:
35 * host.name.of.site[/exclude,exclude,...]\
36 * :pattern,pattern...[/distribution,distribution...]\
40 * sitename[/exclude,exclude,...]\
41 * :pattern,pattern...[/distribution,distribution...]\
47 * or might be blanked out
48 * <spc><spc><spc><spc>....
50 * F site.name main feed file
51 * opened/created, then written, by innd
54 * tokens blanked out by duct when processed
55 * site.name_lock lock preventing multiple ducts
56 * to hold lock must open,F_SETLK[W]
57 * and then stat to check that locked file
58 * still has name site.name_lock
59 * holder of this lock is "duct"
60 * (only) lockholder may remove the lockfile
61 * D site.name_flushing temporary feed file during flush (or crash)
62 * hardlink created by duct
64 * site.name_defer 431'd articles, still being written,
65 * created, written, used by duct
67 * site.name_backlog.<date>.<inum>
68 * 431'd articles, ready for innxmit or duct
69 * created (link/mv) by duct
70 * site.name_backlog<anything-else> (where <anything-else> does not
71 * contain '#' or '~') eg
72 * site.name_backlog.manual
73 * anything the sysadmin likes (eg, feed files
74 * from old feeds to be merged into this one)
75 * created (link/mv) by admin
76 * may be symlinks (in which case links
77 * may be written through, but only links
80 * It is safe to remove backlog files manually,
81 * if it's desired to throw away the backlog.
83 * Backlog files are also processed by innduct. We find the oldest
84 * backlog file which is at least a certain amount old, and feed it
85 * back into our processing. When every article in it has been read
86 * and processed, we unlink it and look for another backlog file.
88 * If we don't have a backlog file that we're reading, we close the
89 * defer file that we're writing and make it into a backlog file at
90 * the first convenient opportunity.
101 | | <----------------<---------------------------------'|
107 | F: innd writing, duct reading |
110 | | duct decides time to flush |
111 | | duct makes hardlink |
113 | V <------------------------'|
115 | F == D: innd writing, duct reading both exist |
118 | | <-----------<-------------<--'|
119 | | open D F ENOENT |
122 | V <---------------------. |
125 | D: innd writing, duct reading; or ENOENT | |
127 | | duct requests flush of feed | |
128 | | (others can too, harmlessly) | |
132 | D: innd flushing, duct; or ENOENT | |
134 | | inndcomm flush fails | |
135 | |`-------------------------->------------------' |
137 | | inndcomm reports no such site |
138 | |`---------------------------------------------------- | -.
140 | | innd finishes writing D, creates F | |
141 | | inndcomm reports flush successful | |
144 | Separated <----------------' |
145 | F: innd writing F!=D /
146 | D: duct reading; or ENOENT both exist /
148 | | duct gets to the end of D /
149 | | duct opens F too /
152 | F: innd writing, duct reading |
153 | D: duct finishing V
155 | | duct finishes processing D F: ENOENT
156 | V duct unlinks D D: duct reading
158 `--<--' | duct finishes
168 "duct reading" means innduct is reading the file but also
169 overwriting processed tokens.
173 * rune for printing diagrams:
175 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
180 /*============================== PROGRAM ==============================*/
182 #define _GNU_SOURCE 1
188 #include "inndcomm.h"
190 #include "inn/list.h"
191 #include "inn/innconf.h"
194 #include <sys/types.h>
195 #include <sys/wait.h>
196 #include <sys/stat.h>
197 #include <sys/socket.h>
216 #include <oop-read.h>
218 /*----- general definitions, probably best not changed -----*/
220 #define CONNCHILD_ESTATUS_STREAM 24
221 #define CONNCHILD_ESTATUS_NOSTREAM 25
223 #define INNDCOMMCHILD_ESTATUS_FAIL 26
224 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
226 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
227 #define MAX_CLI_COMMAND 1000
229 #define VA va_list al; va_start(al,fmt)
230 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
231 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
232 #define NORET __attribute__((__noreturn__))
234 #define NEW(ptr) ((ptr)= zxmalloc(sizeof(*(ptr))))
235 #define NEW_DECL(type,ptr) type ptr = zxmalloc(sizeof(*(ptr)))
237 #define DUMPV(fmt,pfx,v) fprintf(f, " " #v "=" fmt, pfx v);
239 #define FOR_CONN(conn) \
240 for ((conn)=LIST_HEAD(conns); (conn); (conn)=LIST_NEXT((conn)))
242 /*----- doubly linked lists -----*/
244 #define ISNODE(T) struct node list_node
247 union { struct list li; T *for_type; } u; \
251 #define NODE(n) (assert((void*)&(n)->list_node == (n)), &(n)->list_node)
253 #define LIST_CHECKCANHAVENODE(l,n) \
254 ((void)((n) == ((l).u.for_type))) /* just for the type check */
256 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
257 ( LIST_CHECKCANHAVENODE(l,n), \
258 list_addsomehow(&(l).u.li, NODE((n))), \
262 #define LIST_REMSOMEHOW(l,list_remsomehow) \
263 ( (typeof((l).u.for_type)) \
266 list_remsomehow(&(l).u.li) ) \
272 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
273 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
274 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
275 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
277 #define LIST_INIT(l) ((l).count=0, list_new(&(l).u.li))
278 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
279 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
280 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
282 #define LIST_REMOVE(l,n) \
283 ( LIST_CHECKCANHAVENODE(l,n), \
284 list_remove(NODE((n))), \
288 #define LIST_INSERT(l,n,pred) \
289 ( LIST_CHECKCANHAVENODE(l,n), \
290 LIST_CHECKCANHAVENODE(l,pred), \
291 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
295 /*----- type predeclarations -----*/
297 typedef struct Conn Conn;
298 typedef struct Article Article;
299 typedef struct InputFile InputFile;
300 typedef struct XmitDetails XmitDetails;
301 typedef struct Filemon_Perfile Filemon_Perfile;
302 typedef enum StateMachineState StateMachineState;
303 typedef struct CliCommand CliCommand;
308 /*----- function predeclarations -----*/
310 static void conn_maybe_write(Conn *conn);
311 static void conn_make_some_xmits(Conn *conn);
312 static void *conn_write_some_xmits(Conn *conn);
314 static void xmit_free(XmitDetails *d);
316 #define SMS(newstate, periods, why) \
317 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
318 static void statemc_setstate(StateMachineState newsms, int periods,
319 const char *forlog, const char *why);
321 static void statemc_start_flush(const char *why); /* Normal => Flushing */
322 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
323 static int trigger_flush_ok(const char *why /* 0 means timeout */);
324 /* => Flushing,FLUSHING, ret 1; or ret 0 */
326 static void article_done(Article *art, int whichcount);
328 static void check_assign_articles(void);
329 static void queue_check_input_done(void);
330 static void check_reading_pause_resume(InputFile *ipf);
332 static void statemc_check_flushing_done(void);
333 static void statemc_check_backlog_done(void);
335 static void postfork(void);
336 static void period(void);
338 static void open_defer(void);
339 static void close_defer(void);
340 static void search_backlog_file(void);
341 static void preterminate(void);
342 static void raise_default(int signo) NORET;
343 static char *debug_report_ipf(InputFile *ipf);
345 static void inputfile_reading_start(InputFile *ipf);
346 static void inputfile_reading_stop(InputFile *ipf);
347 static void inputfile_reading_pause(InputFile *ipf);
348 static void inputfile_reading_resume(InputFile *ipf);
349 /* pause and resume are idempotent, and no-op if not done _reading_start */
351 static void filemon_start(InputFile *ipf);
352 static void filemon_stop(InputFile *ipf);
353 static void tailing_make_readable(InputFile *ipf);
355 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
356 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
358 static const oop_rd_style peer_rd_style;
359 static oop_rd_call peer_rd_err, peer_rd_ok;
362 /*----- configuration options -----*/
363 /* when changing defaults, remember to update the manpage */
365 static const char *sitename, *remote_host;
366 static const char *feedfile, *path_run, *path_cli, *path_cli_dir;
367 static int quiet_multiple=0;
368 static int interactive=0, try_filemon=1;
369 static int try_stream=1;
371 static const char *inndconffile;
373 static int max_connections=10;
374 static int max_queue_per_conn=200;
375 static int target_max_feedfile_size=100000;
376 static int period_seconds=30;
377 static int filepoll_seconds=5;
378 static int max_queue_per_ipf=-1;
380 static int connection_setup_timeout=200;
381 static int inndcomm_flush_timeout=100;
383 static double nocheck_thresh= 95.0; /* converted from percentage by main */
384 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
386 /* all these are initialised to seconds, and converted to periods in main */
387 static int reconnect_delay_periods=1000;
388 static int flushfail_retry_periods=1000;
389 static int backlog_retry_minperiods=100;
390 static int backlog_spontrescan_periods=300;
391 static int spontaneous_flush_periods=100000;
392 static int max_separated_periods=2000;
393 static int need_activity_periods=1000;
394 static int lowvol_thresh=3;
395 static int lowvol_periods=1000;
397 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
398 static int max_bad_data_initial= 30;
399 /* in one corrupt 4096-byte block the number of newlines has
400 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
403 /*----- statistics -----*/
405 typedef enum { /* in queue in conn->sent */
406 art_Unchecked, /* not checked, not sent checking */
407 art_Wanted, /* checked, wanted sent body as requested */
408 art_Unsolicited, /* - sent body without check */
412 static const char *const artstate_names[]=
413 { "Unchecked", "Wanted", "Unsolicited", 0 };
415 #define RESULT_COUNTS(RCS,RCN) \
424 #define RCI_TRIPLE_FMT_BASE "%d (id=%d,bod=%d,nc=%d)"
425 #define RCI_TRIPLE_VALS_BASE(counts,x) \
426 counts[art_Unchecked] x \
427 + counts[art_Wanted] x \
428 + counts[art_Unsolicited] x, \
429 counts[art_Unchecked] x \
430 , counts[art_Wanted] x \
431 , counts[art_Unsolicited] x
434 #define RC_INDEX(x) RC_##x,
435 RESULT_COUNTS(RC_INDEX, RC_INDEX)
440 /*----- transmission buffers -----*/
456 /*----- core operational data structure types -----*/
459 /* This is also an instance of struct oop_readable */
460 struct oop_readable readable; /* first */
461 oop_readable_call *readable_callback;
462 void *readable_callback_user;
465 Filemon_Perfile *filemon;
467 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
469 int skippinglong, paused, fake_readable;
472 long inprogress; /* includes queue.count and also articles in conns */
473 long autodefer; /* -1 means not doing autodefer */
475 int counts[art_MaxState][RCI_max];
476 int readcount_ok, readcount_blank, readcount_err, count_nooffer_missing;
491 #define SMS_LIST(X) \
499 enum StateMachineState {
500 #define SMS_DEF_ENUM(s) sm_##s,
501 SMS_LIST(SMS_DEF_ENUM)
504 static const char *sms_names[]= {
505 #define SMS_DEF_NAME(s) #s ,
506 SMS_LIST(SMS_DEF_NAME)
512 int fd; /* may be 0, meaning closed (during construction/destruction) */
513 oop_read *rd; /* likewise */
514 int oopwriting; /* since on_fd is not idempotent */
515 int max_queue, stream;
516 const char *quitting;
517 int since_activity; /* periods */
518 ArticleList waiting; /* not yet told peer */
519 ArticleList priority; /* peer says send it now */
520 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
521 struct iovec xmit[CONNIOVS];
522 XmitDetails xmitd[CONNIOVS];
527 /*----- general operational variables -----*/
529 /* main initialises */
530 static oop_source *loop;
531 static ConnList conns;
532 static char *path_lock, *path_flushing, *path_defer, *path_dump;
533 static char *globpat_backlog;
534 static pid_t self_pid;
535 static int *lowvol_perperiod;
536 static int lowvol_circptr;
537 static int lowvol_total; /* does not include current period */
539 /* statemc_init initialises */
540 static StateMachineState sms;
541 static int until_flush;
542 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
545 /* initialisation to 0 is good */
546 static int until_connect, until_backlog_nextscan;
547 static double accept_proportion;
548 static int nocheck, nocheck_reported, in_child;
550 /* for simulation, debugging, etc. */
551 int simulate_flush= -1;
553 /*========== logging ==========*/
555 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
556 static void logcore(int sysloglevel, const char *fmt, ...) {
558 if (interactive < 2) {
559 vsyslog(sysloglevel,fmt,al);
561 if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
562 vfprintf(stderr,fmt,al);
568 static void logv(int sysloglevel, const char *pfx, int errnoval,
569 const char *fmt, va_list al) PRINTF(5,0);
570 static void logv(int sysloglevel, const char *pfx, int errnoval,
571 const char *fmt, va_list al) {
572 char msgbuf[1024]; /* NB do not call xvasprintf here or you'll recurse */
573 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
574 msgbuf[sizeof(msgbuf)-1]= 0;
576 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
577 sysloglevel= LOG_ERR; /* run by wrong user, probably */
579 logcore(sysloglevel, "<%s>%s: %s%s%s",
580 sitename, pfx, msgbuf,
581 errnoval>=0 ? ": " : "",
582 errnoval>=0 ? strerror(errnoval) : "");
585 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
586 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
587 static void fn(const char *fmt, ...) { \
590 logv(sysloglevel, pfx, err, fmt, al); \
594 #define logwrap(fn, pfx, sysloglevel, err) \
595 static void fn(const char *fmt, ...) PRINTF(1,2); \
596 static void fn(const char *fmt, ...) { \
598 logv(sysloglevel, pfx, err, fmt, al); \
602 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
603 diewrap(die, " critical", LOG_CRIT, -1, 16);
605 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
606 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
608 logwrap(syswarn, " warning", LOG_WARNING, errno);
609 logwrap(warn, " warning", LOG_WARNING, -1);
611 logwrap(notice, " notice", LOG_NOTICE, -1);
612 logwrap(info, " info", LOG_INFO, -1);
613 logwrap(debug, " debug", LOG_DEBUG, -1);
616 /*========== utility functions etc. ==========*/
618 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
619 static char *xvasprintf(const char *fmt, va_list al) {
621 int rc= vasprintf(&str,fmt,al);
622 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
625 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
626 static char *xasprintf(const char *fmt, ...) {
628 char *str= xvasprintf(fmt,al);
633 static int close_perhaps(int *fd) {
634 if (*fd <= 0) return 0;
639 static void xclose(int fd, const char *what, const char *what2) {
641 if (r) sysdie("close %s%s",what,what2?what2:"");
643 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
644 if (*fd <= 0) return;
645 xclose(*fd,what,what2);
649 static pid_t xfork(const char *what) {
653 if (child==-1) sysfatal("cannot fork for %s",what);
654 debug("forked %s %ld", what, (unsigned long)child);
655 if (!child) postfork();
659 static void on_fd_read_except(int fd, oop_call_fd callback) {
660 loop->on_fd(loop, fd, OOP_READ, callback, 0);
661 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
663 static void cancel_fd_read_except(int fd) {
664 loop->cancel_fd(loop, fd, OOP_READ);
665 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
668 static void report_child_status(const char *what, int status) {
669 if (WIFEXITED(status)) {
670 int es= WEXITSTATUS(status);
672 warn("%s: child died with error exit status %d", what, es);
673 } else if (WIFSIGNALED(status)) {
674 int sig= WTERMSIG(status);
675 const char *sigstr= strsignal(sig);
676 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
678 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
680 warn("%s: child died due to unknown fatal signal %d%s",
681 what, sig, coredump);
683 warn("%s: child died with unknown wait status %d", what,status);
687 static int xwaitpid(pid_t *pid, const char *what) {
690 int r= kill(*pid, SIGKILL);
691 if (r) sysdie("cannot kill %s child", what);
693 pid_t got= waitpid(*pid, &status, 0);
694 if (got==-1) sysdie("cannot reap %s child", what);
695 if (got==0) die("cannot reap %s child", what);
702 static void *zxmalloc(size_t sz) {
703 void *p= xmalloc(sz);
708 static void xunlink(const char *path, const char *what) {
710 if (r) sysdie("can't unlink %s %s", path, what);
713 static time_t xtime(void) {
715 if (now==-1) sysdie("time(2) failed");
719 static void xsigaction(int signo, const struct sigaction *sa) {
720 int r= sigaction(signo,sa,0);
721 if (r) sysdie("sigaction failed for \"%s\"", strsignal(signo));
724 static void xsigsetdefault(int signo) {
726 memset(&sa,0,sizeof(sa));
727 sa.sa_handler= SIG_DFL;
728 xsigaction(signo,&sa);
731 static void xgettimeofday(struct timeval *tv_r) {
732 int r= gettimeofday(tv_r,0);
733 if (r) sysdie("gettimeofday(2) failed");
736 static void xsetnonblock(int fd, int nonblocking) {
737 int errnoval= oop_fd_nonblock(fd, nonblocking);
738 if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
741 static void check_isreg(const struct stat *stab, const char *path,
743 if (!S_ISREG(stab->st_mode))
744 die("%s %s not a plain file (mode 0%lo)",
745 what, path, (unsigned long)stab->st_mode);
748 static void xfstat(int fd, struct stat *stab_r, const char *what) {
749 int r= fstat(fd, stab_r);
750 if (r) sysdie("could not fstat %s", what);
753 static void xfstat_isreg(int fd, struct stat *stab_r,
754 const char *path, const char *what) {
755 xfstat(fd, stab_r, what);
756 check_isreg(stab_r, path, what);
759 static void xlstat_isreg(const char *path, struct stat *stab,
760 int *enoent_r /* 0 means ENOENT is fatal */,
762 int r= lstat(path, stab);
764 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
765 sysdie("could not lstat %s %s", what, path);
767 if (enoent_r) *enoent_r= 0;
768 check_isreg(stab, path, what);
771 static int samefile(const struct stat *a, const struct stat *b) {
772 assert(S_ISREG(a->st_mode));
773 assert(S_ISREG(b->st_mode));
774 return (a->st_ino == b->st_ino &&
775 a->st_dev == b->st_dev);
778 static char *sanitise(const char *input, int len) {
779 static char sanibuf[100]; /* returns pointer to this buffer! */
781 const char *p= input;
782 const char *endp= len>=0 ? input+len : 0;
786 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
787 int c= (!endp || p<endp) ? *p++ : 0;
788 if (!c) { *q++= '\''; *q=0; break; }
789 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
790 sprintf(q,"\\x%02x",c);
796 static int isewouldblock(int errnoval) {
797 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
800 /*========== command and control (CLI) connections ==========*/
802 static int cli_master;
804 typedef struct CliConn CliConn;
806 void (*destroy)(CliConn*);
812 struct sockaddr_un un;
817 static const oop_rd_style cli_rd_style= {
818 OOP_RD_DELIM_STRIP, '\n',
820 OOP_RD_SHORTREC_FORBID
823 static void cli_destroy(CliConn *cc) {
827 static void cli_checkouterr(CliConn *cc /* may destroy*/) {
828 if (ferror(cc->out) | fflush(cc->out)) {
829 info("CTRL%d write error %s", cc->fd, strerror(errno));
834 static void cli_prompt(CliConn *cc /* may destroy*/) {
835 fprintf(cc->out, "%s| ", sitename);
841 void (*f)(CliConn *cc, const CliCommand *ccmd,
842 const char *arg, size_t argsz);
847 static const CliCommand cli_commands[];
850 static void ccmd_##wh(CliConn *cc, const CliCommand *c, \
851 const char *arg, size_t argsz)
854 fputs("commands:\n", cc->out);
855 const CliCommand *ccmd;
856 for (ccmd=cli_commands; ccmd->cmd; ccmd++)
857 fprintf(cc->out, " %s\n", ccmd->cmd);
858 fputs("NB: permissible arguments are not shown above."
859 " Not all commands listed are safe. See innduct(8).\n", cc->out);
863 int ok= trigger_flush_ok("manual request");
864 if (!ok) fprintf(cc->out,"already flushing (state is %s)\n", sms_names[sms]);
869 notice("terminating (CTRL%d)",cc->fd);
870 raise_default(SIGTERM);
876 /* messing with our head: */
877 CCMD(period) { period(); }
878 CCMD(setintarg) { *(int*)c->xdata= atoi(arg); }
879 CCMD(setint) { *(int*)c->xdata= c->xval; }
880 CCMD(setint_period) { *(int*)c->xdata= c->xval; period(); }
882 static const CliCommand cli_commands[]= {
884 { "flush", ccmd_flush },
885 { "stop", ccmd_stop },
886 { "dump q", ccmd_dump, 0,0 },
887 { "dump a", ccmd_dump, 0,1 },
889 { "p", ccmd_period },
891 #define POKES(cmd,func) \
892 { cmd "flush", func, &until_flush, 1 }, \
893 { cmd "conn", func, &until_connect, 0 }, \
894 { cmd "blscan", func, &until_backlog_nextscan, 0 },
895 POKES("next ", ccmd_setint)
896 POKES("prod ", ccmd_setint_period)
898 { "pretend flush", ccmd_setintarg, &simulate_flush },
899 { "wedge blscan", ccmd_setint, &until_backlog_nextscan, -1 },
903 static void *cli_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
904 const char *errmsg, int errnoval,
905 const char *data, size_t recsz, void *cc_v) {
909 info("CTRL%d closed", cc->fd);
914 if (recsz == 0) goto prompt;
916 const CliCommand *ccmd;
917 for (ccmd=cli_commands; ccmd->cmd; ccmd++) {
918 int l= strlen(ccmd->cmd);
919 if (recsz < l) continue;
920 if (recsz > l && data[l] != ' ') continue;
921 if (memcmp(data, ccmd->cmd, l)) continue;
923 int argl= (int)recsz - (l+1);
924 ccmd->f(cc, ccmd, argl>=0 ? data+l+1 : 0, argl);
928 fputs("unknown command; h for help\n", cc->out);
935 static void *cli_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
936 const char *errmsg, int errnoval,
937 const char *data, size_t recsz, void *cc_v) {
940 info("CTRL%d read error %s", cc->fd, errmsg);
945 static int cli_conn_startup(CliConn *cc /* may destroy*/,
947 cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
948 if (!cc->rd) { warn("oop_rd_new_fd cli failed"); return -1; }
950 int er= oop_rd_read(cc->rd, &cli_rd_style, MAX_CLI_COMMAND,
953 if (er) { errno= er; syswarn("oop_rd_read cli failed"); return -1; }
955 info("CTRL%d %s ready", cc->fd, how);
960 static void cli_stdio_destroy(CliConn *cc) {
962 oop_rd_cancel(cc->rd);
963 errno= oop_rd_delete_tidy(cc->rd);
964 if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
969 static void cli_stdio(void) {
970 NEW_DECL(CliConn *,cc);
971 cc->destroy= cli_stdio_destroy;
975 int r= cli_conn_startup(cc,"stdio");
976 if (r) cc->destroy(cc);
979 static void cli_accepted_destroy(CliConn *cc) {
981 oop_rd_cancel(cc->rd);
982 oop_rd_delete_kill(cc->rd);
984 if (cc->out) { fclose(cc->out); cc->fd=0; }
985 close_perhaps(&cc->fd);
989 static void *cli_master_readable(oop_source *lp, int master,
990 oop_event ev, void *u) {
991 NEW_DECL(CliConn *,cc);
992 cc->destroy= cli_accepted_destroy;
994 cc->salen= sizeof(cc->sa);
995 cc->fd= accept(master, &cc->sa.sa, &cc->salen);
996 if (cc->fd<0) { syswarn("error accepting cli connection"); goto x; }
998 cc->out= fdopen(cc->fd, "w");
999 if (!cc->out) { syswarn("error fdopening accepted cli connection"); goto x; }
1001 int r= cli_conn_startup(cc, "accepted");
1004 return OOP_CONTINUE;
1008 return OOP_CONTINUE;
1011 #define NOCLI(...) do{ \
1012 syswarn("no cli listener, because failed to " __VA_ARGS__); \
1016 static void cli_init(void) {
1019 struct sockaddr_un un;
1022 memset(&sa,0,sizeof(sa));
1023 int maxlen= sizeof(sa.un.sun_path);
1026 info("control command line disabled");
1030 int pathlen= strlen(path_cli);
1031 if (pathlen > maxlen) {
1032 warn("no cli listener, because cli socket path %s too long (%d>%d)",
1033 path_cli, pathlen, maxlen);
1038 int r= mkdir(path_cli_dir, 0700);
1039 if (r && errno!=EEXIST)
1040 NOCLI("create cli socket directory %s", path_cli_dir);
1043 int r= unlink(path_cli);
1044 if (r && errno!=ENOENT)
1045 NOCLI("remove old cli socket %s", path_cli);
1047 cli_master= socket(PF_UNIX, SOCK_STREAM, 0);
1048 if (cli_master<0) NOCLI("create new cli master socket");
1050 int sl= pathlen + offsetof(struct sockaddr_un, sun_path);
1051 sa.un.sun_family= AF_UNIX;
1052 memcpy(sa.un.sun_path, path_cli, pathlen);
1054 r= bind(cli_master, &sa.sa, sl);
1055 if (r) NOCLI("bind to cli socket path %s", sa.un.sun_path);
1057 r= listen(cli_master, 5);
1058 if (r) NOCLI("listen to cli master socket");
1060 xsetnonblock(cli_master, 1);
1062 loop->on_fd(loop, cli_master, OOP_READ, cli_master_readable, 0);
1063 info("cli ready, listening on %s", path_cli);
1068 xclose_perhaps(&cli_master, "cli master",0);
1072 /*========== management of connections ==========*/
1074 static void reconnect_blocking_event(void) {
1075 until_connect= reconnect_delay_periods;
1078 static void conn_closefd(Conn *conn, const char *msgprefix) {
1079 int r= close_perhaps(&conn->fd);
1080 if (r) info("C%d %serror closing socket: %s",
1081 conn->fd, msgprefix, strerror(errno));
1084 static int conn_busy(Conn *conn) {
1086 conn->waiting.count ||
1087 conn->priority.count ||
1092 static void conn_dispose(Conn *conn) {
1095 oop_rd_cancel(conn->rd);
1096 oop_rd_delete_kill(conn->rd);
1100 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1101 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
1103 conn_closefd(conn,"");
1107 static void *conn_exception(oop_source *lp, int fd,
1108 oop_event ev, void *conn_v) {
1111 assert(fd == conn->fd);
1112 assert(ev == OOP_EXCEPTION);
1113 int r= read(conn->fd, &ch, 1);
1114 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1115 else connfail(conn,"exceptional condition on socket (peer sent urgent"
1116 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1117 return OOP_CONTINUE;
1120 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1121 int requeue[art_MaxState];
1122 memset(requeue,0,sizeof(requeue));
1126 while ((art= LIST_REMHEAD(conn->priority)))
1127 LIST_ADDTAIL(art->ipf->queue, art);
1129 while ((art= LIST_REMHEAD(conn->waiting)))
1130 LIST_ADDTAIL(art->ipf->queue, art);
1132 while ((art= LIST_REMHEAD(conn->sent))) {
1133 requeue[art->state]++;
1134 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1135 LIST_ADDTAIL(art->ipf->queue,art);
1136 check_reading_pause_resume(art->ipf);
1141 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1144 LIST_REMOVE(conns,conn);
1146 char *m= xvasprintf(fmt,al);
1147 warn("C%d (now %d) connection failed requeueing " RCI_TRIPLE_FMT_BASE ": %s",
1148 conn->fd, conns.count, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1151 reconnect_blocking_event();
1153 check_assign_articles();
1156 static void connfail(Conn *conn, const char *fmt, ...) {
1159 vconnfail(conn,fmt,al);
1163 static void conn_idle_close(Conn *conn, const char *why) {
1164 static const char quitcmd[]= "QUIT\r\n";
1165 int todo= sizeof(quitcmd)-1;
1166 const char *p= quitcmd;
1168 int r= write(conn->fd, p, todo);
1170 if (isewouldblock(errno))
1171 connfail(conn, "blocked writing QUIT to idle connection");
1173 connfail(conn, "failed to write QUIT to idle connection: %s",
1180 conn->quitting= why;
1181 conn->since_activity= 0;
1182 debug("C%d is idle (%s), quitting", conn->fd, why);
1189 * For our last connection, we also shut it down if we have had
1190 * less than K in the last L
1192 static void check_idle_conns(void) {
1195 int volthisperiod= lowvol_perperiod[lowvol_circptr];
1197 lowvol_circptr %= lowvol_periods;
1198 lowvol_total += volthisperiod;
1199 lowvol_total -= lowvol_perperiod[lowvol_circptr];
1200 lowvol_perperiod[lowvol_circptr]= 0;
1203 conn->since_activity++;
1207 if (conn->since_activity <= need_activity_periods) continue;
1209 /* We need to shut this down */
1211 connfail(conn,"timed out waiting for response to QUIT (%s)",
1213 else if (conn->sent.count)
1214 connfail(conn,"timed out waiting for responses");
1215 else if (conn->waiting.count || conn->priority.count)
1216 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1217 else if (conn->xmitu)
1218 connfail(conn,"peer has been sending responses"
1219 " before receiving our commands!");
1221 conn_idle_close(conn, "no activity");
1226 conn= LIST_HEAD(conns);
1227 if (!volthisperiod &&
1229 lowvol_total < lowvol_thresh &&
1231 conn_idle_close(conn, "low volume");
1234 /*---------- making new connections ----------*/
1236 static pid_t connecting_child;
1237 static int connecting_fdpass_sock;
1239 static void connect_attempt_discard(void) {
1240 if (connecting_child) {
1241 int status= xwaitpid(&connecting_child, "connect");
1242 if (!(WIFEXITED(status) ||
1243 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1244 report_child_status("connect", status);
1246 if (connecting_fdpass_sock) {
1247 cancel_fd_read_except(connecting_fdpass_sock);
1248 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1252 #define PREP_DECL_MSG_CMSG(msg) \
1254 struct iovec msgiov; \
1255 msgiov.iov_base= &msgbyte; \
1256 msgiov.iov_len= 1; \
1257 struct msghdr msg; \
1258 memset(&msg,0,sizeof(msg)); \
1259 char msg##cbuf[CMSG_SPACE(sizeof(int))]; \
1260 msg.msg_iov= &msgiov; \
1261 msg.msg_iovlen= 1; \
1262 msg.msg_control= msg##cbuf; \
1263 msg.msg_controllen= sizeof(msg##cbuf);
1265 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1268 assert(fd == connecting_fdpass_sock);
1270 PREP_DECL_MSG_CMSG(msg);
1272 ssize_t rs= recvmsg(fd, &msg, 0);
1274 if (isewouldblock(errno)) return OOP_CONTINUE;
1275 syswarn("failed to read socket from connecting child");
1280 LIST_INIT(conn->waiting);
1281 LIST_INIT(conn->priority);
1282 LIST_INIT(conn->sent);
1284 struct cmsghdr *h= 0;
1285 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1287 int status= xwaitpid(&connecting_child, "connect child (broken)");
1289 if (WIFEXITED(status)) {
1290 if (WEXITSTATUS(status) != 0 &&
1291 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1292 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1293 /* child already reported the problem */;
1295 if (e == OOP_EXCEPTION)
1296 warn("connect: connection child exited code %d but"
1297 " unexpected exception on fdpass socket",
1298 WEXITSTATUS(status));
1300 warn("connect: connection child exited code %d but"
1302 WEXITSTATUS(status), (int)rs);
1304 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1305 warn("connect: connection attempt timed out");
1307 report_child_status("connect", status);
1312 #define CHK(field, val) \
1313 if (h->cmsg_##field != val) { \
1314 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1315 h->cmsg_##field, val); \
1318 CHK(level, SOL_SOCKET);
1319 CHK(type, SCM_RIGHTS);
1320 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1323 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1325 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1328 pid_t got= waitpid(connecting_child, &status, 0);
1329 if (got==-1) sysdie("connect: real wait for child");
1330 assert(got == connecting_child);
1331 connecting_child= 0;
1333 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1334 int es= WEXITSTATUS(status);
1336 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1337 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1339 fatal("connect: child gave unexpected exit status %d", es);
1343 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1345 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1346 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1347 if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1348 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1350 &peer_rd_err, conn);
1351 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1353 LIST_ADDHEAD(conns, conn);
1354 notice("C%d (now %d) connected %s",
1355 conn->fd, conns.count, conn->stream ? "streaming" : "plain");
1357 connect_attempt_discard();
1358 check_assign_articles();
1359 return OOP_CONTINUE;
1363 connect_attempt_discard();
1364 reconnect_blocking_event();
1365 return OOP_CONTINUE;
1368 static int allow_connect_start(void) {
1369 return conns.count < max_connections
1370 && !connecting_child
1374 static void connect_start(void) {
1375 assert(!connecting_child);
1376 assert(!connecting_fdpass_sock);
1378 info("starting connection attempt");
1379 int ok_until_connect= until_connect;
1380 reconnect_blocking_event();
1383 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1384 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1386 connecting_child= xfork("connection");
1388 if (!connecting_child) {
1389 FILE *cn_from, *cn_to;
1390 char buf[NNTP_STRLEN+100];
1391 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1393 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1395 alarm(connection_setup_timeout);
1396 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1400 unsigned char c= buf[l-1];
1401 if (!isspace(c)) break;
1402 if (c=='\n' || c=='\r') stripped=1;
1406 sysfatal("connect: connection attempt failed");
1409 fatal("connect: %s: %s", stripped ? "rejected" : "failed",
1413 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1414 sysfatal("connect: authentication failed");
1416 if (fputs("MODE STREAM\r\n", cn_to)==EOF ||
1418 sysfatal("connect: could not send MODE STREAM");
1419 buf[sizeof(buf)-1]= 0;
1420 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1421 if (ferror(cn_from))
1422 sysfatal("connect: could not read response to MODE STREAM");
1424 fatal("connect: connection close in response to MODE STREAM");
1429 fatal("connect: response to MODE STREAM is too long: %.100s...",
1431 l--; if (l>0 && buf[l-1]=='\r') l--;
1434 int rcode= strtoul(buf,&ep,10);
1436 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf,-1));
1440 exitstatus= CONNCHILD_ESTATUS_STREAM;
1446 warn("connect: unexpected response to MODE STREAM: %.50s",
1452 int fd= fileno(cn_from);
1454 PREP_DECL_MSG_CMSG(msg);
1455 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1456 cmsg->cmsg_level= SOL_SOCKET;
1457 cmsg->cmsg_type= SCM_RIGHTS;
1458 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1459 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1461 msg.msg_controllen= cmsg->cmsg_len;
1462 r= sendmsg(socks[1], &msg, 0);
1463 if (r<0) sysdie("sendmsg failed for new connection");
1464 if (r!=1) die("sendmsg for new connection gave wrong result %d",r);
1469 xclose(socks[1], "connecting fdpass child's socket",0);
1470 connecting_fdpass_sock= socks[0];
1471 xsetnonblock(connecting_fdpass_sock, 1);
1472 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1475 until_connect= ok_until_connect;
1478 /*---------- assigning articles to conns, and transmitting ----------*/
1480 static Article *dequeue_from(int peek, InputFile *ipf) {
1482 if (peek) return LIST_HEAD(ipf->queue);
1484 Article *art= LIST_REMHEAD(ipf->queue);
1486 check_reading_pause_resume(ipf);
1490 static Article *dequeue(int peek) {
1492 art= dequeue_from(peek, flushing_input_file); if (art) return art;
1493 art= dequeue_from(peek, backlog_input_file); if (art) return art;
1494 art= dequeue_from(peek, main_input_file); if (art) return art;
1498 static void check_assign_articles(void) {
1504 int spare=0, inqueue=0;
1506 /* Find a connection to offer this article. We prefer a busy
1507 * connection to an idle one, provided it's not full. We take the
1508 * first (oldest) and since that's stable, it will mean we fill up
1509 * connections in order. That way if we have too many
1510 * connections, the spare ones will go away eventually.
1513 if (walk->quitting) continue;
1514 inqueue= walk->sent.count + walk->priority.count
1515 + walk->waiting.count;
1516 spare= walk->max_queue - inqueue;
1517 assert(inqueue <= max_queue_per_conn);
1519 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1520 else if (spare>0) /*working*/ { use= walk; break; }
1523 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1525 Article *art= dequeue(0);
1527 LIST_ADDTAIL(use->waiting, art);
1528 lowvol_perperiod[lowvol_circptr]++;
1531 conn_maybe_write(use);
1532 } else if (allow_connect_start()) {
1541 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1542 conn_maybe_write(u);
1543 return OOP_CONTINUE;
1546 static void conn_maybe_write(Conn *conn) {
1548 conn_make_some_xmits(conn);
1550 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1551 conn->oopwriting= 0;
1555 void *rp= conn_write_some_xmits(conn);
1556 if (rp==OOP_CONTINUE) {
1557 if (!conn->oopwriting) {
1558 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1559 conn->oopwriting= 1;
1562 } else if (rp==OOP_HALT) {
1565 /* transmitted everything */
1572 /*---------- expiry, flow control and deferral ----------*/
1575 * flow control notes
1576 * to ensure articles go away eventually
1577 * separate queue for each input file
1579 * every period, check head of backlog queue for expiry with SMretrieve
1580 * if too old: discard, and check next article
1581 * also check every backlog article as we read it
1583 * after too long in SEPARATED/DROPPING ie Separated/Finishing/Dropping
1584 * one-off: eat queued articles from flushing and write them to defer
1585 * one-off: connfail all connections which have any articles from flushing
1586 * newly read articles from flushing go straight to defer
1587 * this should take care of it and get us out of this state
1588 * to avoid filling up ram needlessly
1590 * limit number of queued articles for each ipf
1591 * pause/resume inputfile tailing
1594 static void check_reading_pause_resume(InputFile *ipf) {
1595 if (ipf->queue.count >= max_queue_per_ipf)
1596 inputfile_reading_pause(ipf);
1598 inputfile_reading_resume(ipf);
1601 static void article_defer(Article *art /* not on a queue */, int whichcount) {
1603 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1605 sysfatal("write to defer file %s",path_defer);
1606 article_done(art, whichcount);
1609 static int article_check_expired(Article *art /* must be queued, not conn */) {
1610 ARTHANDLE *artdata= SMretrieve(art->token, RETR_STAT);
1611 if (artdata) { SMfreearticle(artdata); return 0; }
1613 LIST_REMOVE(art->ipf->queue, art);
1615 art->ipf->count_nooffer_missing++;
1616 article_done(art,-1);
1620 static void inputfile_queue_check_expired(InputFile *ipf) {
1624 Article *art= LIST_HEAD(ipf->queue);
1625 int exp= article_check_expired(art);
1628 check_reading_pause_resume(ipf);
1631 static void article_autodefer(InputFile *ipf, Article *art) {
1633 article_defer(art,-1);
1636 static int has_article_in(const ArticleList *al, InputFile *ipf) {
1638 for (art=LIST_HEAD(*al); art; art=LIST_NEXT(art))
1639 if (art->ipf == ipf) return 1;
1643 static void autodefer_input_file_articles(InputFile *ipf) {
1645 while ((art= LIST_REMHEAD(ipf->queue)))
1646 article_autodefer(ipf, art);
1649 static void autodefer_input_file(InputFile *ipf) {
1650 static const char *const abandon= "stuck";
1653 autodefer_input_file_articles(ipf);
1655 if (ipf->inprogress) {
1658 if (has_article_in(&walk->waiting, ipf) ||
1659 has_article_in(&walk->priority, ipf) ||
1660 has_article_in(&walk->sent, ipf))
1661 walk->quitting= abandon;
1663 while (ipf->inprogress) {
1665 if (walk->quitting == abandon) goto found;
1666 abort(); /* where are they ?? */
1669 connfail(walk, "connection is stuck or crawling,"
1670 " and we need to finish flush");
1671 autodefer_input_file_articles(ipf);
1675 check_reading_pause_resume(ipf);
1678 /*========== article transmission ==========*/
1680 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1681 XmitKind kind) { /* caller must then fill in details */
1682 struct iovec *v= &conn->xmit[conn->xmitu];
1683 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1684 v->iov_base= (char*)data;
1690 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1691 xmit_core(conn,data,len, xk_Const);
1693 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1695 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1696 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1700 static void xmit_free(XmitDetails *d) {
1702 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1703 case xk_Const: break;
1708 static void *conn_write_some_xmits(Conn *conn) {
1710 * 0: nothing more to write, no need to call us again
1711 * OOP_CONTINUE: more to write but fd not writeable
1712 * OOP_HALT: disaster, have destroyed conn
1715 int count= conn->xmitu;
1716 if (!count) return 0;
1718 if (count > IOV_MAX) count= IOV_MAX;
1719 ssize_t rs= writev(conn->fd, conn->xmit, count);
1721 if (isewouldblock(errno)) return OOP_CONTINUE;
1722 connfail(conn, "write failed: %s", strerror(errno));
1728 for (done=0; rs; ) {
1729 assert(done<conn->xmitu);
1730 struct iovec *vp= &conn->xmit[done];
1731 XmitDetails *dp= &conn->xmitd[done];
1732 if (rs >= vp->iov_len) {
1734 xmit_free(dp); /* vp->iov_len -= vp->iov_len, etc. */
1737 vp->iov_base= (char*)vp->iov_base + rs;
1739 break; /* rs -= rs */
1742 int newu= conn->xmitu - done;
1743 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1744 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1749 static void conn_make_some_xmits(Conn *conn) {
1751 if (conn->xmitu+5 > CONNIOVS)
1754 Article *art= LIST_REMHEAD(conn->priority);
1755 if (!art) art= LIST_REMHEAD(conn->waiting);
1758 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1759 /* actually send it */
1761 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1764 art->state == art_Unchecked ? art_Unsolicited :
1765 art->state == art_Wanted ? art_Wanted :
1768 if (!artdata) art->missing= 1;
1769 art->ipf->counts[art->state][ artdata ? RC_sent : RC_missing ]++;
1773 XMIT_LITERAL("TAKETHIS ");
1774 xmit_noalloc(conn, art->messageid, art->midlen);
1775 XMIT_LITERAL("\r\n");
1776 xmit_artbody(conn, artdata);
1778 article_done(art, -1);
1782 /* we got 235 from IHAVE */
1784 xmit_artbody(conn, artdata);
1786 XMIT_LITERAL(".\r\n");
1790 LIST_ADDTAIL(conn->sent, art);
1796 XMIT_LITERAL("CHECK ");
1798 XMIT_LITERAL("IHAVE ");
1799 xmit_noalloc(conn, art->messageid, art->midlen);
1800 XMIT_LITERAL("\r\n");
1802 assert(art->state == art_Unchecked);
1803 art->ipf->counts[art->state][RC_sent]++;
1804 LIST_ADDTAIL(conn->sent, art);
1809 /*========== handling responses from peer ==========*/
1811 static const oop_rd_style peer_rd_style= {
1812 OOP_RD_DELIM_STRIP, '\n',
1814 OOP_RD_SHORTREC_FORBID
1817 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1818 const char *errmsg, int errnoval,
1819 const char *data, size_t recsz, void *conn_v) {
1821 connfail(conn, "error receiving from peer: %s", errmsg);
1822 return OOP_CONTINUE;
1825 static Article *article_reply_check(Conn *conn, const char *response,
1826 int code_indicates_streaming,
1828 /* 1:yes, -1:no, 0:dontcare */,
1829 const char *sanitised_response) {
1830 Article *art= LIST_HEAD(conn->sent);
1834 "peer gave unexpected response when no commands outstanding: %s",
1835 sanitised_response);
1839 if (code_indicates_streaming) {
1840 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1841 if (!conn->stream) {
1842 connfail(conn, "peer gave streaming response code "
1843 " to IHAVE or subsequent body: %s", sanitised_response);
1846 const char *got_mid= response+4;
1847 int got_midlen= strcspn(got_mid, " \n\r");
1848 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1849 connfail(conn, "peer gave streaming response with syntactically invalid"
1850 " messageid: %s", sanitised_response);
1853 if (got_midlen != art->midlen ||
1854 memcmp(got_mid, art->messageid, got_midlen)) {
1855 connfail(conn, "peer gave streaming response code to wrong article -"
1856 " probable synchronisation problem; we offered: %s;"
1858 art->messageid, sanitised_response);
1863 connfail(conn, "peer gave non-streaming response code to"
1864 " CHECK/TAKETHIS: %s", sanitised_response);
1869 if (must_have_sent>0 && art->state < art_Wanted) {
1870 connfail(conn, "peer says article accepted but"
1871 " we had not sent the body: %s", sanitised_response);
1874 if (must_have_sent<0 && art->state >= art_Wanted) {
1875 connfail(conn, "peer says please sent the article but we just did: %s",
1876 sanitised_response);
1880 Article *art_again= LIST_REMHEAD(conn->sent);
1881 assert(art_again == art);
1885 static void update_nocheck(int accepted) {
1886 accept_proportion *= nocheck_decay;
1887 accept_proportion += accepted * (1.0 - nocheck_decay);
1888 int new_nocheck= accept_proportion >= nocheck_thresh;
1889 if (new_nocheck && !nocheck_reported) {
1890 notice("entering nocheck mode for the first time");
1891 nocheck_reported= 1;
1892 } else if (new_nocheck != nocheck) {
1893 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1895 nocheck= new_nocheck;
1898 static void article_done(Article *art, int whichcount) {
1899 if (whichcount>=0 && !art->missing)
1900 art->ipf->counts[art->state][whichcount]++;
1902 if (whichcount == RC_accepted) update_nocheck(1);
1903 else if (whichcount == RC_unwanted) update_nocheck(0);
1905 InputFile *ipf= art->ipf;
1907 while (art->blanklen) {
1908 static const char spaces[]=
1918 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1919 int r= pwrite(ipf->fd, spaces, w, art->offset);
1921 if (errno==EINTR) continue;
1922 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1923 art->messageid, art->blanklen,
1924 (unsigned long)art->offset, ipf->path);
1926 assert(r>=0 && r<=w);
1932 assert(ipf->inprogress >= 0);
1935 if (!ipf->inprogress && ipf != main_input_file)
1936 queue_check_input_done();
1939 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1940 const char *errmsg, int errnoval,
1941 const char *data, size_t recsz, void *conn_v) {
1944 if (ev == OOP_RD_EOF) {
1945 connfail(conn, "unexpected EOF from peer");
1946 return OOP_CONTINUE;
1948 assert(ev == OOP_RD_OK);
1950 char *sani= sanitise(data,-1);
1953 unsigned long code= strtoul(data, &ep, 10);
1954 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1955 connfail(conn, "badly formatted response from peer: %s", sani);
1956 return OOP_CONTINUE;
1959 int busy= conn_busy(conn);
1961 if (conn->quitting) {
1962 if (code!=205 && code!=400) {
1963 connfail(conn, "peer gave unexpected response to QUIT (%s): %s",
1964 conn->quitting, sani);
1966 LIST_REMOVE(conns,conn);
1967 notice("C%d (now %d) idle connection closed (%s)",
1968 conn->fd, conns.count, conn->quitting);
1972 return OOP_CONTINUE;
1975 conn->since_activity= 0;
1978 #define GET_ARTICLE(musthavesent) do{ \
1979 art= article_reply_check(conn, data, code_streaming, musthavesent, sani); \
1980 if (!art) return OOP_CONTINUE; /* reply_check has failed the conn */ \
1983 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) do{ \
1984 code_streaming= (streaming); \
1985 GET_ARTICLE(musthavesent); \
1986 article_done(art, RC_##how); \
1990 #define PEERBADMSG(m) do { \
1991 connfail(conn, m ": %s", sani); return OOP_CONTINUE; \
1994 int code_streaming= 0;
1998 default: PEERBADMSG("peer sent unexpected message");
2002 PEERBADMSG("peer timed us out or stopped accepting articles");
2004 LIST_REMOVE(conns,conn);
2005 notice("C%d (now %d) idle connection closed by peer",
2006 conns.count, conn->fd);
2008 return OOP_CONTINUE;
2010 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
2011 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
2013 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
2014 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
2016 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
2017 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
2019 case 238: /* CHECK says send it */
2021 case 335: /* IHAVE says send it */
2023 assert(art->state == art_Unchecked);
2024 art->ipf->counts[art->state][RC_accepted]++;
2025 art->state= art_Wanted;
2026 LIST_ADDTAIL(conn->priority, art);
2029 case 431: /* CHECK or TAKETHIS says try later */
2031 case 436: /* IHAVE says try later */
2033 article_defer(art, RC_deferred);
2039 conn_maybe_write(conn);
2040 check_assign_articles();
2041 return OOP_CONTINUE;
2045 /*========== monitoring of input files ==========*/
2047 static void feedfile_eof(InputFile *ipf) {
2048 assert(ipf != main_input_file); /* promised by tailing_try_read */
2049 inputfile_reading_stop(ipf);
2051 if (ipf == flushing_input_file) {
2052 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2053 if (main_input_file) inputfile_reading_start(main_input_file);
2054 statemc_check_flushing_done();
2055 } else if (ipf == backlog_input_file) {
2056 statemc_check_backlog_done();
2058 abort(); /* supposed to wait rather than get EOF on main input file */
2062 static InputFile *open_input_file(const char *path) {
2063 int fd= open(path, O_RDWR);
2065 if (errno==ENOENT) return 0;
2066 sysfatal("unable to open input file %s", path);
2070 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
2071 memset(ipf,0,sizeof(*ipf));
2075 LIST_INIT(ipf->queue);
2076 strcpy(ipf->path, path);
2081 static void close_input_file(InputFile *ipf) { /* does not free */
2082 assert(!ipf->readable_callback); /* must have had ->on_cancel */
2083 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
2084 assert(!ipf->rd); /* must have had inputfile_reading_stop */
2085 assert(!ipf->inprogress); /* no dangling pointers pointing here */
2086 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
2090 /*---------- dealing with articles read in the input file ----------*/
2092 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
2093 const char *data, const char *how) {
2094 warn("corrupted file: %s, offset %lu: %s: in %s",
2095 ipf->path, (unsigned long)offset, how, sanitise(data,-1));
2096 ipf->readcount_err++;
2097 if (ipf->readcount_err > max_bad_data_initial +
2098 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
2099 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
2100 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
2101 return OOP_CONTINUE;
2104 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
2105 oop_rd_event ev, const char *errmsg,
2106 int errnoval, const char *data, size_t recsz,
2108 InputFile *ipf= ipf_v;
2109 assert(ev == OOP_RD_SYSTEM);
2111 sysdie("error reading input file: %s, offset %lu",
2112 ipf->path, (unsigned long)ipf->offset);
2115 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
2116 oop_rd_event ev, const char *errmsg,
2117 int errnoval, const char *data, size_t recsz,
2119 InputFile *ipf= ipf_v;
2121 char tokentextbuf[sizeof(TOKEN)*2+3];
2123 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
2125 off_t old_offset= ipf->offset;
2126 ipf->offset += recsz + !!(ev == OOP_RD_OK);
2128 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
2130 if (ev==OOP_RD_PARTREC)
2131 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
2132 /* but process it anyway */
2134 if (ipf->skippinglong) {
2135 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
2136 return OOP_CONTINUE;
2138 if (ev==OOP_RD_LONG) {
2139 ipf->skippinglong= 1;
2140 X_BAD_DATA("overly long line");
2143 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
2144 if (!recsz) X_BAD_DATA("empty line");
2147 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
2148 ipf->readcount_blank++;
2149 return OOP_CONTINUE;
2152 char *space= strchr(data,' ');
2153 int tokenlen= space-data;
2154 int midlen= (int)recsz-tokenlen-1;
2155 if (midlen <= 2) X_BAD_DATA("no room for messageid");
2156 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
2158 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
2159 memcpy(tokentextbuf, data, tokenlen);
2160 tokentextbuf[tokenlen]= 0;
2161 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
2163 ipf->readcount_ok++;
2165 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
2166 memset(art,0,sizeof(*art));
2167 art->state= art_Unchecked;
2168 art->midlen= midlen;
2169 art->ipf= ipf; ipf->inprogress++;
2170 art->token= TextToToken(tokentextbuf);
2171 art->offset= old_offset;
2172 art->blanklen= recsz;
2173 strcpy(art->messageid, space+1);
2174 LIST_ADDTAIL(ipf->queue, art);
2176 if (ipf->autodefer >= 0)
2177 article_autodefer(ipf, art);
2178 else if (ipf==backlog_input_file)
2179 article_check_expired(art);
2181 if (sms==sm_NORMAL && ipf==main_input_file &&
2182 ipf->offset >= target_max_feedfile_size)
2183 statemc_start_flush("feed file size");
2185 check_assign_articles(); /* may destroy conn but that's OK */
2186 check_reading_pause_resume(ipf);
2187 return OOP_CONTINUE;
2190 /*========== tailing input file ==========*/
2192 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
2194 /* lifetime of ipf here is OK because destruction will cause
2195 * on_cancel which will cancel this callback */
2196 InputFile *ipf= user;
2198 if (!ipf->fake_readable) return OOP_CONTINUE;
2200 /* we just keep calling readable until our caller (oop_rd)
2201 * has called try_read, and try_read has found EOF so given EAGAIN */
2202 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
2204 return ipf->readable_callback(loop, &ipf->readable,
2205 ipf->readable_callback_user);
2208 static void tailing_on_cancel(struct oop_readable *rable) {
2209 InputFile *ipf= (void*)rable;
2211 if (ipf->filemon) filemon_stop(ipf);
2212 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
2213 ipf->readable_callback= 0;
2216 static void tailing_make_readable(InputFile *ipf) {
2217 if (!ipf || !ipf->readable_callback) /* so callers can be naive */
2219 ipf->fake_readable= 1;
2220 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
2223 static int tailing_on_readable(struct oop_readable *rable,
2224 oop_readable_call *cb, void *user) {
2225 InputFile *ipf= (void*)rable;
2227 tailing_on_cancel(rable);
2228 ipf->readable_callback= cb;
2229 ipf->readable_callback_user= user;
2231 tailing_make_readable(ipf);
2235 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
2237 InputFile *ipf= (void*)rable;
2239 ssize_t r= read(ipf->fd, buffer, length);
2241 if (errno==EINTR) continue;
2242 ipf->fake_readable= 0;
2246 if (ipf==main_input_file) {
2248 ipf->fake_readable= 0;
2250 } else if (ipf==flushing_input_file) {
2252 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2253 } else if (ipf==backlog_input_file) {
2263 /*---------- filemon implemented with inotify ----------*/
2265 #if defined(HAVE_SYS_INOTIFY_H) && !defined(HAVE_FILEMON)
2266 #define HAVE_FILEMON
2268 #include <sys/inotify.h>
2270 static int filemon_inotify_fd;
2271 static int filemon_inotify_wdmax;
2272 static InputFile **filemon_inotify_wd2ipf;
2274 struct Filemon_Perfile {
2278 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
2279 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
2280 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
2282 if (wd >= filemon_inotify_wdmax) {
2284 filemon_inotify_wd2ipf= xrealloc(filemon_inotify_wd2ipf,
2285 sizeof(*filemon_inotify_wd2ipf) * newmax);
2286 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
2287 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
2288 filemon_inotify_wdmax= newmax;
2291 assert(!filemon_inotify_wd2ipf[wd]);
2292 filemon_inotify_wd2ipf[wd]= ipf;
2294 debug("filemon inotify startfile %p wd=%d wdmax=%d",
2295 ipf, wd, filemon_inotify_wdmax);
2300 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
2302 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
2303 int r= inotify_rm_watch(filemon_inotify_fd, wd);
2304 if (r) sysdie("inotify_rm_watch");
2305 filemon_inotify_wd2ipf[wd]= 0;
2308 static void *filemon_inotify_readable(oop_source *lp, int fd,
2309 oop_event e, void *u) {
2310 struct inotify_event iev;
2312 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
2314 if (isewouldblock(errno)) break;
2315 sysdie("read from inotify master");
2316 } else if (r==sizeof(iev)) {
2317 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
2319 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
2321 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
2322 /*debug("filemon inotify readable read %p wd=%d", ipf, iev.wd);*/
2323 tailing_make_readable(ipf);
2325 return OOP_CONTINUE;
2328 static int filemon_method_init(void) {
2329 filemon_inotify_fd= inotify_init();
2330 if (filemon_inotify_fd<0) {
2331 syswarn("filemon/inotify: inotify_init failed");
2334 xsetnonblock(filemon_inotify_fd, 1);
2335 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable, 0);
2337 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2341 static void filemon_method_dump_info(FILE *f) {
2343 fprintf(f,"inotify");
2344 DUMPV("%d",,filemon_inotify_fd);
2345 DUMPV("%d",,filemon_inotify_wdmax);
2346 for (i=0; i<filemon_inotify_wdmax; i++)
2347 fprintf(f," wd2ipf[%d]=%p\n", i, filemon_inotify_wd2ipf[i]);
2350 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2352 /*---------- filemon dummy implementation ----------*/
2354 #if !defined(HAVE_FILEMON)
2356 struct Filemon_Perfile { int dummy; };
2358 static int filemon_method_init(void) {
2359 warn("filemon/dummy: no filemon method compiled in");
2362 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2363 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2364 static void filemon_method_dump_info(FILE *f) { fprintf(f,"dummy\n"); }
2366 #endif /* !HAVE_FILEMON */
2368 /*---------- filemon generic interface ----------*/
2370 static void filemon_start(InputFile *ipf) {
2371 assert(!ipf->filemon);
2374 filemon_method_startfile(ipf, ipf->filemon);
2377 static void filemon_stop(InputFile *ipf) {
2378 if (!ipf->filemon) return;
2379 filemon_method_stopfile(ipf, ipf->filemon);
2384 /*---------- interface to start and stop an input file ----------*/
2386 static const oop_rd_style feedfile_rdstyle= {
2387 OOP_RD_DELIM_STRIP, '\n',
2389 OOP_RD_SHORTREC_LONG,
2392 static void inputfile_reading_resume(InputFile *ipf) {
2393 if (!ipf->rd) return;
2394 if (!ipf->paused) return;
2396 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2397 feedfile_got_article,ipf, feedfile_read_err, ipf);
2398 if (r) sysdie("unable start reading feedfile %s",ipf->path);
2403 static void inputfile_reading_pause(InputFile *ipf) {
2404 if (!ipf->rd) return;
2405 if (ipf->paused) return;
2406 oop_rd_cancel(ipf->rd);
2410 static void inputfile_reading_start(InputFile *ipf) {
2412 ipf->readable.on_readable= tailing_on_readable;
2413 ipf->readable.on_cancel= tailing_on_cancel;
2414 ipf->readable.try_read= tailing_try_read;
2415 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2416 ipf->readable.delete_kill= 0;
2418 ipf->readable_callback= 0;
2419 ipf->readable_callback_user= 0;
2421 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2425 inputfile_reading_resume(ipf);
2428 static void inputfile_reading_stop(InputFile *ipf) {
2430 inputfile_reading_pause(ipf);
2431 oop_rd_delete(ipf->rd);
2433 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2437 /*========== interaction with innd - state machine ==========*/
2439 /* See official state diagram at top of file. We implement
2450 |`---------------------------------------------------.
2452 |`---------------- - - - |
2453 D ENOENT | D EXISTS see OVERALL STATES diagram |
2454 | for full startup logic |
2457 | ============ try to |
2463 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
2464 ^ | hardlink F to D |
2467 | | our handle onto F is now onto D |
2470 | |<-------------------<---------------------<---------+
2472 | | spawn inndcomm flush |
2474 | ================== |
2475 | FLUSHING[-ABSENT] |
2477 | main D tail/none |
2478 | ================== |
2480 | | INNDCOMM FLUSH FAILS ^
2481 | |`----------------------->----------. |
2483 | | NO SUCH SITE V |
2484 ^ |`--------------->----. ==================== |
2485 | | \ FLUSHFAILED[-ABSENT] |
2487 | | FLUSH OK \ main D tail/none |
2488 | | open F \ ==================== |
2490 | | \ | TIME TO RETRY |
2491 | |`------->----. ,---<---'\ `----------------'
2492 | | D NONE | | D NONE `----.
2494 | ============= V V ============
2495 | SEPARATED-1 | | DROPPING-1
2496 | flsh->rd!=0 | | flsh->rd!=0
2497 | [Separated] | | [Dropping]
2498 | main F idle | | main none
2499 | flsh D tail | | flsh D tail
2500 | ============= | | ============
2502 ^ | EOF ON D | | defer | EOF ON D
2504 | =============== | | ===============
2505 | SEPARATED-2 | | DROPPING-2
2506 | flsh->rd==0 | V flsh->rd==0
2507 | [Finishing] | | [Dropping]
2508 | main F tail | `. main none
2509 | flsh D closed | `. flsh D closed
2510 | =============== V `. ===============
2512 | | ALL D PROCESSED `. | ALL D PROCESSED
2513 | V install defer as backlog `. | install defer
2514 ^ | close D `. | close D
2515 | | unlink D `. | unlink D
2518 `----------' ==============
2538 static void startup_set_input_file(InputFile *f) {
2539 assert(!main_input_file);
2541 inputfile_reading_start(f);
2544 static void statemc_lock(void) {
2546 struct stat stab, stabf;
2549 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2550 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2553 memset(&fl,0,sizeof(fl));
2555 fl.l_whence= SEEK_SET;
2556 int r= fcntl(lockfd, F_SETLK, &fl);
2558 if (errno==EACCES || isewouldblock(errno)) {
2559 if (quiet_multiple) exit(0);
2560 fatal("another duct holds the lockfile");
2562 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2565 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2567 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2569 if (!lock_noent && samefile(&stab, &stabf))
2572 xclose(lockfd, "stale lockfile ", path_lock);
2575 FILE *lockfile= fdopen(lockfd, "w");
2576 if (!lockfile) sysdie("fdopen lockfile");
2578 int r= ftruncate(lockfd, 0);
2579 if (r) sysdie("truncate lockfile to write new info");
2581 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2582 (unsigned long)self_pid,
2583 sitename, feedfile, remote_host) == EOF ||
2585 sysfatal("write info to lockfile %s", path_lock);
2587 debug("startup: locked");
2590 static void statemc_init(void) {
2591 struct stat stabdefer;
2593 search_backlog_file();
2596 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2598 debug("startup: ductdefer ENOENT");
2600 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2601 switch (stabdefer.st_nlink==1) {
2603 open_defer(); /* so that we will later close it and rename it */
2606 xunlink(path_defer, "stale defer file link"
2607 " (presumably hardlink to backlog file)");
2610 die("defer file %s has unexpected link count %d",
2611 path_defer, stabdefer.st_nlink);
2615 struct stat stab_f, stab_d;
2618 InputFile *file_d= open_input_file(path_flushing);
2619 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2621 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2623 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2624 debug("startup: F==D => Hardlinked");
2625 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2630 debug("startup: F ENOENT => Moved");
2631 if (file_d) startup_set_input_file(file_d);
2632 spawn_inndcomm_flush("feedfile missing at startup");
2633 /* => Flushing, sms:=FLUSHING */
2636 debug("startup: F!=D => Separated");
2637 startup_set_input_file(file_d);
2638 flushing_input_file= main_input_file;
2639 main_input_file= open_input_file(feedfile);
2640 if (!main_input_file) die("feedfile vanished during startup");
2641 SMS(SEPARATED, max_separated_periods,
2642 "found both old and current feed files");
2644 debug("startup: F exists, D ENOENT => Normal");
2645 InputFile *file_f= open_input_file(feedfile);
2646 if (!file_f) die("feed file vanished during startup");
2647 startup_set_input_file(file_f);
2648 SMS(NORMAL, spontaneous_flush_periods, "normal startup");
2653 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2654 assert(sms == sm_NORMAL);
2656 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2658 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2659 (unsigned long)target_max_feedfile_size,
2662 int r= link(feedfile, path_flushing);
2663 if (r) sysfatal("link feedfile %s to flushing file %s",
2664 feedfile, path_flushing);
2667 xunlink(feedfile, "old feedfile link");
2670 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2673 static int trigger_flush_ok(const char *why) {
2677 statemc_start_flush(why ? why : "periodic");
2678 return 1; /* Normal => Flushing; => FLUSHING */
2680 case sm_FLUSHFAILED:
2681 spawn_inndcomm_flush(why ? why : "retry");
2682 return 1; /* Moved => Flushing; => FLUSHING */
2686 warn("abandoning old feedfile after flush (%s), autodeferring",
2687 why ? why : "took too long to complete");
2688 assert(flushing_input_file);
2689 autodefer_input_file(flushing_input_file);
2697 static void statemc_period_poll(void) {
2698 if (!until_flush) return;
2700 assert(until_flush>=0);
2702 if (until_flush) return;
2703 int ok= trigger_flush_ok(0);
2707 static int inputfile_is_done(InputFile *ipf) {
2709 if (ipf->inprogress) return 0; /* new article in the meantime */
2710 if (ipf->rd) return 0; /* not had EOF */
2714 static void notice_processed(InputFile *ipf, int completed,
2715 const char *what, const char *spec) {
2716 if (!ipf) return; /* allows preterminate to be lazy */
2718 #define RCI_NOTHING(x) /* nothing */
2719 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2720 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2722 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2724 char *inprog= completed
2725 ? xasprintf("%s","") /* GCC produces a stupid warning for printf("") ! */
2726 : xasprintf(" inprogress=%ld", ipf->inprogress);
2727 char *autodefer= ipf->autodefer >= 0
2728 ? xasprintf(" autodeferred=%ld", ipf->autodefer)
2729 : xasprintf("%s","");
2731 info("%s %s%s read=%d (+bl=%d,+err=%d)%s%s"
2732 " missing=%d offered=%d (ch=%d,nc=%d) accepted=%d (ch=%d,nc=%d)"
2733 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2735 completed?"completed":"processed", what, spec,
2736 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2737 inprog, autodefer, ipf->count_nooffer_missing,
2738 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2739 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2740 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2741 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2742 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2751 static void statemc_check_backlog_done(void) {
2752 InputFile *ipf= backlog_input_file;
2753 if (!inputfile_is_done(ipf)) return;
2755 const char *slash= strrchr(ipf->path, '/');
2756 const char *leaf= slash ? slash+1 : ipf->path;
2757 const char *under= strchr(slash, '_');
2758 const char *rest= under ? under+1 : leaf;
2759 if (!strncmp(rest,"backlog",7)) rest += 7;
2760 notice_processed(ipf,1,"backlog ",rest);
2762 close_input_file(ipf);
2763 if (unlink(ipf->path)) {
2764 if (errno != ENOENT)
2765 sysdie("could not unlink processed backlog file %s", ipf->path);
2766 warn("backlog file %s vanished while we were reading it"
2767 " so we couldn't remove it (but it's done now, anyway)",
2771 backlog_input_file= 0;
2772 search_backlog_file();
2776 static void statemc_check_flushing_done(void) {
2777 InputFile *ipf= flushing_input_file;
2778 if (!inputfile_is_done(ipf)) return;
2780 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2782 notice_processed(ipf,1,"feedfile","");
2786 xunlink(path_flushing, "old flushing file");
2788 close_input_file(flushing_input_file);
2789 free(flushing_input_file);
2790 flushing_input_file= 0;
2792 if (sms==sm_SEPARATED) {
2793 notice("flush complete");
2794 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2795 } else if (sms==sm_DROPPING) {
2796 SMS(DROPPED, max_separated_periods, "old flush complete");
2797 search_backlog_file();
2798 notice("feed dropped, but will continue until backlog is finished");
2802 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2804 assert(!inputfile_is_done(main_input_file));
2805 statemc_check_flushing_done();
2806 statemc_check_backlog_done();
2807 return OOP_CONTINUE;
2810 static void queue_check_input_done(void) {
2811 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2814 static void statemc_setstate(StateMachineState newsms, int periods,
2815 const char *forlog, const char *why) {
2817 until_flush= periods;
2819 const char *xtra= "";
2822 case sm_FLUSHFAILED:
2823 if (!main_input_file) xtra= "-ABSENT";
2827 xtra= flushing_input_file->rd ? "-1" : "-2";
2833 info("state %s%s[%d] %s",forlog,xtra,periods,why);
2835 info("state %s%s %s",forlog,xtra,why);
2839 /*---------- defer and backlog files ----------*/
2841 static void open_defer(void) {
2846 defer= fopen(path_defer, "a+");
2847 if (!defer) sysfatal("could not open defer file %s", path_defer);
2849 /* truncate away any half-written records */
2851 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2853 if (stab.st_size > LONG_MAX)
2854 die("defer file %s size is far too large", path_defer);
2859 long orgsize= stab.st_size;
2860 long truncto= stab.st_size;
2862 if (!truncto) break; /* was only (if anything) one half-truncated record */
2863 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2864 sysdie("seek in defer file %s while truncating partial", path_defer);
2869 sysdie("failed read from defer file %s", path_defer);
2871 die("defer file %s shrank while we were checking it!", path_defer);
2877 if (stab.st_size != truncto) {
2878 warn("truncating half-record at end of defer file %s -"
2879 " shrinking by %ld bytes from %ld to %ld",
2880 path_defer, orgsize - truncto, orgsize, truncto);
2883 sysfatal("could not flush defer file %s", path_defer);
2884 if (ftruncate(fileno(defer), truncto))
2885 sysdie("could not truncate defer file %s", path_defer);
2888 info("continuing existing defer file %s (%ld bytes)",
2889 path_defer, orgsize);
2891 if (fseek(defer, truncto, SEEK_SET))
2892 sysdie("could not seek to new end of defer file %s", path_defer);
2895 static void close_defer(void) {
2900 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2902 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2905 time_t now= xtime();
2907 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2909 (unsigned long)stab.st_ino);
2910 if (link(path_defer, backlog))
2911 sysfatal("could not install defer file %s as backlog file %s",
2912 path_defer, backlog);
2913 if (unlink(path_defer))
2914 sysdie("could not unlink old defer link %s to backlog file %s",
2915 path_defer, backlog);
2919 if (until_backlog_nextscan < 0 ||
2920 until_backlog_nextscan > backlog_retry_minperiods + 1)
2921 until_backlog_nextscan= backlog_retry_minperiods + 1;
2924 static void poll_backlog_file(void) {
2925 if (until_backlog_nextscan < 0) return;
2926 if (until_backlog_nextscan-- > 0) return;
2927 search_backlog_file();
2930 static void search_backlog_file(void) {
2931 /* returns non-0 iff there are any backlog files */
2936 const char *oldest_path=0;
2937 time_t oldest_mtime=0, now;
2939 if (backlog_input_file) return;
2943 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2947 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2949 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2951 for (i=0; i<gl.gl_pathc; i++) {
2952 const char *path= gl.gl_pathv[i];
2954 if (strchr(path,'#') || strchr(path,'~')) {
2955 debug("backlog file search skipping %s", path);
2958 r= stat(path, &stab);
2960 syswarn("failed to stat backlog file %s", path);
2963 if (!S_ISREG(stab.st_mode)) {
2964 warn("backlog file %s is not a plain file (or link to one)", path);
2967 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2969 oldest_mtime= stab.st_mtime;
2972 case GLOB_NOMATCH: /* fall through */
2975 sysdie("glob expansion of backlog pattern %s gave unexpected"
2976 " nonzero (error?) return value %d", globpat_backlog, r);
2980 debug("backlog scan: none");
2982 if (sms==sm_DROPPED) {
2984 notice("feed dropped and our work is complete");
2986 int r= unlink(path_cli);
2987 if (r && errno!=ENOENT)
2988 syswarn("failed to unlink cli socket for old feed");
2990 xunlink(path_lock, "lockfile for old feed");
2993 until_backlog_nextscan= backlog_spontrescan_periods;
2998 double age= difftime(now, oldest_mtime);
2999 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
3001 if (age_deficiency <= 0) {
3002 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
3003 age, age_deficiency, oldest_path);
3005 backlog_input_file= open_input_file(oldest_path);
3006 if (!backlog_input_file) {
3007 warn("backlog file %s vanished as we opened it", oldest_path);
3011 inputfile_reading_start(backlog_input_file);
3012 until_backlog_nextscan= -1;
3016 until_backlog_nextscan= age_deficiency / period_seconds;
3018 if (backlog_spontrescan_periods >= 0 &&
3019 until_backlog_nextscan > backlog_spontrescan_periods)
3020 until_backlog_nextscan= backlog_spontrescan_periods;
3022 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
3023 age, age_deficiency, until_backlog_nextscan, oldest_path);
3030 /*---------- shutdown and signal handling ----------*/
3032 static void preterminate(void) {
3033 if (in_child) return;
3034 notice_processed(main_input_file,0,"feedfile","");
3035 notice_processed(flushing_input_file,0,"flushing","");
3036 if (backlog_input_file)
3037 notice_processed(backlog_input_file,0, "backlog file ",
3038 backlog_input_file->path);
3041 static int signal_self_pipe[2];
3042 static sig_atomic_t terminate_sig_flag;
3044 static void raise_default(int signo) {
3045 xsigsetdefault(signo);
3050 static void *sigarrived_event(oop_source *lp, int fd, oop_event e, void *u) {
3051 assert(fd=signal_self_pipe[0]);
3053 int r= read(signal_self_pipe[0], buf, sizeof(buf));
3054 if (r<0 && !isewouldblock(errno)) sysdie("failed to read signal self pipe");
3055 if (r==0) die("eof on signal self pipe");
3056 if (terminate_sig_flag) {
3058 notice("terminating (%s)", strsignal(terminate_sig_flag));
3059 raise_default(terminate_sig_flag);
3061 return OOP_CONTINUE;
3064 static void sigarrived_handler(int signum) {
3069 if (!terminate_sig_flag) terminate_sig_flag= signum;
3074 write(signal_self_pipe[1],&x,1);
3077 static void init_signals(void) {
3078 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3079 sysdie("could not ignore SIGPIPE");
3081 if (pipe(signal_self_pipe)) sysfatal("create self-pipe for signals");
3083 xsetnonblock(signal_self_pipe[0],1);
3084 xsetnonblock(signal_self_pipe[1],1);
3086 struct sigaction sa;
3087 memset(&sa,0,sizeof(sa));
3088 sa.sa_handler= sigarrived_handler;
3089 sa.sa_flags= SA_RESTART;
3090 xsigaction(SIGTERM,&sa);
3091 xsigaction(SIGINT,&sa);
3093 on_fd_read_except(signal_self_pipe[0], sigarrived_event);
3096 /*========== flushing the feed ==========*/
3098 static pid_t inndcomm_child;
3099 static int inndcomm_sentinel_fd;
3101 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
3102 assert(inndcomm_child);
3103 assert(fd == inndcomm_sentinel_fd);
3104 int status= xwaitpid(&inndcomm_child, "inndcomm");
3107 cancel_fd_read_except(fd);
3108 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
3109 inndcomm_sentinel_fd= 0;
3111 assert(!flushing_input_file);
3113 if (WIFEXITED(status)) {
3114 switch (WEXITSTATUS(status)) {
3116 case INNDCOMMCHILD_ESTATUS_FAIL:
3119 case INNDCOMMCHILD_ESTATUS_NONESUCH:
3120 notice("feed has been dropped by innd, finishing up");
3121 flushing_input_file= main_input_file;
3122 tailing_make_readable(flushing_input_file);
3123 /* we probably previously returned EAGAIN from our fake read method
3124 * when in fact we were at EOF, so signal another readable event
3125 * so we actually see the EOF */
3129 if (flushing_input_file) {
3130 SMS(DROPPING, max_separated_periods,
3131 "feed dropped by innd, but must finish last flush");
3134 SMS(DROPPED, 0, "feed dropped by innd");
3135 search_backlog_file();
3137 return OOP_CONTINUE;
3141 flushing_input_file= main_input_file;
3142 tailing_make_readable(flushing_input_file);
3144 main_input_file= open_input_file(feedfile);
3145 if (!main_input_file)
3146 die("flush succeeded but feedfile %s does not exist!"
3147 " (this probably means feedfile does not correspond"
3148 " to site %s in newsfeeds)", feedfile, sitename);
3150 if (flushing_input_file) {
3151 SMS(SEPARATED, max_separated_periods, "flush complete");
3154 SMS(NORMAL, spontaneous_flush_periods, "recovery flush complete");
3156 return OOP_CONTINUE;
3159 goto unexpected_exitstatus;
3162 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
3163 warn("flush timed out trying to talk to innd");
3166 unexpected_exitstatus:
3167 report_child_status("inndcomm child", status);
3171 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
3172 return OOP_CONTINUE;
3175 static void inndcommfail(const char *what) {
3176 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
3177 exit(INNDCOMMCHILD_ESTATUS_FAIL);
3180 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
3183 notice("flushing %s",why);
3185 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
3186 assert(!inndcomm_child);
3187 assert(!inndcomm_sentinel_fd);
3189 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
3191 inndcomm_child= xfork("inndcomm child");
3193 if (!inndcomm_child) {
3194 const char *flushargv[2]= { sitename, 0 };
3198 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
3199 /* parent spots the autoclose of pipefds[1] when we die or exit */
3201 if (simulate_flush>=0) {
3202 warn("SIMULATING flush child status %d", simulate_flush);
3203 if (simulate_flush>128) raise(simulate_flush-128);
3204 else exit(simulate_flush);
3207 alarm(inndcomm_flush_timeout);
3208 r= ICCopen(); if (r) inndcommfail("connect");
3209 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
3210 if (!r) exit(0); /* yay! */
3212 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
3213 syswarn("innd ctlinnd flush failed: innd said %s", reply);
3214 exit(INNDCOMMCHILD_ESTATUS_FAIL);
3219 xclose(pipefds[1], "inndcomm sentinel child's end",0);
3220 inndcomm_sentinel_fd= pipefds[0];
3221 assert(inndcomm_sentinel_fd);
3222 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
3224 SMS(FLUSHING, 0, why);
3227 /*========== main program ==========*/
3229 static void postfork_inputfile(InputFile *ipf) {
3231 xclose(ipf->fd, "(in child) input file ", ipf->path);
3234 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
3235 /* we have no stdio streams that are buffered long-term */
3237 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
3240 static void postfork(void) {
3243 xsigsetdefault(SIGTERM);
3244 xsigsetdefault(SIGINT);
3245 xsigsetdefault(SIGPIPE);
3246 if (terminate_sig_flag) raise(terminate_sig_flag);
3248 postfork_inputfile(main_input_file);
3249 postfork_inputfile(flushing_input_file);
3253 conn_closefd(conn,"(in child) ");
3255 postfork_stdio(defer, "defer file ", path_defer);
3258 typedef struct Every Every;
3260 struct timeval interval;
3265 static void every_schedule(Every *e, struct timeval base);
3267 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
3270 if (!e->fixed_rate) xgettimeofday(&base);
3271 every_schedule(e, base);
3272 return OOP_CONTINUE;
3275 static void every_schedule(Every *e, struct timeval base) {
3276 struct timeval when;
3277 timeradd(&base, &e->interval, &when);
3278 loop->on_time(loop, when, every_happens, e);
3281 static void every(int interval, int fixed_rate, void (*f)(void)) {
3282 NEW_DECL(Every *,e);
3283 e->interval.tv_sec= interval;
3284 e->interval.tv_usec= 0;
3285 e->fixed_rate= fixed_rate;
3288 xgettimeofday(&now);
3289 every_schedule(e, now);
3292 static void filepoll(void) {
3293 tailing_make_readable(main_input_file);
3294 tailing_make_readable(flushing_input_file);
3297 static char *debug_report_ipf(InputFile *ipf) {
3298 if (!ipf) return xasprintf("none");
3300 const char *slash= strrchr(ipf->path,'/');
3301 const char *path= slash ? slash+1 : ipf->path;
3303 return xasprintf("%p/%s:queue=%d,ip=%ld,autodef=%ld,off=%ld,fd=%d%s%s%s",
3305 ipf->queue.count, ipf->inprogress, ipf->autodefer,
3306 (long)ipf->offset, ipf->fd,
3307 ipf->rd ? "" : ",!rd",
3308 ipf->skippinglong ? "*skiplong" : "",
3309 ipf->rd && ipf->paused ? "*paused" : "");
3312 static void period(void) {
3313 char *dipf_main= debug_report_ipf(main_input_file);
3314 char *dipf_flushing= debug_report_ipf(flushing_input_file);
3315 char *dipf_backlog= debug_report_ipf(backlog_input_file);
3318 " sms=%s[%d] conns=%d until_connect=%d"
3319 " input_files main:%s flushing:%s backlog:%s[%d]"
3320 " children connecting=%ld inndcomm=%ld lowvol_total=%d"
3322 sms_names[sms], until_flush, conns.count, until_connect,
3323 dipf_main, dipf_flushing, dipf_backlog, until_backlog_nextscan,
3324 (long)connecting_child, (long)inndcomm_child, lowvol_total
3328 free(dipf_flushing);
3331 if (until_connect) until_connect--;
3333 inputfile_queue_check_expired(backlog_input_file);
3334 poll_backlog_file();
3335 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
3336 statemc_period_poll();
3337 check_assign_articles();
3342 /*========== dumping state ==========*/
3344 static void dump_article_list(FILE *f, const CliCommand *c,
3345 const ArticleList *al) {
3346 fprintf(f, " count=%d\n", al->count);
3347 if (!c->xval) return;
3349 int i; Article *art;
3350 for (i=0, art=LIST_HEAD(*al); art; i++, art=LIST_NEXT(art)) {
3351 fprintf(f," #%05d %-11s", i, artstate_names[art->state]);
3352 DUMPV("%p", art->,ipf);
3353 DUMPV("%d", art->,missing);
3354 DUMPV("%lu", (unsigned long)art->,offset);
3355 DUMPV("%d", art->,blanklen);
3356 DUMPV("%d", art->,midlen);
3357 fprintf(f, " %s %s\n", TokenToText(art->token), art->messageid);
3361 static void dump_input_file(FILE *f, const CliCommand *c,
3362 InputFile *ipf, const char *wh) {
3363 char *dipf= debug_report_ipf(ipf);
3364 fprintf(f,"input %s %s", wh, dipf);
3368 DUMPV("%d", ipf->,readcount_ok);
3369 DUMPV("%d", ipf->,readcount_blank);
3370 DUMPV("%d", ipf->,readcount_err);
3371 DUMPV("%d", ipf->,count_nooffer_missing);
3375 ArtState state; const char *const *statename;
3376 for (state=0, statename=artstate_names; *statename; state++,statename++) {
3377 #define RC_DUMP_FMT(x) " " #x "=%d"
3378 #define RC_DUMP_VAL(x) ,ipf->counts[state][RC_##x]
3379 fprintf(f,"input %s counts %-11s"
3380 RESULT_COUNTS(RC_DUMP_FMT,RC_DUMP_FMT) "\n",
3382 RESULT_COUNTS(RC_DUMP_VAL,RC_DUMP_VAL));
3384 fprintf(f,"input %s queue", wh);
3385 dump_article_list(f,c,&ipf->queue);
3391 fprintf(cc->out, "dumping state to %s\n", path_dump);
3392 FILE *f= fopen(path_dump, "w");
3393 if (!f) { fprintf(cc->out, "failed: open: %s\n", strerror(errno)); return; }
3395 fprintf(f,"general");
3396 DUMPV("%s", sms_names,[sms]);
3397 DUMPV("%d", ,until_flush);
3398 DUMPV("%ld", (long),self_pid);
3399 DUMPV("%p", , defer);
3400 DUMPV("%d", , until_connect);
3401 DUMPV("%d", , until_backlog_nextscan);
3402 DUMPV("%d", , simulate_flush);
3403 fprintf(f,"\nnocheck");
3404 DUMPV("%#.10f", , accept_proportion);
3405 DUMPV("%d", , nocheck);
3406 DUMPV("%d", , nocheck_reported);
3409 fprintf(f,"special");
3410 DUMPV("%ld", (long),connecting_child);
3411 DUMPV("%d", , connecting_fdpass_sock);
3412 DUMPV("%d", , cli_master);
3415 fprintf(f,"lowvol");
3416 DUMPV("%d", , lowvol_circptr);
3417 DUMPV("%d", , lowvol_total);
3419 for (i=0; i<lowvol_periods; i++) {
3421 if (i==lowvol_circptr) fprintf(f,"*");
3422 fprintf(f,"%d",lowvol_perperiod[i]);
3426 fprintf(f,"filemon ");
3427 filemon_method_dump_info(f);
3429 dump_input_file(f,c, main_input_file, "main" );
3430 dump_input_file(f,c, flushing_input_file, "flushing");
3431 dump_input_file(f,c, backlog_input_file, "backlog" );
3433 fprintf(f,"conns count=%d\n", conns.count);
3438 fprintf(f,"C%d",conn->fd);
3439 DUMPV("%p",conn->,rd); DUMPV("%d",conn->,max_queue);
3440 DUMPV("%d",conn->,stream); DUMPV("\"%s\"",conn->,quitting);
3441 DUMPV("%d",conn->,since_activity);
3444 fprintf(f,"C%d waiting", conn->fd); dump_article_list(f,c,&conn->waiting);
3445 fprintf(f,"C%d priority",conn->fd); dump_article_list(f,c,&conn->priority);
3446 fprintf(f,"C%d sent", conn->fd); dump_article_list(f,c,&conn->sent);
3448 fprintf(f,"C%d xmit xmitu=%d\n", conn->fd, conn->xmitu);
3449 for (i=0; i<conn->xmitu; i++) {
3450 const struct iovec *iv= &conn->xmit[i];
3451 const XmitDetails *xd= &conn->xmitd[i];
3454 case xk_Const: dinfo= xasprintf("Const"); break;
3455 case xk_Artdata: dinfo= xasprintf("A%p", xd->info.sm_art); break;
3459 fprintf(f," #%03d %-11s l=%d %s\n", i, dinfo, iv->iov_len,
3460 sanitise(iv->iov_base, iv->iov_len));
3466 DUMPV("%s", , feedfile);
3467 DUMPV("%s", , path_cli);
3468 DUMPV("%s", , path_lock);
3469 DUMPV("%s", , path_flushing);
3470 DUMPV("%s", , path_defer);
3471 DUMPV("%s", , path_dump);
3472 DUMPV("%s", , globpat_backlog);
3475 if (!!ferror(f) + !!fclose(f)) {
3476 fprintf(cc->out, "failed: write: %s\n", strerror(errno));
3481 /*========== option parsing ==========*/
3483 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
3484 static void vbadusage(const char *fmt, va_list al) {
3485 char *m= xvasprintf(fmt,al);
3486 fprintf(stderr, "bad usage: %s\n"
3487 "say --help for help, or read the manpage\n",
3489 if (interactive < 2)
3490 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
3494 /*---------- generic option parser ----------*/
3496 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
3497 static void badusage(const char *fmt, ...) {
3504 of_seconds= 001000u,
3505 of_boolean= 002000u,
3508 typedef struct Option Option;
3509 typedef void OptionParser(const Option*, const char *val);
3513 const char *lng, *formarg;
3519 static void parse_options(const Option *options, char ***argvp) {
3520 /* on return *argvp is first non-option arg; argc is not updated */
3523 const char *arg= *++(*argvp);
3525 if (*arg != '-') break;
3526 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
3528 while ((a= *++arg)) {
3532 char *equals= strchr(arg,'=');
3533 int len= equals ? (equals - arg) : strlen(arg);
3534 for (o=options; o->shrt || o->lng; o++)
3535 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
3537 badusage("unknown long option --%s",arg);
3540 if (equals) badusage("option --%s does not take a value",o->lng);
3542 } else if (equals) {
3546 if (!arg) badusage("option --%s needs a value for %s",
3547 o->lng, o->formarg);
3550 break; /* eaten the whole argument now */
3552 for (o=options; o->shrt || o->lng; o++)
3555 badusage("unknown short option -%c",a);
3562 if (!arg) badusage("option -%c needs a value for %s",
3563 o->shrt, o->formarg);
3566 break; /* eaten the whole argument now */
3572 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
3574 static void print_options(const Option *options, FILE *f) {
3576 for (o=options; o->shrt || o->lng; o++) {
3577 char shrt[2] = { o->shrt, 0 };
3578 char *optspec= xasprintf("%s%s%s%s%s",
3579 o->shrt ? "-" : "", shrt,
3580 o->shrt && o->lng ? "|" : "",
3581 DELIMPERHAPS("--", o->lng));
3582 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
3587 /*---------- specific option types ----------*/
3589 static void op_integer(const Option *o, const char *val) {
3592 unsigned long ul= strtoul(val,&ep,10);
3593 if (*ep || ep==val || errno || ul>INT_MAX)
3594 badusage("bad integer value for %s",o->lng);
3595 int *store= o->store;
3599 static void op_double(const Option *o, const char *val) {
3600 int *store= o->store;
3603 *store= strtod(val, &ep);
3604 if (*ep || ep==val || errno)
3605 badusage("bad floating point value for %s",o->lng);
3608 static void op_string(const Option *o, const char *val) {
3609 const char **store= o->store;
3613 static void op_seconds(const Option *o, const char *val) {
3614 int *store= o->store;
3618 double v= strtod(val,&ep);
3619 if (ep==val) badusage("bad time/duration value for %s",o->lng);
3621 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
3622 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
3623 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
3624 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
3625 else if (!strcmp(ep,"das")) unit= 10;
3626 else if (!strcmp(ep,"hs")) unit= 100;
3627 else if (!strcmp(ep,"ks")) unit= 1000;
3628 else if (!strcmp(ep,"Ms")) unit= 1000000;
3629 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
3633 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
3637 static void op_setint(const Option *o, const char *val) {
3638 int *store= o->store;
3642 /*---------- specific options ----------*/
3644 static void help(const Option *o, const char *val);
3646 static const Option innduct_options[]= {
3647 {'f',"feedfile", "F", &feedfile, op_string },
3648 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
3649 {0,"no-daemon", 0, &interactive, op_setint, 1 },
3650 {0,"interactive", 0, &interactive, op_setint, 2 },
3651 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
3652 {0,"no-filemon", 0, &try_filemon, op_setint, 0 },
3653 {'C',"inndconf", "F", &inndconffile, op_string },
3654 {'P',"port", "PORT", &port, op_integer },
3655 {0,"chdir", "DIR", &path_run, op_string },
3656 {0,"cli", "DIR/|PATH", &path_cli, op_string },
3657 {0,"help", 0, 0, help },
3659 {0,"max-connections", "N", &max_connections, op_integer },
3660 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
3661 {0,"max-queue-per-file", "N", &max_queue_per_ipf, op_integer },
3662 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
3663 {0,"period-interval", "TIME", &period_seconds, op_seconds },
3665 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
3666 {0,"stuck-flush-timeout", "TIME", &inndcomm_flush_timeout, op_seconds },
3667 {0,"feedfile-poll", "TIME", &filepoll_seconds, op_seconds },
3669 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
3670 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
3672 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
3673 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
3674 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3675 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3676 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
3677 {0,"flush-finish-timeout", "PERIOD", &max_separated_periods, op_seconds },
3678 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
3679 {0,"low-volume-thresh", "PERIOD", &lowvol_thresh, op_integer },
3680 {0,"low-volume-window", "PERIOD", &lowvol_periods, op_seconds },
3682 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
3683 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
3688 static void printusage(FILE *f) {
3689 fputs("usage: innduct [options] site [fqdn]\n"
3690 "available options are:\n", f);
3691 print_options(innduct_options, f);
3694 static void help(const Option *o, const char *val) {
3696 if (ferror(stdout) || fflush(stdout)) {
3697 perror("innduct: writing help");
3703 static void convert_to_periods_rndup(int *store) {
3704 *store += period_seconds-1;
3705 *store /= period_seconds;
3708 static int path_ends_slash(const char *specified) {
3709 int l= strlen(specified);
3711 return specified[l-1] == '/';
3714 int main(int argc, char **argv) {
3720 parse_options(innduct_options, &argv);
3725 if (!sitename) badusage("need site name argument");
3727 if (*argv) remote_host= *argv++;
3728 else remote_host= sitename;
3730 if (*argv) badusage("too many non-option arguments");
3734 int r= innconf_read(inndconffile);
3735 if (!r) badusage("could not read inn.conf (more info on stderr)");
3737 if (!remote_host) remote_host= sitename;
3739 if (nocheck_thresh < 0 || nocheck_thresh > 100)
3740 badusage("nocheck threshold percentage must be between 0..100");
3741 nocheck_thresh *= 0.01;
3743 if (nocheck_decay < 0.1)
3744 badusage("nocheck decay articles must be at least 0.1");
3745 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3747 convert_to_periods_rndup(&reconnect_delay_periods);
3748 convert_to_periods_rndup(&flushfail_retry_periods);
3749 convert_to_periods_rndup(&backlog_retry_minperiods);
3750 convert_to_periods_rndup(&backlog_spontrescan_periods);
3751 convert_to_periods_rndup(&spontaneous_flush_periods);
3752 convert_to_periods_rndup(&max_separated_periods);
3753 convert_to_periods_rndup(&need_activity_periods);
3754 convert_to_periods_rndup(&lowvol_periods);
3756 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3757 badusage("bad input data ratio must be between 0..100");
3758 max_bad_data_ratio *= 0.01;
3761 path_run= innconf->pathrun;
3763 if (!feedfile) feedfile= sitename;
3764 if (!feedfile[0]) badusage("feed filename, if specified, must be nonempty");
3765 if (path_ends_slash(feedfile))
3766 feedfile= xasprintf("%s%s", feedfile, sitename);
3767 if (feedfile[0] != '/')
3768 feedfile= xasprintf("%s/%s", innconf->pathoutgoing, feedfile);
3771 path_cli_dir= "innduct";
3772 } else if (!path_cli[0] || !strcmp(path_cli,"none")) {
3773 path_cli= 0; /* ok, don't then */
3774 } else if (path_ends_slash(path_cli)) {
3775 path_cli_dir= xasprintf("%.*s", strlen(path_cli)-1, path_cli);
3778 path_cli= xasprintf("%s/%s", path_cli_dir, sitename);
3780 if (max_queue_per_ipf<0)
3781 max_queue_per_ipf= max_queue_per_conn * 2;
3783 const char *feedfile_forbidden= "?*[~#";
3785 while ((c= *feedfile_forbidden++))
3786 if (strchr(feedfile, c))
3787 badusage("feed filename may not contain metacharacter %c",c);
3790 lowvol_perperiod= xcalloc(sizeof(*lowvol_perperiod), lowvol_periods);
3791 for (i=0; i<lowvol_periods; i++) {
3792 lowvol_perperiod[i]= lowvol_thresh;
3793 lowvol_total += lowvol_thresh;
3795 lowvol_total -= lowvol_thresh;
3799 path_lock= xasprintf("%s_lock", feedfile);
3800 path_flushing= xasprintf("%s_flushing", feedfile);
3801 path_defer= xasprintf("%s_defer", feedfile);
3802 path_dump= xasprintf("%s_dump", feedfile);
3803 globpat_backlog= xasprintf("%s_backlog*", feedfile);
3805 oop_source_sys *sysloop= oop_sys_new();
3806 if (!sysloop) sysdie("could not create liboop event loop");
3807 loop= (oop_source*)sysloop;
3811 if (interactive < 1) {
3813 for (i=3; i<255; i++)
3814 /* do this now before we open syslog, etc. */
3818 if (interactive < 2)
3819 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3821 if (interactive < 1) {
3822 int null= open("/dev/null",O_RDWR);
3823 if (null<0) sysfatal("failed to open /dev/null");
3827 xclose(null, "/dev/null original fd",0);
3829 pid_t child1= xfork("daemonise first fork");
3830 if (child1) _exit(0);
3832 pid_t sid= setsid();
3833 if (sid == -1) sysfatal("setsid failed");
3835 pid_t child2= xfork("daemonise second fork");
3836 if (child2) _exit(0);
3840 if (self_pid==-1) sysdie("getpid");
3843 if (r) sysdie("could not chdir to pathrun %s", path_run);
3852 r= SMsetup(SM_PREOPEN, &val); if (!r) warn("SMsetup SM_PREOPEN failed");
3853 r= SMinit(); if (!r) die("storage manager initialisation (SMinit) failed");
3855 if (interactive >= 2)
3862 notice("filemon: suppressed by command line option, polling");
3864 filemon_ok= filemon_method_init();
3866 warn("filemon: no file monitoring available, polling");
3869 every(filepoll_seconds,0,filepoll);
3871 every(period_seconds,1,period);
3877 void *run= oop_sys_run(sysloop);
3878 assert(run == OOP_ERROR);
3879 sysdie("event loop failed");