4 * - rename sm_period_counter as it's just about flushes
5 * - manpage: document control master stuff
8 * build-lfs/backends/innduct --connection-timeout=30 --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)))
210 #define NORET __attribute__((__noreturn__))
212 #define NEW(ptr) ((ptr)= zxmalloc(sizeof(*(ptr))))
213 #define NEW_DECL(type,ptr) type ptr = zxmalloc(sizeof(*(ptr)))
215 #define DUMPV(fmt,pfx,v) fprintf(f, " " #v "=" fmt, pfx v);
217 #define FOR_CONN(conn) \
218 for ((conn)=LIST_HEAD(conns); (conn); (conn)=LIST_NEXT((conn)))
220 /*----- doubly linked lists -----*/
222 #define ISNODE(T) struct node list_node
225 union { struct list li; T *for_type; } u; \
229 #define NODE(n) (assert((void*)&(n)->list_node == (n)), &(n)->list_node)
231 #define LIST_CHECKCANHAVENODE(l,n) \
232 ((void)((n) == ((l).u.for_type))) /* just for the type check */
234 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
235 ( LIST_CHECKCANHAVENODE(l,n), \
236 list_addsomehow(&(l).u.li, NODE((n))), \
240 #define LIST_REMSOMEHOW(l,list_remsomehow) \
241 ( (typeof((l).u.for_type)) \
244 list_remsomehow(&(l).u.li) ) \
250 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
251 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
252 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
253 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
255 #define LIST_INIT(l) ((l).count=0, list_new(&(l).u.li))
256 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
257 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
258 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
260 #define LIST_REMOVE(l,n) \
261 ( LIST_CHECKCANHAVENODE(l,n), \
262 list_remove(NODE((n))), \
266 #define LIST_INSERT(l,n,pred) \
267 ( LIST_CHECKCANHAVENODE(l,n), \
268 LIST_CHECKCANHAVENODE(l,pred), \
269 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
273 /*----- type predeclarations -----*/
275 typedef struct Conn Conn;
276 typedef struct Article Article;
277 typedef struct InputFile InputFile;
278 typedef struct XmitDetails XmitDetails;
279 typedef struct Filemon_Perfile Filemon_Perfile;
280 typedef enum StateMachineState StateMachineState;
281 typedef struct ControlCommand ControlCommand;
286 /*----- function predeclarations -----*/
288 static void conn_maybe_write(Conn *conn);
289 static void conn_make_some_xmits(Conn *conn);
290 static void *conn_write_some_xmits(Conn *conn);
292 static void xmit_free(XmitDetails *d);
294 #define SMS(newstate, periods, why) \
295 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
296 static void statemc_setstate(StateMachineState newsms, int periods,
297 const char *forlog, const char *why);
299 static void statemc_start_flush(const char *why); /* Normal => Flushing */
300 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
301 static int trigger_flush_ok(void); /* => Flushing,FLUSHING, ret 1; or ret 0 */
303 static void article_done(Conn *conn, Article *art, int whichcount);
305 static void check_assign_articles(void);
306 static void queue_check_input_done(void);
308 static void statemc_check_flushing_done(void);
309 static void statemc_check_backlog_done(void);
311 static void postfork(void);
312 static void period(void);
314 static void open_defer(void);
315 static void close_defer(void);
316 static void search_backlog_file(void);
317 static void preterminate(void);
318 static void raise_default(int signo) NORET;
319 static char *debug_report_ipf(InputFile *ipf);
321 static void inputfile_reading_start(InputFile *ipf);
322 static void inputfile_reading_stop(InputFile *ipf);
324 static void filemon_start(InputFile *ipf);
325 static void filemon_stop(InputFile *ipf);
326 static void filemon_callback(InputFile *ipf);
328 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
329 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
331 static const oop_rd_style peer_rd_style;
332 static oop_rd_call peer_rd_err, peer_rd_ok;
334 /*----- configuration options -----*/
335 /* when changing defaults, remember to update the manpage */
337 static const char *sitename, *remote_host;
338 static const char *feedfile, *realsockdir="/tmp/innduct.control";
339 static int quiet_multiple=0;
340 static int become_daemon=1, try_filemon=1;
341 static int try_stream=1;
343 static const char *inndconffile;
345 static int max_connections=10;
346 static int max_queue_per_conn=200;
347 static int target_max_feedfile_size=100000;
348 static int period_seconds=60;
349 static int filepoll_seconds=5;
351 static int connection_setup_timeout=200;
352 static int inndcomm_flush_timeout=100;
354 static double nocheck_thresh= 95.0; /* converted from percentage by main */
355 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
357 /* all these are initialised to seconds, and converted to periods in main */
358 static int reconnect_delay_periods=1000;
359 static int flushfail_retry_periods=1000;
360 static int backlog_retry_minperiods=50;
361 static int backlog_spontrescan_periods=300;
362 static int spontaneous_flush_periods=100000;
363 static int need_activity_periods=1000;
365 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
366 static int max_bad_data_initial= 30;
367 /* in one corrupt 4096-byte block the number of newlines has
368 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
371 /*----- statistics -----*/
373 typedef enum { /* in queue in conn->sent */
374 art_Unchecked, /* not checked, not sent checking */
375 art_Wanted, /* checked, wanted sent body as requested */
376 art_Unsolicited, /* - sent body without check */
380 static const char *const artstate_names[]=
381 { "Unchecked", "Wanted", "Unsolicited", 0 };
383 #define RESULT_COUNTS(RCS,RCN) \
392 #define RCI_TRIPLE_FMT_BASE "%d (id=%d,bod=%d,nc=%d)"
393 #define RCI_TRIPLE_VALS_BASE(counts,x) \
394 counts[art_Unchecked] x \
395 + counts[art_Wanted] x \
396 + counts[art_Unsolicited] x, \
397 counts[art_Unchecked] x \
398 , counts[art_Wanted] x \
399 , counts[art_Unsolicited] x
402 #define RC_INDEX(x) RC_##x,
403 RESULT_COUNTS(RC_INDEX, RC_INDEX)
408 /*----- transmission buffers -----*/
413 xk_Malloc, xk_Const, xk_Artdata
425 /*----- core operational data structure types -----*/
428 /* This is also an instance of struct oop_readable */
429 struct oop_readable readable; /* first */
430 oop_readable_call *readable_callback;
431 void *readable_callback_user;
434 Filemon_Perfile *filemon;
436 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
437 long inprogress; /* no. of articles read but not processed */
441 int counts[art_MaxState][RCI_max];
442 int readcount_ok, readcount_blank, readcount_err;
457 #define SMS_LIST(X) \
465 enum StateMachineState {
466 #define SMS_DEF_ENUM(s) sm_##s,
467 SMS_LIST(SMS_DEF_ENUM)
470 static const char *sms_names[]= {
471 #define SMS_DEF_NAME(s) #s ,
472 SMS_LIST(SMS_DEF_NAME)
478 int fd; /* may be 0, meaning closed (during construction/destruction) */
479 oop_read *rd; /* likewise */
480 int max_queue, stream, quitting;
481 int since_activity; /* periods */
482 ArticleList waiting; /* not yet told peer */
483 ArticleList priority; /* peer says send it now */
484 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
485 struct iovec xmit[CONNIOVS];
486 XmitDetails xmitd[CONNIOVS];
491 /*----- general operational variables -----*/
493 /* main initialises */
494 static oop_source *loop;
495 static ConnList conns;
496 static ArticleList queue;
497 static char *path_lock, *path_flushing, *path_defer;
498 static char *path_control, *path_dump;
499 static char *globpat_backlog;
500 static pid_t self_pid;
502 /* statemc_init initialises */
503 static StateMachineState sms;
504 static int sm_period_counter;
505 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
508 /* initialisation to 0 is good */
509 static int until_connect, until_backlog_nextscan;
510 static double accept_proportion;
511 static int nocheck, nocheck_reported, in_child;
513 /* for simulation, debugging, etc. */
514 int simulate_flush= -1;
516 /*========== logging ==========*/
518 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
519 static void logcore(int sysloglevel, const char *fmt, ...) {
522 vsyslog(sysloglevel,fmt,al);
524 if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
525 vfprintf(stderr,fmt,al);
531 static void logv(int sysloglevel, const char *pfx, int errnoval,
532 const char *fmt, va_list al) PRINTF(5,0);
533 static void logv(int sysloglevel, const char *pfx, int errnoval,
534 const char *fmt, va_list al) {
535 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
536 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
537 msgbuf[sizeof(msgbuf)-1]= 0;
539 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
540 sysloglevel= LOG_ERR; /* run by wrong user, probably */
542 logcore(sysloglevel, "<%s>%s: %s%s%s",
543 sitename, pfx, msgbuf,
544 errnoval>=0 ? ": " : "",
545 errnoval>=0 ? strerror(errnoval) : "");
548 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
549 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
550 static void fn(const char *fmt, ...) { \
553 logv(sysloglevel, pfx, err, fmt, al); \
557 #define logwrap(fn, pfx, sysloglevel, err) \
558 static void fn(const char *fmt, ...) PRINTF(1,2); \
559 static void fn(const char *fmt, ...) { \
561 logv(sysloglevel, pfx, err, fmt, al); \
565 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
566 diewrap(die, " critical", LOG_CRIT, -1, 16);
568 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
569 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
571 logwrap(syswarn, " warning", LOG_WARNING, errno);
572 logwrap(warn, " warning", LOG_WARNING, -1);
574 logwrap(notice, " notice", LOG_NOTICE, -1);
575 logwrap(info, " info", LOG_INFO, -1);
576 logwrap(debug, " debug", LOG_DEBUG, -1);
579 /*========== utility functions etc. ==========*/
581 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
582 static char *xvasprintf(const char *fmt, va_list al) {
584 int rc= vasprintf(&str,fmt,al);
585 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
588 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
589 static char *xasprintf(const char *fmt, ...) {
591 char *str= xvasprintf(fmt,al);
596 static int close_perhaps(int *fd) {
597 if (*fd <= 0) return 0;
602 static void xclose(int fd, const char *what, const char *what2) {
604 if (r) sysdie("close %s%s",what,what2?what2:"");
606 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
607 if (*fd <= 0) return;
608 xclose(*fd,what,what2);
612 static pid_t xfork(const char *what) {
616 if (child==-1) sysfatal("cannot fork for %s",what);
617 debug("forked %s %ld", what, (unsigned long)child);
618 if (!child) postfork();
622 static void on_fd_read_except(int fd, oop_call_fd callback) {
623 loop->on_fd(loop, fd, OOP_READ, callback, 0);
624 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
626 static void cancel_fd_read_except(int fd) {
627 loop->cancel_fd(loop, fd, OOP_READ);
628 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
631 static void report_child_status(const char *what, int status) {
632 if (WIFEXITED(status)) {
633 int es= WEXITSTATUS(status);
635 warn("%s: child died with error exit status %d", what, es);
636 } else if (WIFSIGNALED(status)) {
637 int sig= WTERMSIG(status);
638 const char *sigstr= strsignal(sig);
639 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
641 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
643 warn("%s: child died due to unknown fatal signal %d%s",
644 what, sig, coredump);
646 warn("%s: child died with unknown wait status %d", what,status);
650 static int xwaitpid(pid_t *pid, const char *what) {
653 int r= kill(*pid, SIGKILL);
654 if (r) sysdie("cannot kill %s child", what);
656 pid_t got= waitpid(*pid, &status, 0);
657 if (got==-1) sysdie("cannot reap %s child", what);
658 if (got==0) die("cannot reap %s child", what);
665 static void *zxmalloc(size_t sz) {
666 void *p= xmalloc(sz);
671 static void xunlink(const char *path, const char *what) {
673 if (r) sysdie("can't unlink %s %s", path, what);
676 static time_t xtime(void) {
678 if (now==-1) sysdie("time(2) failed");
682 static void xsigaction(int signo, const struct sigaction *sa) {
683 int r= sigaction(signo,sa,0);
684 if (r) sysdie("sigaction failed for \"%s\"", strsignal(signo));
687 static void xsigsetdefault(int signo) {
689 memset(&sa,0,sizeof(sa));
690 sa.sa_handler= SIG_DFL;
691 xsigaction(signo,&sa);
694 static void xgettimeofday(struct timeval *tv_r) {
695 int r= gettimeofday(tv_r,0);
696 if (r) sysdie("gettimeofday(2) failed");
699 static void xsetnonblock(int fd, int nonblocking) {
700 int errnoval= oop_fd_nonblock(fd, nonblocking);
701 if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
704 static void check_isreg(const struct stat *stab, const char *path,
706 if (!S_ISREG(stab->st_mode))
707 die("%s %s not a plain file (mode 0%lo)",
708 what, path, (unsigned long)stab->st_mode);
711 static void xfstat(int fd, struct stat *stab_r, const char *what) {
712 int r= fstat(fd, stab_r);
713 if (r) sysdie("could not fstat %s", what);
716 static void xfstat_isreg(int fd, struct stat *stab_r,
717 const char *path, const char *what) {
718 xfstat(fd, stab_r, what);
719 check_isreg(stab_r, path, what);
722 static void xlstat_isreg(const char *path, struct stat *stab,
723 int *enoent_r /* 0 means ENOENT is fatal */,
725 int r= lstat(path, stab);
727 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
728 sysdie("could not lstat %s %s", what, path);
730 if (enoent_r) *enoent_r= 0;
731 check_isreg(stab, path, what);
734 static int samefile(const struct stat *a, const struct stat *b) {
735 assert(S_ISREG(a->st_mode));
736 assert(S_ISREG(b->st_mode));
737 return (a->st_ino == b->st_ino &&
738 a->st_dev == b->st_dev);
741 static char *sanitise(const char *input, int len) {
742 static char sanibuf[100]; /* returns pointer to this buffer! */
744 const char *p= input;
745 const char *endp= len>=0 ? input+len : 0;
749 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
750 int c= (!endp || p<endp) ? *p++ : 0;
751 if (!c) { *q++= '\''; *q=0; break; }
752 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
753 sprintf(q,"\\x%02x",c);
759 static int isewouldblock(int errnoval) {
760 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
763 /*========== command and control connections ==========*/
765 static int control_master;
767 typedef struct ControlConn ControlConn;
769 void (*destroy)(ControlConn*);
775 struct sockaddr_un un;
780 static const oop_rd_style control_rd_style= {
781 OOP_RD_DELIM_STRIP, '\n',
783 OOP_RD_SHORTREC_FORBID
786 static void control_destroy(ControlConn *cc) {
790 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
791 if (ferror(cc->out) | fflush(cc->out)) {
792 info("CTRL%d write error %s", cc->fd, strerror(errno));
797 static void control_prompt(ControlConn *cc /* may destroy*/) {
798 fprintf(cc->out, "%s| ", sitename);
799 control_checkouterr(cc);
802 struct ControlCommand {
804 void (*f)(ControlConn *cc, const ControlCommand *ccmd,
805 const char *arg, size_t argsz);
810 static const ControlCommand control_commands[];
813 static void ccmd_##wh(ControlConn *cc, const ControlCommand *c, \
814 const char *arg, size_t argsz)
817 fputs("commands:\n", cc->out);
818 const ControlCommand *ccmd;
819 for (ccmd=control_commands; ccmd->cmd; ccmd++)
820 fprintf(cc->out, " %s\n", ccmd->cmd);
824 int ok= trigger_flush_ok();
825 if (!ok) fprintf(cc->out,"already flushing (state is %s)\n", sms_names[sms]);
830 notice("terminating (CTRL%d)",cc->fd);
831 raise_default(SIGTERM);
837 /* messing with our head: */
838 CCMD(period) { period(); }
839 CCMD(setintarg) { *(int*)c->xdata= atoi(arg); }
840 CCMD(setint) { *(int*)c->xdata= c->xval; }
841 CCMD(setint_period) { *(int*)c->xdata= c->xval; period(); }
843 static const ControlCommand control_commands[]= {
845 { "flush", ccmd_flush },
846 { "stop", ccmd_stop },
847 { "dump q", ccmd_dump, 0,0 },
848 { "dump a", ccmd_dump, 0,1 },
850 { "p", ccmd_period },
852 #define POKES(cmd,func) \
853 { cmd "sm", func, &sm_period_counter, 1 }, \
854 { cmd "conn", func, &until_connect, 0 }, \
855 { cmd "blscan", func, &until_backlog_nextscan, 0 },
856 POKES("prod ", ccmd_setint_period)
857 POKES("next ", ccmd_setint)
859 { "pretend flush", ccmd_setintarg, &simulate_flush },
860 { "wedge blscan", ccmd_setint, &until_backlog_nextscan, -1 },
864 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
865 const char *errmsg, int errnoval,
866 const char *data, size_t recsz, void *cc_v) {
867 ControlConn *cc= cc_v;
870 info("CTRL%d closed", cc->fd);
875 if (recsz == 0) goto prompt;
877 const ControlCommand *ccmd;
878 for (ccmd=control_commands; ccmd->cmd; ccmd++) {
879 int l= strlen(ccmd->cmd);
880 if (recsz < l) continue;
881 if (recsz > l && data[l] != ' ') continue;
882 if (memcmp(data, ccmd->cmd, l)) continue;
884 int argl= (int)recsz - (l+1);
885 ccmd->f(cc, ccmd, argl>=0 ? data+l+1 : 0, argl);
889 fputs("unknown command; h for help\n", cc->out);
896 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
897 const char *errmsg, int errnoval,
898 const char *data, size_t recsz, void *cc_v) {
899 ControlConn *cc= cc_v;
901 info("CTRL%d read error %s", cc->fd, errmsg);
906 static int control_conn_startup(ControlConn *cc /* may destroy*/,
908 cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
909 if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
911 int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
914 if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
916 info("CTRL%d %s ready", cc->fd, how);
921 static void control_stdio_destroy(ControlConn *cc) {
923 oop_rd_cancel(cc->rd);
924 errno= oop_rd_delete_tidy(cc->rd);
925 if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
930 static void control_stdio(void) {
931 NEW_DECL(ControlConn *,cc);
932 cc->destroy= control_stdio_destroy;
936 int r= control_conn_startup(cc,"stdio");
937 if (r) cc->destroy(cc);
940 static void control_accepted_destroy(ControlConn *cc) {
942 oop_rd_cancel(cc->rd);
943 oop_rd_delete_kill(cc->rd);
945 if (cc->out) { fclose(cc->out); cc->fd=0; }
946 close_perhaps(&cc->fd);
950 static void *control_master_readable(oop_source *lp, int master,
951 oop_event ev, void *u) {
952 NEW_DECL(ControlConn *,cc);
953 cc->destroy= control_accepted_destroy;
955 cc->salen= sizeof(cc->sa);
956 cc->fd= accept(master, &cc->sa.sa, &cc->salen);
957 if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
959 cc->out= fdopen(cc->fd, "w");
960 if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
962 int r= control_conn_startup(cc, "accepted");
972 #define NOCONTROL(...) do{ \
973 syswarn("no control socket, because failed to " __VA_ARGS__); \
977 static void control_init(void) {
982 struct sockaddr_un un;
985 memset(&sa,0,sizeof(sa));
986 int maxlen= sizeof(sa.un.sun_path);
988 int reallen= readlink(path_control, sa.un.sun_path, maxlen);
991 NOCONTROL("readlink control socket symlink path %s", path_control);
993 if (reallen >= maxlen) {
994 debug("control socket symlink path too long (r=%d)",reallen);
995 xunlink(path_control, "old (overlong) control socket symlink");
1001 int r= lstat(realsockdir,&stab);
1003 if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
1005 r= mkdir(realsockdir, 0700);
1006 if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
1009 uid_t self= geteuid();
1010 if (!S_ISDIR(stab.st_mode) ||
1011 stab.st_uid != self ||
1012 stab.st_mode & 0007) {
1013 warn("no control socket, because real socket directory"
1014 " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
1015 !!S_ISDIR(stab.st_mode),
1016 (unsigned long)stab.st_uid, (unsigned long)self,
1017 (unsigned long)stab.st_mode & 0777UL);
1022 real= xasprintf("%s/s%lx.%lx", realsockdir,
1023 (unsigned long)xtime(), (unsigned long)self_pid);
1024 int reallen= strlen(real);
1026 if (reallen >= maxlen) {
1027 warn("no control socket, because tmpnam gave overly-long path"
1031 r= symlink(real, path_control);
1032 if (r) NOCONTROL("make control socket path %s a symlink to real"
1033 " socket path %s", path_control, real);
1034 memcpy(sa.un.sun_path, real, reallen);
1037 int r= unlink(sa.un.sun_path);
1038 if (r && errno!=ENOENT)
1039 NOCONTROL("remove old real socket %s", sa.un.sun_path);
1041 control_master= socket(PF_UNIX, SOCK_STREAM, 0);
1042 if (control_master<0) NOCONTROL("create new control socket");
1044 sa.un.sun_family= AF_UNIX;
1045 int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
1046 r= bind(control_master, &sa.sa, sl);
1047 if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
1049 r= listen(control_master, 5);
1050 if (r) NOCONTROL("listen");
1052 xsetnonblock(control_master, 1);
1054 loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
1055 info("control socket ok, real path %s", sa.un.sun_path);
1061 xclose_perhaps(&control_master, "control master",0);
1065 /*========== management of connections ==========*/
1067 static void conn_closefd(Conn *conn, const char *msgprefix) {
1068 int r= close_perhaps(&conn->fd);
1069 if (r) info("C%d %serror closing socket: %s",
1070 conn->fd, msgprefix, strerror(errno));
1073 static void conn_dispose(Conn *conn) {
1076 oop_rd_cancel(conn->rd);
1077 oop_rd_delete_kill(conn->rd);
1081 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1082 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
1084 conn_closefd(conn,"");
1086 until_connect= reconnect_delay_periods;
1089 static void *conn_exception(oop_source *lp, int fd,
1090 oop_event ev, void *conn_v) {
1093 assert(fd == conn->fd);
1094 assert(ev == OOP_EXCEPTION);
1095 int r= read(conn->fd, &ch, 1);
1096 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1097 else connfail(conn,"exceptional condition on socket (peer sent urgent"
1098 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1099 return OOP_CONTINUE;
1102 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1103 int requeue[art_MaxState];
1104 memset(requeue,0,sizeof(requeue));
1107 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1108 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1109 while ((art= LIST_REMHEAD(conn->sent))) {
1110 requeue[art->state]++;
1111 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1112 LIST_ADDTAIL(queue,art);
1117 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1120 char *m= xvasprintf(fmt,al);
1121 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1122 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1125 LIST_REMOVE(conns,conn);
1127 check_assign_articles();
1130 static void connfail(Conn *conn, const char *fmt, ...) {
1133 vconnfail(conn,fmt,al);
1137 static void check_idle_conns(void) {
1140 conn->since_activity++;
1143 if (conn->since_activity <= need_activity_periods) continue;
1145 /* We need to shut this down */
1147 connfail(conn,"timed out waiting for response to QUIT");
1148 else if (conn->sent.count)
1149 connfail(conn,"timed out waiting for responses");
1150 else if (conn->waiting.count || conn->priority.count)
1151 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1152 else if (conn->xmitu)
1153 connfail(conn,"peer has been sending responses"
1154 " before receiving our commands!");
1156 static const char quitcmd[]= "QUIT\r\n";
1157 int todo= sizeof(quitcmd)-1;
1158 const char *p= quitcmd;
1160 int r= write(conn->fd, p, todo);
1162 if (isewouldblock(errno))
1163 connfail(conn, "blocked writing QUIT to idle connection");
1165 connfail(conn, "failed to write QUIT to idle connection: %s",
1173 conn->since_activity= 0;
1174 debug("C%d is idle, quitting", conn->fd);
1183 /*---------- making new connections ----------*/
1185 static pid_t connecting_child;
1186 static int connecting_fdpass_sock;
1188 static void connect_attempt_discard(void) {
1189 if (connecting_child) {
1190 int status= xwaitpid(&connecting_child, "connect");
1191 if (!(WIFEXITED(status) ||
1192 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1193 report_child_status("connect", status);
1195 if (connecting_fdpass_sock) {
1196 cancel_fd_read_except(connecting_fdpass_sock);
1197 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1201 #define PREP_DECL_MSG_CMSG(msg) \
1203 struct iovec msgiov; \
1204 msgiov.iov_base= &msgbyte; \
1205 msgiov.iov_len= 1; \
1206 struct msghdr msg; \
1207 memset(&msg,0,sizeof(msg)); \
1208 char msg##cbuf[CMSG_SPACE(sizeof(int))]; \
1209 msg.msg_iov= &msgiov; \
1210 msg.msg_iovlen= 1; \
1211 msg.msg_control= msg##cbuf; \
1212 msg.msg_controllen= sizeof(msg##cbuf);
1214 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1217 assert(fd == connecting_fdpass_sock);
1219 PREP_DECL_MSG_CMSG(msg);
1221 ssize_t rs= recvmsg(fd, &msg, 0);
1223 if (isewouldblock(errno)) return OOP_CONTINUE;
1224 syswarn("failed to read socket from connecting child");
1229 LIST_INIT(conn->waiting);
1230 LIST_INIT(conn->priority);
1231 LIST_INIT(conn->sent);
1233 struct cmsghdr *h= 0;
1234 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1236 int status= xwaitpid(&connecting_child, "connect child (broken)");
1238 if (WIFEXITED(status)) {
1239 if (WEXITSTATUS(status) != 0 &&
1240 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1241 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1242 /* child already reported the problem */;
1244 if (e == OOP_EXCEPTION)
1245 warn("connect: connection child exited code %d but"
1246 " unexpected exception on fdpass socket",
1247 WEXITSTATUS(status));
1249 warn("connect: connection child exited code %d but"
1251 WEXITSTATUS(status), (int)rs);
1253 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1254 warn("connect: connection attempt timed out");
1256 report_child_status("connect", status);
1261 #define CHK(field, val) \
1262 if (h->cmsg_##field != val) { \
1263 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1264 h->cmsg_##field, val); \
1267 CHK(level, SOL_SOCKET);
1268 CHK(type, SCM_RIGHTS);
1269 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1272 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1274 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1277 pid_t got= waitpid(connecting_child, &status, 0);
1278 if (got==-1) sysdie("connect: real wait for child");
1279 assert(got == connecting_child);
1280 connecting_child= 0;
1282 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1283 int es= WEXITSTATUS(status);
1285 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1286 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1288 fatal("connect: child gave unexpected exit status %d", es);
1292 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1294 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1295 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1296 if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1297 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1299 &peer_rd_err, conn);
1300 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1302 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1303 LIST_ADDHEAD(conns, conn);
1305 connect_attempt_discard();
1306 check_assign_articles();
1307 return OOP_CONTINUE;
1311 connect_attempt_discard();
1312 return OOP_CONTINUE;
1315 static int allow_connect_start(void) {
1316 return conns.count < max_connections
1317 && !connecting_child
1321 static void connect_start(void) {
1322 assert(!connecting_child);
1323 assert(!connecting_fdpass_sock);
1325 info("starting connection attempt");
1328 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1329 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1331 connecting_child= xfork("connection");
1333 if (!connecting_child) {
1334 FILE *cn_from, *cn_to;
1335 char buf[NNTP_STRLEN+100];
1336 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1338 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1340 alarm(connection_setup_timeout);
1341 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1345 unsigned char c= buf[l-1];
1346 if (!isspace(c)) break;
1347 if (c=='\n' || c=='\r') stripped=1;
1351 sysfatal("connect: connection attempt failed");
1354 fatal("connect: %s: %s", stripped ? "rejected" : "failed",
1358 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1359 sysfatal("connect: authentication failed");
1361 if (fputs("MODE STREAM\r\n", cn_to)==EOF ||
1363 sysfatal("connect: could not send MODE STREAM");
1364 buf[sizeof(buf)-1]= 0;
1365 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1366 if (ferror(cn_from))
1367 sysfatal("connect: could not read response to MODE STREAM");
1369 fatal("connect: connection close in response to MODE STREAM");
1374 fatal("connect: response to MODE STREAM is too long: %.100s...",
1376 l--; if (l>0 && buf[l-1]=='\r') l--;
1379 int rcode= strtoul(buf,&ep,10);
1381 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf,-1));
1385 exitstatus= CONNCHILD_ESTATUS_STREAM;
1391 warn("connect: unexpected response to MODE STREAM: %.50s",
1397 int fd= fileno(cn_from);
1399 PREP_DECL_MSG_CMSG(msg);
1400 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1401 cmsg->cmsg_level= SOL_SOCKET;
1402 cmsg->cmsg_type= SCM_RIGHTS;
1403 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1404 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1406 msg.msg_controllen= cmsg->cmsg_len;
1407 r= sendmsg(socks[1], &msg, 0);
1408 if (r<0) sysdie("sendmsg failed for new connection");
1409 if (r!=1) die("sendmsg for new connection gave wrong result %d",r);
1414 xclose(socks[1], "connecting fdpass child's socket",0);
1415 connecting_fdpass_sock= socks[0];
1416 xsetnonblock(connecting_fdpass_sock, 1);
1417 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1420 /*---------- assigning articles to conns, and transmitting ----------*/
1422 static void check_assign_articles(void) {
1428 int spare=0, inqueue=0;
1430 /* Find a connection to offer this article. We prefer a busy
1431 * connection to an idle one, provided it's not full. We take the
1432 * first (oldest) and since that's stable, it will mean we fill up
1433 * connections in order. That way if we have too many
1434 * connections, the spare ones will go away eventually.
1437 if (walk->quitting) continue;
1438 inqueue= walk->sent.count + walk->priority.count
1439 + walk->waiting.count;
1440 spare= walk->max_queue - inqueue;
1441 assert(inqueue <= max_queue_per_conn);
1443 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1444 else if (spare>0) /*working*/ { use= walk; break; }
1447 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1449 Article *art= LIST_REMHEAD(queue);
1451 LIST_ADDTAIL(use->waiting, art);
1454 conn_maybe_write(use);
1455 } else if (allow_connect_start()) {
1456 until_connect= reconnect_delay_periods;
1465 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1466 conn_maybe_write(u);
1467 return OOP_CONTINUE;
1470 static void conn_maybe_write(Conn *conn) {
1472 conn_make_some_xmits(conn);
1474 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1478 void *rp= conn_write_some_xmits(conn);
1479 if (rp==OOP_CONTINUE) {
1480 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1482 } else if (rp==OOP_HALT) {
1485 /* transmitted everything */
1492 /*========== article transmission ==========*/
1494 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1495 XmitKind kind) { /* caller must then fill in details */
1496 struct iovec *v= &conn->xmit[conn->xmitu];
1497 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1498 v->iov_base= (char*)data;
1504 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1505 xmit_core(conn,data,len, xk_Const);
1507 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1509 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1510 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1514 static void xmit_free(XmitDetails *d) {
1516 case xk_Malloc: free(d->info.malloc_tofree); break;
1517 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1518 case xk_Const: break;
1523 static void *conn_write_some_xmits(Conn *conn) {
1525 * 0: nothing more to write, no need to call us again
1526 * OOP_CONTINUE: more to write but fd not writeable
1527 * OOP_HALT: disaster, have destroyed conn
1530 int count= conn->xmitu;
1531 if (!count) return 0;
1533 if (count > IOV_MAX) count= IOV_MAX;
1534 ssize_t rs= writev(conn->fd, conn->xmit, count);
1536 if (isewouldblock(errno)) return OOP_CONTINUE;
1537 connfail(conn, "write failed: %s", strerror(errno));
1543 for (done=0; rs && done<conn->xmitu; done++) {
1544 struct iovec *vp= &conn->xmit[done];
1545 XmitDetails *dp= &conn->xmitd[done];
1546 if (rs > vp->iov_len) {
1550 vp->iov_base= (char*)vp->iov_base + rs;
1554 int newu= conn->xmitu - done;
1555 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1556 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1561 static void conn_make_some_xmits(Conn *conn) {
1563 if (conn->xmitu+5 > CONNIOVS)
1566 Article *art= LIST_REMHEAD(conn->priority);
1567 if (!art) art= LIST_REMHEAD(conn->waiting);
1570 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1571 /* actually send it */
1573 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1576 art->state == art_Unchecked ? art_Unsolicited :
1577 art->state == art_Wanted ? art_Wanted :
1580 if (!artdata) art->missing= 1;
1581 art->ipf->counts[art->state][ artdata ? RC_sent : RC_missing ]++;
1585 XMIT_LITERAL("TAKETHIS ");
1586 xmit_noalloc(conn, art->messageid, art->midlen);
1587 XMIT_LITERAL("\r\n");
1588 xmit_artbody(conn, artdata);
1590 article_done(conn, art, -1);
1594 /* we got 235 from IHAVE */
1596 xmit_artbody(conn, artdata);
1598 XMIT_LITERAL(".\r\n");
1602 LIST_ADDTAIL(conn->sent, art);
1608 XMIT_LITERAL("CHECK ");
1610 XMIT_LITERAL("IHAVE ");
1611 xmit_noalloc(conn, art->messageid, art->midlen);
1612 XMIT_LITERAL("\r\n");
1614 assert(art->state == art_Unchecked);
1615 art->ipf->counts[art->state][RC_sent]++;
1616 LIST_ADDTAIL(conn->sent, art);
1622 /*========== handling responses from peer ==========*/
1624 static const oop_rd_style peer_rd_style= {
1625 OOP_RD_DELIM_STRIP, '\n',
1627 OOP_RD_SHORTREC_FORBID
1630 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1631 const char *errmsg, int errnoval,
1632 const char *data, size_t recsz, void *conn_v) {
1634 connfail(conn, "error receiving from peer: %s", errmsg);
1635 return OOP_CONTINUE;
1638 static Article *article_reply_check(Conn *conn, const char *response,
1639 int code_indicates_streaming,
1641 /* 1:yes, -1:no, 0:dontcare */,
1642 const char *sanitised_response) {
1643 Article *art= LIST_HEAD(conn->sent);
1647 "peer gave unexpected response when no commands outstanding: %s",
1648 sanitised_response);
1652 if (code_indicates_streaming) {
1653 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1654 if (!conn->stream) {
1655 connfail(conn, "peer gave streaming response code "
1656 " to IHAVE or subsequent body: %s", sanitised_response);
1659 const char *got_mid= response+4;
1660 int got_midlen= strcspn(got_mid, " \n\r");
1661 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1662 connfail(conn, "peer gave streaming response with syntactically invalid"
1663 " messageid: %s", sanitised_response);
1666 if (got_midlen != art->midlen ||
1667 memcmp(got_mid, art->messageid, got_midlen)) {
1668 connfail(conn, "peer gave streaming response code to wrong article -"
1669 " probable synchronisation problem; we offered: %s;"
1671 art->messageid, sanitised_response);
1676 connfail(conn, "peer gave non-streaming response code to"
1677 " CHECK/TAKETHIS: %s", sanitised_response);
1682 if (must_have_sent>0 && art->state < art_Wanted) {
1683 connfail(conn, "peer says article accepted but"
1684 " we had not sent the body: %s", sanitised_response);
1687 if (must_have_sent<0 && art->state >= art_Wanted) {
1688 connfail(conn, "peer says please sent the article but we just did: %s",
1689 sanitised_response);
1693 Article *art_again= LIST_REMHEAD(conn->sent);
1694 assert(art_again == art);
1698 static void update_nocheck(int accepted) {
1699 accept_proportion *= nocheck_decay;
1700 accept_proportion += accepted * (1.0 - nocheck_decay);
1701 int new_nocheck= accept_proportion >= nocheck_thresh;
1702 if (new_nocheck && !nocheck_reported) {
1703 notice("entering nocheck mode for the first time");
1704 nocheck_reported= 1;
1705 } else if (new_nocheck != nocheck) {
1706 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1708 nocheck= new_nocheck;
1711 static void article_done(Conn *conn, Article *art, int whichcount) {
1712 if (!art->missing) art->ipf->counts[art->state][whichcount]++;
1714 if (whichcount == RC_accepted) update_nocheck(1);
1715 else if (whichcount == RC_unwanted) update_nocheck(0);
1717 InputFile *ipf= art->ipf;
1719 while (art->blanklen) {
1720 static const char spaces[]=
1730 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1731 int r= pwrite(ipf->fd, spaces, w, art->offset);
1733 if (errno==EINTR) continue;
1734 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1735 art->messageid, art->blanklen,
1736 (unsigned long)art->offset, ipf->path);
1738 assert(r>=0 && r<=w);
1744 assert(ipf->inprogress >= 0);
1747 if (!ipf->inprogress && ipf != main_input_file)
1748 queue_check_input_done();
1751 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1752 const char *errmsg, int errnoval,
1753 const char *data, size_t recsz, void *conn_v) {
1756 if (ev == OOP_RD_EOF) {
1757 connfail(conn, "unexpected EOF from peer");
1758 return OOP_CONTINUE;
1760 assert(ev == OOP_RD_OK);
1762 char *sani= sanitise(data,-1);
1765 unsigned long code= strtoul(data, &ep, 10);
1766 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1767 connfail(conn, "badly formatted response from peer: %s", sani);
1768 return OOP_CONTINUE;
1772 conn->waiting.count ||
1773 conn->priority.count ||
1777 if (conn->quitting) {
1778 if (code!=205 && code!=503) {
1779 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1781 notice("C%d idle connection closed by us", conn->fd);
1783 LIST_REMOVE(conns,conn);
1786 return OOP_CONTINUE;
1789 conn->since_activity= 0;
1792 #define GET_ARTICLE(musthavesent) do{ \
1793 art= article_reply_check(conn, data, code_streaming, musthavesent, sani); \
1794 if (!art) return OOP_CONTINUE; /* reply_check has failed the conn */ \
1797 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) do{ \
1798 code_streaming= (streaming); \
1799 GET_ARTICLE(musthavesent); \
1800 article_done(conn, art, RC_##how); \
1804 #define PEERBADMSG(m) do { \
1805 connfail(conn, m ": %s", sani); return OOP_CONTINUE; \
1808 int code_streaming= 0;
1812 case 400: PEERBADMSG("peer stopped accepting articles");
1813 default: PEERBADMSG("peer sent unexpected message");
1816 if (conn_busy) PEERBADMSG("peer timed us out");
1817 notice("C%d idle connection closed by peer", conn->fd);
1818 LIST_REMOVE(conns,conn);
1820 return OOP_CONTINUE;
1822 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1823 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1825 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1826 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1828 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1829 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1831 case 238: /* CHECK says send it */
1833 case 335: /* IHAVE says send it */
1835 assert(art->state == art_Unchecked);
1836 art->ipf->counts[art->state][RC_accepted]++;
1837 art->state= art_Wanted;
1838 LIST_ADDTAIL(conn->priority, art);
1841 case 431: /* CHECK or TAKETHIS says try later */
1843 case 436: /* IHAVE says try later */
1846 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1848 sysfatal("write to defer file %s",path_defer);
1849 article_done(conn, art, RC_deferred);
1855 conn_maybe_write(conn);
1856 check_assign_articles();
1857 return OOP_CONTINUE;
1861 /*========== monitoring of input files ==========*/
1863 static void feedfile_eof(InputFile *ipf) {
1864 assert(ipf != main_input_file); /* promised by tailing_try_read */
1865 inputfile_reading_stop(ipf);
1867 if (ipf == flushing_input_file) {
1868 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1869 if (main_input_file) inputfile_reading_start(main_input_file);
1870 statemc_check_flushing_done();
1871 } else if (ipf == backlog_input_file) {
1872 statemc_check_backlog_done();
1874 abort(); /* supposed to wait rather than get EOF on main input file */
1878 static InputFile *open_input_file(const char *path) {
1879 int fd= open(path, O_RDWR);
1881 if (errno==ENOENT) return 0;
1882 sysfatal("unable to open input file %s", path);
1886 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1887 memset(ipf,0,sizeof(*ipf));
1890 strcpy(ipf->path, path);
1895 static void close_input_file(InputFile *ipf) { /* does not free */
1896 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1897 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1898 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1899 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1900 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1904 /*---------- dealing with articles read in the input file ----------*/
1906 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1907 const char *data, const char *how) {
1908 warn("corrupted file: %s, offset %lu: %s: in %s",
1909 ipf->path, (unsigned long)offset, how, sanitise(data,-1));
1910 ipf->readcount_err++;
1911 if (ipf->readcount_err > max_bad_data_initial +
1912 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1913 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1914 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1915 return OOP_CONTINUE;
1918 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1919 oop_rd_event ev, const char *errmsg,
1920 int errnoval, const char *data, size_t recsz,
1922 InputFile *ipf= ipf_v;
1923 assert(ev == OOP_RD_SYSTEM);
1925 sysdie("error reading input file: %s, offset %lu",
1926 ipf->path, (unsigned long)ipf->offset);
1929 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1930 oop_rd_event ev, const char *errmsg,
1931 int errnoval, const char *data, size_t recsz,
1933 InputFile *ipf= ipf_v;
1935 char tokentextbuf[sizeof(TOKEN)*2+3];
1937 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1939 off_t old_offset= ipf->offset;
1940 ipf->offset += recsz + !!(ev == OOP_RD_OK);
1942 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1944 if (ev==OOP_RD_PARTREC)
1945 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1946 /* but process it anyway */
1948 if (ipf->skippinglong) {
1949 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1950 return OOP_CONTINUE;
1952 if (ev==OOP_RD_LONG) {
1953 ipf->skippinglong= 1;
1954 X_BAD_DATA("overly long line");
1957 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1958 if (!recsz) X_BAD_DATA("empty line");
1961 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1962 ipf->readcount_blank++;
1963 return OOP_CONTINUE;
1966 char *space= strchr(data,' ');
1967 int tokenlen= space-data;
1968 int midlen= (int)recsz-tokenlen-1;
1969 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1970 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1972 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1973 memcpy(tokentextbuf, data, tokenlen);
1974 tokentextbuf[tokenlen]= 0;
1975 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1977 ipf->readcount_ok++;
1979 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1980 memset(art,0,sizeof(*art));
1981 art->state= art_Unchecked;
1982 art->midlen= midlen;
1983 art->ipf= ipf; ipf->inprogress++;
1984 art->token= TextToToken(tokentextbuf);
1985 art->offset= old_offset;
1986 art->blanklen= recsz;
1987 strcpy(art->messageid, space+1);
1988 LIST_ADDTAIL(queue, art);
1990 if (sms==sm_NORMAL && ipf==main_input_file &&
1991 ipf->offset >= target_max_feedfile_size)
1992 statemc_start_flush("feed file size");
1994 check_assign_articles();
1995 return OOP_CONTINUE;
1998 /*========== tailing input file ==========*/
2000 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
2002 InputFile *ipf= user;
2003 return ipf->readable_callback(loop, &ipf->readable,
2004 ipf->readable_callback_user);
2007 static void tailing_on_cancel(struct oop_readable *rable) {
2008 InputFile *ipf= (void*)rable;
2010 if (ipf->filemon) filemon_stop(ipf);
2011 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
2012 ipf->readable_callback= 0;
2015 static void tailing_queue_readable(InputFile *ipf) {
2016 /* lifetime of ipf here is OK because destruction will cause
2017 * on_cancel which will cancel this callback */
2018 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
2021 static int tailing_on_readable(struct oop_readable *rable,
2022 oop_readable_call *cb, void *user) {
2023 InputFile *ipf= (void*)rable;
2025 tailing_on_cancel(rable);
2026 ipf->readable_callback= cb;
2027 ipf->readable_callback_user= user;
2030 tailing_queue_readable(ipf);
2034 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
2036 InputFile *ipf= (void*)rable;
2038 ssize_t r= read(ipf->fd, buffer, length);
2040 if (errno==EINTR) continue;
2044 if (ipf==main_input_file) {
2047 } else if (ipf==flushing_input_file) {
2049 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2050 } else if (ipf==backlog_input_file) {
2056 tailing_queue_readable(ipf);
2061 /*---------- filemon implemented with inotify ----------*/
2063 #if defined(HAVE_SYS_INOTIFY_H) && !defined(HAVE_FILEMON)
2064 #define HAVE_FILEMON
2066 #include <sys/inotify.h>
2068 static int filemon_inotify_fd;
2069 static int filemon_inotify_wdmax;
2070 static InputFile **filemon_inotify_wd2ipf;
2072 struct Filemon_Perfile {
2076 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
2077 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
2078 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
2080 if (wd >= filemon_inotify_wdmax) {
2082 filemon_inotify_wd2ipf= xrealloc(filemon_inotify_wd2ipf,
2083 sizeof(*filemon_inotify_wd2ipf) * newmax);
2084 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
2085 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
2086 filemon_inotify_wdmax= newmax;
2089 assert(!filemon_inotify_wd2ipf[wd]);
2090 filemon_inotify_wd2ipf[wd]= ipf;
2092 debug("filemon inotify startfile %p wd=%d wdmax=%d",
2093 ipf, wd, filemon_inotify_wdmax);
2098 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
2100 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
2101 int r= inotify_rm_watch(filemon_inotify_fd, wd);
2102 if (r) sysdie("inotify_rm_watch");
2103 filemon_inotify_wd2ipf[wd]= 0;
2106 static void *filemon_inotify_readable(oop_source *lp, int fd,
2107 oop_event e, void *u) {
2108 struct inotify_event iev;
2110 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
2112 if (isewouldblock(errno)) break;
2113 sysdie("read from inotify master");
2114 } else if (r==sizeof(iev)) {
2115 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
2117 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
2119 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
2120 debug("filemon inotify readable read %p wd=%d", ipf, iev.wd);
2121 filemon_callback(ipf);
2123 return OOP_CONTINUE;
2126 static int filemon_method_init(void) {
2127 filemon_inotify_fd= inotify_init();
2128 if (filemon_inotify_fd<0) {
2129 syswarn("filemon/inotify: inotify_init failed");
2132 xsetnonblock(filemon_inotify_fd, 1);
2133 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable, 0);
2135 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2139 static void filemon_method_dump_info(FILE *f) {
2141 fprintf(f,"inotify");
2142 DUMPV("%d",,filemon_inotify_fd);
2143 DUMPV("%d",,filemon_inotify_wdmax);
2144 for (i=0; i<filemon_inotify_wdmax; i++)
2145 fprintf(f," wd2ipf[%d]=%p\n", i, filemon_inotify_wd2ipf[i],);
2148 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2150 /*---------- filemon dummy implementation ----------*/
2152 #if !defined(HAVE_FILEMON)
2154 struct Filemon_Perfile { int dummy; };
2156 static int filemon_method_init(void) {
2157 warn("filemon/dummy: no filemon method compiled in");
2160 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2161 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2162 static void filemon_method_dump_info(FILE *f) { fprintf(f,"dummy\n"); }
2164 #endif /* !HAVE_FILEMON */
2166 /*---------- filemon generic interface ----------*/
2168 static void filemon_start(InputFile *ipf) {
2169 assert(!ipf->filemon);
2172 filemon_method_startfile(ipf, ipf->filemon);
2175 static void filemon_stop(InputFile *ipf) {
2176 if (!ipf->filemon) return;
2177 filemon_method_stopfile(ipf, ipf->filemon);
2182 static void filemon_callback(InputFile *ipf) {
2183 if (ipf && ipf->readable_callback) /* so filepoll() can be naive */
2184 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2187 /*---------- interface to start and stop an input file ----------*/
2189 static const oop_rd_style feedfile_rdstyle= {
2190 OOP_RD_DELIM_STRIP, '\n',
2192 OOP_RD_SHORTREC_LONG,
2195 static void inputfile_reading_start(InputFile *ipf) {
2197 ipf->readable.on_readable= tailing_on_readable;
2198 ipf->readable.on_cancel= tailing_on_cancel;
2199 ipf->readable.try_read= tailing_try_read;
2200 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2201 ipf->readable.delete_kill= 0;
2203 ipf->readable_callback= 0;
2204 ipf->readable_callback_user= 0;
2206 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2209 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2210 feedfile_got_article,ipf, feedfile_read_err, ipf);
2211 if (r) sysdie("unable start reading feedfile %s",ipf->path);
2214 static void inputfile_reading_stop(InputFile *ipf) {
2216 oop_rd_cancel(ipf->rd);
2217 oop_rd_delete(ipf->rd);
2219 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2223 /*========== interaction with innd - state machine ==========*/
2225 /* See official state diagram at top of file. We implement
2236 |`---------------------------------------------------.
2238 |`---------------- - - - |
2239 D ENOENT | D EXISTS see OVERALL STATES diagram |
2240 | for full startup logic |
2243 | ============ try to |
2249 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
2250 ^ | hardlink F to D |
2253 | | our handle onto F is now onto D |
2256 | |<-------------------<---------------------<---------+
2258 | | spawn inndcomm flush |
2260 | ================== |
2261 | FLUSHING[-ABSENT] |
2263 | main D tail/none |
2264 | ================== |
2266 | | INNDCOMM FLUSH FAILS ^
2267 | |`----------------------->----------. |
2269 | | NO SUCH SITE V |
2270 ^ |`--------------->----. ==================== |
2271 | | \ FLUSHFAILED[-ABSENT] |
2273 | | FLUSH OK \ main D tail/none |
2274 | | open F \ ==================== |
2276 | | \ | TIME TO RETRY |
2277 | |`------->----. ,---<---'\ `----------------'
2278 | | D NONE | | D NONE `----.
2280 | ============= V V ============
2281 | SEPARATED-1 | | DROPPING-1
2282 | flsh->rd!=0 | | flsh->rd!=0
2283 | [Separated] | | [Dropping]
2284 | main F idle | | main none
2285 | flsh D tail | | flsh D tail
2286 | ============= | | ============
2288 ^ | EOF ON D | | defer | EOF ON D
2290 | =============== | | ===============
2291 | SEPARATED-2 | | DROPPING-2
2292 | flsh->rd==0 | V flsh->rd==0
2293 | [Finishing] | | [Dropping]
2294 | main F tail | `. main none
2295 | flsh D closed | `. flsh D closed
2296 | =============== V `. ===============
2298 | | ALL D PROCESSED `. | ALL D PROCESSED
2299 | V install defer as backlog `. | install defer
2300 ^ | close D `. | close D
2301 | | unlink D `. | unlink D
2304 `----------' ==============
2324 static void startup_set_input_file(InputFile *f) {
2325 assert(!main_input_file);
2327 inputfile_reading_start(f);
2330 static void statemc_lock(void) {
2332 struct stat stab, stabf;
2335 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2336 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2339 memset(&fl,0,sizeof(fl));
2341 fl.l_whence= SEEK_SET;
2342 int r= fcntl(lockfd, F_SETLK, &fl);
2344 if (errno==EACCES || isewouldblock(errno)) {
2345 if (quiet_multiple) exit(0);
2346 fatal("another duct holds the lockfile");
2348 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2351 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2353 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2355 if (!lock_noent && samefile(&stab, &stabf))
2358 xclose(lockfd, "stale lockfile ", path_lock);
2361 FILE *lockfile= fdopen(lockfd, "w");
2362 if (!lockfile) sysdie("fdopen lockfile");
2364 int r= ftruncate(lockfd, 0);
2365 if (r) sysdie("truncate lockfile to write new info");
2367 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2368 (unsigned long)self_pid,
2369 sitename, feedfile, remote_host) == EOF ||
2371 sysfatal("write info to lockfile %s", path_lock);
2373 debug("startup: locked");
2376 static void statemc_init(void) {
2377 struct stat stabdefer;
2379 search_backlog_file();
2382 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2384 debug("startup: ductdefer ENOENT");
2386 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2387 switch (stabdefer.st_nlink==1) {
2389 open_defer(); /* so that we will later close it and rename it */
2392 xunlink(path_defer, "stale defer file link"
2393 " (presumably hardlink to backlog file)");
2396 die("defer file %s has unexpected link count %d",
2397 path_defer, stabdefer.st_nlink);
2401 struct stat stab_f, stab_d;
2404 InputFile *file_d= open_input_file(path_flushing);
2405 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2407 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2409 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2410 debug("startup: F==D => Hardlinked");
2411 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2416 debug("startup: F ENOENT => Moved");
2417 if (file_d) startup_set_input_file(file_d);
2418 spawn_inndcomm_flush("feedfile missing at startup");
2419 /* => Flushing, sms:=FLUSHING */
2422 debug("startup: F!=D => Separated");
2423 startup_set_input_file(file_d);
2424 flushing_input_file= main_input_file;
2425 main_input_file= open_input_file(feedfile);
2426 if (!main_input_file) die("feedfile vanished during startup");
2427 SMS(SEPARATED, 0, "found both old and current feed files");
2429 debug("startup: F exists, D ENOENT => Normal");
2430 InputFile *file_f= open_input_file(feedfile);
2431 if (!file_f) die("feed file vanished during startup");
2432 startup_set_input_file(file_f);
2433 SMS(NORMAL, spontaneous_flush_periods, "normal startup");
2438 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2439 assert(sms == sm_NORMAL);
2441 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2443 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2444 (unsigned long)target_max_feedfile_size,
2447 int r= link(feedfile, path_flushing);
2448 if (r) sysfatal("link feedfile %s to flushing file %s",
2449 feedfile, path_flushing);
2452 xunlink(feedfile, "old feedfile link");
2455 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2458 static int trigger_flush_ok(void) { /* => Flushing,FLUSHING, ret 1; or ret 0 */
2461 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2463 case sm_FLUSHFAILED:
2464 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2471 static void statemc_period_poll(void) {
2472 if (!sm_period_counter) return;
2473 sm_period_counter--;
2474 assert(sm_period_counter>=0);
2476 if (sm_period_counter) return;
2477 int ok= trigger_flush_ok();
2481 static int inputfile_is_done(InputFile *ipf) {
2483 if (ipf->inprogress) return 0; /* new article in the meantime */
2484 if (ipf->rd) return 0; /* not had EOF */
2488 static void notice_processed(InputFile *ipf, int completed,
2489 const char *what, const char *spec) {
2490 if (!ipf) return; /* allows preterminate to be lazy */
2492 #define RCI_NOTHING(x) /* nothing */
2493 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2494 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2496 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2498 char *inprog= completed
2499 ? xasprintf("%s","") /* GCC produces a stupid warning for printf("") ! */
2500 : xasprintf(" inprogress=%ld", ipf->inprogress);
2502 info("%s %s%s read=%d (+bl=%d,+err=%d)%s"
2503 " offered=%d (ch=%d,nc=%d) accepted=%d (ch=%d,nc=%d)"
2504 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2506 completed?"completed":"processed", what, spec,
2507 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err, inprog,
2508 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2509 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2510 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2511 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2512 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2520 static void statemc_check_backlog_done(void) {
2521 InputFile *ipf= backlog_input_file;
2522 if (!inputfile_is_done(ipf)) return;
2524 const char *slash= strrchr(ipf->path, '/');
2525 const char *leaf= slash ? slash+1 : ipf->path;
2526 const char *under= strchr(slash, '_');
2527 const char *rest= under ? under+1 : leaf;
2528 if (!strncmp(rest,"backlog",7)) rest += 7;
2529 notice_processed(ipf,1,"backlog ",rest);
2531 close_input_file(ipf);
2532 if (unlink(ipf->path)) {
2533 if (errno != ENOENT)
2534 sysdie("could not unlink processed backlog file %s", ipf->path);
2535 warn("backlog file %s vanished while we were reading it"
2536 " so we couldn't remove it (but it's done now, anyway)",
2540 backlog_input_file= 0;
2541 search_backlog_file();
2545 static void statemc_check_flushing_done(void) {
2546 InputFile *ipf= flushing_input_file;
2547 if (!inputfile_is_done(ipf)) return;
2549 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2551 notice_processed(ipf,1,"feedfile","");
2555 xunlink(path_flushing, "old flushing file");
2557 close_input_file(flushing_input_file);
2558 free(flushing_input_file);
2559 flushing_input_file= 0;
2561 if (sms==sm_SEPARATED) {
2562 notice("flush complete");
2563 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2564 } else if (sms==sm_DROPPING) {
2565 SMS(DROPPED, 0, "old flush complete");
2566 search_backlog_file();
2567 notice("feed dropped, but will continue until backlog is finished");
2571 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2573 assert(!inputfile_is_done(main_input_file));
2574 statemc_check_flushing_done();
2575 statemc_check_backlog_done();
2576 return OOP_CONTINUE;
2579 static void queue_check_input_done(void) {
2580 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2583 static void statemc_setstate(StateMachineState newsms, int periods,
2584 const char *forlog, const char *why) {
2586 sm_period_counter= periods;
2588 const char *xtra= "";
2591 case sm_FLUSHFAILED:
2592 if (!main_input_file) xtra= "-ABSENT";
2596 xtra= flushing_input_file->rd ? "-1" : "-2";
2602 info("state %s%s[%d] %s",forlog,xtra,periods,why);
2604 info("state %s%s %s",forlog,xtra,why);
2608 /*---------- defer and backlog files ----------*/
2610 static void open_defer(void) {
2615 defer= fopen(path_defer, "a+");
2616 if (!defer) sysfatal("could not open defer file %s", path_defer);
2618 /* truncate away any half-written records */
2620 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2622 if (stab.st_size > LONG_MAX)
2623 die("defer file %s size is far too large", path_defer);
2628 long orgsize= stab.st_size;
2629 long truncto= stab.st_size;
2631 if (!truncto) break; /* was only (if anything) one half-truncated record */
2632 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2633 sysdie("seek in defer file %s while truncating partial", path_defer);
2638 sysdie("failed read from defer file %s", path_defer);
2640 die("defer file %s shrank while we were checking it!", path_defer);
2646 if (stab.st_size != truncto) {
2647 warn("truncating half-record at end of defer file %s -"
2648 " shrinking by %ld bytes from %ld to %ld",
2649 path_defer, orgsize - truncto, orgsize, truncto);
2652 sysfatal("could not flush defer file %s", path_defer);
2653 if (ftruncate(fileno(defer), truncto))
2654 sysdie("could not truncate defer file %s", path_defer);
2657 info("continuing existing defer file %s (%ld bytes)",
2658 path_defer, orgsize);
2660 if (fseek(defer, truncto, SEEK_SET))
2661 sysdie("could not seek to new end of defer file %s", path_defer);
2664 static void close_defer(void) {
2669 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2671 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2674 time_t now= xtime();
2676 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2678 (unsigned long)stab.st_ino);
2679 if (link(path_defer, backlog))
2680 sysfatal("could not install defer file %s as backlog file %s",
2681 path_defer, backlog);
2682 if (unlink(path_defer))
2683 sysdie("could not unlink old defer link %s to backlog file %s",
2684 path_defer, backlog);
2688 if (until_backlog_nextscan < 0 ||
2689 until_backlog_nextscan > backlog_retry_minperiods + 1)
2690 until_backlog_nextscan= backlog_retry_minperiods + 1;
2693 static void poll_backlog_file(void) {
2694 if (until_backlog_nextscan < 0) return;
2695 if (until_backlog_nextscan-- > 0) return;
2696 search_backlog_file();
2699 static void search_backlog_file(void) {
2700 /* returns non-0 iff there are any backlog files */
2705 const char *oldest_path=0;
2706 time_t oldest_mtime=0, now;
2708 if (backlog_input_file) return;
2712 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2716 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2718 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2720 for (i=0; i<gl.gl_pathc; i++) {
2721 const char *path= gl.gl_pathv[i];
2723 if (strchr(path,'#') || strchr(path,'~')) {
2724 debug("backlog file search skipping %s", path);
2727 r= stat(path, &stab);
2729 syswarn("failed to stat backlog file %s", path);
2732 if (!S_ISREG(stab.st_mode)) {
2733 warn("backlog file %s is not a plain file (or link to one)", path);
2736 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2738 oldest_mtime= stab.st_mtime;
2741 case GLOB_NOMATCH: /* fall through */
2744 sysdie("glob expansion of backlog pattern %s gave unexpected"
2745 " nonzero (error?) return value %d", globpat_backlog, r);
2749 debug("backlog scan: none");
2751 if (sms==sm_DROPPED) {
2753 notice("feed dropped and our work is complete");
2755 int r= unlink(path_control);
2756 if (r && errno!=ENOENT)
2757 syswarn("failed to remove control symlink for old feed");
2759 xunlink(path_lock, "lockfile for old feed");
2762 until_backlog_nextscan= backlog_spontrescan_periods;
2767 double age= difftime(now, oldest_mtime);
2768 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2770 if (age_deficiency <= 0) {
2771 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2772 age, age_deficiency, oldest_path);
2774 backlog_input_file= open_input_file(oldest_path);
2775 if (!backlog_input_file) {
2776 warn("backlog file %s vanished as we opened it", oldest_path);
2780 inputfile_reading_start(backlog_input_file);
2781 until_backlog_nextscan= -1;
2785 until_backlog_nextscan= age_deficiency / period_seconds;
2787 if (backlog_spontrescan_periods >= 0 &&
2788 until_backlog_nextscan > backlog_spontrescan_periods)
2789 until_backlog_nextscan= backlog_spontrescan_periods;
2791 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2792 age, age_deficiency, until_backlog_nextscan, oldest_path);
2799 /*---------- shutdown and signal handling ----------*/
2801 static void preterminate(void) {
2802 if (in_child) return;
2803 notice_processed(main_input_file,0,"feedfile","");
2804 notice_processed(flushing_input_file,0,"flushing","");
2805 if (backlog_input_file)
2806 notice_processed(backlog_input_file,0, "backlog file ",
2807 backlog_input_file->path);
2810 static int signal_self_pipe[2];
2811 static sig_atomic_t terminate_sig_flag;
2813 static void raise_default(int signo) {
2814 xsigsetdefault(signo);
2819 static void *sigarrived_event(oop_source *lp, int fd, oop_event e, void *u) {
2820 assert(fd=signal_self_pipe[0]);
2822 int r= read(signal_self_pipe[0], buf, sizeof(buf));
2823 if (r<0 && !isewouldblock(errno)) sysdie("failed to read signal self pipe");
2824 if (r==0) die("eof on signal self pipe");
2825 if (terminate_sig_flag) {
2827 notice("terminating (%s)", strsignal(terminate_sig_flag));
2828 raise_default(terminate_sig_flag);
2830 return OOP_CONTINUE;
2833 static void sigarrived_handler(int signum) {
2838 if (!terminate_sig_flag) terminate_sig_flag= signum;
2843 write(signal_self_pipe[1],&x,1);
2846 static void init_signals(void) {
2847 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2848 sysdie("could not ignore SIGPIPE");
2850 if (pipe(signal_self_pipe)) sysfatal("create self-pipe for signals");
2852 xsetnonblock(signal_self_pipe[0],1);
2853 xsetnonblock(signal_self_pipe[1],1);
2855 struct sigaction sa;
2856 memset(&sa,0,sizeof(sa));
2857 sa.sa_handler= sigarrived_handler;
2858 sa.sa_flags= SA_RESTART;
2859 xsigaction(SIGTERM,&sa);
2860 xsigaction(SIGINT,&sa);
2862 on_fd_read_except(signal_self_pipe[0], sigarrived_event);
2865 /*========== flushing the feed ==========*/
2867 static pid_t inndcomm_child;
2868 static int inndcomm_sentinel_fd;
2870 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2871 assert(inndcomm_child);
2872 assert(fd == inndcomm_sentinel_fd);
2873 int status= xwaitpid(&inndcomm_child, "inndcomm");
2876 cancel_fd_read_except(fd);
2877 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2878 inndcomm_sentinel_fd= 0;
2880 assert(!flushing_input_file);
2882 if (WIFEXITED(status)) {
2883 switch (WEXITSTATUS(status)) {
2885 case INNDCOMMCHILD_ESTATUS_FAIL:
2888 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2889 notice("feed has been dropped by innd, finishing up");
2890 flushing_input_file= main_input_file;
2891 tailing_queue_readable(flushing_input_file);
2892 /* we probably previously returned EAGAIN from our fake read method
2893 * when in fact we were at EOF, so signal another readable event
2894 * so we actually see the EOF */
2898 if (flushing_input_file) {
2899 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2902 SMS(DROPPED, 0, "feed dropped by innd");
2903 search_backlog_file();
2905 return OOP_CONTINUE;
2909 flushing_input_file= main_input_file;
2910 tailing_queue_readable(flushing_input_file);
2912 main_input_file= open_input_file(feedfile);
2913 if (!main_input_file)
2914 die("flush succeeded but feedfile %s does not exist!", feedfile);
2916 if (flushing_input_file) {
2917 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2920 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2922 return OOP_CONTINUE;
2925 goto unexpected_exitstatus;
2928 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2929 warn("flush timed out trying to talk to innd");
2932 unexpected_exitstatus:
2933 report_child_status("inndcomm child", status);
2937 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2938 return OOP_CONTINUE;
2941 static void inndcommfail(const char *what) {
2942 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2943 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2946 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2949 notice("flushing %s",why);
2951 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2952 assert(!inndcomm_child);
2953 assert(!inndcomm_sentinel_fd);
2955 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2957 inndcomm_child= xfork("inndcomm child");
2959 if (!inndcomm_child) {
2960 const char *flushargv[2]= { sitename, 0 };
2964 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2965 /* parent spots the autoclose of pipefds[1] when we die or exit */
2967 if (simulate_flush>=0) {
2968 warn("SIMULATING flush child status %d", simulate_flush);
2969 if (simulate_flush>128) raise(simulate_flush-128);
2970 else exit(simulate_flush);
2973 alarm(inndcomm_flush_timeout);
2974 r= ICCopen(); if (r) inndcommfail("connect");
2975 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2976 if (!r) exit(0); /* yay! */
2978 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2979 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2980 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2985 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2986 inndcomm_sentinel_fd= pipefds[0];
2987 assert(inndcomm_sentinel_fd);
2988 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2990 SMS(FLUSHING, 0, why);
2993 /*========== main program ==========*/
2995 static void postfork_inputfile(InputFile *ipf) {
2997 xclose(ipf->fd, "(in child) input file ", ipf->path);
3000 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
3001 /* we have no stdio streams that are buffered long-term */
3003 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
3006 static void postfork(void) {
3009 xsigsetdefault(SIGTERM);
3010 xsigsetdefault(SIGINT);
3011 xsigsetdefault(SIGPIPE);
3012 if (terminate_sig_flag) raise(terminate_sig_flag);
3014 postfork_inputfile(main_input_file);
3015 postfork_inputfile(flushing_input_file);
3019 conn_closefd(conn,"(in child) ");
3021 postfork_stdio(defer, "defer file ", path_defer);
3024 typedef struct Every Every;
3026 struct timeval interval;
3031 static void every_schedule(Every *e, struct timeval base);
3033 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
3036 if (!e->fixed_rate) xgettimeofday(&base);
3037 every_schedule(e, base);
3038 return OOP_CONTINUE;
3041 static void every_schedule(Every *e, struct timeval base) {
3042 struct timeval when;
3043 timeradd(&base, &e->interval, &when);
3044 loop->on_time(loop, when, every_happens, e);
3047 static void every(int interval, int fixed_rate, void (*f)(void)) {
3048 NEW_DECL(Every *,e);
3049 e->interval.tv_sec= interval;
3050 e->interval.tv_usec= 0;
3051 e->fixed_rate= fixed_rate;
3054 xgettimeofday(&now);
3055 every_schedule(e, now);
3058 static void filepoll(void) {
3059 filemon_callback(main_input_file);
3060 filemon_callback(flushing_input_file);
3063 static char *debug_report_ipf(InputFile *ipf) {
3064 if (!ipf) return xasprintf("none");
3066 const char *slash= strrchr(ipf->path,'/');
3067 const char *path= slash ? slash+1 : ipf->path;
3069 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s%s",
3071 ipf->inprogress, (long)ipf->offset,
3073 ipf->rd ? "" : ",!rd",
3074 ipf->skippinglong ? "*skiplong" : "");
3077 static void period(void) {
3078 char *dipf_main= debug_report_ipf(main_input_file);
3079 char *dipf_flushing= debug_report_ipf(flushing_input_file);
3080 char *dipf_backlog= debug_report_ipf(backlog_input_file);
3083 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
3084 " input_files main:%s flushing:%s backlog:%s"
3085 " children connecting=%ld inndcomm=%ld"
3087 sms_names[sms], sm_period_counter,
3088 conns.count, queue.count, until_connect,
3089 dipf_main, dipf_flushing, dipf_backlog,
3090 (long)connecting_child, (long)inndcomm_child
3094 free(dipf_flushing);
3097 if (until_connect) until_connect--;
3099 poll_backlog_file();
3100 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
3101 statemc_period_poll();
3102 check_assign_articles();
3107 /*========== dumping state ==========*/
3109 static void dump_article_list(FILE *f, const ControlCommand *c,
3110 const ArticleList *al) {
3111 fprintf(f, " count=%d\n", al->count);
3112 if (!c->xval) return;
3114 int i; Article *art;
3115 for (i=0, art=LIST_HEAD(*al); art; i++, art=LIST_NEXT(art)) {
3116 fprintf(f," #%05d %-11s", i, artstate_names[art->state]);
3117 DUMPV("%p", art->,ipf);
3118 DUMPV("%d", art->,missing);
3119 DUMPV("%lu", (unsigned long)art->,offset);
3120 DUMPV("%d", art->,blanklen);
3121 DUMPV("%d", art->,midlen);
3122 fprintf(f, " %s %s\n", TokenToText(art->token), art->messageid);
3126 static void dump_input_file(FILE *f, InputFile *ipf, const char *wh) {
3127 char *dipf= debug_report_ipf(ipf);
3128 fprintf(f,"input %s %s", wh, dipf);
3132 DUMPV("%d", ipf->,readcount_ok);
3133 DUMPV("%d", ipf->,readcount_blank);
3134 DUMPV("%d", ipf->,readcount_err);
3138 ArtState state; const char *const *statename;
3139 for (state=0, statename=artstate_names; *statename; state++,statename++) {
3140 #define RC_DUMP_FMT(x) " " #x "=%d"
3141 #define RC_DUMP_VAL(x) ,ipf->counts[state][RC_##x]
3142 fprintf(f,"input %s counts %-11s"
3143 RESULT_COUNTS(RC_DUMP_FMT,RC_DUMP_FMT) "\n",
3145 RESULT_COUNTS(RC_DUMP_VAL,RC_DUMP_VAL));
3152 fprintf(cc->out, "dumping state to %s\n", path_dump);
3153 FILE *f= fopen(path_dump, "w");
3154 if (!f) { fprintf(cc->out, "failed: open: %s\n", strerror(errno)); return; }
3156 fprintf(f,"general");
3157 DUMPV("%s", sms_names,[sms]);
3158 DUMPV("%d", ,sm_period_counter);
3159 DUMPV("%ld", (long),self_pid);
3160 DUMPV("%p", , defer);
3161 DUMPV("%d", , until_connect);
3162 DUMPV("%d", , until_backlog_nextscan);
3163 DUMPV("%d", , simulate_flush);
3164 fprintf(f,"\nnocheck");
3165 DUMPV("%#.10f", , accept_proportion);
3166 DUMPV("%d", , nocheck);
3167 DUMPV("%d", , nocheck_reported);
3170 fprintf(f,"special");
3171 DUMPV("%ld", (long),connecting_child);
3172 DUMPV("%d", , connecting_fdpass_sock);
3173 DUMPV("%d", , control_master);
3176 fprintf(f,"filemon ");
3177 filemon_method_dump_info(f);
3179 dump_input_file(f, main_input_file, "main" );
3180 dump_input_file(f, flushing_input_file, "flushing");
3181 dump_input_file(f, backlog_input_file, "backlog" );
3183 fprintf(f,"conns count=%d\n", conns.count);
3188 fprintf(f,"C%d",conn->fd);
3189 DUMPV("%p",conn->,rd); DUMPV("%d",conn->,max_queue);
3190 DUMPV("%d",conn->,stream); DUMPV("%d",conn->,quitting);
3191 DUMPV("%d",conn->,since_activity);
3194 fprintf(f,"C%d waiting", conn->fd); dump_article_list(f,c,&conn->waiting);
3195 fprintf(f,"C%d priority",conn->fd); dump_article_list(f,c,&conn->priority);
3196 fprintf(f,"C%d sent", conn->fd); dump_article_list(f,c,&conn->sent);
3198 fprintf(f,"C%d xmit xmitu=%d\n", conn->fd, conn->xmitu);
3199 for (i=0; i<conn->xmitu; i++) {
3200 const struct iovec *iv= &conn->xmit[i];
3201 const XmitDetails *xd= &conn->xmitd[i];
3206 diff= xd->info.malloc_tofree - (char*)iv->iov_base;
3207 dinfo= xasprintf("M%5ld", diff);
3210 dinfo= xasprintf("Const");
3213 dinfo= xasprintf("A%p", xd->info.sm_art);
3218 fprintf(f," #%03d %-11s l=%d %s\n", i, dinfo, iv->iov_len,
3219 sanitise(iv->iov_base, iv->iov_len));
3224 fprintf(f,"queue"); dump_article_list(f,c,&queue);
3227 DUMPV("%s", , path_lock);
3228 DUMPV("%s", , path_flushing);
3229 DUMPV("%s", , path_defer);
3230 DUMPV("%s", , path_control);
3231 DUMPV("%s", , path_dump);
3232 DUMPV("%s", , globpat_backlog);
3235 if (!!ferror(f) + !!fclose(f)) {
3236 fprintf(cc->out, "failed: write: %s\n", strerror(errno));
3241 /*========== option parsing ==========*/
3243 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
3244 static void vbadusage(const char *fmt, va_list al) {
3245 char *m= xvasprintf(fmt,al);
3246 fprintf(stderr, "bad usage: %s\n"
3247 "say --help for help, or read the manpage\n",
3250 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
3254 /*---------- generic option parser ----------*/
3256 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
3257 static void badusage(const char *fmt, ...) {
3264 of_seconds= 001000u,
3265 of_boolean= 002000u,
3268 typedef struct Option Option;
3269 typedef void OptionParser(const Option*, const char *val);
3273 const char *lng, *formarg;
3279 static void parse_options(const Option *options, char ***argvp) {
3280 /* on return *argvp is first non-option arg; argc is not updated */
3283 const char *arg= *++(*argvp);
3285 if (*arg != '-') break;
3286 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
3288 while ((a= *++arg)) {
3292 char *equals= strchr(arg,'=');
3293 int len= equals ? (equals - arg) : strlen(arg);
3294 for (o=options; o->shrt || o->lng; o++)
3295 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
3297 badusage("unknown long option --%s",arg);
3300 if (equals) badusage("option --%s does not take a value",o->lng);
3302 } else if (equals) {
3306 if (!arg) badusage("option --%s needs a value for %s",
3307 o->lng, o->formarg);
3310 break; /* eaten the whole argument now */
3312 for (o=options; o->shrt || o->lng; o++)
3315 badusage("unknown short option -%c",a);
3322 if (!arg) badusage("option -%c needs a value for %s",
3323 o->shrt, o->formarg);
3326 break; /* eaten the whole argument now */
3332 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
3334 static void print_options(const Option *options, FILE *f) {
3336 for (o=options; o->shrt || o->lng; o++) {
3337 char shrt[2] = { o->shrt, 0 };
3338 char *optspec= xasprintf("%s%s%s%s%s",
3339 o->shrt ? "-" : "", shrt,
3340 o->shrt && o->lng ? "|" : "",
3341 DELIMPERHAPS("--", o->lng));
3342 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
3347 /*---------- specific option types ----------*/
3349 static void op_integer(const Option *o, const char *val) {
3352 unsigned long ul= strtoul(val,&ep,10);
3353 if (*ep || ep==val || errno || ul>INT_MAX)
3354 badusage("bad integer value for %s",o->lng);
3355 int *store= o->store;
3359 static void op_double(const Option *o, const char *val) {
3360 int *store= o->store;
3363 *store= strtod(val, &ep);
3364 if (*ep || ep==val || errno)
3365 badusage("bad floating point value for %s",o->lng);
3368 static void op_string(const Option *o, const char *val) {
3369 const char **store= o->store;
3373 static void op_seconds(const Option *o, const char *val) {
3374 int *store= o->store;
3378 double v= strtod(val,&ep);
3379 if (ep==val) badusage("bad time/duration value for %s",o->lng);
3381 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
3382 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
3383 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
3384 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
3385 else if (!strcmp(ep,"das")) unit= 10;
3386 else if (!strcmp(ep,"hs")) unit= 100;
3387 else if (!strcmp(ep,"ks")) unit= 1000;
3388 else if (!strcmp(ep,"Ms")) unit= 1000000;
3389 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
3393 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
3397 static void op_setint(const Option *o, const char *val) {
3398 int *store= o->store;
3402 /*---------- specific options ----------*/
3404 static void help(const Option *o, const char *val);
3406 static const Option innduct_options[]= {
3407 {'f',"feedfile", "F", &feedfile, op_string },
3408 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
3409 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
3410 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
3411 {0,"no-filemon", 0, &try_filemon, op_setint, 0 },
3412 {'C',"inndconf", "F", &inndconffile, op_string },
3413 {'P',"port", "PORT", &port, op_integer },
3414 {0,"ctrl-sock-dir", 0, &realsockdir, op_string },
3415 {0,"help", 0, 0, help },
3417 {0,"max-connections", "N", &max_connections, op_integer },
3418 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
3419 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
3420 {0,"period-interval", "TIME", &period_seconds, op_seconds },
3422 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
3423 {0,"stuck-flush-timeout", "TIME", &inndcomm_flush_timeout, op_seconds },
3424 {0,"feedfile-poll", "TIME", &filepoll_seconds, op_seconds },
3426 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
3427 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
3429 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
3430 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
3431 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3432 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3433 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
3434 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
3436 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
3437 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
3442 static void printusage(FILE *f) {
3443 fputs("usage: innduct [options] site [fqdn]\n"
3444 "available options are:\n", f);
3445 print_options(innduct_options, f);
3448 static void help(const Option *o, const char *val) {
3450 if (ferror(stdout) || fflush(stdout)) {
3451 perror("innduct: writing help");
3457 static void convert_to_periods_rndup(int *store) {
3458 *store += period_seconds-1;
3459 *store /= period_seconds;
3462 int main(int argc, char **argv) {
3468 parse_options(innduct_options, &argv);
3473 if (!sitename) badusage("need site name argument");
3474 remote_host= *argv++;
3475 if (*argv) badusage("too many non-option arguments");
3479 int r= innconf_read(inndconffile);
3480 if (!r) badusage("could not read inn.conf (more info on stderr)");
3482 if (!remote_host) remote_host= sitename;
3484 if (nocheck_thresh < 0 || nocheck_thresh > 100)
3485 badusage("nocheck threshold percentage must be between 0..100");
3486 nocheck_thresh *= 0.01;
3488 if (nocheck_decay < 0.1)
3489 badusage("nocheck decay articles must be at least 0.1");
3490 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3492 convert_to_periods_rndup(&reconnect_delay_periods);
3493 convert_to_periods_rndup(&flushfail_retry_periods);
3494 convert_to_periods_rndup(&backlog_retry_minperiods);
3495 convert_to_periods_rndup(&backlog_spontrescan_periods);
3496 convert_to_periods_rndup(&spontaneous_flush_periods);
3497 convert_to_periods_rndup(&need_activity_periods);
3499 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3500 badusage("bad input data ratio must be between 0..100");
3501 max_bad_data_ratio *= 0.01;
3504 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3505 } else if (!feedfile[0]) {
3506 badusage("feed filename must be nonempty");
3507 } else if (feedfile[strlen(feedfile)-1]=='/') {
3508 feedfile= xasprintf("%s%s",feedfile,sitename);
3511 const char *feedfile_forbidden= "?*[~#";
3513 while ((c= *feedfile_forbidden++))
3514 if (strchr(feedfile, c))
3515 badusage("feed filename may not contain metacharacter %c",c);
3519 path_lock= xasprintf("%s_lock", feedfile);
3520 path_flushing= xasprintf("%s_flushing", feedfile);
3521 path_defer= xasprintf("%s_defer", feedfile);
3522 path_control= xasprintf("%s_control", feedfile);
3523 path_dump= xasprintf("%s_dump", feedfile);
3524 globpat_backlog= xasprintf("%s_backlog*", feedfile);
3526 oop_source_sys *sysloop= oop_sys_new();
3527 if (!sysloop) sysdie("could not create liboop event loop");
3528 loop= (oop_source*)sysloop;
3533 if (become_daemon) {
3535 for (i=3; i<255; i++)
3536 /* do this now before we open syslog, etc. */
3538 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3540 int null= open("/dev/null",O_RDWR);
3541 if (null<0) sysfatal("failed to open /dev/null");
3545 xclose(null, "/dev/null original fd",0);
3547 pid_t child1= xfork("daemonise first fork");
3548 if (child1) _exit(0);
3550 pid_t sid= setsid();
3551 if (sid != child1) sysfatal("setsid failed");
3553 pid_t child2= xfork("daemonise second fork");
3554 if (child2) _exit(0);
3558 if (self_pid==-1) sysdie("getpid");
3573 notice("filemon: suppressed by command line option, polling");
3575 filemon_ok= filemon_method_init();
3577 warn("filemon: no file monitoring available, polling");
3580 every(filepoll_seconds,0,filepoll);
3582 every(period_seconds,1,period);
3588 void *run= oop_sys_run(sysloop);
3589 assert(run == OOP_ERROR);
3590 sysdie("event loop failed");