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 */
276 sm_SEPARATED2, /* must follow SEPARATED2 - see feedfile_eof */
278 sm_DROPPING2, /* must follow DROPPING1 - see feedfile_eof */
283 int fd, max_queue, stream;
284 LIST(Article) queue; /* not yet told peer, or CHECK said send it */
285 LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
286 struct iovec xmit[CONNIOVS];
287 XmitDetails xmitd[CONNIOVS];
292 /*----- operational variables -----*/
294 static int since_connect_attempt;
296 static LIST(Conn) idle, working, full;
297 static LIST(Article) *queue;
299 static char *path_ductlock, *path_duct, *path_ductdefer;
301 #define SMS(newstate, periods, why) \
302 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
304 static StateMachineState sms;
306 static InputFile *main_input_file, *old_input_file;
307 static int sm_period_counter;
310 /*----- function predeclarations -----*/
312 static void conn_check_work(Conn *conn);
314 static int filemon_init(void);
315 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
316 static void filemon_callback(void);
318 static void statemc_setstate(StateMachineState newsms, int periods,
319 const char *forlog, const char *why);
321 /*========== utility functions etc. ==========*/
323 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
325 static pid_t xfork(const char *what) {
329 if (child==-1) sysdie("cannot fork for %s",what);
330 if (!child) postfork(what);
334 static void on_fd_read_except(int fd, oop_call_fd callback) {
335 loop->on_fd(loop, fd, OOP_READ, callback, 0);
336 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
338 static void cancel_fd_read_except(int fd) {
339 loop->cancel_fd(loop, fd, OOP_READ);
340 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
343 static void report_child_status(const char *what, int status) {
344 if (WIFEXITED(status)) {
345 int es= WEXITSTATUS(status);
347 warn("%s: child died with error exit status %d",es);
348 } else if (WIFSIGNALED(status)) {
349 int sig= WTERMSIG(status);
350 const char *sigstr= strsignal(sig);
351 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
353 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
355 warn("%s: child died due to unknown fatal signal %d%s",
356 what, sig, coredump);
358 warn("%s: child died with unknown wait status %d", status);
362 static int xwaitpid(pid_t *pid, const char *what) {
365 r= kill(*pid, SIGKILL);
366 if (r) sysdie("cannot kill %s child", what);
368 pid_t got= waitpid(*pid, &status, WNOHANG);
369 if (got==-1) sysdie("cannot reap %s child", what);
376 /*========== logging ==========*/
378 static void logcore(int sysloglevel, const char *fmt, ...)
379 __attribute__((printf,2,3))
380 static void logcore(int sysloglevel, const char *fmt, ...) {
384 vsyslog(sysloglevel,fmt,al);
386 vfprintf(stderr,fmt,al);
391 static void logv(int sysloglevel, const char *pfx, int errnoval,
392 int exitstatus, const char *fmt, va_list al)
393 __attribute__((printf,4,0))
394 static void logv(int sysloglevel, const char *pfx, int errnoval,
395 int exitstatus, const char *fmt, va_list al) {
397 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
398 msgbuf[sizeof(msgbuf)-1]= 0;
400 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
401 sysloglevel= LOG_ERR; /* run by wrong user, probably */
403 logcore(sysloglevel, "<%s>%s: %s%s%s",
404 sitename, pfx, msgbuf,
405 errnoval>=0 ? ": " : "",
406 errnoval>=0 ? strerror(errnoval) : "");
409 #define logwrap(fn, pfx, sysloglevel, errno, estatus) \
410 static void fn(const char *fmt, ...) \
411 __attribute__((printf,1,2)); \
412 static void fn(const char *fmt, ...) { \
415 logv(sysloglevel, pfx, errno, estatus, fmt, al); \
418 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
419 logwrap(die, " critical", LOG_CRIT, -1, 16);
421 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
422 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
424 logwrap(syswarn, " warning", LOG_WARN, errno, 0);
425 logwrap(warn, " warning", LOG_WARN, -1, 0);
427 logwrap(notice, "", LOG_NOTICE, -1, 0);
428 logwrap(info, " info", LOG_INFO, -1, 0);
431 /*========== making new connections ==========*/
433 static int connecting_sockets[2]= {-1,-1};
434 static pid_t connecting_child;
436 static void connect_attempt_discard(void) {
437 if (connecting_sockets[0])
438 cancel_fd(connecting_sockets[0]);
440 perhaps_close(&connecting_sockets[0]);
441 perhaps_close(&connecting_sockets[1]);
443 if (connecting_child) {
444 int status= xwaitpid(&connecting_child, "connect");
446 if (!(WIFEXITED(status) ||
447 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
448 report_child_status("connect", status);
452 #define PREP_DECL_MSG_CMSG(msg) \
454 memset(&msg,0,sizeof(msg)); \
455 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
456 msg.msg_control= msg##cbuf; \
457 msg.msg_controllen= sizeof(msg##cbuf);
459 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
462 conn= xmalloc(sizeof(*conn));
463 memset(conn,0,sizeof(*conn));
466 struct cmsghdr *h= 0;
467 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
468 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
471 pid_t got= waitpid(connecting_child, &status, WNOHANG);
473 assert(got==connecting_child);
475 if (WIFEXITED(status) &&
476 (WEXITSTATUS(status) != 0
477 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
478 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
479 /* child already reported the problem */
480 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
481 warn("connect: connection attempt timed out");
482 } else if (!WIFEXITED(status)) {
483 report_child_status("connect", status);
484 /* that's probably the root cause then */
487 /* child is still running apparently, report the socket problem */
489 syswarn("connect: read from child socket failed");
490 else if (e == OOP_EXCEPTIONN)
491 warn("connect: unexpected exception on child socket");
493 warn("connect: unexpected EOF on child socket");
498 #define CHK(field, val) \
499 if (h->cmsg_##field != val) { \
500 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
503 CHK(level, SOL_SOCKET);
504 CHK(type, SCM_RIGHTS);
505 CHK(len, CMSG_LEN(sizeof(conn-b>fd)));
508 if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
510 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
512 pid_t got= waitpid(connecting_child, &status, 0);
513 if (got==-1) sysdie("connect: real wait for child");
514 assert(got == connecting_child);
517 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
518 int es= WEXITSTATUS(status);
520 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
521 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
523 fatal("connect: child gave unexpected exit status %d", es);
529 LIST_ADDHEAD(idle, conn);
530 notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
531 connect_attempt_discard();
532 check_master_queue();
537 perhaps_close(&conn->fd);
540 connect_attempt_discard();
543 static void connect_start() {
544 assert(!connecting_sockets[0]);
545 assert(!connecting_sockets[1]);
546 assert(!connecting_child);
548 notice("starting connection attempt");
550 r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
551 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
553 connecting_child= xfork("connection");
555 if (!connecting_child) {
556 FILE *cn_from, *cn_to;
557 char buf[NNTP_STRLEN+100];
558 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
560 r= close(connecting_sockets[0]);
561 if (r) sysdie("connect: close parent socket in child");
563 alarm(connection_setup_timeout);
564 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
566 sanitise_inplace(buf);
567 fatal("connect: rejected: %s", buf);
569 sysfatal("connect: connection attempt failed");
572 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
573 sysfatal("connect: authentication failed");
575 if (fputs("MODE STREAM\r\n", cn_to) ||
577 sysfatal("connect: could not send MODE STREAM");
578 buf[sizeof(buf)-1]= 0;
579 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
581 sysfatal("connect: could not read response to MODE STREAM");
583 fatal("connect: connection close in response to MODE STREAM");
588 sanitise_inplace(buf);
589 fatal("connect: response to MODE STREAM is too long: %.100s...",
592 l--; if (l>0 && buf[1-]=='\r') l--;
595 int rcode= strtoul(buf,&ep,10);
597 sanitise_inplace(buf);
598 fatal("connect: bad response to MODE STREAM: %.50s", buf);
602 exitstatus= CONNCHILD_ESTATUS_STREAM;
608 sanitise_inplace(buf);
609 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
614 int fd= fileno(cn_from);
616 PREP_DECL_MSG_CMSG(msg);
617 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
618 cmsg->cmsg_level= SOL_SOCKET;
619 cmsg->cmsg_type= SCM_RIGHTS;
620 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
621 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
623 msg.msg_controllen= cmsg->cmsg_len;
624 r= sendmsg(connecting_sockets[1], &msg, 0);
625 if (r) sysdie("sendmsg failed for new connection");
630 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
631 if (r) sysdie("connect: close child socket in parent");
633 on_fd_read_except(connecting_sockets[0], connchild_event);
637 connect_attempt_discard();
641 /*========== overall control of article flow ==========*/
643 static void check_master_queue(void) {
644 try reading current feed file;
649 Conn *last_assigned=0;
652 conn_assign_one_article(&working, &last_assigned);
653 } else if (idle.head) {
654 conn_assign_one_article(&idle, &last_assigned);
655 } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
656 !connecting_child && !connect_delay) {
657 connect_delay= reconnect_delay_periods;
663 conn_check_work(last_assigned);
666 static void conn_assign_one_article(LIST(Conn) *connlist,
667 Conn **last_assigned) {
668 Conn *conn= connlist->head;
670 LIST_REMOVE(*connlist, conn);
671 Article *art= LIST_REMHEAD(queue);
672 LIST_ADDTAIL(conn->queue, art);
673 LIST_ADD(*conn_determine_right_list(conn), conn);
675 /* This slightly odd arrangement is so that we call conn_check_work
676 * once after filling the queue for a new connection in
677 * check_master_queue, rather than for each article. */
678 if (conn != *last_assigned && *last_assigned)
679 conn_check_work(*last_assigned);
680 *last_assigned= conn;
683 static int conn_total_queued_articles(Conn *conn) {
684 return conn->sent.count + conn->queue.count;
687 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
688 int inqueue= conn_total_queued_articles(conn);
689 assert(inqueue <= max_queue);
690 if (inqueue == 0) return &idle;
691 if (inqueue == conn->max_queue) return &full;
695 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
700 static void conn_check_work(Conn *conn) {
703 conn_make_some_xmits(conn);
705 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
709 void *rp= conn_write_some_xmits(conn);
710 if (rp==OOP_CONTINUE) {
711 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
713 } else if (rp==OOP_HALT) {
716 /* transmitted everything */
724 /*========== article transmission ==========*/
726 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
727 XmitKind kind) { /* caller must then fill in details */
728 struct iovec *v= &conn->xmit[conn->xmitu];
729 XmitDetails *d= &conn->xmitd[conn->xmitu++];
736 static void xmit_noalloc(Conn *conn, const char *data, int len) {
737 xmit_core(conn,data,len, xk_Const);
739 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
741 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
742 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
746 static void xmit_free(XmitDetails *d) {
748 case xk_Malloc: free(d->info.malloc_tofree); break;
749 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
750 case xk_Const: break;
755 static void *conn_write_some_xmits(Conn *conn) {
757 * 0: nothing more to write, no need to call us again
758 * OOP_CONTINUE: more to write but fd not writeable
759 * OOP_HALT: disaster, have destroyed conn
762 int count= conn->xmitu;
763 if (!count) return 0;
765 if (count > IOV_MAX) count= IOV_MAX;
766 ssize_t rs= writev(conn->fd, conn->xmit, count);
768 if (errno == EAGAIN) return OOP_CONTINUE;
769 connfail(conn, "write failed: %s", strerror(errno));
774 for (done=0; rs && done<xmitu; done++) {
775 struct iovec *vp= &conn->xmit[done];
776 XmitDetails *dp= &conn->xmitd[done];
777 if (rs > vp->iov_len) {
785 int newu= conn->xmitu - done;
786 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
787 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
792 static void conn_make_some_xmits(Conn *conn) {
794 if (conn->xmitu+5 > CONNIOVS)
797 Article *art= LIST_REMHEAD(queue);
800 if (art->checked || (conn->stream && nocheck)) {
801 /* actually send it */
803 ARTHANDLE *artdata= SMretrieve();
807 XMIT_LITERAL("TAKETHIS ");
808 xmit_noalloc(conn, art->mid, art->midlen);
809 XMIT_LITERAL("\r\n");
810 xmit_artbody(conn, artdata);
813 /* we got 235 from IHAVE */
815 xmit_artbody(conn, artdata);
817 XMIT_LITERAL(".\r\n");
822 LIST_ADDTAIL(conn->sent, art);
824 counts[art->checked].sent++;
830 XMIT_LITERAL("IHAVE ");
832 XMIT_LITERAL("CHECK ");
833 xmit_noalloc(art->mid, art->midlen);
834 XMIT_LITERAL("\r\n");
836 LIST_ADDTAIL(conn->sent, art);
837 counts[art->checked].offered++;
843 /*========== handling responses from peer ==========*/
845 static const oop_rd_style peer_rd_style= {
846 OOP_RD_DELIM_STRIP, '\n',
848 OOP_RD_SHORTREC_FORBID
851 static Article *article_reply_check(Connection *conn, const char *response,
852 int code_indicates_streaming,
853 const char *sanitised_response) {
854 Article *art= LIST_REMHEAD(conn->sent);
858 "peer gave unexpected response when no commands outstanding: %s",
863 if (code_indicates_streaming) {
864 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
866 connfail("peer gave streaming response code "
867 " to IHAVE or subsequent body: %s", sanitised_response);
870 const char *got_mid= response+4;
871 int got_midlen= strcspn(got_mid, " \n\r");
872 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
873 connfail("peer gave streaming response with syntactically invalid"
874 " messageid: %s", sanitised_response);
877 if (got_midlen != art->midlen ||
878 memcmp(got_mid, art->messageid, got_midlen)) {
879 connfail("peer gave streaming response code to wrong article -"
880 " probable synchronisation problem; we offered: %s;"
882 art->messageid, sanitised_response);
887 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
896 static void update_nocheck(int accepted) {
897 accept_proportion *= accept_decay;
898 accept_proportion += accepted;
899 nocheck= accept_proportion >= nocheck_thresh;
900 if (nocheck && !nocheck_reported) {
901 notice("entering nocheck mode for the first time");
906 static void article_done(Connection *conn, Article *art, int whichcount) {
908 counts.articles[art->checked][whichcount]++;
909 if (whichcount == RC_accepted) update_nocheck(1);
910 else if (whichcount == RC_unwanted) update_nocheck(0);
912 InputFile *ipf= art->ipf;
913 while (art->blanklen) {
914 static const char spaces[]=
919 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
920 int r= pwrite(ipf->fd, spaces, w, art->offset);
922 if (errno==EINTR) continue;
923 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
924 art->messageid, art->blanklen, art->offset, ipf->path);
926 assert(r>=0 && r<=w);
932 assert(ipf->inprogress >= 0);
934 if (!ipf->inprogress)
935 loop->on_time(loop, OOP_TIME_NOW, statemc_check_oldinput_done, 0);
940 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
941 const char *errmsg, int errnoval,
942 const char *data, size_t recsz, void *conn_v) {
944 connfail(conn, "error receiving from peer: %s", errmsg);
948 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
949 const char *errmsg, int errnoval,
950 const char *data, size_t recsz, void *conn_v) {
953 if (ev == OOP_RD_EOF) {
954 connfail(conn, "unexpected EOF from peer");
957 assert(ev == OOP_RD_OK);
960 unsigned long code= strtoul(data, &ep, 10);
961 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
967 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
969 if (!c) { *q++= '\''; break; }
970 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
971 sprintf(q,"\\x%02x",c);
974 connfail(conn, "badly formatted response from peer: %s", sanibuf);
978 if (conn->quitting) {
980 connfail(conn, "peer gave failure response to QUIT: %s", sani);
989 #define GET_ARTICLE \
990 art= article_reply_check(conn, data, code_streaming, sani); \
991 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
993 #define ARTICLE_DEALTWITH(streaming,how) \
994 code_streaming= (streaming) \
996 article_done(conn, art, RC_##how); break;
998 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1000 int code_streaming= 0;
1004 case 400: PEERBADMSG("peer stopped accepting articles");
1005 case 503: PEERBADMSG("peer timed us out");
1006 default: PEERBADMSG("peer sent unexpected message");
1008 case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
1009 case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
1011 case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
1012 case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
1014 case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
1015 case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
1017 case 238: /* CHECK says send it */
1019 case 335: /* IHAVE says send it */
1021 count_checkedwanted++;
1022 LIST_ADDTAIL(conn->queue);
1024 connfail("peer gave %d response to article body: %s",code, sani);
1025 return OOP_CONTINUE;
1030 case 431: /* CHECK or TAKETHIS says try later */
1032 case 436: /* IHAVE says try later */
1034 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1036 sysfatal("write to defer file %s",path_ductdefer);
1037 article_done(conn, art, RC_deferred);
1042 check_check_work(conn);
1043 return OOP_CONTINUE;
1047 /*========== monitoring of input files ==========*/
1049 static void feedfile_eof(InputFile *ipf) {
1050 assert(ipf != main_input_file); /* promised by tailing_try_read */
1051 assert(ipf == old_input_file);
1053 if (sms==sm_SEPARATED1) SMS(SEPARATED2, 0, "eof on old feed file");
1054 else if (sms==sm_DROPPING1) SMS(DROPPING2, 0, "eof on dead feed file");
1057 inputfile_tailing_stop(ipf);
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 */
1088 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1093 /*---------- dealing with articles read in the input file ----------*/
1095 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1096 oop_rd_event ev, const char *errmsg,
1098 const char *data, size_t recsz,
1100 InputFile *ipf= ipf_v;
1102 char tokentextbuf[sizeof(TOKEN)*2+3];
1104 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1106 if (data[0] && data[0]!=' ') {
1107 char *space= strchr(data,' ');
1108 int tokenlen= space-data;
1109 int midlen= (int)recsz-tokenlen-1;
1110 if (midlen < 0) goto bad_data;
1112 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1113 memcpy(tokentextbuf, data, tokenlen);
1114 tokentextbuf[tokenlen]= 0;
1115 if (!IsToken(tokentextbuf)) goto bad_data;
1117 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1118 art->offset= ipf->offset;
1119 art->blanklen= recsz;
1120 art->midlen= midlen;
1121 art->checked= art->sentbody= 0;
1122 art->ipf= ipf; ipf->inprogress++;
1123 art->token= TextToToken(tokentextbuf);
1124 strcpy(art->messageid, space+1);
1125 LIST_ADDTAIL(queue, art);
1127 ipf->offset += recsz + 1;
1129 if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
1130 notice("starting flush (%lu >= %lu)",
1131 (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1133 int r= link(feedfile, duct_path);
1134 if (r) sysdie("link feedfile %s to ductfile %s", feedfile, dut_path);
1137 r= unlink(feedfile);
1138 if (r) sysdie("unlink old feedfile link %s", feedfile);
1141 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1144 check_master_queue();
1148 /*========== tailing input file ==========*/
1150 static void filemon_start(InputFile *ipf) {
1151 assert(!ipf->filemon);
1153 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1154 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1155 filemon_method_startfile(ipf, ipf->filemon);
1158 static void filemon_stop(InputFile *ipf) {
1159 if (!ipf->filemon) return;
1160 filemon_method_stopfile(ipf, ipf->filemon);
1165 static void filemon_callback(InputFile *ipf) {
1166 ipf->readable_callback(ipf->readable_callback_user);
1169 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1171 InputFile *ipf= user;
1172 return ipf->readable_callback(ipf->readable_callback_user);
1175 static void on_cancel(struct oop_readable *rable) {
1176 InputFile *ipf= (void*)rable;
1178 if (ipf->filemon) filemon_stopfile(ipf);
1179 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1180 ipf->readable_callback= 0;
1183 static int tailing_on_readable(struct oop_readable *rable,
1184 oop_readable_call *cb, void *user) {
1185 InputFile *ipf= (void*)rable;
1187 tailing_on_cancel(rable);
1188 ipf->readable_callback= cb;
1189 ipf->readable_callback_user= user;
1190 filemon_startfile(ipf);
1192 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1196 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1198 InputFile *ipf= (void*)rable;
1200 ssize_t r= read(ipf->fd, buffer, length);
1202 if (errno==EINTR) continue;
1206 if (ipf==main_input_file) { errno=EAGAIN; return -1; }
1207 assert(sms==sm_SEPARATED1 || sms==sm_DROPPING1);
1213 /*---------- filemon implemented with inotify ----------*/
1215 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1216 #define HAVE_FILEMON
1218 #include <linux/inotify.h>
1220 static int filemon_inotify_fd;
1221 static int filemon_inotify_wdmax;
1222 static InputFile **filemon_inotify_wd2ipf;
1224 typedef struct Filemon_Perfile {
1226 } Filemon_Inotify_Perfile;
1228 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1229 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1230 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1232 if (wd >= filemon_inotify_wdmax) {
1234 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1235 sizeof(*filemon_inotify_wd2ipf) * newmax);
1236 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1237 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1238 filemon_inotify_wdmax= newmax;
1241 assert(!filemon_inotify_wd2ipf[wd]);
1242 filemon_inotify_wd2ipf[wd]= ipf;
1247 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1249 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1250 if (r) sysdie("inotify_rm_watch");
1251 filemon_inotify_wd2ipf[wd]= 0;
1254 static void *filemon_inotify_readable(oop_source *lp, int fd,
1255 oop_event e, void *u) {
1256 struct inotify_event iev;
1258 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1260 if (errno==EAGAIN) break;
1261 sysdie("read from inotify master");
1262 } else if (r==sizeof(iev)) {
1263 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1265 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1267 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1268 filemon_callback(ipf);
1270 return OOP_CONTINUE;
1273 static int filemon_method_init(void) {
1274 filemon_inotify_fd= inotify_init();
1275 if (filemon_inotify_fd<0) {
1276 syswarn("could not initialise inotify: inotify_init failed");
1280 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1285 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1287 /*---------- filemon dummy implementation ----------*/
1289 #if !defined(HAVE_FILEMON)
1291 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1293 static int filemon_method_init(void) { return 0; }
1294 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1295 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1297 #endif /* !HAVE_FILEMON */
1299 /*---------- interface to start and stop an input file ----------*/
1301 static const oop_rd_style feedfile_rdstyle= {
1302 OOP_RD_DELIM_STRIP, '\n',
1304 OOP_RD_SHORTREC_EOF,
1307 static void inputfile_tailing_start(InputFile *ipf) {
1309 ipf->readable->on_readable= tailing_on_readable;
1310 ipf->readable->on_cancel= tailing_on_cancel;
1311 ipf->readable->try_read= tailing_try_read;
1312 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1313 ipf->readable->delete_kill= 0;
1315 ipf->readable_callback= 0;
1316 ipf->readable_callback_user= 0;
1318 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1321 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1322 feedfile_got_article,ipf, feedfile_problem,ipf);
1323 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1326 static void inputfile_tailing_stop(InputFile *ipf) {
1328 oop_rd_delete(ipf->rd);
1330 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1334 /*========== interaction with innd ==========*/
1336 /* See official state diagram at top of file. We implement
1346 |`--------------------------.
1347 | | install defer as backlog
1348 | OPEN F SUCCEEDS | exit
1353 | [Normal] =========
1357 | | F IS SO BIG WE SHOULD FLUSH
1361 | | our handle onto F is now onto D
1364 | |<---------------------------------------------------.
1366 | | spawn inndcomm flush |
1374 | | INNDCOMM FLUSH FAILS ^
1375 | |`----------------------->----------. |
1377 | | NO SUCH SITE V |
1378 ^ |`--------------->----. =========== |
1384 | | \ | TIME TO RETRY |
1385 | | \ `----------------'
1389 | ============= ============
1390 | SEPARATED1 DROPPING1
1391 | [Separated] [Dropping]
1392 | main F idle main none
1393 | old D tail old D tail
1394 | ============= ============
1396 ^ | EOF ON D | EOF ON D
1398 | ============= ============
1399 | SEPARATED2 DROPPING2
1400 | [Finishing] [Dropping]
1401 | main F tail main none
1402 | old D idle old D idle
1403 | ============= ============
1405 | | ALL D PROCESSED | ALL D PROCESSED
1406 | V install defer as backlog V install defer as backlog
1407 ^ | close D | close D
1408 | | unlink D | unlink D
1409 | | start new defer | exit
1411 `----------' ==========
1417 static void open_defer(void) {
1421 defer= fopen(path_ductdefer, "a+");
1422 if (!defer) sysfatal("could not open defer file %s", path_ductdefer);
1424 /* truncate away any half-written records */
1426 r= fstat(fileno(defer), &stab);
1427 if (r) sysdie("could not stat newly opened defer file %s", path_ductdefer);
1429 if (stab.st_size > LONG_MAX)
1430 die("defer file %s size is far too large", path_ductdefer);
1435 long orgsize= stab.st_size;
1436 long truncto= stab.st_size;
1438 if (!truncto) break; /* was only (if anything) one half-truncated record */
1439 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1440 sysdie("seek in defer file %s while truncating partial", path_ductdefer);
1445 sysdie("failed read from defer file %s", path_ductdefer);
1447 die("defer file %s shrank while we were checking it!", path_ductdefer);
1453 if (stab.st_size != truncto) {
1454 warn("truncating half-record at end of defer file %s -"
1455 " shrinking by %ld bytes from %ld to %ld",
1456 path_ductdefer, orgsize - truncto, orgsize, truncto);
1459 sysfatal("could not flush defer file %s", path_ductdefer);
1460 if (ftruncate(fileno(defer), truncto))
1461 sysdie("could not truncate defer file %s", path_ductdefer);
1464 info("continuing existing defer file %s (%ld bytes)",
1465 path_ductdefer, orgsize);
1467 if (fseek(defer, truncto, SEEK_SET))
1468 sysdie("could not seek to new end of defer file %s", path_ductdefer);
1471 static void statemc_init(void) {
1474 path_ductlock= xasprintf("%s_duct.lock", feedfile);
1475 path_duct= xasprintf("%s_duct", feedfile);
1476 path_ductdefer= xasprintf("%s_duct.defer", feedfile);
1478 if (lstat(path_ductdefer, &stab)) {
1479 if (errno!=ENOENT) sysdie("could not check defer file %s", path_defer);
1481 if (!S_ISREG(stab.st_mode))
1482 die("defer file %s not a plain file (mode 0%lo)",
1483 path_defer, (unsigned long)stab.st_mode);
1484 switch (stab.st_nlink==1) {
1485 case 1: /* ok */ break;
1487 if (unlink(path_defer))
1488 sysdie("could not unlink stale defer file link %s (presumably"
1489 " hardlink to backlog file)", path_defer);
1492 die("defer file %s has unexpected link count %d",
1493 path_defer, stab.st_nlink);
1498 int lockfd= open(path_ductlock, O_CREAT|O_RDWR, 0600);
1499 if (lockfd<0) sysfatal("open lockfile %s", path_ductlock);
1502 memset(&fl,0,sizeof(fl));
1504 fl.l_whence= SEEK_SET;
1505 r= fcntl(lockfd, F_SETLK, &fl);
1507 if (errno==EACCES || errno==EAGAIN) {
1508 if (quiet_if_locked) exit(0);
1509 fatal("another duct holds the lockfile");
1511 sysdie("fcntl F_SETLK lockfile %s", path_ductlock);
1514 InputFile *file_d= open_input_file(path_duct);
1517 struct stat stab_f, stab_d;
1519 r= stat(feedfile, &stab_f);
1521 if (errno!=ENOENT) sysdie("check feed file %s", feedfile);
1522 /* D exists, F ENOENT => Moved */
1526 /* F and D both exist */
1528 r= fstat(file_d->fd, &stab_d);
1529 if (r) sysdie("check duct file %s", ductfile);
1531 if (stab_d.st_ino == stab_f.st_ino &&
1532 stab_d.st_dev == stab_f.st_dev) {
1533 /* F==D => Hardlinked*/
1534 r= unlink(path_duct);
1535 if (r) sysdie("unlink feed file %s during startup", feedfile);
1538 startup_set_input_file(file_d);
1539 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1541 /* F!=D => Separated */
1542 SMS(SEPARATED1, 0, "found both old and current feed files");
1543 startup_set_input_file(file_d);
1545 } else { /*!file_d*/
1546 SMS(WAITING, open_wait_periods, "no feed file currently exists");
1550 static void statemc_poll(void) {
1551 if (sms==sm_WAITING) { statemc_waiting_poll(); return; }
1553 if (!sm_period_counter) return;
1554 sm_period_counter--;
1555 assert(sm_period_counter>=0);
1557 if (sm_period_counter) return;
1560 fatal("timed out waiting for innd to create feed file %s", feedfile);
1562 spawn_inndcomm_flush(void);
1569 static void statemc_waiting_poll(void) {
1570 InputFile *file_f= open_input_file(feedfile);
1571 if (!file_f) return;
1572 startup_set_input_file(file_d);
1573 SMS(NORMAL, 0, "found and opened feed file");
1576 static void startup_set_input_file(InputFile *f) {
1577 assert(!main_input_file);
1579 inputfile_tailing_start(f);
1582 static void *statemc_check_oldinput_done(oop_source *lp,
1583 struct timeval now, void *u) {
1586 int done= (sms==sm_SEPARATED2 || sms==sm_DROPPING2)
1587 && old_input_file->inprogress;
1590 r= fstat(fileno(defer), &stab);
1591 if (r) sysdie("check defer file %s", path_defer);
1593 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1596 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1597 (unsigned long)now.tv_sec,
1598 (unsigned long)stab.st_ino);
1599 if (link(path_defer, path_backlog))
1600 sysfatal("could not install defer file %s as backlog file %s",
1601 path_defer, backlog);
1602 if (unlink(path_defer))
1603 sysdie("could not unlink old defer link %s to backlog file %s",
1604 path_defer, backlog);
1606 if (unlink(path_duct))
1607 sysdie("could not unlink old duct file %s", path_duct);
1609 if (sms==sm_DROPPING2) {
1610 notice("feed dropped and our work is complete"
1611 " (but check for backlog files)");
1617 close_input_file(old_input_file);
1620 notice("flush complete");
1621 SMS(NORMAL, 0, "flush complete");
1624 static void statemc_setstate(StateMachineState newsms, int periods,
1625 const char *forlog, const char *why) {
1627 sm_period_counter= periods;
1629 info("%s[%d] %s",periods,forlog,why);
1631 info("%s %s",forlog,why);
1635 /*========== flushing the feed ==========*/
1637 static pid_t inndcomm_child;
1639 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1640 assert(inndcomm_child);
1641 int status= xwaitpid(&inndcomm_child, "inndcomm");
1642 loop->cancel_fd(fd);
1645 assert(!old_input_file);
1647 if (WIFEXITED(status)) {
1648 switch (WEXITSTATUS(status)) {
1650 case INNDCOMMCHILD_ESTATUS_FAIL:
1653 case INNDCOMMCHILD_ESTATUS_NONESUCH:
1654 warn("feed has been dropped by innd, finishing up");
1655 old_input_file= main_input_file;
1657 SMS(DROPPING1, 0, "dropped by innd");
1658 return OOP_CONTINUE;
1661 old_input_file= main_input_file;
1662 main_input_file= open_input_file(feedfile);
1663 if (!main_input_file)
1664 die("flush succeeded but feedfile %s does not exist!", feedfile);
1665 SMS(SEPARATED1, 0, "feed file missing");
1666 return OOP_CONTINUE;
1669 goto unexpected_exitstatus;
1672 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1673 warn("flush timed out trying to talk to innd");
1676 unexpected_exitstatus:
1677 report_child_status("inndcomm child", status);
1681 SMS(FLUSHFAIL, flushfail_retry_periods, "flush failed, will retry");
1684 static void inndcommfail(const char *what) {
1685 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1686 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1689 void spawn_inndcomm_flush(void) {
1692 assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1693 assert(!inndcomm_child);
1695 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1697 inndcomm_child= xfork();
1699 if (!inndcomm_child) {
1700 static char flushargv[2]= { sitename, 0 };
1705 alarm(inndcomm_flush_timeout);
1706 r= ICCopen(); if (r) inndcommfail("connect");
1707 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
1708 if (!r) exit(0); /* yay! */
1710 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1711 syswarn("innd ctlinnd flush failed: innd said %s", reply);
1712 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1716 int sentinel_fd= pipefds[0];
1717 on_fd_read_except(sentinel_fd, inndcomm_event);
1719 SMS(FLUSHING, 0, "flush is in progress");
1722 /*========== main program ==========*/
1724 static void postfork_inputfile(InputFile *ipf) {
1726 assert(ipf->fd >= 0);
1731 static void postfork_conns(Connection *conn) {
1738 static void postfork_stdio(FILE *f) {
1739 /* we have no stdio streams that are buffered long-term */
1743 static void postfork(const char *what) {
1744 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1745 sysdie("%s child: failed to reset SIGPIPE");
1747 postfork_inputfile(main_input_file);
1748 postfork_inputfile(old_input_file);
1749 postfork_conns(idle.head);
1750 postfork_conns(working.head);
1751 postfork_conns(full.head);
1752 postfork_stdio(defer);
1756 #define EVERY(what, interval, body) \
1757 static const struct timeval what##_timeout = { 5, 0 }; \
1758 static void what##_schedule(void); \
1759 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1761 what##_schedule(); \
1763 static void what##_schedule(void) { \
1764 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
1767 EVERY(filepoll, {5,0}, { check_master_queue(); })
1769 EVERY(period, {PERIOD_SECONDS,0}, {
1770 if (connect_delay) connect_delay--;
1772 check_master_queue();
1776 /*========== option parsing ==========*/
1779 of_seconds= 001000u;
1780 of_boolean= 002000u;
1783 typedef struct Option Option;
1784 typedef void OptionParser(const Option*, const char *val);
1794 void op_integer(const Option *o, const char *val) {
1797 unsigned long ul= strtoul(val,&ep,10);
1798 if (*ep || ep==val || errno || ul>INT_MAX)
1799 badusage("bad integer value for %s",o->long);
1800 int *store= o->store;
1804 void op_double(const Option *o, const char *val) {
1805 int *store= o->store;
1808 *store= strtod(val, &ep);
1809 if (*ep || ep==val || errno)
1810 badusage("bad floating point value for %s",o->long);
1813 void op_string(const Option *o, const char *val) {
1814 char **store= o->store;
1819 void op_seconds(const Option *o, const char *val) {
1820 int *store= o->store;
1823 double v= strtod(val,&ep);
1824 if (ep==val) badusage("bad time/duration value for %s",o->long);
1826 if (!*ep || !strcmp(ep,"s")) unit= 1;
1827 else if (!strcmp(ep,"m")) unit= 60;
1828 else if (!strcmp(ep,"h")) unit= 3600;
1829 else if (!strcmp(ep,"d")) unit= 86400;
1830 else badusage("bad units %s for time/duration value for %s",ep,o->long);
1834 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
1838 void op_periods_rndup(const Option *o, const char *val) {
1839 int *store= o->store;
1841 *store += PERIOD_SECONDS-1;
1842 *store /= PERIOD_SECONDS;
1845 void op_periods_booltrue(const Option *o, const char *val) {
1846 int *store= o->store;
1849 void op_periods_boolfalse(const Option *o, const char *val) {
1850 int *store= o->store;
1854 static const Option options[]= {
1855 { 0, "max-connections", &max_connections op_integer },
1856 { 0, "streaming", &try_stream, op_booltrue, 1 },
1857 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
1858 {'h',"host", &remote_host, op_string },
1859 {'P',"port", &port op_integer },
1860 { 0, "inndconf", &inndconffile, op_string },
1861 {'f',"feedfile", &feedfile, op_string },
1862 {'q',"quiet-multiple", &quiet_if_locked, op_booltrue, 1 },
1863 { 0, "no-quiet-multiple", &quiet_if_locked, op_boolfalse, 1 },
1864 {'d',"daemon", &become_daemon, op_booltrue, 1 },
1865 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
1867 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
1868 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
1870 { 0, "max-queue-size", &max_queue_per_conn op_integer },
1871 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
1872 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
1873 { 0, "feedfile-open-timeout", &open_wait_periods, op_periods_rndup },
1874 { 0, "connection-timeout", &connection_timeout, op_seconds },
1875 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
1878 int main(int argc, char **argv) {
1884 if (*arg != '-') break;
1885 if (!strcmp(arg,"--")) { arg= *++argv; break; }
1887 while ((a= *++arg)) {
1891 char *equals= strchr(arg,'=');
1892 int len= equals ? (equals - arg) : strlen(arg);
1893 for (o=options; o->long; o++)
1894 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
1896 badusage("unknown long option --%s",arg);
1899 if (equals) badusage("option --%s does not take a value",o->long);
1901 } else if (equals) {
1905 if (!arg) badusage("option --%s needs a value",o->long);
1908 break; /* eaten the whole argument now */
1910 for (o=options; o->long; o++)
1913 badusage("unknown short option -%c",a);
1920 if (!arg) badusage("option -%c needs a value",o->short);
1923 break; /* eaten the whole argument now */
1928 if (!arg) badusage("need site name argument");
1929 if (*++argv) badusage("too many non-option arguments");
1932 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
1933 badusage("nocheck threshold percentage must be between 0..100");
1934 nocheck_thresh= nocheck_thresh_pct * 0.01;
1936 if (nocheck_decay_articles < 0.1)
1937 badusage("nocheck decay articles must be at least 0.1");
1938 nocheck_decay= 1 - 1/nocheck_decay_articles;
1940 innconf_read(inndconffile);
1943 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
1944 else if (!feedfile[0])
1945 badusage("feed filename must be nonempty");
1946 else if (feedfile[strlen(feedfile)-1]=='/')
1947 feedfile= xasprintf("%s%s",feedfile,sitename);
1949 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1950 sysdie("could not ignore SIGPIPE");
1952 if (become_daemon) {
1953 for (i=3; i<255; i++)
1954 /* do this now before we open syslog, etc. */
1956 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
1958 int null= open("/dev/null",O_RDWR);
1959 if (null<0) sysdie("failed to open /dev/null");
1965 pid_t child1= xfork("daemonise first fork");
1966 if (child1) _exit(0);
1968 pid_t sid= setsid();
1969 if (sid != child1) sysdie("setsid failed");
1971 pid_t child2= xfork("daemonise second fork");
1972 if (child2) _exit(0);
1977 if (!filemon_init()) {
1978 warn("no file monitoring available, polling");
1979 filepoll_schedule();