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)
68 <--------------------------------------'|
69 Nothing F, D both ENOENT |
72 duct: not not reading anything |
74 |`---------------------. |
75 | | duct times out waiting for F |
76 V innd creates F | duct exits |
78 Noduct GO TO Dropped |
81 duct: not running or not reading anything |
84 ,-->--+ <---------------------------------'|
85 | | duct opens F F exists |
89 | F: innd writing, duct reading |
92 | | duct decides time to flush |
93 | | duct makes hardlink |
95 | V <------------------------'|
97 | F == D: innd writing, duct reading both exist |
101 | Moved <----+------------<--'|
102 | F: ENOENT | F ENOENT |
103 | D: innd writing, duct reading | D exists |
105 | | duct requests flush of feed | |
106 | | (others can too, harmlessly) | |
110 | D: innd flushing, duct reading | |
112 | | inndcomm flush fails | |
113 | |`-------------------------->---------' |
115 | | inndcomm reports no such site |
116 | |`---------------------------------------------------- | -.
118 | | innd finishes writing D, creates F | |
119 | | inndcomm reports flush successful | |
122 | Separated <----------------' |
123 | F: innd writing F!=D /
124 | D: duct reading both exist /
126 | | duct gets to the end of D /
127 | | duct opens F too /
130 | F: innd writing, duct reading |
131 | D: duct finishing V
133 | | duct finishes processing D F: ENOENT
134 | V duct unlinks D D: duct reading
136 `--<--' | duct finishes
146 "duct reading" means innduct is reading the file but also
147 overwriting processed tokens.
154 /*----- general definitions, probably best not changed -----*/
156 #define PERIOD_SECONDS 60
158 #define CONNCHILD_ESTATUS_STREAM 4
159 #define CONNCHILD_ESTATUS_NOSTREAM 5
161 #define INNDCOMMCHILD_ESTATUS_FAIL 6
162 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
165 /*----- configuration options -----*/
167 static char *sitename, *feedfile;
168 static int max_connections=10, max_queue_per_conn=200;
169 static int connection_setup_timeout=200, port=119, try_stream=1;
170 static int inndcomm_flush_timeout=100, quiet_if_locked=0;
171 static const char *remote_host;
172 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
173 static const char *inndconffile;
175 static double accept_proportion;
176 static double nocheck_thresh_pct= 95.0;
177 static double nocheck_thresh; /* computed in main from _pct */
178 static double nocheck_decay_articles= 100; /* converted to _decay */
179 static double nocheck_decay; /* computed in main from _articles */
180 static int nocheck, nocheck_reported;
183 /*----- doubly linked lists -----*/
185 #define ISNODE(T) T *next, *back;
186 #define LIST(T) struct { T *head, *tail, *tailpred; int count; }
188 #define NODE(n) ((struct node*)&(n)->head)
190 #define LIST_ADDHEAD(l,n) \
191 (list_addhead((struct list*)&(l), NODE((n))), (void)(l).count++)
192 #define LIST_ADDTAIL(l,n) \
193 (list_addtail((struct list*)&(l), NODE((n))), (void)(l).count++)
195 #define LIST_REMHEAD(l) \
196 ((l).count ? ((l).count--, (void*)list_remhead((struct list*)&(l))) : 0)
197 #define LIST_REMTAIL(l) \
198 ((l).count ? ((l).count--, (void*)list_remtail((struct list*)&(l))) : 0)
199 #define LIST_REMOVE(l,n) \
200 (list_remove(NODE((n))), (void)(l).count--)
201 #define LIST_INSERT(l,n,pred) \
202 (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
205 /*----- statistics -----*/
207 #define RESULT_COUNTS \
216 #define RC_INDEX(x) RCI_##x
222 int articles[2 /* checked */][RCI_max];
226 /*----- transmission buffers -----*/
231 xk_Malloc, xk_Const, xk_Artdata;
243 /*----- core operational data structure types -----*/
247 int checked, sentbody;
256 /* This is an instance of struct oop_readable */
257 struct oop_readable readable; /* first */
258 oop_readable_call *readable_callback;
259 void *readable_callback_user;
262 const char *path; /* ptr copy of path_<foo> or feedfile */
263 struct Filemon_Perfile *filemon;
266 long inprogress; /* no. of articles read but not processed */
281 int fd, max_queue, stream;
282 LIST(Article) queue; /* not yet told peer, or CHECK said send it */
283 LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
284 struct iovec xmit[CONNIOVS];
285 XmitDetails xmitd[CONNIOVS];
290 /*----- operational variables -----*/
292 static int since_connect_attempt;
294 static LIST(Conn) idle, working, full;
295 static LIST(Article) *queue;
297 static char *path_ductlock, *path_duct, *path_ductdefer;
299 #define SMS(newstate, periods, why) \
300 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
302 static StateMachineState sms;
304 static InputFile *main_input_file, *old_input_file;
305 static int sm_period_counter;
308 /*----- function predeclarations -----*/
310 static void conn_check_work(Conn *conn);
312 static int filemon_init(void);
313 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
314 static void filemon_callback(void);
316 static void statemc_setstate(StateMachineState newsms, int periods,
317 const char *forlog, const char *why);
319 /*========== utility functions etc. ==========*/
321 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
323 static pid_t xfork(const char *what) {
327 if (child==-1) sysdie("cannot fork for %s",what);
328 if (!child) postfork(what);
332 static void on_fd_read_except(int fd, oop_call_fd callback) {
333 loop->on_fd(loop, fd, OOP_READ, callback, 0);
334 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
336 static void cancel_fd_read_except(int fd) {
337 loop->cancel_fd(loop, fd, OOP_READ);
338 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
341 static void report_child_status(const char *what, int status) {
342 if (WIFEXITED(status)) {
343 int es= WEXITSTATUS(status);
345 warn("%s: child died with error exit status %d",es);
346 } else if (WIFSIGNALED(status)) {
347 int sig= WTERMSIG(status);
348 const char *sigstr= strsignal(sig);
349 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
351 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
353 warn("%s: child died due to unknown fatal signal %d%s",
354 what, sig, coredump);
356 warn("%s: child died with unknown wait status %d", status);
360 static int xwaitpid(pid_t *pid, const char *what) {
363 r= kill(*pid, SIGKILL);
364 if (r) sysdie("cannot kill %s child", what);
366 pid_t got= waitpid(*pid, &status, WNOHANG);
367 if (got==-1) sysdie("cannot reap %s child", what);
374 /*========== logging ==========*/
376 static void logcore(int sysloglevel, const char *fmt, ...)
377 __attribute__((printf,2,3))
378 static void logcore(int sysloglevel, const char *fmt, ...) {
382 vsyslog(sysloglevel,fmt,al);
384 vfprintf(stderr,fmt,al);
389 static void logv(int sysloglevel, const char *pfx, int errnoval,
390 int exitstatus, const char *fmt, va_list al)
391 __attribute__((printf,4,0))
392 static void logv(int sysloglevel, const char *pfx, int errnoval,
393 int exitstatus, const char *fmt, va_list al) {
395 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
396 msgbuf[sizeof(msgbuf)-1]= 0;
398 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
399 sysloglevel= LOG_ERR; /* run by wrong user, probably */
401 logcore(sysloglevel, "<%s>%s: %s%s%s",
402 sitename, pfx, msgbuf,
403 errnoval>=0 ? ": " : "",
404 errnoval>=0 ? strerror(errnoval) : "");
407 #define logwrap(fn, pfx, sysloglevel, errno, estatus) \
408 static void fn(const char *fmt, ...) \
409 __attribute__((printf,1,2)); \
410 static void fn(const char *fmt, ...) { \
413 logv(sysloglevel, pfx, errno, estatus, fmt, al); \
416 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
417 logwrap(die, " critical", LOG_CRIT, -1, 16);
419 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
420 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
422 logwrap(syswarn, " warning", LOG_WARN, errno, 0);
423 logwrap(warn, " warning", LOG_WARN, -1, 0);
425 logwrap(notice, "", LOG_NOTICE, -1, 0);
426 logwrap(info, " info", LOG_INFO, -1, 0);
429 /*========== making new connections ==========*/
431 static int connecting_sockets[2]= {-1,-1};
432 static pid_t connecting_child;
434 static void connect_attempt_discard(void) {
435 if (connecting_sockets[0])
436 cancel_fd(connecting_sockets[0]);
438 perhaps_close(&connecting_sockets[0]);
439 perhaps_close(&connecting_sockets[1]);
441 if (connecting_child) {
442 int status= xwaitpid(&connecting_child, "connect");
444 if (!(WIFEXITED(status) ||
445 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
446 report_child_status("connect", status);
450 #define PREP_DECL_MSG_CMSG(msg) \
452 memset(&msg,0,sizeof(msg)); \
453 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
454 msg.msg_control= msg##cbuf; \
455 msg.msg_controllen= sizeof(msg##cbuf);
457 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
460 conn= xmalloc(sizeof(*conn));
461 memset(conn,0,sizeof(*conn));
464 struct cmsghdr *h= 0;
465 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
466 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
469 pid_t got= waitpid(connecting_child, &status, WNOHANG);
471 assert(got==connecting_child);
473 if (WIFEXITED(status) &&
474 (WEXITSTATUS(status) != 0
475 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
476 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
477 /* child already reported the problem */
478 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
479 warn("connect: connection attempt timed out");
480 } else if (!WIFEXITED(status)) {
481 report_child_status("connect", status);
482 /* that's probably the root cause then */
485 /* child is still running apparently, report the socket problem */
487 syswarn("connect: read from child socket failed");
488 else if (e == OOP_EXCEPTIONN)
489 warn("connect: unexpected exception on child socket");
491 warn("connect: unexpected EOF on child socket");
496 #define CHK(field, val) \
497 if (h->cmsg_##field != val) { \
498 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
501 CHK(level, SOL_SOCKET);
502 CHK(type, SCM_RIGHTS);
503 CHK(len, CMSG_LEN(sizeof(conn-b>fd)));
506 if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
508 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
510 pid_t got= waitpid(connecting_child, &status, 0);
511 if (got==-1) sysdie("connect: real wait for child");
512 assert(got == connecting_child);
515 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
516 int es= WEXITSTATUS(status);
518 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
519 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
521 fatal("connect: child gave unexpected exit status %d", es);
527 LIST_ADDHEAD(idle, conn);
528 notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
529 connect_attempt_discard();
530 check_master_queue();
535 perhaps_close(&conn->fd);
538 connect_attempt_discard();
541 static void connect_start() {
542 assert(!connecting_sockets[0]);
543 assert(!connecting_sockets[1]);
544 assert(!connecting_child);
546 notice("starting connection attempt");
548 r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
549 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
551 connecting_child= xfork("connection");
553 if (!connecting_child) {
554 FILE *cn_from, *cn_to;
555 char buf[NNTP_STRLEN+100];
556 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
558 r= close(connecting_sockets[0]);
559 if (r) sysdie("connect: close parent socket in child");
561 alarm(connection_setup_timeout);
562 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
564 sanitise_inplace(buf);
565 fatal("connect: rejected: %s", buf);
567 sysfatal("connect: connection attempt failed");
570 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
571 sysfatal("connect: authentication failed");
573 if (fputs("MODE STREAM\r\n", cn_to) ||
575 sysfatal("connect: could not send MODE STREAM");
576 buf[sizeof(buf)-1]= 0;
577 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
579 sysfatal("connect: could not read response to MODE STREAM");
581 fatal("connect: connection close in response to MODE STREAM");
586 sanitise_inplace(buf);
587 fatal("connect: response to MODE STREAM is too long: %.100s...",
590 l--; if (l>0 && buf[1-]=='\r') l--;
593 int rcode= strtoul(buf,&ep,10);
595 sanitise_inplace(buf);
596 fatal("connect: bad response to MODE STREAM: %.50s", buf);
600 exitstatus= CONNCHILD_ESTATUS_STREAM;
606 sanitise_inplace(buf);
607 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
612 int fd= fileno(cn_from);
614 PREP_DECL_MSG_CMSG(msg);
615 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
616 cmsg->cmsg_level= SOL_SOCKET;
617 cmsg->cmsg_type= SCM_RIGHTS;
618 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
619 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
621 msg.msg_controllen= cmsg->cmsg_len;
622 r= sendmsg(connecting_sockets[1], &msg, 0);
623 if (r) sysdie("sendmsg failed for new connection");
628 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
629 if (r) sysdie("connect: close child socket in parent");
631 on_fd_read_except(connecting_sockets[0], connchild_event);
635 connect_attempt_discard();
639 /*========== overall control of article flow ==========*/
641 static void check_master_queue(void) {
642 try reading current feed file;
647 Conn *last_assigned=0;
650 conn_assign_one_article(&working, &last_assigned);
651 } else if (idle.head) {
652 conn_assign_one_article(&idle, &last_assigned);
653 } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
654 !connecting_child && !connect_delay) {
655 connect_delay= reconnect_delay_periods;
661 conn_check_work(last_assigned);
664 static void conn_assign_one_article(LIST(Conn) *connlist,
665 Conn **last_assigned) {
666 Conn *conn= connlist->head;
668 LIST_REMOVE(*connlist, conn);
669 Article *art= LIST_REMHEAD(queue);
670 LIST_ADDTAIL(conn->queue, art);
671 LIST_ADD(*conn_determine_right_list(conn), conn);
673 /* This slightly odd arrangement is so that we call conn_check_work
674 * once after filling the queue for a new connection in
675 * check_master_queue, rather than for each article. */
676 if (conn != *last_assigned && *last_assigned)
677 conn_check_work(*last_assigned);
678 *last_assigned= conn;
681 static int conn_total_queued_articles(Conn *conn) {
682 return conn->sent.count + conn->queue.count;
685 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
686 int inqueue= conn_total_queued_articles(conn);
687 assert(inqueue <= max_queue);
688 if (inqueue == 0) return &idle;
689 if (inqueue == conn->max_queue) return &full;
693 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
698 static void conn_check_work(Conn *conn) {
701 conn_make_some_xmits(conn);
703 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
707 void *rp= conn_write_some_xmits(conn);
708 if (rp==OOP_CONTINUE) {
709 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
711 } else if (rp==OOP_HALT) {
714 /* transmitted everything */
722 /*========== article transmission ==========*/
724 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
725 XmitKind kind) { /* caller must then fill in details */
726 struct iovec *v= &conn->xmit[conn->xmitu];
727 XmitDetails *d= &conn->xmitd[conn->xmitu++];
734 static void xmit_noalloc(Conn *conn, const char *data, int len) {
735 xmit_core(conn,data,len, xk_Const);
737 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
739 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
740 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
744 static void xmit_free(XmitDetails *d) {
746 case xk_Malloc: free(d->info.malloc_tofree); break;
747 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
748 case xk_Const: break;
753 static void *conn_write_some_xmits(Conn *conn) {
755 * 0: nothing more to write, no need to call us again
756 * OOP_CONTINUE: more to write but fd not writeable
757 * OOP_HALT: disaster, have destroyed conn
760 int count= conn->xmitu;
761 if (!count) return 0;
763 if (count > IOV_MAX) count= IOV_MAX;
764 ssize_t rs= writev(conn->fd, conn->xmit, count);
766 if (errno == EAGAIN) return OOP_CONTINUE;
767 connfail(conn, "write failed: %s", strerror(errno));
772 for (done=0; rs && done<xmitu; done++) {
773 struct iovec *vp= &conn->xmit[done];
774 XmitDetails *dp= &conn->xmitd[done];
775 if (rs > vp->iov_len) {
783 int newu= conn->xmitu - done;
784 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
785 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
790 static void conn_make_some_xmits(Conn *conn) {
792 if (conn->xmitu+5 > CONNIOVS)
795 Article *art= LIST_REMHEAD(queue);
798 if (art->checked || (conn->stream && nocheck)) {
799 /* actually send it */
801 ARTHANDLE *artdata= SMretrieve();
805 XMIT_LITERAL("TAKETHIS ");
806 xmit_noalloc(conn, art->mid, art->midlen);
807 XMIT_LITERAL("\r\n");
808 xmit_artbody(conn, artdata);
811 /* we got 235 from IHAVE */
813 xmit_artbody(conn, artdata);
815 XMIT_LITERAL(".\r\n");
820 LIST_ADDTAIL(conn->sent, art);
822 counts[art->checked].sent++;
828 XMIT_LITERAL("IHAVE ");
830 XMIT_LITERAL("CHECK ");
831 xmit_noalloc(art->mid, art->midlen);
832 XMIT_LITERAL("\r\n");
834 LIST_ADDTAIL(conn->sent, art);
835 counts[art->checked].offered++;
841 /*========== handling responses from peer ==========*/
843 static const oop_rd_style peer_rd_style= {
844 OOP_RD_DELIM_STRIP, '\n',
846 OOP_RD_SHORTREC_FORBID
849 static Article *article_reply_check(Connection *conn, const char *response,
850 int code_indicates_streaming,
851 const char *sanitised_response) {
852 Article *art= LIST_REMHEAD(conn->sent);
856 "peer gave unexpected response when no commands outstanding: %s",
861 if (code_indicates_streaming) {
862 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
864 connfail("peer gave streaming response code "
865 " to IHAVE or subsequent body: %s", sanitised_response);
868 const char *got_mid= response+4;
869 int got_midlen= strcspn(got_mid, " \n\r");
870 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
871 connfail("peer gave streaming response with syntactically invalid"
872 " messageid: %s", sanitised_response);
875 if (got_midlen != art->midlen ||
876 memcmp(got_mid, art->messageid, got_midlen)) {
877 connfail("peer gave streaming response code to wrong article -"
878 " probable synchronisation problem; we offered: %s;"
880 art->messageid, sanitised_response);
885 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
894 static void update_nocheck(int accepted) {
895 accept_proportion *= accept_decay;
896 accept_proportion += accepted;
897 nocheck= accept_proportion >= nocheck_thresh;
898 if (nocheck && !nocheck_reported) {
899 notice("entering nocheck mode for the first time");
904 static void article_done(Connection *conn, Article *art, int whichcount) {
906 counts.articles[art->checked][whichcount]++;
907 if (whichcount == RC_accepted) update_nocheck(1);
908 else if (whichcount == RC_unwanted) update_nocheck(0);
910 InputFile *ipf= art->ipf;
911 while (art->blanklen) {
912 static const char spaces[]=
917 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
918 int r= pwrite(ipf->fd, spaces, w, art->offset);
920 if (errno==EINTR) continue;
921 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
922 art->messageid, art->blanklen, art->offset, ipf->path);
924 assert(r>=0 && r<=w);
930 assert(ipf->inprogress >= 0);
932 if (!ipf->inprogress)
933 loop->on_time(loop, OOP_TIME_NOW, statemc_check_oldinput_done, 0);
938 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
939 const char *errmsg, int errnoval,
940 const char *data, size_t recsz, void *conn_v) {
942 connfail(conn, "error receiving from peer: %s", errmsg);
946 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
947 const char *errmsg, int errnoval,
948 const char *data, size_t recsz, void *conn_v) {
951 if (ev == OOP_RD_EOF) {
952 connfail(conn, "unexpected EOF from peer");
955 assert(ev == OOP_RD_OK);
958 unsigned long code= strtoul(data, &ep, 10);
959 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
965 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
967 if (!c) { *q++= '\''; break; }
968 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
969 sprintf(q,"\\x%02x",c);
972 connfail(conn, "badly formatted response from peer: %s", sanibuf);
976 if (conn->quitting) {
978 connfail(conn, "peer gave failure response to QUIT: %s", sani);
987 #define GET_ARTICLE \
988 art= article_reply_check(conn, data, code_streaming, sani); \
989 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
991 #define ARTICLE_DEALTWITH(streaming,how) \
992 code_streaming= (streaming) \
994 article_done(conn, art, RC_##how); break;
996 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
998 int code_streaming= 0;
1002 case 400: PEERBADMSG("peer stopped accepting articles");
1003 case 503: PEERBADMSG("peer timed us out");
1004 default: PEERBADMSG("peer sent unexpected message");
1006 case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
1007 case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
1009 case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
1010 case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
1012 case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
1013 case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
1015 case 238: /* CHECK says send it */
1017 case 335: /* IHAVE says send it */
1019 count_checkedwanted++;
1020 LIST_ADDTAIL(conn->queue);
1022 connfail("peer gave %d response to article body: %s",code, sani);
1023 return OOP_CONTINUE;
1028 case 431: /* CHECK or TAKETHIS says try later */
1030 case 436: /* IHAVE says try later */
1032 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1034 sysfatal("write to defer file %s",path_ductdefer);
1035 article_done(conn, art, RC_deferred);
1040 check_check_work(conn);
1041 return OOP_CONTINUE;
1045 /*========== monitoring of input files ==========*/
1047 static void feedfile_eof(InputFile *ipf) {
1048 assert(ipf != main_input_file); /* promised by tailing_try_read */
1049 assert(ipf == old_input_file);
1051 inputfile_tailing_stop(ipf);
1052 assert(ipf->fd >= 0);
1053 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1056 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1058 if (main_input_file)
1059 inputfile_tailing_start(main_input_file);
1062 static InputFile *open_input_file(const char *path) {
1063 int fd= open(path, O_RDONLY);
1065 if (errno==ENOENT) return 0;
1066 sysfatal("unable to open input file %s", path);
1069 InputFile *ipf= xmalloc(sizeof(InputFile));
1070 memset(ipf,0,sizeof(*ipf));
1072 ipf->readable.on_readable= tailing_on_readable;
1073 ipf->readable.on_cancel= tailing_on_cancel;
1074 ipf->readable.try_read= tailing_try_read;
1082 static void close_input_file(InputFile *ipf) {
1083 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1084 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1085 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1086 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1089 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1094 /*---------- dealing with articles read in the input file ----------*/
1096 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1097 oop_rd_event ev, const char *errmsg,
1099 const char *data, size_t recsz,
1101 InputFile *ipf= ipf_v;
1103 char tokentextbuf[sizeof(TOKEN)*2+3];
1105 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1107 if (data[0] && data[0]!=' ') {
1108 char *space= strchr(data,' ');
1109 int tokenlen= space-data;
1110 int midlen= (int)recsz-tokenlen-1;
1111 if (midlen < 0) goto bad_data;
1113 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1114 memcpy(tokentextbuf, data, tokenlen);
1115 tokentextbuf[tokenlen]= 0;
1116 if (!IsToken(tokentextbuf)) goto bad_data;
1118 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1119 art->offset= ipf->offset;
1120 art->blanklen= recsz;
1121 art->midlen= midlen;
1122 art->checked= art->sentbody= 0;
1123 art->ipf= ipf; ipf->inprogress++;
1124 art->token= TextToToken(tokentextbuf);
1125 strcpy(art->messageid, space+1);
1126 LIST_ADDTAIL(queue, art);
1128 ipf->offset += recsz + 1;
1130 if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
1131 notice("starting flush (%lu >= %lu)",
1132 (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1134 int r= link(feedfile, duct_path);
1135 if (r) sysdie("link feedfile %s to ductfile %s", feedfile, dut_path);
1138 r= unlink(feedfile);
1139 if (r) sysdie("unlink old feedfile link %s", feedfile);
1142 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1145 check_master_queue();
1149 /*========== tailing input file ==========*/
1151 static void filemon_start(InputFile *ipf) {
1152 assert(!ipf->filemon);
1154 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1155 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1156 filemon_method_startfile(ipf, ipf->filemon);
1159 static void filemon_stop(InputFile *ipf) {
1160 if (!ipf->filemon) return;
1161 filemon_method_stopfile(ipf, ipf->filemon);
1166 static void filemon_callback(InputFile *ipf) {
1167 ipf->readable_callback(ipf->readable_callback_user);
1170 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1172 InputFile *ipf= user;
1173 return ipf->readable_callback(ipf->readable_callback_user);
1176 static void on_cancel(struct oop_readable *rable) {
1177 InputFile *ipf= (void*)rable;
1179 if (ipf->filemon) filemon_stopfile(ipf);
1180 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1181 ipf->readable_callback= 0;
1184 static int tailing_on_readable(struct oop_readable *rable,
1185 oop_readable_call *cb, void *user) {
1186 InputFile *ipf= (void*)rable;
1188 tailing_on_cancel(rable);
1189 ipf->readable_callback= cb;
1190 ipf->readable_callback_user= user;
1191 filemon_startfile(ipf);
1193 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1197 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1199 InputFile *ipf= (void*)rable;
1201 ssize_t r= read(ipf->fd, buffer, length);
1203 if (errno==EINTR) continue;
1207 if (ipf==main_input_file) {
1210 } else if (ipf==old_input_file) {
1212 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1213 } else if (ipf==backlog_input_file) {
1223 /*---------- filemon implemented with inotify ----------*/
1225 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1226 #define HAVE_FILEMON
1228 #include <linux/inotify.h>
1230 static int filemon_inotify_fd;
1231 static int filemon_inotify_wdmax;
1232 static InputFile **filemon_inotify_wd2ipf;
1234 typedef struct Filemon_Perfile {
1236 } Filemon_Inotify_Perfile;
1238 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1239 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1240 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1242 if (wd >= filemon_inotify_wdmax) {
1244 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1245 sizeof(*filemon_inotify_wd2ipf) * newmax);
1246 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1247 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1248 filemon_inotify_wdmax= newmax;
1251 assert(!filemon_inotify_wd2ipf[wd]);
1252 filemon_inotify_wd2ipf[wd]= ipf;
1257 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1259 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1260 if (r) sysdie("inotify_rm_watch");
1261 filemon_inotify_wd2ipf[wd]= 0;
1264 static void *filemon_inotify_readable(oop_source *lp, int fd,
1265 oop_event e, void *u) {
1266 struct inotify_event iev;
1268 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1270 if (errno==EAGAIN) break;
1271 sysdie("read from inotify master");
1272 } else if (r==sizeof(iev)) {
1273 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1275 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1277 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1278 filemon_callback(ipf);
1280 return OOP_CONTINUE;
1283 static int filemon_method_init(void) {
1284 filemon_inotify_fd= inotify_init();
1285 if (filemon_inotify_fd<0) {
1286 syswarn("could not initialise inotify: inotify_init failed");
1290 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1295 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1297 /*---------- filemon dummy implementation ----------*/
1299 #if !defined(HAVE_FILEMON)
1301 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1303 static int filemon_method_init(void) { return 0; }
1304 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1305 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1307 #endif /* !HAVE_FILEMON */
1309 /*---------- interface to start and stop an input file ----------*/
1311 static const oop_rd_style feedfile_rdstyle= {
1312 OOP_RD_DELIM_STRIP, '\n',
1314 OOP_RD_SHORTREC_EOF,
1317 static void inputfile_tailing_start(InputFile *ipf) {
1319 ipf->readable->on_readable= tailing_on_readable;
1320 ipf->readable->on_cancel= tailing_on_cancel;
1321 ipf->readable->try_read= tailing_try_read;
1322 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1323 ipf->readable->delete_kill= 0;
1325 ipf->readable_callback= 0;
1326 ipf->readable_callback_user= 0;
1328 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1331 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1332 feedfile_got_article,ipf, feedfile_problem,ipf);
1333 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1336 static void inputfile_tailing_stop(InputFile *ipf) {
1338 oop_rd_delete(ipf->rd);
1340 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1344 /*========== interaction with innd ==========*/
1346 /* See official state diagram at top of file. We implement
1356 |`--------------------------.
1357 | | install defer as backlog
1358 | OPEN F SUCCEEDS | exit
1363 | [Normal] =========
1367 | | F IS SO BIG WE SHOULD FLUSH
1371 | | our handle onto F is now onto D
1374 | |<---------------------------------------------------.
1376 | | spawn inndcomm flush |
1384 | | INNDCOMM FLUSH FAILS ^
1385 | |`----------------------->----------. |
1387 | | NO SUCH SITE V |
1388 ^ |`--------------->----. =========== |
1394 | | \ | TIME TO RETRY |
1395 | | \ `----------------'
1399 | ============= ============
1400 | SEPARATED/ DROPPING/
1401 | old->fd>=0 old->fd>=0
1402 | [Separated] [Dropping]
1403 | main F idle main none
1404 | old D tail old D tail
1405 | ============= ============
1407 ^ | EOF ON D | EOF ON D
1409 | =============== ===============
1410 | SEPARATED/ DROPPING/
1411 | old->fd==-1 old->fd==-1
1412 | [Finishing] [Dropping]
1413 | main F tail main none
1414 | old D closed old D closed
1415 | =============== ===============
1417 | | ALL D PROCESSED | ALL D PROCESSED
1418 | V install defer as backlog V install defer as backlog
1419 ^ | close D | close D
1420 | | unlink D | unlink D
1421 | | start new defer | exit
1423 `----------' ==========
1429 static void open_defer(void) {
1433 defer= fopen(path_ductdefer, "a+");
1434 if (!defer) sysfatal("could not open defer file %s", path_ductdefer);
1436 /* truncate away any half-written records */
1438 r= fstat(fileno(defer), &stab);
1439 if (r) sysdie("could not stat newly opened defer file %s", path_ductdefer);
1441 if (stab.st_size > LONG_MAX)
1442 die("defer file %s size is far too large", path_ductdefer);
1447 long orgsize= stab.st_size;
1448 long truncto= stab.st_size;
1450 if (!truncto) break; /* was only (if anything) one half-truncated record */
1451 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1452 sysdie("seek in defer file %s while truncating partial", path_ductdefer);
1457 sysdie("failed read from defer file %s", path_ductdefer);
1459 die("defer file %s shrank while we were checking it!", path_ductdefer);
1465 if (stab.st_size != truncto) {
1466 warn("truncating half-record at end of defer file %s -"
1467 " shrinking by %ld bytes from %ld to %ld",
1468 path_ductdefer, orgsize - truncto, orgsize, truncto);
1471 sysfatal("could not flush defer file %s", path_ductdefer);
1472 if (ftruncate(fileno(defer), truncto))
1473 sysdie("could not truncate defer file %s", path_ductdefer);
1476 info("continuing existing defer file %s (%ld bytes)",
1477 path_ductdefer, orgsize);
1479 if (fseek(defer, truncto, SEEK_SET))
1480 sysdie("could not seek to new end of defer file %s", path_ductdefer);
1483 static void statemc_init(void) {
1486 path_ductlock= xasprintf("%s_duct.lock", feedfile);
1487 path_duct= xasprintf("%s_duct", feedfile);
1488 path_ductdefer= xasprintf("%s_duct.defer", feedfile);
1490 if (lstat(path_ductdefer, &stab)) {
1491 if (errno!=ENOENT) sysdie("could not check defer file %s", path_defer);
1493 if (!S_ISREG(stab.st_mode))
1494 die("defer file %s not a plain file (mode 0%lo)",
1495 path_defer, (unsigned long)stab.st_mode);
1496 switch (stab.st_nlink==1) {
1497 case 1: /* ok */ break;
1499 if (unlink(path_defer))
1500 sysdie("could not unlink stale defer file link %s (presumably"
1501 " hardlink to backlog file)", path_defer);
1504 die("defer file %s has unexpected link count %d",
1505 path_defer, stab.st_nlink);
1510 int lockfd= open(path_ductlock, O_CREAT|O_RDWR, 0600);
1511 if (lockfd<0) sysfatal("open lockfile %s", path_ductlock);
1514 memset(&fl,0,sizeof(fl));
1516 fl.l_whence= SEEK_SET;
1517 r= fcntl(lockfd, F_SETLK, &fl);
1519 if (errno==EACCES || errno==EAGAIN) {
1520 if (quiet_if_locked) exit(0);
1521 fatal("another duct holds the lockfile");
1523 sysdie("fcntl F_SETLK lockfile %s", path_ductlock);
1526 InputFile *file_d= open_input_file(path_duct);
1529 struct stat stab_f, stab_d;
1531 r= stat(feedfile, &stab_f);
1533 if (errno!=ENOENT) sysdie("check feed file %s", feedfile);
1534 /* D exists, F ENOENT => Moved */
1538 /* F and D both exist */
1540 r= fstat(file_d->fd, &stab_d);
1541 if (r) sysdie("check duct file %s", ductfile);
1543 if (stab_d.st_ino == stab_f.st_ino &&
1544 stab_d.st_dev == stab_f.st_dev) {
1545 /* F==D => Hardlinked*/
1546 r= unlink(path_duct);
1547 if (r) sysdie("unlink feed file %s during startup", feedfile);
1550 startup_set_input_file(file_d);
1551 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1553 /* F!=D => Separated */
1554 SMS(SEPARATED, 0, "found both old and current feed files");
1555 startup_set_input_file(file_d);
1557 } else { /*!file_d*/
1558 SMS(WAITING, open_wait_periods, "no feed file currently exists");
1562 static void statemc_poll(void) {
1563 if (sms==sm_WAITING) { statemc_waiting_poll(); return; }
1565 if (!sm_period_counter) return;
1566 sm_period_counter--;
1567 assert(sm_period_counter>=0);
1569 if (sm_period_counter) return;
1572 fatal("timed out waiting for innd to create feed file %s", feedfile);
1574 spawn_inndcomm_flush(void);
1581 static void statemc_waiting_poll(void) {
1582 InputFile *file_f= open_input_file(feedfile);
1583 if (!file_f) return;
1584 startup_set_input_file(file_d);
1585 SMS(NORMAL, 0, "found and opened feed file");
1588 static void startup_set_input_file(InputFile *f) {
1589 assert(!main_input_file);
1591 inputfile_tailing_start(f);
1594 static void *statemc_check_oldinput_done(oop_source *lp,
1595 struct timeval now, void *u) {
1598 int done= (sms==sm_SEPARATED || sms==sm_DROPPING)
1599 && old_input_file->fd==-1
1600 && !old_input_file->inprogress;
1603 r= fstat(fileno(defer), &stab);
1604 if (r) sysdie("check defer file %s", path_defer);
1606 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1609 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1610 (unsigned long)now.tv_sec,
1611 (unsigned long)stab.st_ino);
1612 if (link(path_defer, path_backlog))
1613 sysfatal("could not install defer file %s as backlog file %s",
1614 path_defer, backlog);
1615 if (unlink(path_defer))
1616 sysdie("could not unlink old defer link %s to backlog file %s",
1617 path_defer, backlog);
1619 if (unlink(path_duct))
1620 sysdie("could not unlink old duct file %s", path_duct);
1622 if (sms==sm_DROPPING) {
1623 notice("feed dropped and our work is complete"
1624 " (but check for backlog files)");
1630 close_input_file(old_input_file);
1633 notice("flush complete");
1634 SMS(NORMAL, 0, "flush complete");
1637 static void statemc_setstate(StateMachineState newsms, int periods,
1638 const char *forlog, const char *why) {
1640 sm_period_counter= periods;
1642 info("%s[%d] %s",periods,forlog,why);
1644 info("%s %s",forlog,why);
1648 /*========== flushing the feed ==========*/
1650 static pid_t inndcomm_child;
1652 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1653 assert(inndcomm_child);
1654 int status= xwaitpid(&inndcomm_child, "inndcomm");
1655 loop->cancel_fd(fd);
1658 assert(!old_input_file);
1660 if (WIFEXITED(status)) {
1661 switch (WEXITSTATUS(status)) {
1663 case INNDCOMMCHILD_ESTATUS_FAIL:
1666 case INNDCOMMCHILD_ESTATUS_NONESUCH:
1667 warn("feed has been dropped by innd, finishing up");
1668 old_input_file= main_input_file;
1670 SMS(DROPPING, 0, "dropped by innd");
1671 return OOP_CONTINUE;
1674 old_input_file= main_input_file;
1675 main_input_file= open_input_file(feedfile);
1676 if (!main_input_file)
1677 die("flush succeeded but feedfile %s does not exist!", feedfile);
1678 SMS(SEPARATED, 0, "feed file missing");
1679 return OOP_CONTINUE;
1682 goto unexpected_exitstatus;
1685 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1686 warn("flush timed out trying to talk to innd");
1689 unexpected_exitstatus:
1690 report_child_status("inndcomm child", status);
1694 SMS(FLUSHFAIL, flushfail_retry_periods, "flush failed, will retry");
1697 static void inndcommfail(const char *what) {
1698 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1699 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1702 void spawn_inndcomm_flush(void) {
1705 assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1706 assert(!inndcomm_child);
1708 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1710 inndcomm_child= xfork();
1712 if (!inndcomm_child) {
1713 static char flushargv[2]= { sitename, 0 };
1718 alarm(inndcomm_flush_timeout);
1719 r= ICCopen(); if (r) inndcommfail("connect");
1720 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
1721 if (!r) exit(0); /* yay! */
1723 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1724 syswarn("innd ctlinnd flush failed: innd said %s", reply);
1725 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1729 int sentinel_fd= pipefds[0];
1730 on_fd_read_except(sentinel_fd, inndcomm_event);
1732 SMS(FLUSHING, 0, "flush is in progress");
1735 /*========== main program ==========*/
1737 static void postfork_inputfile(InputFile *ipf) {
1739 assert(ipf->fd >= 0);
1744 static void postfork_conns(Connection *conn) {
1751 static void postfork_stdio(FILE *f) {
1752 /* we have no stdio streams that are buffered long-term */
1756 static void postfork(const char *what) {
1757 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1758 sysdie("%s child: failed to reset SIGPIPE");
1760 postfork_inputfile(main_input_file);
1761 postfork_inputfile(old_input_file);
1762 postfork_conns(idle.head);
1763 postfork_conns(working.head);
1764 postfork_conns(full.head);
1765 postfork_stdio(defer);
1769 #define EVERY(what, interval, body) \
1770 static const struct timeval what##_timeout = { 5, 0 }; \
1771 static void what##_schedule(void); \
1772 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1774 what##_schedule(); \
1776 static void what##_schedule(void) { \
1777 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
1780 EVERY(filepoll, {5,0}, { check_master_queue(); })
1782 EVERY(period, {PERIOD_SECONDS,0}, {
1783 if (connect_delay) connect_delay--;
1785 check_master_queue();
1789 /*========== option parsing ==========*/
1792 of_seconds= 001000u;
1793 of_boolean= 002000u;
1796 typedef struct Option Option;
1797 typedef void OptionParser(const Option*, const char *val);
1807 void op_integer(const Option *o, const char *val) {
1810 unsigned long ul= strtoul(val,&ep,10);
1811 if (*ep || ep==val || errno || ul>INT_MAX)
1812 badusage("bad integer value for %s",o->long);
1813 int *store= o->store;
1817 void op_double(const Option *o, const char *val) {
1818 int *store= o->store;
1821 *store= strtod(val, &ep);
1822 if (*ep || ep==val || errno)
1823 badusage("bad floating point value for %s",o->long);
1826 void op_string(const Option *o, const char *val) {
1827 char **store= o->store;
1832 void op_seconds(const Option *o, const char *val) {
1833 int *store= o->store;
1836 double v= strtod(val,&ep);
1837 if (ep==val) badusage("bad time/duration value for %s",o->long);
1839 if (!*ep || !strcmp(ep,"s")) unit= 1;
1840 else if (!strcmp(ep,"m")) unit= 60;
1841 else if (!strcmp(ep,"h")) unit= 3600;
1842 else if (!strcmp(ep,"d")) unit= 86400;
1843 else badusage("bad units %s for time/duration value for %s",ep,o->long);
1847 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
1851 void op_periods_rndup(const Option *o, const char *val) {
1852 int *store= o->store;
1854 *store += PERIOD_SECONDS-1;
1855 *store /= PERIOD_SECONDS;
1858 void op_periods_booltrue(const Option *o, const char *val) {
1859 int *store= o->store;
1862 void op_periods_boolfalse(const Option *o, const char *val) {
1863 int *store= o->store;
1867 static const Option options[]= {
1868 { 0, "max-connections", &max_connections op_integer },
1869 { 0, "streaming", &try_stream, op_booltrue, 1 },
1870 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
1871 {'h',"host", &remote_host, op_string },
1872 {'P',"port", &port op_integer },
1873 { 0, "inndconf", &inndconffile, op_string },
1874 {'f',"feedfile", &feedfile, op_string },
1875 {'q',"quiet-multiple", &quiet_if_locked, op_booltrue, 1 },
1876 { 0, "no-quiet-multiple", &quiet_if_locked, op_boolfalse, 1 },
1877 {'d',"daemon", &become_daemon, op_booltrue, 1 },
1878 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
1880 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
1881 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
1883 { 0, "max-queue-size", &max_queue_per_conn op_integer },
1884 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
1885 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
1886 { 0, "feedfile-open-timeout", &open_wait_periods, op_periods_rndup },
1887 { 0, "connection-timeout", &connection_timeout, op_seconds },
1888 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
1891 int main(int argc, char **argv) {
1897 if (*arg != '-') break;
1898 if (!strcmp(arg,"--")) { arg= *++argv; break; }
1900 while ((a= *++arg)) {
1904 char *equals= strchr(arg,'=');
1905 int len= equals ? (equals - arg) : strlen(arg);
1906 for (o=options; o->long; o++)
1907 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
1909 badusage("unknown long option --%s",arg);
1912 if (equals) badusage("option --%s does not take a value",o->long);
1914 } else if (equals) {
1918 if (!arg) badusage("option --%s needs a value",o->long);
1921 break; /* eaten the whole argument now */
1923 for (o=options; o->long; o++)
1926 badusage("unknown short option -%c",a);
1933 if (!arg) badusage("option -%c needs a value",o->short);
1936 break; /* eaten the whole argument now */
1941 if (!arg) badusage("need site name argument");
1942 if (*++argv) badusage("too many non-option arguments");
1945 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
1946 badusage("nocheck threshold percentage must be between 0..100");
1947 nocheck_thresh= nocheck_thresh_pct * 0.01;
1949 if (nocheck_decay_articles < 0.1)
1950 badusage("nocheck decay articles must be at least 0.1");
1951 nocheck_decay= 1 - 1/nocheck_decay_articles;
1953 innconf_read(inndconffile);
1956 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
1957 else if (!feedfile[0])
1958 badusage("feed filename must be nonempty");
1959 else if (feedfile[strlen(feedfile)-1]=='/')
1960 feedfile= xasprintf("%s%s",feedfile,sitename);
1962 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1963 sysdie("could not ignore SIGPIPE");
1965 if (become_daemon) {
1966 for (i=3; i<255; i++)
1967 /* do this now before we open syslog, etc. */
1969 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
1971 int null= open("/dev/null",O_RDWR);
1972 if (null<0) sysdie("failed to open /dev/null");
1978 pid_t child1= xfork("daemonise first fork");
1979 if (child1) _exit(0);
1981 pid_t sid= setsid();
1982 if (sid != child1) sysdie("setsid failed");
1984 pid_t child2= xfork("daemonise second fork");
1985 if (child2) _exit(0);
1990 if (!filemon_init()) {
1991 warn("no file monitoring available, polling");
1992 filepoll_schedule();