2 * Newsfeeds file entries should look like this:
3 * host.name.of.site[/exclude,exclude,...]\
4 * :pattern,pattern...[/distribution,distribution...]\
8 * sitename[/exclude,exclude,...]\
9 * :pattern,pattern...[/distribution,distribution...]\
15 * or might be blanked out
16 * <spc><spc><spc><spc>....
18 * site.name_duct.lock lock preventing multiple ducts
19 * holder of this lock is "duct"
20 * F site.name main feed file
21 * opened/created, then written, by innd
24 * tokens blanked out by duct when processed
25 * D site.name_duct temporary feed file during flush (or crash)
26 * hardlink created by duct
28 * site.name_duct.defer 431'd articles, still being written,
29 * created, written, used by duct
30 * site.name_backlog.lock lock taken out by innxmit wrapper
31 * holder and its child are "xmit"
32 * site.name_backlog_<date>.<inum>
33 * 431'd articles, ready for innxmit
34 * created (link/mv) by duct
37 * site.name_backlog_<letters> eg
38 * site.name_backlog_manual
39 * anything the sysadmin likes (eg, feed files
40 * from old feeds to be merged into this one)
41 * created (link/mv) by admin
48 BLATHER ABOUT NOT USING INNXMIT
50 scan for backlog files
51 take "old enough" backlog files one at a time and reprocess them
52 so need another input file - the current backlog file
53 inhibit scanning for backlog files only when
54 - last file not "old enough"
55 - no backlog files found and we haven't made one
57 also we have to start a new backlog file every (some interval)
59 TODO for backlog file inputs
60 - all code to search for and open these files
61 - write proper algorithm comment
72 <--------------------------------------'|
73 Nothing F, D both ENOENT |
76 duct: not not reading anything |
78 |`---------------------. |
79 | | duct times out waiting for F |
80 V innd creates F | duct exits |
82 Noduct GO TO Dropped |
85 duct: not running or not reading anything |
88 ,-->--+ <---------------------------------'|
89 | | duct opens F F exists |
93 | F: innd writing, duct reading |
96 | | duct decides time to flush |
97 | | duct makes hardlink |
99 | V <------------------------'|
101 | F == D: innd writing, duct reading both exist |
105 | Moved <----+------------<--'|
106 | F: ENOENT | F ENOENT |
107 | D: innd writing, duct reading | D exists |
109 | | duct requests flush of feed | |
110 | | (others can too, harmlessly) | |
114 | D: innd flushing, duct reading | |
116 | | inndcomm flush fails | |
117 | |`-------------------------->---------' |
119 | | inndcomm reports no such site |
120 | |`---------------------------------------------------- | -.
122 | | innd finishes writing D, creates F | |
123 | | inndcomm reports flush successful | |
126 | Separated <----------------' |
127 | F: innd writing F!=D /
128 | D: duct reading both exist /
130 | | duct gets to the end of D /
131 | | duct opens F too /
134 | F: innd writing, duct reading |
135 | D: duct finishing V
137 | | duct finishes processing D F: ENOENT
138 | V duct unlinks D D: duct reading
140 `--<--' | duct finishes
150 "duct reading" means innduct is reading the file but also
151 overwriting processed tokens.
158 /*----- general definitions, probably best not changed -----*/
160 #define PERIOD_SECONDS 60
162 #define CONNCHILD_ESTATUS_STREAM 4
163 #define CONNCHILD_ESTATUS_NOSTREAM 5
165 #define INNDCOMMCHILD_ESTATUS_FAIL 6
166 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
169 /*----- configuration options -----*/
171 static char *sitename, *feedfile;
172 static int max_connections=10, max_queue_per_conn=200;
173 static int connection_setup_timeout=200, port=119, try_stream=1;
174 static int inndcomm_flush_timeout=100, quiet_if_locked=0;
175 static const char *remote_host;
176 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
177 static const char *inndconffile;
179 static double accept_proportion;
180 static double nocheck_thresh_pct= 95.0;
181 static double nocheck_thresh; /* computed in main from _pct */
182 static double nocheck_decay_articles= 100; /* converted to _decay */
183 static double nocheck_decay; /* computed in main from _articles */
184 static int nocheck, nocheck_reported;
187 /*----- doubly linked lists -----*/
189 #define ISNODE(T) T *next, *back;
190 #define LIST(T) struct { T *head, *tail, *tailpred; int count; }
192 #define NODE(n) ((struct node*)&(n)->head)
194 #define LIST_ADDHEAD(l,n) \
195 (list_addhead((struct list*)&(l), NODE((n))), (void)(l).count++)
196 #define LIST_ADDTAIL(l,n) \
197 (list_addtail((struct list*)&(l), NODE((n))), (void)(l).count++)
199 #define LIST_REMHEAD(l) \
200 ((l).count ? ((l).count--, (void*)list_remhead((struct list*)&(l))) : 0)
201 #define LIST_REMTAIL(l) \
202 ((l).count ? ((l).count--, (void*)list_remtail((struct list*)&(l))) : 0)
203 #define LIST_REMOVE(l,n) \
204 (list_remove(NODE((n))), (void)(l).count--)
205 #define LIST_INSERT(l,n,pred) \
206 (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
209 /*----- statistics -----*/
211 #define RESULT_COUNTS \
220 #define RC_INDEX(x) RCI_##x
226 int articles[2 /* checked */][RCI_max];
230 /*----- transmission buffers -----*/
235 xk_Malloc, xk_Const, xk_Artdata;
247 /*----- core operational data structure types -----*/
251 int checked, sentbody;
259 typedef struct InputFile {
260 /* This is an instance of struct oop_readable */
261 struct oop_readable readable; /* first */
262 oop_readable_call *readable_callback;
263 void *readable_callback_user;
266 const char *path; /* ptr copy of path_<foo> or feedfile */
267 struct Filemon_Perfile *filemon;
270 long inprogress; /* no. of articles read but not processed */
287 int fd, max_queue, stream;
288 LIST(Article) queue; /* not yet told peer, or CHECK said send it */
289 LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
290 struct iovec xmit[CONNIOVS];
291 XmitDetails xmitd[CONNIOVS];
296 /*----- operational variables -----*/
298 static int since_connect_attempt;
300 static LIST(Conn) idle, working, full;
301 static LIST(Article) *queue;
303 static char *path_ductlock, *path_duct, *path_ductdefer;
305 #define SMS(newstate, periods, why) \
306 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
308 static StateMachineState sms;
310 static InputFile *main_input_file, *old_input_file, *backlog_input_file;
311 static int sm_period_counter;
314 /*----- function predeclarations -----*/
316 static void conn_check_work(Conn *conn);
318 static int filemon_init(void);
319 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
320 static void filemon_callback(void);
322 static void statemc_setstate(StateMachineState newsms, int periods,
323 const char *forlog, const char *why);
325 /*========== utility functions etc. ==========*/
327 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
329 static pid_t xfork(const char *what) {
333 if (child==-1) sysdie("cannot fork for %s",what);
334 if (!child) postfork(what);
338 static void on_fd_read_except(int fd, oop_call_fd callback) {
339 loop->on_fd(loop, fd, OOP_READ, callback, 0);
340 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
342 static void cancel_fd_read_except(int fd) {
343 loop->cancel_fd(loop, fd, OOP_READ);
344 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
347 static void report_child_status(const char *what, int status) {
348 if (WIFEXITED(status)) {
349 int es= WEXITSTATUS(status);
351 warn("%s: child died with error exit status %d",es);
352 } else if (WIFSIGNALED(status)) {
353 int sig= WTERMSIG(status);
354 const char *sigstr= strsignal(sig);
355 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
357 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
359 warn("%s: child died due to unknown fatal signal %d%s",
360 what, sig, coredump);
362 warn("%s: child died with unknown wait status %d", status);
366 static int xwaitpid(pid_t *pid, const char *what) {
369 r= kill(*pid, SIGKILL);
370 if (r) sysdie("cannot kill %s child", what);
372 pid_t got= waitpid(*pid, &status, WNOHANG);
373 if (got==-1) sysdie("cannot reap %s child", what);
380 /*========== logging ==========*/
382 static void logcore(int sysloglevel, const char *fmt, ...)
383 __attribute__((printf,2,3))
384 static void logcore(int sysloglevel, const char *fmt, ...) {
388 vsyslog(sysloglevel,fmt,al);
390 vfprintf(stderr,fmt,al);
395 static void logv(int sysloglevel, const char *pfx, int errnoval,
396 int exitstatus, const char *fmt, va_list al)
397 __attribute__((printf,4,0))
398 static void logv(int sysloglevel, const char *pfx, int errnoval,
399 int exitstatus, const char *fmt, va_list al) {
401 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
402 msgbuf[sizeof(msgbuf)-1]= 0;
404 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
405 sysloglevel= LOG_ERR; /* run by wrong user, probably */
407 logcore(sysloglevel, "<%s>%s: %s%s%s",
408 sitename, pfx, msgbuf,
409 errnoval>=0 ? ": " : "",
410 errnoval>=0 ? strerror(errnoval) : "");
413 #define logwrap(fn, pfx, sysloglevel, errno, estatus) \
414 static void fn(const char *fmt, ...) \
415 __attribute__((printf,1,2)); \
416 static void fn(const char *fmt, ...) { \
419 logv(sysloglevel, pfx, errno, estatus, fmt, al); \
422 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
423 logwrap(die, " critical", LOG_CRIT, -1, 16);
425 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
426 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
428 logwrap(syswarn, " warning", LOG_WARN, errno, 0);
429 logwrap(warn, " warning", LOG_WARN, -1, 0);
431 logwrap(notice, "", LOG_NOTICE, -1, 0);
432 logwrap(info, " info", LOG_INFO, -1, 0);
435 /*========== making new connections ==========*/
437 static int connecting_sockets[2]= {-1,-1};
438 static pid_t connecting_child;
440 static void connect_attempt_discard(void) {
441 if (connecting_sockets[0])
442 cancel_fd(connecting_sockets[0]);
444 perhaps_close(&connecting_sockets[0]);
445 perhaps_close(&connecting_sockets[1]);
447 if (connecting_child) {
448 int status= xwaitpid(&connecting_child, "connect");
450 if (!(WIFEXITED(status) ||
451 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
452 report_child_status("connect", status);
456 #define PREP_DECL_MSG_CMSG(msg) \
458 memset(&msg,0,sizeof(msg)); \
459 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
460 msg.msg_control= msg##cbuf; \
461 msg.msg_controllen= sizeof(msg##cbuf);
463 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
466 conn= xmalloc(sizeof(*conn));
467 memset(conn,0,sizeof(*conn));
470 struct cmsghdr *h= 0;
471 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
472 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
475 pid_t got= waitpid(connecting_child, &status, WNOHANG);
477 assert(got==connecting_child);
479 if (WIFEXITED(status) &&
480 (WEXITSTATUS(status) != 0
481 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
482 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
483 /* child already reported the problem */
484 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
485 warn("connect: connection attempt timed out");
486 } else if (!WIFEXITED(status)) {
487 report_child_status("connect", status);
488 /* that's probably the root cause then */
491 /* child is still running apparently, report the socket problem */
493 syswarn("connect: read from child socket failed");
494 else if (e == OOP_EXCEPTIONN)
495 warn("connect: unexpected exception on child socket");
497 warn("connect: unexpected EOF on child socket");
502 #define CHK(field, val) \
503 if (h->cmsg_##field != val) { \
504 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
507 CHK(level, SOL_SOCKET);
508 CHK(type, SCM_RIGHTS);
509 CHK(len, CMSG_LEN(sizeof(conn-b>fd)));
512 if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
514 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
516 pid_t got= waitpid(connecting_child, &status, 0);
517 if (got==-1) sysdie("connect: real wait for child");
518 assert(got == connecting_child);
521 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
522 int es= WEXITSTATUS(status);
524 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
525 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
527 fatal("connect: child gave unexpected exit status %d", es);
533 LIST_ADDHEAD(idle, conn);
534 notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
535 connect_attempt_discard();
536 check_master_queue();
541 perhaps_close(&conn->fd);
544 connect_attempt_discard();
547 static void connect_start() {
548 assert(!connecting_sockets[0]);
549 assert(!connecting_sockets[1]);
550 assert(!connecting_child);
552 notice("starting connection attempt");
554 r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
555 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
557 connecting_child= xfork("connection");
559 if (!connecting_child) {
560 FILE *cn_from, *cn_to;
561 char buf[NNTP_STRLEN+100];
562 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
564 r= close(connecting_sockets[0]);
565 if (r) sysdie("connect: close parent socket in child");
567 alarm(connection_setup_timeout);
568 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
570 sanitise_inplace(buf);
571 fatal("connect: rejected: %s", buf);
573 sysfatal("connect: connection attempt failed");
576 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
577 sysfatal("connect: authentication failed");
579 if (fputs("MODE STREAM\r\n", cn_to) ||
581 sysfatal("connect: could not send MODE STREAM");
582 buf[sizeof(buf)-1]= 0;
583 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
585 sysfatal("connect: could not read response to MODE STREAM");
587 fatal("connect: connection close in response to MODE STREAM");
592 sanitise_inplace(buf);
593 fatal("connect: response to MODE STREAM is too long: %.100s...",
596 l--; if (l>0 && buf[1-]=='\r') l--;
599 int rcode= strtoul(buf,&ep,10);
601 sanitise_inplace(buf);
602 fatal("connect: bad response to MODE STREAM: %.50s", buf);
606 exitstatus= CONNCHILD_ESTATUS_STREAM;
612 sanitise_inplace(buf);
613 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
618 int fd= fileno(cn_from);
620 PREP_DECL_MSG_CMSG(msg);
621 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
622 cmsg->cmsg_level= SOL_SOCKET;
623 cmsg->cmsg_type= SCM_RIGHTS;
624 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
625 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
627 msg.msg_controllen= cmsg->cmsg_len;
628 r= sendmsg(connecting_sockets[1], &msg, 0);
629 if (r) sysdie("sendmsg failed for new connection");
634 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
635 if (r) sysdie("connect: close child socket in parent");
637 on_fd_read_except(connecting_sockets[0], connchild_event);
641 connect_attempt_discard();
645 /*========== overall control of article flow ==========*/
647 static void check_master_queue(void) {
648 try reading current feed file;
653 Conn *last_assigned=0;
656 conn_assign_one_article(&working, &last_assigned);
657 } else if (idle.head) {
658 conn_assign_one_article(&idle, &last_assigned);
659 } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
660 !connecting_child && !connect_delay) {
661 connect_delay= reconnect_delay_periods;
667 conn_check_work(last_assigned);
670 static void conn_assign_one_article(LIST(Conn) *connlist,
671 Conn **last_assigned) {
672 Conn *conn= connlist->head;
674 LIST_REMOVE(*connlist, conn);
675 Article *art= LIST_REMHEAD(queue);
676 LIST_ADDTAIL(conn->queue, art);
677 LIST_ADD(*conn_determine_right_list(conn), conn);
679 /* This slightly odd arrangement is so that we call conn_check_work
680 * once after filling the queue for a new connection in
681 * check_master_queue, rather than for each article. */
682 if (conn != *last_assigned && *last_assigned)
683 conn_check_work(*last_assigned);
684 *last_assigned= conn;
687 static int conn_total_queued_articles(Conn *conn) {
688 return conn->sent.count + conn->queue.count;
691 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
692 int inqueue= conn_total_queued_articles(conn);
693 assert(inqueue <= max_queue);
694 if (inqueue == 0) return &idle;
695 if (inqueue == conn->max_queue) return &full;
699 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
704 static void conn_check_work(Conn *conn) {
707 conn_make_some_xmits(conn);
709 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
713 void *rp= conn_write_some_xmits(conn);
714 if (rp==OOP_CONTINUE) {
715 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
717 } else if (rp==OOP_HALT) {
720 /* transmitted everything */
728 /*========== article transmission ==========*/
730 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
731 XmitKind kind) { /* caller must then fill in details */
732 struct iovec *v= &conn->xmit[conn->xmitu];
733 XmitDetails *d= &conn->xmitd[conn->xmitu++];
740 static void xmit_noalloc(Conn *conn, const char *data, int len) {
741 xmit_core(conn,data,len, xk_Const);
743 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
745 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
746 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
750 static void xmit_free(XmitDetails *d) {
752 case xk_Malloc: free(d->info.malloc_tofree); break;
753 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
754 case xk_Const: break;
759 static void *conn_write_some_xmits(Conn *conn) {
761 * 0: nothing more to write, no need to call us again
762 * OOP_CONTINUE: more to write but fd not writeable
763 * OOP_HALT: disaster, have destroyed conn
766 int count= conn->xmitu;
767 if (!count) return 0;
769 if (count > IOV_MAX) count= IOV_MAX;
770 ssize_t rs= writev(conn->fd, conn->xmit, count);
772 if (errno == EAGAIN) return OOP_CONTINUE;
773 connfail(conn, "write failed: %s", strerror(errno));
778 for (done=0; rs && done<xmitu; done++) {
779 struct iovec *vp= &conn->xmit[done];
780 XmitDetails *dp= &conn->xmitd[done];
781 if (rs > vp->iov_len) {
789 int newu= conn->xmitu - done;
790 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
791 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
796 static void conn_make_some_xmits(Conn *conn) {
798 if (conn->xmitu+5 > CONNIOVS)
801 Article *art= LIST_REMHEAD(queue);
804 if (art->checked || (conn->stream && nocheck)) {
805 /* actually send it */
807 ARTHANDLE *artdata= SMretrieve();
811 XMIT_LITERAL("TAKETHIS ");
812 xmit_noalloc(conn, art->mid, art->midlen);
813 XMIT_LITERAL("\r\n");
814 xmit_artbody(conn, artdata);
817 /* we got 235 from IHAVE */
819 xmit_artbody(conn, artdata);
821 XMIT_LITERAL(".\r\n");
826 LIST_ADDTAIL(conn->sent, art);
828 art->ipf->counts[art->checked].sent++;
834 XMIT_LITERAL("IHAVE ");
836 XMIT_LITERAL("CHECK ");
837 xmit_noalloc(art->mid, art->midlen);
838 XMIT_LITERAL("\r\n");
840 LIST_ADDTAIL(conn->sent, art);
841 art->ipf->counts[art->checked].offered++;
847 /*========== handling responses from peer ==========*/
849 static const oop_rd_style peer_rd_style= {
850 OOP_RD_DELIM_STRIP, '\n',
852 OOP_RD_SHORTREC_FORBID
855 static Article *article_reply_check(Connection *conn, const char *response,
856 int code_indicates_streaming,
857 const char *sanitised_response) {
858 Article *art= LIST_REMHEAD(conn->sent);
862 "peer gave unexpected response when no commands outstanding: %s",
867 if (code_indicates_streaming) {
868 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
870 connfail("peer gave streaming response code "
871 " to IHAVE or subsequent body: %s", sanitised_response);
874 const char *got_mid= response+4;
875 int got_midlen= strcspn(got_mid, " \n\r");
876 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
877 connfail("peer gave streaming response with syntactically invalid"
878 " messageid: %s", sanitised_response);
881 if (got_midlen != art->midlen ||
882 memcmp(got_mid, art->messageid, got_midlen)) {
883 connfail("peer gave streaming response code to wrong article -"
884 " probable synchronisation problem; we offered: %s;"
886 art->messageid, sanitised_response);
891 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
900 static void update_nocheck(int accepted) {
901 accept_proportion *= accept_decay;
902 accept_proportion += accepted;
903 nocheck= accept_proportion >= nocheck_thresh;
904 if (nocheck && !nocheck_reported) {
905 notice("entering nocheck mode for the first time");
910 static void article_done(Connection *conn, Article *art, int whichcount) {
912 art->ipf->counts.articles[art->checked][whichcount]++;
913 if (whichcount == RC_accepted) update_nocheck(1);
914 else if (whichcount == RC_unwanted) update_nocheck(0);
916 InputFile *ipf= art->ipf;
917 while (art->blanklen) {
918 static const char spaces[]=
923 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
924 int r= pwrite(ipf->fd, spaces, w, art->offset);
926 if (errno==EINTR) continue;
927 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
928 art->messageid, art->blanklen, art->offset, ipf->path);
930 assert(r>=0 && r<=w);
936 assert(ipf->inprogress >= 0);
938 if (!ipf->inprogress)
939 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, ipf);
944 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
945 const char *errmsg, int errnoval,
946 const char *data, size_t recsz, void *conn_v) {
948 connfail(conn, "error receiving from peer: %s", errmsg);
952 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
953 const char *errmsg, int errnoval,
954 const char *data, size_t recsz, void *conn_v) {
957 if (ev == OOP_RD_EOF) {
958 connfail(conn, "unexpected EOF from peer");
961 assert(ev == OOP_RD_OK);
964 unsigned long code= strtoul(data, &ep, 10);
965 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
971 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
973 if (!c) { *q++= '\''; break; }
974 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
975 sprintf(q,"\\x%02x",c);
978 connfail(conn, "badly formatted response from peer: %s", sanibuf);
982 if (conn->quitting) {
984 connfail(conn, "peer gave failure response to QUIT: %s", sani);
993 #define GET_ARTICLE \
994 art= article_reply_check(conn, data, code_streaming, sani); \
995 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
997 #define ARTICLE_DEALTWITH(streaming,how) \
998 code_streaming= (streaming) \
1000 article_done(conn, art, RC_##how); break;
1002 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1004 int code_streaming= 0;
1008 case 400: PEERBADMSG("peer stopped accepting articles");
1009 case 503: PEERBADMSG("peer timed us out");
1010 default: PEERBADMSG("peer sent unexpected message");
1012 case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
1013 case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
1015 case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
1016 case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
1018 case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
1019 case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
1021 case 238: /* CHECK says send it */
1023 case 335: /* IHAVE says send it */
1025 count_checkedwanted++;
1026 LIST_ADDTAIL(conn->queue);
1028 connfail("peer gave %d response to article body: %s",code, sani);
1029 return OOP_CONTINUE;
1034 case 431: /* CHECK or TAKETHIS says try later */
1036 case 436: /* IHAVE says try later */
1038 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1040 sysfatal("write to defer file %s",path_ductdefer);
1041 article_done(conn, art, RC_deferred);
1046 check_check_work(conn);
1047 return OOP_CONTINUE;
1051 /*========== monitoring of input files ==========*/
1053 static void feedfile_eof(InputFile *ipf) {
1054 assert(ipf != main_input_file); /* promised by tailing_try_read */
1056 inputfile_tailing_stop(ipf);
1058 if (ipf == backlog_input_file) {
1059 assert(ipf->fd >= 0);
1060 if (close(ipf->fd)) sysdie("could not close backlog file %s", ipf->path);
1065 assert(ipf == old_input_file);
1067 inputfile_tailing_stop(ipf);
1068 assert(ipf->fd >= 0);
1069 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1072 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1074 if (main_input_file)
1075 inputfile_tailing_start(main_input_file);
1078 static InputFile *open_input_file(const char *path) {
1079 int fd= open(path, O_RDONLY);
1081 if (errno==ENOENT) return 0;
1082 sysfatal("unable to open input file %s", path);
1085 InputFile *ipf= xmalloc(sizeof(InputFile));
1086 memset(ipf,0,sizeof(*ipf));
1088 ipf->readable.on_readable= tailing_on_readable;
1089 ipf->readable.on_cancel= tailing_on_cancel;
1090 ipf->readable.try_read= tailing_try_read;
1098 static void close_input_file(InputFile *ipf) {
1099 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1100 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1101 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1102 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1105 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1107 fixme maybe free ipf->path;
1113 /*---------- dealing with articles read in the input file ----------*/
1115 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1116 oop_rd_event ev, const char *errmsg,
1118 const char *data, size_t recsz,
1120 InputFile *ipf= ipf_v;
1122 char tokentextbuf[sizeof(TOKEN)*2+3];
1124 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1126 if (data[0] && data[0]!=' ') {
1127 char *space= strchr(data,' ');
1128 int tokenlen= space-data;
1129 int midlen= (int)recsz-tokenlen-1;
1130 if (midlen < 0) goto bad_data;
1132 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1133 memcpy(tokentextbuf, data, tokenlen);
1134 tokentextbuf[tokenlen]= 0;
1135 if (!IsToken(tokentextbuf)) goto bad_data;
1137 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1138 art->offset= ipf->offset;
1139 art->blanklen= recsz;
1140 art->midlen= midlen;
1141 art->checked= art->sentbody= 0;
1142 art->ipf= ipf; ipf->inprogress++;
1143 art->token= TextToToken(tokentextbuf);
1144 strcpy(art->messageid, space+1);
1145 LIST_ADDTAIL(queue, art);
1147 ipf->offset += recsz + 1;
1149 if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
1150 notice("starting flush (%lu >= %lu)",
1151 (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1153 int r= link(feedfile, duct_path);
1154 if (r) sysdie("link feedfile %s to ductfile %s", feedfile, dut_path);
1157 r= unlink(feedfile);
1158 if (r) sysdie("unlink old feedfile link %s", feedfile);
1161 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1164 check_master_queue();
1168 /*========== tailing input file ==========*/
1170 static void filemon_start(InputFile *ipf) {
1171 assert(!ipf->filemon);
1173 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1174 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1175 filemon_method_startfile(ipf, ipf->filemon);
1178 static void filemon_stop(InputFile *ipf) {
1179 if (!ipf->filemon) return;
1180 filemon_method_stopfile(ipf, ipf->filemon);
1185 static void filemon_callback(InputFile *ipf) {
1186 ipf->readable_callback(ipf->readable_callback_user);
1189 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1191 InputFile *ipf= user;
1192 return ipf->readable_callback(ipf->readable_callback_user);
1195 static void on_cancel(struct oop_readable *rable) {
1196 InputFile *ipf= (void*)rable;
1198 if (ipf->filemon) filemon_stopfile(ipf);
1199 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1200 ipf->readable_callback= 0;
1203 static int tailing_on_readable(struct oop_readable *rable,
1204 oop_readable_call *cb, void *user) {
1205 InputFile *ipf= (void*)rable;
1207 tailing_on_cancel(rable);
1208 ipf->readable_callback= cb;
1209 ipf->readable_callback_user= user;
1210 filemon_startfile(ipf);
1212 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1216 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1218 InputFile *ipf= (void*)rable;
1220 ssize_t r= read(ipf->fd, buffer, length);
1222 if (errno==EINTR) continue;
1226 if (ipf==main_input_file) {
1229 } else if (ipf==old_input_file) {
1231 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1232 } else if (ipf==backlog_input_file) {
1242 /*---------- filemon implemented with inotify ----------*/
1244 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1245 #define HAVE_FILEMON
1247 #include <linux/inotify.h>
1249 static int filemon_inotify_fd;
1250 static int filemon_inotify_wdmax;
1251 static InputFile **filemon_inotify_wd2ipf;
1253 typedef struct Filemon_Perfile {
1255 } Filemon_Inotify_Perfile;
1257 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1258 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1259 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1261 if (wd >= filemon_inotify_wdmax) {
1263 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1264 sizeof(*filemon_inotify_wd2ipf) * newmax);
1265 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1266 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1267 filemon_inotify_wdmax= newmax;
1270 assert(!filemon_inotify_wd2ipf[wd]);
1271 filemon_inotify_wd2ipf[wd]= ipf;
1276 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1278 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1279 if (r) sysdie("inotify_rm_watch");
1280 filemon_inotify_wd2ipf[wd]= 0;
1283 static void *filemon_inotify_readable(oop_source *lp, int fd,
1284 oop_event e, void *u) {
1285 struct inotify_event iev;
1287 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1289 if (errno==EAGAIN) break;
1290 sysdie("read from inotify master");
1291 } else if (r==sizeof(iev)) {
1292 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1294 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1296 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1297 filemon_callback(ipf);
1299 return OOP_CONTINUE;
1302 static int filemon_method_init(void) {
1303 filemon_inotify_fd= inotify_init();
1304 if (filemon_inotify_fd<0) {
1305 syswarn("could not initialise inotify: inotify_init failed");
1309 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1314 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1316 /*---------- filemon dummy implementation ----------*/
1318 #if !defined(HAVE_FILEMON)
1320 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1322 static int filemon_method_init(void) { return 0; }
1323 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1324 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1326 #endif /* !HAVE_FILEMON */
1328 /*---------- interface to start and stop an input file ----------*/
1330 static const oop_rd_style feedfile_rdstyle= {
1331 OOP_RD_DELIM_STRIP, '\n',
1333 OOP_RD_SHORTREC_EOF,
1336 static void inputfile_tailing_start(InputFile *ipf) {
1338 ipf->readable->on_readable= tailing_on_readable;
1339 ipf->readable->on_cancel= tailing_on_cancel;
1340 ipf->readable->try_read= tailing_try_read;
1341 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1342 ipf->readable->delete_kill= 0;
1344 ipf->readable_callback= 0;
1345 ipf->readable_callback_user= 0;
1347 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1350 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1351 feedfile_got_article,ipf, feedfile_problem,ipf);
1352 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1355 static void inputfile_tailing_stop(InputFile *ipf) {
1357 oop_rd_delete(ipf->rd);
1359 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1363 /*========== interaction with innd ==========*/
1365 /* See official state diagram at top of file. We implement
1375 |`--------------------------.
1376 | | install defer as backlog
1377 | OPEN F SUCCEEDS | exit
1382 | [Normal] =========
1386 | | F IS SO BIG WE SHOULD FLUSH
1390 | | our handle onto F is now onto D
1393 | |<---------------------------------------------------.
1395 | | spawn inndcomm flush |
1403 | | INNDCOMM FLUSH FAILS ^
1404 | |`----------------------->----------. |
1406 | | NO SUCH SITE V |
1407 ^ |`--------------->----. =========== |
1413 | | \ | TIME TO RETRY |
1414 | | \ `----------------'
1418 | ============= ============
1419 | SEPARATED/ DROPPING/
1420 | old->fd>=0 old->fd>=0
1421 | [Separated] [Dropping]
1422 | main F idle main none
1423 | old D tail old D tail
1424 | ============= ============
1426 ^ | EOF ON D | EOF ON D
1428 | =============== ===============
1429 | SEPARATED/ DROPPING/
1430 | old->fd==-1 old->fd==-1
1431 | [Finishing] [Dropping]
1432 | main F tail main none
1433 | old D closed old D closed
1434 | =============== ===============
1436 | | ALL D PROCESSED | ALL D PROCESSED
1437 | V install defer as backlog V install defer as backlog
1438 ^ | close D | close D
1439 | | unlink D | unlink D
1440 | | start new defer | exit
1442 `----------' ==========
1448 static void open_defer(void) {
1452 defer= fopen(path_ductdefer, "a+");
1453 if (!defer) sysfatal("could not open defer file %s", path_ductdefer);
1455 /* truncate away any half-written records */
1457 r= fstat(fileno(defer), &stab);
1458 if (r) sysdie("could not stat newly opened defer file %s", path_ductdefer);
1460 if (stab.st_size > LONG_MAX)
1461 die("defer file %s size is far too large", path_ductdefer);
1466 long orgsize= stab.st_size;
1467 long truncto= stab.st_size;
1469 if (!truncto) break; /* was only (if anything) one half-truncated record */
1470 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1471 sysdie("seek in defer file %s while truncating partial", path_ductdefer);
1476 sysdie("failed read from defer file %s", path_ductdefer);
1478 die("defer file %s shrank while we were checking it!", path_ductdefer);
1484 if (stab.st_size != truncto) {
1485 warn("truncating half-record at end of defer file %s -"
1486 " shrinking by %ld bytes from %ld to %ld",
1487 path_ductdefer, orgsize - truncto, orgsize, truncto);
1490 sysfatal("could not flush defer file %s", path_ductdefer);
1491 if (ftruncate(fileno(defer), truncto))
1492 sysdie("could not truncate defer file %s", path_ductdefer);
1495 info("continuing existing defer file %s (%ld bytes)",
1496 path_ductdefer, orgsize);
1498 if (fseek(defer, truncto, SEEK_SET))
1499 sysdie("could not seek to new end of defer file %s", path_ductdefer);
1502 static void statemc_init(void) {
1505 path_ductlock= xasprintf("%s_duct.lock", feedfile);
1506 path_duct= xasprintf("%s_duct", feedfile);
1507 path_ductdefer= xasprintf("%s_duct.defer", feedfile);
1509 if (lstat(path_ductdefer, &stab)) {
1510 if (errno!=ENOENT) sysdie("could not check defer file %s", path_defer);
1512 if (!S_ISREG(stab.st_mode))
1513 die("defer file %s not a plain file (mode 0%lo)",
1514 path_defer, (unsigned long)stab.st_mode);
1515 switch (stab.st_nlink==1) {
1516 case 1: /* ok */ break;
1518 if (unlink(path_defer))
1519 sysdie("could not unlink stale defer file link %s (presumably"
1520 " hardlink to backlog file)", path_defer);
1523 die("defer file %s has unexpected link count %d",
1524 path_defer, stab.st_nlink);
1529 int lockfd= open(path_ductlock, O_CREAT|O_RDWR, 0600);
1530 if (lockfd<0) sysfatal("open lockfile %s", path_ductlock);
1533 memset(&fl,0,sizeof(fl));
1535 fl.l_whence= SEEK_SET;
1536 r= fcntl(lockfd, F_SETLK, &fl);
1538 if (errno==EACCES || errno==EAGAIN) {
1539 if (quiet_if_locked) exit(0);
1540 fatal("another duct holds the lockfile");
1542 sysdie("fcntl F_SETLK lockfile %s", path_ductlock);
1545 InputFile *file_d= open_input_file(path_duct);
1548 struct stat stab_f, stab_d;
1550 r= stat(feedfile, &stab_f);
1552 if (errno!=ENOENT) sysdie("check feed file %s", feedfile);
1553 /* D exists, F ENOENT => Moved */
1557 /* F and D both exist */
1559 r= fstat(file_d->fd, &stab_d);
1560 if (r) sysdie("check duct file %s", ductfile);
1562 if (stab_d.st_ino == stab_f.st_ino &&
1563 stab_d.st_dev == stab_f.st_dev) {
1564 /* F==D => Hardlinked*/
1565 r= unlink(path_duct);
1566 if (r) sysdie("unlink feed file %s during startup", feedfile);
1569 startup_set_input_file(file_d);
1570 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1572 /* F!=D => Separated */
1573 SMS(SEPARATED, 0, "found both old and current feed files");
1574 startup_set_input_file(file_d);
1576 } else { /*!file_d*/
1577 SMS(WAITING, open_wait_periods, "no feed file currently exists");
1581 static void statemc_poll(void) {
1582 if (sms==sm_WAITING) { statemc_waiting_poll(); return; }
1584 if (!sm_period_counter) return;
1585 sm_period_counter--;
1586 assert(sm_period_counter>=0);
1588 if (sm_period_counter) return;
1591 fatal("timed out waiting for innd to create feed file %s", feedfile);
1593 spawn_inndcomm_flush(void);
1600 static void statemc_waiting_poll(void) {
1601 InputFile *file_f= open_input_file(feedfile);
1602 if (!file_f) return;
1603 startup_set_input_file(file_d);
1604 SMS(NORMAL, 0, "found and opened feed file");
1607 static void startup_set_input_file(InputFile *f) {
1608 assert(!main_input_file);
1610 inputfile_tailing_start(f);
1613 static void *statemc_check_input_done(oop_source *lp,
1614 struct timeval now, void *ipf_v) {
1615 InputFile *ipf= ipf_v;
1618 if (ipf->inprogress) return; /* new article in the meantime */
1619 if (ipf->fd >= 0); return; /* not had EOF */
1621 if (ipf == backlog_input_file) {
1622 notice_processed(ipf,"backlog file",ipf->path);
1623 if (unlink(ipf->path))
1624 sysdie("could not unlink done backlog file %s", ipf->path);
1625 close_input_file(ipf);
1626 fixme trigger search for new backlog file;
1629 assert(ipf == old_input_file);
1630 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1632 notice_processed(ipf,"feed file",0);
1634 r= fstat(fileno(defer), &stab);
1635 if (r) sysdie("check defer file %s", path_defer);
1637 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1640 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1641 (unsigned long)now.tv_sec,
1642 (unsigned long)stab.st_ino);
1643 if (link(path_defer, path_backlog))
1644 sysfatal("could not install defer file %s as backlog file %s",
1645 path_defer, backlog);
1646 if (unlink(path_defer))
1647 sysdie("could not unlink old defer link %s to backlog file %s",
1648 path_defer, backlog);
1650 if (unlink(path_duct))
1651 sysdie("could not unlink old duct file %s", path_duct);
1653 if (sms==sm_DROPPING) {
1654 notice("feed dropped and our work is complete"
1655 " (but check for backlog files)");
1661 close_input_file(old_input_file);
1664 notice("flush complete");
1665 SMS(NORMAL, 0, "flush complete");
1668 static void statemc_setstate(StateMachineState newsms, int periods,
1669 const char *forlog, const char *why) {
1671 sm_period_counter= periods;
1673 info("%s[%d] %s",periods,forlog,why);
1675 info("%s %s",forlog,why);
1679 /*========== flushing the feed ==========*/
1681 static pid_t inndcomm_child;
1683 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1684 assert(inndcomm_child);
1685 int status= xwaitpid(&inndcomm_child, "inndcomm");
1686 loop->cancel_fd(fd);
1689 assert(!old_input_file);
1691 if (WIFEXITED(status)) {
1692 switch (WEXITSTATUS(status)) {
1694 case INNDCOMMCHILD_ESTATUS_FAIL:
1697 case INNDCOMMCHILD_ESTATUS_NONESUCH:
1698 warn("feed has been dropped by innd, finishing up");
1699 old_input_file= main_input_file;
1701 SMS(DROPPING, 0, "dropped by innd");
1702 return OOP_CONTINUE;
1705 old_input_file= main_input_file;
1706 main_input_file= open_input_file(feedfile);
1707 if (!main_input_file)
1708 die("flush succeeded but feedfile %s does not exist!", feedfile);
1709 SMS(SEPARATED, 0, "feed file missing");
1710 return OOP_CONTINUE;
1713 goto unexpected_exitstatus;
1716 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1717 warn("flush timed out trying to talk to innd");
1720 unexpected_exitstatus:
1721 report_child_status("inndcomm child", status);
1725 SMS(FLUSHFAIL, flushfail_retry_periods, "flush failed, will retry");
1728 static void inndcommfail(const char *what) {
1729 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1730 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1733 void spawn_inndcomm_flush(void) {
1736 assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1737 assert(!inndcomm_child);
1739 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1741 inndcomm_child= xfork();
1743 if (!inndcomm_child) {
1744 static char flushargv[2]= { sitename, 0 };
1749 alarm(inndcomm_flush_timeout);
1750 r= ICCopen(); if (r) inndcommfail("connect");
1751 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
1752 if (!r) exit(0); /* yay! */
1754 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1755 syswarn("innd ctlinnd flush failed: innd said %s", reply);
1756 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1760 int sentinel_fd= pipefds[0];
1761 on_fd_read_except(sentinel_fd, inndcomm_event);
1763 SMS(FLUSHING, 0, "flush is in progress");
1766 /*========== main program ==========*/
1768 static void postfork_inputfile(InputFile *ipf) {
1770 assert(ipf->fd >= 0);
1775 static void postfork_conns(Connection *conn) {
1782 static void postfork_stdio(FILE *f) {
1783 /* we have no stdio streams that are buffered long-term */
1787 static void postfork(const char *what) {
1788 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1789 sysdie("%s child: failed to reset SIGPIPE");
1791 postfork_inputfile(main_input_file);
1792 postfork_inputfile(old_input_file);
1793 postfork_conns(idle.head);
1794 postfork_conns(working.head);
1795 postfork_conns(full.head);
1796 postfork_stdio(defer);
1800 #define EVERY(what, interval, body) \
1801 static const struct timeval what##_timeout = { 5, 0 }; \
1802 static void what##_schedule(void); \
1803 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1805 what##_schedule(); \
1807 static void what##_schedule(void) { \
1808 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
1811 EVERY(filepoll, {5,0}, { check_master_queue(); })
1813 EVERY(period, {PERIOD_SECONDS,0}, {
1814 if (connect_delay) connect_delay--;
1816 check_master_queue();
1820 /*========== option parsing ==========*/
1823 of_seconds= 001000u;
1824 of_boolean= 002000u;
1827 typedef struct Option Option;
1828 typedef void OptionParser(const Option*, const char *val);
1838 void op_integer(const Option *o, const char *val) {
1841 unsigned long ul= strtoul(val,&ep,10);
1842 if (*ep || ep==val || errno || ul>INT_MAX)
1843 badusage("bad integer value for %s",o->long);
1844 int *store= o->store;
1848 void op_double(const Option *o, const char *val) {
1849 int *store= o->store;
1852 *store= strtod(val, &ep);
1853 if (*ep || ep==val || errno)
1854 badusage("bad floating point value for %s",o->long);
1857 void op_string(const Option *o, const char *val) {
1858 char **store= o->store;
1863 void op_seconds(const Option *o, const char *val) {
1864 int *store= o->store;
1867 double v= strtod(val,&ep);
1868 if (ep==val) badusage("bad time/duration value for %s",o->long);
1870 if (!*ep || !strcmp(ep,"s")) unit= 1;
1871 else if (!strcmp(ep,"m")) unit= 60;
1872 else if (!strcmp(ep,"h")) unit= 3600;
1873 else if (!strcmp(ep,"d")) unit= 86400;
1874 else badusage("bad units %s for time/duration value for %s",ep,o->long);
1878 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
1882 void op_periods_rndup(const Option *o, const char *val) {
1883 int *store= o->store;
1885 *store += PERIOD_SECONDS-1;
1886 *store /= PERIOD_SECONDS;
1889 void op_periods_booltrue(const Option *o, const char *val) {
1890 int *store= o->store;
1893 void op_periods_boolfalse(const Option *o, const char *val) {
1894 int *store= o->store;
1898 static const Option options[]= {
1899 { 0, "max-connections", &max_connections op_integer },
1900 { 0, "streaming", &try_stream, op_booltrue, 1 },
1901 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
1902 {'h',"host", &remote_host, op_string },
1903 {'P',"port", &port op_integer },
1904 { 0, "inndconf", &inndconffile, op_string },
1905 {'f',"feedfile", &feedfile, op_string },
1906 {'q',"quiet-multiple", &quiet_if_locked, op_booltrue, 1 },
1907 { 0, "no-quiet-multiple", &quiet_if_locked, op_boolfalse, 1 },
1908 {'d',"daemon", &become_daemon, op_booltrue, 1 },
1909 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
1911 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
1912 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
1914 { 0, "max-queue-size", &max_queue_per_conn op_integer },
1915 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
1916 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
1917 { 0, "feedfile-open-timeout", &open_wait_periods, op_periods_rndup },
1918 { 0, "connection-timeout", &connection_timeout, op_seconds },
1919 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
1922 int main(int argc, char **argv) {
1928 if (*arg != '-') break;
1929 if (!strcmp(arg,"--")) { arg= *++argv; break; }
1931 while ((a= *++arg)) {
1935 char *equals= strchr(arg,'=');
1936 int len= equals ? (equals - arg) : strlen(arg);
1937 for (o=options; o->long; o++)
1938 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
1940 badusage("unknown long option --%s",arg);
1943 if (equals) badusage("option --%s does not take a value",o->long);
1945 } else if (equals) {
1949 if (!arg) badusage("option --%s needs a value",o->long);
1952 break; /* eaten the whole argument now */
1954 for (o=options; o->long; o++)
1957 badusage("unknown short option -%c",a);
1964 if (!arg) badusage("option -%c needs a value",o->short);
1967 break; /* eaten the whole argument now */
1972 if (!arg) badusage("need site name argument");
1973 if (*++argv) badusage("too many non-option arguments");
1976 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
1977 badusage("nocheck threshold percentage must be between 0..100");
1978 nocheck_thresh= nocheck_thresh_pct * 0.01;
1980 if (nocheck_decay_articles < 0.1)
1981 badusage("nocheck decay articles must be at least 0.1");
1982 nocheck_decay= 1 - 1/nocheck_decay_articles;
1984 innconf_read(inndconffile);
1987 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
1988 else if (!feedfile[0])
1989 badusage("feed filename must be nonempty");
1990 else if (feedfile[strlen(feedfile)-1]=='/')
1991 feedfile= xasprintf("%s%s",feedfile,sitename);
1993 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1994 sysdie("could not ignore SIGPIPE");
1996 if (become_daemon) {
1997 for (i=3; i<255; i++)
1998 /* do this now before we open syslog, etc. */
2000 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2002 int null= open("/dev/null",O_RDWR);
2003 if (null<0) sysdie("failed to open /dev/null");
2009 pid_t child1= xfork("daemonise first fork");
2010 if (child1) _exit(0);
2012 pid_t sid= setsid();
2013 if (sid != child1) sysdie("setsid failed");
2015 pid_t child2= xfork("daemonise second fork");
2016 if (child2) _exit(0);
2021 if (!filemon_init()) {
2022 warn("no file monitoring available, polling");
2023 filepoll_schedule();