3 * - some per-conn info thing for control
4 * - manpage: document control master stuff
5 * - admin-initiated flush
8 * build-lfs/backends/innduct --no-daemon -C ../inn.conf -f `pwd`/fee sit localhost
12 * Newsfeeds file entries should look like this:
13 * host.name.of.site[/exclude,exclude,...]\
14 * :pattern,pattern...[/distribution,distribution...]\
18 * sitename[/exclude,exclude,...]\
19 * :pattern,pattern...[/distribution,distribution...]\
25 * or might be blanked out
26 * <spc><spc><spc><spc>....
28 * F site.name main feed file
29 * opened/created, then written, by innd
32 * tokens blanked out by duct when processed
33 * site.name_lock lock preventing multiple ducts
34 * to hold lock must open,F_SETLK[W]
35 * and then stat to check that locked file
36 * still has name site.name_lock
37 * holder of this lock is "duct"
38 * (only) lockholder may remove the lockfile
39 * D site.name_flushing temporary feed file during flush (or crash)
40 * hardlink created by duct
42 * site.name_defer 431'd articles, still being written,
43 * created, written, used by duct
45 * site.name_backlog.<date>.<inum>
46 * 431'd articles, ready for innxmit or duct
47 * created (link/mv) by duct
48 * site.name_backlog<anything-else> (where <anything-else> does not
49 * contain '#' or '~') eg
50 * site.name_backlog.manual
51 * anything the sysadmin likes (eg, feed files
52 * from old feeds to be merged into this one)
53 * created (link/mv) by admin
54 * may be symlinks (in which case links
55 * may be written through, but only links
58 * It is safe to remove backlog files manually,
59 * if it's desired to throw away the backlog.
61 * Backlog files are also processed by innduct. We find the oldest
62 * backlog file which is at least a certain amount old, and feed it
63 * back into our processing. When every article in it has been read
64 * and processed, we unlink it and look for another backlog file.
66 * If we don't have a backlog file that we're reading, we close the
67 * defer file that we're writing and make it into a backlog file at
68 * the first convenient opportunity.
79 | | <----------------<---------------------------------'|
85 | F: innd writing, duct reading |
88 | | duct decides time to flush |
89 | | duct makes hardlink |
91 | V <------------------------'|
93 | F == D: innd writing, duct reading both exist |
96 | | <-----------<-------------<--'|
100 | V <---------------------. |
103 | D: innd writing, duct reading; or ENOENT | |
105 | | duct requests flush of feed | |
106 | | (others can too, harmlessly) | |
110 | D: innd flushing, duct; or ENOENT | |
112 | | inndcomm flush fails | |
113 | |`-------------------------->------------------' |
115 | | inndcomm reports no such site |
116 | |`---------------------------------------------------- | -.
118 | | innd finishes writing D, creates F | |
119 | | inndcomm reports flush successful | |
122 | Separated <----------------' |
123 | F: innd writing F!=D /
124 | D: duct reading; or ENOENT both exist /
126 | | duct gets to the end of D /
127 | | duct opens F too /
130 | F: innd writing, duct reading |
131 | D: duct finishing V
133 | | duct finishes processing D F: ENOENT
134 | V duct unlinks D D: duct reading
136 `--<--' | duct finishes
146 "duct reading" means innduct is reading the file but also
147 overwriting processed tokens.
151 * rune for printing diagrams:
153 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
158 /*============================== PROGRAM ==============================*/
160 #define _GNU_SOURCE 1
166 #include "inndcomm.h"
168 #include "inn/list.h"
169 #include "inn/innconf.h"
172 #include <sys/types.h>
173 #include <sys/wait.h>
174 #include <sys/stat.h>
175 #include <sys/socket.h>
194 #include <oop-read.h>
196 /*----- general definitions, probably best not changed -----*/
198 #define CONNCHILD_ESTATUS_STREAM 24
199 #define CONNCHILD_ESTATUS_NOSTREAM 25
201 #define INNDCOMMCHILD_ESTATUS_FAIL 26
202 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
204 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
205 #define MAX_CONTROL_COMMAND 1000
207 #define VA va_list al; va_start(al,fmt)
208 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
209 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
211 /*----- doubly linked lists -----*/
213 #define ISNODE(T) struct node list_node
216 union { struct list li; T *for_type; } u; \
220 #define NODE(n) (assert((void*)&(n)->list_node == (n)), &(n)->list_node)
222 #define LIST_CHECKCANHAVENODE(l,n) \
223 ((void)((n) == ((l).u.for_type))) /* just for the type check */
225 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
226 ( LIST_CHECKCANHAVENODE(l,n), \
227 list_addsomehow(&(l).u.li, NODE((n))), \
231 #define LIST_REMSOMEHOW(l,list_remsomehow) \
232 ( (typeof((l).u.for_type)) \
235 list_remsomehow(&(l).u.li) ) \
241 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
242 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
243 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
244 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
246 #define LIST_INIT(l) ((l).count=0, list_new(&(l).u.li))
247 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
248 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
249 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
251 #define LIST_REMOVE(l,n) \
252 ( LIST_CHECKCANHAVENODE(l,n), \
253 list_remove(NODE((n))), \
257 #define LIST_INSERT(l,n,pred) \
258 ( LIST_CHECKCANHAVENODE(l,n), \
259 LIST_CHECKCANHAVENODE(l,pred), \
260 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
264 /*----- type predeclarations -----*/
266 typedef struct Conn Conn;
267 typedef struct Article Article;
268 typedef struct InputFile InputFile;
269 typedef struct XmitDetails XmitDetails;
270 typedef struct Filemon_Perfile Filemon_Perfile;
271 typedef enum StateMachineState StateMachineState;
276 /*----- function predeclarations -----*/
278 static void conn_maybe_write(Conn *conn);
279 static void conn_make_some_xmits(Conn *conn);
280 static void *conn_write_some_xmits(Conn *conn);
282 static void xmit_free(XmitDetails *d);
284 #define SMS(newstate, periods, why) \
285 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
286 static void statemc_setstate(StateMachineState newsms, int periods,
287 const char *forlog, const char *why);
289 static void statemc_start_flush(const char *why); /* Normal => Flushing */
290 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
292 static void article_done(Conn *conn, Article *art, int whichcount);
294 static void check_assign_articles(void);
295 static void queue_check_input_done(void);
297 static void statemc_check_flushing_done(void);
298 static void statemc_check_backlog_done(void);
300 static void postfork(void);
301 static void period(void);
303 static void open_defer(void);
304 static void close_defer(void);
305 static void search_backlog_file(void);
306 static void preterminate(void);
307 static void defraise(int signo);
309 static void inputfile_reading_start(InputFile *ipf);
310 static void inputfile_reading_stop(InputFile *ipf);
312 static void filemon_start(InputFile *ipf);
313 static void filemon_stop(InputFile *ipf);
314 static void filemon_callback(InputFile *ipf);
316 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
317 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
319 static const oop_rd_style peer_rd_style;
320 static oop_rd_call peer_rd_err, peer_rd_ok;
322 /*----- configuration options -----*/
323 /* when changing defaults, remember to update the manpage */
325 static const char *sitename, *remote_host;
326 static const char *feedfile, *realsockdir="/tmp/innduct.control";
327 static int quiet_multiple=0;
328 static int become_daemon=1, try_filemon=1;
329 static int try_stream=1;
331 static const char *inndconffile;
333 static int max_connections=10;
334 static int max_queue_per_conn=200;
335 static int target_max_feedfile_size=100000;
336 static int period_seconds=60;
337 static int filepoll_seconds=5;
339 static int connection_setup_timeout=200;
340 static int inndcomm_flush_timeout=100;
342 static double nocheck_thresh= 95.0; /* converted from percentage by main */
343 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
345 /* all these are initialised to seconds, and converted to periods in main */
346 static int reconnect_delay_periods=1000;
347 static int flushfail_retry_periods=1000;
348 static int backlog_retry_minperiods=50;
349 static int backlog_spontrescan_periods=300;
350 static int spontaneous_flush_periods=100000;
351 static int need_activity_periods=1000;
353 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
354 static int max_bad_data_initial= 30;
355 /* in one corrupt 4096-byte block the number of newlines has
356 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
359 /*----- statistics -----*/
361 typedef enum { /* in queue in conn->sent */
362 art_Unchecked, /* not checked, not sent checking */
363 art_Wanted, /* checked, wanted sent body as requested */
364 art_Unsolicited, /* - sent body without check */
368 #define RESULT_COUNTS(RCS,RCN) \
377 #define RCI_TRIPLE_FMT_BASE "%d (id=%d,bod=%d,nc=%d)"
378 #define RCI_TRIPLE_VALS_BASE(counts,x) \
379 counts[art_Unchecked] x \
380 + counts[art_Wanted] x \
381 + counts[art_Unsolicited] x, \
382 counts[art_Unchecked] x \
383 , counts[art_Wanted] x \
384 , counts[art_Unsolicited] x
387 #define RC_INDEX(x) RC_##x,
388 RESULT_COUNTS(RC_INDEX, RC_INDEX)
393 /*----- transmission buffers -----*/
398 xk_Malloc, xk_Const, xk_Artdata
410 /*----- core operational data structure types -----*/
413 /* This is also an instance of struct oop_readable */
414 struct oop_readable readable; /* first */
415 oop_readable_call *readable_callback;
416 void *readable_callback_user;
419 Filemon_Perfile *filemon;
421 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
422 long inprogress; /* no. of articles read but not processed */
426 int counts[art_MaxState][RCI_max];
427 int readcount_ok, readcount_blank, readcount_err;
442 #define SMS_LIST(X) \
450 enum StateMachineState {
451 #define SMS_DEF_ENUM(s) sm_##s,
452 SMS_LIST(SMS_DEF_ENUM)
455 static const char *sms_names[]= {
456 #define SMS_DEF_NAME(s) #s ,
457 SMS_LIST(SMS_DEF_NAME)
463 int fd; /* may be 0, meaning closed (during construction/destruction) */
464 oop_read *rd; /* likewise */
465 int max_queue, stream, quitting;
466 int since_activity; /* periods */
467 ArticleList waiting; /* not yet told peer */
468 ArticleList priority; /* peer says send it now */
469 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
470 struct iovec xmit[CONNIOVS];
471 XmitDetails xmitd[CONNIOVS];
476 /*----- general operational variables -----*/
478 /* main initialises */
479 static oop_source *loop;
480 static ConnList conns;
481 static ArticleList queue;
482 static char *path_lock, *path_flushing, *path_defer, *path_control;
483 static char *globpat_backlog;
484 static pid_t self_pid;
486 /* statemc_init initialises */
487 static StateMachineState sms;
489 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
490 static int sm_period_counter;
492 /* initialisation to 0 is good */
493 static int until_connect, until_backlog_nextscan;
494 static double accept_proportion;
495 static int nocheck, nocheck_reported, in_child;
497 /* for simulation, debugging, etc. */
498 int simulate_flush= -1;
500 /*========== logging ==========*/
502 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
503 static void logcore(int sysloglevel, const char *fmt, ...) {
506 vsyslog(sysloglevel,fmt,al);
508 if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
509 vfprintf(stderr,fmt,al);
515 static void logv(int sysloglevel, const char *pfx, int errnoval,
516 const char *fmt, va_list al) PRINTF(5,0);
517 static void logv(int sysloglevel, const char *pfx, int errnoval,
518 const char *fmt, va_list al) {
519 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
520 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
521 msgbuf[sizeof(msgbuf)-1]= 0;
523 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
524 sysloglevel= LOG_ERR; /* run by wrong user, probably */
526 logcore(sysloglevel, "<%s>%s: %s%s%s",
527 sitename, pfx, msgbuf,
528 errnoval>=0 ? ": " : "",
529 errnoval>=0 ? strerror(errnoval) : "");
532 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
533 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
534 static void fn(const char *fmt, ...) { \
537 logv(sysloglevel, pfx, err, fmt, al); \
541 #define logwrap(fn, pfx, sysloglevel, err) \
542 static void fn(const char *fmt, ...) PRINTF(1,2); \
543 static void fn(const char *fmt, ...) { \
545 logv(sysloglevel, pfx, err, fmt, al); \
549 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
550 diewrap(die, " critical", LOG_CRIT, -1, 16);
552 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
553 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
555 logwrap(syswarn, " warning", LOG_WARNING, errno);
556 logwrap(warn, " warning", LOG_WARNING, -1);
558 logwrap(notice, " notice", LOG_NOTICE, -1);
559 logwrap(info, " info", LOG_INFO, -1);
560 logwrap(debug, " debug", LOG_DEBUG, -1);
563 /*========== utility functions etc. ==========*/
565 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
566 static char *xvasprintf(const char *fmt, va_list al) {
568 int rc= vasprintf(&str,fmt,al);
569 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
572 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
573 static char *xasprintf(const char *fmt, ...) {
575 char *str= xvasprintf(fmt,al);
580 static int close_perhaps(int *fd) {
581 if (*fd <= 0) return 0;
586 static void xclose(int fd, const char *what, const char *what2) {
588 if (r) sysdie("close %s%s",what,what2?what2:"");
590 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
591 if (*fd <= 0) return;
592 xclose(*fd,what,what2);
596 static pid_t xfork(const char *what) {
600 if (child==-1) sysfatal("cannot fork for %s",what);
601 debug("forked %s %ld", what, (unsigned long)child);
602 if (!child) postfork();
606 static void on_fd_read_except(int fd, oop_call_fd callback) {
607 loop->on_fd(loop, fd, OOP_READ, callback, 0);
608 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
610 static void cancel_fd_read_except(int fd) {
611 loop->cancel_fd(loop, fd, OOP_READ);
612 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
615 static void report_child_status(const char *what, int status) {
616 if (WIFEXITED(status)) {
617 int es= WEXITSTATUS(status);
619 warn("%s: child died with error exit status %d", what, es);
620 } else if (WIFSIGNALED(status)) {
621 int sig= WTERMSIG(status);
622 const char *sigstr= strsignal(sig);
623 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
625 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
627 warn("%s: child died due to unknown fatal signal %d%s",
628 what, sig, coredump);
630 warn("%s: child died with unknown wait status %d", what,status);
634 static int xwaitpid(pid_t *pid, const char *what) {
637 int r= kill(*pid, SIGKILL);
638 if (r) sysdie("cannot kill %s child", what);
640 pid_t got= waitpid(*pid, &status, 0);
641 if (got==-1) sysdie("cannot reap %s child", what);
642 if (got==0) die("cannot reap %s child", what);
649 static void xunlink(const char *path, const char *what) {
651 if (r) sysdie("can't unlink %s %s", path, what);
654 static time_t xtime(void) {
656 if (now==-1) sysdie("time(2) failed");
660 static void xsigaction(int s, const struct sigaction *sa) {
661 int r= sigaction(s,sa,0);
662 if (r) sysdie("sigaction failed for \"%s\"", strsignal(s));
665 static void xgettimeofday(struct timeval *tv_r) {
666 int r= gettimeofday(tv_r,0);
667 if (r) sysdie("gettimeofday(2) failed");
670 static void xsetnonblock(int fd, int nonblocking) {
671 int errnoval= oop_fd_nonblock(fd, nonblocking);
672 if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
675 static void check_isreg(const struct stat *stab, const char *path,
677 if (!S_ISREG(stab->st_mode))
678 die("%s %s not a plain file (mode 0%lo)",
679 what, path, (unsigned long)stab->st_mode);
682 static void xfstat(int fd, struct stat *stab_r, const char *what) {
683 int r= fstat(fd, stab_r);
684 if (r) sysdie("could not fstat %s", what);
687 static void xfstat_isreg(int fd, struct stat *stab_r,
688 const char *path, const char *what) {
689 xfstat(fd, stab_r, what);
690 check_isreg(stab_r, path, what);
693 static void xlstat_isreg(const char *path, struct stat *stab,
694 int *enoent_r /* 0 means ENOENT is fatal */,
696 int r= lstat(path, stab);
698 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
699 sysdie("could not lstat %s %s", what, path);
701 if (enoent_r) *enoent_r= 0;
702 check_isreg(stab, path, what);
705 static int samefile(const struct stat *a, const struct stat *b) {
706 assert(S_ISREG(a->st_mode));
707 assert(S_ISREG(b->st_mode));
708 return (a->st_ino == b->st_ino &&
709 a->st_dev == b->st_dev);
712 static char *sanitise(const char *input) {
713 static char sanibuf[100]; /* returns pointer to this buffer! */
715 const char *p= input;
719 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
721 if (!c) { *q++= '\''; *q=0; break; }
722 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
723 sprintf(q,"\\x%02x",c);
729 static int isewouldblock(int errnoval) {
730 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
734 /*========== command and control connections ==========*/
736 static int control_master;
738 typedef struct ControlConn ControlConn;
740 void (*destroy)(ControlConn*);
746 struct sockaddr_un un;
751 static const oop_rd_style control_rd_style= {
752 OOP_RD_DELIM_STRIP, '\n',
754 OOP_RD_SHORTREC_FORBID
757 static void control_destroy(ControlConn *cc) {
761 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
762 if (ferror(cc->out) | fflush(cc->out)) {
763 info("CTRL%d write error %s", cc->fd, strerror(errno));
768 static void control_prompt(ControlConn *cc /* may destroy*/) {
769 fprintf(cc->out, "%s| ", sitename);
770 control_checkouterr(cc);
773 typedef struct ControlCommand ControlCommand;
774 struct ControlCommand {
776 void (*f)(ControlConn *cc, const ControlCommand *ccmd,
777 const char *arg, size_t argsz);
782 static const ControlCommand control_commands[];
785 static void ccmd_##wh(ControlConn *cc, const ControlCommand *c, \
786 const char *arg, size_t argsz)
789 fputs("commands:\n", cc->out);
790 const ControlCommand *ccmd;
791 for (ccmd=control_commands; ccmd->cmd; ccmd++)
792 fprintf(cc->out, " %s\n", ccmd->cmd);
795 CCMD(period) { period(); }
796 CCMD(setintarg) { *(int*)c->xdata= atoi(arg); }
797 CCMD(setint) { *(int*)c->xdata= c->xval; }
798 CCMD(setint_period) { *(int*)c->xdata= c->xval; period(); }
802 notice("terminating (CTRL%d)",cc->fd);
807 static const ControlCommand control_commands[]= {
809 { "p", ccmd_period },
810 { "stop", ccmd_stop },
812 #define POKES(cmd,func) \
813 { cmd "sm", func, &sm_period_counter, 1 }, \
814 { cmd "conn", func, &until_connect, 0 }, \
815 { cmd "blscan", func, &until_backlog_nextscan, 0 },
816 POKES("prod ", ccmd_setint_period)
817 POKES("next ", ccmd_setint)
819 { "pretend flush", ccmd_setintarg, &simulate_flush },
820 { "wedge blscan", ccmd_setint, &until_backlog_nextscan, -1 },
824 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
825 const char *errmsg, int errnoval,
826 const char *data, size_t recsz, void *cc_v) {
827 ControlConn *cc= cc_v;
830 info("CTRL%d closed", cc->fd);
835 if (recsz == 0) goto prompt;
837 const ControlCommand *ccmd;
838 for (ccmd=control_commands; ccmd->cmd; ccmd++) {
839 int l= strlen(ccmd->cmd);
840 if (recsz < l) continue;
841 if (recsz > l && data[l] != ' ') continue;
842 if (memcmp(data, ccmd->cmd, l)) continue;
844 int argl= (int)recsz - (l+1);
845 ccmd->f(cc, ccmd, argl>=0 ? data+l+1 : 0, argl);
849 fputs("unknown command; h for help\n", cc->out);
856 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
857 const char *errmsg, int errnoval,
858 const char *data, size_t recsz, void *cc_v) {
859 ControlConn *cc= cc_v;
861 info("CTRL%d read error %s", cc->fd, errmsg);
866 static int control_conn_startup(ControlConn *cc /* may destroy*/,
868 cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
869 if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
871 int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
874 if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
876 info("CTRL%d %s ready", cc->fd, how);
881 static void control_stdio_destroy(ControlConn *cc) {
883 oop_rd_cancel(cc->rd);
884 errno= oop_rd_delete_tidy(cc->rd);
885 if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
890 static void control_stdio(void) {
891 ControlConn *cc= xmalloc(sizeof(*cc));
892 memset(cc,0,sizeof(*cc));
893 cc->destroy= control_stdio_destroy;
897 int r= control_conn_startup(cc,"stdio");
898 if (r) cc->destroy(cc);
901 static void control_accepted_destroy(ControlConn *cc) {
903 oop_rd_cancel(cc->rd);
904 oop_rd_delete_kill(cc->rd);
906 if (cc->out) { fclose(cc->out); cc->fd=0; }
907 close_perhaps(&cc->fd);
911 static void *control_master_readable(oop_source *lp, int master,
912 oop_event ev, void *u) {
913 ControlConn *cc= xmalloc(sizeof(*cc));
914 memset(cc,0,sizeof(*cc));
915 cc->destroy= control_accepted_destroy;
917 cc->salen= sizeof(cc->sa);
918 cc->fd= accept(master, &cc->sa.sa, &cc->salen);
919 if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
921 cc->out= fdopen(cc->fd, "w");
922 if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
924 int r= control_conn_startup(cc, "accepted");
934 #define NOCONTROL(...) do{ \
935 syswarn("no control socket, because failed to " __VA_ARGS__); \
939 static void control_init(void) {
944 struct sockaddr_un un;
947 memset(&sa,0,sizeof(sa));
948 int maxlen= sizeof(sa.un.sun_path);
950 int reallen= readlink(path_control, sa.un.sun_path, maxlen);
953 NOCONTROL("readlink control socket symlink path %s", path_control);
955 if (reallen >= maxlen) {
956 debug("control socket symlink path too long (r=%d)",reallen);
957 xunlink(path_control, "old (overlong) control socket symlink");
963 int r= lstat(realsockdir,&stab);
965 if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
967 r= mkdir(realsockdir, 0700);
968 if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
971 uid_t self= geteuid();
972 if (!S_ISDIR(stab.st_mode) ||
973 stab.st_uid != self ||
974 stab.st_mode & 0007) {
975 warn("no control socket, because real socket directory"
976 " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
977 !!S_ISDIR(stab.st_mode),
978 (unsigned long)stab.st_uid, (unsigned long)self,
979 (unsigned long)stab.st_mode & 0777UL);
984 real= xasprintf("%s/s%lx.%lx", realsockdir,
985 (unsigned long)xtime(), (unsigned long)self_pid);
986 int reallen= strlen(real);
988 if (reallen >= maxlen) {
989 warn("no control socket, because tmpnam gave overly-long path"
993 r= symlink(real, path_control);
994 if (r) NOCONTROL("make control socket path %s a symlink to real"
995 " socket path %s", path_control, real);
996 memcpy(sa.un.sun_path, real, reallen);
999 int r= unlink(sa.un.sun_path);
1000 if (r && errno!=ENOENT)
1001 NOCONTROL("remove old real socket %s", sa.un.sun_path);
1003 control_master= socket(PF_UNIX, SOCK_STREAM, 0);
1004 if (control_master<0) NOCONTROL("create new control socket");
1006 sa.un.sun_family= AF_UNIX;
1007 int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
1008 r= bind(control_master, &sa.sa, sl);
1009 if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
1011 r= listen(control_master, 5);
1012 if (r) NOCONTROL("listen");
1014 xsetnonblock(control_master, 1);
1016 loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
1017 info("control socket ok, real path %s", sa.un.sun_path);
1023 xclose_perhaps(&control_master, "control master",0);
1027 /*========== management of connections ==========*/
1029 static void conn_closefd(Conn *conn, const char *msgprefix) {
1030 int r= close_perhaps(&conn->fd);
1031 if (r) info("C%d %serror closing socket: %s",
1032 conn->fd, msgprefix, strerror(errno));
1035 static void conn_dispose(Conn *conn) {
1038 oop_rd_cancel(conn->rd);
1039 oop_rd_delete_kill(conn->rd);
1043 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1044 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
1046 conn_closefd(conn,"");
1048 until_connect= reconnect_delay_periods;
1051 static void *conn_exception(oop_source *lp, int fd,
1052 oop_event ev, void *conn_v) {
1055 assert(fd == conn->fd);
1056 assert(ev == OOP_EXCEPTION);
1057 int r= read(conn->fd, &ch, 1);
1058 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1059 else connfail(conn,"exceptional condition on socket (peer sent urgent"
1060 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1061 return OOP_CONTINUE;
1064 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1065 int requeue[art_MaxState];
1066 memset(requeue,0,sizeof(requeue));
1069 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1070 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1071 while ((art= LIST_REMHEAD(conn->sent))) {
1072 requeue[art->state]++;
1073 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1074 LIST_ADDTAIL(queue,art);
1079 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1082 char *m= xvasprintf(fmt,al);
1083 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1084 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1087 LIST_REMOVE(conns,conn);
1089 check_assign_articles();
1092 static void connfail(Conn *conn, const char *fmt, ...) {
1095 vconnfail(conn,fmt,al);
1099 static void check_idle_conns(void) {
1101 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
1102 conn->since_activity++;
1104 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
1105 if (conn->since_activity <= need_activity_periods) continue;
1107 /* We need to shut this down */
1109 connfail(conn,"timed out waiting for response to QUIT");
1110 else if (conn->sent.count)
1111 connfail(conn,"timed out waiting for responses");
1112 else if (conn->waiting.count || conn->priority.count)
1113 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1114 else if (conn->xmitu)
1115 connfail(conn,"peer has been sending responses"
1116 " before receiving our commands!");
1118 static const char quitcmd[]= "QUIT\r\n";
1119 int todo= sizeof(quitcmd)-1;
1120 const char *p= quitcmd;
1122 int r= write(conn->fd, p, todo);
1124 if (isewouldblock(errno))
1125 connfail(conn, "blocked writing QUIT to idle connection");
1127 connfail(conn, "failed to write QUIT to idle connection: %s",
1135 conn->since_activity= 0;
1136 debug("C%d is idle, quitting", conn->fd);
1145 /*---------- making new connections ----------*/
1147 static pid_t connecting_child;
1148 static int connecting_fdpass_sock;
1150 static void connect_attempt_discard(void) {
1151 if (connecting_child) {
1152 int status= xwaitpid(&connecting_child, "connect");
1153 if (!(WIFEXITED(status) ||
1154 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1155 report_child_status("connect", status);
1157 if (connecting_fdpass_sock) {
1158 cancel_fd_read_except(connecting_fdpass_sock);
1159 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1163 #define PREP_DECL_MSG_CMSG(msg) \
1165 struct iovec msgiov; \
1166 msgiov.iov_base= &msgbyte; \
1167 msgiov.iov_len= 1; \
1168 struct msghdr msg; \
1169 memset(&msg,0,sizeof(msg)); \
1170 char msg##cbuf[CMSG_SPACE(sizeof(int))]; \
1171 msg.msg_iov= &msgiov; \
1172 msg.msg_iovlen= 1; \
1173 msg.msg_control= msg##cbuf; \
1174 msg.msg_controllen= sizeof(msg##cbuf);
1176 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1179 assert(fd == connecting_fdpass_sock);
1181 PREP_DECL_MSG_CMSG(msg);
1183 ssize_t rs= recvmsg(fd, &msg, 0);
1185 if (isewouldblock(errno)) return OOP_CONTINUE;
1186 syswarn("failed to read socket from connecting child");
1190 conn= xmalloc(sizeof(*conn));
1191 memset(conn,0,sizeof(*conn));
1192 LIST_INIT(conn->waiting);
1193 LIST_INIT(conn->priority);
1194 LIST_INIT(conn->sent);
1196 struct cmsghdr *h= 0;
1197 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1199 int status= xwaitpid(&connecting_child, "connect child (broken)");
1201 if (WIFEXITED(status)) {
1202 if (WEXITSTATUS(status) != 0 &&
1203 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1204 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1205 /* child already reported the problem */;
1207 if (e == OOP_EXCEPTION)
1208 warn("connect: connection child exited code %d but"
1209 " unexpected exception on fdpass socket",
1210 WEXITSTATUS(status));
1212 warn("connect: connection child exited code %d but"
1214 WEXITSTATUS(status), (int)rs);
1216 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1217 warn("connect: connection attempt timed out");
1219 report_child_status("connect", status);
1224 #define CHK(field, val) \
1225 if (h->cmsg_##field != val) { \
1226 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1227 h->cmsg_##field, val); \
1230 CHK(level, SOL_SOCKET);
1231 CHK(type, SCM_RIGHTS);
1232 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1235 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1237 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1240 pid_t got= waitpid(connecting_child, &status, 0);
1241 if (got==-1) sysdie("connect: real wait for child");
1242 assert(got == connecting_child);
1243 connecting_child= 0;
1245 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1246 int es= WEXITSTATUS(status);
1248 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1249 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1251 fatal("connect: child gave unexpected exit status %d", es);
1255 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1257 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1258 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1259 if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1260 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1262 &peer_rd_err, conn);
1263 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1265 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1266 LIST_ADDHEAD(conns, conn);
1268 connect_attempt_discard();
1269 check_assign_articles();
1270 return OOP_CONTINUE;
1274 connect_attempt_discard();
1275 return OOP_CONTINUE;
1278 static int allow_connect_start(void) {
1279 return conns.count < max_connections
1280 && !connecting_child
1284 static void connect_start(void) {
1285 assert(!connecting_child);
1286 assert(!connecting_fdpass_sock);
1288 info("starting connection attempt");
1291 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1292 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1294 connecting_child= xfork("connection");
1296 if (!connecting_child) {
1297 FILE *cn_from, *cn_to;
1298 char buf[NNTP_STRLEN+100];
1299 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1301 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1303 alarm(connection_setup_timeout);
1304 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1308 unsigned char c= buf[l-1];
1309 if (!isspace(c)) break;
1310 if (c=='\n' || c=='\r') stripped=1;
1314 sysfatal("connect: connection attempt failed");
1317 fatal("connect: %s: %s", stripped ? "rejected" : "failed",
1321 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1322 sysfatal("connect: authentication failed");
1324 if (fputs("MODE STREAM\r\n", cn_to)==EOF ||
1326 sysfatal("connect: could not send MODE STREAM");
1327 buf[sizeof(buf)-1]= 0;
1328 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1329 if (ferror(cn_from))
1330 sysfatal("connect: could not read response to MODE STREAM");
1332 fatal("connect: connection close in response to MODE STREAM");
1337 fatal("connect: response to MODE STREAM is too long: %.100s...",
1339 l--; if (l>0 && buf[l-1]=='\r') l--;
1342 int rcode= strtoul(buf,&ep,10);
1344 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
1348 exitstatus= CONNCHILD_ESTATUS_STREAM;
1354 warn("connect: unexpected response to MODE STREAM: %.50s",
1360 int fd= fileno(cn_from);
1362 PREP_DECL_MSG_CMSG(msg);
1363 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1364 cmsg->cmsg_level= SOL_SOCKET;
1365 cmsg->cmsg_type= SCM_RIGHTS;
1366 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1367 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1369 msg.msg_controllen= cmsg->cmsg_len;
1370 r= sendmsg(socks[1], &msg, 0);
1371 if (r<0) sysdie("sendmsg failed for new connection");
1372 if (r!=1) die("sendmsg for new connection gave wrong result %d",r);
1377 xclose(socks[1], "connecting fdpass child's socket",0);
1378 connecting_fdpass_sock= socks[0];
1379 xsetnonblock(connecting_fdpass_sock, 1);
1380 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1383 /*---------- assigning articles to conns, and transmitting ----------*/
1385 static void check_assign_articles(void) {
1391 int spare=0, inqueue=0;
1393 /* Find a connection to offer this article. We prefer a busy
1394 * connection to an idle one, provided it's not full. We take the
1395 * first (oldest) and since that's stable, it will mean we fill up
1396 * connections in order. That way if we have too many
1397 * connections, the spare ones will go away eventually.
1399 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1400 if (walk->quitting) continue;
1401 inqueue= walk->sent.count + walk->priority.count
1402 + walk->waiting.count;
1403 spare= walk->max_queue - inqueue;
1404 assert(inqueue <= max_queue_per_conn);
1406 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1407 else if (spare>0) /*working*/ { use= walk; break; }
1410 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1412 Article *art= LIST_REMHEAD(queue);
1414 LIST_ADDTAIL(use->waiting, art);
1417 conn_maybe_write(use);
1418 } else if (allow_connect_start()) {
1419 until_connect= reconnect_delay_periods;
1428 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1429 conn_maybe_write(u);
1430 return OOP_CONTINUE;
1433 static void conn_maybe_write(Conn *conn) {
1435 conn_make_some_xmits(conn);
1437 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1441 void *rp= conn_write_some_xmits(conn);
1442 if (rp==OOP_CONTINUE) {
1443 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1445 } else if (rp==OOP_HALT) {
1448 /* transmitted everything */
1455 /*========== article transmission ==========*/
1457 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1458 XmitKind kind) { /* caller must then fill in details */
1459 struct iovec *v= &conn->xmit[conn->xmitu];
1460 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1461 v->iov_base= (char*)data;
1467 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1468 xmit_core(conn,data,len, xk_Const);
1470 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1472 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1473 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1477 static void xmit_free(XmitDetails *d) {
1479 case xk_Malloc: free(d->info.malloc_tofree); break;
1480 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1481 case xk_Const: break;
1486 static void *conn_write_some_xmits(Conn *conn) {
1488 * 0: nothing more to write, no need to call us again
1489 * OOP_CONTINUE: more to write but fd not writeable
1490 * OOP_HALT: disaster, have destroyed conn
1493 int count= conn->xmitu;
1494 if (!count) return 0;
1496 if (count > IOV_MAX) count= IOV_MAX;
1497 ssize_t rs= writev(conn->fd, conn->xmit, count);
1499 if (isewouldblock(errno)) return OOP_CONTINUE;
1500 connfail(conn, "write failed: %s", strerror(errno));
1506 for (done=0; rs && done<conn->xmitu; done++) {
1507 struct iovec *vp= &conn->xmit[done];
1508 XmitDetails *dp= &conn->xmitd[done];
1509 if (rs > vp->iov_len) {
1513 vp->iov_base= (char*)vp->iov_base + rs;
1517 int newu= conn->xmitu - done;
1518 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1519 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1524 static void conn_make_some_xmits(Conn *conn) {
1526 if (conn->xmitu+5 > CONNIOVS)
1529 Article *art= LIST_REMHEAD(conn->priority);
1530 if (!art) art= LIST_REMHEAD(conn->waiting);
1533 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1534 /* actually send it */
1536 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1539 art->state == art_Unchecked ? art_Unsolicited :
1540 art->state == art_Wanted ? art_Wanted :
1543 if (!artdata) art->missing= 1;
1544 art->ipf->counts[art->state][ artdata ? RC_sent : RC_missing ]++;
1548 XMIT_LITERAL("TAKETHIS ");
1549 xmit_noalloc(conn, art->messageid, art->midlen);
1550 XMIT_LITERAL("\r\n");
1551 xmit_artbody(conn, artdata);
1553 article_done(conn, art, -1);
1557 /* we got 235 from IHAVE */
1559 xmit_artbody(conn, artdata);
1561 XMIT_LITERAL(".\r\n");
1565 LIST_ADDTAIL(conn->sent, art);
1571 XMIT_LITERAL("CHECK ");
1573 XMIT_LITERAL("IHAVE ");
1574 xmit_noalloc(conn, art->messageid, art->midlen);
1575 XMIT_LITERAL("\r\n");
1577 assert(art->state == art_Unchecked);
1578 art->ipf->counts[art->state][RC_sent]++;
1579 LIST_ADDTAIL(conn->sent, art);
1585 /*========== handling responses from peer ==========*/
1587 static const oop_rd_style peer_rd_style= {
1588 OOP_RD_DELIM_STRIP, '\n',
1590 OOP_RD_SHORTREC_FORBID
1593 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1594 const char *errmsg, int errnoval,
1595 const char *data, size_t recsz, void *conn_v) {
1597 connfail(conn, "error receiving from peer: %s", errmsg);
1598 return OOP_CONTINUE;
1601 static Article *article_reply_check(Conn *conn, const char *response,
1602 int code_indicates_streaming,
1604 /* 1:yes, -1:no, 0:dontcare */,
1605 const char *sanitised_response) {
1606 Article *art= LIST_HEAD(conn->sent);
1610 "peer gave unexpected response when no commands outstanding: %s",
1611 sanitised_response);
1615 if (code_indicates_streaming) {
1616 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1617 if (!conn->stream) {
1618 connfail(conn, "peer gave streaming response code "
1619 " to IHAVE or subsequent body: %s", sanitised_response);
1622 const char *got_mid= response+4;
1623 int got_midlen= strcspn(got_mid, " \n\r");
1624 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1625 connfail(conn, "peer gave streaming response with syntactically invalid"
1626 " messageid: %s", sanitised_response);
1629 if (got_midlen != art->midlen ||
1630 memcmp(got_mid, art->messageid, got_midlen)) {
1631 connfail(conn, "peer gave streaming response code to wrong article -"
1632 " probable synchronisation problem; we offered: %s;"
1634 art->messageid, sanitised_response);
1639 connfail(conn, "peer gave non-streaming response code to"
1640 " CHECK/TAKETHIS: %s", sanitised_response);
1645 if (must_have_sent>0 && art->state < art_Wanted) {
1646 connfail(conn, "peer says article accepted but"
1647 " we had not sent the body: %s", sanitised_response);
1650 if (must_have_sent<0 && art->state >= art_Wanted) {
1651 connfail(conn, "peer says please sent the article but we just did: %s",
1652 sanitised_response);
1656 Article *art_again= LIST_REMHEAD(conn->sent);
1657 assert(art_again == art);
1661 static void update_nocheck(int accepted) {
1662 accept_proportion *= nocheck_decay;
1663 accept_proportion += accepted * (1.0 - nocheck_decay);
1664 int new_nocheck= accept_proportion >= nocheck_thresh;
1665 if (new_nocheck && !nocheck_reported) {
1666 notice("entering nocheck mode for the first time");
1667 nocheck_reported= 1;
1668 } else if (new_nocheck != nocheck) {
1669 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1671 nocheck= new_nocheck;
1674 static void article_done(Conn *conn, Article *art, int whichcount) {
1675 if (!art->missing) art->ipf->counts[art->state][whichcount]++;
1677 if (whichcount == RC_accepted) update_nocheck(1);
1678 else if (whichcount == RC_unwanted) update_nocheck(0);
1680 InputFile *ipf= art->ipf;
1682 while (art->blanklen) {
1683 static const char spaces[]=
1693 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1694 int r= pwrite(ipf->fd, spaces, w, art->offset);
1696 if (errno==EINTR) continue;
1697 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1698 art->messageid, art->blanklen,
1699 (unsigned long)art->offset, ipf->path);
1701 assert(r>=0 && r<=w);
1707 assert(ipf->inprogress >= 0);
1710 if (!ipf->inprogress && ipf != main_input_file)
1711 queue_check_input_done();
1714 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1715 const char *errmsg, int errnoval,
1716 const char *data, size_t recsz, void *conn_v) {
1719 if (ev == OOP_RD_EOF) {
1720 connfail(conn, "unexpected EOF from peer");
1721 return OOP_CONTINUE;
1723 assert(ev == OOP_RD_OK);
1725 char *sani= sanitise(data);
1728 unsigned long code= strtoul(data, &ep, 10);
1729 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1730 connfail(conn, "badly formatted response from peer: %s", sani);
1731 return OOP_CONTINUE;
1735 conn->waiting.count ||
1736 conn->priority.count ||
1740 if (conn->quitting) {
1741 if (code!=205 && code!=503) {
1742 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1744 notice("C%d idle connection closed by us", conn->fd);
1746 LIST_REMOVE(conns,conn);
1749 return OOP_CONTINUE;
1752 conn->since_activity= 0;
1755 #define GET_ARTICLE(musthavesent) do{ \
1756 art= article_reply_check(conn, data, code_streaming, musthavesent, sani); \
1757 if (!art) return OOP_CONTINUE; /* reply_check has failed the conn */ \
1760 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) do{ \
1761 code_streaming= (streaming); \
1762 GET_ARTICLE(musthavesent); \
1763 article_done(conn, art, RC_##how); \
1767 #define PEERBADMSG(m) do { \
1768 connfail(conn, m ": %s", sani); return OOP_CONTINUE; \
1771 int code_streaming= 0;
1775 case 400: PEERBADMSG("peer stopped accepting articles");
1776 default: PEERBADMSG("peer sent unexpected message");
1779 if (conn_busy) PEERBADMSG("peer timed us out");
1780 notice("C%d idle connection closed by peer", conn->fd);
1781 LIST_REMOVE(conns,conn);
1783 return OOP_CONTINUE;
1785 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1786 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1788 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1789 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1791 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1792 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1794 case 238: /* CHECK says send it */
1796 case 335: /* IHAVE says send it */
1798 assert(art->state == art_Unchecked);
1799 art->ipf->counts[art->state][RC_accepted]++;
1800 art->state= art_Wanted;
1801 LIST_ADDTAIL(conn->priority, art);
1804 case 431: /* CHECK or TAKETHIS says try later */
1806 case 436: /* IHAVE says try later */
1809 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1811 sysfatal("write to defer file %s",path_defer);
1812 article_done(conn, art, RC_deferred);
1818 conn_maybe_write(conn);
1819 check_assign_articles();
1820 return OOP_CONTINUE;
1824 /*========== monitoring of input files ==========*/
1826 static void feedfile_eof(InputFile *ipf) {
1827 assert(ipf != main_input_file); /* promised by tailing_try_read */
1828 inputfile_reading_stop(ipf);
1830 if (ipf == flushing_input_file) {
1831 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1832 if (main_input_file) inputfile_reading_start(main_input_file);
1833 statemc_check_flushing_done();
1834 } else if (ipf == backlog_input_file) {
1835 statemc_check_backlog_done();
1837 abort(); /* supposed to wait rather than get EOF on main input file */
1841 static InputFile *open_input_file(const char *path) {
1842 int fd= open(path, O_RDWR);
1844 if (errno==ENOENT) return 0;
1845 sysfatal("unable to open input file %s", path);
1849 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1850 memset(ipf,0,sizeof(*ipf));
1853 strcpy(ipf->path, path);
1858 static void close_input_file(InputFile *ipf) { /* does not free */
1859 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1860 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1861 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1862 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1863 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1867 /*---------- dealing with articles read in the input file ----------*/
1869 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1870 const char *data, const char *how) {
1871 warn("corrupted file: %s, offset %lu: %s: in %s",
1872 ipf->path, (unsigned long)offset, how, sanitise(data));
1873 ipf->readcount_err++;
1874 if (ipf->readcount_err > max_bad_data_initial +
1875 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1876 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1877 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1878 return OOP_CONTINUE;
1881 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1882 oop_rd_event ev, const char *errmsg,
1883 int errnoval, const char *data, size_t recsz,
1885 InputFile *ipf= ipf_v;
1886 assert(ev == OOP_RD_SYSTEM);
1888 sysdie("error reading input file: %s, offset %lu",
1889 ipf->path, (unsigned long)ipf->offset);
1892 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1893 oop_rd_event ev, const char *errmsg,
1894 int errnoval, const char *data, size_t recsz,
1896 InputFile *ipf= ipf_v;
1898 char tokentextbuf[sizeof(TOKEN)*2+3];
1900 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1902 off_t old_offset= ipf->offset;
1903 ipf->offset += recsz + 1;
1905 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1907 if (ev==OOP_RD_PARTREC)
1908 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1909 /* but process it anyway */
1911 if (ipf->skippinglong) {
1912 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1913 return OOP_CONTINUE;
1915 if (ev==OOP_RD_LONG) {
1916 ipf->skippinglong= 1;
1917 X_BAD_DATA("overly long line");
1920 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1921 if (!recsz) X_BAD_DATA("empty line");
1924 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1925 ipf->readcount_blank++;
1926 return OOP_CONTINUE;
1929 char *space= strchr(data,' ');
1930 int tokenlen= space-data;
1931 int midlen= (int)recsz-tokenlen-1;
1932 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1933 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1935 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1936 memcpy(tokentextbuf, data, tokenlen);
1937 tokentextbuf[tokenlen]= 0;
1938 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1940 ipf->readcount_ok++;
1942 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1943 art->state= art_Unchecked;
1944 art->midlen= midlen;
1945 art->ipf= ipf; ipf->inprogress++;
1946 art->token= TextToToken(tokentextbuf);
1947 art->offset= old_offset;
1948 art->blanklen= recsz;
1949 strcpy(art->messageid, space+1);
1950 LIST_ADDTAIL(queue, art);
1952 if (sms==sm_NORMAL && ipf==main_input_file &&
1953 ipf->offset >= target_max_feedfile_size)
1954 statemc_start_flush("feed file size");
1956 check_assign_articles();
1957 return OOP_CONTINUE;
1960 /*========== tailing input file ==========*/
1962 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1964 InputFile *ipf= user;
1965 return ipf->readable_callback(loop, &ipf->readable,
1966 ipf->readable_callback_user);
1969 static void tailing_on_cancel(struct oop_readable *rable) {
1970 InputFile *ipf= (void*)rable;
1972 if (ipf->filemon) filemon_stop(ipf);
1973 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1974 ipf->readable_callback= 0;
1977 static void tailing_queue_readable(InputFile *ipf) {
1978 /* lifetime of ipf here is OK because destruction will cause
1979 * on_cancel which will cancel this callback */
1980 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1983 static int tailing_on_readable(struct oop_readable *rable,
1984 oop_readable_call *cb, void *user) {
1985 InputFile *ipf= (void*)rable;
1987 tailing_on_cancel(rable);
1988 ipf->readable_callback= cb;
1989 ipf->readable_callback_user= user;
1992 tailing_queue_readable(ipf);
1996 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1998 InputFile *ipf= (void*)rable;
2000 ssize_t r= read(ipf->fd, buffer, length);
2002 if (errno==EINTR) continue;
2006 if (ipf==main_input_file) {
2009 } else if (ipf==flushing_input_file) {
2011 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2012 } else if (ipf==backlog_input_file) {
2018 tailing_queue_readable(ipf);
2023 /*---------- filemon implemented with inotify ----------*/
2025 #if defined(HAVE_SYS_INOTIFY_H) && !defined(HAVE_FILEMON)
2026 #define HAVE_FILEMON
2028 #include <sys/inotify.h>
2030 static int filemon_inotify_fd;
2031 static int filemon_inotify_wdmax;
2032 static InputFile **filemon_inotify_wd2ipf;
2034 struct Filemon_Perfile {
2038 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
2039 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
2040 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
2042 if (wd >= filemon_inotify_wdmax) {
2044 filemon_inotify_wd2ipf= xrealloc(filemon_inotify_wd2ipf,
2045 sizeof(*filemon_inotify_wd2ipf) * newmax);
2046 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
2047 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
2048 filemon_inotify_wdmax= newmax;
2051 assert(!filemon_inotify_wd2ipf[wd]);
2052 filemon_inotify_wd2ipf[wd]= ipf;
2054 debug("filemon inotify startfile %p wd=%d wdmax=%d",
2055 ipf, wd, filemon_inotify_wdmax);
2060 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
2062 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
2063 int r= inotify_rm_watch(filemon_inotify_fd, wd);
2064 if (r) sysdie("inotify_rm_watch");
2065 filemon_inotify_wd2ipf[wd]= 0;
2068 static void *filemon_inotify_readable(oop_source *lp, int fd,
2069 oop_event e, void *u) {
2070 struct inotify_event iev;
2072 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
2074 if (isewouldblock(errno)) break;
2075 sysdie("read from inotify master");
2076 } else if (r==sizeof(iev)) {
2077 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
2079 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
2081 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
2082 debug("filemon inotify readable read %p wd=%d", ipf, iev.wd);
2083 filemon_callback(ipf);
2085 return OOP_CONTINUE;
2088 static int filemon_method_init(void) {
2089 filemon_inotify_fd= inotify_init();
2090 if (filemon_inotify_fd<0) {
2091 syswarn("filemon/inotify: inotify_init failed");
2094 xsetnonblock(filemon_inotify_fd, 1);
2095 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable, 0);
2097 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2101 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2103 /*---------- filemon dummy implementation ----------*/
2105 #if !defined(HAVE_FILEMON)
2107 struct Filemon_Perfile { int dummy; };
2109 static int filemon_method_init(void) {
2110 warn("filemon/dummy: no filemon method compiled in");
2113 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2114 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2116 #endif /* !HAVE_FILEMON */
2118 /*---------- filemon generic interface ----------*/
2120 static void filemon_start(InputFile *ipf) {
2121 assert(!ipf->filemon);
2123 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
2124 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
2125 filemon_method_startfile(ipf, ipf->filemon);
2128 static void filemon_stop(InputFile *ipf) {
2129 if (!ipf->filemon) return;
2130 filemon_method_stopfile(ipf, ipf->filemon);
2135 static void filemon_callback(InputFile *ipf) {
2136 if (ipf && ipf->readable_callback) /* so filepoll() can be naive */
2137 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2140 /*---------- interface to start and stop an input file ----------*/
2142 static const oop_rd_style feedfile_rdstyle= {
2143 OOP_RD_DELIM_STRIP, '\n',
2145 OOP_RD_SHORTREC_LONG,
2148 static void inputfile_reading_start(InputFile *ipf) {
2150 ipf->readable.on_readable= tailing_on_readable;
2151 ipf->readable.on_cancel= tailing_on_cancel;
2152 ipf->readable.try_read= tailing_try_read;
2153 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2154 ipf->readable.delete_kill= 0;
2156 ipf->readable_callback= 0;
2157 ipf->readable_callback_user= 0;
2159 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2162 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2163 feedfile_got_article,ipf, feedfile_read_err, ipf);
2164 if (r) sysdie("unable start reading feedfile %s",ipf->path);
2167 static void inputfile_reading_stop(InputFile *ipf) {
2169 oop_rd_cancel(ipf->rd);
2170 oop_rd_delete(ipf->rd);
2172 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2176 /*========== interaction with innd - state machine ==========*/
2178 /* See official state diagram at top of file. We implement
2189 |`---------------------------------------------------.
2191 |`---------------- - - - |
2192 D ENOENT | D EXISTS see OVERALL STATES diagram |
2193 | for full startup logic |
2196 | ============ try to |
2202 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
2203 ^ | hardlink F to D |
2206 | | our handle onto F is now onto D |
2209 | |<-------------------<---------------------<---------+
2211 | | spawn inndcomm flush |
2213 | ================== |
2214 | FLUSHING[-ABSENT] |
2216 | main D tail/none |
2217 | ================== |
2219 | | INNDCOMM FLUSH FAILS ^
2220 | |`----------------------->----------. |
2222 | | NO SUCH SITE V |
2223 ^ |`--------------->----. ==================== |
2224 | | \ FLUSHFAILED[-ABSENT] |
2226 | | FLUSH OK \ main D tail/none |
2227 | | open F \ ==================== |
2229 | | \ | TIME TO RETRY |
2230 | |`------->----. ,---<---'\ `----------------'
2231 | | D NONE | | D NONE `----.
2233 | ============= V V ============
2234 | SEPARATED-1 | | DROPPING-1
2235 | flsh->rd!=0 | | flsh->rd!=0
2236 | [Separated] | | [Dropping]
2237 | main F idle | | main none
2238 | old D tail | | old D tail
2239 | ============= | | ============
2241 ^ | EOF ON D | | defer | EOF ON D
2243 | =============== | | ===============
2244 | SEPARATED-2 | | DROPPING-2
2245 | flsh->rd==0 | V flsh->rd==0
2246 | [Finishing] | | [Dropping]
2247 | main F tail | `. main none
2248 | old D closed | `. old D closed
2249 | =============== V `. ===============
2251 | | ALL D PROCESSED `. | ALL D PROCESSED
2252 | V install defer as backlog `. | install defer
2253 ^ | close D `. | close D
2254 | | unlink D `. | unlink D
2257 `----------' ==============
2277 static void startup_set_input_file(InputFile *f) {
2278 assert(!main_input_file);
2280 inputfile_reading_start(f);
2283 static void statemc_lock(void) {
2285 struct stat stab, stabf;
2288 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2289 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2292 memset(&fl,0,sizeof(fl));
2294 fl.l_whence= SEEK_SET;
2295 int r= fcntl(lockfd, F_SETLK, &fl);
2297 if (errno==EACCES || isewouldblock(errno)) {
2298 if (quiet_multiple) exit(0);
2299 fatal("another duct holds the lockfile");
2301 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2304 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2306 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2308 if (!lock_noent && samefile(&stab, &stabf))
2311 xclose(lockfd, "stale lockfile ", path_lock);
2314 FILE *lockfile= fdopen(lockfd, "w");
2315 if (!lockfile) sysdie("fdopen lockfile");
2317 int r= ftruncate(lockfd, 0);
2318 if (r) sysdie("truncate lockfile to write new info");
2320 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2321 (unsigned long)self_pid,
2322 sitename, feedfile, remote_host) == EOF ||
2324 sysfatal("write info to lockfile %s", path_lock);
2326 debug("startup: locked");
2329 static void statemc_init(void) {
2330 struct stat stabdefer;
2332 search_backlog_file();
2335 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2337 debug("startup: ductdefer ENOENT");
2339 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2340 switch (stabdefer.st_nlink==1) {
2342 open_defer(); /* so that we will later close it and rename it */
2345 xunlink(path_defer, "stale defer file link"
2346 " (presumably hardlink to backlog file)");
2349 die("defer file %s has unexpected link count %d",
2350 path_defer, stabdefer.st_nlink);
2354 struct stat stab_f, stab_d;
2357 InputFile *file_d= open_input_file(path_flushing);
2358 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2360 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2362 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2363 debug("startup: F==D => Hardlinked");
2364 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2369 debug("startup: F ENOENT => Moved");
2370 if (file_d) startup_set_input_file(file_d);
2371 spawn_inndcomm_flush("feedfile missing at startup");
2372 /* => Flushing, sms:=FLUSHING */
2375 debug("startup: F!=D => Separated");
2376 startup_set_input_file(file_d);
2377 SMS(SEPARATED, 0, "found both old and current feed files");
2379 debug("startup: F exists, D ENOENT => Normal");
2380 InputFile *file_f= open_input_file(feedfile);
2381 if (!file_f) die("feed file vanished during startup");
2382 startup_set_input_file(file_f);
2383 SMS(NORMAL, spontaneous_flush_periods, "normal startup");
2388 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2389 assert(sms == sm_NORMAL);
2391 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2393 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2394 (unsigned long)target_max_feedfile_size,
2397 int r= link(feedfile, path_flushing);
2398 if (r) sysfatal("link feedfile %s to flushing file %s",
2399 feedfile, path_flushing);
2402 xunlink(feedfile, "old feedfile link");
2405 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2408 static void statemc_period_poll(void) {
2409 if (!sm_period_counter) return;
2410 sm_period_counter--;
2411 assert(sm_period_counter>=0);
2413 if (sm_period_counter) return;
2416 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2418 case sm_FLUSHFAILED:
2419 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2426 static int inputfile_is_done(InputFile *ipf) {
2428 if (ipf->inprogress) return 0; /* new article in the meantime */
2429 if (ipf->rd) return 0; /* not had EOF */
2433 static void notice_processed(InputFile *ipf, int completed,
2434 const char *what, const char *spec) {
2435 if (!ipf) return; /* allows preterminate to be lazy */
2437 #define RCI_NOTHING(x) /* nothing */
2438 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2439 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2441 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2443 char *inprog= completed
2444 ? xasprintf("%s","") /* GCC produces a stupid warning for printf("") ! */
2445 : xasprintf(" inprogress=%ld", ipf->inprogress);
2447 info("%s %s%s read=%d (+bl=%d,+err=%d)%s"
2448 " offered=%d (ch=%d,nc=%d) accepted=%d (ch=%d,nc=%d)"
2449 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2451 completed?"completed":"processed", what, spec,
2452 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err, inprog,
2453 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2454 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2455 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2456 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2457 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2465 static void statemc_check_backlog_done(void) {
2466 InputFile *ipf= backlog_input_file;
2467 if (!inputfile_is_done(ipf)) return;
2469 const char *slash= strrchr(ipf->path, '/');
2470 const char *leaf= slash ? slash+1 : ipf->path;
2471 const char *under= strchr(slash, '_');
2472 const char *rest= under ? under+1 : leaf;
2473 if (!strncmp(rest,"backlog",7)) rest += 7;
2474 notice_processed(ipf,1,"backlog ",rest);
2476 close_input_file(ipf);
2477 if (unlink(ipf->path)) {
2478 if (errno != ENOENT)
2479 sysdie("could not unlink processed backlog file %s", ipf->path);
2480 warn("backlog file %s vanished while we were reading it"
2481 " so we couldn't remove it (but it's done now, anyway)",
2485 backlog_input_file= 0;
2486 search_backlog_file();
2490 static void statemc_check_flushing_done(void) {
2491 InputFile *ipf= flushing_input_file;
2492 if (!inputfile_is_done(ipf)) return;
2494 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2496 notice_processed(ipf,1,"feedfile","");
2500 xunlink(path_flushing, "old flushing file");
2502 close_input_file(flushing_input_file);
2503 free(flushing_input_file);
2504 flushing_input_file= 0;
2506 if (sms==sm_SEPARATED) {
2507 notice("flush complete");
2508 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2509 } else if (sms==sm_DROPPING) {
2510 SMS(DROPPED, 0, "old flush complete");
2511 search_backlog_file();
2512 notice("feed dropped, but will continue until backlog is finished");
2516 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2518 assert(!inputfile_is_done(main_input_file));
2519 statemc_check_flushing_done();
2520 statemc_check_backlog_done();
2521 return OOP_CONTINUE;
2524 static void queue_check_input_done(void) {
2525 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2528 static void statemc_setstate(StateMachineState newsms, int periods,
2529 const char *forlog, const char *why) {
2531 sm_period_counter= periods;
2533 const char *xtra= "";
2536 case sm_FLUSHFAILED:
2537 if (!main_input_file) xtra= "-ABSENT";
2541 xtra= flushing_input_file->rd ? "-1" : "-2";
2547 info("state %s%s[%d] %s",forlog,xtra,periods,why);
2549 info("state %s%s %s",forlog,xtra,why);
2553 /*---------- defer and backlog files ----------*/
2555 static void open_defer(void) {
2560 defer= fopen(path_defer, "a+");
2561 if (!defer) sysfatal("could not open defer file %s", path_defer);
2563 /* truncate away any half-written records */
2565 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2567 if (stab.st_size > LONG_MAX)
2568 die("defer file %s size is far too large", path_defer);
2573 long orgsize= stab.st_size;
2574 long truncto= stab.st_size;
2576 if (!truncto) break; /* was only (if anything) one half-truncated record */
2577 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2578 sysdie("seek in defer file %s while truncating partial", path_defer);
2583 sysdie("failed read from defer file %s", path_defer);
2585 die("defer file %s shrank while we were checking it!", path_defer);
2591 if (stab.st_size != truncto) {
2592 warn("truncating half-record at end of defer file %s -"
2593 " shrinking by %ld bytes from %ld to %ld",
2594 path_defer, orgsize - truncto, orgsize, truncto);
2597 sysfatal("could not flush defer file %s", path_defer);
2598 if (ftruncate(fileno(defer), truncto))
2599 sysdie("could not truncate defer file %s", path_defer);
2602 info("continuing existing defer file %s (%ld bytes)",
2603 path_defer, orgsize);
2605 if (fseek(defer, truncto, SEEK_SET))
2606 sysdie("could not seek to new end of defer file %s", path_defer);
2609 static void close_defer(void) {
2614 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2616 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2619 time_t now= xtime();
2621 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2623 (unsigned long)stab.st_ino);
2624 if (link(path_defer, backlog))
2625 sysfatal("could not install defer file %s as backlog file %s",
2626 path_defer, backlog);
2627 if (unlink(path_defer))
2628 sysdie("could not unlink old defer link %s to backlog file %s",
2629 path_defer, backlog);
2633 if (until_backlog_nextscan < 0 ||
2634 until_backlog_nextscan > backlog_retry_minperiods + 1)
2635 until_backlog_nextscan= backlog_retry_minperiods + 1;
2638 static void poll_backlog_file(void) {
2639 if (until_backlog_nextscan < 0) return;
2640 if (until_backlog_nextscan-- > 0) return;
2641 search_backlog_file();
2644 static void search_backlog_file(void) {
2645 /* returns non-0 iff there are any backlog files */
2650 const char *oldest_path=0;
2651 time_t oldest_mtime=0, now;
2653 if (backlog_input_file) return;
2657 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2661 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2663 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2665 for (i=0; i<gl.gl_pathc; i++) {
2666 const char *path= gl.gl_pathv[i];
2668 if (strchr(path,'#') || strchr(path,'~')) {
2669 debug("backlog file search skipping %s", path);
2672 r= stat(path, &stab);
2674 syswarn("failed to stat backlog file %s", path);
2677 if (!S_ISREG(stab.st_mode)) {
2678 warn("backlog file %s is not a plain file (or link to one)", path);
2681 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2683 oldest_mtime= stab.st_mtime;
2686 case GLOB_NOMATCH: /* fall through */
2689 sysdie("glob expansion of backlog pattern %s gave unexpected"
2690 " nonzero (error?) return value %d", globpat_backlog, r);
2694 debug("backlog scan: none");
2696 if (sms==sm_DROPPED) {
2698 notice("feed dropped and our work is complete");
2700 int r= unlink(path_control);
2701 if (r && errno!=ENOENT)
2702 syswarn("failed to remove control symlink for old feed");
2704 xunlink(path_lock, "lockfile for old feed");
2707 until_backlog_nextscan= backlog_spontrescan_periods;
2712 double age= difftime(now, oldest_mtime);
2713 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2715 if (age_deficiency <= 0) {
2716 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2717 age, age_deficiency, oldest_path);
2719 backlog_input_file= open_input_file(oldest_path);
2720 if (!backlog_input_file) {
2721 warn("backlog file %s vanished as we opened it", oldest_path);
2725 inputfile_reading_start(backlog_input_file);
2726 until_backlog_nextscan= -1;
2730 until_backlog_nextscan= age_deficiency / period_seconds;
2732 if (backlog_spontrescan_periods >= 0 &&
2733 until_backlog_nextscan > backlog_spontrescan_periods)
2734 until_backlog_nextscan= backlog_spontrescan_periods;
2736 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2737 age, age_deficiency, until_backlog_nextscan, oldest_path);
2744 /*---------- shutdown and signal handling ----------*/
2746 static void preterminate(void) {
2747 if (in_child) return;
2748 notice_processed(main_input_file,0,"feedfile","");
2749 notice_processed(flushing_input_file,0,"flushing file","");
2750 if (backlog_input_file)
2751 notice_processed(backlog_input_file,0, "backlog file ",
2752 backlog_input_file->path);
2755 static int signal_self_pipe[2];
2756 static sig_atomic_t terminate_sig_flag;
2758 static void defraise(int signo) {
2759 struct sigaction sa;
2760 memset(&sa,0,sizeof(sa));
2761 sa.sa_handler= SIG_DFL;
2762 xsigaction(signo,&sa);
2766 static void *sigarrived_event(oop_source *lp, int fd, oop_event e, void *u) {
2767 assert(fd=signal_self_pipe[0]);
2769 int r= read(signal_self_pipe[0], buf, sizeof(buf));
2770 if (r<0 && !isewouldblock(errno)) sysdie("failed to read signal self pipe");
2771 if (r==0) die("eof on signal self pipe");
2772 if (terminate_sig_flag) {
2774 notice("terminating (%s)", strsignal(terminate_sig_flag));
2775 defraise(terminate_sig_flag);
2778 return OOP_CONTINUE;
2781 static void sigarrived_handler(int signum) {
2784 case SIGINT: case SIGTERM:
2785 if (!terminate_sig_flag) terminate_sig_flag= signum;
2790 write(signal_self_pipe[1],&x,1);
2793 static void init_signals(void) {
2794 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2795 sysdie("could not ignore SIGPIPE");
2797 if (pipe(signal_self_pipe)) sysfatal("create self-pipe for signals");
2799 xsetnonblock(signal_self_pipe[0],1);
2800 xsetnonblock(signal_self_pipe[1],1);
2802 struct sigaction sa;
2803 memset(&sa,0,sizeof(sa));
2804 sa.sa_handler= sigarrived_handler;
2805 sa.sa_flags= SA_RESTART;
2806 xsigaction(SIGTERM,&sa);
2807 xsigaction(SIGINT,&sa);
2809 on_fd_read_except(signal_self_pipe[0], sigarrived_event);
2812 /*========== flushing the feed ==========*/
2814 static pid_t inndcomm_child;
2815 static int inndcomm_sentinel_fd;
2817 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2818 assert(inndcomm_child);
2819 assert(fd == inndcomm_sentinel_fd);
2820 int status= xwaitpid(&inndcomm_child, "inndcomm");
2823 cancel_fd_read_except(fd);
2824 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2825 inndcomm_sentinel_fd= 0;
2827 assert(!flushing_input_file);
2829 if (WIFEXITED(status)) {
2830 switch (WEXITSTATUS(status)) {
2832 case INNDCOMMCHILD_ESTATUS_FAIL:
2835 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2836 notice("feed has been dropped by innd, finishing up");
2837 flushing_input_file= main_input_file;
2838 tailing_queue_readable(flushing_input_file);
2839 /* we probably previously returned EAGAIN from our fake read method
2840 * when in fact we were at EOF, so signal another readable event
2841 * so we actually see the EOF */
2845 if (flushing_input_file) {
2846 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2849 SMS(DROPPED, 0, "feed dropped by innd");
2850 search_backlog_file();
2852 return OOP_CONTINUE;
2856 flushing_input_file= main_input_file;
2857 tailing_queue_readable(flushing_input_file);
2859 main_input_file= open_input_file(feedfile);
2860 if (!main_input_file)
2861 die("flush succeeded but feedfile %s does not exist!", feedfile);
2863 if (flushing_input_file) {
2864 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2867 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2869 return OOP_CONTINUE;
2872 goto unexpected_exitstatus;
2875 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2876 warn("flush timed out trying to talk to innd");
2879 unexpected_exitstatus:
2880 report_child_status("inndcomm child", status);
2884 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2885 return OOP_CONTINUE;
2888 static void inndcommfail(const char *what) {
2889 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2890 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2893 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2896 notice("flushing %s",why);
2898 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2899 assert(!inndcomm_child);
2900 assert(!inndcomm_sentinel_fd);
2902 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2904 inndcomm_child= xfork("inndcomm child");
2906 if (!inndcomm_child) {
2907 const char *flushargv[2]= { sitename, 0 };
2911 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2912 /* parent spots the autoclose of pipefds[1] when we die or exit */
2914 if (simulate_flush>=0) {
2915 warn("SIMULATING flush child status %d", simulate_flush);
2916 if (simulate_flush>128) raise(simulate_flush-128);
2917 else exit(simulate_flush);
2920 alarm(inndcomm_flush_timeout);
2921 r= ICCopen(); if (r) inndcommfail("connect");
2922 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2923 if (!r) exit(0); /* yay! */
2925 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2926 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2927 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2932 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2933 inndcomm_sentinel_fd= pipefds[0];
2934 assert(inndcomm_sentinel_fd);
2935 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2937 SMS(FLUSHING, 0, why);
2940 /*========== main program ==========*/
2942 static void postfork_inputfile(InputFile *ipf) {
2944 xclose(ipf->fd, "(in child) input file ", ipf->path);
2947 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2948 /* we have no stdio streams that are buffered long-term */
2950 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2953 static void postfork(void) {
2956 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2957 sysdie("(in child) failed to reset SIGPIPE");
2959 postfork_inputfile(main_input_file);
2960 postfork_inputfile(flushing_input_file);
2963 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2964 conn_closefd(conn,"(in child) ");
2966 postfork_stdio(defer, "defer file ", path_defer);
2969 typedef struct Every Every;
2971 struct timeval interval;
2976 static void every_schedule(Every *e, struct timeval base);
2978 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
2981 if (!e->fixed_rate) xgettimeofday(&base);
2982 every_schedule(e, base);
2983 return OOP_CONTINUE;
2986 static void every_schedule(Every *e, struct timeval base) {
2987 struct timeval when;
2988 timeradd(&base, &e->interval, &when);
2989 loop->on_time(loop, when, every_happens, e);
2992 static void every(int interval, int fixed_rate, void (*f)(void)) {
2993 Every *e= xmalloc(sizeof(*e));
2994 e->interval.tv_sec= interval;
2995 e->interval.tv_usec= 0;
2996 e->fixed_rate= fixed_rate;
2999 xgettimeofday(&now);
3000 every_schedule(e, now);
3003 static void filepoll(void) {
3004 filemon_callback(main_input_file);
3005 filemon_callback(flushing_input_file);
3008 static char *debug_report_ipf(InputFile *ipf) {
3009 if (!ipf) return xasprintf("none");
3011 const char *slash= strrchr(ipf->path,'/');
3012 const char *path= slash ? slash+1 : ipf->path;
3014 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
3016 ipf->inprogress, (long)ipf->offset,
3017 ipf->fd, ipf->rd ? "" : ",!rd");
3020 static void period(void) {
3021 char *dipf_main= debug_report_ipf(main_input_file);
3022 char *dipf_flushing= debug_report_ipf(flushing_input_file);
3023 char *dipf_backlog= debug_report_ipf(backlog_input_file);
3026 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
3027 " input_files main:%s flushing:%s backlog:%s"
3028 " children connecting=%ld inndcomm=%ld"
3030 sms_names[sms], sm_period_counter,
3031 conns.count, queue.count, until_connect,
3032 dipf_main, dipf_flushing, dipf_backlog,
3033 (long)connecting_child, (long)inndcomm_child
3037 free(dipf_flushing);
3040 if (until_connect) until_connect--;
3042 poll_backlog_file();
3043 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
3044 statemc_period_poll();
3045 check_assign_articles();
3050 /*========== option parsing ==========*/
3052 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
3053 static void vbadusage(const char *fmt, va_list al) {
3054 char *m= xvasprintf(fmt,al);
3055 fprintf(stderr, "bad usage: %s\n"
3056 "say --help for help, or read the manpage\n",
3059 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
3063 /*---------- generic option parser ----------*/
3065 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
3066 static void badusage(const char *fmt, ...) {
3073 of_seconds= 001000u,
3074 of_boolean= 002000u,
3077 typedef struct Option Option;
3078 typedef void OptionParser(const Option*, const char *val);
3082 const char *lng, *formarg;
3088 static void parse_options(const Option *options, char ***argvp) {
3089 /* on return *argvp is first non-option arg; argc is not updated */
3092 const char *arg= *++(*argvp);
3094 if (*arg != '-') break;
3095 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
3097 while ((a= *++arg)) {
3101 char *equals= strchr(arg,'=');
3102 int len= equals ? (equals - arg) : strlen(arg);
3103 for (o=options; o->shrt || o->lng; o++)
3104 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
3106 badusage("unknown long option --%s",arg);
3109 if (equals) badusage("option --%s does not take a value",o->lng);
3111 } else if (equals) {
3115 if (!arg) badusage("option --%s needs a value for %s",
3116 o->lng, o->formarg);
3119 break; /* eaten the whole argument now */
3121 for (o=options; o->shrt || o->lng; o++)
3124 badusage("unknown short option -%c",a);
3131 if (!arg) badusage("option -%c needs a value for %s",
3132 o->shrt, o->formarg);
3135 break; /* eaten the whole argument now */
3141 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
3143 static void print_options(const Option *options, FILE *f) {
3145 for (o=options; o->shrt || o->lng; o++) {
3146 char shrt[2] = { o->shrt, 0 };
3147 char *optspec= xasprintf("%s%s%s%s%s",
3148 o->shrt ? "-" : "", shrt,
3149 o->shrt && o->lng ? "|" : "",
3150 DELIMPERHAPS("--", o->lng));
3151 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
3156 /*---------- specific option types ----------*/
3158 static void op_integer(const Option *o, const char *val) {
3161 unsigned long ul= strtoul(val,&ep,10);
3162 if (*ep || ep==val || errno || ul>INT_MAX)
3163 badusage("bad integer value for %s",o->lng);
3164 int *store= o->store;
3168 static void op_double(const Option *o, const char *val) {
3169 int *store= o->store;
3172 *store= strtod(val, &ep);
3173 if (*ep || ep==val || errno)
3174 badusage("bad floating point value for %s",o->lng);
3177 static void op_string(const Option *o, const char *val) {
3178 const char **store= o->store;
3182 static void op_seconds(const Option *o, const char *val) {
3183 int *store= o->store;
3187 double v= strtod(val,&ep);
3188 if (ep==val) badusage("bad time/duration value for %s",o->lng);
3190 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
3191 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
3192 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
3193 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
3194 else if (!strcmp(ep,"das")) unit= 10;
3195 else if (!strcmp(ep,"hs")) unit= 100;
3196 else if (!strcmp(ep,"ks")) unit= 1000;
3197 else if (!strcmp(ep,"Ms")) unit= 1000000;
3198 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
3202 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
3206 static void op_setint(const Option *o, const char *val) {
3207 int *store= o->store;
3211 /*---------- specific options ----------*/
3213 static void help(const Option *o, const char *val);
3215 static const Option innduct_options[]= {
3216 {'f',"feedfile", "F", &feedfile, op_string },
3217 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
3218 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
3219 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
3220 {0,"no-filemon", 0, &try_filemon, op_setint, 0 },
3221 {'C',"inndconf", "F", &inndconffile, op_string },
3222 {'P',"port", "PORT", &port, op_integer },
3223 {0,"ctrl-sock-dir", 0, &realsockdir, op_string },
3224 {0,"help", 0, 0, help },
3226 {0,"max-connections", "N", &max_connections, op_integer },
3227 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
3228 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
3229 {0,"period-interval", "TIME", &period_seconds, op_seconds },
3231 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
3232 {0,"stuck-flush-timeout", "TIME", &inndcomm_flush_timeout, op_seconds },
3233 {0,"feedfile-poll", "TIME", &filepoll_seconds, op_seconds },
3235 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
3236 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
3238 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
3239 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
3240 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3241 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3242 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
3243 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
3245 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
3246 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
3251 static void printusage(FILE *f) {
3252 fputs("usage: innduct [options] site [fqdn]\n"
3253 "available options are:\n", f);
3254 print_options(innduct_options, f);
3257 static void help(const Option *o, const char *val) {
3259 if (ferror(stdout) || fflush(stdout)) {
3260 perror("innduct: writing help");
3266 static void convert_to_periods_rndup(int *store) {
3267 *store += period_seconds-1;
3268 *store /= period_seconds;
3271 int main(int argc, char **argv) {
3277 parse_options(innduct_options, &argv);
3282 if (!sitename) badusage("need site name argument");
3283 remote_host= *argv++;
3284 if (*argv) badusage("too many non-option arguments");
3288 int r= innconf_read(inndconffile);
3289 if (!r) badusage("could not read inn.conf (more info on stderr)");
3291 if (!remote_host) remote_host= sitename;
3293 if (nocheck_thresh < 0 || nocheck_thresh > 100)
3294 badusage("nocheck threshold percentage must be between 0..100");
3295 nocheck_thresh *= 0.01;
3297 if (nocheck_decay < 0.1)
3298 badusage("nocheck decay articles must be at least 0.1");
3299 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3301 convert_to_periods_rndup(&reconnect_delay_periods);
3302 convert_to_periods_rndup(&flushfail_retry_periods);
3303 convert_to_periods_rndup(&backlog_retry_minperiods);
3304 convert_to_periods_rndup(&backlog_spontrescan_periods);
3305 convert_to_periods_rndup(&spontaneous_flush_periods);
3306 convert_to_periods_rndup(&need_activity_periods);
3308 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3309 badusage("bad input data ratio must be between 0..100");
3310 max_bad_data_ratio *= 0.01;
3313 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3314 } else if (!feedfile[0]) {
3315 badusage("feed filename must be nonempty");
3316 } else if (feedfile[strlen(feedfile)-1]=='/') {
3317 feedfile= xasprintf("%s%s",feedfile,sitename);
3320 const char *feedfile_forbidden= "?*[~#";
3322 while ((c= *feedfile_forbidden++))
3323 if (strchr(feedfile, c))
3324 badusage("feed filename may not contain metacharacter %c",c);
3328 path_lock= xasprintf("%s_lock", feedfile);
3329 path_flushing= xasprintf("%s_flushing", feedfile);
3330 path_defer= xasprintf("%s_defer", feedfile);
3331 path_control= xasprintf("%s_control", feedfile);
3332 globpat_backlog= xasprintf("%s_backlog*", feedfile);
3334 oop_source_sys *sysloop= oop_sys_new();
3335 if (!sysloop) sysdie("could not create liboop event loop");
3336 loop= (oop_source*)sysloop;
3341 if (become_daemon) {
3343 for (i=3; i<255; i++)
3344 /* do this now before we open syslog, etc. */
3346 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3348 int null= open("/dev/null",O_RDWR);
3349 if (null<0) sysfatal("failed to open /dev/null");
3353 xclose(null, "/dev/null original fd",0);
3355 pid_t child1= xfork("daemonise first fork");
3356 if (child1) _exit(0);
3358 pid_t sid= setsid();
3359 if (sid != child1) sysfatal("setsid failed");
3361 pid_t child2= xfork("daemonise second fork");
3362 if (child2) _exit(0);
3366 if (self_pid==-1) sysdie("getpid");
3381 notice("filemon: suppressed by command line option, polling");
3383 filemon_ok= filemon_method_init();
3385 warn("filemon: no file monitoring available, polling");
3388 every(filepoll_seconds,0,filepoll);
3390 every(period_seconds,1,period);
3396 void *run= oop_sys_run(sysloop);
3397 assert(run == OOP_ERROR);
3398 sysdie("event loop failed");