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
52 <--------------------------------------'|
53 Nothing F, D both ENOENT |
56 duct: not not reading anything |
58 |`---------------------. |
59 | | duct times out waiting for F |
60 V innd creates F | duct exits |
62 Noduct GO TO Dropped |
65 duct: not running or not reading anything |
68 ,-->--+ <---------------------------------'|
69 | | duct opens F F exists |
73 | F: innd writing, duct reading |
76 | | duct decides time to flush |
77 | | duct makes hardlink |
79 | V <------------------------'|
81 | F == D: innd writing, duct reading both exist |
85 | Moved <----+------------<--'|
86 | F: ENOENT | F ENOENT |
87 | D: innd writing, duct reading | D exists |
89 | | duct requests flush of feed | |
90 | | (others can too, harmlessly) | |
94 | D: innd flushing, duct reading | |
96 | | inndcomm flush fails | |
97 | |`-------------------------->---------' |
99 | | inndcomm reports no such site |
100 | |`---------------------------------------------------- | -.
102 | | innd finishes writing D, creates F | |
103 | | inndcomm reports flush successful | |
106 | Separated <----------------' |
107 | F: innd writing F!=D /
108 | D: duct reading both exist /
110 | | duct gets to the end of D /
111 | | duct opens F too /
114 | F: innd writing, duct reading |
115 | D: duct finishing V
117 | | duct finishes processing D F: ENOENT
118 | V duct unlinks D D: duct reading
120 `--<--' | duct finishes
130 "duct reading" means innduct is reading the file but also
131 overwriting processed tokens.
138 /*----- general definitions, probably best not changed -----*/
140 #define PERIOD_SECONDS 60
142 #define CONNCHILD_ESTATUS_STREAM 4
143 #define CONNCHILD_ESTATUS_NOSTREAM 5
145 #define INNDCOMMCHILD_ESTATUS_FAIL 6
146 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
149 /*----- configuration options -----*/
151 static char *sitename, *feedfile;
152 static int max_connections=10, max_queue_per_conn=200;
153 static int connection_setup_timeout=200, port=119, try_stream=1;
154 static int inndcomm_flush_timeout=100, quiet_if_locked=0;
155 static const char *remote_host;
156 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
157 static const char *inndconffile;
159 static double accept_proportion;
160 static double nocheck_thresh_pct= 95.0;
161 static double nocheck_thresh; /* computed in main from _pct */
162 static double nocheck_decay_articles= 100; /* converted to _decay */
163 static double nocheck_decay; /* computed in main from _articles */
164 static int nocheck, nocheck_reported;
167 /*----- doubly linked lists -----*/
169 #define ISNODE(T) T *next, *back;
170 #define LIST(T) struct { T *head, *tail, *tailpred; int count; }
172 #define NODE(n) ((struct node*)&(n)->head)
174 #define LIST_ADDHEAD(l,n) \
175 (list_addhead((struct list*)&(l), NODE((n))), (void)(l).count++)
176 #define LIST_ADDTAIL(l,n) \
177 (list_addtail((struct list*)&(l), NODE((n))), (void)(l).count++)
179 #define LIST_REMHEAD(l) \
180 ((l).count ? ((l).count--, (void*)list_remhead((struct list*)&(l))) : 0)
181 #define LIST_REMTAIL(l) \
182 ((l).count ? ((l).count--, (void*)list_remtail((struct list*)&(l))) : 0)
183 #define LIST_REMOVE(l,n) \
184 (list_remove(NODE((n))), (void)(l).count--)
185 #define LIST_INSERT(l,n,pred) \
186 (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
189 /*----- statistics -----*/
191 #define RESULT_COUNTS \
200 #define RC_INDEX(x) RCI_##x
206 int articles[2 /* checked */][RCI_max];
210 /*----- transmission buffers -----*/
215 xk_Malloc, xk_Const, xk_Artdata;
227 /*----- core operational data structure types -----*/
231 int checked, sentbody;
240 /* This is an instance of struct oop_readable */
241 struct oop_readable readable; /* first */
242 oop_readable_call *readable_callback;
243 void *readable_callback_user;
246 const char *path; /* ptr copy of path_<foo> or feedfile */
247 struct Filemon_Perfile *filemon;
250 long inprogress; /* no. of articles read but not processed */
260 sm_SEPARATED2, /* must follow SEPARATED2 - see feedfile_eof */
262 sm_DROPPING2, /* must follow DROPPING1 - see feedfile_eof */
267 int fd, max_queue, stream;
268 LIST(Article) queue; /* not yet told peer, or CHECK said send it */
269 LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
270 struct iovec xmit[CONNIOVS];
271 XmitDetails xmitd[CONNIOVS];
276 /*----- operational variables -----*/
278 static int since_connect_attempt;
280 static LIST(Conn) idle, working, full;
281 static LIST(Article) *queue;
283 static char *path_ductlock, *path_duct, *path_ductdefer;
285 #define SMS(newstate, periods, why) \
286 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
288 static StateMachineState sms;
290 static InputFile *main_input_file, *old_input_file;
291 static int sm_period_counter;
294 /*----- function predeclarations -----*/
296 static void conn_check_work(Conn *conn);
298 static int filemon_init(void);
299 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
300 static void filemon_callback(void);
302 static void statemc_setstate(StateMachineState newsms, int periods,
303 const char *forlog, const char *why);
305 /*========== utility functions etc. ==========*/
307 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
309 static pid_t xfork(const char *what) {
313 if (child==-1) sysdie("cannot fork for %s",what);
314 if (!child) postfork(what);
318 static void on_fd_read_except(int fd, oop_call_fd callback) {
319 loop->on_fd(loop, fd, OOP_READ, callback, 0);
320 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
322 static void cancel_fd_read_except(int fd) {
323 loop->cancel_fd(loop, fd, OOP_READ);
324 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
327 static void report_child_status(const char *what, int status) {
328 if (WIFEXITED(status)) {
329 int es= WEXITSTATUS(status);
331 warn("%s: child died with error exit status %d",es);
332 } else if (WIFSIGNALED(status)) {
333 int sig= WTERMSIG(status);
334 const char *sigstr= strsignal(sig);
335 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
337 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
339 warn("%s: child died due to unknown fatal signal %d%s",
340 what, sig, coredump);
342 warn("%s: child died with unknown wait status %d", status);
346 static int xwaitpid(pid_t *pid, const char *what) {
349 r= kill(*pid, SIGKILL);
350 if (r) sysdie("cannot kill %s child", what);
352 pid_t got= waitpid(*pid, &status, WNOHANG);
353 if (got==-1) sysdie("cannot reap %s child", what);
360 /*========== logging ==========*/
362 static void logcore(int sysloglevel, const char *fmt, ...)
363 __attribute__((printf,2,3))
364 static void logcore(int sysloglevel, const char *fmt, ...) {
368 vsyslog(sysloglevel,fmt,al);
370 vfprintf(stderr,fmt,al);
375 static void logv(int sysloglevel, const char *pfx, int errnoval,
376 int exitstatus, const char *fmt, va_list al)
377 __attribute__((printf,4,0))
378 static void logv(int sysloglevel, const char *pfx, int errnoval,
379 int exitstatus, const char *fmt, va_list al) {
381 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
382 msgbuf[sizeof(msgbuf)-1]= 0;
384 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
385 sysloglevel= LOG_ERR; /* run by wrong user, probably */
387 logcore(sysloglevel, "<%s>%s: %s%s%s",
388 sitename, pfx, msgbuf,
389 errnoval>=0 ? ": " : "",
390 errnoval>=0 ? strerror(errnoval) : "");
393 #define logwrap(fn, pfx, sysloglevel, errno, estatus) \
394 static void fn(const char *fmt, ...) \
395 __attribute__((printf,1,2)); \
396 static void fn(const char *fmt, ...) { \
399 logv(sysloglevel, pfx, errno, estatus, fmt, al); \
402 logwrap(sysdie, " critical", LOG_CRIT, errno, 16);
403 logwrap(die, " critical", LOG_CRIT, -1, 16);
405 logwrap(sysfatal, " fatal", LOG_ERR, errno, 12);
406 logwrap(fatal, " fatal", LOG_ERR, -1, 12);
408 logwrap(syswarn, " warning", LOG_WARN, errno, 0);
409 logwrap(warn, " warning", LOG_WARN, -1, 0);
411 logwrap(notice, "", LOG_NOTICE, -1, 0);
412 logwrap(info, " info", LOG_INFO, -1, 0);
415 /*========== making new connections ==========*/
417 static int connecting_sockets[2]= {-1,-1};
418 static pid_t connecting_child;
420 static void connect_attempt_discard(void) {
421 if (connecting_sockets[0])
422 cancel_fd(connecting_sockets[0]);
424 perhaps_close(&connecting_sockets[0]);
425 perhaps_close(&connecting_sockets[1]);
427 if (connecting_child) {
428 int status= xwaitpid(&connecting_child, "connect");
430 if (!(WIFEXITED(status) ||
431 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
432 report_child_status("connect", status);
436 #define PREP_DECL_MSG_CMSG(msg) \
438 memset(&msg,0,sizeof(msg)); \
439 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
440 msg.msg_control= msg##cbuf; \
441 msg.msg_controllen= sizeof(msg##cbuf);
443 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
446 conn= xmalloc(sizeof(*conn));
447 memset(conn,0,sizeof(*conn));
450 struct cmsghdr *h= 0;
451 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
452 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
455 pid_t got= waitpid(connecting_child, &status, WNOHANG);
457 assert(got==connecting_child);
459 if (WIFEXITED(status) &&
460 (WEXITSTATUS(status) != 0
461 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
462 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
463 /* child already reported the problem */
464 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
465 warn("connect: connection attempt timed out");
466 } else if (!WIFEXITED(status)) {
467 report_child_status("connect", status);
468 /* that's probably the root cause then */
471 /* child is still running apparently, report the socket problem */
473 syswarn("connect: read from child socket failed");
474 else if (e == OOP_EXCEPTIONN)
475 warn("connect: unexpected exception on child socket");
477 warn("connect: unexpected EOF on child socket");
482 #define CHK(field, val) \
483 if (h->cmsg_##field != val) { \
484 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
487 CHK(level, SOL_SOCKET);
488 CHK(type, SCM_RIGHTS);
489 CHK(len, CMSG_LEN(sizeof(conn-b>fd)));
492 if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
494 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
496 pid_t got= waitpid(connecting_child, &status, 0);
497 if (got==-1) sysdie("connect: real wait for child");
498 assert(got == connecting_child);
501 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
502 int es= WEXITSTATUS(status);
504 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
505 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
507 fatal("connect: child gave unexpected exit status %d", es);
513 LIST_ADDHEAD(idle, conn);
514 notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
515 connect_attempt_discard();
516 check_master_queue();
521 perhaps_close(&conn->fd);
524 connect_attempt_discard();
527 static void connect_start() {
528 assert(!connecting_sockets[0]);
529 assert(!connecting_sockets[1]);
530 assert(!connecting_child);
532 notice("starting connection attempt");
534 r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
535 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
537 connecting_child= xfork("connection");
539 if (!connecting_child) {
540 FILE *cn_from, *cn_to;
541 char buf[NNTP_STRLEN+100];
542 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
544 r= close(connecting_sockets[0]);
545 if (r) sysdie("connect: close parent socket in child");
547 alarm(connection_setup_timeout);
548 if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
550 sanitise_inplace(buf);
551 fatal("connect: rejected: %s", buf);
553 sysfatal("connect: connection attempt failed");
556 if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
557 sysfatal("connect: authentication failed");
559 if (fputs("MODE STREAM\r\n", cn_to) ||
561 sysfatal("connect: could not send MODE STREAM");
562 buf[sizeof(buf)-1]= 0;
563 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
565 sysfatal("connect: could not read response to MODE STREAM");
567 fatal("connect: connection close in response to MODE STREAM");
572 sanitise_inplace(buf);
573 fatal("connect: response to MODE STREAM is too long: %.100s...",
576 l--; if (l>0 && buf[1-]=='\r') l--;
579 int rcode= strtoul(buf,&ep,10);
581 sanitise_inplace(buf);
582 fatal("connect: bad response to MODE STREAM: %.50s", buf);
586 exitstatus= CONNCHILD_ESTATUS_STREAM;
592 sanitise_inplace(buf);
593 warn("connect: unexpected response to MODE STREAM: %.50s", buf);
598 int fd= fileno(cn_from);
600 PREP_DECL_MSG_CMSG(msg);
601 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
602 cmsg->cmsg_level= SOL_SOCKET;
603 cmsg->cmsg_type= SCM_RIGHTS;
604 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
605 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
607 msg.msg_controllen= cmsg->cmsg_len;
608 r= sendmsg(connecting_sockets[1], &msg, 0);
609 if (r) sysdie("sendmsg failed for new connection");
614 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
615 if (r) sysdie("connect: close child socket in parent");
617 on_fd_read_except(connecting_sockets[0], connchild_event);
621 connect_attempt_discard();
625 /*========== overall control of article flow ==========*/
627 static void check_master_queue(void) {
628 try reading current feed file;
633 Conn *last_assigned=0;
636 conn_assign_one_article(&working, &last_assigned);
637 } else if (idle.head) {
638 conn_assign_one_article(&idle, &last_assigned);
639 } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
640 !connecting_child && !connect_delay) {
641 connect_delay= reconnect_delay_periods;
647 conn_check_work(last_assigned);
650 static void conn_assign_one_article(LIST(Conn) *connlist,
651 Conn **last_assigned) {
652 Conn *conn= connlist->head;
654 LIST_REMOVE(*connlist, conn);
655 Article *art= LIST_REMHEAD(queue);
656 LIST_ADDTAIL(conn->queue, art);
657 LIST_ADD(*conn_determine_right_list(conn), conn);
659 /* This slightly odd arrangement is so that we call conn_check_work
660 * once after filling the queue for a new connection in
661 * check_master_queue, rather than for each article. */
662 if (conn != *last_assigned && *last_assigned)
663 conn_check_work(*last_assigned);
664 *last_assigned= conn;
667 static int conn_total_queued_articles(Conn *conn) {
668 return conn->sent.count + conn->queue.count;
671 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
672 int inqueue= conn_total_queued_articles(conn);
673 assert(inqueue <= max_queue);
674 if (inqueue == 0) return &idle;
675 if (inqueue == conn->max_queue) return &full;
679 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
684 static void conn_check_work(Conn *conn) {
687 conn_make_some_xmits(conn);
689 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
693 void *rp= conn_write_some_xmits(conn);
694 if (rp==OOP_CONTINUE) {
695 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
697 } else if (rp==OOP_HALT) {
700 /* transmitted everything */
708 /*========== article transmission ==========*/
710 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
711 XmitKind kind) { /* caller must then fill in details */
712 struct iovec *v= &conn->xmit[conn->xmitu];
713 XmitDetails *d= &conn->xmitd[conn->xmitu++];
720 static void xmit_noalloc(Conn *conn, const char *data, int len) {
721 xmit_core(conn,data,len, xk_Const);
723 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
725 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
726 XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
730 static void xmit_free(XmitDetails *d) {
732 case xk_Malloc: free(d->info.malloc_tofree); break;
733 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
734 case xk_Const: break;
739 static void *conn_write_some_xmits(Conn *conn) {
741 * 0: nothing more to write, no need to call us again
742 * OOP_CONTINUE: more to write but fd not writeable
743 * OOP_HALT: disaster, have destroyed conn
746 int count= conn->xmitu;
747 if (!count) return 0;
749 if (count > IOV_MAX) count= IOV_MAX;
750 ssize_t rs= writev(conn->fd, conn->xmit, count);
752 if (errno == EAGAIN) return OOP_CONTINUE;
753 connfail(conn, "write failed: %s", strerror(errno));
758 for (done=0; rs && done<xmitu; done++) {
759 struct iovec *vp= &conn->xmit[done];
760 XmitDetails *dp= &conn->xmitd[done];
761 if (rs > vp->iov_len) {
769 int newu= conn->xmitu - done;
770 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
771 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
776 static void conn_make_some_xmits(Conn *conn) {
778 if (conn->xmitu+5 > CONNIOVS)
781 Article *art= LIST_REMHEAD(queue);
784 if (art->checked || (conn->stream && nocheck)) {
785 /* actually send it */
787 ARTHANDLE *artdata= SMretrieve();
791 XMIT_LITERAL("TAKETHIS ");
792 xmit_noalloc(conn, art->mid, art->midlen);
793 XMIT_LITERAL("\r\n");
794 xmit_artbody(conn, artdata);
797 /* we got 235 from IHAVE */
799 xmit_artbody(conn, artdata);
801 XMIT_LITERAL(".\r\n");
806 LIST_ADDTAIL(conn->sent, art);
808 counts[art->checked].sent++;
814 XMIT_LITERAL("IHAVE ");
816 XMIT_LITERAL("CHECK ");
817 xmit_noalloc(art->mid, art->midlen);
818 XMIT_LITERAL("\r\n");
820 LIST_ADDTAIL(conn->sent, art);
821 counts[art->checked].offered++;
827 /*========== handling responses from peer ==========*/
829 static const oop_rd_style peer_rd_style= {
830 OOP_RD_DELIM_STRIP, '\n',
832 OOP_RD_SHORTREC_FORBID
835 static Article *article_reply_check(Connection *conn, const char *response,
836 int code_indicates_streaming,
837 const char *sanitised_response) {
838 Article *art= LIST_REMHEAD(conn->sent);
842 "peer gave unexpected response when no commands outstanding: %s",
847 if (code_indicates_streaming) {
848 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
850 connfail("peer gave streaming response code "
851 " to IHAVE or subsequent body: %s", sanitised_response);
854 const char *got_mid= response+4;
855 int got_midlen= strcspn(got_mid, " \n\r");
856 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
857 connfail("peer gave streaming response with syntactically invalid"
858 " messageid: %s", sanitised_response);
861 if (got_midlen != art->midlen ||
862 memcmp(got_mid, art->messageid, got_midlen)) {
863 connfail("peer gave streaming response code to wrong article -"
864 " probable synchronisation problem; we offered: %s;"
866 art->messageid, sanitised_response);
871 connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
880 static void update_nocheck(int accepted) {
881 accept_proportion *= accept_decay;
882 accept_proportion += accepted;
883 nocheck= accept_proportion >= nocheck_thresh;
884 if (nocheck && !nocheck_reported) {
885 notice("entering nocheck mode for the first time");
890 static void article_done(Connection *conn, Article *art, int whichcount) {
892 counts.articles[art->checked][whichcount]++;
893 if (whichcount == RC_accepted) update_nocheck(1);
894 else if (whichcount == RC_unwanted) update_nocheck(0);
896 InputFile *ipf= art->ipf;
897 while (art->blanklen) {
898 static const char spaces[]=
903 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
904 int r= pwrite(ipf->fd, spaces, w, art->offset);
906 if (errno==EINTR) continue;
907 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
908 art->messageid, art->blanklen, art->offset, ipf->path);
910 assert(r>=0 && r<=w);
916 assert(ipf->inprogress >= 0);
918 if (!ipf->inprogress)
919 loop->on_time(loop, OOP_TIME_NOW, statemc_check_oldinput_done, 0);
924 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
925 const char *errmsg, int errnoval,
926 const char *data, size_t recsz, void *conn_v) {
928 connfail(conn, "error receiving from peer: %s", errmsg);
932 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
933 const char *errmsg, int errnoval,
934 const char *data, size_t recsz, void *conn_v) {
937 if (ev == OOP_RD_EOF) {
938 connfail(conn, "unexpected EOF from peer");
941 assert(ev == OOP_RD_OK);
944 unsigned long code= strtoul(data, &ep, 10);
945 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
951 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
953 if (!c) { *q++= '\''; break; }
954 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
955 sprintf(q,"\\x%02x",c);
958 connfail(conn, "badly formatted response from peer: %s", sanibuf);
962 if (conn->quitting) {
964 connfail(conn, "peer gave failure response to QUIT: %s", sani);
973 #define GET_ARTICLE \
974 art= article_reply_check(conn, data, code_streaming, sani); \
975 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
977 #define ARTICLE_DEALTWITH(streaming,how) \
978 code_streaming= (streaming) \
980 article_done(conn, art, RC_##how); break;
982 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
984 int code_streaming= 0;
988 case 400: PEERBADMSG("peer stopped accepting articles");
989 case 503: PEERBADMSG("peer timed us out");
990 default: PEERBADMSG("peer sent unexpected message");
992 case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
993 case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
995 case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
996 case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
998 case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
999 case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
1001 case 238: /* CHECK says send it */
1003 case 335: /* IHAVE says send it */
1005 count_checkedwanted++;
1006 LIST_ADDTAIL(conn->queue);
1008 connfail("peer gave %d response to article body: %s",code, sani);
1009 return OOP_CONTINUE;
1014 case 431: /* CHECK or TAKETHIS says try later */
1016 case 436: /* IHAVE says try later */
1018 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1020 sysfatal("write to defer file %s",path_ductdefer);
1021 article_done(conn, art, RC_deferred);
1026 check_check_work(conn);
1027 return OOP_CONTINUE;
1031 /*========== monitoring of input files ==========*/
1033 static void feedfile_eof(InputFile *ipf) {
1034 assert(ipf != main_input_file); /* promised by tailing_try_read */
1035 assert(ipf == old_input_file);
1037 if (sms==sm_SEPARATED1) SMS(SEPARATED2, 0, "eof on old feed file");
1038 else if (sms==sm_DROPPING1) SMS(DROPPING2, 0, "eof on dead feed file");
1041 inputfile_tailing_stop(ipf);
1042 if (main_input_file)
1043 inputfile_tailing_start(main_input_file);
1046 static InputFile *open_input_file(const char *path) {
1047 int fd= open(path, O_RDONLY);
1049 if (errno==ENOENT) return 0;
1050 sysfatal("unable to open input file %s", path);
1053 InputFile *ipf= xmalloc(sizeof(InputFile));
1054 memset(ipf,0,sizeof(*ipf));
1056 ipf->readable.on_readable= tailing_on_readable;
1057 ipf->readable.on_cancel= tailing_on_cancel;
1058 ipf->readable.try_read= tailing_try_read;
1066 static void close_input_file(InputFile *ipf) {
1067 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1068 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1069 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1070 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1072 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1077 /*---------- dealing with articles read in the input file ----------*/
1079 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1080 oop_rd_event ev, const char *errmsg,
1082 const char *data, size_t recsz,
1084 InputFile *ipf= ipf_v;
1086 char tokentextbuf[sizeof(TOKEN)*2+3];
1088 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1090 if (data[0] && data[0]!=' ') {
1091 char *space= strchr(data,' ');
1092 int tokenlen= space-data;
1093 int midlen= (int)recsz-tokenlen-1;
1094 if (midlen < 0) goto bad_data;
1096 if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1097 memcpy(tokentextbuf, data, tokenlen);
1098 tokentextbuf[tokenlen]= 0;
1099 if (!IsToken(tokentextbuf)) goto bad_data;
1101 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1102 art->offset= ipf->offset;
1103 art->blanklen= recsz;
1104 art->midlen= midlen;
1105 art->checked= art->sentbody= 0;
1106 art->ipf= ipf; ipf->inprogress++;
1107 art->token= TextToToken(tokentextbuf);
1108 strcpy(art->messageid, space+1);
1109 LIST_ADDTAIL(queue, art);
1111 ipf->offset += recsz + 1;
1113 if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
1114 notice("starting flush (%lu >= %lu)",
1115 (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1117 int r= link(feedfile, duct_path);
1118 if (r) sysdie("link feedfile %s to ductfile %s", feedfile, dut_path);
1121 r= unlink(feedfile);
1122 if (r) sysdie("unlink old feedfile link %s", feedfile);
1125 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1128 check_master_queue();
1132 /*========== tailing input file ==========*/
1134 static void filemon_start(InputFile *ipf) {
1135 assert(!ipf->filemon);
1137 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1138 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1139 filemon_method_startfile(ipf, ipf->filemon);
1142 static void filemon_stop(InputFile *ipf) {
1143 if (!ipf->filemon) return;
1144 filemon_method_stopfile(ipf, ipf->filemon);
1149 static void filemon_callback(InputFile *ipf) {
1150 ipf->readable_callback(ipf->readable_callback_user);
1153 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1155 InputFile *ipf= user;
1156 return ipf->readable_callback(ipf->readable_callback_user);
1159 static void on_cancel(struct oop_readable *rable) {
1160 InputFile *ipf= (void*)rable;
1162 if (ipf->filemon) filemon_stopfile(ipf);
1163 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1164 ipf->readable_callback= 0;
1167 static int tailing_on_readable(struct oop_readable *rable,
1168 oop_readable_call *cb, void *user) {
1169 InputFile *ipf= (void*)rable;
1171 tailing_on_cancel(rable);
1172 ipf->readable_callback= cb;
1173 ipf->readable_callback_user= user;
1174 filemon_startfile(ipf);
1176 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1180 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1182 InputFile *ipf= (void*)rable;
1184 ssize_t r= read(ipf->fd, buffer, length);
1186 if (errno==EINTR) continue;
1190 if (ipf==main_input_file) { errno=EAGAIN; return -1; }
1191 assert(sms==sm_SEPARATED1 || sms==sm_DROPPING1);
1197 /*---------- filemon implemented with inotify ----------*/
1199 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1200 #define HAVE_FILEMON
1202 #include <linux/inotify.h>
1204 static int filemon_inotify_fd;
1205 static int filemon_inotify_wdmax;
1206 static InputFile **filemon_inotify_wd2ipf;
1208 typedef struct Filemon_Perfile {
1210 } Filemon_Inotify_Perfile;
1212 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1213 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1214 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1216 if (wd >= filemon_inotify_wdmax) {
1218 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1219 sizeof(*filemon_inotify_wd2ipf) * newmax);
1220 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1221 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1222 filemon_inotify_wdmax= newmax;
1225 assert(!filemon_inotify_wd2ipf[wd]);
1226 filemon_inotify_wd2ipf[wd]= ipf;
1231 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1233 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1234 if (r) sysdie("inotify_rm_watch");
1235 filemon_inotify_wd2ipf[wd]= 0;
1238 static void *filemon_inotify_readable(oop_source *lp, int fd,
1239 oop_event e, void *u) {
1240 struct inotify_event iev;
1242 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1244 if (errno==EAGAIN) break;
1245 sysdie("read from inotify master");
1246 } else if (r==sizeof(iev)) {
1247 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1249 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1251 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1252 filemon_callback(ipf);
1254 return OOP_CONTINUE;
1257 static int filemon_method_init(void) {
1258 filemon_inotify_fd= inotify_init();
1259 if (filemon_inotify_fd<0) {
1260 syswarn("could not initialise inotify: inotify_init failed");
1264 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1269 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1271 /*---------- filemon dummy implementation ----------*/
1273 #if !defined(HAVE_FILEMON)
1275 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1277 static int filemon_method_init(void) { return 0; }
1278 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1279 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1281 #endif /* !HAVE_FILEMON */
1283 /*---------- interface to start and stop an input file ----------*/
1285 static const oop_rd_style feedfile_rdstyle= {
1286 OOP_RD_DELIM_STRIP, '\n',
1288 OOP_RD_SHORTREC_EOF,
1291 static void inputfile_tailing_start(InputFile *ipf) {
1293 ipf->readable->on_readable= tailing_on_readable;
1294 ipf->readable->on_cancel= tailing_on_cancel;
1295 ipf->readable->try_read= tailing_try_read;
1296 ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1297 ipf->readable->delete_kill= 0;
1299 ipf->readable_callback= 0;
1300 ipf->readable_callback_user= 0;
1302 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1305 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1306 feedfile_got_article,ipf, feedfile_problem,ipf);
1307 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1310 static void inputfile_tailing_stop(InputFile *ipf) {
1312 oop_rd_delete(ipf->rd);
1314 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1318 /*========== interaction with innd ==========*/
1320 /* See official state diagram at top of file. We implement
1330 |`--------------------------.
1331 | | install defer as backlog
1332 | OPEN F SUCCEEDS | exit
1337 | [Normal] =========
1341 | | F IS SO BIG WE SHOULD FLUSH
1345 | | our handle onto F is now onto D
1348 | |<---------------------------------------------------.
1350 | | spawn inndcomm flush |
1358 | | INNDCOMM FLUSH FAILS ^
1359 | |`----------------------->----------. |
1361 | | NO SUCH SITE V |
1362 ^ |`--------------->----. =========== |
1368 | | \ | TIME TO RETRY |
1369 | | \ `----------------'
1373 | ============= ============
1374 | SEPARATED1 DROPPING1
1375 | [Separated] [Dropping]
1376 | main F idle main none
1377 | old D tail old D tail
1378 | ============= ============
1380 ^ | EOF ON D | EOF ON D
1382 | ============= ============
1383 | SEPARATED2 DROPPING2
1384 | [Finishing] [Dropping]
1385 | main F tail main none
1386 | old D idle old D idle
1387 | ============= ============
1389 | | ALL D PROCESSED | ALL D PROCESSED
1390 | V install defer as backlog V install defer as backlog
1391 ^ | close D | close D
1392 | | unlink D | unlink D
1393 | | start new defer | exit
1395 `----------' ==========
1401 static void open_defer(void) {
1405 defer= fopen(path_ductdefer, "a+");
1406 if (!defer) sysfatal("could not open defer file %s", path_ductdefer);
1408 /* truncate away any half-written records */
1410 r= fstat(fileno(defer), &stab);
1411 if (r) sysdie("could not stat newly opened defer file %s", path_ductdefer);
1413 if (stab.st_size > LONG_MAX)
1414 die("defer file %s size is far too large", path_ductdefer);
1419 long orgsize= stab.st_size;
1420 long truncto= stab.st_size;
1422 if (!truncto) break; /* was only (if anything) one half-truncated record */
1423 if (fseek(defer, truncto-1, SEEK_SET) < 0)
1424 sysdie("seek in defer file %s while truncating partial", path_ductdefer);
1429 sysdie("failed read from defer file %s", path_ductdefer);
1431 die("defer file %s shrank while we were checking it!", path_ductdefer);
1437 if (stab.st_size != truncto) {
1438 warn("truncating half-record at end of defer file %s -"
1439 " shrinking by %ld bytes from %ld to %ld",
1440 path_ductdefer, orgsize - truncto, orgsize, truncto);
1443 sysfatal("could not flush defer file %s", path_ductdefer);
1444 if (ftruncate(fileno(defer), truncto))
1445 sysdie("could not truncate defer file %s", path_ductdefer);
1448 info("continuing existing defer file %s (%ld bytes)",
1449 path_ductdefer, orgsize);
1451 if (fseek(defer, truncto, SEEK_SET))
1452 sysdie("could not seek to new end of defer file %s", path_ductdefer);
1455 static void statemc_init(void) {
1458 path_ductlock= xasprintf("%s_duct.lock", feedfile);
1459 path_duct= xasprintf("%s_duct", feedfile);
1460 path_ductdefer= xasprintf("%s_duct.defer", feedfile);
1462 if (lstat(path_ductdefer, &stab)) {
1463 if (errno!=ENOENT) sysdie("could not check defer file %s", path_defer);
1465 if (!S_ISREG(stab.st_mode))
1466 die("defer file %s not a plain file (mode 0%lo)",
1467 path_defer, (unsigned long)stab.st_mode);
1468 switch (stab.st_nlink==1) {
1469 case 1: /* ok */ break;
1471 if (unlink(path_defer))
1472 sysdie("could not unlink stale defer file link %s (presumably"
1473 " hardlink to backlog file)", path_defer);
1476 die("defer file %s has unexpected link count %d",
1477 path_defer, stab.st_nlink);
1482 int lockfd= open(path_ductlock, O_CREAT|O_RDWR, 0600);
1483 if (lockfd<0) sysfatal("open lockfile %s", path_ductlock);
1486 memset(&fl,0,sizeof(fl));
1488 fl.l_whence= SEEK_SET;
1489 r= fcntl(lockfd, F_SETLK, &fl);
1491 if (errno==EACCES || errno==EAGAIN) {
1492 if (quiet_if_locked) exit(0);
1493 fatal("another duct holds the lockfile");
1495 sysdie("fcntl F_SETLK lockfile %s", path_ductlock);
1498 InputFile *file_d= open_input_file(path_duct);
1501 struct stat stab_f, stab_d;
1503 r= stat(feedfile, &stab_f);
1505 if (errno!=ENOENT) sysdie("check feed file %s", feedfile);
1506 /* D exists, F ENOENT => Moved */
1510 /* F and D both exist */
1512 r= fstat(file_d->fd, &stab_d);
1513 if (r) sysdie("check duct file %s", ductfile);
1515 if (stab_d.st_ino == stab_f.st_ino &&
1516 stab_d.st_dev == stab_f.st_dev) {
1517 /* F==D => Hardlinked*/
1518 r= unlink(path_duct);
1519 if (r) sysdie("unlink feed file %s during startup", feedfile);
1522 startup_set_input_file(file_d);
1523 spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1525 /* F!=D => Separated */
1526 SMS(SEPARATED1, 0, "found both old and current feed files");
1527 startup_set_input_file(file_d);
1529 } else { /*!file_d*/
1530 SMS(WAITING, open_wait_periods, "no feed file currently exists");
1534 static void statemc_poll(void) {
1535 if (sms==sm_WAITING) { statemc_waiting_poll(); return; }
1537 if (!sm_period_counter) return;
1538 sm_period_counter--;
1539 assert(sm_period_counter>=0);
1541 if (sm_period_counter) return;
1544 fatal("timed out waiting for innd to create feed file %s", feedfile);
1546 spawn_inndcomm_flush(void);
1553 static void statemc_waiting_poll(void) {
1554 InputFile *file_f= open_input_file(feedfile);
1555 if (!file_f) return;
1556 startup_set_input_file(file_d);
1557 SMS(NORMAL, 0, "found and opened feed file");
1560 static void startup_set_input_file(InputFile *f) {
1561 assert(!main_input_file);
1563 inputfile_tailing_start(f);
1566 static void *statemc_check_oldinput_done(oop_source *lp,
1567 struct timeval now, void *u) {
1570 int done= (sms==sm_SEPARATED2 || sms==sm_DROPPING2)
1571 && old_input_file->inprogress;
1574 r= fstat(fileno(defer), &stab);
1575 if (r) sysdie("check defer file %s", path_defer);
1577 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1580 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1581 (unsigned long)now.tv_sec,
1582 (unsigned long)stab.st_ino);
1583 if (link(path_defer, path_backlog))
1584 sysfatal("could not install defer file %s as backlog file %s",
1585 path_defer, backlog);
1586 if (unlink(path_defer))
1587 sysdie("could not unlink old defer link %s to backlog file %s",
1588 path_defer, backlog);
1590 if (unlink(path_duct))
1591 sysdie("could not unlink old duct file %s", path_duct);
1593 if (sms==sm_DROPPING2) {
1594 notice("feed dropped and our work is complete"
1595 " (but check for backlog files)");
1601 close_input_file(old_input_file);
1604 notice("flush complete");
1605 SMS(NORMAL, 0, "flush complete");
1608 static void statemc_setstate(StateMachineState newsms, int periods,
1609 const char *forlog, const char *why) {
1611 sm_period_counter= periods;
1613 info("%s[%d] %s",periods,forlog,why);
1615 info("%s %s",forlog,why);
1619 /*========== flushing the feed ==========*/
1621 static pid_t inndcomm_child;
1623 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1624 assert(inndcomm_child);
1625 int status= xwaitpid(&inndcomm_child, "inndcomm");
1626 loop->cancel_fd(fd);
1629 assert(!old_input_file);
1631 if (WIFEXITED(status)) {
1632 switch (WEXITSTATUS(status)) {
1634 case INNDCOMMCHILD_ESTATUS_FAIL:
1637 case INNDCOMMCHILD_ESTATUS_NONESUCH:
1638 warn("feed has been dropped by innd, finishing up");
1639 old_input_file= main_input_file;
1641 SMS(DROPPING1, 0, "dropped by innd");
1642 return OOP_CONTINUE;
1645 old_input_file= main_input_file;
1646 main_input_file= open_input_file(feedfile);
1647 if (!main_input_file)
1648 die("flush succeeded but feedfile %s does not exist!", feedfile);
1649 SMS(SEPARATED1, 0, "feed file missing");
1650 return OOP_CONTINUE;
1653 goto unexpected_exitstatus;
1656 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1657 warn("flush timed out trying to talk to innd");
1660 unexpected_exitstatus:
1661 report_child_status("inndcomm child", status);
1665 SMS(FLUSHFAIL, flushfail_retry_periods, "flush failed, will retry");
1668 static void inndcommfail(const char *what) {
1669 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1670 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1673 void spawn_inndcomm_flush(void) {
1676 assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1677 assert(!inndcomm_child);
1679 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1681 inndcomm_child= xfork();
1683 if (!inndcomm_child) {
1684 static char flushargv[2]= { sitename, 0 };
1689 alarm(inndcomm_flush_timeout);
1690 r= ICCopen(); if (r) inndcommfail("connect");
1691 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
1692 if (!r) exit(0); /* yay! */
1694 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1695 syswarn("innd ctlinnd flush failed: innd said %s", reply);
1696 exit(INNDCOMMCHILD_ESTATUS_FAIL);
1700 int sentinel_fd= pipefds[0];
1701 on_fd_read_except(sentinel_fd, inndcomm_event);
1703 SMS(FLUSHING, 0, "flush is in progress");
1706 /*========== main program ==========*/
1708 static void postfork_inputfile(InputFile *ipf) {
1710 assert(ipf->fd >= 0);
1715 static void postfork_conns(Connection *conn) {
1722 static void postfork_stdio(FILE *f) {
1723 /* we have no stdio streams that are buffered long-term */
1727 static void postfork(const char *what) {
1728 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1729 sysdie("%s child: failed to reset SIGPIPE");
1731 postfork_inputfile(main_input_file);
1732 postfork_inputfile(old_input_file);
1733 postfork_conns(idle.head);
1734 postfork_conns(working.head);
1735 postfork_conns(full.head);
1736 postfork_stdio(defer);
1740 #define EVERY(what, interval, body) \
1741 static const struct timeval what##_timeout = { 5, 0 }; \
1742 static void what##_schedule(void); \
1743 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1745 what##_schedule(); \
1747 static void what##_schedule(void) { \
1748 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
1751 EVERY(filepoll, {5,0}, { check_master_queue(); })
1753 EVERY(period, {PERIOD_SECONDS,0}, {
1754 if (connect_delay) connect_delay--;
1756 check_master_queue();
1760 /*========== option parsing ==========*/
1763 of_seconds= 001000u;
1764 of_boolean= 002000u;
1767 typedef struct Option Option;
1768 typedef void OptionParser(const Option*, const char *val);
1778 void op_integer(const Option *o, const char *val) {
1781 unsigned long ul= strtoul(val,&ep,10);
1782 if (*ep || ep==val || errno || ul>INT_MAX)
1783 badusage("bad integer value for %s",o->long);
1784 int *store= o->store;
1788 void op_double(const Option *o, const char *val) {
1789 int *store= o->store;
1792 *store= strtod(val, &ep);
1793 if (*ep || ep==val || errno)
1794 badusage("bad floating point value for %s",o->long);
1797 void op_string(const Option *o, const char *val) {
1798 char **store= o->store;
1803 void op_seconds(const Option *o, const char *val) {
1804 int *store= o->store;
1807 double v= strtod(val,&ep);
1808 if (ep==val) badusage("bad time/duration value for %s",o->long);
1810 if (!*ep || !strcmp(ep,"s")) unit= 1;
1811 else if (!strcmp(ep,"m")) unit= 60;
1812 else if (!strcmp(ep,"h")) unit= 3600;
1813 else if (!strcmp(ep,"d")) unit= 86400;
1814 else badusage("bad units %s for time/duration value for %s",ep,o->long);
1818 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
1822 void op_periods_rndup(const Option *o, const char *val) {
1823 int *store= o->store;
1825 *store += PERIOD_SECONDS-1;
1826 *store /= PERIOD_SECONDS;
1829 void op_periods_booltrue(const Option *o, const char *val) {
1830 int *store= o->store;
1833 void op_periods_boolfalse(const Option *o, const char *val) {
1834 int *store= o->store;
1838 static const Option options[]= {
1839 { 0, "max-connections", &max_connections op_integer },
1840 { 0, "streaming", &try_stream, op_booltrue, 1 },
1841 { 0, "no-streaming", &try_stream, op_boolfalse, 1 },
1842 {'h',"host", &remote_host, op_string },
1843 {'P',"port", &port op_integer },
1844 { 0, "inndconf", &inndconffile, op_string },
1845 {'f',"feedfile", &feedfile, op_string },
1846 {'q',"quiet-multiple", &quiet_if_locked, op_booltrue, 1 },
1847 { 0, "no-quiet-multiple", &quiet_if_locked, op_boolfalse, 1 },
1848 {'d',"daemon", &become_daemon, op_booltrue, 1 },
1849 { 0, "no-daemon", &become_daemon, op_boolfalse, 1 },
1851 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
1852 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
1854 { 0, "max-queue-size", &max_queue_per_conn op_integer },
1855 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
1856 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
1857 { 0, "feedfile-open-timeout", &open_wait_periods, op_periods_rndup },
1858 { 0, "connection-timeout", &connection_timeout, op_seconds },
1859 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
1862 int main(int argc, char **argv) {
1868 if (*arg != '-') break;
1869 if (!strcmp(arg,"--")) { arg= *++argv; break; }
1871 while ((a= *++arg)) {
1875 char *equals= strchr(arg,'=');
1876 int len= equals ? (equals - arg) : strlen(arg);
1877 for (o=options; o->long; o++)
1878 if (strlen(o->long) == len && !memcmp(o->long,arg,len))
1880 badusage("unknown long option --%s",arg);
1883 if (equals) badusage("option --%s does not take a value",o->long);
1885 } else if (equals) {
1889 if (!arg) badusage("option --%s needs a value",o->long);
1892 break; /* eaten the whole argument now */
1894 for (o=options; o->long; o++)
1897 badusage("unknown short option -%c",a);
1904 if (!arg) badusage("option -%c needs a value",o->short);
1907 break; /* eaten the whole argument now */
1912 if (!arg) badusage("need site name argument");
1913 if (*++argv) badusage("too many non-option arguments");
1916 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
1917 badusage("nocheck threshold percentage must be between 0..100");
1918 nocheck_thresh= nocheck_thresh_pct * 0.01;
1920 if (nocheck_decay_articles < 0.1)
1921 badusage("nocheck decay articles must be at least 0.1");
1922 nocheck_decay= 1 - 1/nocheck_decay_articles;
1924 innconf_read(inndconffile);
1927 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
1928 else if (!feedfile[0])
1929 badusage("feed filename must be nonempty");
1930 else if (feedfile[strlen(feedfile)-1]=='/')
1931 feedfile= xasprintf("%s%s",feedfile,sitename);
1933 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1934 sysdie("could not ignore SIGPIPE");
1936 if (become_daemon) {
1937 for (i=3; i<255; i++)
1938 /* do this now before we open syslog, etc. */
1940 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
1942 int null= open("/dev/null",O_RDWR);
1943 if (null<0) sysdie("failed to open /dev/null");
1949 pid_t child1= xfork("daemonise first fork");
1950 if (child1) _exit(0);
1952 pid_t sid= setsid();
1953 if (sid != child1) sysdie("setsid failed");
1955 pid_t child2= xfork("daemonise second fork");
1956 if (child2) _exit(0);
1961 if (!filemon_init()) {
1962 warn("no file monitoring available, polling");
1963 filepoll_schedule();