4 * - actually implement badusage
5 * - options for all options
7 * - pid, sitename, hostname in lockfile
12 * Newsfeeds file entries should look like this:
13 * host.name.of.site[/exclude,exclude,...]\
14 * :pattern,pattern...[/distribution,distribution...]\
18 * sitename[/exclude,exclude,...]\
19 * :pattern,pattern...[/distribution,distribution...]\
25 * or might be blanked out
26 * <spc><spc><spc><spc>....
28 * F site.name main feed file
29 * opened/created, then written, by innd
32 * tokens blanked out by duct when processed
33 * site.name_lock lock preventing multiple ducts
34 * to hold lock must open,F_SETLK[W]
35 * and then stat to check that locked file
36 * still has name site.name_lock
37 * holder of this lock is "duct"
38 * (only) lockholder may remove the lockfile
39 * D site.name_flushing temporary feed file during flush (or crash)
40 * hardlink created by duct
42 * site.name_defer 431'd articles, still being written,
43 * created, written, used by duct
45 * site.name_backlog.<date>.<inum>
46 * 431'd articles, ready for innxmit or duct
47 * created (link/mv) by duct
48 * site.name_backlog<anything-else> (where <anything-else> does not
49 * contain '#' or '~') eg
50 * site.name_backlog.manual
51 * anything the sysadmin likes (eg, feed files
52 * from old feeds to be merged into this one)
53 * created (link/mv) by admin
54 * may be symlinks (in which case links
55 * may be written through, but only links
58 * It is safe to remove backlog files manually,
59 * if it's desired to throw away the backlog.
61 * Backlog files are also processed by innduct. We find the oldest
62 * backlog file which is at least a certain amount old, and feed it
63 * back into our processing. When every article in it has been read
64 * and processed, we unlink it and look for another backlog file.
66 * If we don't have a backlog file that we're reading, we close the
67 * defer file that we're writing and make it into a backlog file at
68 * the first convenient opportunity.
79 | | <----------------<---------------------------------'|
85 | F: innd writing, duct reading |
88 | | duct decides time to flush |
89 | | duct makes hardlink |
91 | V <------------------------'|
93 | F == D: innd writing, duct reading both exist |
96 | | <-----------<-------------<--'|
100 | V <---------------------. |
103 | D: innd writing, duct reading; or ENOENT | |
105 | | duct requests flush of feed | |
106 | | (others can too, harmlessly) | |
110 | D: innd flushing, duct; or ENOENT | |
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; or ENOENT 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.
151 * rune for printing diagrams:
153 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
158 /*============================== PROGRAM ==============================*/
160 #define _GNU_SOURCE 1
166 #include "inndcomm.h"
168 #include "inn/list.h"
169 #include "inn/innconf.h"
172 #include <sys/types.h>
173 #include <sys/wait.h>
174 #include <sys/stat.h>
175 #include <sys/socket.h>
191 #include <oop-read.h>
193 /*----- general definitions, probably best not changed -----*/
195 #define CONNCHILD_ESTATUS_STREAM 4
196 #define CONNCHILD_ESTATUS_NOSTREAM 5
198 #define INNDCOMMCHILD_ESTATUS_FAIL 6
199 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
201 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
203 #define VA va_list al; va_start(al,fmt)
204 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
205 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
207 /*----- doubly linked lists -----*/
209 #define ISNODE(T) struct { T *succ, *pred; } node /* must be at start */
210 #define DEFLIST(T) typedef struct { T *hd, *tl, *tp; int count; } T##List
212 #define NODE(n) (assert((void*)&(n)->node == &(n)), \
213 (struct node*)&(n)->node)
215 #define LIST_CHECKCANHAVENODE(l,n) \
216 ((void)((n) == ((l).hd))) /* just for the type check */
218 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
219 ( LIST_CHECKCANHAVENODE(l,n), \
220 list_addsomehow((struct list*)&(l), NODE((n))), \
224 #define LIST_REMSOMEHOW(l,list_remsomehow) \
228 list_remsomehow((struct list*)&(l)) ) \
234 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
235 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
236 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
237 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
239 #define LIST_INIT(l) ((l).hd, list_new((struct list*)&(l)))
240 #define LIST_HEAD(l) ((typeof((l).hd))(list_head((struct list*)&(l))))
241 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
242 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
244 #define LIST_REMOVE(l,n) \
245 ( LIST_CHECKCANHAVENODE(l,n), \
246 list_remove(NODE((n))), \
250 #define LIST_INSERT(l,n,pred) \
251 ( LIST_CHECKCANHAVENODE(l,n), \
252 LIST_CHECKCANHAVENODE(l,pred), \
253 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
257 /*----- type predeclarations -----*/
259 typedef struct Conn Conn;
260 typedef struct Article Article;
261 typedef struct InputFile InputFile;
262 typedef struct XmitDetails XmitDetails;
263 typedef struct Filemon_Perfile Filemon_Perfile;
264 typedef enum StateMachineState StateMachineState;
269 /*----- function predeclarations -----*/
271 static void conn_maybe_write(Conn *conn);
272 static void conn_make_some_xmits(Conn *conn);
273 static void *conn_write_some_xmits(Conn *conn);
275 static void xmit_free(XmitDetails *d);
277 #define SMS(newstate, periods, why) \
278 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
279 static void statemc_setstate(StateMachineState newsms, int periods,
280 const char *forlog, const char *why);
282 static void statemc_start_flush(const char *why); /* Normal => Flushing */
283 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
285 static void check_assign_articles(void);
286 static void queue_check_input_done(void);
288 static void statemc_check_flushing_done(void);
289 static void statemc_check_backlog_done(void);
291 static void postfork(const char *what);
292 static void postfork_inputfile(InputFile *ipf);
294 static void open_defer(void);
295 static void close_defer(void);
296 static void search_backlog_file(void);
298 static void inputfile_tailing_start(InputFile *ipf);
299 static void inputfile_tailing_stop(InputFile *ipf);
301 static void filemon_start(InputFile *ipf);
302 static void filemon_stop(InputFile *ipf);
303 static void filemon_callback(InputFile *ipf);
305 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
306 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
308 /*----- configuration options -----*/
310 static const char *sitename, *feedfile, *pathoutgoing;
311 static const char *remote_host;
312 static int quiet_multiple=0, become_daemon=1;
314 static int max_connections=10, max_queue_per_conn=200;
315 static int target_max_feedfile_size=100000;
317 static int period_seconds=60;
319 static double max_bad_data_ratio= 0.01;
320 static int max_bad_data_initial= 30;
321 /* in one corrupt 4096-byte block the number of newlines has
322 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
324 static int connection_setup_timeout=200, port=119, try_stream=1;
325 static int inndcomm_flush_timeout=100;
326 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
327 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
328 static int spontaneous_flush_periods, need_activity_periods;
329 static const char *inndconffile;
331 static double nocheck_thresh_pct= 95.0;
332 static double nocheck_thresh; /* computed in main from _pct */
333 static double nocheck_decay_articles= 100; /* converted to _decay */
334 static double nocheck_decay; /* computed in main from _articles */
337 /*----- statistics -----*/
339 typedef enum { /* in queue in conn->sent */
340 art_Unchecked, /* not checked, not sent checking */
341 art_Wanted, /* checked, wanted sent body as requested */
342 art_Unsolicited, /* - sent body without check */
346 #define RESULT_COUNTS(RCS,RCN) \
354 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
355 #define RCI_TRIPLE_VALS_BASE(counts,x) \
356 counts[art_Unchecked] x \
357 + counts[art_Wanted] x \
358 + counts[art_Unsolicited] x, \
359 counts[art_Unchecked] x \
360 , counts[art_Wanted] x \
361 , counts[art_Unsolicited] x
364 #define RC_INDEX(x) RC_##x,
365 RESULT_COUNTS(RC_INDEX, RC_INDEX)
370 /*----- transmission buffers -----*/
375 xk_Malloc, xk_Const, xk_Artdata
387 /*----- core operational data structure types -----*/
390 /* This is also an instance of struct oop_readable */
391 struct oop_readable readable; /* first */
392 oop_readable_call *readable_callback;
393 void *readable_callback_user;
395 int fd; /* may be 0, meaning closed */
396 Filemon_Perfile *filemon;
399 long inprogress; /* no. of articles read but not processed */
403 int counts[art_MaxState][RCI_max];
404 int readcount_ok, readcount_blank, readcount_err;
419 #define SMS_LIST(X) \
427 enum StateMachineState {
428 #define SMS_DEF_ENUM(s) sm_##s,
429 SMS_LIST(SMS_DEF_ENUM)
432 static const char *sms_names[]= {
433 #define SMS_DEF_NAME(s) #s ,
434 SMS_LIST(SMS_DEF_NAME)
440 int fd; /* may be 0, meaning closed (during construction/destruction) */
441 int max_queue, stream, quitting;
442 int since_activity; /* periods */
443 ArticleList waiting; /* not yet told peer */
444 ArticleList priority; /* peer says send it now */
445 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
446 struct iovec xmit[CONNIOVS];
447 XmitDetails xmitd[CONNIOVS];
452 /*----- general operational variables -----*/
454 /* main initialises */
455 static oop_source *loop;
456 static ConnList conns;
457 static ArticleList queue;
458 static char *path_lock, *path_flushing, *path_defer, *globpat_backlog;
460 /* statemc_init initialises */
461 static StateMachineState sms;
463 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
464 static int sm_period_counter;
466 /* initialisation to 0 is good */
467 static int until_connect, until_backlog_nextscan;
468 static double accept_proportion;
469 static int nocheck, nocheck_reported;
471 /*========== logging ==========*/
473 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
474 static void logcore(int sysloglevel, const char *fmt, ...) {
477 vsyslog(sysloglevel,fmt,al);
479 vfprintf(stderr,fmt,al);
485 static void logv(int sysloglevel, const char *pfx, int errnoval,
486 const char *fmt, va_list al) PRINTF(5,0);
487 static void logv(int sysloglevel, const char *pfx, int errnoval,
488 const char *fmt, va_list al) {
489 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
490 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
491 msgbuf[sizeof(msgbuf)-1]= 0;
493 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
494 sysloglevel= LOG_ERR; /* run by wrong user, probably */
496 logcore(sysloglevel, "<%s>%s: %s%s%s",
497 sitename, pfx, msgbuf,
498 errnoval>=0 ? ": " : "",
499 errnoval>=0 ? strerror(errnoval) : "");
502 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
503 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
504 static void fn(const char *fmt, ...) { \
506 logv(sysloglevel, pfx, err, fmt, al); \
510 #define logwrap(fn, pfx, sysloglevel, err) \
511 static void fn(const char *fmt, ...) PRINTF(1,2); \
512 static void fn(const char *fmt, ...) { \
514 logv(sysloglevel, pfx, err, fmt, al); \
518 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
519 diewrap(die, " critical", LOG_CRIT, -1, 16);
521 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
522 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
524 logwrap(syswarn, " warning", LOG_WARNING, errno);
525 logwrap(warn, " warning", LOG_WARNING, -1);
527 logwrap(notice, "", LOG_NOTICE, -1);
528 logwrap(info, " info", LOG_INFO, -1);
529 logwrap(debug, " debug", LOG_DEBUG, -1);
532 /*========== utility functions etc. ==========*/
534 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
535 static char *xvasprintf(const char *fmt, va_list al) {
537 int rc= vasprintf(&str,fmt,al);
538 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
541 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
542 static char *xasprintf(const char *fmt, ...) {
544 char *str= xvasprintf(fmt,al);
549 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
551 static pid_t xfork(const char *what) {
555 if (child==-1) sysdie("cannot fork for %s",what);
556 if (!child) postfork(what);
557 debug("forked %s %ld", what, (unsigned long)child);
561 static void on_fd_read_except(int fd, oop_call_fd callback) {
562 loop->on_fd(loop, fd, OOP_READ, callback, 0);
563 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
565 static void cancel_fd_read_except(int fd) {
566 loop->cancel_fd(loop, fd, OOP_READ);
567 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
570 static void report_child_status(const char *what, int status) {
571 if (WIFEXITED(status)) {
572 int es= WEXITSTATUS(status);
574 warn("%s: child died with error exit status %d",es);
575 } else if (WIFSIGNALED(status)) {
576 int sig= WTERMSIG(status);
577 const char *sigstr= strsignal(sig);
578 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
580 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
582 warn("%s: child died due to unknown fatal signal %d%s",
583 what, sig, coredump);
585 warn("%s: child died with unknown wait status %d", status);
589 static int xwaitpid(pid_t *pid, const char *what) {
592 int r= kill(*pid, SIGKILL);
593 if (r) sysdie("cannot kill %s child", what);
595 pid_t got= waitpid(*pid, &status, WNOHANG);
596 if (got==-1) sysdie("cannot reap %s child", what);
603 static void xunlink(const char *path, const char *what) {
605 if (r) sysdie("can't unlink %s %s", path, what);
608 static time_t xtime(void) {
610 if (now==-1) sysdie("time(2) failed");
613 static void check_isreg(const struct stat *stab, const char *path,
615 if (!S_ISREG(stab->st_mode))
616 die("%s %s not a plain file (mode 0%lo)",
617 what, path, (unsigned long)stab->st_mode);
620 static void xfstat(int fd, struct stat *stab_r, const char *what) {
621 int r= fstat(fd, stab_r);
622 if (r) sysdie("could not fstat %s", what);
625 static void xfstat_isreg(int fd, struct stat *stab_r,
626 const char *path, const char *what) {
627 xfstat(fd, stab_r, what);
628 check_isreg(stab_r, path, what);
631 static void xlstat_isreg(const char *path, struct stat *stab,
632 int *enoent_r /* 0 means ENOENT is fatal */,
634 int r= lstat(path, stab);
636 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
637 sysdie("could not lstat %s %s", what, path);
639 if (enoent_r) *enoent_r= 0;
640 check_isreg(stab, path, what);
643 static void setnonblock(int fd, int nonblocking) {
644 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
645 if (nonblocking) r |= O_NONBLOCK;
646 else r &= ~O_NONBLOCK;
647 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
650 static int samefile(const struct stat *a, const struct stat *b) {
651 assert(S_ISREG(a->st_mode));
652 assert(S_ISREG(b->st_mode));
653 return (a->st_ino == b->st_ino &&
654 a->st_dev == b->st_dev);
657 static char *sanitise(const char *input) {
658 static char sanibuf[100]; /* returns pointer to this buffer! */
660 const char *p= input;
664 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
666 if (!c) { *q++= '\''; *q=0; break; }
667 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
668 sprintf(q,"\\x%02x",c);
674 static int isewouldblock(int errnoval) {
675 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
678 /*========== management of connections ==========*/
680 static void conn_dispose(Conn *conn) {
683 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
684 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
686 perhaps_close(&conn->fd);
688 until_connect= reconnect_delay_periods;
691 static void *conn_exception(oop_source *lp, int fd,
692 oop_event ev, void *conn_v) {
695 assert(fd == conn->fd);
696 assert(ev == OOP_EXCEPTION);
697 int r= read(conn->fd, &ch, 1);
698 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
699 else connfail(conn,"exceptional condition on socket (peer sent urgent"
700 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
704 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
705 int requeue[art_MaxState];
708 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
709 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
710 while ((art= LIST_REMHEAD(conn->sent))) {
711 requeue[art->state]++;
712 if (art->state==art_Unsolicited) art->state= art_Unchecked;
713 LIST_ADDTAIL(queue,art);
718 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
721 char *m= xvasprintf(fmt,al);
722 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
723 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
726 LIST_REMOVE(conns,conn);
728 check_assign_articles();
731 static void connfail(Conn *conn, const char *fmt, ...) {
734 vconnfail(conn,fmt,al);
738 static void check_idle_conns(void) {
740 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
741 conn->since_activity++;
743 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
744 if (conn->since_activity <= need_activity_periods) continue;
746 /* We need to shut this down */
748 connfail(conn,"timed out waiting for response to QUIT");
749 else if (conn->sent.count)
750 connfail(conn,"timed out waiting for responses");
751 else if (conn->waiting.count || conn->priority.count)
752 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
753 else if (conn->xmitu)
754 connfail(conn,"peer has been sending responses"
755 " before receiving our commands!");
757 static const char quitcmd[]= "QUIT\r\n";
758 int todo= sizeof(quitcmd)-1;
759 const char *p= quitcmd;
761 int r= write(conn->fd, p, todo);
763 if (isewouldblock(errno))
764 connfail(conn, "blocked writing QUIT to idle connection");
766 connfail(conn, "failed to write QUIT to idle connection: %s",
774 conn->since_activity= 0;
775 debug("C%d is idle, quitting", conn->fd);
784 /*---------- making new connections ----------*/
786 static int connecting_sockets[2]= {-1,-1};
787 static pid_t connecting_child;
789 static void connect_attempt_discard(void) {
790 if (connecting_sockets[0])
791 cancel_fd_read_except(connecting_sockets[0]);
793 perhaps_close(&connecting_sockets[0]);
794 perhaps_close(&connecting_sockets[1]);
796 if (connecting_child) {
797 int r= kill(connecting_child, SIGTERM);
798 if (r) syswarn("failed to kill connecting child");
799 int status= xwaitpid(&connecting_child, "connect");
801 if (!(WIFEXITED(status) ||
802 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
803 report_child_status("connect", status);
807 #define PREP_DECL_MSG_CMSG(msg) \
809 memset(&msg,0,sizeof(msg)); \
810 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
811 msg.msg_control= msg##cbuf; \
812 msg.msg_controllen= sizeof(msg##cbuf);
814 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
817 conn= xmalloc(sizeof(*conn));
818 memset(conn,0,sizeof(*conn));
820 PREP_DECL_MSG_CMSG(msg);
821 struct cmsghdr *h= 0;
822 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
823 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
826 pid_t got= waitpid(connecting_child, &status, WNOHANG);
828 assert(got==connecting_child);
830 if (WIFEXITED(status)) {
831 if (WEXITSTATUS(status) != 0 &&
832 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
833 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
834 /* child already reported the problem */;
836 warn("connect: connection child exited code %d but no cmsg",
837 WEXITSTATUS(status));
838 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
839 warn("connect: connection attempt timed out");
841 report_child_status("connect", status);
844 /* child is still running apparently, report the socket problem */
846 syswarn("connect: read from child socket failed");
847 else if (e == OOP_EXCEPTION)
848 warn("connect: unexpected exception on child socket");
850 warn("connect: unexpected EOF on child socket");
852 fatal("connect: unexpected lack of cmsg from child");
857 #define CHK(field, val) \
858 if (h->cmsg_##field != val) { \
859 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
862 CHK(level, SOL_SOCKET);
863 CHK(type, SCM_RIGHTS);
864 CHK(len, CMSG_LEN(sizeof(conn->fd)));
867 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
869 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
870 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
873 pid_t got= waitpid(connecting_child, &status, 0);
874 if (got==-1) sysdie("connect: real wait for child");
875 assert(got == connecting_child);
878 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
879 int es= WEXITSTATUS(status);
881 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
882 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
884 fatal("connect: child gave unexpected exit status %d", es);
888 LIST_INIT(conn->waiting);
889 LIST_INIT(conn->priority);
890 LIST_INIT(conn->sent);
891 setnonblock(conn->fd, 1);
892 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
893 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
894 LIST_ADDHEAD(conns, conn);
896 connect_attempt_discard();
897 check_assign_articles();
902 connect_attempt_discard();
905 static int allow_connect_start(void) {
906 return conns.count < max_connections
911 static void connect_start(void) {
912 assert(!connecting_sockets[0]);
913 assert(!connecting_sockets[1]);
914 assert(!connecting_child);
916 notice("starting connection attempt");
918 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
919 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
921 connecting_child= xfork("connection");
923 if (!connecting_child) {
924 FILE *cn_from, *cn_to;
925 char buf[NNTP_STRLEN+100];
926 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
928 r= close(connecting_sockets[0]);
929 if (r) sysdie("connect: close parent socket in child");
931 alarm(connection_setup_timeout);
932 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
933 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
934 else sysfatal("connect: connection attempt failed");
936 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
937 sysfatal("connect: authentication failed");
939 if (fputs("MODE STREAM\r\n", cn_to) ||
941 sysfatal("connect: could not send MODE STREAM");
942 buf[sizeof(buf)-1]= 0;
943 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
945 sysfatal("connect: could not read response to MODE STREAM");
947 fatal("connect: connection close in response to MODE STREAM");
952 fatal("connect: response to MODE STREAM is too long: %.100s...",
953 remote_host, sanitise(buf));
954 l--; if (l>0 && buf[l-1]=='\r') l--;
957 int rcode= strtoul(buf,&ep,10);
959 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
963 exitstatus= CONNCHILD_ESTATUS_STREAM;
969 warn("connect: unexpected response to MODE STREAM: %.50s",
975 int fd= fileno(cn_from);
977 PREP_DECL_MSG_CMSG(msg);
978 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
979 cmsg->cmsg_level= SOL_SOCKET;
980 cmsg->cmsg_type= SCM_RIGHTS;
981 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
982 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
984 msg.msg_controllen= cmsg->cmsg_len;
985 r= sendmsg(connecting_sockets[1], &msg, 0);
986 if (r) sysdie("sendmsg failed for new connection");
991 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
992 if (r) sysdie("connect: close child socket in parent");
994 on_fd_read_except(connecting_sockets[0], connchild_event);
998 connect_attempt_discard();
1001 /*---------- assigning articles to conns, and transmitting ----------*/
1003 static void check_assign_articles(void) {
1011 /* Find a connection to offer this article. We prefer a busy
1012 * connection to an idle one, provided it's not full. We take the
1013 * first (oldest) and since that's stable, it will mean we fill up
1014 * connections in order. That way if we have too many
1015 * connections, the spare ones will go away eventually.
1017 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1018 if (walk->quitting) continue;
1019 inqueue= walk->sent.count + walk->priority.count
1020 + walk->waiting.count;
1021 spare= walk->max_queue - inqueue;
1022 assert(inqueue <= max_queue_per_conn);
1024 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1025 else if (spare>0) /*working*/ { use= walk; break; }
1028 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1030 Article *art= LIST_REMHEAD(queue);
1031 LIST_ADDTAIL(use->waiting, art);
1034 conn_maybe_write(use);
1035 } else if (allow_connect_start()) {
1036 until_connect= reconnect_delay_periods;
1045 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1046 conn_maybe_write(u);
1047 return OOP_CONTINUE;
1050 static void conn_maybe_write(Conn *conn) {
1053 conn_make_some_xmits(conn);
1055 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1059 void *rp= conn_write_some_xmits(conn);
1060 if (rp==OOP_CONTINUE) {
1061 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1063 } else if (rp==OOP_HALT) {
1066 /* transmitted everything */
1073 /*========== article transmission ==========*/
1075 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1076 XmitKind kind) { /* caller must then fill in details */
1077 struct iovec *v= &conn->xmit[conn->xmitu];
1078 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1079 v->iov_base= (char*)data;
1085 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1086 xmit_core(conn,data,len, xk_Const);
1088 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1090 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1091 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1095 static void xmit_free(XmitDetails *d) {
1097 case xk_Malloc: free(d->info.malloc_tofree); break;
1098 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1099 case xk_Const: break;
1104 static void *conn_write_some_xmits(Conn *conn) {
1106 * 0: nothing more to write, no need to call us again
1107 * OOP_CONTINUE: more to write but fd not writeable
1108 * OOP_HALT: disaster, have destroyed conn
1111 int count= conn->xmitu;
1112 if (!count) return 0;
1114 if (count > IOV_MAX) count= IOV_MAX;
1115 ssize_t rs= writev(conn->fd, conn->xmit, count);
1117 if (isewouldblock(errno)) return OOP_CONTINUE;
1118 connfail(conn, "write failed: %s", strerror(errno));
1124 for (done=0; rs && done<conn->xmitu; done++) {
1125 struct iovec *vp= &conn->xmit[done];
1126 XmitDetails *dp= &conn->xmitd[done];
1127 if (rs > vp->iov_len) {
1135 int newu= conn->xmitu - done;
1136 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1137 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1142 static void conn_make_some_xmits(Conn *conn) {
1144 if (conn->xmitu+5 > CONNIOVS)
1147 Article *art= LIST_REMHEAD(conn->priority);
1148 if (!art) art= LIST_REMHEAD(conn->waiting);
1151 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1152 /* actually send it */
1154 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1158 XMIT_LITERAL("TAKETHIS ");
1159 xmit_noalloc(conn, art->messageid, art->midlen);
1160 XMIT_LITERAL("\r\n");
1161 xmit_artbody(conn, artdata);
1164 /* we got 235 from IHAVE */
1166 xmit_artbody(conn, artdata);
1168 XMIT_LITERAL(".\r\n");
1173 art->state == art_Unchecked ? art_Unsolicited :
1174 art->state == art_Wanted ? art_Wanted :
1176 art->ipf->counts[art->state][RC_sent]++;
1177 LIST_ADDTAIL(conn->sent, art);
1183 XMIT_LITERAL("IHAVE ");
1185 XMIT_LITERAL("CHECK ");
1186 xmit_noalloc(conn, art->messageid, art->midlen);
1187 XMIT_LITERAL("\r\n");
1189 assert(art->state == art_Unchecked);
1190 art->ipf->counts[art->state][RC_sent]++;
1191 LIST_ADDTAIL(conn->sent, art);
1197 /*========== handling responses from peer ==========*/
1199 static const oop_rd_style peer_rd_style= {
1200 OOP_RD_DELIM_STRIP, '\n',
1202 OOP_RD_SHORTREC_FORBID
1205 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1206 const char *errmsg, int errnoval,
1207 const char *data, size_t recsz, void *conn_v) {
1209 connfail(conn, "error receiving from peer: %s", errmsg);
1210 return OOP_CONTINUE;
1213 static Article *article_reply_check(Conn *conn, const char *response,
1214 int code_indicates_streaming,
1216 /* 1:yes, -1:no, 0:dontcare */,
1217 const char *sanitised_response) {
1218 Article *art= LIST_HEAD(conn->sent);
1222 "peer gave unexpected response when no commands outstanding: %s",
1223 sanitised_response);
1227 if (code_indicates_streaming) {
1228 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1229 if (!conn->stream) {
1230 connfail(conn, "peer gave streaming response code "
1231 " to IHAVE or subsequent body: %s", sanitised_response);
1234 const char *got_mid= response+4;
1235 int got_midlen= strcspn(got_mid, " \n\r");
1236 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1237 connfail(conn, "peer gave streaming response with syntactically invalid"
1238 " messageid: %s", sanitised_response);
1241 if (got_midlen != art->midlen ||
1242 memcmp(got_mid, art->messageid, got_midlen)) {
1243 connfail(conn, "peer gave streaming response code to wrong article -"
1244 " probable synchronisation problem; we offered: %s;"
1246 art->messageid, sanitised_response);
1251 connfail(conn, "peer gave non-streaming response code to"
1252 " CHECK/TAKETHIS: %s", sanitised_response);
1257 if (must_have_sent>0 && art->state < art_Wanted) {
1258 connfail(conn, "peer says article accepted but"
1259 " we had not sent the body: %s", sanitised_response);
1262 if (must_have_sent<0 && art->state >= art_Wanted) {
1263 connfail(conn, "peer says please sent the article but we just did: %s",
1264 sanitised_response);
1268 Article *art_again= LIST_REMHEAD(conn->sent);
1269 assert(art_again == art);
1273 static void update_nocheck(int accepted) {
1274 accept_proportion *= nocheck_decay;
1275 accept_proportion += accepted * (1.0 - nocheck_decay);
1276 int new_nocheck= accept_proportion >= nocheck_thresh;
1277 if (new_nocheck && !nocheck_reported) {
1278 notice("entering nocheck mode for the first time");
1279 nocheck_reported= 1;
1280 } else if (new_nocheck != nocheck) {
1281 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1283 nocheck= new_nocheck;
1286 static void article_done(Conn *conn, Article *art, int whichcount) {
1287 art->ipf->counts[art->state][whichcount]++;
1288 if (whichcount == RC_accepted) update_nocheck(1);
1289 else if (whichcount == RC_unwanted) update_nocheck(0);
1291 InputFile *ipf= art->ipf;
1294 while (art->blanklen) {
1295 static const char spaces[]=
1300 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1301 int r= pwrite(ipf->fd, spaces, w, art->offset);
1303 if (errno==EINTR) continue;
1304 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1305 art->messageid, art->blanklen, art->offset, ipf->path);
1307 assert(r>=0 && r<=w);
1313 assert(ipf->inprogress >= 0);
1316 if (!ipf->inprogress && ipf != main_input_file)
1317 queue_check_input_done();
1320 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1321 const char *errmsg, int errnoval,
1322 const char *data, size_t recsz, void *conn_v) {
1325 if (ev == OOP_RD_EOF) {
1326 connfail(conn, "unexpected EOF from peer");
1327 return OOP_CONTINUE;
1329 assert(ev == OOP_RD_OK);
1331 char *sani= sanitise(data);
1334 unsigned long code= strtoul(data, &ep, 10);
1335 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1336 connfail(conn, "badly formatted response from peer: %s", sani);
1337 return OOP_CONTINUE;
1340 if (conn->quitting) {
1341 if (code!=205 && code!=503) {
1342 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1344 notice("C%d idle connection closed", conn->fd);
1345 assert(!conn->waiting.count);
1346 assert(!conn->priority.count);
1347 assert(!conn->sent.count);
1348 assert(!conn->xmitu);
1349 LIST_REMOVE(conns,conn);
1352 return OOP_CONTINUE;
1355 conn->since_activity= 0;
1358 #define GET_ARTICLE(musthavesent) \
1359 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1360 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1362 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1363 code_streaming= (streaming); \
1364 GET_ARTICLE(musthavesent); \
1365 article_done(conn, art, RC_##how); break;
1367 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1369 int code_streaming= 0;
1373 case 400: PEERBADMSG("peer stopped accepting articles");
1374 case 503: PEERBADMSG("peer timed us out");
1375 default: PEERBADMSG("peer sent unexpected message");
1377 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1378 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1380 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1381 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1383 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1384 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1386 case 238: /* CHECK says send it */
1388 case 335: /* IHAVE says send it */
1390 assert(art->state == art_Unchecked);
1391 art->ipf->counts[art->state][RC_accepted]++;
1392 art->state= art_Wanted;
1393 LIST_ADDTAIL(conn->priority, art);
1396 case 431: /* CHECK or TAKETHIS says try later */
1398 case 436: /* IHAVE says try later */
1401 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1403 sysfatal("write to defer file %s",path_defer);
1404 article_done(conn, art, RC_deferred);
1409 conn_maybe_write(conn);
1410 check_assign_articles();
1411 return OOP_CONTINUE;
1415 /*========== monitoring of input files ==========*/
1417 static void feedfile_eof(InputFile *ipf) {
1418 assert(ipf != main_input_file); /* promised by tailing_try_read */
1420 inputfile_tailing_stop(ipf);
1421 assert(ipf->fd > 0);
1422 fixme do not close fd do something else because art_done needs it to blank entries;
1423 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1426 if (ipf == flushing_input_file) {
1427 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1428 if (main_input_file) inputfile_tailing_start(main_input_file);
1429 statemc_check_flushing_done();
1430 } else if (ipf == backlog_input_file) {
1431 statemc_check_backlog_done();
1433 abort(); /* supposed to wait rather than get EOF on main input file */
1437 static InputFile *open_input_file(const char *path) {
1438 int fd= open(path, O_RDONLY);
1440 if (errno==ENOENT) return 0;
1441 sysfatal("unable to open input file %s", path);
1445 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1446 memset(ipf,0,sizeof(*ipf));
1449 strcpy(ipf->path, path);
1454 static void close_input_file(InputFile *ipf) { /* does not free */
1455 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1456 assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1457 assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1458 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1461 if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1467 /*---------- dealing with articles read in the input file ----------*/
1469 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1470 const char *data, const char *how) {
1471 warn("corrupted file: %s, offset %lu: %s: %s",
1472 ipf->path, (unsigned long)offset, how, sanitise(data));
1473 ipf->readcount_err++;
1474 if (ipf->readcount_err > max_bad_data_initial +
1475 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1476 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1477 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1478 return OOP_CONTINUE;
1481 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1482 oop_rd_event ev, const char *errmsg,
1483 int errnoval, const char *data, size_t recsz,
1485 InputFile *ipf= ipf_v;
1486 assert(ev == OOP_RD_SYSTEM);
1488 sysdie("error reading input file: %s, offset %lu",
1489 ipf->path, (unsigned long)ipf->offset);
1492 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1493 oop_rd_event ev, const char *errmsg,
1494 int errnoval, const char *data, size_t recsz,
1496 InputFile *ipf= ipf_v;
1498 char tokentextbuf[sizeof(TOKEN)*2+3];
1500 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1502 off_t old_offset= ipf->offset;
1503 ipf->offset += recsz + 1;
1505 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1507 if (ev==OOP_RD_PARTREC)
1508 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1509 /* but process it anyway */
1511 if (ipf->skippinglong) {
1512 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1515 if (ev==OOP_RD_LONG) {
1516 ipf->skippinglong= 1;
1517 X_BAD_DATA("overly long line");
1520 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1521 if (!recsz) X_BAD_DATA("empty line");
1524 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1525 ipf->readcount_blank++;
1526 return OOP_CONTINUE;
1529 char *space= strchr(data,' ');
1530 int tokenlen= space-data;
1531 int midlen= (int)recsz-tokenlen-1;
1532 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1533 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1535 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1536 memcpy(tokentextbuf, data, tokenlen);
1537 tokentextbuf[tokenlen]= 0;
1538 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1540 ipf->readcount_ok++;
1542 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1543 art->state= art_Unchecked;
1544 art->midlen= midlen;
1545 art->ipf= ipf; ipf->inprogress++;
1546 art->token= TextToToken(tokentextbuf);
1547 art->offset= ipf->offset;
1548 art->blanklen= recsz;
1549 strcpy(art->messageid, space+1);
1550 LIST_ADDTAIL(queue, art);
1552 if (sms==sm_NORMAL && ipf==main_input_file &&
1553 ipf->offset >= target_max_feedfile_size)
1554 statemc_start_flush("feed file size");
1556 check_assign_articles();
1557 return OOP_CONTINUE;
1560 /*========== tailing input file ==========*/
1562 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1564 InputFile *ipf= user;
1565 return ipf->readable_callback(loop, &ipf->readable,
1566 ipf->readable_callback_user);
1569 static void tailing_on_cancel(struct oop_readable *rable) {
1570 InputFile *ipf= (void*)rable;
1572 if (ipf->filemon) filemon_stop(ipf);
1573 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1574 ipf->readable_callback= 0;
1577 static void tailing_queue_readable(InputFile *ipf) {
1578 /* lifetime of ipf here is OK because destruction will cause
1579 * on_cancel which will cancel this callback */
1580 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1583 static int tailing_on_readable(struct oop_readable *rable,
1584 oop_readable_call *cb, void *user) {
1585 InputFile *ipf= (void*)rable;
1587 tailing_on_cancel(rable);
1588 ipf->readable_callback= cb;
1589 ipf->readable_callback_user= user;
1592 tailing_queue_readable(ipf);
1596 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1598 InputFile *ipf= (void*)rable;
1600 ssize_t r= read(ipf->fd, buffer, length);
1602 if (errno==EINTR) continue;
1606 if (ipf==main_input_file) {
1609 } else if (ipf==flushing_input_file) {
1611 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1612 } else if (ipf==backlog_input_file) {
1622 /*---------- filemon implemented with inotify ----------*/
1624 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1625 #define HAVE_FILEMON
1627 #include <linux/inotify.h>
1629 static int filemon_inotify_fd;
1630 static int filemon_inotify_wdmax;
1631 static InputFile **filemon_inotify_wd2ipf;
1633 struct Filemon_Perfile {
1637 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1638 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1639 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1641 if (wd >= filemon_inotify_wdmax) {
1643 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1644 sizeof(*filemon_inotify_wd2ipf) * newmax);
1645 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1646 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1647 filemon_inotify_wdmax= newmax;
1650 assert(!filemon_inotify_wd2ipf[wd]);
1651 filemon_inotify_wd2ipf[wd]= ipf;
1653 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1654 ipf, wd, filemon_inotify_wdmax);
1659 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1661 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1662 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1663 if (r) sysdie("inotify_rm_watch");
1664 filemon_inotify_wd2ipf[wd]= 0;
1667 static void *filemon_inotify_readable(oop_source *lp, int fd,
1668 oop_event e, void *u) {
1669 struct inotify_event iev;
1671 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1673 if (isewouldblock(errno)) break;
1674 sysdie("read from inotify master");
1675 } else if (r==sizeof(iev)) {
1676 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1678 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1680 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1681 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1682 filemon_callback(ipf);
1684 return OOP_CONTINUE;
1687 static int filemon_method_init(void) {
1688 filemon_inotify_fd= inotify_init();
1689 if (filemon_inotify_fd<0) {
1690 syswarn("could not initialise inotify: inotify_init failed");
1694 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1696 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1700 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1702 /*---------- filemon dummy implementation ----------*/
1704 #if !defined(HAVE_FILEMON)
1706 struct Filemon_Perfile { int dummy; };
1708 static int filemon_method_init(void) { return 0; }
1709 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1710 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1712 #endif /* !HAVE_FILEMON */
1714 /*---------- filemon generic interface ----------*/
1716 static void filemon_start(InputFile *ipf) {
1717 assert(!ipf->filemon);
1719 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1720 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1721 filemon_method_startfile(ipf, ipf->filemon);
1724 static void filemon_stop(InputFile *ipf) {
1725 if (!ipf->filemon) return;
1726 filemon_method_stopfile(ipf, ipf->filemon);
1731 static void filemon_callback(InputFile *ipf) {
1732 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1735 /*---------- interface to start and stop an input file ----------*/
1737 static const oop_rd_style feedfile_rdstyle= {
1738 OOP_RD_DELIM_STRIP, '\n',
1740 OOP_RD_SHORTREC_LONG,
1743 static void inputfile_tailing_start(InputFile *ipf) {
1745 ipf->readable.on_readable= tailing_on_readable;
1746 ipf->readable.on_cancel= tailing_on_cancel;
1747 ipf->readable.try_read= tailing_try_read;
1748 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1749 ipf->readable.delete_kill= 0;
1751 ipf->readable_callback= 0;
1752 ipf->readable_callback_user= 0;
1754 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1757 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1758 feedfile_got_article,ipf, feedfile_read_err, ipf);
1759 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1762 static void inputfile_tailing_stop(InputFile *ipf) {
1764 oop_rd_cancel(ipf->rd);
1765 oop_rd_delete(ipf->rd);
1767 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1771 /*========== interaction with innd - state machine ==========*/
1773 /* See official state diagram at top of file. We implement
1784 |`---------------------------------------------------.
1786 |`---------------- - - - |
1787 D ENOENT | D EXISTS see OVERALL STATES diagram |
1788 | for full startup logic |
1791 | ============ try to |
1797 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1798 ^ | hardlink F to D |
1801 | | our handle onto F is now onto D |
1804 | |<-------------------<---------------------<---------+
1806 | | spawn inndcomm flush |
1808 | ================== |
1809 | FLUSHING[-ABSENT] |
1811 | main D tail/none |
1812 | ================== |
1814 | | INNDCOMM FLUSH FAILS ^
1815 | |`----------------------->----------. |
1817 | | NO SUCH SITE V |
1818 ^ |`--------------->----. ==================== |
1819 | | \ FLUSHFAILED[-ABSENT] |
1821 | | FLUSH OK \ main D tail/none |
1822 | | open F \ ==================== |
1824 | | \ | TIME TO RETRY |
1825 | |`------->----. ,---<---'\ `----------------'
1826 | | D NONE | | D NONE `----.
1828 | ============= V V ============
1829 | SEPARATED-1 | | DROPPING-1
1830 | flsh->fd>0 | | flsh->fd>0
1831 | [Separated] | | [Dropping]
1832 | main F idle | | main none
1833 | old D tail | | old D tail
1834 | ============= | | ============
1836 ^ | EOF ON D | | defer | EOF ON D
1838 | =============== | | ===============
1839 | SEPARATED-2 | | DROPPING-2
1840 | flsh->fd==0 | V flsh->fd==0
1841 | [Finishing] | | [Dropping]
1842 | main F tail | `. main none
1843 | old D closed | `. old D closed
1844 | =============== V `. ===============
1846 | | ALL D PROCESSED `. | ALL D PROCESSED
1847 | V install defer as backlog `. | install defer
1848 ^ | close D `. | close D
1849 | | unlink D `. | unlink D
1852 `----------' ==============
1872 static void startup_set_input_file(InputFile *f) {
1873 assert(!main_input_file);
1875 inputfile_tailing_start(f);
1878 static void statemc_init(void) {
1879 struct stat stab, stabf;
1881 path_lock= xasprintf("%s_lock", feedfile);
1882 path_flushing= xasprintf("%s_flushing", feedfile);
1883 path_defer= xasprintf("%s_defer", feedfile);
1884 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1887 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1888 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1891 memset(&fl,0,sizeof(fl));
1893 fl.l_whence= SEEK_SET;
1894 int r= fcntl(lockfd, F_SETLK, &fl);
1896 if (errno==EACCES || isewouldblock(errno)) {
1897 if (quiet_multiple) exit(0);
1898 fatal("another duct holds the lockfile");
1900 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1903 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
1905 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1907 if (!lock_noent && samefile(&stab, &stabf))
1911 sysdie("could not close stale lockfile %s", path_lock);
1913 debug("startup: locked");
1915 search_backlog_file();
1918 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1920 debug("startup: ductdefer ENOENT");
1922 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1923 switch (stab.st_nlink==1) {
1925 open_defer(); /* so that we will later close it and rename it */
1928 xunlink(path_defer, "stale defer file link"
1929 " (presumably hardlink to backlog file)");
1932 die("defer file %s has unexpected link count %d",
1933 path_defer, stab.st_nlink);
1937 struct stat stab_f, stab_d;
1940 InputFile *file_d= open_input_file(path_flushing);
1941 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
1943 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1945 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1946 debug("startup: F==D => Hardlinked");
1947 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1952 debug("startup: F ENOENT => Moved");
1953 if (file_d) startup_set_input_file(file_d);
1954 spawn_inndcomm_flush("feedfile missing at startup");
1955 /* => Flushing, sms:=FLUSHING */
1958 debug("startup: F!=D => Separated");
1959 startup_set_input_file(file_d);
1960 SMS(SEPARATED, 0, "found both old and current feed files");
1962 debug("startup: F exists, D ENOENT => Normal");
1963 InputFile *file_f= open_input_file(feedfile);
1964 if (!file_f) die("feed file vanished during startup");
1965 startup_set_input_file(file_f);
1966 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1971 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1972 assert(sms == sm_NORMAL);
1974 debug("starting flush (%s) (%lu >?= %lu) (%d)",
1976 (unsigned long)(main_input_file ? main_input_file->offset : 0),
1977 (unsigned long)target_max_feedfile_size,
1980 int r= link(feedfile, path_flushing);
1981 if (r) sysdie("link feedfile %s to flushing file %s",
1982 feedfile, path_flushing);
1985 xunlink(feedfile, "old feedfile link");
1988 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1991 static void statemc_period_poll(void) {
1992 if (!sm_period_counter) return;
1993 sm_period_counter--;
1994 assert(sm_period_counter>=0);
1996 if (sm_period_counter) return;
1999 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2001 case sm_FLUSHFAILED:
2002 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2009 static int inputfile_is_done(InputFile *ipf) {
2011 if (ipf->inprogress) return 0; /* new article in the meantime */
2012 if (ipf->fd) return 0; /* not had EOF */
2016 static void notice_processed(InputFile *ipf, const char *what,
2018 #define RCI_NOTHING(x) /* nothing */
2019 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2020 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2022 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2024 info("processed %s%s read=%d(+%dbl,+%derr)"
2025 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2026 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2029 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2030 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2031 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2032 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2033 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2034 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2040 static void statemc_check_backlog_done(void) {
2041 InputFile *ipf= backlog_input_file;
2042 if (!inputfile_is_done(ipf)) return;
2044 const char *slash= strrchr(ipf->path, '/');
2045 const char *leaf= slash ? slash+1 : ipf->path;
2046 const char *under= strchr(slash, '_');
2047 const char *rest= under ? under+1 : leaf;
2048 if (!strncmp(rest,"backlog",7)) rest += 7;
2049 notice_processed(ipf,"backlog:",rest);
2051 close_input_file(ipf);
2052 if (unlink(ipf->path)) {
2053 if (errno != ENOENT)
2054 sysdie("could not unlink processed backlog file %s", ipf->path);
2055 warn("backlog file %s vanished while we were reading it"
2056 " so we couldn't remove it (but it's done now, anyway)",
2060 backlog_input_file= 0;
2061 search_backlog_file();
2065 static void statemc_check_flushing_done(void) {
2066 InputFile *ipf= flushing_input_file;
2067 if (!inputfile_is_done(ipf)) return;
2069 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2071 notice_processed(ipf,"feedfile",0);
2075 xunlink(path_flushing, "old flushing file");
2077 close_input_file(flushing_input_file);
2078 free(flushing_input_file);
2079 flushing_input_file= 0;
2081 if (sms==sm_SEPARATED) {
2082 notice("flush complete");
2083 SMS(NORMAL, 0, "flush complete");
2084 } else if (sms==sm_DROPPING) {
2085 SMS(DROPPED, 0, "old flush complete");
2086 search_backlog_file();
2087 notice("feed dropped, but will continue until backlog is finished");
2091 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2093 assert(!inputfile_is_done(main_input_file));
2094 statemc_check_flushing_done();
2095 statemc_check_backlog_done();
2096 return OOP_CONTINUE;
2099 static void queue_check_input_done(void) {
2100 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2103 static void statemc_setstate(StateMachineState newsms, int periods,
2104 const char *forlog, const char *why) {
2106 sm_period_counter= periods;
2108 const char *xtra= "";
2110 case sm_FLUSHING: sm_FLUSHFAILED:
2111 if (!main_input_file) xtra= "-ABSENT";
2113 case sm_SEPARATED: case sm_DROPPING:
2114 xtra= flushing_input_file->fd ? "-1" : "-2";
2120 info("%s%s[%d] %s",forlog,xtra,periods,why);
2122 info("%s%s %s",forlog,xtra,why);
2126 /*---------- defer and backlog files ----------*/
2128 static void open_defer(void) {
2133 defer= fopen(path_defer, "a+");
2134 if (!defer) sysfatal("could not open defer file %s", path_defer);
2136 /* truncate away any half-written records */
2138 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2140 if (stab.st_size > LONG_MAX)
2141 die("defer file %s size is far too large", path_defer);
2146 long orgsize= stab.st_size;
2147 long truncto= stab.st_size;
2149 if (!truncto) break; /* was only (if anything) one half-truncated record */
2150 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2151 sysdie("seek in defer file %s while truncating partial", path_defer);
2156 sysdie("failed read from defer file %s", path_defer);
2158 die("defer file %s shrank while we were checking it!", path_defer);
2164 if (stab.st_size != truncto) {
2165 warn("truncating half-record at end of defer file %s -"
2166 " shrinking by %ld bytes from %ld to %ld",
2167 path_defer, orgsize - truncto, orgsize, truncto);
2170 sysfatal("could not flush defer file %s", path_defer);
2171 if (ftruncate(fileno(defer), truncto))
2172 sysdie("could not truncate defer file %s", path_defer);
2175 info("continuing existing defer file %s (%ld bytes)",
2176 path_defer, orgsize);
2178 if (fseek(defer, truncto, SEEK_SET))
2179 sysdie("could not seek to new end of defer file %s", path_defer);
2182 static void close_defer(void) {
2187 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2189 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2192 time_t now= xtime();
2194 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2196 (unsigned long)stab.st_ino);
2197 if (link(path_defer, backlog))
2198 sysfatal("could not install defer file %s as backlog file %s",
2199 path_defer, backlog);
2200 if (unlink(path_defer))
2201 sysdie("could not unlink old defer link %s to backlog file %s",
2202 path_defer, backlog);
2206 if (until_backlog_nextscan < 0 ||
2207 until_backlog_nextscan > backlog_retry_minperiods + 1)
2208 until_backlog_nextscan= backlog_retry_minperiods + 1;
2211 static void poll_backlog_file(void) {
2212 if (until_backlog_nextscan < 0) return;
2213 if (until_backlog_nextscan-- > 0) return;
2214 search_backlog_file();
2217 static void search_backlog_file(void) {
2218 /* returns non-0 iff there are any backlog files */
2223 const char *oldest_path=0;
2224 time_t oldest_mtime, now;
2226 if (backlog_input_file) return;
2230 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2234 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2236 die("out of memory expanding backlog pattern %s", globpat_backlog);
2238 for (i=0; i<gl.gl_pathc; i++) {
2239 const char *path= gl.gl_pathv[i];
2241 if (strchr(path,'#') || strchr(path,'~')) {
2242 debug("backlog file search skipping %s", path);
2245 r= stat(path, &stab);
2247 syswarn("failed to stat backlog file %s", path);
2250 if (!S_ISREG(stab.st_mode)) {
2251 warn("backlog file %s is not a plain file (or link to one)", path);
2254 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2256 oldest_mtime= stab.st_mtime;
2259 case GLOB_NOMATCH: /* fall through */
2262 sysdie("glob expansion of backlog pattern %s gave unexpected"
2263 " nonzero (error?) return value %d", globpat_backlog, r);
2269 debug("backlog scan: none");
2271 if (sms==sm_DROPPED) {
2272 notice("feed dropped and our work is complete");
2273 xunlink(path_lock, "lockfile for old feed");
2276 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2281 double age= difftime(now, oldest_mtime);
2282 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2284 if (age_deficiency <= 0) {
2285 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2286 age, age_deficiency, oldest_path);
2288 backlog_input_file= open_input_file(oldest_path);
2289 if (!backlog_input_file) {
2290 warn("backlog file %s vanished as we opened it", backlog_input_file);
2293 inputfile_tailing_start(backlog_input_file);
2294 until_backlog_nextscan= -1;
2298 until_backlog_nextscan= age_deficiency / period_seconds;
2300 if (backlog_spontaneous_rescan_periods >= 0 &&
2301 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2302 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2304 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2305 age, age_deficiency, until_backlog_nextscan, oldest_path);
2309 /*========== flushing the feed ==========*/
2311 static pid_t inndcomm_child;
2313 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2314 assert(inndcomm_child);
2315 int status= xwaitpid(&inndcomm_child, "inndcomm");
2316 cancel_fd_read_except(fd);
2319 assert(!flushing_input_file);
2321 if (WIFEXITED(status)) {
2322 switch (WEXITSTATUS(status)) {
2324 case INNDCOMMCHILD_ESTATUS_FAIL:
2327 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2328 warn("feed has been dropped by innd, finishing up");
2329 flushing_input_file= main_input_file;
2330 tailing_queue_readable(flushing_input_file);
2331 /* we probably previously returned EAGAIN from our fake read method
2332 * when in fact we were at EOF, so signal another readable event
2333 * so we actually see the EOF */
2337 if (flushing_input_file) {
2338 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2341 SMS(DROPPED, 0, "feed dropped by innd");
2342 search_backlog_file();
2344 return OOP_CONTINUE;
2348 flushing_input_file= main_input_file;
2349 tailing_queue_readable(flushing_input_file);
2351 main_input_file= open_input_file(feedfile);
2352 if (!main_input_file)
2353 die("flush succeeded but feedfile %s does not exist!", feedfile);
2355 if (flushing_input_file) {
2356 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2359 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2361 return OOP_CONTINUE;
2364 goto unexpected_exitstatus;
2367 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2368 warn("flush timed out trying to talk to innd");
2371 unexpected_exitstatus:
2372 report_child_status("inndcomm child", status);
2376 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2379 static void inndcommfail(const char *what) {
2380 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2381 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2384 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2387 notice("flushing %s",why);
2389 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2390 assert(!inndcomm_child);
2392 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2394 inndcomm_child= xfork("inndcomm child");
2396 if (!inndcomm_child) {
2397 const char *flushargv[2]= { sitename, 0 };
2403 alarm(inndcomm_flush_timeout);
2404 r= ICCopen(); if (r) inndcommfail("connect");
2405 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2406 if (!r) exit(0); /* yay! */
2408 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2409 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2410 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2414 int sentinel_fd= pipefds[0];
2415 on_fd_read_except(sentinel_fd, inndcomm_event);
2417 SMS(FLUSHING, 0, why);
2420 /*========== main program ==========*/
2422 static void postfork_inputfile(InputFile *ipf) {
2425 perhaps_close(&ipf->fd);
2428 static void postfork_stdio(FILE *f) {
2429 /* we have no stdio streams that are buffered long-term */
2433 static void postfork(const char *what) {
2434 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2435 sysdie("%s child: failed to reset SIGPIPE");
2437 postfork_inputfile(main_input_file);
2438 postfork_inputfile(flushing_input_file);
2441 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2444 postfork_stdio(defer);
2447 #define EVERY(what, interval_sec, interval_usec, body) \
2448 static struct timeval what##_timeout = { interval_sec, interval_usec }; \
2449 static void what##_schedule(void); \
2450 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2452 what##_schedule(); \
2454 static void what##_schedule(void) { \
2455 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2458 EVERY(filepoll, 5,0, {
2459 if (main_input_file && main_input_file->readable_callback)
2460 filemon_callback(main_input_file);
2463 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s"
2464 #define DEBUG_IPF(wh) \
2465 wh##_input_file, debug_ipf_path(wh##_input_file), \
2466 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2467 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2468 static const char *debug_ipf_path(InputFile *ipf) {
2469 char *slash= strrchr(ipf->path,'/');
2470 return slash ? slash+1 : ipf->path;
2473 EVERY(period, -1,0, {
2475 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2476 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_IPF(flushing)
2477 " children connecting=%ld inndcomm_child"
2479 sms_names[sms], sm_period_counter,
2480 queue.count, conns.count, until_connect,
2481 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2482 (long)connecting_child, (long)inndcomm_child
2485 if (until_connect) until_connect--;
2487 poll_backlog_file();
2488 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2489 statemc_period_poll();
2490 check_assign_articles();
2495 /*========== option parsing ==========*/
2497 /*---------- generic option parser and logging ----------*/
2499 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2500 static void vbadusage(const char *fmt, va_list al) {
2503 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2504 static void badusage(const char *fmt, ...) {
2511 of_seconds= 001000u,
2512 of_boolean= 002000u,
2515 typedef struct Option Option;
2516 typedef void OptionParser(const Option*, const char *val);
2526 /*---------- specific option types ----------*/
2528 static void op_integer(const Option *o, const char *val) {
2531 unsigned long ul= strtoul(val,&ep,10);
2532 if (*ep || ep==val || errno || ul>INT_MAX)
2533 badusage("bad integer value for %s",o->lng);
2534 int *store= o->store;
2538 static void op_double(const Option *o, const char *val) {
2539 int *store= o->store;
2542 *store= strtod(val, &ep);
2543 if (*ep || ep==val || errno)
2544 badusage("bad floating point value for %s",o->lng);
2547 static void op_string(const Option *o, const char *val) {
2548 const char **store= o->store;
2552 static void op_seconds(const Option *o, const char *val) {
2553 int *store= o->store;
2557 double v= strtod(val,&ep);
2558 if (ep==val) badusage("bad time/duration value for %s",o->lng);
2560 if (!*ep || !strcmp(ep,"s")) unit= 1;
2561 else if (!strcmp(ep,"m")) unit= 60;
2562 else if (!strcmp(ep,"h")) unit= 3600;
2563 else if (!strcmp(ep,"d")) unit= 86400;
2564 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2568 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2572 static void op_periods_rndup(const Option *o, const char *val) {
2573 int *store= o->store;
2575 *store += period_seconds-1;
2576 *store /= period_seconds;
2579 static void op_setint(const Option *o, const char *val) {
2580 int *store= o->store;
2584 /*---------- specific options ----------*/
2586 static const Option options[]= {
2587 {'f',"feedfile", &feedfile, op_string },
2588 {'q',"quiet-multiple", &quiet_multiple, op_setint, 1,1 },
2590 { 0, "max-connections", &max_connections, op_integer },
2591 { 0, "max-queue-per-conn", &max_queue_per_conn, op_integer },
2594 { 0, "streaming", &try_stream, op_setint, 1,1 },
2595 { 0, "no-streaming", &try_stream, op_setint, 1,0 },
2596 {'P',"port", &port, op_integer },
2597 { 0, "inndconf", &inndconffile, op_string },
2598 {'d',"daemon", &become_daemon, op_setint, 1,1 },
2599 { 0, "no-daemon", &become_daemon, op_setint, 1,0 },
2601 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2602 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2604 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2605 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2606 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2609 int main(int argc, char **argv) {
2615 if (*arg != '-') break;
2616 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2618 while ((a= *++arg)) {
2622 char *equals= strchr(arg,'=');
2623 int len= equals ? (equals - arg) : strlen(arg);
2624 for (o=options; o->lng; o++)
2625 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2627 badusage("unknown long option --%s",arg);
2630 if (equals) badusage("option --%s does not take a value",o->lng);
2632 } else if (equals) {
2636 if (!arg) badusage("option --%s needs a value",o->lng);
2639 break; /* eaten the whole argument now */
2641 for (o=options; o->lng; o++)
2644 badusage("unknown short option -%c",a);
2651 if (!arg) badusage("option -%c needs a value",o->shrt);
2654 break; /* eaten the whole argument now */
2659 if (!arg) badusage("need site name argument");
2665 if (*++argv) badusage("too many non-option arguments");
2667 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2668 badusage("nocheck threshold percentage must be between 0..100");
2669 nocheck_thresh= nocheck_thresh_pct * 0.01;
2671 if (nocheck_decay_articles < 0.1)
2672 badusage("nocheck decay articles must be at least 0.1");
2673 nocheck_decay= 1 - 1/nocheck_decay_articles;
2676 pathoutgoing= innconf->pathoutgoing;
2677 innconf_read(inndconffile);
2680 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2681 else if (!feedfile[0])
2682 badusage("feed filename must be nonempty");
2683 else if (feedfile[strlen(feedfile)-1]=='/')
2684 feedfile= xasprintf("%s%s",feedfile,sitename);
2686 const char *feedfile_forbidden= "?*[~#";
2688 while ((c= *feedfile_forbidden++))
2689 if (strchr(feedfile, c))
2690 badusage("feed filename may not contain metacharacter %c",c);
2692 oop_source_sys *sysloop= oop_sys_new();
2693 if (!sysloop) sysdie("could not create liboop event loop");
2694 loop= (oop_source*)sysloop;
2696 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2697 sysdie("could not ignore SIGPIPE");
2699 if (become_daemon) {
2701 for (i=3; i<255; i++)
2702 /* do this now before we open syslog, etc. */
2704 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2706 int null= open("/dev/null",O_RDWR);
2707 if (null<0) sysdie("failed to open /dev/null");
2713 pid_t child1= xfork("daemonise first fork");
2714 if (child1) _exit(0);
2716 pid_t sid= setsid();
2717 if (sid != child1) sysdie("setsid failed");
2719 pid_t child2= xfork("daemonise second fork");
2720 if (child2) _exit(0);
2728 if (!filemon_method_init()) {
2729 warn("no file monitoring available, polling");
2730 filepoll_schedule();
2733 period_timeout.tv_sec= period_seconds;
2738 void *r= oop_sys_run(sysloop);
2739 assert(r == OOP_ERROR);
2740 sysdie("event loop failed");