5 [740] <sit> info: processed feedfile(null) read=4(+0bl,+6err) offered=5(ch5,nc0) accepted=0(ch0+nc0) unwanted=0(0id+0bd+0nc) rejected=0(0id+0bd+0nc) deferred=0(0id+0bd+0nc) missing=2(0id+2bd+0nc) connretry=0(0id+0bd+0nc)
7 also unwanted should be nonzero I think
9 [740] <sit> warning: corrupted file: /home/ian/things/Innfeed/inn2-2.4.5/fee, offset 349: line partially blanked: in ` @050000002D130000006A0000000000000000@ <mi'..
13 * some per-conn info thing for control
16 * - actually do something with readable on control master
17 * - option for realsockdir
18 * - option for filepoll
19 * - option for no inotify
20 * - manpage: document control master stuff
21 * - manpage: innconf is used for communicating with innd
23 * build-lfs/backends/innduct --no-daemon -f `pwd`/fee sit dom
27 * Newsfeeds file entries should look like this:
28 * host.name.of.site[/exclude,exclude,...]\
29 * :pattern,pattern...[/distribution,distribution...]\
33 * sitename[/exclude,exclude,...]\
34 * :pattern,pattern...[/distribution,distribution...]\
40 * or might be blanked out
41 * <spc><spc><spc><spc>....
43 * F site.name main feed file
44 * opened/created, then written, by innd
47 * tokens blanked out by duct when processed
48 * site.name_lock lock preventing multiple ducts
49 * to hold lock must open,F_SETLK[W]
50 * and then stat to check that locked file
51 * still has name site.name_lock
52 * holder of this lock is "duct"
53 * (only) lockholder may remove the lockfile
54 * D site.name_flushing temporary feed file during flush (or crash)
55 * hardlink created by duct
57 * site.name_defer 431'd articles, still being written,
58 * created, written, used by duct
60 * site.name_backlog.<date>.<inum>
61 * 431'd articles, ready for innxmit or duct
62 * created (link/mv) by duct
63 * site.name_backlog<anything-else> (where <anything-else> does not
64 * contain '#' or '~') eg
65 * site.name_backlog.manual
66 * anything the sysadmin likes (eg, feed files
67 * from old feeds to be merged into this one)
68 * created (link/mv) by admin
69 * may be symlinks (in which case links
70 * may be written through, but only links
73 * It is safe to remove backlog files manually,
74 * if it's desired to throw away the backlog.
76 * Backlog files are also processed by innduct. We find the oldest
77 * backlog file which is at least a certain amount old, and feed it
78 * back into our processing. When every article in it has been read
79 * and processed, we unlink it and look for another backlog file.
81 * If we don't have a backlog file that we're reading, we close the
82 * defer file that we're writing and make it into a backlog file at
83 * the first convenient opportunity.
94 | | <----------------<---------------------------------'|
100 | F: innd writing, duct reading |
103 | | duct decides time to flush |
104 | | duct makes hardlink |
106 | V <------------------------'|
108 | F == D: innd writing, duct reading both exist |
111 | | <-----------<-------------<--'|
112 | | open D F ENOENT |
115 | V <---------------------. |
118 | D: innd writing, duct reading; or ENOENT | |
120 | | duct requests flush of feed | |
121 | | (others can too, harmlessly) | |
125 | D: innd flushing, duct; or ENOENT | |
127 | | inndcomm flush fails | |
128 | |`-------------------------->------------------' |
130 | | inndcomm reports no such site |
131 | |`---------------------------------------------------- | -.
133 | | innd finishes writing D, creates F | |
134 | | inndcomm reports flush successful | |
137 | Separated <----------------' |
138 | F: innd writing F!=D /
139 | D: duct reading; or ENOENT both exist /
141 | | duct gets to the end of D /
142 | | duct opens F too /
145 | F: innd writing, duct reading |
146 | D: duct finishing V
148 | | duct finishes processing D F: ENOENT
149 | V duct unlinks D D: duct reading
151 `--<--' | duct finishes
161 "duct reading" means innduct is reading the file but also
162 overwriting processed tokens.
166 * rune for printing diagrams:
168 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
173 /*============================== PROGRAM ==============================*/
175 #define _GNU_SOURCE 1
181 #include "inndcomm.h"
183 #include "inn/list.h"
184 #include "inn/innconf.h"
187 #include <sys/types.h>
188 #include <sys/wait.h>
189 #include <sys/stat.h>
190 #include <sys/socket.h>
209 #include <oop-read.h>
211 /*----- general definitions, probably best not changed -----*/
213 #define CONNCHILD_ESTATUS_STREAM 24
214 #define CONNCHILD_ESTATUS_NOSTREAM 25
216 #define INNDCOMMCHILD_ESTATUS_FAIL 26
217 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
219 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
220 #define MAX_CONTROL_COMMAND 1000
222 #define VA va_list al; va_start(al,fmt)
223 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
224 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
226 /*----- doubly linked lists -----*/
228 #define ISNODE(T) struct node list_node
231 union { struct list li; T *for_type; } u; \
235 #define NODE(n) (assert((void*)&(n)->list_node == (n)), &(n)->list_node)
237 #define LIST_CHECKCANHAVENODE(l,n) \
238 ((void)((n) == ((l).u.for_type))) /* just for the type check */
240 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
241 ( LIST_CHECKCANHAVENODE(l,n), \
242 list_addsomehow(&(l).u.li, NODE((n))), \
246 #define LIST_REMSOMEHOW(l,list_remsomehow) \
247 ( (typeof((l).u.for_type)) \
250 list_remsomehow(&(l).u.li) ) \
256 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
257 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
258 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
259 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
261 #define LIST_INIT(l) ((l).count=0, list_new(&(l).u.li))
262 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
263 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
264 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
266 #define LIST_REMOVE(l,n) \
267 ( LIST_CHECKCANHAVENODE(l,n), \
268 list_remove(NODE((n))), \
272 #define LIST_INSERT(l,n,pred) \
273 ( LIST_CHECKCANHAVENODE(l,n), \
274 LIST_CHECKCANHAVENODE(l,pred), \
275 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
279 /*----- type predeclarations -----*/
281 typedef struct Conn Conn;
282 typedef struct Article Article;
283 typedef struct InputFile InputFile;
284 typedef struct XmitDetails XmitDetails;
285 typedef struct Filemon_Perfile Filemon_Perfile;
286 typedef enum StateMachineState StateMachineState;
291 /*----- function predeclarations -----*/
293 static void conn_maybe_write(Conn *conn);
294 static void conn_make_some_xmits(Conn *conn);
295 static void *conn_write_some_xmits(Conn *conn);
297 static void xmit_free(XmitDetails *d);
299 #define SMS(newstate, periods, why) \
300 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
301 static void statemc_setstate(StateMachineState newsms, int periods,
302 const char *forlog, const char *why);
304 static void statemc_start_flush(const char *why); /* Normal => Flushing */
305 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
307 static void article_done(Conn *conn, Article *art, int whichcount);
309 static void check_assign_articles(void);
310 static void queue_check_input_done(void);
312 static void statemc_check_flushing_done(void);
313 static void statemc_check_backlog_done(void);
315 static void postfork(void);
316 static void period(void);
318 static void open_defer(void);
319 static void close_defer(void);
320 static void search_backlog_file(void);
322 static void inputfile_reading_start(InputFile *ipf);
323 static void inputfile_reading_stop(InputFile *ipf);
325 static void filemon_start(InputFile *ipf);
326 static void filemon_stop(InputFile *ipf);
327 static void filemon_callback(InputFile *ipf);
329 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
330 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
332 static const oop_rd_style peer_rd_style;
333 static oop_rd_call peer_rd_err, peer_rd_ok;
335 /*----- configuration options -----*/
336 /* when changing defaults, remember to update the manpage */
338 static const char *sitename, *remote_host;
339 static const char *feedfile, *realsockdir="/tmp/innduct.control";
340 static int quiet_multiple=0;
341 static int become_daemon=1;
342 static int try_stream=1;
344 static const char *inndconffile;
346 static int max_connections=10;
347 static int max_queue_per_conn=200;
348 static int target_max_feedfile_size=100000;
349 static int period_seconds=60;
351 static int connection_setup_timeout=200;
352 static int inndcomm_flush_timeout=100;
354 static double nocheck_thresh= 95.0; /* converted from percentage by main */
355 static double nocheck_decay= 100; /* conv'd from articles to lambda by main */
357 /* all these are initialised to seconds, and converted to periods in main */
358 static int reconnect_delay_periods=1000;
359 static int flushfail_retry_periods=1000;
360 static int backlog_retry_minperiods=50;
361 static int backlog_spontrescan_periods=300;
362 static int spontaneous_flush_periods=100000;
363 static int need_activity_periods=1000;
365 static double max_bad_data_ratio= 1; /* conv'd from percentage by main */
366 static int max_bad_data_initial= 30;
367 /* in one corrupt 4096-byte block the number of newlines has
368 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
371 /*----- statistics -----*/
373 typedef enum { /* in queue in conn->sent */
374 art_Unchecked, /* not checked, not sent checking */
375 art_Wanted, /* checked, wanted sent body as requested */
376 art_Unsolicited, /* - sent body without check */
380 #define RESULT_COUNTS(RCS,RCN) \
389 #define RCI_TRIPLE_FMT_BASE "%d (id=%d,bod=%d,nc=%d)"
390 #define RCI_TRIPLE_VALS_BASE(counts,x) \
391 counts[art_Unchecked] x \
392 + counts[art_Wanted] x \
393 + counts[art_Unsolicited] x, \
394 counts[art_Unchecked] x \
395 , counts[art_Wanted] x \
396 , counts[art_Unsolicited] x
399 #define RC_INDEX(x) RC_##x,
400 RESULT_COUNTS(RC_INDEX, RC_INDEX)
405 /*----- transmission buffers -----*/
410 xk_Malloc, xk_Const, xk_Artdata
422 /*----- core operational data structure types -----*/
425 /* This is also an instance of struct oop_readable */
426 struct oop_readable readable; /* first */
427 oop_readable_call *readable_callback;
428 void *readable_callback_user;
431 Filemon_Perfile *filemon;
433 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
434 long inprogress; /* no. of articles read but not processed */
438 int counts[art_MaxState][RCI_max];
439 int readcount_ok, readcount_blank, readcount_err;
454 #define SMS_LIST(X) \
462 enum StateMachineState {
463 #define SMS_DEF_ENUM(s) sm_##s,
464 SMS_LIST(SMS_DEF_ENUM)
467 static const char *sms_names[]= {
468 #define SMS_DEF_NAME(s) #s ,
469 SMS_LIST(SMS_DEF_NAME)
475 int fd; /* may be 0, meaning closed (during construction/destruction) */
476 oop_read *rd; /* likewise */
477 int max_queue, stream, quitting;
478 int since_activity; /* periods */
479 ArticleList waiting; /* not yet told peer */
480 ArticleList priority; /* peer says send it now */
481 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
482 struct iovec xmit[CONNIOVS];
483 XmitDetails xmitd[CONNIOVS];
488 /*----- general operational variables -----*/
490 /* main initialises */
491 static oop_source *loop;
492 static ConnList conns;
493 static ArticleList queue;
494 static char *path_lock, *path_flushing, *path_defer, *path_control;
495 static char *globpat_backlog;
496 static pid_t self_pid;
498 /* statemc_init initialises */
499 static StateMachineState sms;
501 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
502 static int sm_period_counter;
504 /* initialisation to 0 is good */
505 static int until_connect, until_backlog_nextscan;
506 static double accept_proportion;
507 static int nocheck, nocheck_reported;
509 /* for simulation, debugging, etc. */
510 int simulate_flush= -1;
512 /*========== logging ==========*/
514 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
515 static void logcore(int sysloglevel, const char *fmt, ...) {
518 vsyslog(sysloglevel,fmt,al);
520 if (self_pid) fprintf(stderr,"[%lu] ",(unsigned long)self_pid);
521 vfprintf(stderr,fmt,al);
527 static void logv(int sysloglevel, const char *pfx, int errnoval,
528 const char *fmt, va_list al) PRINTF(5,0);
529 static void logv(int sysloglevel, const char *pfx, int errnoval,
530 const char *fmt, va_list al) {
531 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
532 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
533 msgbuf[sizeof(msgbuf)-1]= 0;
535 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
536 sysloglevel= LOG_ERR; /* run by wrong user, probably */
538 logcore(sysloglevel, "<%s>%s: %s%s%s",
539 sitename, pfx, msgbuf,
540 errnoval>=0 ? ": " : "",
541 errnoval>=0 ? strerror(errnoval) : "");
544 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
545 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
546 static void fn(const char *fmt, ...) { \
548 logv(sysloglevel, pfx, err, fmt, al); \
552 #define logwrap(fn, pfx, sysloglevel, err) \
553 static void fn(const char *fmt, ...) PRINTF(1,2); \
554 static void fn(const char *fmt, ...) { \
556 logv(sysloglevel, pfx, err, fmt, al); \
560 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
561 diewrap(die, " critical", LOG_CRIT, -1, 16);
563 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
564 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
566 logwrap(syswarn, " warning", LOG_WARNING, errno);
567 logwrap(warn, " warning", LOG_WARNING, -1);
569 logwrap(notice, " notice", LOG_NOTICE, -1);
570 logwrap(info, " info", LOG_INFO, -1);
571 logwrap(debug, " debug", LOG_DEBUG, -1);
574 /*========== utility functions etc. ==========*/
576 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
577 static char *xvasprintf(const char *fmt, va_list al) {
579 int rc= vasprintf(&str,fmt,al);
580 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
583 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
584 static char *xasprintf(const char *fmt, ...) {
586 char *str= xvasprintf(fmt,al);
591 static int close_perhaps(int *fd) {
592 if (*fd <= 0) return 0;
597 static void xclose(int fd, const char *what, const char *what2) {
599 if (r) sysdie("close %s%s",what,what2?what2:"");
601 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
602 if (*fd <= 0) return;
603 xclose(*fd,what,what2);
607 static pid_t xfork(const char *what) {
611 if (child==-1) sysfatal("cannot fork for %s",what);
612 debug("forked %s %ld", what, (unsigned long)child);
613 if (!child) postfork();
617 static void on_fd_read_except(int fd, oop_call_fd callback) {
618 loop->on_fd(loop, fd, OOP_READ, callback, 0);
619 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
621 static void cancel_fd_read_except(int fd) {
622 loop->cancel_fd(loop, fd, OOP_READ);
623 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
626 static void report_child_status(const char *what, int status) {
627 if (WIFEXITED(status)) {
628 int es= WEXITSTATUS(status);
630 warn("%s: child died with error exit status %d", what, es);
631 } else if (WIFSIGNALED(status)) {
632 int sig= WTERMSIG(status);
633 const char *sigstr= strsignal(sig);
634 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
636 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
638 warn("%s: child died due to unknown fatal signal %d%s",
639 what, sig, coredump);
641 warn("%s: child died with unknown wait status %d", what,status);
645 static int xwaitpid(pid_t *pid, const char *what) {
648 int r= kill(*pid, SIGKILL);
649 if (r) sysdie("cannot kill %s child", what);
651 pid_t got= waitpid(*pid, &status, 0);
652 if (got==-1) sysdie("cannot reap %s child", what);
653 if (got==0) die("cannot reap %s child", what);
660 static void xunlink(const char *path, const char *what) {
662 if (r) sysdie("can't unlink %s %s", path, what);
665 static time_t xtime(void) {
667 if (now==-1) sysdie("time(2) failed");
671 static void xgettimeofday(struct timeval *tv_r) {
672 int r= gettimeofday(tv_r,0);
673 if (r) sysdie("gettimeofday(2) failed");
676 static void xsetnonblock(int fd, int nonblocking) {
677 int errnoval= oop_fd_nonblock(fd, nonblocking);
678 if (errnoval) { errno= errnoval; sysdie("setnonblocking"); }
681 static void check_isreg(const struct stat *stab, const char *path,
683 if (!S_ISREG(stab->st_mode))
684 die("%s %s not a plain file (mode 0%lo)",
685 what, path, (unsigned long)stab->st_mode);
688 static void xfstat(int fd, struct stat *stab_r, const char *what) {
689 int r= fstat(fd, stab_r);
690 if (r) sysdie("could not fstat %s", what);
693 static void xfstat_isreg(int fd, struct stat *stab_r,
694 const char *path, const char *what) {
695 xfstat(fd, stab_r, what);
696 check_isreg(stab_r, path, what);
699 static void xlstat_isreg(const char *path, struct stat *stab,
700 int *enoent_r /* 0 means ENOENT is fatal */,
702 int r= lstat(path, stab);
704 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
705 sysdie("could not lstat %s %s", what, path);
707 if (enoent_r) *enoent_r= 0;
708 check_isreg(stab, path, what);
711 static int samefile(const struct stat *a, const struct stat *b) {
712 assert(S_ISREG(a->st_mode));
713 assert(S_ISREG(b->st_mode));
714 return (a->st_ino == b->st_ino &&
715 a->st_dev == b->st_dev);
718 static char *sanitise(const char *input) {
719 static char sanibuf[100]; /* returns pointer to this buffer! */
721 const char *p= input;
725 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
727 if (!c) { *q++= '\''; *q=0; break; }
728 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
729 sprintf(q,"\\x%02x",c);
735 static int isewouldblock(int errnoval) {
736 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
740 /*========== command and control connections ==========*/
742 static int control_master;
744 typedef struct ControlConn ControlConn;
746 void (*destroy)(ControlConn*);
752 struct sockaddr_un un;
757 static const oop_rd_style control_rd_style= {
758 OOP_RD_DELIM_STRIP, '\n',
760 OOP_RD_SHORTREC_FORBID
763 static void control_destroy(ControlConn *cc) {
767 static void control_checkouterr(ControlConn *cc /* may destroy*/) {
768 if (ferror(cc->out) | fflush(cc->out)) {
769 info("CTRL%d write error %s", cc->fd, strerror(errno));
774 static void control_prompt(ControlConn *cc /* may destroy*/) {
775 fprintf(cc->out, "%s| ", sitename);
776 control_checkouterr(cc);
779 typedef struct ControlCommand ControlCommand;
780 struct ControlCommand {
782 void (*f)(ControlConn *cc, const ControlCommand *ccmd,
783 const char *arg, size_t argsz);
788 static const ControlCommand control_commands[];
791 static void ccmd_##wh(ControlConn *cc, const ControlCommand *c, \
792 const char *arg, size_t argsz)
795 fputs("commands:\n", cc->out);
796 const ControlCommand *ccmd;
797 for (ccmd=control_commands; ccmd->cmd; ccmd++)
798 fprintf(cc->out, " %s\n", ccmd->cmd);
801 CCMD(period) { period(); }
802 CCMD(setintarg) { *(int*)c->xdata= atoi(arg); }
803 CCMD(setint) { *(int*)c->xdata= c->xval; }
805 static const ControlCommand control_commands[]= {
807 { "p", ccmd_period },
808 { "pretend flush", ccmd_setintarg, &simulate_flush },
809 { "poke sm", ccmd_setint, &sm_period_counter, 1 },
810 { "poke conn", ccmd_setint, &until_connect, 0 },
811 { "poke blscan", ccmd_setint, &until_backlog_nextscan, 0 },
812 { "wedge blscan", ccmd_setint, &until_backlog_nextscan, -1 },
816 static void *control_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
817 const char *errmsg, int errnoval,
818 const char *data, size_t recsz, void *cc_v) {
819 ControlConn *cc= cc_v;
822 info("CTRL%d closed", cc->fd);
827 if (recsz == 0) goto prompt;
829 const ControlCommand *ccmd;
830 for (ccmd=control_commands; ccmd->cmd; ccmd++) {
831 int l= strlen(ccmd->cmd);
832 if (recsz < l) continue;
833 if (recsz > l && data[l] != ' ') continue;
834 if (memcmp(data, ccmd->cmd, l)) continue;
836 int argl= (int)recsz - (l+1);
837 ccmd->f(cc, ccmd, argl>=0 ? data+l+1 : 0, argl);
841 fputs("unknown command; h for help\n", cc->out);
848 static void *control_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
849 const char *errmsg, int errnoval,
850 const char *data, size_t recsz, void *cc_v) {
851 ControlConn *cc= cc_v;
853 info("CTRL%d read error %s", cc->fd, errmsg);
858 static int control_conn_startup(ControlConn *cc /* may destroy*/,
860 cc->rd= oop_rd_new_fd(loop, cc->fd, 0,0);
861 if (!cc->rd) { warn("oop_rd_new_fd control failed"); return -1; }
863 int er= oop_rd_read(cc->rd, &control_rd_style, MAX_CONTROL_COMMAND,
866 if (er) { errno= er; syswarn("oop_rd_read control failed"); return -1; }
868 info("CTRL%d %s ready", cc->fd, how);
873 static void control_stdio_destroy(ControlConn *cc) {
875 oop_rd_cancel(cc->rd);
876 errno= oop_rd_delete_tidy(cc->rd);
877 if (errno) syswarn("oop_rd_delete tidy failed (no-nonblock stdin?)");
882 static void control_stdio(void) {
883 ControlConn *cc= xmalloc(sizeof(*cc));
884 memset(cc,0,sizeof(*cc));
885 cc->destroy= control_stdio_destroy;
889 int r= control_conn_startup(cc,"stdio");
890 if (r) cc->destroy(cc);
893 static void control_accepted_destroy(ControlConn *cc) {
895 oop_rd_cancel(cc->rd);
896 oop_rd_delete_kill(cc->rd);
898 if (cc->out) { fclose(cc->out); cc->fd=0; }
899 close_perhaps(&cc->fd);
903 static void *control_master_readable(oop_source *lp, int master,
904 oop_event ev, void *u) {
905 ControlConn *cc= xmalloc(sizeof(*cc));
906 memset(cc,0,sizeof(*cc));
907 cc->destroy= control_accepted_destroy;
909 cc->salen= sizeof(cc->sa);
910 cc->fd= accept(master, &cc->sa.sa, &cc->salen);
911 if (cc->fd<0) { syswarn("error accepting control connection"); goto x; }
913 cc->out= fdopen(cc->fd, "w");
914 if (!cc->out) { syswarn("error fdopening accepted control conn"); goto x; }
916 int r= control_conn_startup(cc, "accepted");
926 #define NOCONTROL(...) do{ \
927 syswarn("no control socket, because failed to " __VA_ARGS__); \
931 static void control_init(void) {
936 struct sockaddr_un un;
939 memset(&sa,0,sizeof(sa));
940 int maxlen= sizeof(sa.un.sun_path);
942 int reallen= readlink(path_control, sa.un.sun_path, maxlen);
945 NOCONTROL("readlink control socket symlink path %s", path_control);
947 if (reallen >= maxlen) {
948 debug("control socket symlink path too long (r=%d)",reallen);
949 xunlink(path_control, "old (overlong) control socket symlink");
955 int r= lstat(realsockdir,&stab);
957 if (errno != ENOENT) NOCONTROL("lstat real socket dir %s", realsockdir);
959 r= mkdir(realsockdir, 0700);
960 if (r) NOCONTROL("mkdir real socket dir %s", realsockdir);
963 uid_t self= geteuid();
964 if (!S_ISDIR(stab.st_mode) ||
965 stab.st_uid != self ||
966 stab.st_mode & 0077) {
967 warn("no control socket, because real socket directory"
968 " is somehow wrong (ISDIR=%d, uid=%lu (exp.%lu), mode %lo)",
969 !!S_ISDIR(stab.st_mode),
970 (unsigned long)stab.st_uid, (unsigned long)self,
971 (unsigned long)stab.st_mode & 0777UL);
976 real= xasprintf("%s/s%lx.%lx", realsockdir,
977 (unsigned long)xtime(), (unsigned long)self_pid);
978 int reallen= strlen(real);
980 if (reallen >= maxlen) {
981 warn("no control socket, because tmpnam gave overly-long path"
985 r= symlink(real, path_control);
986 if (r) NOCONTROL("make control socket path %s a symlink to real"
987 " socket path %s", path_control, real);
988 memcpy(sa.un.sun_path, real, reallen);
991 int r= unlink(sa.un.sun_path);
992 if (r && errno!=ENOENT)
993 NOCONTROL("remove old real socket %s", sa.un.sun_path);
995 control_master= socket(PF_UNIX, SOCK_STREAM, 0);
996 if (control_master<0) NOCONTROL("create new control socket");
998 sa.un.sun_family= AF_UNIX;
999 int sl= strlen(sa.un.sun_path) + offsetof(struct sockaddr_un, sun_path);
1000 r= bind(control_master, &sa.sa, sl);
1001 if (r) NOCONTROL("bind to real socket path %s", sa.un.sun_path);
1003 r= listen(control_master, 5);
1004 if (r) NOCONTROL("listen");
1006 xsetnonblock(control_master, 1);
1008 loop->on_fd(loop, control_master, OOP_READ, control_master_readable, 0);
1009 info("control socket ok, real path %s", sa.un.sun_path);
1015 xclose_perhaps(&control_master, "control master",0);
1019 /*========== management of connections ==========*/
1021 static void conn_closefd(Conn *conn, const char *msgprefix) {
1022 int r= close_perhaps(&conn->fd);
1023 if (r) info("C%d %serror closing socket: %s",
1024 conn->fd, msgprefix, strerror(errno));
1027 static void conn_dispose(Conn *conn) {
1030 oop_rd_cancel(conn->rd);
1031 oop_rd_delete_kill(conn->rd);
1035 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1036 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
1038 conn_closefd(conn,"");
1040 until_connect= reconnect_delay_periods;
1043 static void *conn_exception(oop_source *lp, int fd,
1044 oop_event ev, void *conn_v) {
1047 assert(fd == conn->fd);
1048 assert(ev == OOP_EXCEPTION);
1049 int r= read(conn->fd, &ch, 1);
1050 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
1051 else connfail(conn,"exceptional condition on socket (peer sent urgent"
1052 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
1053 return OOP_CONTINUE;
1056 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
1057 int requeue[art_MaxState];
1058 memset(requeue,0,sizeof(requeue));
1061 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
1062 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
1063 while ((art= LIST_REMHEAD(conn->sent))) {
1064 requeue[art->state]++;
1065 if (art->state==art_Unsolicited) art->state= art_Unchecked;
1066 LIST_ADDTAIL(queue,art);
1071 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
1074 char *m= xvasprintf(fmt,al);
1075 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
1076 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
1079 LIST_REMOVE(conns,conn);
1081 check_assign_articles();
1084 static void connfail(Conn *conn, const char *fmt, ...) {
1087 vconnfail(conn,fmt,al);
1091 static void check_idle_conns(void) {
1093 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
1094 conn->since_activity++;
1096 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
1097 if (conn->since_activity <= need_activity_periods) continue;
1099 /* We need to shut this down */
1101 connfail(conn,"timed out waiting for response to QUIT");
1102 else if (conn->sent.count)
1103 connfail(conn,"timed out waiting for responses");
1104 else if (conn->waiting.count || conn->priority.count)
1105 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
1106 else if (conn->xmitu)
1107 connfail(conn,"peer has been sending responses"
1108 " before receiving our commands!");
1110 static const char quitcmd[]= "QUIT\r\n";
1111 int todo= sizeof(quitcmd)-1;
1112 const char *p= quitcmd;
1114 int r= write(conn->fd, p, todo);
1116 if (isewouldblock(errno))
1117 connfail(conn, "blocked writing QUIT to idle connection");
1119 connfail(conn, "failed to write QUIT to idle connection: %s",
1127 conn->since_activity= 0;
1128 debug("C%d is idle, quitting", conn->fd);
1137 /*---------- making new connections ----------*/
1139 static pid_t connecting_child;
1140 static int connecting_fdpass_sock;
1142 static void connect_attempt_discard(void) {
1143 if (connecting_child) {
1144 int status= xwaitpid(&connecting_child, "connect");
1145 if (!(WIFEXITED(status) ||
1146 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
1147 report_child_status("connect", status);
1149 if (connecting_fdpass_sock) {
1150 cancel_fd_read_except(connecting_fdpass_sock);
1151 xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
1155 #define PREP_DECL_MSG_CMSG(msg) \
1157 struct iovec msgiov; \
1158 msgiov.iov_base= &msgbyte; \
1159 msgiov.iov_len= 1; \
1160 struct msghdr msg; \
1161 memset(&msg,0,sizeof(msg)); \
1162 char msg##cbuf[CMSG_SPACE(sizeof(int))]; \
1163 msg.msg_iov= &msgiov; \
1164 msg.msg_iovlen= 1; \
1165 msg.msg_control= msg##cbuf; \
1166 msg.msg_controllen= sizeof(msg##cbuf);
1168 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
1171 assert(fd == connecting_fdpass_sock);
1173 PREP_DECL_MSG_CMSG(msg);
1175 ssize_t rs= recvmsg(fd, &msg, 0);
1177 if (isewouldblock(errno)) return OOP_CONTINUE;
1178 syswarn("failed to read socket from connecting child");
1182 conn= xmalloc(sizeof(*conn));
1183 memset(conn,0,sizeof(*conn));
1184 LIST_INIT(conn->waiting);
1185 LIST_INIT(conn->priority);
1186 LIST_INIT(conn->sent);
1188 struct cmsghdr *h= 0;
1189 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
1191 int status= xwaitpid(&connecting_child, "connect child (broken)");
1193 if (WIFEXITED(status)) {
1194 if (WEXITSTATUS(status) != 0 &&
1195 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
1196 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
1197 /* child already reported the problem */;
1199 if (e == OOP_EXCEPTION)
1200 warn("connect: connection child exited code %d but"
1201 " unexpected exception on fdpass socket",
1202 WEXITSTATUS(status));
1204 warn("connect: connection child exited code %d but"
1206 WEXITSTATUS(status), (int)rs);
1208 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1209 warn("connect: connection attempt timed out");
1211 report_child_status("connect", status);
1216 #define CHK(field, val) \
1217 if (h->cmsg_##field != val) { \
1218 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
1219 h->cmsg_##field, val); \
1222 CHK(level, SOL_SOCKET);
1223 CHK(type, SCM_RIGHTS);
1224 CHK(len, CMSG_LEN(sizeof(conn->fd)));
1227 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
1229 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
1232 pid_t got= waitpid(connecting_child, &status, 0);
1233 if (got==-1) sysdie("connect: real wait for child");
1234 assert(got == connecting_child);
1235 connecting_child= 0;
1237 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
1238 int es= WEXITSTATUS(status);
1240 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
1241 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
1243 fatal("connect: child gave unexpected exit status %d", es);
1247 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
1249 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
1250 conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
1251 if (!conn->fd) die("oop_rd_new_fd conn failed (fd=%d)",conn->fd);
1252 int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
1254 &peer_rd_err, conn);
1255 if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
1257 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
1258 LIST_ADDHEAD(conns, conn);
1260 connect_attempt_discard();
1261 check_assign_articles();
1262 return OOP_CONTINUE;
1266 connect_attempt_discard();
1267 return OOP_CONTINUE;
1270 static int allow_connect_start(void) {
1271 return conns.count < max_connections
1272 && !connecting_child
1276 static void connect_start(void) {
1277 assert(!connecting_child);
1278 assert(!connecting_fdpass_sock);
1280 info("starting connection attempt");
1283 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
1284 if (r) { syswarn("connect: cannot create socketpair for child"); return; }
1286 connecting_child= xfork("connection");
1288 if (!connecting_child) {
1289 FILE *cn_from, *cn_to;
1290 char buf[NNTP_STRLEN+100];
1291 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
1293 xclose(socks[0], "(in child) parent's connection fdpass socket",0);
1295 alarm(connection_setup_timeout);
1296 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
1300 unsigned char c= buf[l-1];
1301 if (!isspace(c)) break;
1302 if (c=='\n' || c=='\r') stripped=1;
1306 sysfatal("connect: connection attempt failed");
1309 fatal("connect: %s: %s", stripped ? "rejected" : "failed",
1313 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
1314 sysfatal("connect: authentication failed");
1316 if (fputs("MODE STREAM\r\n", cn_to)==EOF ||
1318 sysfatal("connect: could not send MODE STREAM");
1319 buf[sizeof(buf)-1]= 0;
1320 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
1321 if (ferror(cn_from))
1322 sysfatal("connect: could not read response to MODE STREAM");
1324 fatal("connect: connection close in response to MODE STREAM");
1329 fatal("connect: response to MODE STREAM is too long: %.100s...",
1331 l--; if (l>0 && buf[l-1]=='\r') l--;
1334 int rcode= strtoul(buf,&ep,10);
1336 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
1340 exitstatus= CONNCHILD_ESTATUS_STREAM;
1346 warn("connect: unexpected response to MODE STREAM: %.50s",
1352 int fd= fileno(cn_from);
1354 PREP_DECL_MSG_CMSG(msg);
1355 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1356 cmsg->cmsg_level= SOL_SOCKET;
1357 cmsg->cmsg_type= SCM_RIGHTS;
1358 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
1359 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1361 msg.msg_controllen= cmsg->cmsg_len;
1362 r= sendmsg(socks[1], &msg, 0);
1363 if (r<0) sysdie("sendmsg failed for new connection");
1364 if (r!=1) die("sendmsg for new connection gave wrong result %d",r);
1369 xclose(socks[1], "connecting fdpass child's socket",0);
1370 connecting_fdpass_sock= socks[0];
1371 xsetnonblock(connecting_fdpass_sock, 1);
1372 on_fd_read_except(connecting_fdpass_sock, connchild_event);
1375 /*---------- assigning articles to conns, and transmitting ----------*/
1377 static void check_assign_articles(void) {
1383 int spare=0, inqueue=0;
1385 /* Find a connection to offer this article. We prefer a busy
1386 * connection to an idle one, provided it's not full. We take the
1387 * first (oldest) and since that's stable, it will mean we fill up
1388 * connections in order. That way if we have too many
1389 * connections, the spare ones will go away eventually.
1391 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1392 if (walk->quitting) continue;
1393 inqueue= walk->sent.count + walk->priority.count
1394 + walk->waiting.count;
1395 spare= walk->max_queue - inqueue;
1396 assert(inqueue <= max_queue_per_conn);
1398 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1399 else if (spare>0) /*working*/ { use= walk; break; }
1402 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1404 Article *art= LIST_REMHEAD(queue);
1406 LIST_ADDTAIL(use->waiting, art);
1409 conn_maybe_write(use);
1410 } else if (allow_connect_start()) {
1411 until_connect= reconnect_delay_periods;
1420 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1421 conn_maybe_write(u);
1422 return OOP_CONTINUE;
1425 static void conn_maybe_write(Conn *conn) {
1427 conn_make_some_xmits(conn);
1429 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1433 void *rp= conn_write_some_xmits(conn);
1434 if (rp==OOP_CONTINUE) {
1435 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1437 } else if (rp==OOP_HALT) {
1440 /* transmitted everything */
1447 /*========== article transmission ==========*/
1449 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1450 XmitKind kind) { /* caller must then fill in details */
1451 struct iovec *v= &conn->xmit[conn->xmitu];
1452 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1453 v->iov_base= (char*)data;
1459 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1460 xmit_core(conn,data,len, xk_Const);
1462 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1464 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1465 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1469 static void xmit_free(XmitDetails *d) {
1471 case xk_Malloc: free(d->info.malloc_tofree); break;
1472 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1473 case xk_Const: break;
1478 static void *conn_write_some_xmits(Conn *conn) {
1480 * 0: nothing more to write, no need to call us again
1481 * OOP_CONTINUE: more to write but fd not writeable
1482 * OOP_HALT: disaster, have destroyed conn
1485 int count= conn->xmitu;
1486 if (!count) return 0;
1488 if (count > IOV_MAX) count= IOV_MAX;
1489 ssize_t rs= writev(conn->fd, conn->xmit, count);
1491 if (isewouldblock(errno)) return OOP_CONTINUE;
1492 connfail(conn, "write failed: %s", strerror(errno));
1498 for (done=0; rs && done<conn->xmitu; done++) {
1499 struct iovec *vp= &conn->xmit[done];
1500 XmitDetails *dp= &conn->xmitd[done];
1501 if (rs > vp->iov_len) {
1505 vp->iov_base= (char*)vp->iov_base + rs;
1509 int newu= conn->xmitu - done;
1510 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1511 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1516 static void conn_make_some_xmits(Conn *conn) {
1518 if (conn->xmitu+5 > CONNIOVS)
1521 Article *art= LIST_REMHEAD(conn->priority);
1522 if (!art) art= LIST_REMHEAD(conn->waiting);
1525 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1526 /* actually send it */
1528 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1531 art->state == art_Unchecked ? art_Unsolicited :
1532 art->state == art_Wanted ? art_Wanted :
1535 if (!artdata) art->missing= 1;
1536 fprintf(stderr,"INC %d %d?%d:%d\n",(int)art->state,
1537 !!artdata, (int)RC_sent, (int)RC_missing);
1538 art->ipf->counts[art->state][ artdata ? RC_sent : RC_missing ]++;
1542 XMIT_LITERAL("TAKETHIS ");
1543 xmit_noalloc(conn, art->messageid, art->midlen);
1544 XMIT_LITERAL("\r\n");
1545 xmit_artbody(conn, artdata);
1547 article_done(conn, art, -1);
1551 /* we got 235 from IHAVE */
1553 xmit_artbody(conn, artdata);
1555 XMIT_LITERAL(".\r\n");
1559 LIST_ADDTAIL(conn->sent, art);
1565 XMIT_LITERAL("CHECK ");
1567 XMIT_LITERAL("IHAVE ");
1568 xmit_noalloc(conn, art->messageid, art->midlen);
1569 XMIT_LITERAL("\r\n");
1571 assert(art->state == art_Unchecked);
1572 fprintf(stderr,"INC %d %d\n",(int)art->state,(int)RC_sent);
1573 art->ipf->counts[art->state][RC_sent]++;
1574 LIST_ADDTAIL(conn->sent, art);
1580 /*========== handling responses from peer ==========*/
1582 static const oop_rd_style peer_rd_style= {
1583 OOP_RD_DELIM_STRIP, '\n',
1585 OOP_RD_SHORTREC_FORBID
1588 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1589 const char *errmsg, int errnoval,
1590 const char *data, size_t recsz, void *conn_v) {
1592 connfail(conn, "error receiving from peer: %s", errmsg);
1593 return OOP_CONTINUE;
1596 static Article *article_reply_check(Conn *conn, const char *response,
1597 int code_indicates_streaming,
1599 /* 1:yes, -1:no, 0:dontcare */,
1600 const char *sanitised_response) {
1601 Article *art= LIST_HEAD(conn->sent);
1605 "peer gave unexpected response when no commands outstanding: %s",
1606 sanitised_response);
1610 if (code_indicates_streaming) {
1611 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1612 if (!conn->stream) {
1613 connfail(conn, "peer gave streaming response code "
1614 " to IHAVE or subsequent body: %s", sanitised_response);
1617 const char *got_mid= response+4;
1618 int got_midlen= strcspn(got_mid, " \n\r");
1619 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1620 connfail(conn, "peer gave streaming response with syntactically invalid"
1621 " messageid: %s", sanitised_response);
1624 if (got_midlen != art->midlen ||
1625 memcmp(got_mid, art->messageid, got_midlen)) {
1626 connfail(conn, "peer gave streaming response code to wrong article -"
1627 " probable synchronisation problem; we offered: %s;"
1629 art->messageid, sanitised_response);
1634 connfail(conn, "peer gave non-streaming response code to"
1635 " CHECK/TAKETHIS: %s", sanitised_response);
1640 if (must_have_sent>0 && art->state < art_Wanted) {
1641 connfail(conn, "peer says article accepted but"
1642 " we had not sent the body: %s", sanitised_response);
1645 if (must_have_sent<0 && art->state >= art_Wanted) {
1646 connfail(conn, "peer says please sent the article but we just did: %s",
1647 sanitised_response);
1651 Article *art_again= LIST_REMHEAD(conn->sent);
1652 assert(art_again == art);
1656 static void update_nocheck(int accepted) {
1657 accept_proportion *= nocheck_decay;
1658 accept_proportion += accepted * (1.0 - nocheck_decay);
1659 int new_nocheck= accept_proportion >= nocheck_thresh;
1660 if (new_nocheck && !nocheck_reported) {
1661 notice("entering nocheck mode for the first time");
1662 nocheck_reported= 1;
1663 } else if (new_nocheck != nocheck) {
1664 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1666 nocheck= new_nocheck;
1669 static void article_done(Conn *conn, Article *art, int whichcount) {
1670 fprintf(stderr,"INC %d %d\n",(int)art->state,whichcount);
1671 if (!art->missing) art->ipf->counts[art->state][whichcount]++;
1673 if (whichcount == RC_accepted) update_nocheck(1);
1674 else if (whichcount == RC_unwanted) update_nocheck(0);
1676 InputFile *ipf= art->ipf;
1678 while (art->blanklen) {
1679 static const char spaces[]=
1689 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1690 int r= pwrite(ipf->fd, spaces, w, art->offset);
1692 if (errno==EINTR) continue;
1693 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1694 art->messageid, art->blanklen,
1695 (unsigned long)art->offset, ipf->path);
1697 assert(r>=0 && r<=w);
1703 assert(ipf->inprogress >= 0);
1706 if (!ipf->inprogress && ipf != main_input_file)
1707 queue_check_input_done();
1710 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1711 const char *errmsg, int errnoval,
1712 const char *data, size_t recsz, void *conn_v) {
1715 if (ev == OOP_RD_EOF) {
1716 connfail(conn, "unexpected EOF from peer");
1717 return OOP_CONTINUE;
1719 assert(ev == OOP_RD_OK);
1721 char *sani= sanitise(data);
1724 unsigned long code= strtoul(data, &ep, 10);
1725 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1726 connfail(conn, "badly formatted response from peer: %s", sani);
1727 return OOP_CONTINUE;
1730 if (conn->quitting) {
1731 if (code!=205 && code!=503) {
1732 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1734 notice("C%d idle connection closed", conn->fd);
1735 assert(!conn->waiting.count);
1736 assert(!conn->priority.count);
1737 assert(!conn->sent.count);
1738 assert(!conn->xmitu);
1739 LIST_REMOVE(conns,conn);
1742 return OOP_CONTINUE;
1745 conn->since_activity= 0;
1748 #define GET_ARTICLE(musthavesent) \
1749 art= article_reply_check(conn, data, code_streaming, musthavesent, sani); \
1750 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1752 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1753 code_streaming= (streaming); \
1754 GET_ARTICLE(musthavesent); \
1755 article_done(conn, art, RC_##how); break;
1757 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1759 int code_streaming= 0;
1763 case 400: PEERBADMSG("peer stopped accepting articles");
1764 case 503: PEERBADMSG("peer timed us out");
1765 default: PEERBADMSG("peer sent unexpected message");
1767 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1768 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1770 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1771 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1773 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1774 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1776 case 238: /* CHECK says send it */
1778 case 335: /* IHAVE says send it */
1780 assert(art->state == art_Unchecked);
1781 fprintf(stderr,"INC %d %d\n",(int)art->state,(int)RC_accepted);
1782 art->ipf->counts[art->state][RC_accepted]++;
1783 art->state= art_Wanted;
1784 LIST_ADDTAIL(conn->priority, art);
1787 case 431: /* CHECK or TAKETHIS says try later */
1789 case 436: /* IHAVE says try later */
1792 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1794 sysfatal("write to defer file %s",path_defer);
1795 article_done(conn, art, RC_deferred);
1800 conn_maybe_write(conn);
1801 check_assign_articles();
1802 return OOP_CONTINUE;
1806 /*========== monitoring of input files ==========*/
1808 static void feedfile_eof(InputFile *ipf) {
1809 assert(ipf != main_input_file); /* promised by tailing_try_read */
1810 inputfile_reading_stop(ipf);
1812 if (ipf == flushing_input_file) {
1813 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1814 if (main_input_file) inputfile_reading_start(main_input_file);
1815 statemc_check_flushing_done();
1816 } else if (ipf == backlog_input_file) {
1817 statemc_check_backlog_done();
1819 abort(); /* supposed to wait rather than get EOF on main input file */
1823 static InputFile *open_input_file(const char *path) {
1824 int fd= open(path, O_RDWR);
1826 if (errno==ENOENT) return 0;
1827 sysfatal("unable to open input file %s", path);
1831 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1832 memset(ipf,0,sizeof(*ipf));
1835 strcpy(ipf->path, path);
1840 static void close_input_file(InputFile *ipf) { /* does not free */
1841 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1842 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1843 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1844 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1845 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1849 /*---------- dealing with articles read in the input file ----------*/
1851 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1852 const char *data, const char *how) {
1853 warn("corrupted file: %s, offset %lu: %s: in %s",
1854 ipf->path, (unsigned long)offset, how, sanitise(data));
1855 ipf->readcount_err++;
1856 if (ipf->readcount_err > max_bad_data_initial +
1857 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1858 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1859 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1860 return OOP_CONTINUE;
1863 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1864 oop_rd_event ev, const char *errmsg,
1865 int errnoval, const char *data, size_t recsz,
1867 InputFile *ipf= ipf_v;
1868 assert(ev == OOP_RD_SYSTEM);
1870 sysdie("error reading input file: %s, offset %lu",
1871 ipf->path, (unsigned long)ipf->offset);
1874 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1875 oop_rd_event ev, const char *errmsg,
1876 int errnoval, const char *data, size_t recsz,
1878 InputFile *ipf= ipf_v;
1880 char tokentextbuf[sizeof(TOKEN)*2+3];
1882 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1884 off_t old_offset= ipf->offset;
1885 ipf->offset += recsz + 1;
1887 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1889 if (ev==OOP_RD_PARTREC)
1890 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1891 /* but process it anyway */
1893 if (ipf->skippinglong) {
1894 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1895 return OOP_CONTINUE;
1897 if (ev==OOP_RD_LONG) {
1898 ipf->skippinglong= 1;
1899 X_BAD_DATA("overly long line");
1902 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1903 if (!recsz) X_BAD_DATA("empty line");
1906 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1907 ipf->readcount_blank++;
1908 return OOP_CONTINUE;
1911 char *space= strchr(data,' ');
1912 int tokenlen= space-data;
1913 int midlen= (int)recsz-tokenlen-1;
1914 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1915 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1917 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1918 memcpy(tokentextbuf, data, tokenlen);
1919 tokentextbuf[tokenlen]= 0;
1920 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1922 ipf->readcount_ok++;
1924 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1925 art->state= art_Unchecked;
1926 art->midlen= midlen;
1927 art->ipf= ipf; ipf->inprogress++;
1928 art->token= TextToToken(tokentextbuf);
1929 art->offset= ipf->offset;
1930 art->blanklen= recsz;
1931 strcpy(art->messageid, space+1);
1932 LIST_ADDTAIL(queue, art);
1934 if (sms==sm_NORMAL && ipf==main_input_file &&
1935 ipf->offset >= target_max_feedfile_size)
1936 statemc_start_flush("feed file size");
1938 check_assign_articles();
1939 return OOP_CONTINUE;
1942 /*========== tailing input file ==========*/
1944 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1946 InputFile *ipf= user;
1947 return ipf->readable_callback(loop, &ipf->readable,
1948 ipf->readable_callback_user);
1951 static void tailing_on_cancel(struct oop_readable *rable) {
1952 InputFile *ipf= (void*)rable;
1954 if (ipf->filemon) filemon_stop(ipf);
1955 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1956 ipf->readable_callback= 0;
1959 static void tailing_queue_readable(InputFile *ipf) {
1960 /* lifetime of ipf here is OK because destruction will cause
1961 * on_cancel which will cancel this callback */
1962 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1965 static int tailing_on_readable(struct oop_readable *rable,
1966 oop_readable_call *cb, void *user) {
1967 InputFile *ipf= (void*)rable;
1969 tailing_on_cancel(rable);
1970 ipf->readable_callback= cb;
1971 ipf->readable_callback_user= user;
1974 tailing_queue_readable(ipf);
1978 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1980 InputFile *ipf= (void*)rable;
1982 ssize_t r= read(ipf->fd, buffer, length);
1984 if (errno==EINTR) continue;
1988 if (ipf==main_input_file) {
1991 } else if (ipf==flushing_input_file) {
1993 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1994 } else if (ipf==backlog_input_file) {
2000 tailing_queue_readable(ipf);
2005 /*---------- filemon implemented with inotify ----------*/
2007 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
2008 #define HAVE_FILEMON
2010 #include <linux/inotify.h>
2012 static int filemon_inotify_fd;
2013 static int filemon_inotify_wdmax;
2014 static InputFile **filemon_inotify_wd2ipf;
2016 struct Filemon_Perfile {
2020 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
2021 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
2022 if (wd < 0) sysfatal("inotify_add_watch %s", ipf->path);
2024 if (wd >= filemon_inotify_wdmax) {
2026 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
2027 sizeof(*filemon_inotify_wd2ipf) * newmax);
2028 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
2029 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
2030 filemon_inotify_wdmax= newmax;
2033 assert(!filemon_inotify_wd2ipf[wd]);
2034 filemon_inotify_wd2ipf[wd]= ipf;
2036 debug("filemon inotify startfile %p wd=%d wdmax=%d",
2037 ipf, wd, filemon_inotify_wdmax);
2042 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
2044 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
2045 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
2046 if (r) sysdie("inotify_rm_watch");
2047 filemon_inotify_wd2ipf[wd]= 0;
2050 static void *filemon_inotify_readable(oop_source *lp, int fd,
2051 oop_event e, void *u) {
2052 struct inotify_event iev;
2054 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
2056 if (isewouldblock(errno)) break;
2057 sysdie("read from inotify master");
2058 } else if (r==sizeof(iev)) {
2059 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
2061 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
2063 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
2064 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
2065 filemon_callback(ipf);
2067 return OOP_CONTINUE;
2070 static int filemon_method_init(void) {
2071 filemon_inotify_fd= inotify_init();
2072 if (filemon_inotify_fd<0) {
2073 syswarn("could not initialise inotify: inotify_init failed");
2077 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
2079 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
2083 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
2085 /*---------- filemon dummy implementation ----------*/
2087 #if !defined(HAVE_FILEMON)
2089 struct Filemon_Perfile { int dummy; };
2091 static int filemon_method_init(void) { return 0; }
2092 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
2093 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
2095 #endif /* !HAVE_FILEMON */
2097 /*---------- filemon generic interface ----------*/
2099 static void filemon_start(InputFile *ipf) {
2100 assert(!ipf->filemon);
2102 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
2103 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
2104 filemon_method_startfile(ipf, ipf->filemon);
2107 static void filemon_stop(InputFile *ipf) {
2108 if (!ipf->filemon) return;
2109 filemon_method_stopfile(ipf, ipf->filemon);
2114 static void filemon_callback(InputFile *ipf) {
2115 if (ipf && ipf->readable_callback) /* so filepoll() can be naive */
2116 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
2119 /*---------- interface to start and stop an input file ----------*/
2121 static const oop_rd_style feedfile_rdstyle= {
2122 OOP_RD_DELIM_STRIP, '\n',
2124 OOP_RD_SHORTREC_LONG,
2127 static void inputfile_reading_start(InputFile *ipf) {
2129 ipf->readable.on_readable= tailing_on_readable;
2130 ipf->readable.on_cancel= tailing_on_cancel;
2131 ipf->readable.try_read= tailing_try_read;
2132 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
2133 ipf->readable.delete_kill= 0;
2135 ipf->readable_callback= 0;
2136 ipf->readable_callback_user= 0;
2138 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
2141 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
2142 feedfile_got_article,ipf, feedfile_read_err, ipf);
2143 if (r) sysdie("unable start reading feedfile %s",ipf->path);
2146 static void inputfile_reading_stop(InputFile *ipf) {
2148 oop_rd_cancel(ipf->rd);
2149 oop_rd_delete(ipf->rd);
2151 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
2155 /*========== interaction with innd - state machine ==========*/
2157 /* See official state diagram at top of file. We implement
2168 |`---------------------------------------------------.
2170 |`---------------- - - - |
2171 D ENOENT | D EXISTS see OVERALL STATES diagram |
2172 | for full startup logic |
2175 | ============ try to |
2181 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
2182 ^ | hardlink F to D |
2185 | | our handle onto F is now onto D |
2188 | |<-------------------<---------------------<---------+
2190 | | spawn inndcomm flush |
2192 | ================== |
2193 | FLUSHING[-ABSENT] |
2195 | main D tail/none |
2196 | ================== |
2198 | | INNDCOMM FLUSH FAILS ^
2199 | |`----------------------->----------. |
2201 | | NO SUCH SITE V |
2202 ^ |`--------------->----. ==================== |
2203 | | \ FLUSHFAILED[-ABSENT] |
2205 | | FLUSH OK \ main D tail/none |
2206 | | open F \ ==================== |
2208 | | \ | TIME TO RETRY |
2209 | |`------->----. ,---<---'\ `----------------'
2210 | | D NONE | | D NONE `----.
2212 | ============= V V ============
2213 | SEPARATED-1 | | DROPPING-1
2214 | flsh->rd!=0 | | flsh->rd!=0
2215 | [Separated] | | [Dropping]
2216 | main F idle | | main none
2217 | old D tail | | old D tail
2218 | ============= | | ============
2220 ^ | EOF ON D | | defer | EOF ON D
2222 | =============== | | ===============
2223 | SEPARATED-2 | | DROPPING-2
2224 | flsh->rd==0 | V flsh->rd==0
2225 | [Finishing] | | [Dropping]
2226 | main F tail | `. main none
2227 | old D closed | `. old D closed
2228 | =============== V `. ===============
2230 | | ALL D PROCESSED `. | ALL D PROCESSED
2231 | V install defer as backlog `. | install defer
2232 ^ | close D `. | close D
2233 | | unlink D `. | unlink D
2236 `----------' ==============
2256 static void startup_set_input_file(InputFile *f) {
2257 assert(!main_input_file);
2259 inputfile_reading_start(f);
2262 static void statemc_lock(void) {
2264 struct stat stab, stabf;
2267 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
2268 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
2271 memset(&fl,0,sizeof(fl));
2273 fl.l_whence= SEEK_SET;
2274 int r= fcntl(lockfd, F_SETLK, &fl);
2276 if (errno==EACCES || isewouldblock(errno)) {
2277 if (quiet_multiple) exit(0);
2278 fatal("another duct holds the lockfile");
2280 sysfatal("fcntl F_SETLK lockfile %s", path_lock);
2283 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
2285 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
2287 if (!lock_noent && samefile(&stab, &stabf))
2290 xclose(lockfd, "stale lockfile ", path_lock);
2293 FILE *lockfile= fdopen(lockfd, "w");
2294 if (!lockfile) sysdie("fdopen lockfile");
2296 int r= ftruncate(lockfd, 0);
2297 if (r) sysdie("truncate lockfile to write new info");
2299 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
2300 (unsigned long)self_pid,
2301 sitename, feedfile, remote_host) == EOF ||
2303 sysfatal("write info to lockfile %s", path_lock);
2305 debug("startup: locked");
2308 static void statemc_init(void) {
2309 struct stat stabdefer;
2311 search_backlog_file();
2314 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
2316 debug("startup: ductdefer ENOENT");
2318 debug("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
2319 switch (stabdefer.st_nlink==1) {
2321 open_defer(); /* so that we will later close it and rename it */
2324 xunlink(path_defer, "stale defer file link"
2325 " (presumably hardlink to backlog file)");
2328 die("defer file %s has unexpected link count %d",
2329 path_defer, stabdefer.st_nlink);
2333 struct stat stab_f, stab_d;
2336 InputFile *file_d= open_input_file(path_flushing);
2337 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
2339 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
2341 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
2342 debug("startup: F==D => Hardlinked");
2343 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
2348 debug("startup: F ENOENT => Moved");
2349 if (file_d) startup_set_input_file(file_d);
2350 spawn_inndcomm_flush("feedfile missing at startup");
2351 /* => Flushing, sms:=FLUSHING */
2354 debug("startup: F!=D => Separated");
2355 startup_set_input_file(file_d);
2356 SMS(SEPARATED, 0, "found both old and current feed files");
2358 debug("startup: F exists, D ENOENT => Normal");
2359 InputFile *file_f= open_input_file(feedfile);
2360 if (!file_f) die("feed file vanished during startup");
2361 startup_set_input_file(file_f);
2362 SMS(NORMAL, spontaneous_flush_periods, "normal startup");
2367 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
2368 assert(sms == sm_NORMAL);
2370 debug("starting flush (%s) (%lu >?= %lu) (%d)",
2372 (unsigned long)(main_input_file ? main_input_file->offset : 0),
2373 (unsigned long)target_max_feedfile_size,
2376 int r= link(feedfile, path_flushing);
2377 if (r) sysfatal("link feedfile %s to flushing file %s",
2378 feedfile, path_flushing);
2381 xunlink(feedfile, "old feedfile link");
2384 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2387 static void statemc_period_poll(void) {
2388 if (!sm_period_counter) return;
2389 sm_period_counter--;
2390 assert(sm_period_counter>=0);
2392 if (sm_period_counter) return;
2395 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2397 case sm_FLUSHFAILED:
2398 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2405 static int inputfile_is_done(InputFile *ipf) {
2407 if (ipf->inprogress) return 0; /* new article in the meantime */
2408 if (ipf->rd) return 0; /* not had EOF */
2412 static void notice_processed(InputFile *ipf, const char *what,
2414 #define RCI_NOTHING(x) /* nothing */
2415 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2416 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2418 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2420 info("processed %s%s read=%d (+bl=%d,+err=%d)"
2421 " offered=%d (ch=%d,nc=%d) accepted=%d (ch=%d,nc=%d)"
2422 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2425 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2426 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2427 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2428 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2429 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2430 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2436 static void statemc_check_backlog_done(void) {
2437 InputFile *ipf= backlog_input_file;
2438 if (!inputfile_is_done(ipf)) return;
2440 const char *slash= strrchr(ipf->path, '/');
2441 const char *leaf= slash ? slash+1 : ipf->path;
2442 const char *under= strchr(slash, '_');
2443 const char *rest= under ? under+1 : leaf;
2444 if (!strncmp(rest,"backlog",7)) rest += 7;
2445 notice_processed(ipf,"backlog ",rest);
2447 close_input_file(ipf);
2448 if (unlink(ipf->path)) {
2449 if (errno != ENOENT)
2450 sysdie("could not unlink processed backlog file %s", ipf->path);
2451 warn("backlog file %s vanished while we were reading it"
2452 " so we couldn't remove it (but it's done now, anyway)",
2456 backlog_input_file= 0;
2457 search_backlog_file();
2461 static void statemc_check_flushing_done(void) {
2462 InputFile *ipf= flushing_input_file;
2463 if (!inputfile_is_done(ipf)) return;
2465 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2467 notice_processed(ipf,"feedfile","");
2471 xunlink(path_flushing, "old flushing file");
2473 close_input_file(flushing_input_file);
2474 free(flushing_input_file);
2475 flushing_input_file= 0;
2477 if (sms==sm_SEPARATED) {
2478 notice("flush complete");
2479 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2480 } else if (sms==sm_DROPPING) {
2481 SMS(DROPPED, 0, "old flush complete");
2482 search_backlog_file();
2483 notice("feed dropped, but will continue until backlog is finished");
2487 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2489 assert(!inputfile_is_done(main_input_file));
2490 statemc_check_flushing_done();
2491 statemc_check_backlog_done();
2492 return OOP_CONTINUE;
2495 static void queue_check_input_done(void) {
2496 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2499 static void statemc_setstate(StateMachineState newsms, int periods,
2500 const char *forlog, const char *why) {
2502 sm_period_counter= periods;
2504 const char *xtra= "";
2507 case sm_FLUSHFAILED:
2508 if (!main_input_file) xtra= "-ABSENT";
2512 xtra= flushing_input_file->rd ? "-1" : "-2";
2518 info("state %s%s[%d] %s",forlog,xtra,periods,why);
2520 info("state %s%s %s",forlog,xtra,why);
2524 /*---------- defer and backlog files ----------*/
2526 static void open_defer(void) {
2531 defer= fopen(path_defer, "a+");
2532 if (!defer) sysfatal("could not open defer file %s", path_defer);
2534 /* truncate away any half-written records */
2536 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2538 if (stab.st_size > LONG_MAX)
2539 die("defer file %s size is far too large", path_defer);
2544 long orgsize= stab.st_size;
2545 long truncto= stab.st_size;
2547 if (!truncto) break; /* was only (if anything) one half-truncated record */
2548 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2549 sysdie("seek in defer file %s while truncating partial", path_defer);
2554 sysdie("failed read from defer file %s", path_defer);
2556 die("defer file %s shrank while we were checking it!", path_defer);
2562 if (stab.st_size != truncto) {
2563 warn("truncating half-record at end of defer file %s -"
2564 " shrinking by %ld bytes from %ld to %ld",
2565 path_defer, orgsize - truncto, orgsize, truncto);
2568 sysfatal("could not flush defer file %s", path_defer);
2569 if (ftruncate(fileno(defer), truncto))
2570 sysdie("could not truncate defer file %s", path_defer);
2573 info("continuing existing defer file %s (%ld bytes)",
2574 path_defer, orgsize);
2576 if (fseek(defer, truncto, SEEK_SET))
2577 sysdie("could not seek to new end of defer file %s", path_defer);
2580 static void close_defer(void) {
2585 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2587 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2590 time_t now= xtime();
2592 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2594 (unsigned long)stab.st_ino);
2595 if (link(path_defer, backlog))
2596 sysfatal("could not install defer file %s as backlog file %s",
2597 path_defer, backlog);
2598 if (unlink(path_defer))
2599 sysdie("could not unlink old defer link %s to backlog file %s",
2600 path_defer, backlog);
2604 if (until_backlog_nextscan < 0 ||
2605 until_backlog_nextscan > backlog_retry_minperiods + 1)
2606 until_backlog_nextscan= backlog_retry_minperiods + 1;
2609 static void poll_backlog_file(void) {
2610 if (until_backlog_nextscan < 0) return;
2611 if (until_backlog_nextscan-- > 0) return;
2612 search_backlog_file();
2615 static void search_backlog_file(void) {
2616 /* returns non-0 iff there are any backlog files */
2621 const char *oldest_path=0;
2622 time_t oldest_mtime=0, now;
2624 if (backlog_input_file) return;
2628 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2632 sysfatal("failed to expand backlog pattern %s", globpat_backlog);
2634 fatal("out of memory expanding backlog pattern %s", globpat_backlog);
2636 for (i=0; i<gl.gl_pathc; i++) {
2637 const char *path= gl.gl_pathv[i];
2639 if (strchr(path,'#') || strchr(path,'~')) {
2640 debug("backlog file search skipping %s", path);
2643 r= stat(path, &stab);
2645 syswarn("failed to stat backlog file %s", path);
2648 if (!S_ISREG(stab.st_mode)) {
2649 warn("backlog file %s is not a plain file (or link to one)", path);
2652 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2654 oldest_mtime= stab.st_mtime;
2657 case GLOB_NOMATCH: /* fall through */
2660 sysdie("glob expansion of backlog pattern %s gave unexpected"
2661 " nonzero (error?) return value %d", globpat_backlog, r);
2665 debug("backlog scan: none");
2667 if (sms==sm_DROPPED) {
2668 notice("feed dropped and our work is complete");
2670 int r= unlink(path_control);
2671 if (r && errno!=ENOENT)
2672 syswarn("failed to remove control symlink for old feed");
2674 xunlink(path_lock, "lockfile for old feed");
2677 until_backlog_nextscan= backlog_spontrescan_periods;
2682 double age= difftime(now, oldest_mtime);
2683 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2685 if (age_deficiency <= 0) {
2686 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2687 age, age_deficiency, oldest_path);
2689 backlog_input_file= open_input_file(oldest_path);
2690 if (!backlog_input_file) {
2691 warn("backlog file %s vanished as we opened it", oldest_path);
2695 inputfile_reading_start(backlog_input_file);
2696 until_backlog_nextscan= -1;
2700 until_backlog_nextscan= age_deficiency / period_seconds;
2702 if (backlog_spontrescan_periods >= 0 &&
2703 until_backlog_nextscan > backlog_spontrescan_periods)
2704 until_backlog_nextscan= backlog_spontrescan_periods;
2706 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2707 age, age_deficiency, until_backlog_nextscan, oldest_path);
2714 /*========== flushing the feed ==========*/
2716 static pid_t inndcomm_child;
2717 static int inndcomm_sentinel_fd;
2719 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2720 assert(inndcomm_child);
2721 assert(fd == inndcomm_sentinel_fd);
2722 int status= xwaitpid(&inndcomm_child, "inndcomm");
2725 cancel_fd_read_except(fd);
2726 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2727 inndcomm_sentinel_fd= 0;
2729 assert(!flushing_input_file);
2731 if (WIFEXITED(status)) {
2732 switch (WEXITSTATUS(status)) {
2734 case INNDCOMMCHILD_ESTATUS_FAIL:
2737 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2738 notice("feed has been dropped by innd, finishing up");
2739 flushing_input_file= main_input_file;
2740 tailing_queue_readable(flushing_input_file);
2741 /* we probably previously returned EAGAIN from our fake read method
2742 * when in fact we were at EOF, so signal another readable event
2743 * so we actually see the EOF */
2747 if (flushing_input_file) {
2748 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2751 SMS(DROPPED, 0, "feed dropped by innd");
2752 search_backlog_file();
2754 return OOP_CONTINUE;
2758 flushing_input_file= main_input_file;
2759 tailing_queue_readable(flushing_input_file);
2761 main_input_file= open_input_file(feedfile);
2762 if (!main_input_file)
2763 die("flush succeeded but feedfile %s does not exist!", feedfile);
2765 if (flushing_input_file) {
2766 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2769 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2771 return OOP_CONTINUE;
2774 goto unexpected_exitstatus;
2777 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2778 warn("flush timed out trying to talk to innd");
2781 unexpected_exitstatus:
2782 report_child_status("inndcomm child", status);
2786 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2787 return OOP_CONTINUE;
2790 static void inndcommfail(const char *what) {
2791 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2792 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2795 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2798 notice("flushing %s",why);
2800 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2801 assert(!inndcomm_child);
2802 assert(!inndcomm_sentinel_fd);
2804 if (pipe(pipefds)) sysfatal("create pipe for inndcomm child sentinel");
2806 inndcomm_child= xfork("inndcomm child");
2808 if (!inndcomm_child) {
2809 const char *flushargv[2]= { sitename, 0 };
2813 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2814 /* parent spots the autoclose of pipefds[1] when we die or exit */
2816 if (simulate_flush>=0) {
2817 warn("SIMULATING flush child status %d", simulate_flush);
2818 if (simulate_flush>128) raise(simulate_flush-128);
2819 else exit(simulate_flush);
2822 alarm(inndcomm_flush_timeout);
2823 r= ICCopen(); if (r) inndcommfail("connect");
2824 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2825 if (!r) exit(0); /* yay! */
2827 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2828 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2829 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2834 xclose(pipefds[1], "inndcomm sentinel child's end",0);
2835 inndcomm_sentinel_fd= pipefds[0];
2836 assert(inndcomm_sentinel_fd);
2837 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2839 SMS(FLUSHING, 0, why);
2842 /*========== main program ==========*/
2844 static void postfork_inputfile(InputFile *ipf) {
2846 xclose(ipf->fd, "(in child) input file ", ipf->path);
2849 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2850 /* we have no stdio streams that are buffered long-term */
2852 if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2855 static void postfork(void) {
2856 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2857 sysdie("(in child) failed to reset SIGPIPE");
2859 postfork_inputfile(main_input_file);
2860 postfork_inputfile(flushing_input_file);
2863 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2864 conn_closefd(conn,"(in child) ");
2866 postfork_stdio(defer, "defer file ", path_defer);
2869 typedef struct Every Every;
2871 struct timeval interval;
2876 static void every_schedule(Every *e, struct timeval base);
2878 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
2881 if (!e->fixed_rate) xgettimeofday(&base);
2882 every_schedule(e, base);
2883 return OOP_CONTINUE;
2886 static void every_schedule(Every *e, struct timeval base) {
2887 struct timeval when;
2888 timeradd(&base, &e->interval, &when);
2889 loop->on_time(loop, when, every_happens, e);
2892 static void every(int interval, int fixed_rate, void (*f)(void)) {
2893 Every *e= xmalloc(sizeof(*e));
2894 e->interval.tv_sec= interval;
2895 e->interval.tv_usec= 0;
2896 e->fixed_rate= fixed_rate;
2899 xgettimeofday(&now);
2900 every_schedule(e, now);
2903 static void filepoll(void) {
2904 filemon_callback(main_input_file);
2905 filemon_callback(flushing_input_file);
2908 static char *debug_report_ipf(InputFile *ipf) {
2909 if (!ipf) return xasprintf("none");
2911 const char *slash= strrchr(ipf->path,'/');
2912 const char *path= slash ? slash+1 : ipf->path;
2914 return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2916 ipf->inprogress, (long)ipf->offset,
2917 ipf->fd, ipf->rd ? "" : ",!rd");
2920 static void period(void) {
2921 char *dipf_main= debug_report_ipf(main_input_file);
2922 char *dipf_flushing= debug_report_ipf(flushing_input_file);
2923 char *dipf_backlog= debug_report_ipf(backlog_input_file);
2926 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2927 " input_files main:%s flushing:%s backlog:%s"
2928 " children connecting=%ld inndcomm=%ld"
2930 sms_names[sms], sm_period_counter,
2931 conns.count, queue.count, until_connect,
2932 dipf_main, dipf_flushing, dipf_backlog,
2933 (long)connecting_child, (long)inndcomm_child
2937 free(dipf_flushing);
2940 if (until_connect) until_connect--;
2942 poll_backlog_file();
2943 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2944 statemc_period_poll();
2945 check_assign_articles();
2950 /*========== option parsing ==========*/
2952 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2953 static void vbadusage(const char *fmt, va_list al) {
2954 char *m= xvasprintf(fmt,al);
2955 fprintf(stderr, "bad usage: %s\n"
2956 "say --help for help, or read the manpage\n",
2959 syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2963 /*---------- generic option parser ----------*/
2965 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2966 static void badusage(const char *fmt, ...) {
2973 of_seconds= 001000u,
2974 of_boolean= 002000u,
2977 typedef struct Option Option;
2978 typedef void OptionParser(const Option*, const char *val);
2982 const char *lng, *formarg;
2988 static void parse_options(const Option *options, char ***argvp) {
2989 /* on return *argvp is first non-option arg; argc is not updated */
2992 const char *arg= *++(*argvp);
2994 if (*arg != '-') break;
2995 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2997 while ((a= *++arg)) {
3001 char *equals= strchr(arg,'=');
3002 int len= equals ? (equals - arg) : strlen(arg);
3003 for (o=options; o->shrt || o->lng; o++)
3004 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
3006 badusage("unknown long option --%s",arg);
3009 if (equals) badusage("option --%s does not take a value",o->lng);
3011 } else if (equals) {
3015 if (!arg) badusage("option --%s needs a value for %s",
3016 o->lng, o->formarg);
3019 break; /* eaten the whole argument now */
3021 for (o=options; o->shrt || o->lng; o++)
3024 badusage("unknown short option -%c",a);
3031 if (!arg) badusage("option -%c needs a value for %s",
3032 o->shrt, o->formarg);
3035 break; /* eaten the whole argument now */
3041 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
3043 static void print_options(const Option *options, FILE *f) {
3045 for (o=options; o->shrt || o->lng; o++) {
3046 char shrt[2] = { o->shrt, 0 };
3047 char *optspec= xasprintf("%s%s%s%s%s",
3048 o->shrt ? "-" : "", shrt,
3049 o->shrt && o->lng ? "|" : "",
3050 DELIMPERHAPS("--", o->lng));
3051 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
3056 /*---------- specific option types ----------*/
3058 static void op_integer(const Option *o, const char *val) {
3061 unsigned long ul= strtoul(val,&ep,10);
3062 if (*ep || ep==val || errno || ul>INT_MAX)
3063 badusage("bad integer value for %s",o->lng);
3064 int *store= o->store;
3068 static void op_double(const Option *o, const char *val) {
3069 int *store= o->store;
3072 *store= strtod(val, &ep);
3073 if (*ep || ep==val || errno)
3074 badusage("bad floating point value for %s",o->lng);
3077 static void op_string(const Option *o, const char *val) {
3078 const char **store= o->store;
3082 static void op_seconds(const Option *o, const char *val) {
3083 int *store= o->store;
3087 double v= strtod(val,&ep);
3088 if (ep==val) badusage("bad time/duration value for %s",o->lng);
3090 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
3091 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
3092 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
3093 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
3094 else if (!strcmp(ep,"das")) unit= 10;
3095 else if (!strcmp(ep,"hs")) unit= 100;
3096 else if (!strcmp(ep,"ks")) unit= 1000;
3097 else if (!strcmp(ep,"Ms")) unit= 1000000;
3098 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
3102 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
3106 static void op_setint(const Option *o, const char *val) {
3107 int *store= o->store;
3111 /*---------- specific options ----------*/
3113 static void help(const Option *o, const char *val);
3115 static const Option innduct_options[]= {
3116 {'f',"feedfile", "F", &feedfile, op_string },
3117 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
3118 {0,"no-daemon", 0, &become_daemon, op_setint, 0 },
3119 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
3120 {'C',"inndconf", "F", &inndconffile, op_string },
3121 {'P',"port", "PORT", &port, op_integer },
3122 {0,"help", 0, 0, help },
3124 {0,"max-connections", "N", &max_connections, op_integer },
3125 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
3126 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
3127 {0,"period-interval", "TIME", &period_seconds, op_seconds },
3129 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
3130 {0,"stuck-flush-timeout","TIME", &inndcomm_flush_timeout, op_seconds },
3132 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
3133 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
3135 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
3136 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
3137 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
3138 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
3139 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
3140 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
3142 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
3143 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
3148 static void printusage(FILE *f) {
3149 fputs("usage: innduct [options] site [fqdn]\n"
3150 "available options are:\n", f);
3151 print_options(innduct_options, f);
3154 static void help(const Option *o, const char *val) {
3156 if (ferror(stdout) || fflush(stdout)) {
3157 perror("innduct: writing help");
3163 static void convert_to_periods_rndup(int *store) {
3164 *store += period_seconds-1;
3165 *store /= period_seconds;
3168 int main(int argc, char **argv) {
3174 parse_options(innduct_options, &argv);
3179 if (!sitename) badusage("need site name argument");
3180 remote_host= *argv++;
3181 if (*argv) badusage("too many non-option arguments");
3185 int r= innconf_read(inndconffile);
3186 if (!r) badusage("could not read inn.conf (more info on stderr)");
3188 if (!remote_host) remote_host= sitename;
3190 if (nocheck_thresh < 0 || nocheck_thresh > 100)
3191 badusage("nocheck threshold percentage must be between 0..100");
3192 nocheck_thresh *= 0.01;
3194 if (nocheck_decay < 0.1)
3195 badusage("nocheck decay articles must be at least 0.1");
3196 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
3198 convert_to_periods_rndup(&reconnect_delay_periods);
3199 convert_to_periods_rndup(&flushfail_retry_periods);
3200 convert_to_periods_rndup(&backlog_retry_minperiods);
3201 convert_to_periods_rndup(&backlog_spontrescan_periods);
3202 convert_to_periods_rndup(&spontaneous_flush_periods);
3203 convert_to_periods_rndup(&need_activity_periods);
3205 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
3206 badusage("bad input data ratio must be between 0..100");
3207 max_bad_data_ratio *= 0.01;
3210 feedfile= xasprintf("%s/%s",innconf->pathoutgoing,sitename);
3211 } else if (!feedfile[0]) {
3212 badusage("feed filename must be nonempty");
3213 } else if (feedfile[strlen(feedfile)-1]=='/') {
3214 feedfile= xasprintf("%s%s",feedfile,sitename);
3217 const char *feedfile_forbidden= "?*[~#";
3219 while ((c= *feedfile_forbidden++))
3220 if (strchr(feedfile, c))
3221 badusage("feed filename may not contain metacharacter %c",c);
3225 path_lock= xasprintf("%s_lock", feedfile);
3226 path_flushing= xasprintf("%s_flushing", feedfile);
3227 path_defer= xasprintf("%s_defer", feedfile);
3228 path_control= xasprintf("%s_control", feedfile);
3229 globpat_backlog= xasprintf("%s_backlog*", feedfile);
3231 oop_source_sys *sysloop= oop_sys_new();
3232 if (!sysloop) sysdie("could not create liboop event loop");
3233 loop= (oop_source*)sysloop;
3235 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3236 sysdie("could not ignore SIGPIPE");
3241 if (become_daemon) {
3243 for (i=3; i<255; i++)
3244 /* do this now before we open syslog, etc. */
3246 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
3248 int null= open("/dev/null",O_RDWR);
3249 if (null<0) sysfatal("failed to open /dev/null");
3253 xclose(null, "/dev/null original fd",0);
3255 pid_t child1= xfork("daemonise first fork");
3256 if (child1) _exit(0);
3258 pid_t sid= setsid();
3259 if (sid != child1) sysfatal("setsid failed");
3261 pid_t child2= xfork("daemonise second fork");
3262 if (child2) _exit(0);
3266 if (self_pid==-1) sysdie("getpid");
3277 if (!filemon_method_init()) {
3278 warn("no file monitoring available, polling");
3279 every(5,0,filepoll);
3282 every(period_seconds,1,period);
3288 void *run= oop_sys_run(sysloop);
3289 assert(run == OOP_ERROR);
3290 sysdie("event loop failed");