3 * - actually do something with readable on control master
4 * - option for realsockdir
5 * - manpage: document control master stuff
6 * - manpage: innconf is used for communicating with innd
8 * build-lfs/backends/innduct --no-daemon -f `pwd`/fee sit dom
12 * Newsfeeds file entries should look like this:
13 * host.name.of.site[/exclude,exclude,...]\
14 * :pattern,pattern...[/distribution,distribution...]\
18 * sitename[/exclude,exclude,...]\
19 * :pattern,pattern...[/distribution,distribution...]\
25 * or might be blanked out
26 * <spc><spc><spc><spc>....
28 * F site.name main feed file
29 * opened/created, then written, by innd
32 * tokens blanked out by duct when processed
33 * site.name_lock lock preventing multiple ducts
34 * to hold lock must open,F_SETLK[W]
35 * and then stat to check that locked file
36 * still has name site.name_lock
37 * holder of this lock is "duct"
38 * (only) lockholder may remove the lockfile
39 * D site.name_flushing temporary feed file during flush (or crash)
40 * hardlink created by duct
42 * site.name_defer 431'd articles, still being written,
43 * created, written, used by duct
45 * site.name_backlog.<date>.<inum>
46 * 431'd articles, ready for innxmit or duct
47 * created (link/mv) by duct
48 * site.name_backlog<anything-else> (where <anything-else> does not
49 * contain '#' or '~') eg
50 * site.name_backlog.manual
51 * anything the sysadmin likes (eg, feed files
52 * from old feeds to be merged into this one)
53 * created (link/mv) by admin
54 * may be symlinks (in which case links
55 * may be written through, but only links
58 * It is safe to remove backlog files manually,
59 * if it's desired to throw away the backlog.
61 * Backlog files are also processed by innduct. We find the oldest
62 * backlog file which is at least a certain amount old, and feed it
63 * back into our processing. When every article in it has been read
64 * and processed, we unlink it and look for another backlog file.
66 * If we don't have a backlog file that we're reading, we close the
67 * defer file that we're writing and make it into a backlog file at
68 * the first convenient opportunity.
79 | | <----------------<---------------------------------'|
85 | F: innd writing, duct reading |
88 | | duct decides time to flush |
89 | | duct makes hardlink |
91 | V <------------------------'|
93 | F == D: innd writing, duct reading both exist |
96 | | <-----------<-------------<--'|
100 | V <---------------------. |
103 | D: innd writing, duct reading; or ENOENT | |
105 | | duct requests flush of feed | |
106 | | (others can too, harmlessly) | |
110 | D: innd flushing, duct; or ENOENT | |
112 | | inndcomm flush fails | |
113 | |`-------------------------->------------------' |
115 | | inndcomm reports no such site |
116 | |`---------------------------------------------------- | -.
118 | | innd finishes writing D, creates F | |
119 | | inndcomm reports flush successful | |
122 | Separated <----------------' |
123 | F: innd writing F!=D /
124 | D: duct reading; or ENOENT both exist /
126 | | duct gets to the end of D /
127 | | duct opens F too /
130 | F: innd writing, duct reading |
131 | D: duct finishing V
133 | | duct finishes processing D F: ENOENT
134 | V duct unlinks D D: duct reading
136 `--<--' | duct finishes
146 "duct reading" means innduct is reading the file but also
147 overwriting processed tokens.
151 * rune for printing diagrams:
153 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
158 /*============================== PROGRAM ==============================*/
160 #define _GNU_SOURCE 1
166 #include "inndcomm.h"
168 #include "inn/list.h"
169 #include "inn/innconf.h"
172 #include <sys/types.h>
173 #include <sys/wait.h>
174 #include <sys/stat.h>
175 #include <sys/socket.h>
193 #include <oop-read.h>
195 /*----- general definitions, probably best not changed -----*/
197 #define CONNCHILD_ESTATUS_STREAM 24
198 #define CONNCHILD_ESTATUS_NOSTREAM 25
200 #define INNDCOMMCHILD_ESTATUS_FAIL 26
201 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
203 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
204 #define MAX_CONTROL_COMMAND 1000
206 #define VA va_list al; va_start(al,fmt)
207 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
208 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
210 /*----- doubly linked lists -----*/
212 #define ISNODE(T) struct node list_node
215 union { struct list li; T *for_type; } u; \
219 #define NODE(n) (assert((void*)&(n)->list_node == &(n)), &(n)->list_node)
221 #define LIST_CHECKCANHAVENODE(l,n) \
222 ((void)((n) == ((l).u.for_type))) /* just for the type check */
224 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
225 ( LIST_CHECKCANHAVENODE(l,n), \
226 list_addsomehow(&(l).u.li, NODE((n))), \
230 #define LIST_REMSOMEHOW(l,list_remsomehow) \
231 ( (typeof((l).u.for_type)) \
234 list_remsomehow(&(l).u.li) ) \
240 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
241 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
242 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
243 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
245 #define LIST_INIT(l) (list_new(&(l).u.li))
246 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
247 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
248 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
250 #define LIST_REMOVE(l,n) \
251 ( LIST_CHECKCANHAVENODE(l,n), \
252 list_remove(NODE((n))), \
256 #define LIST_INSERT(l,n,pred) \
257 ( LIST_CHECKCANHAVENODE(l,n), \
258 LIST_CHECKCANHAVENODE(l,pred), \
259 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
263 /*----- type predeclarations -----*/
265 typedef struct Conn Conn;
266 typedef struct Article Article;
267 typedef struct InputFile InputFile;
268 typedef struct XmitDetails XmitDetails;
269 typedef struct Filemon_Perfile Filemon_Perfile;
270 typedef enum StateMachineState StateMachineState;
275 /*----- function predeclarations -----*/
277 static void conn_maybe_write(Conn *conn);
278 static void conn_make_some_xmits(Conn *conn);
279 static void *conn_write_some_xmits(Conn *conn);
281 static void xmit_free(XmitDetails *d);
283 #define SMS(newstate, periods, why) \
284 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
285 static void statemc_setstate(StateMachineState newsms, int periods,
286 const char *forlog, const char *why);
288 static void statemc_start_flush(const char *why); /* Normal => Flushing */
289 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
291 static void check_assign_articles(void);
292 static void queue_check_input_done(void);
294 static void statemc_check_flushing_done(void);
295 static void statemc_check_backlog_done(void);
297 static void postfork(void);
299 static void open_defer(void);
300 static void close_defer(void);
301 static void search_backlog_file(void);
303 static void inputfile_reading_start(InputFile *ipf);
304 static void inputfile_reading_stop(InputFile *ipf);
306 static void filemon_start(InputFile *ipf);
307 static void filemon_stop(InputFile *ipf);
308 static void filemon_callback(InputFile *ipf);
310 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
311 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
313 static const oop_rd_style peer_rd_style;
314 static oop_rd_call peer_rd_err, peer_rd_ok;
316 /*----- configuration options -----*/
317 /* when changing defaults, remember to update the manpage */
319 static const char *sitename, *remote_host;
320 static const char *feedfile, *realsockdir="/tmp/innduct.control";
321 static int quiet_multiple=0;
322 static int become_daemon=1;
323 static int try_stream=1;
325 static const char *inndconffile;
327 static int max_connections=10;
328 static int max_queue_per_conn=200;
329 static int target_max_feedfile_size=100000;
330 static int period_seconds=60;
332 static int connection_setup_timeout=200;
333 static int inndcomm_flush_timeout=100;
335 static double nocheck_thresh= 95.0; /* converted from percentage by main */
336 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
338 /* all these are initialised to seconds, and converted to periods in main */
339 static int reconnect_delay_periods=1000;
340 static int flushfail_retry_periods=1000;
341 static int backlog_retry_minperiods=50;
342 static int backlog_spontrescan_periods=300;
343 static int spontaneous_flush_periods=100000;
344 static int need_activity_periods=1000;
346 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
347 static int max_bad_data_initial= 30;
348 /* in one corrupt 4096-byte block the number of newlines has
349 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
352 /*----- statistics -----*/
354 typedef enum { /* in queue in conn->sent */
355 art_Unchecked, /* not checked, not sent checking */
356 art_Wanted, /* checked, wanted sent body as requested */
357 art_Unsolicited, /* - sent body without check */
361 #define RESULT_COUNTS(RCS,RCN) \
369 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
370 #define RCI_TRIPLE_VALS_BASE(counts,x) \
371 counts[art_Unchecked] x \
372 + counts[art_Wanted] x \
373 + counts[art_Unsolicited] x, \
374 counts[art_Unchecked] x \
375 , counts[art_Wanted] x \
376 , counts[art_Unsolicited] x
379 #define RC_INDEX(x) RC_##x,
380 RESULT_COUNTS(RC_INDEX, RC_INDEX)
385 /*----- transmission buffers -----*/
390 xk_Malloc, xk_Const, xk_Artdata
402 /*----- core operational data structure types -----*/
405 /* This is also an instance of struct oop_readable */
406 struct oop_readable readable; /* first */
407 oop_readable_call *readable_callback;
408 void *readable_callback_user;
411 Filemon_Perfile *filemon;
413 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
414 long inprogress; /* no. of articles read but not processed */
418 int counts[art_MaxState][RCI_max];
419 int readcount_ok, readcount_blank, readcount_err;
434 #define SMS_LIST(X) \
442 enum StateMachineState {
443 #define SMS_DEF_ENUM(s) sm_##s,
444 SMS_LIST(SMS_DEF_ENUM)
447 static const char *sms_names[]= {
448 #define SMS_DEF_NAME(s) #s ,
449 SMS_LIST(SMS_DEF_NAME)
455 int fd; /* may be 0, meaning closed (during construction/destruction) */
456 oop_read *rd; /* likewise */
457 int max_queue, stream, quitting;
458 int since_activity; /* periods */
459 ArticleList waiting; /* not yet told peer */
460 ArticleList priority; /* peer says send it now */
461 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
462 struct iovec xmit[CONNIOVS];
463 XmitDetails xmitd[CONNIOVS];
468 /*----- general operational variables -----*/
470 /* main initialises */
471 static oop_source *loop;
472 static ConnList conns;
473 static ArticleList queue;
474 static char *path_lock, *path_flushing, *path_defer, *path_control;
475 static char *globpat_backlog;
476 static pid_t self_pid;
478 /* statemc_init initialises */
479 static StateMachineState sms;
481 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
482 static int sm_period_counter;
484 /* initialisation to 0 is good */
485 static int until_connect, until_backlog_nextscan;
486 static double accept_proportion;
487 static int nocheck, nocheck_reported;
489 /*========== logging ==========*/
491 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
492 static void logcore(int sysloglevel, const char *fmt, ...) {
495 vsyslog(sysloglevel,fmt,al);
497 if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
498 vfprintf(stderr,fmt,al);
504 static void logv(int sysloglevel, const char *pfx, int errnoval,
505 const char *fmt, va_list al) PRINTF(5,0);
506 static void logv(int sysloglevel, const char *pfx, int errnoval,
507 const char *fmt, va_list al) {
508 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
509 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
510 msgbuf[sizeof(msgbuf)-1]= 0;
512 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
513 sysloglevel= LOG_ERR; /* run by wrong user, probably */
515 logcore(sysloglevel, "<%s>%s: %s%s%s",
516 sitename, pfx, msgbuf,
517 errnoval>=0 ? ": " : "",
518 errnoval>=0 ? strerror(errnoval) : "");
521 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
522 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
523 static void fn(const char *fmt, ...) { \
525 logv(sysloglevel, pfx, err, fmt, al); \
529 #define logwrap(fn, pfx, sysloglevel, err) \
530 static void fn(const char *fmt, ...) PRINTF(1,2); \
531 static void fn(const char *fmt, ...) { \
533 logv(sysloglevel, pfx, err, fmt, al); \
537 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
538 diewrap(die, " critical", LOG_CRIT, -1, 16);
540 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
541 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
543 logwrap(syswarn, " warning", LOG_WARNING, errno);
544 logwrap(warn, " warning", LOG_WARNING, -1);
546 logwrap(notice, " notice", LOG_NOTICE, -1);
547 logwrap(info, " info", LOG_INFO, -1);
548 logwrap(debug, " debug", LOG_DEBUG, -1);
551 /*========== utility functions etc. ==========*/
553 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
554 static char *xvasprintf(const char *fmt, va_list al) {
556 int rc= vasprintf(&str,fmt,al);
557 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
560 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
561 static char *xasprintf(const char *fmt, ...) {
563 char *str= xvasprintf(fmt,al);
568 static int close_perhaps(int *fd) {
569 if (*fd <= 0) return 0;
574 static void xclose(int fd, const char *what, const char *what2) {
576 if (r) sysdie("close %s%s",what,what2?what2:"");
578 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
579 if (*fd <= 0) return;
580 xclose(*fd,what,what2);
584 static pid_t xfork(const char *what) {
588 if (child==-1) sysfatal("cannot fork for %s",what);
589 debug("forked %s %ld", what, (unsigned long)child);
590 if (!child) postfork();
594 static void on_fd_read_except(int fd, oop_call_fd callback) {
595 loop->on_fd(loop, fd, OOP_READ, callback, 0);
596 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
598 static void cancel_fd_read_except(int fd) {
599 loop->cancel_fd(loop, fd, OOP_READ);
600 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
603 static void report_child_status(const char *what, int status) {
604 if (WIFEXITED(status)) {
605 int es= WEXITSTATUS(status);
607 warn("%s: child died with error exit status %d", what, es);
608 } else if (WIFSIGNALED(status)) {
609 int sig= WTERMSIG(status);
610 const char *sigstr= strsignal(sig);
611 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
613 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
615 warn("%s: child died due to unknown fatal signal %d%s",
616 what, sig, coredump);
618 warn("%s: child died with unknown wait status %d", what,status);
622 static int xwaitpid(pid_t *pid, const char *what) {
625 int r= kill(*pid, SIGKILL);
626 if (r) sysdie("cannot kill %s child", what);
628 pid_t got= waitpid(*pid, &status, WNOHANG);
629 if (got==-1) sysdie("cannot reap %s child", what);
636 static void xunlink(const char *path, const char *what) {
638 if (r) sysdie("can't unlink %s %s", path, what);
641 static time_t xtime(void) {
643 if (now==-1) sysdie("time(2) failed");
647 static void xsetnonblock(int fd, int nonblocking) {
648 int errnoval= oop_fd_nonblock(fd, nonblocking);
649 if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
652 static void check_isreg(const struct stat *stab, const char *path,
654 if (!S_ISREG(stab->st_mode))
655 die("%s %s not a plain file (mode 0%lo)",
656 what, path, (unsigned long)stab->st_mode);
659 static void xfstat(int fd, struct stat *stab_r, const char *what) {
660 int r= fstat(fd, stab_r);
661 if (r) sysdie("could not fstat %s", what);
664 static void xfstat_isreg(int fd, struct stat *stab_r,
665 const char *path, const char *what) {
666 xfstat(fd, stab_r, what);
667 check_isreg(stab_r, path, what);
670 static void xlstat_isreg(const char *path, struct stat *stab,
671 int *enoent_r /* 0 means ENOENT is fatal */,
673 int r= lstat(path, stab);
675 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
676 sysdie("could not lstat %s %s", what, path);
678 if (enoent_r) *enoent_r= 0;
679 check_isreg(stab, path, what);
682 static int samefile(const struct stat *a, const struct stat *b) {
683 assert(S_ISREG(a->st_mode));
684 assert(S_ISREG(b->st_mode));
685 return (a->st_ino == b->st_ino &&
686 a->st_dev == b->st_dev);
689 static char *sanitise(const char *input) {
690 static char sanibuf[100]; /* returns pointer to this buffer! */
692 const char *p= input;
696 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
698 if (!c) { *q++= '\''; *q=0; break; }
699 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
700 sprintf(q,"\\x%02x",c);
706 static int isewouldblock(int errnoval) {
707 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
711 /*========== command and control connections ==========*/
713 static int control_master;
715 typedef struct ControlConn ControlConn;
717 void (*destroy)(ControlConn*);
723 struct sockaddr_un un;
728 static const oop_rd_style control_rd_style= {
729 OOP_RD_DELIM_STRIP, '\n',
731 OOP_RD_SHORTREC_FORBID
734 static void control_destroy(ControlConn *cc) {
738 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
739 if (ferror(cc->out) | fflush(cc->out)) {
740 info("CTRL%d write error %s", cc->fd, strerror(errno));
745 static void control_prompt(ControlConn *cc /* may destroy*/) {
746 fprintf(cc->out, "%s|", sitename);
747 control_checkouterr(cc);
750 typedef struct ControlCommand ControlCommand;
751 struct ControlCommand {
753 void (*f)(ControlConn *cc, const ControlCommand *ccmd,
754 const char *arg, size_t argsz);
757 static const ControlCommand control_commands[];
759 static void ccmd_help(ControlConn *cc, const ControlCommand *thisccmd,
760 const char *arg, size_t argsz) {
761 fputs("commands:\n", cc->out);
762 const ControlCommand *ccmd;
763 for (ccmd=control_commands; ccmd->cmd; ccmd++)
764 fprintf(cc->out, " %s\n", ccmd->cmd);
767 static const ControlCommand control_commands[]= {
772 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
773 const char *errmsg, int errnoval,
774 const char *data, size_t recsz, void *cc_v) {
775 ControlConn *cc= cc_v;
778 info("CTRL%d closed", cc->fd);
783 if (recsz == 0) goto prompt;
785 const ControlCommand *ccmd;
786 for (ccmd=control_commands; ccmd->cmd; ccmd++) {
787 int l= strlen(ccmd->cmd);
788 if (recsz < l) continue;
789 if (recsz > l && data[l] != ' ') continue;
790 if (memcmp(data, ccmd->cmd, l)) continue;
792 int argl= (int)recsz - (l+1);
793 ccmd->f(cc, ccmd, argl>=0 ? data : 0, argl);
797 fputs("unknown command; h for help\n", cc->out);
804 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
805 const char *errmsg, int errnoval,
806 const char *data, size_t recsz, void *cc_v) {
807 ControlConn *cc= cc_v;
809 info("CTRL%d read error %s", cc->fd, errmsg);
814 static int control_conn_startup(ControlConn *cc /* may destroy*/,
816 cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
817 if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
819 int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
822 if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
824 info("CTRL%d %s ready", cc->fd, how);
829 static void control_stdio_destroy(ControlConn *cc) {
831 oop_rd_cancel(cc->rd);
832 errno= oop_rd_delete_tidy(cc->rd);
833 if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
838 static void control_stdio(void) {
839 ControlConn *cc= xmalloc(sizeof(*cc));
840 memset(cc,0,sizeof(*cc));
841 cc->destroy= control_stdio_destroy;
845 int r= control_conn_startup(cc,"stdio");
846 if (r) cc->destroy(cc);
849 static void control_accepted_destroy(ControlConn *cc) {
851 oop_rd_cancel(cc->rd);
852 oop_rd_delete_kill(cc->rd);
854 if (cc->out) { fclose(cc->out); cc->fd=0; }
855 close_perhaps(&cc->fd);
859 static void *control_master_readable(oop_source *lp, int master,
860 oop_event ev, void *u) {
861 ControlConn *cc= xmalloc(sizeof(*cc));
862 memset(cc,0,sizeof(*cc));
863 cc->destroy= control_accepted_destroy;
865 cc->salen= sizeof(cc->sa);
866 cc->fd= accept(master, &cc->sa.sa, &cc->salen);
867 if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
869 cc->out= fdopen(cc->fd, "w");
870 if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
872 int r= control_conn_startup(cc, "accepted");
882 #define NOCONTROL(...) do{ \
883 syswarn("no control socket, because failed to " __VA_ARGS__); \
887 static void control_init(void) {
892 struct sockaddr_un un;
895 memset(&sa,0,sizeof(sa));
896 int maxlen= sizeof(sa.un.sun_path);
898 int reallen= readlink(path_control, sa.un.sun_path, maxlen);
901 NOCONTROL("readlink control socket symlink path %s", path_control);
903 if (reallen >= maxlen) {
904 debug("control socket symlink path too long (r=%d)",reallen);
905 xunlink(path_control, "old (overlong) control socket symlink");
911 int r= lstat(realsockdir,&stab);
913 if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
915 r= mkdir(realsockdir, 0700);
916 if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
919 uid_t self= geteuid();
920 if (!S_ISDIR(stab.st_mode) ||
921 stab.st_uid != self ||
922 stab.st_mode & 0077) {
923 warn("no control socket, because real socket directory"
924 " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
925 !!S_ISDIR(stab.st_mode),
926 (unsigned long)stab.st_uid, (unsigned long)self,
927 (unsigned long)stab.st_mode & 0777UL);
932 real= xasprintf("%s/s%lx.%lx", realsockdir,
933 (unsigned long)xtime(), (unsigned long)self_pid);
934 int reallen= strlen(real);
936 if (reallen >= maxlen) {
937 warn("no control socket, because tmpnam gave overly-long path"
941 r= symlink(real, path_control);
942 if (r) NOCONTROL("make control socket path %s a symlink to real"
943 " socket path %s", path_control, real);
944 memcpy(sa.un.sun_path, real, reallen);
947 int r= unlink(sa.un.sun_path);
948 if (r && errno!=ENOENT)
949 NOCONTROL("remove old real socket %s", sa.un.sun_path);
951 control_master= socket(PF_UNIX, SOCK_STREAM, 0);
952 if (control_master<0) NOCONTROL("create new control socket");
954 sa.un.sun_family= AF_UNIX;
955 int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
956 r= bind(control_master, &sa.sa, sl);
957 if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
959 r= listen(control_master, 5);
960 if (r) NOCONTROL("listen");
962 xsetnonblock(control_master, 1);
964 loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
965 info("control socket ok, real path %s", sa.un.sun_path);
971 xclose_perhaps(&control_master, "control master",0);
975 /*========== management of connections ==========*/
977 static void conn_closefd(Conn *conn, const char *msgprefix) {
978 int r= close_perhaps(&conn->fd);
979 if (r) info("C%d %serror closing socket: %s",
980 conn->fd, msgprefix, strerror(errno));
983 static void conn_dispose(Conn *conn) {
986 oop_rd_cancel(conn->rd);
987 oop_rd_delete_kill(conn->rd);
991 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
992 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
994 conn_closefd(conn,"");
996 until_connect= reconnect_delay_periods;
999 static void *conn_exception(oop_source *lp, int fd,
1000 oop_event ev, void *conn_v) {
1003 assert(fd == conn->fd);
1004 assert(ev == OOP_EXCEPTION);
1005 int r= read(conn->fd, &ch, 1);
1006 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1007 else connfail(conn,"exceptional condition on socket (peer sent urgent"
1008 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1009 return OOP_CONTINUE;
1012 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1013 int requeue[art_MaxState];
1016 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1017 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1018 while ((art= LIST_REMHEAD(conn->sent))) {
1019 requeue[art->state]++;
1020 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1021 LIST_ADDTAIL(queue,art);
1026 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1029 char *m= xvasprintf(fmt,al);
1030 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1031 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1034 LIST_REMOVE(conns,conn);
1036 check_assign_articles();
1039 static void connfail(Conn *conn, const char *fmt, ...) {
1042 vconnfail(conn,fmt,al);
1046 static void check_idle_conns(void) {
1048 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
1049 conn->since_activity++;
1051 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
1052 if (conn->since_activity <= need_activity_periods) continue;
1054 /* We need to shut this down */
1056 connfail(conn,"timed out waiting for response to QUIT");
1057 else if (conn->sent.count)
1058 connfail(conn,"timed out waiting for responses");
1059 else if (conn->waiting.count || conn->priority.count)
1060 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1061 else if (conn->xmitu)
1062 connfail(conn,"peer has been sending responses"
1063 " before receiving our commands!");
1065 static const char quitcmd[]= "QUIT\r\n";
1066 int todo= sizeof(quitcmd)-1;
1067 const char *p= quitcmd;
1069 int r= write(conn->fd, p, todo);
1071 if (isewouldblock(errno))
1072 connfail(conn, "blocked writing QUIT to idle connection");
1074 connfail(conn, "failed to write QUIT to idle connection: %s",
1082 conn->since_activity= 0;
1083 debug("C%d is idle, quitting", conn->fd);
1092 /*---------- making new connections ----------*/
1094 static pid_t connecting_child;
1095 static int connecting_fdpass_sock;
1097 static void connect_attempt_discard(void) {
1098 if (connecting_child) {
1099 int r= kill(connecting_child, SIGTERM);
1100 if (r) syswarn("failed to kill connecting child");
1101 int status= xwaitpid(&connecting_child, "connect");
1103 if (!(WIFEXITED(status) ||
1104 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1105 report_child_status("connect", status);
1107 if (connecting_fdpass_sock) {
1108 cancel_fd_read_except(connecting_fdpass_sock);
1109 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1113 #define PREP_DECL_MSG_CMSG(msg) \
1114 struct msghdr msg; \
1115 memset(&msg,0,sizeof(msg)); \
1116 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
1117 msg.msg_control= msg##cbuf; \
1118 msg.msg_controllen= sizeof(msg##cbuf);
1120 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1123 assert(fd == connecting_fdpass_sock);
1125 conn= xmalloc(sizeof(*conn));
1126 memset(conn,0,sizeof(*conn));
1128 PREP_DECL_MSG_CMSG(msg);
1129 struct cmsghdr *h= 0;
1130 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
1131 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1134 pid_t got= waitpid(connecting_child, &status, WNOHANG);
1136 assert(got==connecting_child);
1137 connecting_child= 0;
1138 if (WIFEXITED(status)) {
1139 if (WEXITSTATUS(status) != 0 &&
1140 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1141 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1142 /* child already reported the problem */;
1144 warn("connect: connection child exited code %d but no cmsg",
1145 WEXITSTATUS(status));
1146 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1147 warn("connect: connection attempt timed out");
1149 report_child_status("connect", status);
1152 /* child is still running apparently, report the socket problem */
1154 syswarn("connect: read from fdpass socket failed");
1155 else if (e == OOP_EXCEPTION)
1156 warn("connect: unexpected exception on fdpass socket");
1158 warn("connect: unexpected EOF on fdpass socket");
1160 fatal("connect: unexpected lack of cmsg from child");
1165 #define CHK(field, val) \
1166 if (h->cmsg_##field != val) { \
1167 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1168 h->cmsg_##field, val); \
1171 CHK(level, SOL_SOCKET);
1172 CHK(type, SCM_RIGHTS);
1173 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1176 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1178 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1181 pid_t got= waitpid(connecting_child, &status, 0);
1182 if (got==-1) sysdie("connect: real wait for child");
1183 assert(got == connecting_child);
1184 connecting_child= 0;
1186 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1187 int es= WEXITSTATUS(status);
1189 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1190 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1192 fatal("connect: child gave unexpected exit status %d", es);
1196 LIST_INIT(conn->waiting);
1197 LIST_INIT(conn->priority);
1198 LIST_INIT(conn->sent);
1199 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1201 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1202 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1203 if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1204 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1206 &peer_rd_err, conn);
1207 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1209 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1210 LIST_ADDHEAD(conns, conn);
1212 connect_attempt_discard();
1213 check_assign_articles();
1218 connect_attempt_discard();
1219 return OOP_CONTINUE;
1222 static int allow_connect_start(void) {
1223 return conns.count < max_connections
1224 && !connecting_child
1228 static void connect_start(void) {
1229 assert(!connecting_child);
1230 assert(!connecting_fdpass_sock);
1232 notice("starting connection attempt");
1235 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1236 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1238 connecting_child= xfork("connection");
1240 if (!connecting_child) {
1241 FILE *cn_from, *cn_to;
1242 char buf[NNTP_STRLEN+100];
1243 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1245 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1247 alarm(connection_setup_timeout);
1248 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1249 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
1250 else sysfatal("connect: connection attempt failed");
1252 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1253 sysfatal("connect: authentication failed");
1255 if (fputs("MODE STREAM\r\n", cn_to) ||
1257 sysfatal("connect: could not send MODE STREAM");
1258 buf[sizeof(buf)-1]= 0;
1259 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1260 if (ferror(cn_from))
1261 sysfatal("connect: could not read response to MODE STREAM");
1263 fatal("connect: connection close in response to MODE STREAM");
1268 fatal("connect: response to MODE STREAM is too long: %.100s...",
1270 l--; if (l>0 && buf[l-1]=='\r') l--;
1273 int rcode= strtoul(buf,&ep,10);
1275 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
1279 exitstatus= CONNCHILD_ESTATUS_STREAM;
1285 warn("connect: unexpected response to MODE STREAM: %.50s",
1291 int fd= fileno(cn_from);
1293 PREP_DECL_MSG_CMSG(msg);
1294 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1295 cmsg->cmsg_level= SOL_SOCKET;
1296 cmsg->cmsg_type= SCM_RIGHTS;
1297 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1298 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1300 msg.msg_controllen= cmsg->cmsg_len;
1301 r= sendmsg(socks[1], &msg, 0);
1302 if (r) sysdie("sendmsg failed for new connection");
1307 xclose(socks[1], "connecting fdpass child's socket",0);
1308 connecting_fdpass_sock= socks[0];
1309 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1312 /*---------- assigning articles to conns, and transmitting ----------*/
1314 static void check_assign_articles(void) {
1320 int spare=0, inqueue=0;
1322 /* Find a connection to offer this article. We prefer a busy
1323 * connection to an idle one, provided it's not full. We take the
1324 * first (oldest) and since that's stable, it will mean we fill up
1325 * connections in order. That way if we have too many
1326 * connections, the spare ones will go away eventually.
1328 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1329 if (walk->quitting) continue;
1330 inqueue= walk->sent.count + walk->priority.count
1331 + walk->waiting.count;
1332 spare= walk->max_queue - inqueue;
1333 assert(inqueue <= max_queue_per_conn);
1335 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1336 else if (spare>0) /*working*/ { use= walk; break; }
1339 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1341 Article *art= LIST_REMHEAD(queue);
1342 LIST_ADDTAIL(use->waiting, art);
1345 conn_maybe_write(use);
1346 } else if (allow_connect_start()) {
1347 until_connect= reconnect_delay_periods;
1356 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1357 conn_maybe_write(u);
1358 return OOP_CONTINUE;
1361 static void conn_maybe_write(Conn *conn) {
1363 conn_make_some_xmits(conn);
1365 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1369 void *rp= conn_write_some_xmits(conn);
1370 if (rp==OOP_CONTINUE) {
1371 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1373 } else if (rp==OOP_HALT) {
1376 /* transmitted everything */
1383 /*========== article transmission ==========*/
1385 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1386 XmitKind kind) { /* caller must then fill in details */
1387 struct iovec *v= &conn->xmit[conn->xmitu];
1388 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1389 v->iov_base= (char*)data;
1395 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1396 xmit_core(conn,data,len, xk_Const);
1398 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1400 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1401 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1405 static void xmit_free(XmitDetails *d) {
1407 case xk_Malloc: free(d->info.malloc_tofree); break;
1408 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1409 case xk_Const: break;
1414 static void *conn_write_some_xmits(Conn *conn) {
1416 * 0: nothing more to write, no need to call us again
1417 * OOP_CONTINUE: more to write but fd not writeable
1418 * OOP_HALT: disaster, have destroyed conn
1421 int count= conn->xmitu;
1422 if (!count) return 0;
1424 if (count > IOV_MAX) count= IOV_MAX;
1425 ssize_t rs= writev(conn->fd, conn->xmit, count);
1427 if (isewouldblock(errno)) return OOP_CONTINUE;
1428 connfail(conn, "write failed: %s", strerror(errno));
1434 for (done=0; rs && done<conn->xmitu; done++) {
1435 struct iovec *vp= &conn->xmit[done];
1436 XmitDetails *dp= &conn->xmitd[done];
1437 if (rs > vp->iov_len) {
1441 vp->iov_base= (char*)vp->iov_base + rs;
1445 int newu= conn->xmitu - done;
1446 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1447 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1452 static void conn_make_some_xmits(Conn *conn) {
1454 if (conn->xmitu+5 > CONNIOVS)
1457 Article *art= LIST_REMHEAD(conn->priority);
1458 if (!art) art= LIST_REMHEAD(conn->waiting);
1461 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1462 /* actually send it */
1464 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1468 XMIT_LITERAL("TAKETHIS ");
1469 xmit_noalloc(conn, art->messageid, art->midlen);
1470 XMIT_LITERAL("\r\n");
1471 xmit_artbody(conn, artdata);
1474 /* we got 235 from IHAVE */
1476 xmit_artbody(conn, artdata);
1478 XMIT_LITERAL(".\r\n");
1483 art->state == art_Unchecked ? art_Unsolicited :
1484 art->state == art_Wanted ? art_Wanted :
1486 art->ipf->counts[art->state][RC_sent]++;
1487 LIST_ADDTAIL(conn->sent, art);
1493 XMIT_LITERAL("IHAVE ");
1495 XMIT_LITERAL("CHECK ");
1496 xmit_noalloc(conn, art->messageid, art->midlen);
1497 XMIT_LITERAL("\r\n");
1499 assert(art->state == art_Unchecked);
1500 art->ipf->counts[art->state][RC_sent]++;
1501 LIST_ADDTAIL(conn->sent, art);
1507 /*========== handling responses from peer ==========*/
1509 static const oop_rd_style peer_rd_style= {
1510 OOP_RD_DELIM_STRIP, '\n',
1512 OOP_RD_SHORTREC_FORBID
1515 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1516 const char *errmsg, int errnoval,
1517 const char *data, size_t recsz, void *conn_v) {
1519 connfail(conn, "error receiving from peer: %s", errmsg);
1520 return OOP_CONTINUE;
1523 static Article *article_reply_check(Conn *conn, const char *response,
1524 int code_indicates_streaming,
1526 /* 1:yes, -1:no, 0:dontcare */,
1527 const char *sanitised_response) {
1528 Article *art= LIST_HEAD(conn->sent);
1532 "peer gave unexpected response when no commands outstanding: %s",
1533 sanitised_response);
1537 if (code_indicates_streaming) {
1538 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1539 if (!conn->stream) {
1540 connfail(conn, "peer gave streaming response code "
1541 " to IHAVE or subsequent body: %s", sanitised_response);
1544 const char *got_mid= response+4;
1545 int got_midlen= strcspn(got_mid, " \n\r");
1546 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1547 connfail(conn, "peer gave streaming response with syntactically invalid"
1548 " messageid: %s", sanitised_response);
1551 if (got_midlen != art->midlen ||
1552 memcmp(got_mid, art->messageid, got_midlen)) {
1553 connfail(conn, "peer gave streaming response code to wrong article -"
1554 " probable synchronisation problem; we offered: %s;"
1556 art->messageid, sanitised_response);
1561 connfail(conn, "peer gave non-streaming response code to"
1562 " CHECK/TAKETHIS: %s", sanitised_response);
1567 if (must_have_sent>0 && art->state < art_Wanted) {
1568 connfail(conn, "peer says article accepted but"
1569 " we had not sent the body: %s", sanitised_response);
1572 if (must_have_sent<0 && art->state >= art_Wanted) {
1573 connfail(conn, "peer says please sent the article but we just did: %s",
1574 sanitised_response);
1578 Article *art_again= LIST_REMHEAD(conn->sent);
1579 assert(art_again == art);
1583 static void update_nocheck(int accepted) {
1584 accept_proportion *= nocheck_decay;
1585 accept_proportion += accepted * (1.0 - nocheck_decay);
1586 int new_nocheck= accept_proportion >= nocheck_thresh;
1587 if (new_nocheck && !nocheck_reported) {
1588 notice("entering nocheck mode for the first time");
1589 nocheck_reported= 1;
1590 } else if (new_nocheck != nocheck) {
1591 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1593 nocheck= new_nocheck;
1596 static void article_done(Conn *conn, Article *art, int whichcount) {
1597 art->ipf->counts[art->state][whichcount]++;
1598 if (whichcount == RC_accepted) update_nocheck(1);
1599 else if (whichcount == RC_unwanted) update_nocheck(0);
1601 InputFile *ipf= art->ipf;
1603 while (art->blanklen) {
1604 static const char spaces[]=
1609 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1610 int r= pwrite(ipf->fd, spaces, w, art->offset);
1612 if (errno==EINTR) continue;
1613 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1614 art->messageid, art->blanklen,
1615 (unsigned long)art->offset, ipf->path);
1617 assert(r>=0 && r<=w);
1623 assert(ipf->inprogress >= 0);
1626 if (!ipf->inprogress && ipf != main_input_file)
1627 queue_check_input_done();
1630 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1631 const char *errmsg, int errnoval,
1632 const char *data, size_t recsz, void *conn_v) {
1635 if (ev == OOP_RD_EOF) {
1636 connfail(conn, "unexpected EOF from peer");
1637 return OOP_CONTINUE;
1639 assert(ev == OOP_RD_OK);
1641 char *sani= sanitise(data);
1644 unsigned long code= strtoul(data, &ep, 10);
1645 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1646 connfail(conn, "badly formatted response from peer: %s", sani);
1647 return OOP_CONTINUE;
1650 if (conn->quitting) {
1651 if (code!=205 && code!=503) {
1652 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1654 notice("C%d idle connection closed", conn->fd);
1655 assert(!conn->waiting.count);
1656 assert(!conn->priority.count);
1657 assert(!conn->sent.count);
1658 assert(!conn->xmitu);
1659 LIST_REMOVE(conns,conn);
1662 return OOP_CONTINUE;
1665 conn->since_activity= 0;
1668 #define GET_ARTICLE(musthavesent) \
1669 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1670 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1672 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1673 code_streaming= (streaming); \
1674 GET_ARTICLE(musthavesent); \
1675 article_done(conn, art, RC_##how); break;
1677 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1679 int code_streaming= 0;
1683 case 400: PEERBADMSG("peer stopped accepting articles");
1684 case 503: PEERBADMSG("peer timed us out");
1685 default: PEERBADMSG("peer sent unexpected message");
1687 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1688 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1690 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1691 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1693 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1694 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1696 case 238: /* CHECK says send it */
1698 case 335: /* IHAVE says send it */
1700 assert(art->state == art_Unchecked);
1701 art->ipf->counts[art->state][RC_accepted]++;
1702 art->state= art_Wanted;
1703 LIST_ADDTAIL(conn->priority, art);
1706 case 431: /* CHECK or TAKETHIS says try later */
1708 case 436: /* IHAVE says try later */
1711 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1713 sysfatal("write to defer file %s",path_defer);
1714 article_done(conn, art, RC_deferred);
1719 conn_maybe_write(conn);
1720 check_assign_articles();
1721 return OOP_CONTINUE;
1725 /*========== monitoring of input files ==========*/
1727 static void feedfile_eof(InputFile *ipf) {
1728 assert(ipf != main_input_file); /* promised by tailing_try_read */
1729 inputfile_reading_stop(ipf);
1731 if (ipf == flushing_input_file) {
1732 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1733 if (main_input_file) inputfile_reading_start(main_input_file);
1734 statemc_check_flushing_done();
1735 } else if (ipf == backlog_input_file) {
1736 statemc_check_backlog_done();
1738 abort(); /* supposed to wait rather than get EOF on main input file */
1742 static InputFile *open_input_file(const char *path) {
1743 int fd= open(path, O_RDONLY);
1745 if (errno==ENOENT) return 0;
1746 sysfatal("unable to open input file %s", path);
1750 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1751 memset(ipf,0,sizeof(*ipf));
1754 strcpy(ipf->path, path);
1759 static void close_input_file(InputFile *ipf) { /* does not free */
1760 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1761 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1762 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1763 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1764 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1768 /*---------- dealing with articles read in the input file ----------*/
1770 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1771 const char *data, const char *how) {
1772 warn("corrupted file: %s, offset %lu: %s: %s",
1773 ipf->path, (unsigned long)offset, how, sanitise(data));
1774 ipf->readcount_err++;
1775 if (ipf->readcount_err > max_bad_data_initial +
1776 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1777 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1778 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1779 return OOP_CONTINUE;
1782 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1783 oop_rd_event ev, const char *errmsg,
1784 int errnoval, const char *data, size_t recsz,
1786 InputFile *ipf= ipf_v;
1787 assert(ev == OOP_RD_SYSTEM);
1789 sysdie("error reading input file: %s, offset %lu",
1790 ipf->path, (unsigned long)ipf->offset);
1793 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1794 oop_rd_event ev, const char *errmsg,
1795 int errnoval, const char *data, size_t recsz,
1797 InputFile *ipf= ipf_v;
1799 char tokentextbuf[sizeof(TOKEN)*2+3];
1801 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1803 off_t old_offset= ipf->offset;
1804 ipf->offset += recsz + 1;
1806 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1808 if (ev==OOP_RD_PARTREC)
1809 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1810 /* but process it anyway */
1812 if (ipf->skippinglong) {
1813 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1814 return OOP_CONTINUE;
1816 if (ev==OOP_RD_LONG) {
1817 ipf->skippinglong= 1;
1818 X_BAD_DATA("overly long line");
1821 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1822 if (!recsz) X_BAD_DATA("empty line");
1825 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1826 ipf->readcount_blank++;
1827 return OOP_CONTINUE;
1830 char *space= strchr(data,' ');
1831 int tokenlen= space-data;
1832 int midlen= (int)recsz-tokenlen-1;
1833 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1834 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1836 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1837 memcpy(tokentextbuf, data, tokenlen);
1838 tokentextbuf[tokenlen]= 0;
1839 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1841 ipf->readcount_ok++;
1843 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1844 art->state= art_Unchecked;
1845 art->midlen= midlen;
1846 art->ipf= ipf; ipf->inprogress++;
1847 art->token= TextToToken(tokentextbuf);
1848 art->offset= ipf->offset;
1849 art->blanklen= recsz;
1850 strcpy(art->messageid, space+1);
1851 LIST_ADDTAIL(queue, art);
1853 if (sms==sm_NORMAL && ipf==main_input_file &&
1854 ipf->offset >= target_max_feedfile_size)
1855 statemc_start_flush("feed file size");
1857 check_assign_articles();
1858 return OOP_CONTINUE;
1861 /*========== tailing input file ==========*/
1863 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1865 InputFile *ipf= user;
1866 return ipf->readable_callback(loop, &ipf->readable,
1867 ipf->readable_callback_user);
1870 static void tailing_on_cancel(struct oop_readable *rable) {
1871 InputFile *ipf= (void*)rable;
1873 if (ipf->filemon) filemon_stop(ipf);
1874 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1875 ipf->readable_callback= 0;
1878 static void tailing_queue_readable(InputFile *ipf) {
1879 /* lifetime of ipf here is OK because destruction will cause
1880 * on_cancel which will cancel this callback */
1881 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1884 static int tailing_on_readable(struct oop_readable *rable,
1885 oop_readable_call *cb, void *user) {
1886 InputFile *ipf= (void*)rable;
1888 tailing_on_cancel(rable);
1889 ipf->readable_callback= cb;
1890 ipf->readable_callback_user= user;
1893 tailing_queue_readable(ipf);
1897 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1899 InputFile *ipf= (void*)rable;
1901 ssize_t r= read(ipf->fd, buffer, length);
1903 if (errno==EINTR) continue;
1907 if (ipf==main_input_file) {
1910 } else if (ipf==flushing_input_file) {
1912 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1913 } else if (ipf==backlog_input_file) {
1923 /*---------- filemon implemented with inotify ----------*/
1925 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1926 #define HAVE_FILEMON
1928 #include <linux/inotify.h>
1930 static int filemon_inotify_fd;
1931 static int filemon_inotify_wdmax;
1932 static InputFile **filemon_inotify_wd2ipf;
1934 struct Filemon_Perfile {
1938 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1939 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1940 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
1942 if (wd >= filemon_inotify_wdmax) {
1944 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1945 sizeof(*filemon_inotify_wd2ipf) * newmax);
1946 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1947 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1948 filemon_inotify_wdmax= newmax;
1951 assert(!filemon_inotify_wd2ipf[wd]);
1952 filemon_inotify_wd2ipf[wd]= ipf;
1954 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1955 ipf, wd, filemon_inotify_wdmax);
1960 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1962 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1963 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1964 if (r) sysdie("inotify_rm_watch");
1965 filemon_inotify_wd2ipf[wd]= 0;
1968 static void *filemon_inotify_readable(oop_source *lp, int fd,
1969 oop_event e, void *u) {
1970 struct inotify_event iev;
1972 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1974 if (isewouldblock(errno)) break;
1975 sysdie("read from inotify master");
1976 } else if (r==sizeof(iev)) {
1977 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1979 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1981 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1982 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1983 filemon_callback(ipf);
1985 return OOP_CONTINUE;
1988 static int filemon_method_init(void) {
1989 filemon_inotify_fd= inotify_init();
1990 if (filemon_inotify_fd<0) {
1991 syswarn("could not initialise inotify: inotify_init failed");
1995 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1997 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2001 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2003 /*---------- filemon dummy implementation ----------*/
2005 #if !defined(HAVE_FILEMON)
2007 struct Filemon_Perfile { int dummy; };
2009 static int filemon_method_init(void) { return 0; }
2010 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2011 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2013 #endif /* !HAVE_FILEMON */
2015 /*---------- filemon generic interface ----------*/
2017 static void filemon_start(InputFile *ipf) {
2018 assert(!ipf->filemon);
2020 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
2021 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
2022 filemon_method_startfile(ipf, ipf->filemon);
2025 static void filemon_stop(InputFile *ipf) {
2026 if (!ipf->filemon) return;
2027 filemon_method_stopfile(ipf, ipf->filemon);
2032 static void filemon_callback(InputFile *ipf) {
2033 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2036 /*---------- interface to start and stop an input file ----------*/
2038 static const oop_rd_style feedfile_rdstyle= {
2039 OOP_RD_DELIM_STRIP, '\n',
2041 OOP_RD_SHORTREC_LONG,
2044 static void inputfile_reading_start(InputFile *ipf) {
2046 ipf->readable.on_readable= tailing_on_readable;
2047 ipf->readable.on_cancel= tailing_on_cancel;
2048 ipf->readable.try_read= tailing_try_read;
2049 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2050 ipf->readable.delete_kill= 0;
2052 ipf->readable_callback= 0;
2053 ipf->readable_callback_user= 0;
2055 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2058 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2059 feedfile_got_article,ipf, feedfile_read_err, ipf);
2060 if (r) sysdie("unable start reading feedfile %s",ipf->path);
2063 static void inputfile_reading_stop(InputFile *ipf) {
2065 oop_rd_cancel(ipf->rd);
2066 oop_rd_delete(ipf->rd);
2068 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2072 /*========== interaction with innd - state machine ==========*/
2074 /* See official state diagram at top of file. We implement
2085 |`---------------------------------------------------.
2087 |`---------------- - - - |
2088 D ENOENT | D EXISTS see OVERALL STATES diagram |
2089 | for full startup logic |
2092 | ============ try to |
2098 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
2099 ^ | hardlink F to D |
2102 | | our handle onto F is now onto D |
2105 | |<-------------------<---------------------<---------+
2107 | | spawn inndcomm flush |
2109 | ================== |
2110 | FLUSHING[-ABSENT] |
2112 | main D tail/none |
2113 | ================== |
2115 | | INNDCOMM FLUSH FAILS ^
2116 | |`----------------------->----------. |
2118 | | NO SUCH SITE V |
2119 ^ |`--------------->----. ==================== |
2120 | | \ FLUSHFAILED[-ABSENT] |
2122 | | FLUSH OK \ main D tail/none |
2123 | | open F \ ==================== |
2125 | | \ | TIME TO RETRY |
2126 | |`------->----. ,---<---'\ `----------------'
2127 | | D NONE | | D NONE `----.
2129 | ============= V V ============
2130 | SEPARATED-1 | | DROPPING-1
2131 | flsh->rd!=0 | | flsh->rd!=0
2132 | [Separated] | | [Dropping]
2133 | main F idle | | main none
2134 | old D tail | | old D tail
2135 | ============= | | ============
2137 ^ | EOF ON D | | defer | EOF ON D
2139 | =============== | | ===============
2140 | SEPARATED-2 | | DROPPING-2
2141 | flsh->rd==0 | V flsh->rd==0
2142 | [Finishing] | | [Dropping]
2143 | main F tail | `. main none
2144 | old D closed | `. old D closed
2145 | =============== V `. ===============
2147 | | ALL D PROCESSED `. | ALL D PROCESSED
2148 | V install defer as backlog `. | install defer
2149 ^ | close D `. | close D
2150 | | unlink D `. | unlink D
2153 `----------' ==============
2173 static void startup_set_input_file(InputFile *f) {
2174 assert(!main_input_file);
2176 inputfile_reading_start(f);
2179 static void statemc_lock(void) {
2181 struct stat stab, stabf;
2184 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2185 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2188 memset(&fl,0,sizeof(fl));
2190 fl.l_whence= SEEK_SET;
2191 int r= fcntl(lockfd, F_SETLK, &fl);
2193 if (errno==EACCES || isewouldblock(errno)) {
2194 if (quiet_multiple) exit(0);
2195 fatal("another duct holds the lockfile");
2197 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2200 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2202 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2204 if (!lock_noent && samefile(&stab, &stabf))
2207 xclose(lockfd, "stale lockfile ", path_lock);
2210 FILE *lockfile= fdopen(lockfd, "w");
2211 if (!lockfile) sysdie("fdopen lockfile");
2213 int r= ftruncate(lockfd, 0);
2214 if (r) sysdie("truncate lockfile to write new info");
2216 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2217 (unsigned long)self_pid,
2218 sitename, feedfile, remote_host) == EOF ||
2220 sysfatal("write info to lockfile %s", path_lock);
2222 debug("startup: locked");
2225 static void statemc_init(void) {
2226 struct stat stabdefer;
2228 search_backlog_file();
2231 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2233 debug("startup: ductdefer ENOENT");
2235 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2236 switch (stabdefer.st_nlink==1) {
2238 open_defer(); /* so that we will later close it and rename it */
2241 xunlink(path_defer, "stale defer file link"
2242 " (presumably hardlink to backlog file)");
2245 die("defer file %s has unexpected link count %d",
2246 path_defer, stabdefer.st_nlink);
2250 struct stat stab_f, stab_d;
2253 InputFile *file_d= open_input_file(path_flushing);
2254 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2256 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2258 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2259 debug("startup: F==D => Hardlinked");
2260 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2265 debug("startup: F ENOENT => Moved");
2266 if (file_d) startup_set_input_file(file_d);
2267 spawn_inndcomm_flush("feedfile missing at startup");
2268 /* => Flushing, sms:=FLUSHING */
2271 debug("startup: F!=D => Separated");
2272 startup_set_input_file(file_d);
2273 SMS(SEPARATED, 0, "found both old and current feed files");
2275 debug("startup: F exists, D ENOENT => Normal");
2276 InputFile *file_f= open_input_file(feedfile);
2277 if (!file_f) die("feed file vanished during startup");
2278 startup_set_input_file(file_f);
2279 SMS(NORMAL, flushfail_retry_periods, "normal startup");
2284 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2285 assert(sms == sm_NORMAL);
2287 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2289 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2290 (unsigned long)target_max_feedfile_size,
2293 int r= link(feedfile, path_flushing);
2294 if (r) sysfatal("link feedfile %s to flushing file %s",
2295 feedfile, path_flushing);
2298 xunlink(feedfile, "old feedfile link");
2301 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2304 static void statemc_period_poll(void) {
2305 if (!sm_period_counter) return;
2306 sm_period_counter--;
2307 assert(sm_period_counter>=0);
2309 if (sm_period_counter) return;
2312 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2314 case sm_FLUSHFAILED:
2315 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2322 static int inputfile_is_done(InputFile *ipf) {
2324 if (ipf->inprogress) return 0; /* new article in the meantime */
2325 if (ipf->rd) return 0; /* not had EOF */
2329 static void notice_processed(InputFile *ipf, const char *what,
2331 #define RCI_NOTHING(x) /* nothing */
2332 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2333 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2335 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2337 info("processed %s%s read=%d(+%dbl,+%derr)"
2338 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2339 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2342 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2343 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2344 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2345 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2346 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2347 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2353 static void statemc_check_backlog_done(void) {
2354 InputFile *ipf= backlog_input_file;
2355 if (!inputfile_is_done(ipf)) return;
2357 const char *slash= strrchr(ipf->path, '/');
2358 const char *leaf= slash ? slash+1 : ipf->path;
2359 const char *under= strchr(slash, '_');
2360 const char *rest= under ? under+1 : leaf;
2361 if (!strncmp(rest,"backlog",7)) rest += 7;
2362 notice_processed(ipf,"backlog:",rest);
2364 close_input_file(ipf);
2365 if (unlink(ipf->path)) {
2366 if (errno != ENOENT)
2367 sysdie("could not unlink processed backlog file %s", ipf->path);
2368 warn("backlog file %s vanished while we were reading it"
2369 " so we couldn't remove it (but it's done now, anyway)",
2373 backlog_input_file= 0;
2374 search_backlog_file();
2378 static void statemc_check_flushing_done(void) {
2379 InputFile *ipf= flushing_input_file;
2380 if (!inputfile_is_done(ipf)) return;
2382 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2384 notice_processed(ipf,"feedfile",0);
2388 xunlink(path_flushing, "old flushing file");
2390 close_input_file(flushing_input_file);
2391 free(flushing_input_file);
2392 flushing_input_file= 0;
2394 if (sms==sm_SEPARATED) {
2395 notice("flush complete");
2396 SMS(NORMAL, 0, "flush complete");
2397 } else if (sms==sm_DROPPING) {
2398 SMS(DROPPED, 0, "old flush complete");
2399 search_backlog_file();
2400 notice("feed dropped, but will continue until backlog is finished");
2404 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2406 assert(!inputfile_is_done(main_input_file));
2407 statemc_check_flushing_done();
2408 statemc_check_backlog_done();
2409 return OOP_CONTINUE;
2412 static void queue_check_input_done(void) {
2413 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2416 static void statemc_setstate(StateMachineState newsms, int periods,
2417 const char *forlog, const char *why) {
2419 sm_period_counter= periods;
2421 const char *xtra= "";
2424 case sm_FLUSHFAILED:
2425 if (!main_input_file) xtra= "-ABSENT";
2429 xtra= flushing_input_file->rd ? "-1" : "-2";
2435 info("%s%s[%d] %s",forlog,xtra,periods,why);
2437 info("%s%s %s",forlog,xtra,why);
2441 /*---------- defer and backlog files ----------*/
2443 static void open_defer(void) {
2448 defer= fopen(path_defer, "a+");
2449 if (!defer) sysfatal("could not open defer file %s", path_defer);
2451 /* truncate away any half-written records */
2453 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2455 if (stab.st_size > LONG_MAX)
2456 die("defer file %s size is far too large", path_defer);
2461 long orgsize= stab.st_size;
2462 long truncto= stab.st_size;
2464 if (!truncto) break; /* was only (if anything) one half-truncated record */
2465 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2466 sysdie("seek in defer file %s while truncating partial", path_defer);
2471 sysdie("failed read from defer file %s", path_defer);
2473 die("defer file %s shrank while we were checking it!", path_defer);
2479 if (stab.st_size != truncto) {
2480 warn("truncating half-record at end of defer file %s -"
2481 " shrinking by %ld bytes from %ld to %ld",
2482 path_defer, orgsize - truncto, orgsize, truncto);
2485 sysfatal("could not flush defer file %s", path_defer);
2486 if (ftruncate(fileno(defer), truncto))
2487 sysdie("could not truncate defer file %s", path_defer);
2490 info("continuing existing defer file %s (%ld bytes)",
2491 path_defer, orgsize);
2493 if (fseek(defer, truncto, SEEK_SET))
2494 sysdie("could not seek to new end of defer file %s", path_defer);
2497 static void close_defer(void) {
2502 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2504 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2507 time_t now= xtime();
2509 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2511 (unsigned long)stab.st_ino);
2512 if (link(path_defer, backlog))
2513 sysfatal("could not install defer file %s as backlog file %s",
2514 path_defer, backlog);
2515 if (unlink(path_defer))
2516 sysdie("could not unlink old defer link %s to backlog file %s",
2517 path_defer, backlog);
2521 if (until_backlog_nextscan < 0 ||
2522 until_backlog_nextscan > backlog_retry_minperiods + 1)
2523 until_backlog_nextscan= backlog_retry_minperiods + 1;
2526 static void poll_backlog_file(void) {
2527 if (until_backlog_nextscan < 0) return;
2528 if (until_backlog_nextscan-- > 0) return;
2529 search_backlog_file();
2532 static void search_backlog_file(void) {
2533 /* returns non-0 iff there are any backlog files */
2538 const char *oldest_path=0;
2539 time_t oldest_mtime=0, now;
2541 if (backlog_input_file) return;
2545 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2549 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2551 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2553 for (i=0; i<gl.gl_pathc; i++) {
2554 const char *path= gl.gl_pathv[i];
2556 if (strchr(path,'#') || strchr(path,'~')) {
2557 debug("backlog file search skipping %s", path);
2560 r= stat(path, &stab);
2562 syswarn("failed to stat backlog file %s", path);
2565 if (!S_ISREG(stab.st_mode)) {
2566 warn("backlog file %s is not a plain file (or link to one)", path);
2569 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2571 oldest_mtime= stab.st_mtime;
2574 case GLOB_NOMATCH: /* fall through */
2577 sysdie("glob expansion of backlog pattern %s gave unexpected"
2578 " nonzero (error?) return value %d", globpat_backlog, r);
2582 debug("backlog scan: none");
2584 if (sms==sm_DROPPED) {
2585 notice("feed dropped and our work is complete");
2586 xunlink(path_lock, "lockfile for old feed");
2589 until_backlog_nextscan= backlog_spontrescan_periods;
2594 double age= difftime(now, oldest_mtime);
2595 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2597 if (age_deficiency <= 0) {
2598 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2599 age, age_deficiency, oldest_path);
2601 backlog_input_file= open_input_file(oldest_path);
2602 if (!backlog_input_file) {
2603 warn("backlog file %s vanished as we opened it", oldest_path);
2607 inputfile_reading_start(backlog_input_file);
2608 until_backlog_nextscan= -1;
2612 until_backlog_nextscan= age_deficiency / period_seconds;
2614 if (backlog_spontrescan_periods >= 0 &&
2615 until_backlog_nextscan > backlog_spontrescan_periods)
2616 until_backlog_nextscan= backlog_spontrescan_periods;
2618 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2619 age, age_deficiency, until_backlog_nextscan, oldest_path);
2626 /*========== flushing the feed ==========*/
2628 static pid_t inndcomm_child;
2629 static int inndcomm_sentinel_fd;
2631 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2632 assert(inndcomm_child);
2633 assert(fd == inndcomm_sentinel_fd);
2634 int status= xwaitpid(&inndcomm_child, "inndcomm");
2637 cancel_fd_read_except(fd);
2638 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2639 inndcomm_sentinel_fd= 0;
2641 assert(!flushing_input_file);
2643 if (WIFEXITED(status)) {
2644 switch (WEXITSTATUS(status)) {
2646 case INNDCOMMCHILD_ESTATUS_FAIL:
2649 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2650 warn("feed has been dropped by innd, finishing up");
2651 flushing_input_file= main_input_file;
2652 tailing_queue_readable(flushing_input_file);
2653 /* we probably previously returned EAGAIN from our fake read method
2654 * when in fact we were at EOF, so signal another readable event
2655 * so we actually see the EOF */
2659 if (flushing_input_file) {
2660 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2663 SMS(DROPPED, 0, "feed dropped by innd");
2664 search_backlog_file();
2666 return OOP_CONTINUE;
2670 flushing_input_file= main_input_file;
2671 tailing_queue_readable(flushing_input_file);
2673 main_input_file= open_input_file(feedfile);
2674 if (!main_input_file)
2675 die("flush succeeded but feedfile %s does not exist!", feedfile);
2677 if (flushing_input_file) {
2678 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2681 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2683 return OOP_CONTINUE;
2686 goto unexpected_exitstatus;
2689 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2690 warn("flush timed out trying to talk to innd");
2693 unexpected_exitstatus:
2694 report_child_status("inndcomm child", status);
2698 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2699 return OOP_CONTINUE;
2702 static void inndcommfail(const char *what) {
2703 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2704 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2707 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2710 notice("flushing %s",why);
2712 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2713 assert(!inndcomm_child);
2714 assert(!inndcomm_sentinel_fd);
2716 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2718 inndcomm_child= xfork("inndcomm child");
2720 if (!inndcomm_child) {
2721 const char *flushargv[2]= { sitename, 0 };
2725 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2726 /* parent spots the autoclose of pipefds[1] when we die or exit */
2728 alarm(inndcomm_flush_timeout);
2729 r= ICCopen(); if (r) inndcommfail("connect");
2730 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2731 if (!r) exit(0); /* yay! */
2733 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2734 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2735 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2738 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2739 inndcomm_sentinel_fd= pipefds[0];
2740 assert(inndcomm_sentinel_fd);
2741 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2743 SMS(FLUSHING, 0, why);
2746 /*========== main program ==========*/
2748 static void postfork_inputfile(InputFile *ipf) {
2750 xclose(ipf->fd, "(in child) input file ", ipf->path);
2753 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2754 /* we have no stdio streams that are buffered long-term */
2756 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2759 static void postfork(void) {
2760 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2761 sysdie("(in child) failed to reset SIGPIPE");
2763 postfork_inputfile(main_input_file);
2764 postfork_inputfile(flushing_input_file);
2767 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2768 conn_closefd(conn,"(in child) ");
2770 postfork_stdio(defer, "defer file ", path_defer);
2773 #define EVERY(what, interval_sec, interval_usec, body) \
2774 static struct timeval what##_timeout = { interval_sec, interval_usec }; \
2775 static void what##_schedule(void); \
2776 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2778 what##_schedule(); \
2779 return OOP_CONTINUE; \
2781 static void what##_schedule(void) { \
2782 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2785 EVERY(filepoll, 5,0, ({
2786 if (main_input_file && main_input_file->readable_callback)
2787 filemon_callback(main_input_file);
2790 static char *debug_report_ipf(InputFile *ipf) {
2791 if (!ipf) return xasprintf("none");
2793 const char *slash= strrchr(ipf->path,'/');
2794 const char *path= slash ? slash+1 : ipf->path;
2796 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2798 ipf->inprogress, (long)ipf->offset,
2799 ipf->fd, ipf->rd ? "+" : "");
2802 EVERY(period, -1,0, ({
2803 char *dipf_main= debug_report_ipf(main_input_file);
2804 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2805 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2808 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2809 " input_files main:%s old:%s flushing:%s"
2810 " children connecting=%ld inndcomm=%ld"
2812 sms_names[sms], sm_period_counter,
2813 conns.count, queue.count, until_connect,
2814 dipf_main, dipf_flushing, dipf_backlog,
2815 (long)connecting_child, (long)inndcomm_child
2819 free(dipf_flushing);
2822 if (until_connect) until_connect--;
2824 poll_backlog_file();
2825 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2826 statemc_period_poll();
2827 check_assign_articles();
2832 /*========== option parsing ==========*/
2834 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2835 static void vbadusage(const char *fmt, va_list al) {
2836 char *m= xvasprintf(fmt,al);
2837 fprintf(stderr, "bad usage: %s\n"
2838 "say --help for help, or read the manpage\n",
2841 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2845 /*---------- generic option parser ----------*/
2847 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2848 static void badusage(const char *fmt, ...) {
2855 of_seconds= 001000u,
2856 of_boolean= 002000u,
2859 typedef struct Option Option;
2860 typedef void OptionParser(const Option*, const char *val);
2864 const char *lng, *formarg;
2870 static void parse_options(const Option *options, char ***argvp) {
2871 /* on return *argvp is first non-option arg; argc is not updated */
2874 const char *arg= *++(*argvp);
2876 if (*arg != '-') break;
2877 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2879 while ((a= *++arg)) {
2883 char *equals= strchr(arg,'=');
2884 int len= equals ? (equals - arg) : strlen(arg);
2885 for (o=options; o->shrt || o->lng; o++)
2886 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2888 badusage("unknown long option --%s",arg);
2891 if (equals) badusage("option --%s does not take a value",o->lng);
2893 } else if (equals) {
2897 if (!arg) badusage("option --%s needs a value for %s",
2898 o->lng, o->formarg);
2901 break; /* eaten the whole argument now */
2903 for (o=options; o->shrt || o->lng; o++)
2906 badusage("unknown short option -%c",a);
2913 if (!arg) badusage("option -%c needs a value for %s",
2914 o->shrt, o->formarg);
2917 break; /* eaten the whole argument now */
2923 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
2925 static void print_options(const Option *options, FILE *f) {
2927 for (o=options; o->shrt || o->lng; o++) {
2928 char shrt[2] = { o->shrt, 0 };
2929 char *optspec= xasprintf("%s%s%s%s%s",
2930 o->shrt ? "-" : "", shrt,
2931 o->shrt && o->lng ? "|" : "",
2932 DELIMPERHAPS("--", o->lng));
2933 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
2938 /*---------- specific option types ----------*/
2940 static void op_integer(const Option *o, const char *val) {
2943 unsigned long ul= strtoul(val,&ep,10);
2944 if (*ep || ep==val || errno || ul>INT_MAX)
2945 badusage("bad integer value for %s",o->lng);
2946 int *store= o->store;
2950 static void op_double(const Option *o, const char *val) {
2951 int *store= o->store;
2954 *store= strtod(val, &ep);
2955 if (*ep || ep==val || errno)
2956 badusage("bad floating point value for %s",o->lng);
2959 static void op_string(const Option *o, const char *val) {
2960 const char **store= o->store;
2964 static void op_seconds(const Option *o, const char *val) {
2965 int *store= o->store;
2969 double v= strtod(val,&ep);
2970 if (ep==val) badusage("bad time/duration value for %s",o->lng);
2972 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
2973 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
2974 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
2975 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
2976 else if (!strcmp(ep,"das")) unit= 10;
2977 else if (!strcmp(ep,"hs")) unit= 100;
2978 else if (!strcmp(ep,"ks")) unit= 1000;
2979 else if (!strcmp(ep,"Ms")) unit= 1000000;
2980 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2984 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2988 static void op_setint(const Option *o, const char *val) {
2989 int *store= o->store;
2993 /*---------- specific options ----------*/
2995 static void help(const Option *o, const char *val);
2997 static const Option innduct_options[]= {
2998 {'f',"feedfile", "F", &feedfile, op_string },
2999 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
3000 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
3001 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
3002 {0,"inndconf", "F", &inndconffile, op_string },
3003 {'P',"port", "PORT", &port, op_integer },
3004 {0,"help", 0, 0, help },
3006 {0,"max-connections", "N", &max_connections, op_integer },
3007 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
3008 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
3009 {0,"period-interval", "TIME", &period_seconds, op_seconds },
3011 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
3012 {0,"stuck-flush-timeout","TIME", &inndcomm_flush_timeout, op_seconds },
3014 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
3015 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
3017 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
3018 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
3019 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3020 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3021 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
3022 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
3024 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
3025 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
3030 static void printusage(FILE *f) {
3031 fputs("usage: innduct [options] site [fqdn]\n"
3032 "available options are:\n", f);
3033 print_options(innduct_options, f);
3036 static void help(const Option *o, const char *val) {
3038 if (ferror(stdout) || fflush(stdout)) {
3039 perror("innduct: writing help");
3045 static void convert_to_periods_rndup(int *store) {
3046 *store += period_seconds-1;
3047 *store /= period_seconds;
3050 int main(int argc, char **argv) {
3056 parse_options(innduct_options, &argv);
3061 if (!sitename) badusage("need site name argument");
3062 remote_host= *argv++;
3063 if (*argv) badusage("too many non-option arguments");
3067 if (!remote_host) remote_host= sitename;
3069 if (nocheck_thresh < 0 || nocheck_thresh > 100)
3070 badusage("nocheck threshold percentage must be between 0..100");
3071 nocheck_thresh *= 0.01;
3073 if (nocheck_decay < 0.1)
3074 badusage("nocheck decay articles must be at least 0.1");
3075 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3077 convert_to_periods_rndup(&reconnect_delay_periods);
3078 convert_to_periods_rndup(&flushfail_retry_periods);
3079 convert_to_periods_rndup(&backlog_retry_minperiods);
3080 convert_to_periods_rndup(&backlog_spontrescan_periods);
3081 convert_to_periods_rndup(&spontaneous_flush_periods);
3082 convert_to_periods_rndup(&need_activity_periods);
3084 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3085 badusage("bad input data ratio must be between 0..100");
3086 max_bad_data_ratio *= 0.01;
3089 innconf_read(inndconffile);
3090 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3091 } else if (!feedfile[0]) {
3092 badusage("feed filename must be nonempty");
3093 } else if (feedfile[strlen(feedfile)-1]=='/') {
3094 feedfile= xasprintf("%s%s",feedfile,sitename);
3097 const char *feedfile_forbidden= "?*[~#";
3099 while ((c= *feedfile_forbidden++))
3100 if (strchr(feedfile, c))
3101 badusage("feed filename may not contain metacharacter %c",c);
3105 path_lock= xasprintf("%s_lock", feedfile);
3106 path_flushing= xasprintf("%s_flushing", feedfile);
3107 path_defer= xasprintf("%s_defer", feedfile);
3108 path_control= xasprintf("%s_control", feedfile);
3109 globpat_backlog= xasprintf("%s_backlog*", feedfile);
3111 oop_source_sys *sysloop= oop_sys_new();
3112 if (!sysloop) sysdie("could not create liboop event loop");
3113 loop= (oop_source*)sysloop;
3115 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3116 sysdie("could not ignore SIGPIPE");
3121 if (become_daemon) {
3123 for (i=3; i<255; i++)
3124 /* do this now before we open syslog, etc. */
3126 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3128 int null= open("/dev/null",O_RDWR);
3129 if (null<0) sysfatal("failed to open /dev/null");
3133 xclose(null, "/dev/null original fd",0);
3135 pid_t child1= xfork("daemonise first fork");
3136 if (child1) _exit(0);
3138 pid_t sid= setsid();
3139 if (sid != child1) sysfatal("setsid failed");
3141 pid_t child2= xfork("daemonise second fork");
3142 if (child2) _exit(0);
3146 if (self_pid==-1) sysdie("getpid");
3157 if (!filemon_method_init()) {
3158 warn("no file monitoring available, polling");
3159 filepoll_schedule();
3162 period_timeout.tv_sec= period_seconds;
3169 void *r= oop_sys_run(sysloop);
3170 assert(r == OOP_ERROR);
3171 sysdie("event loop failed");