3 * - actually do something with readable on control master
4 * - option for realsockdir
5 * - option for filepoll
6 * - option for no inotify
7 * - manpage: document control master stuff
8 * - manpage: innconf is used for communicating with innd
10 * build-lfs/backends/innduct --no-daemon -f `pwd`/fee sit dom
14 * Newsfeeds file entries should look like this:
15 * host.name.of.site[/exclude,exclude,...]\
16 * :pattern,pattern...[/distribution,distribution...]\
20 * sitename[/exclude,exclude,...]\
21 * :pattern,pattern...[/distribution,distribution...]\
27 * or might be blanked out
28 * <spc><spc><spc><spc>....
30 * F site.name main feed file
31 * opened/created, then written, by innd
34 * tokens blanked out by duct when processed
35 * site.name_lock lock preventing multiple ducts
36 * to hold lock must open,F_SETLK[W]
37 * and then stat to check that locked file
38 * still has name site.name_lock
39 * holder of this lock is "duct"
40 * (only) lockholder may remove the lockfile
41 * D site.name_flushing temporary feed file during flush (or crash)
42 * hardlink created by duct
44 * site.name_defer 431'd articles, still being written,
45 * created, written, used by duct
47 * site.name_backlog.<date>.<inum>
48 * 431'd articles, ready for innxmit or duct
49 * created (link/mv) by duct
50 * site.name_backlog<anything-else> (where <anything-else> does not
51 * contain '#' or '~') eg
52 * site.name_backlog.manual
53 * anything the sysadmin likes (eg, feed files
54 * from old feeds to be merged into this one)
55 * created (link/mv) by admin
56 * may be symlinks (in which case links
57 * may be written through, but only links
60 * It is safe to remove backlog files manually,
61 * if it's desired to throw away the backlog.
63 * Backlog files are also processed by innduct. We find the oldest
64 * backlog file which is at least a certain amount old, and feed it
65 * back into our processing. When every article in it has been read
66 * and processed, we unlink it and look for another backlog file.
68 * If we don't have a backlog file that we're reading, we close the
69 * defer file that we're writing and make it into a backlog file at
70 * the first convenient opportunity.
81 | | <----------------<---------------------------------'|
87 | F: innd writing, duct reading |
90 | | duct decides time to flush |
91 | | duct makes hardlink |
93 | V <------------------------'|
95 | F == D: innd writing, duct reading both exist |
98 | | <-----------<-------------<--'|
102 | V <---------------------. |
105 | D: innd writing, duct reading; or ENOENT | |
107 | | duct requests flush of feed | |
108 | | (others can too, harmlessly) | |
112 | D: innd flushing, duct; or ENOENT | |
114 | | inndcomm flush fails | |
115 | |`-------------------------->------------------' |
117 | | inndcomm reports no such site |
118 | |`---------------------------------------------------- | -.
120 | | innd finishes writing D, creates F | |
121 | | inndcomm reports flush successful | |
124 | Separated <----------------' |
125 | F: innd writing F!=D /
126 | D: duct reading; or ENOENT both exist /
128 | | duct gets to the end of D /
129 | | duct opens F too /
132 | F: innd writing, duct reading |
133 | D: duct finishing V
135 | | duct finishes processing D F: ENOENT
136 | V duct unlinks D D: duct reading
138 `--<--' | duct finishes
148 "duct reading" means innduct is reading the file but also
149 overwriting processed tokens.
153 * rune for printing diagrams:
155 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
160 /*============================== PROGRAM ==============================*/
162 #define _GNU_SOURCE 1
168 #include "inndcomm.h"
170 #include "inn/list.h"
171 #include "inn/innconf.h"
174 #include <sys/types.h>
175 #include <sys/wait.h>
176 #include <sys/stat.h>
177 #include <sys/socket.h>
196 #include <oop-read.h>
198 /*----- general definitions, probably best not changed -----*/
200 #define CONNCHILD_ESTATUS_STREAM 24
201 #define CONNCHILD_ESTATUS_NOSTREAM 25
203 #define INNDCOMMCHILD_ESTATUS_FAIL 26
204 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
206 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
207 #define MAX_CONTROL_COMMAND 1000
209 #define VA va_list al; va_start(al,fmt)
210 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
211 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
213 /*----- doubly linked lists -----*/
215 #define ISNODE(T) struct node list_node
218 union { struct list li; T *for_type; } u; \
222 #define NODE(n) (assert((void*)&(n)->list_node == (n)), &(n)->list_node)
224 #define LIST_CHECKCANHAVENODE(l,n) \
225 ((void)((n) == ((l).u.for_type))) /* just for the type check */
227 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
228 ( LIST_CHECKCANHAVENODE(l,n), \
229 list_addsomehow(&(l).u.li, NODE((n))), \
233 #define LIST_REMSOMEHOW(l,list_remsomehow) \
234 ( (typeof((l).u.for_type)) \
237 list_remsomehow(&(l).u.li) ) \
243 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
244 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
245 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
246 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
248 #define LIST_INIT(l) ((l).count=0, list_new(&(l).u.li))
249 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
250 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
251 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
253 #define LIST_REMOVE(l,n) \
254 ( LIST_CHECKCANHAVENODE(l,n), \
255 list_remove(NODE((n))), \
259 #define LIST_INSERT(l,n,pred) \
260 ( LIST_CHECKCANHAVENODE(l,n), \
261 LIST_CHECKCANHAVENODE(l,pred), \
262 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
266 /*----- type predeclarations -----*/
268 typedef struct Conn Conn;
269 typedef struct Article Article;
270 typedef struct InputFile InputFile;
271 typedef struct XmitDetails XmitDetails;
272 typedef struct Filemon_Perfile Filemon_Perfile;
273 typedef enum StateMachineState StateMachineState;
278 /*----- function predeclarations -----*/
280 static void conn_maybe_write(Conn *conn);
281 static void conn_make_some_xmits(Conn *conn);
282 static void *conn_write_some_xmits(Conn *conn);
284 static void xmit_free(XmitDetails *d);
286 #define SMS(newstate, periods, why) \
287 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
288 static void statemc_setstate(StateMachineState newsms, int periods,
289 const char *forlog, const char *why);
291 static void statemc_start_flush(const char *why); /* Normal => Flushing */
292 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
294 static void check_assign_articles(void);
295 static void queue_check_input_done(void);
297 static void statemc_check_flushing_done(void);
298 static void statemc_check_backlog_done(void);
300 static void postfork(void);
301 static void period(void);
303 static void open_defer(void);
304 static void close_defer(void);
305 static void search_backlog_file(void);
307 static void inputfile_reading_start(InputFile *ipf);
308 static void inputfile_reading_stop(InputFile *ipf);
310 static void filemon_start(InputFile *ipf);
311 static void filemon_stop(InputFile *ipf);
312 static void filemon_callback(InputFile *ipf);
314 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
315 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
317 static const oop_rd_style peer_rd_style;
318 static oop_rd_call peer_rd_err, peer_rd_ok;
320 /*----- configuration options -----*/
321 /* when changing defaults, remember to update the manpage */
323 static const char *sitename, *remote_host;
324 static const char *feedfile, *realsockdir="/tmp/innduct.control";
325 static int quiet_multiple=0;
326 static int become_daemon=1;
327 static int try_stream=1;
329 static const char *inndconffile;
331 static int max_connections=10;
332 static int max_queue_per_conn=200;
333 static int target_max_feedfile_size=100000;
334 static int period_seconds=60;
336 static int connection_setup_timeout=200;
337 static int inndcomm_flush_timeout=100;
339 static double nocheck_thresh= 95.0; /* converted from percentage by main */
340 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
342 /* all these are initialised to seconds, and converted to periods in main */
343 static int reconnect_delay_periods=1000;
344 static int flushfail_retry_periods=1000;
345 static int backlog_retry_minperiods=50;
346 static int backlog_spontrescan_periods=300;
347 static int spontaneous_flush_periods=100000;
348 static int need_activity_periods=1000;
350 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
351 static int max_bad_data_initial= 30;
352 /* in one corrupt 4096-byte block the number of newlines has
353 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
356 /*----- statistics -----*/
358 typedef enum { /* in queue in conn->sent */
359 art_Unchecked, /* not checked, not sent checking */
360 art_Wanted, /* checked, wanted sent body as requested */
361 art_Unsolicited, /* - sent body without check */
365 #define RESULT_COUNTS(RCS,RCN) \
373 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
374 #define RCI_TRIPLE_VALS_BASE(counts,x) \
375 counts[art_Unchecked] x \
376 + counts[art_Wanted] x \
377 + counts[art_Unsolicited] x, \
378 counts[art_Unchecked] x \
379 , counts[art_Wanted] x \
380 , counts[art_Unsolicited] x
383 #define RC_INDEX(x) RC_##x,
384 RESULT_COUNTS(RC_INDEX, RC_INDEX)
389 /*----- transmission buffers -----*/
394 xk_Malloc, xk_Const, xk_Artdata
406 /*----- core operational data structure types -----*/
409 /* This is also an instance of struct oop_readable */
410 struct oop_readable readable; /* first */
411 oop_readable_call *readable_callback;
412 void *readable_callback_user;
415 Filemon_Perfile *filemon;
417 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
418 long inprogress; /* no. of articles read but not processed */
422 int counts[art_MaxState][RCI_max];
423 int readcount_ok, readcount_blank, readcount_err;
438 #define SMS_LIST(X) \
446 enum StateMachineState {
447 #define SMS_DEF_ENUM(s) sm_##s,
448 SMS_LIST(SMS_DEF_ENUM)
451 static const char *sms_names[]= {
452 #define SMS_DEF_NAME(s) #s ,
453 SMS_LIST(SMS_DEF_NAME)
459 int fd; /* may be 0, meaning closed (during construction/destruction) */
460 oop_read *rd; /* likewise */
461 int max_queue, stream, quitting;
462 int since_activity; /* periods */
463 ArticleList waiting; /* not yet told peer */
464 ArticleList priority; /* peer says send it now */
465 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
466 struct iovec xmit[CONNIOVS];
467 XmitDetails xmitd[CONNIOVS];
472 /*----- general operational variables -----*/
474 /* main initialises */
475 static oop_source *loop;
476 static ConnList conns;
477 static ArticleList queue;
478 static char *path_lock, *path_flushing, *path_defer, *path_control;
479 static char *globpat_backlog;
480 static pid_t self_pid;
482 /* statemc_init initialises */
483 static StateMachineState sms;
485 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
486 static int sm_period_counter;
488 /* initialisation to 0 is good */
489 static int until_connect, until_backlog_nextscan;
490 static double accept_proportion;
491 static int nocheck, nocheck_reported;
493 /* for simulation, debugging, etc. */
494 int simulate_flush= -1;
496 /*========== logging ==========*/
498 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
499 static void logcore(int sysloglevel, const char *fmt, ...) {
502 vsyslog(sysloglevel,fmt,al);
504 if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
505 vfprintf(stderr,fmt,al);
511 static void logv(int sysloglevel, const char *pfx, int errnoval,
512 const char *fmt, va_list al) PRINTF(5,0);
513 static void logv(int sysloglevel, const char *pfx, int errnoval,
514 const char *fmt, va_list al) {
515 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
516 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
517 msgbuf[sizeof(msgbuf)-1]= 0;
519 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
520 sysloglevel= LOG_ERR; /* run by wrong user, probably */
522 logcore(sysloglevel, "<%s>%s: %s%s%s",
523 sitename, pfx, msgbuf,
524 errnoval>=0 ? ": " : "",
525 errnoval>=0 ? strerror(errnoval) : "");
528 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
529 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
530 static void fn(const char *fmt, ...) { \
532 logv(sysloglevel, pfx, err, fmt, al); \
536 #define logwrap(fn, pfx, sysloglevel, err) \
537 static void fn(const char *fmt, ...) PRINTF(1,2); \
538 static void fn(const char *fmt, ...) { \
540 logv(sysloglevel, pfx, err, fmt, al); \
544 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
545 diewrap(die, " critical", LOG_CRIT, -1, 16);
547 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
548 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
550 logwrap(syswarn, " warning", LOG_WARNING, errno);
551 logwrap(warn, " warning", LOG_WARNING, -1);
553 logwrap(notice, " notice", LOG_NOTICE, -1);
554 logwrap(info, " info", LOG_INFO, -1);
555 logwrap(debug, " debug", LOG_DEBUG, -1);
558 /*========== utility functions etc. ==========*/
560 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
561 static char *xvasprintf(const char *fmt, va_list al) {
563 int rc= vasprintf(&str,fmt,al);
564 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
567 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
568 static char *xasprintf(const char *fmt, ...) {
570 char *str= xvasprintf(fmt,al);
575 static int close_perhaps(int *fd) {
576 if (*fd <= 0) return 0;
581 static void xclose(int fd, const char *what, const char *what2) {
583 if (r) sysdie("close %s%s",what,what2?what2:"");
585 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
586 if (*fd <= 0) return;
587 xclose(*fd,what,what2);
591 static pid_t xfork(const char *what) {
595 if (child==-1) sysfatal("cannot fork for %s",what);
596 debug("forked %s %ld", what, (unsigned long)child);
597 if (!child) postfork();
601 static void on_fd_read_except(int fd, oop_call_fd callback) {
602 loop->on_fd(loop, fd, OOP_READ, callback, 0);
603 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
605 static void cancel_fd_read_except(int fd) {
606 loop->cancel_fd(loop, fd, OOP_READ);
607 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
610 static void report_child_status(const char *what, int status) {
611 if (WIFEXITED(status)) {
612 int es= WEXITSTATUS(status);
614 warn("%s: child died with error exit status %d", what, es);
615 } else if (WIFSIGNALED(status)) {
616 int sig= WTERMSIG(status);
617 const char *sigstr= strsignal(sig);
618 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
620 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
622 warn("%s: child died due to unknown fatal signal %d%s",
623 what, sig, coredump);
625 warn("%s: child died with unknown wait status %d", what,status);
629 static int xwaitpid(pid_t *pid, const char *what) {
632 int r= kill(*pid, SIGKILL);
633 if (r) sysdie("cannot kill %s child", what);
635 pid_t got= waitpid(*pid, &status, 0);
636 if (got==-1) sysdie("cannot reap %s child", what);
637 if (got==0) die("cannot reap %s child", what);
644 static void xunlink(const char *path, const char *what) {
646 if (r) sysdie("can't unlink %s %s", path, what);
649 static time_t xtime(void) {
651 if (now==-1) sysdie("time(2) failed");
655 static void xgettimeofday(struct timeval *tv_r) {
656 int r= gettimeofday(tv_r,0);
657 if (r) sysdie("gettimeofday(2) failed");
660 static void xsetnonblock(int fd, int nonblocking) {
661 int errnoval= oop_fd_nonblock(fd, nonblocking);
662 if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
665 static void check_isreg(const struct stat *stab, const char *path,
667 if (!S_ISREG(stab->st_mode))
668 die("%s %s not a plain file (mode 0%lo)",
669 what, path, (unsigned long)stab->st_mode);
672 static void xfstat(int fd, struct stat *stab_r, const char *what) {
673 int r= fstat(fd, stab_r);
674 if (r) sysdie("could not fstat %s", what);
677 static void xfstat_isreg(int fd, struct stat *stab_r,
678 const char *path, const char *what) {
679 xfstat(fd, stab_r, what);
680 check_isreg(stab_r, path, what);
683 static void xlstat_isreg(const char *path, struct stat *stab,
684 int *enoent_r /* 0 means ENOENT is fatal */,
686 int r= lstat(path, stab);
688 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
689 sysdie("could not lstat %s %s", what, path);
691 if (enoent_r) *enoent_r= 0;
692 check_isreg(stab, path, what);
695 static int samefile(const struct stat *a, const struct stat *b) {
696 assert(S_ISREG(a->st_mode));
697 assert(S_ISREG(b->st_mode));
698 return (a->st_ino == b->st_ino &&
699 a->st_dev == b->st_dev);
702 static char *sanitise(const char *input) {
703 static char sanibuf[100]; /* returns pointer to this buffer! */
705 const char *p= input;
709 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
711 if (!c) { *q++= '\''; *q=0; break; }
712 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
713 sprintf(q,"\\x%02x",c);
719 static int isewouldblock(int errnoval) {
720 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
724 /*========== command and control connections ==========*/
726 static int control_master;
728 typedef struct ControlConn ControlConn;
730 void (*destroy)(ControlConn*);
736 struct sockaddr_un un;
741 static const oop_rd_style control_rd_style= {
742 OOP_RD_DELIM_STRIP, '\n',
744 OOP_RD_SHORTREC_FORBID
747 static void control_destroy(ControlConn *cc) {
751 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
752 if (ferror(cc->out) | fflush(cc->out)) {
753 info("CTRL%d write error %s", cc->fd, strerror(errno));
758 static void control_prompt(ControlConn *cc /* may destroy*/) {
759 fprintf(cc->out, "%s| ", sitename);
760 control_checkouterr(cc);
763 typedef struct ControlCommand ControlCommand;
764 struct ControlCommand {
766 void (*f)(ControlConn *cc, const ControlCommand *ccmd,
767 const char *arg, size_t argsz);
772 static const ControlCommand control_commands[];
775 static void ccmd_##wh(ControlConn *cc, const ControlCommand *c, \
776 const char *arg, size_t argsz)
779 fputs("commands:\n", cc->out);
780 const ControlCommand *ccmd;
781 for (ccmd=control_commands; ccmd->cmd; ccmd++)
782 fprintf(cc->out, " %s\n", ccmd->cmd);
785 CCMD(period) { period(); }
786 CCMD(setintarg) { *(int*)c->xdata= atoi(arg); }
787 CCMD(setint) { *(int*)c->xdata= c->xval; }
789 static const ControlCommand control_commands[]= {
791 { "p", ccmd_period },
792 { "pretend flush", ccmd_setintarg, &simulate_flush },
793 { "poke sm", ccmd_setint, &sm_period_counter, 1 },
794 { "poke conn", ccmd_setint, &until_connect, 0 },
795 { "poke blscan", ccmd_setint, &until_backlog_nextscan, 0 },
796 { "wedge blscan", ccmd_setint, &until_backlog_nextscan, -1 },
800 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
801 const char *errmsg, int errnoval,
802 const char *data, size_t recsz, void *cc_v) {
803 ControlConn *cc= cc_v;
806 info("CTRL%d closed", cc->fd);
811 if (recsz == 0) goto prompt;
813 const ControlCommand *ccmd;
814 for (ccmd=control_commands; ccmd->cmd; ccmd++) {
815 int l= strlen(ccmd->cmd);
816 if (recsz < l) continue;
817 if (recsz > l && data[l] != ' ') continue;
818 if (memcmp(data, ccmd->cmd, l)) continue;
820 int argl= (int)recsz - (l+1);
821 ccmd->f(cc, ccmd, argl>=0 ? data+l+1 : 0, argl);
825 fputs("unknown command; h for help\n", cc->out);
832 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
833 const char *errmsg, int errnoval,
834 const char *data, size_t recsz, void *cc_v) {
835 ControlConn *cc= cc_v;
837 info("CTRL%d read error %s", cc->fd, errmsg);
842 static int control_conn_startup(ControlConn *cc /* may destroy*/,
844 cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
845 if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
847 int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
850 if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
852 info("CTRL%d %s ready", cc->fd, how);
857 static void control_stdio_destroy(ControlConn *cc) {
859 oop_rd_cancel(cc->rd);
860 errno= oop_rd_delete_tidy(cc->rd);
861 if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
866 static void control_stdio(void) {
867 ControlConn *cc= xmalloc(sizeof(*cc));
868 memset(cc,0,sizeof(*cc));
869 cc->destroy= control_stdio_destroy;
873 int r= control_conn_startup(cc,"stdio");
874 if (r) cc->destroy(cc);
877 static void control_accepted_destroy(ControlConn *cc) {
879 oop_rd_cancel(cc->rd);
880 oop_rd_delete_kill(cc->rd);
882 if (cc->out) { fclose(cc->out); cc->fd=0; }
883 close_perhaps(&cc->fd);
887 static void *control_master_readable(oop_source *lp, int master,
888 oop_event ev, void *u) {
889 ControlConn *cc= xmalloc(sizeof(*cc));
890 memset(cc,0,sizeof(*cc));
891 cc->destroy= control_accepted_destroy;
893 cc->salen= sizeof(cc->sa);
894 cc->fd= accept(master, &cc->sa.sa, &cc->salen);
895 if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
897 cc->out= fdopen(cc->fd, "w");
898 if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
900 int r= control_conn_startup(cc, "accepted");
910 #define NOCONTROL(...) do{ \
911 syswarn("no control socket, because failed to " __VA_ARGS__); \
915 static void control_init(void) {
920 struct sockaddr_un un;
923 memset(&sa,0,sizeof(sa));
924 int maxlen= sizeof(sa.un.sun_path);
926 int reallen= readlink(path_control, sa.un.sun_path, maxlen);
929 NOCONTROL("readlink control socket symlink path %s", path_control);
931 if (reallen >= maxlen) {
932 debug("control socket symlink path too long (r=%d)",reallen);
933 xunlink(path_control, "old (overlong) control socket symlink");
939 int r= lstat(realsockdir,&stab);
941 if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
943 r= mkdir(realsockdir, 0700);
944 if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
947 uid_t self= geteuid();
948 if (!S_ISDIR(stab.st_mode) ||
949 stab.st_uid != self ||
950 stab.st_mode & 0077) {
951 warn("no control socket, because real socket directory"
952 " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
953 !!S_ISDIR(stab.st_mode),
954 (unsigned long)stab.st_uid, (unsigned long)self,
955 (unsigned long)stab.st_mode & 0777UL);
960 real= xasprintf("%s/s%lx.%lx", realsockdir,
961 (unsigned long)xtime(), (unsigned long)self_pid);
962 int reallen= strlen(real);
964 if (reallen >= maxlen) {
965 warn("no control socket, because tmpnam gave overly-long path"
969 r= symlink(real, path_control);
970 if (r) NOCONTROL("make control socket path %s a symlink to real"
971 " socket path %s", path_control, real);
972 memcpy(sa.un.sun_path, real, reallen);
975 int r= unlink(sa.un.sun_path);
976 if (r && errno!=ENOENT)
977 NOCONTROL("remove old real socket %s", sa.un.sun_path);
979 control_master= socket(PF_UNIX, SOCK_STREAM, 0);
980 if (control_master<0) NOCONTROL("create new control socket");
982 sa.un.sun_family= AF_UNIX;
983 int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
984 r= bind(control_master, &sa.sa, sl);
985 if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
987 r= listen(control_master, 5);
988 if (r) NOCONTROL("listen");
990 xsetnonblock(control_master, 1);
992 loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
993 info("control socket ok, real path %s", sa.un.sun_path);
999 xclose_perhaps(&control_master, "control master",0);
1003 /*========== management of connections ==========*/
1005 static void conn_closefd(Conn *conn, const char *msgprefix) {
1006 int r= close_perhaps(&conn->fd);
1007 if (r) info("C%d %serror closing socket: %s",
1008 conn->fd, msgprefix, strerror(errno));
1011 static void conn_dispose(Conn *conn) {
1014 oop_rd_cancel(conn->rd);
1015 oop_rd_delete_kill(conn->rd);
1019 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1020 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
1022 conn_closefd(conn,"");
1024 until_connect= reconnect_delay_periods;
1027 static void *conn_exception(oop_source *lp, int fd,
1028 oop_event ev, void *conn_v) {
1031 assert(fd == conn->fd);
1032 assert(ev == OOP_EXCEPTION);
1033 int r= read(conn->fd, &ch, 1);
1034 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1035 else connfail(conn,"exceptional condition on socket (peer sent urgent"
1036 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1037 return OOP_CONTINUE;
1040 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1041 int requeue[art_MaxState];
1044 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1045 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1046 while ((art= LIST_REMHEAD(conn->sent))) {
1047 requeue[art->state]++;
1048 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1049 LIST_ADDTAIL(queue,art);
1054 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1057 char *m= xvasprintf(fmt,al);
1058 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1059 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1062 LIST_REMOVE(conns,conn);
1064 check_assign_articles();
1067 static void connfail(Conn *conn, const char *fmt, ...) {
1070 vconnfail(conn,fmt,al);
1074 static void check_idle_conns(void) {
1076 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
1077 conn->since_activity++;
1079 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
1080 if (conn->since_activity <= need_activity_periods) continue;
1082 /* We need to shut this down */
1084 connfail(conn,"timed out waiting for response to QUIT");
1085 else if (conn->sent.count)
1086 connfail(conn,"timed out waiting for responses");
1087 else if (conn->waiting.count || conn->priority.count)
1088 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1089 else if (conn->xmitu)
1090 connfail(conn,"peer has been sending responses"
1091 " before receiving our commands!");
1093 static const char quitcmd[]= "QUIT\r\n";
1094 int todo= sizeof(quitcmd)-1;
1095 const char *p= quitcmd;
1097 int r= write(conn->fd, p, todo);
1099 if (isewouldblock(errno))
1100 connfail(conn, "blocked writing QUIT to idle connection");
1102 connfail(conn, "failed to write QUIT to idle connection: %s",
1110 conn->since_activity= 0;
1111 debug("C%d is idle, quitting", conn->fd);
1120 /*---------- making new connections ----------*/
1122 static pid_t connecting_child;
1123 static int connecting_fdpass_sock;
1125 static void connect_attempt_discard(void) {
1126 if (connecting_child) {
1127 int status= xwaitpid(&connecting_child, "connect");
1128 if (!(WIFEXITED(status) ||
1129 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1130 report_child_status("connect", status);
1132 if (connecting_fdpass_sock) {
1133 cancel_fd_read_except(connecting_fdpass_sock);
1134 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1138 #define PREP_DECL_MSG_CMSG(msg) \
1140 struct iovec msgiov; \
1141 msgiov.iov_base= &msgbyte; \
1142 msgiov.iov_len= 1; \
1143 struct msghdr msg; \
1144 memset(&msg,0,sizeof(msg)); \
1145 char msg##cbuf[CMSG_SPACE(sizeof(int))]; \
1146 msg.msg_iov= &msgiov; \
1147 msg.msg_iovlen= 1; \
1148 msg.msg_control= msg##cbuf; \
1149 msg.msg_controllen= sizeof(msg##cbuf);
1151 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1154 assert(fd == connecting_fdpass_sock);
1156 PREP_DECL_MSG_CMSG(msg);
1158 ssize_t rs= recvmsg(fd, &msg, 0);
1160 if (isewouldblock(errno)) return OOP_CONTINUE;
1161 syswarn("failed to read socket from connecting child");
1165 conn= xmalloc(sizeof(*conn));
1166 memset(conn,0,sizeof(*conn));
1167 LIST_INIT(conn->waiting);
1168 LIST_INIT(conn->priority);
1169 LIST_INIT(conn->sent);
1171 struct cmsghdr *h= 0;
1172 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1174 int status= xwaitpid(&connecting_child, "connect child (broken)");
1176 if (WIFEXITED(status)) {
1177 if (WEXITSTATUS(status) != 0 &&
1178 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1179 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1180 /* child already reported the problem */;
1182 if (e == OOP_EXCEPTION)
1183 warn("connect: connection child exited code %d but"
1184 " unexpected exception on fdpass socket",
1185 WEXITSTATUS(status));
1187 warn("connect: connection child exited code %d but"
1189 WEXITSTATUS(status), (int)rs);
1191 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1192 warn("connect: connection attempt timed out");
1194 report_child_status("connect", status);
1199 #define CHK(field, val) \
1200 if (h->cmsg_##field != val) { \
1201 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1202 h->cmsg_##field, val); \
1205 CHK(level, SOL_SOCKET);
1206 CHK(type, SCM_RIGHTS);
1207 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1210 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1212 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1215 pid_t got= waitpid(connecting_child, &status, 0);
1216 if (got==-1) sysdie("connect: real wait for child");
1217 assert(got == connecting_child);
1218 connecting_child= 0;
1220 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1221 int es= WEXITSTATUS(status);
1223 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1224 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1226 fatal("connect: child gave unexpected exit status %d", es);
1230 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1232 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1233 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1234 if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1235 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1237 &peer_rd_err, conn);
1238 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1240 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1241 LIST_ADDHEAD(conns, conn);
1243 connect_attempt_discard();
1244 check_assign_articles();
1249 connect_attempt_discard();
1250 return OOP_CONTINUE;
1253 static int allow_connect_start(void) {
1254 return conns.count < max_connections
1255 && !connecting_child
1259 static void connect_start(void) {
1260 assert(!connecting_child);
1261 assert(!connecting_fdpass_sock);
1263 info("starting connection attempt");
1266 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1267 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1269 connecting_child= xfork("connection");
1271 if (!connecting_child) {
1272 FILE *cn_from, *cn_to;
1273 char buf[NNTP_STRLEN+100];
1274 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1276 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1278 alarm(connection_setup_timeout);
1279 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1283 unsigned char c= buf[l-1];
1284 if (!isspace(c)) break;
1285 if (c=='\n' || c=='\r') stripped=1;
1289 sysfatal("connect: connection attempt failed");
1292 fatal("connect: %s: %s", stripped ? "rejected" : "failed",
1296 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1297 sysfatal("connect: authentication failed");
1299 if (fputs("MODE STREAM\r\n", cn_to)==EOF ||
1301 sysfatal("connect: could not send MODE STREAM");
1302 buf[sizeof(buf)-1]= 0;
1303 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1304 if (ferror(cn_from))
1305 sysfatal("connect: could not read response to MODE STREAM");
1307 fatal("connect: connection close in response to MODE STREAM");
1312 fatal("connect: response to MODE STREAM is too long: %.100s...",
1314 l--; if (l>0 && buf[l-1]=='\r') l--;
1317 int rcode= strtoul(buf,&ep,10);
1319 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
1323 exitstatus= CONNCHILD_ESTATUS_STREAM;
1329 warn("connect: unexpected response to MODE STREAM: %.50s",
1335 int fd= fileno(cn_from);
1337 PREP_DECL_MSG_CMSG(msg);
1338 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1339 cmsg->cmsg_level= SOL_SOCKET;
1340 cmsg->cmsg_type= SCM_RIGHTS;
1341 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1342 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1344 msg.msg_controllen= cmsg->cmsg_len;
1345 r= sendmsg(socks[1], &msg, 0);
1346 if (r<0) sysdie("sendmsg failed for new connection");
1347 if (r!=1) die("sendmsg for new connection gave wrong result %d",r);
1352 xclose(socks[1], "connecting fdpass child's socket",0);
1353 connecting_fdpass_sock= socks[0];
1354 xsetnonblock(connecting_fdpass_sock, 1);
1355 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1358 /*---------- assigning articles to conns, and transmitting ----------*/
1360 static void check_assign_articles(void) {
1366 int spare=0, inqueue=0;
1368 /* Find a connection to offer this article. We prefer a busy
1369 * connection to an idle one, provided it's not full. We take the
1370 * first (oldest) and since that's stable, it will mean we fill up
1371 * connections in order. That way if we have too many
1372 * connections, the spare ones will go away eventually.
1374 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1375 if (walk->quitting) continue;
1376 inqueue= walk->sent.count + walk->priority.count
1377 + walk->waiting.count;
1378 spare= walk->max_queue - inqueue;
1379 assert(inqueue <= max_queue_per_conn);
1381 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1382 else if (spare>0) /*working*/ { use= walk; break; }
1385 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1387 Article *art= LIST_REMHEAD(queue);
1389 LIST_ADDTAIL(use->waiting, art);
1392 conn_maybe_write(use);
1393 } else if (allow_connect_start()) {
1394 until_connect= reconnect_delay_periods;
1403 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1404 conn_maybe_write(u);
1405 return OOP_CONTINUE;
1408 static void conn_maybe_write(Conn *conn) {
1410 conn_make_some_xmits(conn);
1412 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1416 void *rp= conn_write_some_xmits(conn);
1417 if (rp==OOP_CONTINUE) {
1418 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1420 } else if (rp==OOP_HALT) {
1423 /* transmitted everything */
1430 /*========== article transmission ==========*/
1432 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1433 XmitKind kind) { /* caller must then fill in details */
1434 struct iovec *v= &conn->xmit[conn->xmitu];
1435 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1436 v->iov_base= (char*)data;
1442 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1443 xmit_core(conn,data,len, xk_Const);
1445 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1447 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1448 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1452 static void xmit_free(XmitDetails *d) {
1454 case xk_Malloc: free(d->info.malloc_tofree); break;
1455 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1456 case xk_Const: break;
1461 static void *conn_write_some_xmits(Conn *conn) {
1463 * 0: nothing more to write, no need to call us again
1464 * OOP_CONTINUE: more to write but fd not writeable
1465 * OOP_HALT: disaster, have destroyed conn
1468 int count= conn->xmitu;
1469 if (!count) return 0;
1471 if (count > IOV_MAX) count= IOV_MAX;
1472 ssize_t rs= writev(conn->fd, conn->xmit, count);
1474 if (isewouldblock(errno)) return OOP_CONTINUE;
1475 connfail(conn, "write failed: %s", strerror(errno));
1481 for (done=0; rs && done<conn->xmitu; done++) {
1482 struct iovec *vp= &conn->xmit[done];
1483 XmitDetails *dp= &conn->xmitd[done];
1484 if (rs > vp->iov_len) {
1488 vp->iov_base= (char*)vp->iov_base + rs;
1492 int newu= conn->xmitu - done;
1493 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1494 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1499 static void conn_make_some_xmits(Conn *conn) {
1501 if (conn->xmitu+5 > CONNIOVS)
1504 Article *art= LIST_REMHEAD(conn->priority);
1505 if (!art) art= LIST_REMHEAD(conn->waiting);
1508 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1509 /* actually send it */
1511 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1515 XMIT_LITERAL("TAKETHIS ");
1516 xmit_noalloc(conn, art->messageid, art->midlen);
1517 XMIT_LITERAL("\r\n");
1518 xmit_artbody(conn, artdata);
1521 /* we got 235 from IHAVE */
1523 xmit_artbody(conn, artdata);
1525 XMIT_LITERAL(".\r\n");
1530 art->state == art_Unchecked ? art_Unsolicited :
1531 art->state == art_Wanted ? art_Wanted :
1533 art->ipf->counts[art->state][RC_sent]++;
1534 LIST_ADDTAIL(conn->sent, art);
1540 XMIT_LITERAL("IHAVE ");
1542 XMIT_LITERAL("CHECK ");
1543 xmit_noalloc(conn, art->messageid, art->midlen);
1544 XMIT_LITERAL("\r\n");
1546 assert(art->state == art_Unchecked);
1547 art->ipf->counts[art->state][RC_sent]++;
1548 LIST_ADDTAIL(conn->sent, art);
1554 /*========== handling responses from peer ==========*/
1556 static const oop_rd_style peer_rd_style= {
1557 OOP_RD_DELIM_STRIP, '\n',
1559 OOP_RD_SHORTREC_FORBID
1562 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1563 const char *errmsg, int errnoval,
1564 const char *data, size_t recsz, void *conn_v) {
1566 connfail(conn, "error receiving from peer: %s", errmsg);
1567 return OOP_CONTINUE;
1570 static Article *article_reply_check(Conn *conn, const char *response,
1571 int code_indicates_streaming,
1573 /* 1:yes, -1:no, 0:dontcare */,
1574 const char *sanitised_response) {
1575 Article *art= LIST_HEAD(conn->sent);
1579 "peer gave unexpected response when no commands outstanding: %s",
1580 sanitised_response);
1584 if (code_indicates_streaming) {
1585 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1586 if (!conn->stream) {
1587 connfail(conn, "peer gave streaming response code "
1588 " to IHAVE or subsequent body: %s", sanitised_response);
1591 const char *got_mid= response+4;
1592 int got_midlen= strcspn(got_mid, " \n\r");
1593 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1594 connfail(conn, "peer gave streaming response with syntactically invalid"
1595 " messageid: %s", sanitised_response);
1598 if (got_midlen != art->midlen ||
1599 memcmp(got_mid, art->messageid, got_midlen)) {
1600 connfail(conn, "peer gave streaming response code to wrong article -"
1601 " probable synchronisation problem; we offered: %s;"
1603 art->messageid, sanitised_response);
1608 connfail(conn, "peer gave non-streaming response code to"
1609 " CHECK/TAKETHIS: %s", sanitised_response);
1614 if (must_have_sent>0 && art->state < art_Wanted) {
1615 connfail(conn, "peer says article accepted but"
1616 " we had not sent the body: %s", sanitised_response);
1619 if (must_have_sent<0 && art->state >= art_Wanted) {
1620 connfail(conn, "peer says please sent the article but we just did: %s",
1621 sanitised_response);
1625 Article *art_again= LIST_REMHEAD(conn->sent);
1626 assert(art_again == art);
1630 static void update_nocheck(int accepted) {
1631 accept_proportion *= nocheck_decay;
1632 accept_proportion += accepted * (1.0 - nocheck_decay);
1633 int new_nocheck= accept_proportion >= nocheck_thresh;
1634 if (new_nocheck && !nocheck_reported) {
1635 notice("entering nocheck mode for the first time");
1636 nocheck_reported= 1;
1637 } else if (new_nocheck != nocheck) {
1638 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1640 nocheck= new_nocheck;
1643 static void article_done(Conn *conn, Article *art, int whichcount) {
1644 art->ipf->counts[art->state][whichcount]++;
1645 if (whichcount == RC_accepted) update_nocheck(1);
1646 else if (whichcount == RC_unwanted) update_nocheck(0);
1648 InputFile *ipf= art->ipf;
1650 while (art->blanklen) {
1651 static const char spaces[]=
1656 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1657 int r= pwrite(ipf->fd, spaces, w, art->offset);
1659 if (errno==EINTR) continue;
1660 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1661 art->messageid, art->blanklen,
1662 (unsigned long)art->offset, ipf->path);
1664 assert(r>=0 && r<=w);
1670 assert(ipf->inprogress >= 0);
1673 if (!ipf->inprogress && ipf != main_input_file)
1674 queue_check_input_done();
1677 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1678 const char *errmsg, int errnoval,
1679 const char *data, size_t recsz, void *conn_v) {
1682 if (ev == OOP_RD_EOF) {
1683 connfail(conn, "unexpected EOF from peer");
1684 return OOP_CONTINUE;
1686 assert(ev == OOP_RD_OK);
1688 char *sani= sanitise(data);
1691 unsigned long code= strtoul(data, &ep, 10);
1692 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1693 connfail(conn, "badly formatted response from peer: %s", sani);
1694 return OOP_CONTINUE;
1697 if (conn->quitting) {
1698 if (code!=205 && code!=503) {
1699 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1701 notice("C%d idle connection closed", conn->fd);
1702 assert(!conn->waiting.count);
1703 assert(!conn->priority.count);
1704 assert(!conn->sent.count);
1705 assert(!conn->xmitu);
1706 LIST_REMOVE(conns,conn);
1709 return OOP_CONTINUE;
1712 conn->since_activity= 0;
1715 #define GET_ARTICLE(musthavesent) \
1716 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1717 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1719 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1720 code_streaming= (streaming); \
1721 GET_ARTICLE(musthavesent); \
1722 article_done(conn, art, RC_##how); break;
1724 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1726 int code_streaming= 0;
1730 case 400: PEERBADMSG("peer stopped accepting articles");
1731 case 503: PEERBADMSG("peer timed us out");
1732 default: PEERBADMSG("peer sent unexpected message");
1734 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1735 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1737 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1738 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1740 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1741 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1743 case 238: /* CHECK says send it */
1745 case 335: /* IHAVE says send it */
1747 assert(art->state == art_Unchecked);
1748 art->ipf->counts[art->state][RC_accepted]++;
1749 art->state= art_Wanted;
1750 LIST_ADDTAIL(conn->priority, art);
1753 case 431: /* CHECK or TAKETHIS says try later */
1755 case 436: /* IHAVE says try later */
1758 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1760 sysfatal("write to defer file %s",path_defer);
1761 article_done(conn, art, RC_deferred);
1766 conn_maybe_write(conn);
1767 check_assign_articles();
1768 return OOP_CONTINUE;
1772 /*========== monitoring of input files ==========*/
1774 static void feedfile_eof(InputFile *ipf) {
1775 assert(ipf != main_input_file); /* promised by tailing_try_read */
1776 inputfile_reading_stop(ipf);
1778 if (ipf == flushing_input_file) {
1779 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1780 if (main_input_file) inputfile_reading_start(main_input_file);
1781 statemc_check_flushing_done();
1782 } else if (ipf == backlog_input_file) {
1783 statemc_check_backlog_done();
1785 abort(); /* supposed to wait rather than get EOF on main input file */
1789 static InputFile *open_input_file(const char *path) {
1790 int fd= open(path, O_RDONLY);
1792 if (errno==ENOENT) return 0;
1793 sysfatal("unable to open input file %s", path);
1797 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1798 memset(ipf,0,sizeof(*ipf));
1801 strcpy(ipf->path, path);
1806 static void close_input_file(InputFile *ipf) { /* does not free */
1807 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1808 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1809 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1810 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1811 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1815 /*---------- dealing with articles read in the input file ----------*/
1817 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1818 const char *data, const char *how) {
1819 warn("corrupted file: %s, offset %lu: %s: in %s",
1820 ipf->path, (unsigned long)offset, how, sanitise(data));
1821 ipf->readcount_err++;
1822 if (ipf->readcount_err > max_bad_data_initial +
1823 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1824 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1825 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1826 return OOP_CONTINUE;
1829 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1830 oop_rd_event ev, const char *errmsg,
1831 int errnoval, const char *data, size_t recsz,
1833 InputFile *ipf= ipf_v;
1834 assert(ev == OOP_RD_SYSTEM);
1836 sysdie("error reading input file: %s, offset %lu",
1837 ipf->path, (unsigned long)ipf->offset);
1840 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1841 oop_rd_event ev, const char *errmsg,
1842 int errnoval, const char *data, size_t recsz,
1844 InputFile *ipf= ipf_v;
1846 char tokentextbuf[sizeof(TOKEN)*2+3];
1848 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1850 off_t old_offset= ipf->offset;
1851 ipf->offset += recsz + 1;
1853 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1855 if (ev==OOP_RD_PARTREC)
1856 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1857 /* but process it anyway */
1859 if (ipf->skippinglong) {
1860 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1861 return OOP_CONTINUE;
1863 if (ev==OOP_RD_LONG) {
1864 ipf->skippinglong= 1;
1865 X_BAD_DATA("overly long line");
1868 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1869 if (!recsz) X_BAD_DATA("empty line");
1872 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1873 ipf->readcount_blank++;
1874 return OOP_CONTINUE;
1877 char *space= strchr(data,' ');
1878 int tokenlen= space-data;
1879 int midlen= (int)recsz-tokenlen-1;
1880 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1881 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1883 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1884 memcpy(tokentextbuf, data, tokenlen);
1885 tokentextbuf[tokenlen]= 0;
1886 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1888 ipf->readcount_ok++;
1890 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1891 art->state= art_Unchecked;
1892 art->midlen= midlen;
1893 art->ipf= ipf; ipf->inprogress++;
1894 art->token= TextToToken(tokentextbuf);
1895 art->offset= ipf->offset;
1896 art->blanklen= recsz;
1897 strcpy(art->messageid, space+1);
1898 LIST_ADDTAIL(queue, art);
1900 if (sms==sm_NORMAL && ipf==main_input_file &&
1901 ipf->offset >= target_max_feedfile_size)
1902 statemc_start_flush("feed file size");
1904 check_assign_articles();
1905 return OOP_CONTINUE;
1908 /*========== tailing input file ==========*/
1910 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1912 InputFile *ipf= user;
1913 return ipf->readable_callback(loop, &ipf->readable,
1914 ipf->readable_callback_user);
1917 static void tailing_on_cancel(struct oop_readable *rable) {
1918 InputFile *ipf= (void*)rable;
1920 if (ipf->filemon) filemon_stop(ipf);
1921 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1922 ipf->readable_callback= 0;
1925 static void tailing_queue_readable(InputFile *ipf) {
1926 /* lifetime of ipf here is OK because destruction will cause
1927 * on_cancel which will cancel this callback */
1928 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1931 static int tailing_on_readable(struct oop_readable *rable,
1932 oop_readable_call *cb, void *user) {
1933 InputFile *ipf= (void*)rable;
1935 tailing_on_cancel(rable);
1936 ipf->readable_callback= cb;
1937 ipf->readable_callback_user= user;
1940 tailing_queue_readable(ipf);
1944 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1946 InputFile *ipf= (void*)rable;
1948 ssize_t r= read(ipf->fd, buffer, length);
1950 if (errno==EINTR) continue;
1954 if (ipf==main_input_file) {
1957 } else if (ipf==flushing_input_file) {
1959 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1960 } else if (ipf==backlog_input_file) {
1966 tailing_queue_readable(ipf);
1971 /*---------- filemon implemented with inotify ----------*/
1973 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1974 #define HAVE_FILEMON
1976 #include <linux/inotify.h>
1978 static int filemon_inotify_fd;
1979 static int filemon_inotify_wdmax;
1980 static InputFile **filemon_inotify_wd2ipf;
1982 struct Filemon_Perfile {
1986 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1987 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1988 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
1990 if (wd >= filemon_inotify_wdmax) {
1992 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1993 sizeof(*filemon_inotify_wd2ipf) * newmax);
1994 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1995 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1996 filemon_inotify_wdmax= newmax;
1999 assert(!filemon_inotify_wd2ipf[wd]);
2000 filemon_inotify_wd2ipf[wd]= ipf;
2002 debug("filemon inotify startfile %p wd=%d wdmax=%d",
2003 ipf, wd, filemon_inotify_wdmax);
2008 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
2010 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
2011 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
2012 if (r) sysdie("inotify_rm_watch");
2013 filemon_inotify_wd2ipf[wd]= 0;
2016 static void *filemon_inotify_readable(oop_source *lp, int fd,
2017 oop_event e, void *u) {
2018 struct inotify_event iev;
2020 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
2022 if (isewouldblock(errno)) break;
2023 sysdie("read from inotify master");
2024 } else if (r==sizeof(iev)) {
2025 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
2027 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
2029 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
2030 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
2031 filemon_callback(ipf);
2033 return OOP_CONTINUE;
2036 static int filemon_method_init(void) {
2037 filemon_inotify_fd= inotify_init();
2038 if (filemon_inotify_fd<0) {
2039 syswarn("could not initialise inotify: inotify_init failed");
2043 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
2045 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2049 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2051 /*---------- filemon dummy implementation ----------*/
2053 #if !defined(HAVE_FILEMON)
2055 struct Filemon_Perfile { int dummy; };
2057 static int filemon_method_init(void) { return 0; }
2058 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2059 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2061 #endif /* !HAVE_FILEMON */
2063 /*---------- filemon generic interface ----------*/
2065 static void filemon_start(InputFile *ipf) {
2066 assert(!ipf->filemon);
2068 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
2069 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
2070 filemon_method_startfile(ipf, ipf->filemon);
2073 static void filemon_stop(InputFile *ipf) {
2074 if (!ipf->filemon) return;
2075 filemon_method_stopfile(ipf, ipf->filemon);
2080 static void filemon_callback(InputFile *ipf) {
2081 if (ipf && ipf->readable_callback) /* so filepoll() can be naive */
2082 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2085 /*---------- interface to start and stop an input file ----------*/
2087 static const oop_rd_style feedfile_rdstyle= {
2088 OOP_RD_DELIM_STRIP, '\n',
2090 OOP_RD_SHORTREC_LONG,
2093 static void inputfile_reading_start(InputFile *ipf) {
2095 ipf->readable.on_readable= tailing_on_readable;
2096 ipf->readable.on_cancel= tailing_on_cancel;
2097 ipf->readable.try_read= tailing_try_read;
2098 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2099 ipf->readable.delete_kill= 0;
2101 ipf->readable_callback= 0;
2102 ipf->readable_callback_user= 0;
2104 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2107 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2108 feedfile_got_article,ipf, feedfile_read_err, ipf);
2109 if (r) sysdie("unable start reading feedfile %s",ipf->path);
2112 static void inputfile_reading_stop(InputFile *ipf) {
2114 oop_rd_cancel(ipf->rd);
2115 oop_rd_delete(ipf->rd);
2117 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2121 /*========== interaction with innd - state machine ==========*/
2123 /* See official state diagram at top of file. We implement
2134 |`---------------------------------------------------.
2136 |`---------------- - - - |
2137 D ENOENT | D EXISTS see OVERALL STATES diagram |
2138 | for full startup logic |
2141 | ============ try to |
2147 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
2148 ^ | hardlink F to D |
2151 | | our handle onto F is now onto D |
2154 | |<-------------------<---------------------<---------+
2156 | | spawn inndcomm flush |
2158 | ================== |
2159 | FLUSHING[-ABSENT] |
2161 | main D tail/none |
2162 | ================== |
2164 | | INNDCOMM FLUSH FAILS ^
2165 | |`----------------------->----------. |
2167 | | NO SUCH SITE V |
2168 ^ |`--------------->----. ==================== |
2169 | | \ FLUSHFAILED[-ABSENT] |
2171 | | FLUSH OK \ main D tail/none |
2172 | | open F \ ==================== |
2174 | | \ | TIME TO RETRY |
2175 | |`------->----. ,---<---'\ `----------------'
2176 | | D NONE | | D NONE `----.
2178 | ============= V V ============
2179 | SEPARATED-1 | | DROPPING-1
2180 | flsh->rd!=0 | | flsh->rd!=0
2181 | [Separated] | | [Dropping]
2182 | main F idle | | main none
2183 | old D tail | | old D tail
2184 | ============= | | ============
2186 ^ | EOF ON D | | defer | EOF ON D
2188 | =============== | | ===============
2189 | SEPARATED-2 | | DROPPING-2
2190 | flsh->rd==0 | V flsh->rd==0
2191 | [Finishing] | | [Dropping]
2192 | main F tail | `. main none
2193 | old D closed | `. old D closed
2194 | =============== V `. ===============
2196 | | ALL D PROCESSED `. | ALL D PROCESSED
2197 | V install defer as backlog `. | install defer
2198 ^ | close D `. | close D
2199 | | unlink D `. | unlink D
2202 `----------' ==============
2222 static void startup_set_input_file(InputFile *f) {
2223 assert(!main_input_file);
2225 inputfile_reading_start(f);
2228 static void statemc_lock(void) {
2230 struct stat stab, stabf;
2233 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2234 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2237 memset(&fl,0,sizeof(fl));
2239 fl.l_whence= SEEK_SET;
2240 int r= fcntl(lockfd, F_SETLK, &fl);
2242 if (errno==EACCES || isewouldblock(errno)) {
2243 if (quiet_multiple) exit(0);
2244 fatal("another duct holds the lockfile");
2246 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2249 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2251 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2253 if (!lock_noent && samefile(&stab, &stabf))
2256 xclose(lockfd, "stale lockfile ", path_lock);
2259 FILE *lockfile= fdopen(lockfd, "w");
2260 if (!lockfile) sysdie("fdopen lockfile");
2262 int r= ftruncate(lockfd, 0);
2263 if (r) sysdie("truncate lockfile to write new info");
2265 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2266 (unsigned long)self_pid,
2267 sitename, feedfile, remote_host) == EOF ||
2269 sysfatal("write info to lockfile %s", path_lock);
2271 debug("startup: locked");
2274 static void statemc_init(void) {
2275 struct stat stabdefer;
2277 search_backlog_file();
2280 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2282 debug("startup: ductdefer ENOENT");
2284 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2285 switch (stabdefer.st_nlink==1) {
2287 open_defer(); /* so that we will later close it and rename it */
2290 xunlink(path_defer, "stale defer file link"
2291 " (presumably hardlink to backlog file)");
2294 die("defer file %s has unexpected link count %d",
2295 path_defer, stabdefer.st_nlink);
2299 struct stat stab_f, stab_d;
2302 InputFile *file_d= open_input_file(path_flushing);
2303 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2305 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2307 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2308 debug("startup: F==D => Hardlinked");
2309 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2314 debug("startup: F ENOENT => Moved");
2315 if (file_d) startup_set_input_file(file_d);
2316 spawn_inndcomm_flush("feedfile missing at startup");
2317 /* => Flushing, sms:=FLUSHING */
2320 debug("startup: F!=D => Separated");
2321 startup_set_input_file(file_d);
2322 SMS(SEPARATED, 0, "found both old and current feed files");
2324 debug("startup: F exists, D ENOENT => Normal");
2325 InputFile *file_f= open_input_file(feedfile);
2326 if (!file_f) die("feed file vanished during startup");
2327 startup_set_input_file(file_f);
2328 SMS(NORMAL, spontaneous_flush_periods, "normal startup");
2333 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2334 assert(sms == sm_NORMAL);
2336 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2338 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2339 (unsigned long)target_max_feedfile_size,
2342 int r= link(feedfile, path_flushing);
2343 if (r) sysfatal("link feedfile %s to flushing file %s",
2344 feedfile, path_flushing);
2347 xunlink(feedfile, "old feedfile link");
2350 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2353 static void statemc_period_poll(void) {
2354 if (!sm_period_counter) return;
2355 sm_period_counter--;
2356 assert(sm_period_counter>=0);
2358 if (sm_period_counter) return;
2361 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2363 case sm_FLUSHFAILED:
2364 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2371 static int inputfile_is_done(InputFile *ipf) {
2373 if (ipf->inprogress) return 0; /* new article in the meantime */
2374 if (ipf->rd) return 0; /* not had EOF */
2378 static void notice_processed(InputFile *ipf, const char *what,
2380 #define RCI_NOTHING(x) /* nothing */
2381 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2382 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2384 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2386 info("processed %s%s read=%d(+%dbl,+%derr)"
2387 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2388 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2391 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2392 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2393 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2394 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2395 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2396 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2402 static void statemc_check_backlog_done(void) {
2403 InputFile *ipf= backlog_input_file;
2404 if (!inputfile_is_done(ipf)) return;
2406 const char *slash= strrchr(ipf->path, '/');
2407 const char *leaf= slash ? slash+1 : ipf->path;
2408 const char *under= strchr(slash, '_');
2409 const char *rest= under ? under+1 : leaf;
2410 if (!strncmp(rest,"backlog",7)) rest += 7;
2411 notice_processed(ipf,"backlog:",rest);
2413 close_input_file(ipf);
2414 if (unlink(ipf->path)) {
2415 if (errno != ENOENT)
2416 sysdie("could not unlink processed backlog file %s", ipf->path);
2417 warn("backlog file %s vanished while we were reading it"
2418 " so we couldn't remove it (but it's done now, anyway)",
2422 backlog_input_file= 0;
2423 search_backlog_file();
2427 static void statemc_check_flushing_done(void) {
2428 InputFile *ipf= flushing_input_file;
2429 if (!inputfile_is_done(ipf)) return;
2431 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2433 notice_processed(ipf,"feedfile",0);
2437 xunlink(path_flushing, "old flushing file");
2439 close_input_file(flushing_input_file);
2440 free(flushing_input_file);
2441 flushing_input_file= 0;
2443 if (sms==sm_SEPARATED) {
2444 notice("flush complete");
2445 SMS(NORMAL, 0, "flush complete");
2446 } else if (sms==sm_DROPPING) {
2447 SMS(DROPPED, 0, "old flush complete");
2448 search_backlog_file();
2449 notice("feed dropped, but will continue until backlog is finished");
2453 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2455 assert(!inputfile_is_done(main_input_file));
2456 statemc_check_flushing_done();
2457 statemc_check_backlog_done();
2458 return OOP_CONTINUE;
2461 static void queue_check_input_done(void) {
2462 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2465 static void statemc_setstate(StateMachineState newsms, int periods,
2466 const char *forlog, const char *why) {
2468 sm_period_counter= periods;
2470 const char *xtra= "";
2473 case sm_FLUSHFAILED:
2474 if (!main_input_file) xtra= "-ABSENT";
2478 xtra= flushing_input_file->rd ? "-1" : "-2";
2484 info("state %s%s[%d] %s",forlog,xtra,periods,why);
2486 info("state %s%s %s",forlog,xtra,why);
2490 /*---------- defer and backlog files ----------*/
2492 static void open_defer(void) {
2497 defer= fopen(path_defer, "a+");
2498 if (!defer) sysfatal("could not open defer file %s", path_defer);
2500 /* truncate away any half-written records */
2502 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2504 if (stab.st_size > LONG_MAX)
2505 die("defer file %s size is far too large", path_defer);
2510 long orgsize= stab.st_size;
2511 long truncto= stab.st_size;
2513 if (!truncto) break; /* was only (if anything) one half-truncated record */
2514 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2515 sysdie("seek in defer file %s while truncating partial", path_defer);
2520 sysdie("failed read from defer file %s", path_defer);
2522 die("defer file %s shrank while we were checking it!", path_defer);
2528 if (stab.st_size != truncto) {
2529 warn("truncating half-record at end of defer file %s -"
2530 " shrinking by %ld bytes from %ld to %ld",
2531 path_defer, orgsize - truncto, orgsize, truncto);
2534 sysfatal("could not flush defer file %s", path_defer);
2535 if (ftruncate(fileno(defer), truncto))
2536 sysdie("could not truncate defer file %s", path_defer);
2539 info("continuing existing defer file %s (%ld bytes)",
2540 path_defer, orgsize);
2542 if (fseek(defer, truncto, SEEK_SET))
2543 sysdie("could not seek to new end of defer file %s", path_defer);
2546 static void close_defer(void) {
2551 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2553 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2556 time_t now= xtime();
2558 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2560 (unsigned long)stab.st_ino);
2561 if (link(path_defer, backlog))
2562 sysfatal("could not install defer file %s as backlog file %s",
2563 path_defer, backlog);
2564 if (unlink(path_defer))
2565 sysdie("could not unlink old defer link %s to backlog file %s",
2566 path_defer, backlog);
2570 if (until_backlog_nextscan < 0 ||
2571 until_backlog_nextscan > backlog_retry_minperiods + 1)
2572 until_backlog_nextscan= backlog_retry_minperiods + 1;
2575 static void poll_backlog_file(void) {
2576 if (until_backlog_nextscan < 0) return;
2577 if (until_backlog_nextscan-- > 0) return;
2578 search_backlog_file();
2581 static void search_backlog_file(void) {
2582 /* returns non-0 iff there are any backlog files */
2587 const char *oldest_path=0;
2588 time_t oldest_mtime=0, now;
2590 if (backlog_input_file) return;
2594 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2598 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2600 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2602 for (i=0; i<gl.gl_pathc; i++) {
2603 const char *path= gl.gl_pathv[i];
2605 if (strchr(path,'#') || strchr(path,'~')) {
2606 debug("backlog file search skipping %s", path);
2609 r= stat(path, &stab);
2611 syswarn("failed to stat backlog file %s", path);
2614 if (!S_ISREG(stab.st_mode)) {
2615 warn("backlog file %s is not a plain file (or link to one)", path);
2618 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2620 oldest_mtime= stab.st_mtime;
2623 case GLOB_NOMATCH: /* fall through */
2626 sysdie("glob expansion of backlog pattern %s gave unexpected"
2627 " nonzero (error?) return value %d", globpat_backlog, r);
2631 debug("backlog scan: none");
2633 if (sms==sm_DROPPED) {
2634 notice("feed dropped and our work is complete");
2636 int r= unlink(path_control);
2637 if (r && errno!=ENOENT)
2638 syswarn("failed to remove control symlink for old feed");
2640 xunlink(path_lock, "lockfile for old feed");
2643 until_backlog_nextscan= backlog_spontrescan_periods;
2648 double age= difftime(now, oldest_mtime);
2649 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2651 if (age_deficiency <= 0) {
2652 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2653 age, age_deficiency, oldest_path);
2655 backlog_input_file= open_input_file(oldest_path);
2656 if (!backlog_input_file) {
2657 warn("backlog file %s vanished as we opened it", oldest_path);
2661 inputfile_reading_start(backlog_input_file);
2662 until_backlog_nextscan= -1;
2666 until_backlog_nextscan= age_deficiency / period_seconds;
2668 if (backlog_spontrescan_periods >= 0 &&
2669 until_backlog_nextscan > backlog_spontrescan_periods)
2670 until_backlog_nextscan= backlog_spontrescan_periods;
2672 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2673 age, age_deficiency, until_backlog_nextscan, oldest_path);
2680 /*========== flushing the feed ==========*/
2682 static pid_t inndcomm_child;
2683 static int inndcomm_sentinel_fd;
2685 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2686 assert(inndcomm_child);
2687 assert(fd == inndcomm_sentinel_fd);
2688 int status= xwaitpid(&inndcomm_child, "inndcomm");
2691 cancel_fd_read_except(fd);
2692 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2693 inndcomm_sentinel_fd= 0;
2695 assert(!flushing_input_file);
2697 if (WIFEXITED(status)) {
2698 switch (WEXITSTATUS(status)) {
2700 case INNDCOMMCHILD_ESTATUS_FAIL:
2703 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2704 notice("feed has been dropped by innd, finishing up");
2705 flushing_input_file= main_input_file;
2706 tailing_queue_readable(flushing_input_file);
2707 /* we probably previously returned EAGAIN from our fake read method
2708 * when in fact we were at EOF, so signal another readable event
2709 * so we actually see the EOF */
2713 if (flushing_input_file) {
2714 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2717 SMS(DROPPED, 0, "feed dropped by innd");
2718 search_backlog_file();
2720 return OOP_CONTINUE;
2724 flushing_input_file= main_input_file;
2725 tailing_queue_readable(flushing_input_file);
2727 main_input_file= open_input_file(feedfile);
2728 if (!main_input_file)
2729 die("flush succeeded but feedfile %s does not exist!", feedfile);
2731 if (flushing_input_file) {
2732 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2735 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2737 return OOP_CONTINUE;
2740 goto unexpected_exitstatus;
2743 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2744 warn("flush timed out trying to talk to innd");
2747 unexpected_exitstatus:
2748 report_child_status("inndcomm child", status);
2752 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2753 return OOP_CONTINUE;
2756 static void inndcommfail(const char *what) {
2757 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2758 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2761 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2764 notice("flushing %s",why);
2766 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2767 assert(!inndcomm_child);
2768 assert(!inndcomm_sentinel_fd);
2770 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2772 inndcomm_child= xfork("inndcomm child");
2774 if (!inndcomm_child) {
2775 const char *flushargv[2]= { sitename, 0 };
2779 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2780 /* parent spots the autoclose of pipefds[1] when we die or exit */
2782 if (simulate_flush>=0) {
2783 warn("SIMULATING flush child status %d", simulate_flush);
2784 if (simulate_flush>128) raise(simulate_flush-128);
2785 else exit(simulate_flush);
2788 alarm(inndcomm_flush_timeout);
2789 r= ICCopen(); if (r) inndcommfail("connect");
2790 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2791 if (!r) exit(0); /* yay! */
2793 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2794 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2795 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2800 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2801 inndcomm_sentinel_fd= pipefds[0];
2802 assert(inndcomm_sentinel_fd);
2803 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2805 SMS(FLUSHING, 0, why);
2808 /*========== main program ==========*/
2810 static void postfork_inputfile(InputFile *ipf) {
2812 xclose(ipf->fd, "(in child) input file ", ipf->path);
2815 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2816 /* we have no stdio streams that are buffered long-term */
2818 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2821 static void postfork(void) {
2822 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2823 sysdie("(in child) failed to reset SIGPIPE");
2825 postfork_inputfile(main_input_file);
2826 postfork_inputfile(flushing_input_file);
2829 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2830 conn_closefd(conn,"(in child) ");
2832 postfork_stdio(defer, "defer file ", path_defer);
2835 typedef struct Every Every;
2837 struct timeval interval;
2842 static void every_schedule(Every *e, struct timeval base);
2844 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
2847 if (!e->fixed_rate) xgettimeofday(&base);
2848 every_schedule(e, base);
2849 return OOP_CONTINUE;
2852 static void every_schedule(Every *e, struct timeval base) {
2853 struct timeval when;
2854 timeradd(&base, &e->interval, &when);
2855 loop->on_time(loop, when, every_happens, e);
2858 static void every(int interval, int fixed_rate, void (*f)(void)) {
2859 Every *e= xmalloc(sizeof(*e));
2860 e->interval.tv_sec= interval;
2861 e->interval.tv_usec= 0;
2862 e->fixed_rate= fixed_rate;
2865 xgettimeofday(&now);
2866 every_schedule(e, now);
2869 static void filepoll(void) {
2870 filemon_callback(main_input_file);
2871 filemon_callback(flushing_input_file);
2874 static char *debug_report_ipf(InputFile *ipf) {
2875 if (!ipf) return xasprintf("none");
2877 const char *slash= strrchr(ipf->path,'/');
2878 const char *path= slash ? slash+1 : ipf->path;
2880 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2882 ipf->inprogress, (long)ipf->offset,
2883 ipf->fd, ipf->rd ? "+" : "");
2886 static void period(void) {
2887 char *dipf_main= debug_report_ipf(main_input_file);
2888 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2889 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2892 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2893 " input_files main:%s old:%s flushing:%s"
2894 " children connecting=%ld inndcomm=%ld"
2896 sms_names[sms], sm_period_counter,
2897 conns.count, queue.count, until_connect,
2898 dipf_main, dipf_flushing, dipf_backlog,
2899 (long)connecting_child, (long)inndcomm_child
2903 free(dipf_flushing);
2906 if (until_connect) until_connect--;
2908 poll_backlog_file();
2909 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2910 statemc_period_poll();
2911 check_assign_articles();
2916 /*========== option parsing ==========*/
2918 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2919 static void vbadusage(const char *fmt, va_list al) {
2920 char *m= xvasprintf(fmt,al);
2921 fprintf(stderr, "bad usage: %s\n"
2922 "say --help for help, or read the manpage\n",
2925 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2929 /*---------- generic option parser ----------*/
2931 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2932 static void badusage(const char *fmt, ...) {
2939 of_seconds= 001000u,
2940 of_boolean= 002000u,
2943 typedef struct Option Option;
2944 typedef void OptionParser(const Option*, const char *val);
2948 const char *lng, *formarg;
2954 static void parse_options(const Option *options, char ***argvp) {
2955 /* on return *argvp is first non-option arg; argc is not updated */
2958 const char *arg= *++(*argvp);
2960 if (*arg != '-') break;
2961 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2963 while ((a= *++arg)) {
2967 char *equals= strchr(arg,'=');
2968 int len= equals ? (equals - arg) : strlen(arg);
2969 for (o=options; o->shrt || o->lng; o++)
2970 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2972 badusage("unknown long option --%s",arg);
2975 if (equals) badusage("option --%s does not take a value",o->lng);
2977 } else if (equals) {
2981 if (!arg) badusage("option --%s needs a value for %s",
2982 o->lng, o->formarg);
2985 break; /* eaten the whole argument now */
2987 for (o=options; o->shrt || o->lng; o++)
2990 badusage("unknown short option -%c",a);
2997 if (!arg) badusage("option -%c needs a value for %s",
2998 o->shrt, o->formarg);
3001 break; /* eaten the whole argument now */
3007 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
3009 static void print_options(const Option *options, FILE *f) {
3011 for (o=options; o->shrt || o->lng; o++) {
3012 char shrt[2] = { o->shrt, 0 };
3013 char *optspec= xasprintf("%s%s%s%s%s",
3014 o->shrt ? "-" : "", shrt,
3015 o->shrt && o->lng ? "|" : "",
3016 DELIMPERHAPS("--", o->lng));
3017 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
3022 /*---------- specific option types ----------*/
3024 static void op_integer(const Option *o, const char *val) {
3027 unsigned long ul= strtoul(val,&ep,10);
3028 if (*ep || ep==val || errno || ul>INT_MAX)
3029 badusage("bad integer value for %s",o->lng);
3030 int *store= o->store;
3034 static void op_double(const Option *o, const char *val) {
3035 int *store= o->store;
3038 *store= strtod(val, &ep);
3039 if (*ep || ep==val || errno)
3040 badusage("bad floating point value for %s",o->lng);
3043 static void op_string(const Option *o, const char *val) {
3044 const char **store= o->store;
3048 static void op_seconds(const Option *o, const char *val) {
3049 int *store= o->store;
3053 double v= strtod(val,&ep);
3054 if (ep==val) badusage("bad time/duration value for %s",o->lng);
3056 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
3057 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
3058 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
3059 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
3060 else if (!strcmp(ep,"das")) unit= 10;
3061 else if (!strcmp(ep,"hs")) unit= 100;
3062 else if (!strcmp(ep,"ks")) unit= 1000;
3063 else if (!strcmp(ep,"Ms")) unit= 1000000;
3064 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
3068 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
3072 static void op_setint(const Option *o, const char *val) {
3073 int *store= o->store;
3077 /*---------- specific options ----------*/
3079 static void help(const Option *o, const char *val);
3081 static const Option innduct_options[]= {
3082 {'f',"feedfile", "F", &feedfile, op_string },
3083 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
3084 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
3085 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
3086 {'C',"inndconf", "F", &inndconffile, op_string },
3087 {'P',"port", "PORT", &port, op_integer },
3088 {0,"help", 0, 0, help },
3090 {0,"max-connections", "N", &max_connections, op_integer },
3091 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
3092 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
3093 {0,"period-interval", "TIME", &period_seconds, op_seconds },
3095 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
3096 {0,"stuck-flush-timeout","TIME", &inndcomm_flush_timeout, op_seconds },
3098 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
3099 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
3101 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
3102 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
3103 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3104 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3105 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
3106 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
3108 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
3109 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
3114 static void printusage(FILE *f) {
3115 fputs("usage: innduct [options] site [fqdn]\n"
3116 "available options are:\n", f);
3117 print_options(innduct_options, f);
3120 static void help(const Option *o, const char *val) {
3122 if (ferror(stdout) || fflush(stdout)) {
3123 perror("innduct: writing help");
3129 static void convert_to_periods_rndup(int *store) {
3130 *store += period_seconds-1;
3131 *store /= period_seconds;
3134 int main(int argc, char **argv) {
3140 parse_options(innduct_options, &argv);
3145 if (!sitename) badusage("need site name argument");
3146 remote_host= *argv++;
3147 if (*argv) badusage("too many non-option arguments");
3151 int r= innconf_read(inndconffile);
3152 if (!r) badusage("could not read inn.conf (more info on stderr)");
3154 if (!remote_host) remote_host= sitename;
3156 if (nocheck_thresh < 0 || nocheck_thresh > 100)
3157 badusage("nocheck threshold percentage must be between 0..100");
3158 nocheck_thresh *= 0.01;
3160 if (nocheck_decay < 0.1)
3161 badusage("nocheck decay articles must be at least 0.1");
3162 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3164 convert_to_periods_rndup(&reconnect_delay_periods);
3165 convert_to_periods_rndup(&flushfail_retry_periods);
3166 convert_to_periods_rndup(&backlog_retry_minperiods);
3167 convert_to_periods_rndup(&backlog_spontrescan_periods);
3168 convert_to_periods_rndup(&spontaneous_flush_periods);
3169 convert_to_periods_rndup(&need_activity_periods);
3171 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3172 badusage("bad input data ratio must be between 0..100");
3173 max_bad_data_ratio *= 0.01;
3176 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3177 } else if (!feedfile[0]) {
3178 badusage("feed filename must be nonempty");
3179 } else if (feedfile[strlen(feedfile)-1]=='/') {
3180 feedfile= xasprintf("%s%s",feedfile,sitename);
3183 const char *feedfile_forbidden= "?*[~#";
3185 while ((c= *feedfile_forbidden++))
3186 if (strchr(feedfile, c))
3187 badusage("feed filename may not contain metacharacter %c",c);
3191 path_lock= xasprintf("%s_lock", feedfile);
3192 path_flushing= xasprintf("%s_flushing", feedfile);
3193 path_defer= xasprintf("%s_defer", feedfile);
3194 path_control= xasprintf("%s_control", feedfile);
3195 globpat_backlog= xasprintf("%s_backlog*", feedfile);
3197 oop_source_sys *sysloop= oop_sys_new();
3198 if (!sysloop) sysdie("could not create liboop event loop");
3199 loop= (oop_source*)sysloop;
3201 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3202 sysdie("could not ignore SIGPIPE");
3207 if (become_daemon) {
3209 for (i=3; i<255; i++)
3210 /* do this now before we open syslog, etc. */
3212 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3214 int null= open("/dev/null",O_RDWR);
3215 if (null<0) sysfatal("failed to open /dev/null");
3219 xclose(null, "/dev/null original fd",0);
3221 pid_t child1= xfork("daemonise first fork");
3222 if (child1) _exit(0);
3224 pid_t sid= setsid();
3225 if (sid != child1) sysfatal("setsid failed");
3227 pid_t child2= xfork("daemonise second fork");
3228 if (child2) _exit(0);
3232 if (self_pid==-1) sysdie("getpid");
3243 if (!filemon_method_init()) {
3244 warn("no file monitoring available, polling");
3245 every(5,0,filepoll);
3248 every(period_seconds,1,period);
3254 void *run= oop_sys_run(sysloop);
3255 assert(run == OOP_ERROR);
3256 sysdie("event loop failed");