3 * - reset signals TERM and INT (and HUP) in children
5 * - manpage: document control master stuff
6 * - admin-initiated flush
9 * build-lfs/backends/innduct --connection-timeout=30 --no-daemon -C ../inn.conf -f `pwd`/fee sit localhost
13 * Newsfeeds file entries should look like this:
14 * host.name.of.site[/exclude,exclude,...]\
15 * :pattern,pattern...[/distribution,distribution...]\
19 * sitename[/exclude,exclude,...]\
20 * :pattern,pattern...[/distribution,distribution...]\
26 * or might be blanked out
27 * <spc><spc><spc><spc>....
29 * F site.name main feed file
30 * opened/created, then written, by innd
33 * tokens blanked out by duct when processed
34 * site.name_lock lock preventing multiple ducts
35 * to hold lock must open,F_SETLK[W]
36 * and then stat to check that locked file
37 * still has name site.name_lock
38 * holder of this lock is "duct"
39 * (only) lockholder may remove the lockfile
40 * D site.name_flushing temporary feed file during flush (or crash)
41 * hardlink created by duct
43 * site.name_defer 431'd articles, still being written,
44 * created, written, used by duct
46 * site.name_backlog.<date>.<inum>
47 * 431'd articles, ready for innxmit or duct
48 * created (link/mv) by duct
49 * site.name_backlog<anything-else> (where <anything-else> does not
50 * contain '#' or '~') eg
51 * site.name_backlog.manual
52 * anything the sysadmin likes (eg, feed files
53 * from old feeds to be merged into this one)
54 * created (link/mv) by admin
55 * may be symlinks (in which case links
56 * may be written through, but only links
59 * It is safe to remove backlog files manually,
60 * if it's desired to throw away the backlog.
62 * Backlog files are also processed by innduct. We find the oldest
63 * backlog file which is at least a certain amount old, and feed it
64 * back into our processing. When every article in it has been read
65 * and processed, we unlink it and look for another backlog file.
67 * If we don't have a backlog file that we're reading, we close the
68 * defer file that we're writing and make it into a backlog file at
69 * the first convenient opportunity.
80 | | <----------------<---------------------------------'|
86 | F: innd writing, duct reading |
89 | | duct decides time to flush |
90 | | duct makes hardlink |
92 | V <------------------------'|
94 | F == D: innd writing, duct reading both exist |
97 | | <-----------<-------------<--'|
101 | V <---------------------. |
104 | D: innd writing, duct reading; or ENOENT | |
106 | | duct requests flush of feed | |
107 | | (others can too, harmlessly) | |
111 | D: innd flushing, duct; or ENOENT | |
113 | | inndcomm flush fails | |
114 | |`-------------------------->------------------' |
116 | | inndcomm reports no such site |
117 | |`---------------------------------------------------- | -.
119 | | innd finishes writing D, creates F | |
120 | | inndcomm reports flush successful | |
123 | Separated <----------------' |
124 | F: innd writing F!=D /
125 | D: duct reading; or ENOENT both exist /
127 | | duct gets to the end of D /
128 | | duct opens F too /
131 | F: innd writing, duct reading |
132 | D: duct finishing V
134 | | duct finishes processing D F: ENOENT
135 | V duct unlinks D D: duct reading
137 `--<--' | duct finishes
147 "duct reading" means innduct is reading the file but also
148 overwriting processed tokens.
152 * rune for printing diagrams:
154 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
159 /*============================== PROGRAM ==============================*/
161 #define _GNU_SOURCE 1
167 #include "inndcomm.h"
169 #include "inn/list.h"
170 #include "inn/innconf.h"
173 #include <sys/types.h>
174 #include <sys/wait.h>
175 #include <sys/stat.h>
176 #include <sys/socket.h>
195 #include <oop-read.h>
197 /*----- general definitions, probably best not changed -----*/
199 #define CONNCHILD_ESTATUS_STREAM 24
200 #define CONNCHILD_ESTATUS_NOSTREAM 25
202 #define INNDCOMMCHILD_ESTATUS_FAIL 26
203 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
205 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
206 #define MAX_CONTROL_COMMAND 1000
208 #define VA va_list al; va_start(al,fmt)
209 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
210 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
212 #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 */
302 static void article_done(Conn *conn, Article *art, int whichcount);
304 static void check_assign_articles(void);
305 static void queue_check_input_done(void);
307 static void statemc_check_flushing_done(void);
308 static void statemc_check_backlog_done(void);
310 static void postfork(void);
311 static void period(void);
313 static void open_defer(void);
314 static void close_defer(void);
315 static void search_backlog_file(void);
316 static void preterminate(void);
317 static void raise_default(int signo);
318 static char *debug_report_ipf(InputFile *ipf);
320 static void inputfile_reading_start(InputFile *ipf);
321 static void inputfile_reading_stop(InputFile *ipf);
323 static void filemon_start(InputFile *ipf);
324 static void filemon_stop(InputFile *ipf);
325 static void filemon_callback(InputFile *ipf);
327 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
328 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
330 static const oop_rd_style peer_rd_style;
331 static oop_rd_call peer_rd_err, peer_rd_ok;
333 /*----- configuration options -----*/
334 /* when changing defaults, remember to update the manpage */
336 static const char *sitename, *remote_host;
337 static const char *feedfile, *realsockdir="/tmp/innduct.control";
338 static int quiet_multiple=0;
339 static int become_daemon=1, try_filemon=1;
340 static int try_stream=1;
342 static const char *inndconffile;
344 static int max_connections=10;
345 static int max_queue_per_conn=200;
346 static int target_max_feedfile_size=100000;
347 static int period_seconds=60;
348 static int filepoll_seconds=5;
350 static int connection_setup_timeout=200;
351 static int inndcomm_flush_timeout=100;
353 static double nocheck_thresh= 95.0; /* converted from percentage by main */
354 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
356 /* all these are initialised to seconds, and converted to periods in main */
357 static int reconnect_delay_periods=1000;
358 static int flushfail_retry_periods=1000;
359 static int backlog_retry_minperiods=50;
360 static int backlog_spontrescan_periods=300;
361 static int spontaneous_flush_periods=100000;
362 static int need_activity_periods=1000;
364 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
365 static int max_bad_data_initial= 30;
366 /* in one corrupt 4096-byte block the number of newlines has
367 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
370 /*----- statistics -----*/
372 typedef enum { /* in queue in conn->sent */
373 art_Unchecked, /* not checked, not sent checking */
374 art_Wanted, /* checked, wanted sent body as requested */
375 art_Unsolicited, /* - sent body without check */
379 static const char *const artstate_names[]=
380 { "Unchecked", "Wanted", "Unsolicited", 0 };
382 #define RESULT_COUNTS(RCS,RCN) \
391 #define RCI_TRIPLE_FMT_BASE "%d (id=%d,bod=%d,nc=%d)"
392 #define RCI_TRIPLE_VALS_BASE(counts,x) \
393 counts[art_Unchecked] x \
394 + counts[art_Wanted] x \
395 + counts[art_Unsolicited] x, \
396 counts[art_Unchecked] x \
397 , counts[art_Wanted] x \
398 , counts[art_Unsolicited] x
401 #define RC_INDEX(x) RC_##x,
402 RESULT_COUNTS(RC_INDEX, RC_INDEX)
407 /*----- transmission buffers -----*/
412 xk_Malloc, xk_Const, xk_Artdata
424 /*----- core operational data structure types -----*/
427 /* This is also an instance of struct oop_readable */
428 struct oop_readable readable; /* first */
429 oop_readable_call *readable_callback;
430 void *readable_callback_user;
433 Filemon_Perfile *filemon;
435 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
436 long inprogress; /* no. of articles read but not processed */
440 int counts[art_MaxState][RCI_max];
441 int readcount_ok, readcount_blank, readcount_err;
456 #define SMS_LIST(X) \
464 enum StateMachineState {
465 #define SMS_DEF_ENUM(s) sm_##s,
466 SMS_LIST(SMS_DEF_ENUM)
469 static const char *sms_names[]= {
470 #define SMS_DEF_NAME(s) #s ,
471 SMS_LIST(SMS_DEF_NAME)
477 int fd; /* may be 0, meaning closed (during construction/destruction) */
478 oop_read *rd; /* likewise */
479 int max_queue, stream, quitting;
480 int since_activity; /* periods */
481 ArticleList waiting; /* not yet told peer */
482 ArticleList priority; /* peer says send it now */
483 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
484 struct iovec xmit[CONNIOVS];
485 XmitDetails xmitd[CONNIOVS];
490 /*----- general operational variables -----*/
492 /* main initialises */
493 static oop_source *loop;
494 static ConnList conns;
495 static ArticleList queue;
496 static char *path_lock, *path_flushing, *path_defer;
497 static char *path_control, *path_dump;
498 static char *globpat_backlog;
499 static pid_t self_pid;
501 /* statemc_init initialises */
502 static StateMachineState sms;
503 static int sm_period_counter;
504 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
507 /* initialisation to 0 is good */
508 static int until_connect, until_backlog_nextscan;
509 static double accept_proportion;
510 static int nocheck, nocheck_reported, in_child;
512 /* for simulation, debugging, etc. */
513 int simulate_flush= -1;
515 /*========== logging ==========*/
517 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
518 static void logcore(int sysloglevel, const char *fmt, ...) {
521 vsyslog(sysloglevel,fmt,al);
523 if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
524 vfprintf(stderr,fmt,al);
530 static void logv(int sysloglevel, const char *pfx, int errnoval,
531 const char *fmt, va_list al) PRINTF(5,0);
532 static void logv(int sysloglevel, const char *pfx, int errnoval,
533 const char *fmt, va_list al) {
534 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
535 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
536 msgbuf[sizeof(msgbuf)-1]= 0;
538 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
539 sysloglevel= LOG_ERR; /* run by wrong user, probably */
541 logcore(sysloglevel, "<%s>%s: %s%s%s",
542 sitename, pfx, msgbuf,
543 errnoval>=0 ? ": " : "",
544 errnoval>=0 ? strerror(errnoval) : "");
547 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
548 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
549 static void fn(const char *fmt, ...) { \
552 logv(sysloglevel, pfx, err, fmt, al); \
556 #define logwrap(fn, pfx, sysloglevel, err) \
557 static void fn(const char *fmt, ...) PRINTF(1,2); \
558 static void fn(const char *fmt, ...) { \
560 logv(sysloglevel, pfx, err, fmt, al); \
564 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
565 diewrap(die, " critical", LOG_CRIT, -1, 16);
567 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
568 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
570 logwrap(syswarn, " warning", LOG_WARNING, errno);
571 logwrap(warn, " warning", LOG_WARNING, -1);
573 logwrap(notice, " notice", LOG_NOTICE, -1);
574 logwrap(info, " info", LOG_INFO, -1);
575 logwrap(debug, " debug", LOG_DEBUG, -1);
578 /*========== utility functions etc. ==========*/
580 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
581 static char *xvasprintf(const char *fmt, va_list al) {
583 int rc= vasprintf(&str,fmt,al);
584 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
587 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
588 static char *xasprintf(const char *fmt, ...) {
590 char *str= xvasprintf(fmt,al);
595 static int close_perhaps(int *fd) {
596 if (*fd <= 0) return 0;
601 static void xclose(int fd, const char *what, const char *what2) {
603 if (r) sysdie("close %s%s",what,what2?what2:"");
605 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
606 if (*fd <= 0) return;
607 xclose(*fd,what,what2);
611 static pid_t xfork(const char *what) {
615 if (child==-1) sysfatal("cannot fork for %s",what);
616 debug("forked %s %ld", what, (unsigned long)child);
617 if (!child) postfork();
621 static void on_fd_read_except(int fd, oop_call_fd callback) {
622 loop->on_fd(loop, fd, OOP_READ, callback, 0);
623 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
625 static void cancel_fd_read_except(int fd) {
626 loop->cancel_fd(loop, fd, OOP_READ);
627 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
630 static void report_child_status(const char *what, int status) {
631 if (WIFEXITED(status)) {
632 int es= WEXITSTATUS(status);
634 warn("%s: child died with error exit status %d", what, es);
635 } else if (WIFSIGNALED(status)) {
636 int sig= WTERMSIG(status);
637 const char *sigstr= strsignal(sig);
638 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
640 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
642 warn("%s: child died due to unknown fatal signal %d%s",
643 what, sig, coredump);
645 warn("%s: child died with unknown wait status %d", what,status);
649 static int xwaitpid(pid_t *pid, const char *what) {
652 int r= kill(*pid, SIGKILL);
653 if (r) sysdie("cannot kill %s child", what);
655 pid_t got= waitpid(*pid, &status, 0);
656 if (got==-1) sysdie("cannot reap %s child", what);
657 if (got==0) die("cannot reap %s child", what);
664 static void *zxmalloc(size_t sz) {
665 void *p= xmalloc(sz);
670 static void xunlink(const char *path, const char *what) {
672 if (r) sysdie("can't unlink %s %s", path, what);
675 static time_t xtime(void) {
677 if (now==-1) sysdie("time(2) failed");
681 static void xsigaction(int s, const struct sigaction *sa) {
682 int r= sigaction(s,sa,0);
683 if (r) sysdie("sigaction failed for \"%s\"", strsignal(s));
686 static void xgettimeofday(struct timeval *tv_r) {
687 int r= gettimeofday(tv_r,0);
688 if (r) sysdie("gettimeofday(2) failed");
691 static void xsetnonblock(int fd, int nonblocking) {
692 int errnoval= oop_fd_nonblock(fd, nonblocking);
693 if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
696 static void check_isreg(const struct stat *stab, const char *path,
698 if (!S_ISREG(stab->st_mode))
699 die("%s %s not a plain file (mode 0%lo)",
700 what, path, (unsigned long)stab->st_mode);
703 static void xfstat(int fd, struct stat *stab_r, const char *what) {
704 int r= fstat(fd, stab_r);
705 if (r) sysdie("could not fstat %s", what);
708 static void xfstat_isreg(int fd, struct stat *stab_r,
709 const char *path, const char *what) {
710 xfstat(fd, stab_r, what);
711 check_isreg(stab_r, path, what);
714 static void xlstat_isreg(const char *path, struct stat *stab,
715 int *enoent_r /* 0 means ENOENT is fatal */,
717 int r= lstat(path, stab);
719 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
720 sysdie("could not lstat %s %s", what, path);
722 if (enoent_r) *enoent_r= 0;
723 check_isreg(stab, path, what);
726 static int samefile(const struct stat *a, const struct stat *b) {
727 assert(S_ISREG(a->st_mode));
728 assert(S_ISREG(b->st_mode));
729 return (a->st_ino == b->st_ino &&
730 a->st_dev == b->st_dev);
733 static char *sanitise(const char *input, int len) {
734 static char sanibuf[100]; /* returns pointer to this buffer! */
736 const char *p= input;
737 const char *endp= len>=0 ? input+len : 0;
741 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
742 int c= (!endp || p<endp) ? *p++ : 0;
743 if (!c) { *q++= '\''; *q=0; break; }
744 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
745 sprintf(q,"\\x%02x",c);
751 static int isewouldblock(int errnoval) {
752 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
755 /*========== command and control connections ==========*/
757 static int control_master;
759 typedef struct ControlConn ControlConn;
761 void (*destroy)(ControlConn*);
767 struct sockaddr_un un;
772 static const oop_rd_style control_rd_style= {
773 OOP_RD_DELIM_STRIP, '\n',
775 OOP_RD_SHORTREC_FORBID
778 static void control_destroy(ControlConn *cc) {
782 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
783 if (ferror(cc->out) | fflush(cc->out)) {
784 info("CTRL%d write error %s", cc->fd, strerror(errno));
789 static void control_prompt(ControlConn *cc /* may destroy*/) {
790 fprintf(cc->out, "%s| ", sitename);
791 control_checkouterr(cc);
794 struct ControlCommand {
796 void (*f)(ControlConn *cc, const ControlCommand *ccmd,
797 const char *arg, size_t argsz);
802 static const ControlCommand control_commands[];
805 static void ccmd_##wh(ControlConn *cc, const ControlCommand *c, \
806 const char *arg, size_t argsz)
809 fputs("commands:\n", cc->out);
810 const ControlCommand *ccmd;
811 for (ccmd=control_commands; ccmd->cmd; ccmd++)
812 fprintf(cc->out, " %s\n", ccmd->cmd);
815 CCMD(period) { period(); }
816 CCMD(setintarg) { *(int*)c->xdata= atoi(arg); }
817 CCMD(setint) { *(int*)c->xdata= c->xval; }
818 CCMD(setint_period) { *(int*)c->xdata= c->xval; period(); }
823 notice("terminating (CTRL%d)",cc->fd);
824 raise_default(SIGTERM);
828 static const ControlCommand control_commands[]= {
830 { "p", ccmd_period },
831 { "stop", ccmd_stop },
832 { "dump q", ccmd_dump, 0,0 },
833 { "dump a", ccmd_dump, 0,1 },
835 #define POKES(cmd,func) \
836 { cmd "sm", func, &sm_period_counter, 1 }, \
837 { cmd "conn", func, &until_connect, 0 }, \
838 { cmd "blscan", func, &until_backlog_nextscan, 0 },
839 POKES("prod ", ccmd_setint_period)
840 POKES("next ", ccmd_setint)
842 { "pretend flush", ccmd_setintarg, &simulate_flush },
843 { "wedge blscan", ccmd_setint, &until_backlog_nextscan, -1 },
847 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
848 const char *errmsg, int errnoval,
849 const char *data, size_t recsz, void *cc_v) {
850 ControlConn *cc= cc_v;
853 info("CTRL%d closed", cc->fd);
858 if (recsz == 0) goto prompt;
860 const ControlCommand *ccmd;
861 for (ccmd=control_commands; ccmd->cmd; ccmd++) {
862 int l= strlen(ccmd->cmd);
863 if (recsz < l) continue;
864 if (recsz > l && data[l] != ' ') continue;
865 if (memcmp(data, ccmd->cmd, l)) continue;
867 int argl= (int)recsz - (l+1);
868 ccmd->f(cc, ccmd, argl>=0 ? data+l+1 : 0, argl);
872 fputs("unknown command; h for help\n", cc->out);
879 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
880 const char *errmsg, int errnoval,
881 const char *data, size_t recsz, void *cc_v) {
882 ControlConn *cc= cc_v;
884 info("CTRL%d read error %s", cc->fd, errmsg);
889 static int control_conn_startup(ControlConn *cc /* may destroy*/,
891 cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
892 if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
894 int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
897 if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
899 info("CTRL%d %s ready", cc->fd, how);
904 static void control_stdio_destroy(ControlConn *cc) {
906 oop_rd_cancel(cc->rd);
907 errno= oop_rd_delete_tidy(cc->rd);
908 if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
913 static void control_stdio(void) {
914 NEW_DECL(ControlConn *,cc);
915 cc->destroy= control_stdio_destroy;
919 int r= control_conn_startup(cc,"stdio");
920 if (r) cc->destroy(cc);
923 static void control_accepted_destroy(ControlConn *cc) {
925 oop_rd_cancel(cc->rd);
926 oop_rd_delete_kill(cc->rd);
928 if (cc->out) { fclose(cc->out); cc->fd=0; }
929 close_perhaps(&cc->fd);
933 static void *control_master_readable(oop_source *lp, int master,
934 oop_event ev, void *u) {
935 NEW_DECL(ControlConn *,cc);
936 cc->destroy= control_accepted_destroy;
938 cc->salen= sizeof(cc->sa);
939 cc->fd= accept(master, &cc->sa.sa, &cc->salen);
940 if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
942 cc->out= fdopen(cc->fd, "w");
943 if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
945 int r= control_conn_startup(cc, "accepted");
955 #define NOCONTROL(...) do{ \
956 syswarn("no control socket, because failed to " __VA_ARGS__); \
960 static void control_init(void) {
965 struct sockaddr_un un;
968 memset(&sa,0,sizeof(sa));
969 int maxlen= sizeof(sa.un.sun_path);
971 int reallen= readlink(path_control, sa.un.sun_path, maxlen);
974 NOCONTROL("readlink control socket symlink path %s", path_control);
976 if (reallen >= maxlen) {
977 debug("control socket symlink path too long (r=%d)",reallen);
978 xunlink(path_control, "old (overlong) control socket symlink");
984 int r= lstat(realsockdir,&stab);
986 if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
988 r= mkdir(realsockdir, 0700);
989 if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
992 uid_t self= geteuid();
993 if (!S_ISDIR(stab.st_mode) ||
994 stab.st_uid != self ||
995 stab.st_mode & 0007) {
996 warn("no control socket, because real socket directory"
997 " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
998 !!S_ISDIR(stab.st_mode),
999 (unsigned long)stab.st_uid, (unsigned long)self,
1000 (unsigned long)stab.st_mode & 0777UL);
1005 real= xasprintf("%s/s%lx.%lx", realsockdir,
1006 (unsigned long)xtime(), (unsigned long)self_pid);
1007 int reallen= strlen(real);
1009 if (reallen >= maxlen) {
1010 warn("no control socket, because tmpnam gave overly-long path"
1014 r= symlink(real, path_control);
1015 if (r) NOCONTROL("make control socket path %s a symlink to real"
1016 " socket path %s", path_control, real);
1017 memcpy(sa.un.sun_path, real, reallen);
1020 int r= unlink(sa.un.sun_path);
1021 if (r && errno!=ENOENT)
1022 NOCONTROL("remove old real socket %s", sa.un.sun_path);
1024 control_master= socket(PF_UNIX, SOCK_STREAM, 0);
1025 if (control_master<0) NOCONTROL("create new control socket");
1027 sa.un.sun_family= AF_UNIX;
1028 int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
1029 r= bind(control_master, &sa.sa, sl);
1030 if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
1032 r= listen(control_master, 5);
1033 if (r) NOCONTROL("listen");
1035 xsetnonblock(control_master, 1);
1037 loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
1038 info("control socket ok, real path %s", sa.un.sun_path);
1044 xclose_perhaps(&control_master, "control master",0);
1048 /*========== management of connections ==========*/
1050 static void conn_closefd(Conn *conn, const char *msgprefix) {
1051 int r= close_perhaps(&conn->fd);
1052 if (r) info("C%d %serror closing socket: %s",
1053 conn->fd, msgprefix, strerror(errno));
1056 static void conn_dispose(Conn *conn) {
1059 oop_rd_cancel(conn->rd);
1060 oop_rd_delete_kill(conn->rd);
1064 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1065 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
1067 conn_closefd(conn,"");
1069 until_connect= reconnect_delay_periods;
1072 static void *conn_exception(oop_source *lp, int fd,
1073 oop_event ev, void *conn_v) {
1076 assert(fd == conn->fd);
1077 assert(ev == OOP_EXCEPTION);
1078 int r= read(conn->fd, &ch, 1);
1079 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1080 else connfail(conn,"exceptional condition on socket (peer sent urgent"
1081 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1082 return OOP_CONTINUE;
1085 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1086 int requeue[art_MaxState];
1087 memset(requeue,0,sizeof(requeue));
1090 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1091 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1092 while ((art= LIST_REMHEAD(conn->sent))) {
1093 requeue[art->state]++;
1094 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1095 LIST_ADDTAIL(queue,art);
1100 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1103 char *m= xvasprintf(fmt,al);
1104 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1105 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1108 LIST_REMOVE(conns,conn);
1110 check_assign_articles();
1113 static void connfail(Conn *conn, const char *fmt, ...) {
1116 vconnfail(conn,fmt,al);
1120 static void check_idle_conns(void) {
1123 conn->since_activity++;
1126 if (conn->since_activity <= need_activity_periods) continue;
1128 /* We need to shut this down */
1130 connfail(conn,"timed out waiting for response to QUIT");
1131 else if (conn->sent.count)
1132 connfail(conn,"timed out waiting for responses");
1133 else if (conn->waiting.count || conn->priority.count)
1134 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1135 else if (conn->xmitu)
1136 connfail(conn,"peer has been sending responses"
1137 " before receiving our commands!");
1139 static const char quitcmd[]= "QUIT\r\n";
1140 int todo= sizeof(quitcmd)-1;
1141 const char *p= quitcmd;
1143 int r= write(conn->fd, p, todo);
1145 if (isewouldblock(errno))
1146 connfail(conn, "blocked writing QUIT to idle connection");
1148 connfail(conn, "failed to write QUIT to idle connection: %s",
1156 conn->since_activity= 0;
1157 debug("C%d is idle, quitting", conn->fd);
1166 /*---------- making new connections ----------*/
1168 static pid_t connecting_child;
1169 static int connecting_fdpass_sock;
1171 static void connect_attempt_discard(void) {
1172 if (connecting_child) {
1173 int status= xwaitpid(&connecting_child, "connect");
1174 if (!(WIFEXITED(status) ||
1175 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1176 report_child_status("connect", status);
1178 if (connecting_fdpass_sock) {
1179 cancel_fd_read_except(connecting_fdpass_sock);
1180 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1184 #define PREP_DECL_MSG_CMSG(msg) \
1186 struct iovec msgiov; \
1187 msgiov.iov_base= &msgbyte; \
1188 msgiov.iov_len= 1; \
1189 struct msghdr msg; \
1190 memset(&msg,0,sizeof(msg)); \
1191 char msg##cbuf[CMSG_SPACE(sizeof(int))]; \
1192 msg.msg_iov= &msgiov; \
1193 msg.msg_iovlen= 1; \
1194 msg.msg_control= msg##cbuf; \
1195 msg.msg_controllen= sizeof(msg##cbuf);
1197 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1200 assert(fd == connecting_fdpass_sock);
1202 PREP_DECL_MSG_CMSG(msg);
1204 ssize_t rs= recvmsg(fd, &msg, 0);
1206 if (isewouldblock(errno)) return OOP_CONTINUE;
1207 syswarn("failed to read socket from connecting child");
1212 LIST_INIT(conn->waiting);
1213 LIST_INIT(conn->priority);
1214 LIST_INIT(conn->sent);
1216 struct cmsghdr *h= 0;
1217 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1219 int status= xwaitpid(&connecting_child, "connect child (broken)");
1221 if (WIFEXITED(status)) {
1222 if (WEXITSTATUS(status) != 0 &&
1223 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1224 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1225 /* child already reported the problem */;
1227 if (e == OOP_EXCEPTION)
1228 warn("connect: connection child exited code %d but"
1229 " unexpected exception on fdpass socket",
1230 WEXITSTATUS(status));
1232 warn("connect: connection child exited code %d but"
1234 WEXITSTATUS(status), (int)rs);
1236 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1237 warn("connect: connection attempt timed out");
1239 report_child_status("connect", status);
1244 #define CHK(field, val) \
1245 if (h->cmsg_##field != val) { \
1246 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1247 h->cmsg_##field, val); \
1250 CHK(level, SOL_SOCKET);
1251 CHK(type, SCM_RIGHTS);
1252 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1255 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1257 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1260 pid_t got= waitpid(connecting_child, &status, 0);
1261 if (got==-1) sysdie("connect: real wait for child");
1262 assert(got == connecting_child);
1263 connecting_child= 0;
1265 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1266 int es= WEXITSTATUS(status);
1268 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1269 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1271 fatal("connect: child gave unexpected exit status %d", es);
1275 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1277 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1278 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1279 if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1280 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1282 &peer_rd_err, conn);
1283 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1285 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1286 LIST_ADDHEAD(conns, conn);
1288 connect_attempt_discard();
1289 check_assign_articles();
1290 return OOP_CONTINUE;
1294 connect_attempt_discard();
1295 return OOP_CONTINUE;
1298 static int allow_connect_start(void) {
1299 return conns.count < max_connections
1300 && !connecting_child
1304 static void connect_start(void) {
1305 assert(!connecting_child);
1306 assert(!connecting_fdpass_sock);
1308 info("starting connection attempt");
1311 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1312 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1314 connecting_child= xfork("connection");
1316 if (!connecting_child) {
1317 FILE *cn_from, *cn_to;
1318 char buf[NNTP_STRLEN+100];
1319 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1321 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1323 alarm(connection_setup_timeout);
1324 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1328 unsigned char c= buf[l-1];
1329 if (!isspace(c)) break;
1330 if (c=='\n' || c=='\r') stripped=1;
1334 sysfatal("connect: connection attempt failed");
1337 fatal("connect: %s: %s", stripped ? "rejected" : "failed",
1341 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1342 sysfatal("connect: authentication failed");
1344 if (fputs("MODE STREAM\r\n", cn_to)==EOF ||
1346 sysfatal("connect: could not send MODE STREAM");
1347 buf[sizeof(buf)-1]= 0;
1348 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1349 if (ferror(cn_from))
1350 sysfatal("connect: could not read response to MODE STREAM");
1352 fatal("connect: connection close in response to MODE STREAM");
1357 fatal("connect: response to MODE STREAM is too long: %.100s...",
1359 l--; if (l>0 && buf[l-1]=='\r') l--;
1362 int rcode= strtoul(buf,&ep,10);
1364 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf,-1));
1368 exitstatus= CONNCHILD_ESTATUS_STREAM;
1374 warn("connect: unexpected response to MODE STREAM: %.50s",
1380 int fd= fileno(cn_from);
1382 PREP_DECL_MSG_CMSG(msg);
1383 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1384 cmsg->cmsg_level= SOL_SOCKET;
1385 cmsg->cmsg_type= SCM_RIGHTS;
1386 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1387 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1389 msg.msg_controllen= cmsg->cmsg_len;
1390 r= sendmsg(socks[1], &msg, 0);
1391 if (r<0) sysdie("sendmsg failed for new connection");
1392 if (r!=1) die("sendmsg for new connection gave wrong result %d",r);
1397 xclose(socks[1], "connecting fdpass child's socket",0);
1398 connecting_fdpass_sock= socks[0];
1399 xsetnonblock(connecting_fdpass_sock, 1);
1400 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1403 /*---------- assigning articles to conns, and transmitting ----------*/
1405 static void check_assign_articles(void) {
1411 int spare=0, inqueue=0;
1413 /* Find a connection to offer this article. We prefer a busy
1414 * connection to an idle one, provided it's not full. We take the
1415 * first (oldest) and since that's stable, it will mean we fill up
1416 * connections in order. That way if we have too many
1417 * connections, the spare ones will go away eventually.
1420 if (walk->quitting) continue;
1421 inqueue= walk->sent.count + walk->priority.count
1422 + walk->waiting.count;
1423 spare= walk->max_queue - inqueue;
1424 assert(inqueue <= max_queue_per_conn);
1426 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1427 else if (spare>0) /*working*/ { use= walk; break; }
1430 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1432 Article *art= LIST_REMHEAD(queue);
1434 LIST_ADDTAIL(use->waiting, art);
1437 conn_maybe_write(use);
1438 } else if (allow_connect_start()) {
1439 until_connect= reconnect_delay_periods;
1448 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1449 conn_maybe_write(u);
1450 return OOP_CONTINUE;
1453 static void conn_maybe_write(Conn *conn) {
1455 conn_make_some_xmits(conn);
1457 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1461 void *rp= conn_write_some_xmits(conn);
1462 if (rp==OOP_CONTINUE) {
1463 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1465 } else if (rp==OOP_HALT) {
1468 /* transmitted everything */
1475 /*========== article transmission ==========*/
1477 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1478 XmitKind kind) { /* caller must then fill in details */
1479 struct iovec *v= &conn->xmit[conn->xmitu];
1480 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1481 v->iov_base= (char*)data;
1487 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1488 xmit_core(conn,data,len, xk_Const);
1490 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1492 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1493 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1497 static void xmit_free(XmitDetails *d) {
1499 case xk_Malloc: free(d->info.malloc_tofree); break;
1500 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1501 case xk_Const: break;
1506 static void *conn_write_some_xmits(Conn *conn) {
1508 * 0: nothing more to write, no need to call us again
1509 * OOP_CONTINUE: more to write but fd not writeable
1510 * OOP_HALT: disaster, have destroyed conn
1513 int count= conn->xmitu;
1514 if (!count) return 0;
1516 if (count > IOV_MAX) count= IOV_MAX;
1517 ssize_t rs= writev(conn->fd, conn->xmit, count);
1519 if (isewouldblock(errno)) return OOP_CONTINUE;
1520 connfail(conn, "write failed: %s", strerror(errno));
1526 for (done=0; rs && done<conn->xmitu; done++) {
1527 struct iovec *vp= &conn->xmit[done];
1528 XmitDetails *dp= &conn->xmitd[done];
1529 if (rs > vp->iov_len) {
1533 vp->iov_base= (char*)vp->iov_base + rs;
1537 int newu= conn->xmitu - done;
1538 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1539 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1544 static void conn_make_some_xmits(Conn *conn) {
1546 if (conn->xmitu+5 > CONNIOVS)
1549 Article *art= LIST_REMHEAD(conn->priority);
1550 if (!art) art= LIST_REMHEAD(conn->waiting);
1553 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1554 /* actually send it */
1556 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1559 art->state == art_Unchecked ? art_Unsolicited :
1560 art->state == art_Wanted ? art_Wanted :
1563 if (!artdata) art->missing= 1;
1564 art->ipf->counts[art->state][ artdata ? RC_sent : RC_missing ]++;
1568 XMIT_LITERAL("TAKETHIS ");
1569 xmit_noalloc(conn, art->messageid, art->midlen);
1570 XMIT_LITERAL("\r\n");
1571 xmit_artbody(conn, artdata);
1573 article_done(conn, art, -1);
1577 /* we got 235 from IHAVE */
1579 xmit_artbody(conn, artdata);
1581 XMIT_LITERAL(".\r\n");
1585 LIST_ADDTAIL(conn->sent, art);
1591 XMIT_LITERAL("CHECK ");
1593 XMIT_LITERAL("IHAVE ");
1594 xmit_noalloc(conn, art->messageid, art->midlen);
1595 XMIT_LITERAL("\r\n");
1597 assert(art->state == art_Unchecked);
1598 art->ipf->counts[art->state][RC_sent]++;
1599 LIST_ADDTAIL(conn->sent, art);
1605 /*========== handling responses from peer ==========*/
1607 static const oop_rd_style peer_rd_style= {
1608 OOP_RD_DELIM_STRIP, '\n',
1610 OOP_RD_SHORTREC_FORBID
1613 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1614 const char *errmsg, int errnoval,
1615 const char *data, size_t recsz, void *conn_v) {
1617 connfail(conn, "error receiving from peer: %s", errmsg);
1618 return OOP_CONTINUE;
1621 static Article *article_reply_check(Conn *conn, const char *response,
1622 int code_indicates_streaming,
1624 /* 1:yes, -1:no, 0:dontcare */,
1625 const char *sanitised_response) {
1626 Article *art= LIST_HEAD(conn->sent);
1630 "peer gave unexpected response when no commands outstanding: %s",
1631 sanitised_response);
1635 if (code_indicates_streaming) {
1636 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1637 if (!conn->stream) {
1638 connfail(conn, "peer gave streaming response code "
1639 " to IHAVE or subsequent body: %s", sanitised_response);
1642 const char *got_mid= response+4;
1643 int got_midlen= strcspn(got_mid, " \n\r");
1644 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1645 connfail(conn, "peer gave streaming response with syntactically invalid"
1646 " messageid: %s", sanitised_response);
1649 if (got_midlen != art->midlen ||
1650 memcmp(got_mid, art->messageid, got_midlen)) {
1651 connfail(conn, "peer gave streaming response code to wrong article -"
1652 " probable synchronisation problem; we offered: %s;"
1654 art->messageid, sanitised_response);
1659 connfail(conn, "peer gave non-streaming response code to"
1660 " CHECK/TAKETHIS: %s", sanitised_response);
1665 if (must_have_sent>0 && art->state < art_Wanted) {
1666 connfail(conn, "peer says article accepted but"
1667 " we had not sent the body: %s", sanitised_response);
1670 if (must_have_sent<0 && art->state >= art_Wanted) {
1671 connfail(conn, "peer says please sent the article but we just did: %s",
1672 sanitised_response);
1676 Article *art_again= LIST_REMHEAD(conn->sent);
1677 assert(art_again == art);
1681 static void update_nocheck(int accepted) {
1682 accept_proportion *= nocheck_decay;
1683 accept_proportion += accepted * (1.0 - nocheck_decay);
1684 int new_nocheck= accept_proportion >= nocheck_thresh;
1685 if (new_nocheck && !nocheck_reported) {
1686 notice("entering nocheck mode for the first time");
1687 nocheck_reported= 1;
1688 } else if (new_nocheck != nocheck) {
1689 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1691 nocheck= new_nocheck;
1694 static void article_done(Conn *conn, Article *art, int whichcount) {
1695 if (!art->missing) art->ipf->counts[art->state][whichcount]++;
1697 if (whichcount == RC_accepted) update_nocheck(1);
1698 else if (whichcount == RC_unwanted) update_nocheck(0);
1700 InputFile *ipf= art->ipf;
1702 while (art->blanklen) {
1703 static const char spaces[]=
1713 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1714 int r= pwrite(ipf->fd, spaces, w, art->offset);
1716 if (errno==EINTR) continue;
1717 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1718 art->messageid, art->blanklen,
1719 (unsigned long)art->offset, ipf->path);
1721 assert(r>=0 && r<=w);
1727 assert(ipf->inprogress >= 0);
1730 if (!ipf->inprogress && ipf != main_input_file)
1731 queue_check_input_done();
1734 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1735 const char *errmsg, int errnoval,
1736 const char *data, size_t recsz, void *conn_v) {
1739 if (ev == OOP_RD_EOF) {
1740 connfail(conn, "unexpected EOF from peer");
1741 return OOP_CONTINUE;
1743 assert(ev == OOP_RD_OK);
1745 char *sani= sanitise(data,-1);
1748 unsigned long code= strtoul(data, &ep, 10);
1749 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1750 connfail(conn, "badly formatted response from peer: %s", sani);
1751 return OOP_CONTINUE;
1755 conn->waiting.count ||
1756 conn->priority.count ||
1760 if (conn->quitting) {
1761 if (code!=205 && code!=503) {
1762 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1764 notice("C%d idle connection closed by us", conn->fd);
1766 LIST_REMOVE(conns,conn);
1769 return OOP_CONTINUE;
1772 conn->since_activity= 0;
1775 #define GET_ARTICLE(musthavesent) do{ \
1776 art= article_reply_check(conn, data, code_streaming, musthavesent, sani); \
1777 if (!art) return OOP_CONTINUE; /* reply_check has failed the conn */ \
1780 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) do{ \
1781 code_streaming= (streaming); \
1782 GET_ARTICLE(musthavesent); \
1783 article_done(conn, art, RC_##how); \
1787 #define PEERBADMSG(m) do { \
1788 connfail(conn, m ": %s", sani); return OOP_CONTINUE; \
1791 int code_streaming= 0;
1795 case 400: PEERBADMSG("peer stopped accepting articles");
1796 default: PEERBADMSG("peer sent unexpected message");
1799 if (conn_busy) PEERBADMSG("peer timed us out");
1800 notice("C%d idle connection closed by peer", conn->fd);
1801 LIST_REMOVE(conns,conn);
1803 return OOP_CONTINUE;
1805 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1806 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1808 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1809 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1811 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1812 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1814 case 238: /* CHECK says send it */
1816 case 335: /* IHAVE says send it */
1818 assert(art->state == art_Unchecked);
1819 art->ipf->counts[art->state][RC_accepted]++;
1820 art->state= art_Wanted;
1821 LIST_ADDTAIL(conn->priority, art);
1824 case 431: /* CHECK or TAKETHIS says try later */
1826 case 436: /* IHAVE says try later */
1829 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1831 sysfatal("write to defer file %s",path_defer);
1832 article_done(conn, art, RC_deferred);
1838 conn_maybe_write(conn);
1839 check_assign_articles();
1840 return OOP_CONTINUE;
1844 /*========== monitoring of input files ==========*/
1846 static void feedfile_eof(InputFile *ipf) {
1847 assert(ipf != main_input_file); /* promised by tailing_try_read */
1848 inputfile_reading_stop(ipf);
1850 if (ipf == flushing_input_file) {
1851 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1852 if (main_input_file) inputfile_reading_start(main_input_file);
1853 statemc_check_flushing_done();
1854 } else if (ipf == backlog_input_file) {
1855 statemc_check_backlog_done();
1857 abort(); /* supposed to wait rather than get EOF on main input file */
1861 static InputFile *open_input_file(const char *path) {
1862 int fd= open(path, O_RDWR);
1864 if (errno==ENOENT) return 0;
1865 sysfatal("unable to open input file %s", path);
1869 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1870 memset(ipf,0,sizeof(*ipf));
1873 strcpy(ipf->path, path);
1878 static void close_input_file(InputFile *ipf) { /* does not free */
1879 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1880 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1881 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1882 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1883 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1887 /*---------- dealing with articles read in the input file ----------*/
1889 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1890 const char *data, const char *how) {
1891 warn("corrupted file: %s, offset %lu: %s: in %s",
1892 ipf->path, (unsigned long)offset, how, sanitise(data,-1));
1893 ipf->readcount_err++;
1894 if (ipf->readcount_err > max_bad_data_initial +
1895 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1896 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1897 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1898 return OOP_CONTINUE;
1901 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1902 oop_rd_event ev, const char *errmsg,
1903 int errnoval, const char *data, size_t recsz,
1905 InputFile *ipf= ipf_v;
1906 assert(ev == OOP_RD_SYSTEM);
1908 sysdie("error reading input file: %s, offset %lu",
1909 ipf->path, (unsigned long)ipf->offset);
1912 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1913 oop_rd_event ev, const char *errmsg,
1914 int errnoval, const char *data, size_t recsz,
1916 InputFile *ipf= ipf_v;
1918 char tokentextbuf[sizeof(TOKEN)*2+3];
1920 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1922 off_t old_offset= ipf->offset;
1923 ipf->offset += recsz + !!(ev == OOP_RD_OK);
1925 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1927 if (ev==OOP_RD_PARTREC)
1928 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1929 /* but process it anyway */
1931 if (ipf->skippinglong) {
1932 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1933 return OOP_CONTINUE;
1935 if (ev==OOP_RD_LONG) {
1936 ipf->skippinglong= 1;
1937 X_BAD_DATA("overly long line");
1940 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1941 if (!recsz) X_BAD_DATA("empty line");
1944 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1945 ipf->readcount_blank++;
1946 return OOP_CONTINUE;
1949 char *space= strchr(data,' ');
1950 int tokenlen= space-data;
1951 int midlen= (int)recsz-tokenlen-1;
1952 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1953 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1955 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1956 memcpy(tokentextbuf, data, tokenlen);
1957 tokentextbuf[tokenlen]= 0;
1958 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1960 ipf->readcount_ok++;
1962 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1963 memset(art,0,sizeof(art));
1964 art->state= art_Unchecked;
1965 art->midlen= midlen;
1966 art->ipf= ipf; ipf->inprogress++;
1967 art->token= TextToToken(tokentextbuf);
1968 art->offset= old_offset;
1969 art->blanklen= recsz;
1970 strcpy(art->messageid, space+1);
1971 LIST_ADDTAIL(queue, art);
1973 if (sms==sm_NORMAL && ipf==main_input_file &&
1974 ipf->offset >= target_max_feedfile_size)
1975 statemc_start_flush("feed file size");
1977 check_assign_articles();
1978 return OOP_CONTINUE;
1981 /*========== tailing input file ==========*/
1983 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1985 InputFile *ipf= user;
1986 return ipf->readable_callback(loop, &ipf->readable,
1987 ipf->readable_callback_user);
1990 static void tailing_on_cancel(struct oop_readable *rable) {
1991 InputFile *ipf= (void*)rable;
1993 if (ipf->filemon) filemon_stop(ipf);
1994 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1995 ipf->readable_callback= 0;
1998 static void tailing_queue_readable(InputFile *ipf) {
1999 /* lifetime of ipf here is OK because destruction will cause
2000 * on_cancel which will cancel this callback */
2001 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
2004 static int tailing_on_readable(struct oop_readable *rable,
2005 oop_readable_call *cb, void *user) {
2006 InputFile *ipf= (void*)rable;
2008 tailing_on_cancel(rable);
2009 ipf->readable_callback= cb;
2010 ipf->readable_callback_user= user;
2013 tailing_queue_readable(ipf);
2017 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
2019 InputFile *ipf= (void*)rable;
2021 ssize_t r= read(ipf->fd, buffer, length);
2023 if (errno==EINTR) continue;
2027 if (ipf==main_input_file) {
2030 } else if (ipf==flushing_input_file) {
2032 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2033 } else if (ipf==backlog_input_file) {
2039 tailing_queue_readable(ipf);
2044 /*---------- filemon implemented with inotify ----------*/
2046 #if defined(HAVE_SYS_INOTIFY_H) && !defined(HAVE_FILEMON)
2047 #define HAVE_FILEMON
2049 #include <sys/inotify.h>
2051 static int filemon_inotify_fd;
2052 static int filemon_inotify_wdmax;
2053 static InputFile **filemon_inotify_wd2ipf;
2055 struct Filemon_Perfile {
2059 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
2060 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
2061 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
2063 if (wd >= filemon_inotify_wdmax) {
2065 filemon_inotify_wd2ipf= xrealloc(filemon_inotify_wd2ipf,
2066 sizeof(*filemon_inotify_wd2ipf) * newmax);
2067 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
2068 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
2069 filemon_inotify_wdmax= newmax;
2072 assert(!filemon_inotify_wd2ipf[wd]);
2073 filemon_inotify_wd2ipf[wd]= ipf;
2075 debug("filemon inotify startfile %p wd=%d wdmax=%d",
2076 ipf, wd, filemon_inotify_wdmax);
2081 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
2083 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
2084 int r= inotify_rm_watch(filemon_inotify_fd, wd);
2085 if (r) sysdie("inotify_rm_watch");
2086 filemon_inotify_wd2ipf[wd]= 0;
2089 static void *filemon_inotify_readable(oop_source *lp, int fd,
2090 oop_event e, void *u) {
2091 struct inotify_event iev;
2093 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
2095 if (isewouldblock(errno)) break;
2096 sysdie("read from inotify master");
2097 } else if (r==sizeof(iev)) {
2098 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
2100 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
2102 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
2103 debug("filemon inotify readable read %p wd=%d", ipf, iev.wd);
2104 filemon_callback(ipf);
2106 return OOP_CONTINUE;
2109 static int filemon_method_init(void) {
2110 filemon_inotify_fd= inotify_init();
2111 if (filemon_inotify_fd<0) {
2112 syswarn("filemon/inotify: inotify_init failed");
2115 xsetnonblock(filemon_inotify_fd, 1);
2116 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable, 0);
2118 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2122 static void filemon_method_dump_info(FILE *f) {
2124 fprintf(f,"inotify");
2125 DUMPV("%d",,filemon_inotify_fd);
2126 DUMPV("%d",,filemon_inotify_wdmax);
2127 for (i=0; i<filemon_inotify_wdmax; i++)
2128 fprintf(f," wd2ipf[%d]=%p\n", i, filemon_inotify_wd2ipf[i],);
2131 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2133 /*---------- filemon dummy implementation ----------*/
2135 #if !defined(HAVE_FILEMON)
2137 struct Filemon_Perfile { int dummy; };
2139 static int filemon_method_init(void) {
2140 warn("filemon/dummy: no filemon method compiled in");
2143 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2144 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2145 static void filemon_method_dump_info(FILE *f) { fprintf(f,"dummy\n"); }
2147 #endif /* !HAVE_FILEMON */
2149 /*---------- filemon generic interface ----------*/
2151 static void filemon_start(InputFile *ipf) {
2152 assert(!ipf->filemon);
2155 filemon_method_startfile(ipf, ipf->filemon);
2158 static void filemon_stop(InputFile *ipf) {
2159 if (!ipf->filemon) return;
2160 filemon_method_stopfile(ipf, ipf->filemon);
2165 static void filemon_callback(InputFile *ipf) {
2166 if (ipf && ipf->readable_callback) /* so filepoll() can be naive */
2167 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2170 /*---------- interface to start and stop an input file ----------*/
2172 static const oop_rd_style feedfile_rdstyle= {
2173 OOP_RD_DELIM_STRIP, '\n',
2175 OOP_RD_SHORTREC_LONG,
2178 static void inputfile_reading_start(InputFile *ipf) {
2180 ipf->readable.on_readable= tailing_on_readable;
2181 ipf->readable.on_cancel= tailing_on_cancel;
2182 ipf->readable.try_read= tailing_try_read;
2183 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2184 ipf->readable.delete_kill= 0;
2186 ipf->readable_callback= 0;
2187 ipf->readable_callback_user= 0;
2189 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2192 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2193 feedfile_got_article,ipf, feedfile_read_err, ipf);
2194 if (r) sysdie("unable start reading feedfile %s",ipf->path);
2197 static void inputfile_reading_stop(InputFile *ipf) {
2199 oop_rd_cancel(ipf->rd);
2200 oop_rd_delete(ipf->rd);
2202 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2206 /*========== interaction with innd - state machine ==========*/
2208 /* See official state diagram at top of file. We implement
2219 |`---------------------------------------------------.
2221 |`---------------- - - - |
2222 D ENOENT | D EXISTS see OVERALL STATES diagram |
2223 | for full startup logic |
2226 | ============ try to |
2232 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
2233 ^ | hardlink F to D |
2236 | | our handle onto F is now onto D |
2239 | |<-------------------<---------------------<---------+
2241 | | spawn inndcomm flush |
2243 | ================== |
2244 | FLUSHING[-ABSENT] |
2246 | main D tail/none |
2247 | ================== |
2249 | | INNDCOMM FLUSH FAILS ^
2250 | |`----------------------->----------. |
2252 | | NO SUCH SITE V |
2253 ^ |`--------------->----. ==================== |
2254 | | \ FLUSHFAILED[-ABSENT] |
2256 | | FLUSH OK \ main D tail/none |
2257 | | open F \ ==================== |
2259 | | \ | TIME TO RETRY |
2260 | |`------->----. ,---<---'\ `----------------'
2261 | | D NONE | | D NONE `----.
2263 | ============= V V ============
2264 | SEPARATED-1 | | DROPPING-1
2265 | flsh->rd!=0 | | flsh->rd!=0
2266 | [Separated] | | [Dropping]
2267 | main F idle | | main none
2268 | old D tail | | old D tail
2269 | ============= | | ============
2271 ^ | EOF ON D | | defer | EOF ON D
2273 | =============== | | ===============
2274 | SEPARATED-2 | | DROPPING-2
2275 | flsh->rd==0 | V flsh->rd==0
2276 | [Finishing] | | [Dropping]
2277 | main F tail | `. main none
2278 | old D closed | `. old D closed
2279 | =============== V `. ===============
2281 | | ALL D PROCESSED `. | ALL D PROCESSED
2282 | V install defer as backlog `. | install defer
2283 ^ | close D `. | close D
2284 | | unlink D `. | unlink D
2287 `----------' ==============
2307 static void startup_set_input_file(InputFile *f) {
2308 assert(!main_input_file);
2310 inputfile_reading_start(f);
2313 static void statemc_lock(void) {
2315 struct stat stab, stabf;
2318 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2319 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2322 memset(&fl,0,sizeof(fl));
2324 fl.l_whence= SEEK_SET;
2325 int r= fcntl(lockfd, F_SETLK, &fl);
2327 if (errno==EACCES || isewouldblock(errno)) {
2328 if (quiet_multiple) exit(0);
2329 fatal("another duct holds the lockfile");
2331 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2334 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2336 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2338 if (!lock_noent && samefile(&stab, &stabf))
2341 xclose(lockfd, "stale lockfile ", path_lock);
2344 FILE *lockfile= fdopen(lockfd, "w");
2345 if (!lockfile) sysdie("fdopen lockfile");
2347 int r= ftruncate(lockfd, 0);
2348 if (r) sysdie("truncate lockfile to write new info");
2350 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2351 (unsigned long)self_pid,
2352 sitename, feedfile, remote_host) == EOF ||
2354 sysfatal("write info to lockfile %s", path_lock);
2356 debug("startup: locked");
2359 static void statemc_init(void) {
2360 struct stat stabdefer;
2362 search_backlog_file();
2365 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2367 debug("startup: ductdefer ENOENT");
2369 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2370 switch (stabdefer.st_nlink==1) {
2372 open_defer(); /* so that we will later close it and rename it */
2375 xunlink(path_defer, "stale defer file link"
2376 " (presumably hardlink to backlog file)");
2379 die("defer file %s has unexpected link count %d",
2380 path_defer, stabdefer.st_nlink);
2384 struct stat stab_f, stab_d;
2387 InputFile *file_d= open_input_file(path_flushing);
2388 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2390 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2392 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2393 debug("startup: F==D => Hardlinked");
2394 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2399 debug("startup: F ENOENT => Moved");
2400 if (file_d) startup_set_input_file(file_d);
2401 spawn_inndcomm_flush("feedfile missing at startup");
2402 /* => Flushing, sms:=FLUSHING */
2405 debug("startup: F!=D => Separated");
2406 startup_set_input_file(file_d);
2407 SMS(SEPARATED, 0, "found both old and current feed files");
2409 debug("startup: F exists, D ENOENT => Normal");
2410 InputFile *file_f= open_input_file(feedfile);
2411 if (!file_f) die("feed file vanished during startup");
2412 startup_set_input_file(file_f);
2413 SMS(NORMAL, spontaneous_flush_periods, "normal startup");
2418 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2419 assert(sms == sm_NORMAL);
2421 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2423 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2424 (unsigned long)target_max_feedfile_size,
2427 int r= link(feedfile, path_flushing);
2428 if (r) sysfatal("link feedfile %s to flushing file %s",
2429 feedfile, path_flushing);
2432 xunlink(feedfile, "old feedfile link");
2435 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2438 static void statemc_period_poll(void) {
2439 if (!sm_period_counter) return;
2440 sm_period_counter--;
2441 assert(sm_period_counter>=0);
2443 if (sm_period_counter) return;
2446 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2448 case sm_FLUSHFAILED:
2449 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2456 static int inputfile_is_done(InputFile *ipf) {
2458 if (ipf->inprogress) return 0; /* new article in the meantime */
2459 if (ipf->rd) return 0; /* not had EOF */
2463 static void notice_processed(InputFile *ipf, int completed,
2464 const char *what, const char *spec) {
2465 if (!ipf) return; /* allows preterminate to be lazy */
2467 #define RCI_NOTHING(x) /* nothing */
2468 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2469 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2471 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2473 char *inprog= completed
2474 ? xasprintf("%s","") /* GCC produces a stupid warning for printf("") ! */
2475 : xasprintf(" inprogress=%ld", ipf->inprogress);
2477 info("%s %s%s read=%d (+bl=%d,+err=%d)%s"
2478 " offered=%d (ch=%d,nc=%d) accepted=%d (ch=%d,nc=%d)"
2479 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2481 completed?"completed":"processed", what, spec,
2482 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err, inprog,
2483 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2484 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2485 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2486 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2487 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2495 static void statemc_check_backlog_done(void) {
2496 InputFile *ipf= backlog_input_file;
2497 if (!inputfile_is_done(ipf)) return;
2499 const char *slash= strrchr(ipf->path, '/');
2500 const char *leaf= slash ? slash+1 : ipf->path;
2501 const char *under= strchr(slash, '_');
2502 const char *rest= under ? under+1 : leaf;
2503 if (!strncmp(rest,"backlog",7)) rest += 7;
2504 notice_processed(ipf,1,"backlog ",rest);
2506 close_input_file(ipf);
2507 if (unlink(ipf->path)) {
2508 if (errno != ENOENT)
2509 sysdie("could not unlink processed backlog file %s", ipf->path);
2510 warn("backlog file %s vanished while we were reading it"
2511 " so we couldn't remove it (but it's done now, anyway)",
2515 backlog_input_file= 0;
2516 search_backlog_file();
2520 static void statemc_check_flushing_done(void) {
2521 InputFile *ipf= flushing_input_file;
2522 if (!inputfile_is_done(ipf)) return;
2524 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2526 notice_processed(ipf,1,"feedfile","");
2530 xunlink(path_flushing, "old flushing file");
2532 close_input_file(flushing_input_file);
2533 free(flushing_input_file);
2534 flushing_input_file= 0;
2536 if (sms==sm_SEPARATED) {
2537 notice("flush complete");
2538 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2539 } else if (sms==sm_DROPPING) {
2540 SMS(DROPPED, 0, "old flush complete");
2541 search_backlog_file();
2542 notice("feed dropped, but will continue until backlog is finished");
2546 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2548 assert(!inputfile_is_done(main_input_file));
2549 statemc_check_flushing_done();
2550 statemc_check_backlog_done();
2551 return OOP_CONTINUE;
2554 static void queue_check_input_done(void) {
2555 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2558 static void statemc_setstate(StateMachineState newsms, int periods,
2559 const char *forlog, const char *why) {
2561 sm_period_counter= periods;
2563 const char *xtra= "";
2566 case sm_FLUSHFAILED:
2567 if (!main_input_file) xtra= "-ABSENT";
2571 xtra= flushing_input_file->rd ? "-1" : "-2";
2577 info("state %s%s[%d] %s",forlog,xtra,periods,why);
2579 info("state %s%s %s",forlog,xtra,why);
2583 /*---------- defer and backlog files ----------*/
2585 static void open_defer(void) {
2590 defer= fopen(path_defer, "a+");
2591 if (!defer) sysfatal("could not open defer file %s", path_defer);
2593 /* truncate away any half-written records */
2595 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2597 if (stab.st_size > LONG_MAX)
2598 die("defer file %s size is far too large", path_defer);
2603 long orgsize= stab.st_size;
2604 long truncto= stab.st_size;
2606 if (!truncto) break; /* was only (if anything) one half-truncated record */
2607 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2608 sysdie("seek in defer file %s while truncating partial", path_defer);
2613 sysdie("failed read from defer file %s", path_defer);
2615 die("defer file %s shrank while we were checking it!", path_defer);
2621 if (stab.st_size != truncto) {
2622 warn("truncating half-record at end of defer file %s -"
2623 " shrinking by %ld bytes from %ld to %ld",
2624 path_defer, orgsize - truncto, orgsize, truncto);
2627 sysfatal("could not flush defer file %s", path_defer);
2628 if (ftruncate(fileno(defer), truncto))
2629 sysdie("could not truncate defer file %s", path_defer);
2632 info("continuing existing defer file %s (%ld bytes)",
2633 path_defer, orgsize);
2635 if (fseek(defer, truncto, SEEK_SET))
2636 sysdie("could not seek to new end of defer file %s", path_defer);
2639 static void close_defer(void) {
2644 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2646 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2649 time_t now= xtime();
2651 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2653 (unsigned long)stab.st_ino);
2654 if (link(path_defer, backlog))
2655 sysfatal("could not install defer file %s as backlog file %s",
2656 path_defer, backlog);
2657 if (unlink(path_defer))
2658 sysdie("could not unlink old defer link %s to backlog file %s",
2659 path_defer, backlog);
2663 if (until_backlog_nextscan < 0 ||
2664 until_backlog_nextscan > backlog_retry_minperiods + 1)
2665 until_backlog_nextscan= backlog_retry_minperiods + 1;
2668 static void poll_backlog_file(void) {
2669 if (until_backlog_nextscan < 0) return;
2670 if (until_backlog_nextscan-- > 0) return;
2671 search_backlog_file();
2674 static void search_backlog_file(void) {
2675 /* returns non-0 iff there are any backlog files */
2680 const char *oldest_path=0;
2681 time_t oldest_mtime=0, now;
2683 if (backlog_input_file) return;
2687 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2691 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2693 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2695 for (i=0; i<gl.gl_pathc; i++) {
2696 const char *path= gl.gl_pathv[i];
2698 if (strchr(path,'#') || strchr(path,'~')) {
2699 debug("backlog file search skipping %s", path);
2702 r= stat(path, &stab);
2704 syswarn("failed to stat backlog file %s", path);
2707 if (!S_ISREG(stab.st_mode)) {
2708 warn("backlog file %s is not a plain file (or link to one)", path);
2711 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2713 oldest_mtime= stab.st_mtime;
2716 case GLOB_NOMATCH: /* fall through */
2719 sysdie("glob expansion of backlog pattern %s gave unexpected"
2720 " nonzero (error?) return value %d", globpat_backlog, r);
2724 debug("backlog scan: none");
2726 if (sms==sm_DROPPED) {
2728 notice("feed dropped and our work is complete");
2730 int r= unlink(path_control);
2731 if (r && errno!=ENOENT)
2732 syswarn("failed to remove control symlink for old feed");
2734 xunlink(path_lock, "lockfile for old feed");
2737 until_backlog_nextscan= backlog_spontrescan_periods;
2742 double age= difftime(now, oldest_mtime);
2743 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2745 if (age_deficiency <= 0) {
2746 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2747 age, age_deficiency, oldest_path);
2749 backlog_input_file= open_input_file(oldest_path);
2750 if (!backlog_input_file) {
2751 warn("backlog file %s vanished as we opened it", oldest_path);
2755 inputfile_reading_start(backlog_input_file);
2756 until_backlog_nextscan= -1;
2760 until_backlog_nextscan= age_deficiency / period_seconds;
2762 if (backlog_spontrescan_periods >= 0 &&
2763 until_backlog_nextscan > backlog_spontrescan_periods)
2764 until_backlog_nextscan= backlog_spontrescan_periods;
2766 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2767 age, age_deficiency, until_backlog_nextscan, oldest_path);
2774 /*---------- shutdown and signal handling ----------*/
2776 static void preterminate(void) {
2777 if (in_child) return;
2778 notice_processed(main_input_file,0,"feedfile","");
2779 notice_processed(flushing_input_file,0,"flushing file","");
2780 if (backlog_input_file)
2781 notice_processed(backlog_input_file,0, "backlog file ",
2782 backlog_input_file->path);
2785 static int signal_self_pipe[2];
2786 static sig_atomic_t terminate_sig_flag;
2788 static void raise_default(int signo) {
2789 struct sigaction sa;
2790 memset(&sa,0,sizeof(sa));
2791 sa.sa_handler= SIG_DFL;
2792 xsigaction(signo,&sa);
2796 static void *sigarrived_event(oop_source *lp, int fd, oop_event e, void *u) {
2797 assert(fd=signal_self_pipe[0]);
2799 int r= read(signal_self_pipe[0], buf, sizeof(buf));
2800 if (r<0 && !isewouldblock(errno)) sysdie("failed to read signal self pipe");
2801 if (r==0) die("eof on signal self pipe");
2802 if (terminate_sig_flag) {
2804 notice("terminating (%s)", strsignal(terminate_sig_flag));
2805 raise_default(terminate_sig_flag);
2808 return OOP_CONTINUE;
2811 static void sigarrived_handler(int signum) {
2814 case SIGINT: case SIGTERM:
2815 if (!terminate_sig_flag) terminate_sig_flag= signum;
2820 write(signal_self_pipe[1],&x,1);
2823 static void init_signals(void) {
2824 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2825 sysdie("could not ignore SIGPIPE");
2827 if (pipe(signal_self_pipe)) sysfatal("create self-pipe for signals");
2829 xsetnonblock(signal_self_pipe[0],1);
2830 xsetnonblock(signal_self_pipe[1],1);
2832 struct sigaction sa;
2833 memset(&sa,0,sizeof(sa));
2834 sa.sa_handler= sigarrived_handler;
2835 sa.sa_flags= SA_RESTART;
2836 xsigaction(SIGTERM,&sa);
2837 xsigaction(SIGINT,&sa);
2839 on_fd_read_except(signal_self_pipe[0], sigarrived_event);
2842 /*========== flushing the feed ==========*/
2844 static pid_t inndcomm_child;
2845 static int inndcomm_sentinel_fd;
2847 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2848 assert(inndcomm_child);
2849 assert(fd == inndcomm_sentinel_fd);
2850 int status= xwaitpid(&inndcomm_child, "inndcomm");
2853 cancel_fd_read_except(fd);
2854 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2855 inndcomm_sentinel_fd= 0;
2857 assert(!flushing_input_file);
2859 if (WIFEXITED(status)) {
2860 switch (WEXITSTATUS(status)) {
2862 case INNDCOMMCHILD_ESTATUS_FAIL:
2865 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2866 notice("feed has been dropped by innd, finishing up");
2867 flushing_input_file= main_input_file;
2868 tailing_queue_readable(flushing_input_file);
2869 /* we probably previously returned EAGAIN from our fake read method
2870 * when in fact we were at EOF, so signal another readable event
2871 * so we actually see the EOF */
2875 if (flushing_input_file) {
2876 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2879 SMS(DROPPED, 0, "feed dropped by innd");
2880 search_backlog_file();
2882 return OOP_CONTINUE;
2886 flushing_input_file= main_input_file;
2887 tailing_queue_readable(flushing_input_file);
2889 main_input_file= open_input_file(feedfile);
2890 if (!main_input_file)
2891 die("flush succeeded but feedfile %s does not exist!", feedfile);
2893 if (flushing_input_file) {
2894 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2897 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2899 return OOP_CONTINUE;
2902 goto unexpected_exitstatus;
2905 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2906 warn("flush timed out trying to talk to innd");
2909 unexpected_exitstatus:
2910 report_child_status("inndcomm child", status);
2914 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2915 return OOP_CONTINUE;
2918 static void inndcommfail(const char *what) {
2919 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2920 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2923 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2926 notice("flushing %s",why);
2928 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2929 assert(!inndcomm_child);
2930 assert(!inndcomm_sentinel_fd);
2932 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2934 inndcomm_child= xfork("inndcomm child");
2936 if (!inndcomm_child) {
2937 const char *flushargv[2]= { sitename, 0 };
2941 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2942 /* parent spots the autoclose of pipefds[1] when we die or exit */
2944 if (simulate_flush>=0) {
2945 warn("SIMULATING flush child status %d", simulate_flush);
2946 if (simulate_flush>128) raise(simulate_flush-128);
2947 else exit(simulate_flush);
2950 alarm(inndcomm_flush_timeout);
2951 r= ICCopen(); if (r) inndcommfail("connect");
2952 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2953 if (!r) exit(0); /* yay! */
2955 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2956 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2957 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2962 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2963 inndcomm_sentinel_fd= pipefds[0];
2964 assert(inndcomm_sentinel_fd);
2965 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2967 SMS(FLUSHING, 0, why);
2970 /*========== main program ==========*/
2972 static void postfork_inputfile(InputFile *ipf) {
2974 xclose(ipf->fd, "(in child) input file ", ipf->path);
2977 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2978 /* we have no stdio streams that are buffered long-term */
2980 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2983 static void postfork(void) {
2986 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2987 sysdie("(in child) failed to reset SIGPIPE");
2989 postfork_inputfile(main_input_file);
2990 postfork_inputfile(flushing_input_file);
2994 conn_closefd(conn,"(in child) ");
2996 postfork_stdio(defer, "defer file ", path_defer);
2999 typedef struct Every Every;
3001 struct timeval interval;
3006 static void every_schedule(Every *e, struct timeval base);
3008 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
3011 if (!e->fixed_rate) xgettimeofday(&base);
3012 every_schedule(e, base);
3013 return OOP_CONTINUE;
3016 static void every_schedule(Every *e, struct timeval base) {
3017 struct timeval when;
3018 timeradd(&base, &e->interval, &when);
3019 loop->on_time(loop, when, every_happens, e);
3022 static void every(int interval, int fixed_rate, void (*f)(void)) {
3023 NEW_DECL(Every *,e);
3024 e->interval.tv_sec= interval;
3025 e->interval.tv_usec= 0;
3026 e->fixed_rate= fixed_rate;
3029 xgettimeofday(&now);
3030 every_schedule(e, now);
3033 static void filepoll(void) {
3034 filemon_callback(main_input_file);
3035 filemon_callback(flushing_input_file);
3038 static char *debug_report_ipf(InputFile *ipf) {
3039 if (!ipf) return xasprintf("none");
3041 const char *slash= strrchr(ipf->path,'/');
3042 const char *path= slash ? slash+1 : ipf->path;
3044 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s%s",
3046 ipf->inprogress, (long)ipf->offset,
3048 ipf->rd ? "" : ",!rd",
3049 ipf->skippinglong ? "*skiplong" : "");
3052 static void period(void) {
3053 char *dipf_main= debug_report_ipf(main_input_file);
3054 char *dipf_flushing= debug_report_ipf(flushing_input_file);
3055 char *dipf_backlog= debug_report_ipf(backlog_input_file);
3058 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
3059 " input_files main:%s flushing:%s backlog:%s"
3060 " children connecting=%ld inndcomm=%ld"
3062 sms_names[sms], sm_period_counter,
3063 conns.count, queue.count, until_connect,
3064 dipf_main, dipf_flushing, dipf_backlog,
3065 (long)connecting_child, (long)inndcomm_child
3069 free(dipf_flushing);
3072 if (until_connect) until_connect--;
3074 poll_backlog_file();
3075 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
3076 statemc_period_poll();
3077 check_assign_articles();
3082 /*========== dumping state ==========*/
3084 static void dump_article_list(FILE *f, const ControlCommand *c,
3085 const ArticleList *al) {
3086 fprintf(f, " count=%d\n", al->count);
3087 if (!c->xval) return;
3089 int i; Article *art;
3090 for (i=0, art=LIST_HEAD(*al); art; i++, art=LIST_NEXT(art)) {
3091 fprintf(f," #%05d %-11s", i, artstate_names[art->state]);
3092 DUMPV("%p", art->,ipf);
3093 DUMPV("%d", art->,missing);
3094 DUMPV("%lu", (unsigned long)art->,offset);
3095 DUMPV("%d", art->,blanklen);
3096 DUMPV("%d", art->,midlen);
3097 fprintf(f, " %s %s\n", TokenToText(art->token), art->messageid);
3101 static void dump_input_file(FILE *f, InputFile *ipf, const char *wh) {
3102 char *dipf= debug_report_ipf(ipf);
3103 fprintf(f,"input %s %s", wh, dipf);
3107 DUMPV("%d", ipf->,readcount_ok);
3108 DUMPV("%d", ipf->,readcount_blank);
3109 DUMPV("%d", ipf->,readcount_err);
3113 ArtState state; const char *const *statename;
3114 for (state=0, statename=artstate_names; *statename; state++,statename++) {
3115 #define RC_DUMP_FMT(x) " " #x "=%d"
3116 #define RC_DUMP_VAL(x) ,ipf->counts[state][RC_##x]
3117 fprintf(f,"input %s counts %-11s"
3118 RESULT_COUNTS(RC_DUMP_FMT,RC_DUMP_FMT) "\n",
3120 RESULT_COUNTS(RC_DUMP_VAL,RC_DUMP_VAL));
3127 fprintf(cc->out, "dumping state to %s\n", path_dump);
3128 FILE *f= fopen(path_dump, "w");
3129 if (!f) { fprintf(cc->out, "failed: open: %s\n", strerror(errno)); return; }
3131 fprintf(f,"general");
3132 DUMPV("%s", sms_names,[sms]);
3133 DUMPV("%d", ,sm_period_counter);
3134 DUMPV("%ld", (long),self_pid);
3135 DUMPV("%p", , defer);
3136 DUMPV("%d", , until_connect);
3137 DUMPV("%d", , until_backlog_nextscan);
3138 DUMPV("%d", , simulate_flush);
3139 fprintf(f,"\nnocheck");
3140 DUMPV("%#.10f", , accept_proportion);
3141 DUMPV("%d", , nocheck);
3142 DUMPV("%d", , nocheck_reported);
3145 fprintf(f,"special");
3146 DUMPV("%ld", (long),connecting_child);
3147 DUMPV("%d", , connecting_fdpass_sock);
3148 DUMPV("%d", , control_master);
3151 fprintf(f,"filemon ");
3152 filemon_method_dump_info(f);
3154 dump_input_file(f, main_input_file, "main" );
3155 dump_input_file(f, flushing_input_file, "flushing");
3156 dump_input_file(f, backlog_input_file, "backlog" );
3158 fprintf(f,"conns count=%d\n", conns.count);
3163 fprintf(f,"C%d",conn->fd);
3164 DUMPV("%p",conn->,rd); DUMPV("%d",conn->,max_queue);
3165 DUMPV("%d",conn->,stream); DUMPV("%d",conn->,quitting);
3166 DUMPV("%d",conn->,since_activity);
3169 fprintf(f,"C%d waiting", conn->fd); dump_article_list(f,c,&conn->waiting);
3170 fprintf(f,"C%d priority",conn->fd); dump_article_list(f,c,&conn->priority);
3171 fprintf(f,"C%d sent", conn->fd); dump_article_list(f,c,&conn->sent);
3173 fprintf(f,"C%d xmit xmitu=%d\n", conn->fd, conn->xmitu);
3174 for (i=0; i<conn->xmitu; i++) {
3175 const struct iovec *iv= &conn->xmit[i];
3176 const XmitDetails *xd= &conn->xmitd[i];
3181 diff= xd->info.malloc_tofree - (char*)iv->iov_base;
3182 dinfo= xasprintf("M%5ld", diff);
3185 dinfo= xasprintf("Const");
3188 dinfo= xasprintf("A%p", xd->info.sm_art);
3193 fprintf(f," #%03d %-11s l=%d %s\n", i, dinfo, iv->iov_len,
3194 sanitise(iv->iov_base, iv->iov_len));
3199 fprintf(f,"queue"); dump_article_list(f,c,&queue);
3202 DUMPV("%s", , path_lock);
3203 DUMPV("%s", , path_flushing);
3204 DUMPV("%s", , path_defer);
3205 DUMPV("%s", , path_control);
3206 DUMPV("%s", , path_dump);
3207 DUMPV("%s", , globpat_backlog);
3210 if (!!ferror(f) + !!fclose(f)) {
3211 fprintf(cc->out, "failed: write: %s\n", strerror(errno));
3216 /*========== option parsing ==========*/
3218 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
3219 static void vbadusage(const char *fmt, va_list al) {
3220 char *m= xvasprintf(fmt,al);
3221 fprintf(stderr, "bad usage: %s\n"
3222 "say --help for help, or read the manpage\n",
3225 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
3229 /*---------- generic option parser ----------*/
3231 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
3232 static void badusage(const char *fmt, ...) {
3239 of_seconds= 001000u,
3240 of_boolean= 002000u,
3243 typedef struct Option Option;
3244 typedef void OptionParser(const Option*, const char *val);
3248 const char *lng, *formarg;
3254 static void parse_options(const Option *options, char ***argvp) {
3255 /* on return *argvp is first non-option arg; argc is not updated */
3258 const char *arg= *++(*argvp);
3260 if (*arg != '-') break;
3261 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
3263 while ((a= *++arg)) {
3267 char *equals= strchr(arg,'=');
3268 int len= equals ? (equals - arg) : strlen(arg);
3269 for (o=options; o->shrt || o->lng; o++)
3270 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
3272 badusage("unknown long option --%s",arg);
3275 if (equals) badusage("option --%s does not take a value",o->lng);
3277 } else if (equals) {
3281 if (!arg) badusage("option --%s needs a value for %s",
3282 o->lng, o->formarg);
3285 break; /* eaten the whole argument now */
3287 for (o=options; o->shrt || o->lng; o++)
3290 badusage("unknown short option -%c",a);
3297 if (!arg) badusage("option -%c needs a value for %s",
3298 o->shrt, o->formarg);
3301 break; /* eaten the whole argument now */
3307 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
3309 static void print_options(const Option *options, FILE *f) {
3311 for (o=options; o->shrt || o->lng; o++) {
3312 char shrt[2] = { o->shrt, 0 };
3313 char *optspec= xasprintf("%s%s%s%s%s",
3314 o->shrt ? "-" : "", shrt,
3315 o->shrt && o->lng ? "|" : "",
3316 DELIMPERHAPS("--", o->lng));
3317 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
3322 /*---------- specific option types ----------*/
3324 static void op_integer(const Option *o, const char *val) {
3327 unsigned long ul= strtoul(val,&ep,10);
3328 if (*ep || ep==val || errno || ul>INT_MAX)
3329 badusage("bad integer value for %s",o->lng);
3330 int *store= o->store;
3334 static void op_double(const Option *o, const char *val) {
3335 int *store= o->store;
3338 *store= strtod(val, &ep);
3339 if (*ep || ep==val || errno)
3340 badusage("bad floating point value for %s",o->lng);
3343 static void op_string(const Option *o, const char *val) {
3344 const char **store= o->store;
3348 static void op_seconds(const Option *o, const char *val) {
3349 int *store= o->store;
3353 double v= strtod(val,&ep);
3354 if (ep==val) badusage("bad time/duration value for %s",o->lng);
3356 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
3357 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
3358 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
3359 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
3360 else if (!strcmp(ep,"das")) unit= 10;
3361 else if (!strcmp(ep,"hs")) unit= 100;
3362 else if (!strcmp(ep,"ks")) unit= 1000;
3363 else if (!strcmp(ep,"Ms")) unit= 1000000;
3364 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
3368 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
3372 static void op_setint(const Option *o, const char *val) {
3373 int *store= o->store;
3377 /*---------- specific options ----------*/
3379 static void help(const Option *o, const char *val);
3381 static const Option innduct_options[]= {
3382 {'f',"feedfile", "F", &feedfile, op_string },
3383 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
3384 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
3385 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
3386 {0,"no-filemon", 0, &try_filemon, op_setint, 0 },
3387 {'C',"inndconf", "F", &inndconffile, op_string },
3388 {'P',"port", "PORT", &port, op_integer },
3389 {0,"ctrl-sock-dir", 0, &realsockdir, op_string },
3390 {0,"help", 0, 0, help },
3392 {0,"max-connections", "N", &max_connections, op_integer },
3393 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
3394 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
3395 {0,"period-interval", "TIME", &period_seconds, op_seconds },
3397 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
3398 {0,"stuck-flush-timeout", "TIME", &inndcomm_flush_timeout, op_seconds },
3399 {0,"feedfile-poll", "TIME", &filepoll_seconds, op_seconds },
3401 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
3402 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
3404 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
3405 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
3406 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3407 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3408 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
3409 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
3411 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
3412 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
3417 static void printusage(FILE *f) {
3418 fputs("usage: innduct [options] site [fqdn]\n"
3419 "available options are:\n", f);
3420 print_options(innduct_options, f);
3423 static void help(const Option *o, const char *val) {
3425 if (ferror(stdout) || fflush(stdout)) {
3426 perror("innduct: writing help");
3432 static void convert_to_periods_rndup(int *store) {
3433 *store += period_seconds-1;
3434 *store /= period_seconds;
3437 int main(int argc, char **argv) {
3443 parse_options(innduct_options, &argv);
3448 if (!sitename) badusage("need site name argument");
3449 remote_host= *argv++;
3450 if (*argv) badusage("too many non-option arguments");
3454 int r= innconf_read(inndconffile);
3455 if (!r) badusage("could not read inn.conf (more info on stderr)");
3457 if (!remote_host) remote_host= sitename;
3459 if (nocheck_thresh < 0 || nocheck_thresh > 100)
3460 badusage("nocheck threshold percentage must be between 0..100");
3461 nocheck_thresh *= 0.01;
3463 if (nocheck_decay < 0.1)
3464 badusage("nocheck decay articles must be at least 0.1");
3465 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3467 convert_to_periods_rndup(&reconnect_delay_periods);
3468 convert_to_periods_rndup(&flushfail_retry_periods);
3469 convert_to_periods_rndup(&backlog_retry_minperiods);
3470 convert_to_periods_rndup(&backlog_spontrescan_periods);
3471 convert_to_periods_rndup(&spontaneous_flush_periods);
3472 convert_to_periods_rndup(&need_activity_periods);
3474 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3475 badusage("bad input data ratio must be between 0..100");
3476 max_bad_data_ratio *= 0.01;
3479 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3480 } else if (!feedfile[0]) {
3481 badusage("feed filename must be nonempty");
3482 } else if (feedfile[strlen(feedfile)-1]=='/') {
3483 feedfile= xasprintf("%s%s",feedfile,sitename);
3486 const char *feedfile_forbidden= "?*[~#";
3488 while ((c= *feedfile_forbidden++))
3489 if (strchr(feedfile, c))
3490 badusage("feed filename may not contain metacharacter %c",c);
3494 path_lock= xasprintf("%s_lock", feedfile);
3495 path_flushing= xasprintf("%s_flushing", feedfile);
3496 path_defer= xasprintf("%s_defer", feedfile);
3497 path_control= xasprintf("%s_control", feedfile);
3498 path_dump= xasprintf("%s_dump", feedfile);
3499 globpat_backlog= xasprintf("%s_backlog*", feedfile);
3501 oop_source_sys *sysloop= oop_sys_new();
3502 if (!sysloop) sysdie("could not create liboop event loop");
3503 loop= (oop_source*)sysloop;
3508 if (become_daemon) {
3510 for (i=3; i<255; i++)
3511 /* do this now before we open syslog, etc. */
3513 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3515 int null= open("/dev/null",O_RDWR);
3516 if (null<0) sysfatal("failed to open /dev/null");
3520 xclose(null, "/dev/null original fd",0);
3522 pid_t child1= xfork("daemonise first fork");
3523 if (child1) _exit(0);
3525 pid_t sid= setsid();
3526 if (sid != child1) sysfatal("setsid failed");
3528 pid_t child2= xfork("daemonise second fork");
3529 if (child2) _exit(0);
3533 if (self_pid==-1) sysdie("getpid");
3548 notice("filemon: suppressed by command line option, polling");
3550 filemon_ok= filemon_method_init();
3552 warn("filemon: no file monitoring available, polling");
3555 every(filepoll_seconds,0,filepoll);
3557 every(period_seconds,1,period);
3563 void *run= oop_sys_run(sysloop);
3564 assert(run == OOP_ERROR);
3565 sysdie("event loop failed");