3 * - actually implement badusage
4 * - options for all options
6 * - pid, sitename, hostname in lockfile
11 * Newsfeeds file entries should look like this:
12 * host.name.of.site[/exclude,exclude,...]\
13 * :pattern,pattern...[/distribution,distribution...]\
17 * sitename[/exclude,exclude,...]\
18 * :pattern,pattern...[/distribution,distribution...]\
24 * or might be blanked out
25 * <spc><spc><spc><spc>....
27 * F site.name main feed file
28 * opened/created, then written, by innd
31 * tokens blanked out by duct when processed
32 * site.name_lock lock preventing multiple ducts
33 * to hold lock must open,F_SETLK[W]
34 * and then stat to check that locked file
35 * still has name site.name_lock
36 * holder of this lock is "duct"
37 * (only) lockholder may remove the lockfile
38 * D site.name_flushing temporary feed file during flush (or crash)
39 * hardlink created by duct
41 * site.name_defer 431'd articles, still being written,
42 * created, written, used by duct
44 * site.name_backlog.<date>.<inum>
45 * 431'd articles, ready for innxmit or duct
46 * created (link/mv) by duct
47 * site.name_backlog<anything-else> (where <anything-else> does not
48 * contain '#' or '~') eg
49 * site.name_backlog.manual
50 * anything the sysadmin likes (eg, feed files
51 * from old feeds to be merged into this one)
52 * created (link/mv) by admin
53 * may be symlinks (in which case links
54 * may be written through, but only links
57 * It is safe to remove backlog files manually,
58 * if it's desired to throw away the backlog.
60 * Backlog files are also processed by innduct. We find the oldest
61 * backlog file which is at least a certain amount old, and feed it
62 * back into our processing. When every article in it has been read
63 * and processed, we unlink it and look for another backlog file.
65 * If we don't have a backlog file that we're reading, we close the
66 * defer file that we're writing and make it into a backlog file at
67 * the first convenient opportunity.
78 | | <----------------<---------------------------------'|
84 | F: innd writing, duct reading |
87 | | duct decides time to flush |
88 | | duct makes hardlink |
90 | V <------------------------'|
92 | F == D: innd writing, duct reading both exist |
95 | | <-----------<-------------<--'|
99 | V <---------------------. |
102 | D: innd writing, duct reading; or ENOENT | |
104 | | duct requests flush of feed | |
105 | | (others can too, harmlessly) | |
109 | D: innd flushing, duct; or ENOENT | |
111 | | inndcomm flush fails | |
112 | |`-------------------------->------------------' |
114 | | inndcomm reports no such site |
115 | |`---------------------------------------------------- | -.
117 | | innd finishes writing D, creates F | |
118 | | inndcomm reports flush successful | |
121 | Separated <----------------' |
122 | F: innd writing F!=D /
123 | D: duct reading; or ENOENT both exist /
125 | | duct gets to the end of D /
126 | | duct opens F too /
129 | F: innd writing, duct reading |
130 | D: duct finishing V
132 | | duct finishes processing D F: ENOENT
133 | V duct unlinks D D: duct reading
135 `--<--' | duct finishes
145 "duct reading" means innduct is reading the file but also
146 overwriting processed tokens.
150 * rune for printing diagrams:
152 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
157 /*============================== PROGRAM ==============================*/
159 #define _GNU_SOURCE 1
165 #include "inndcomm.h"
167 #include "inn/list.h"
168 #include "inn/innconf.h"
171 #include <sys/types.h>
172 #include <sys/wait.h>
173 #include <sys/stat.h>
174 #include <sys/socket.h>
190 #include <oop-read.h>
192 /*----- general definitions, probably best not changed -----*/
194 #define CONNCHILD_ESTATUS_STREAM 4
195 #define CONNCHILD_ESTATUS_NOSTREAM 5
197 #define INNDCOMMCHILD_ESTATUS_FAIL 6
198 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
200 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
202 #define VA va_list al; va_start(al,fmt)
203 #define PRINTF(f,a) __attribute__((__format__(printf,f,a)))
204 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
206 /*----- doubly linked lists -----*/
208 #define ISNODE(T) struct { T *succ, *pred; } node /* must be at start */
209 #define DEFLIST(T) typedef struct { T *hd, *tl, *tp; int count; } T##List
211 #define NODE(n) (assert((void*)&(n)->node == &(n)), \
212 (struct node*)&(n)->node)
214 #define LIST_CHECKCANHAVENODE(l,n) \
215 ((void)((n) == ((l).hd))) /* just for the type check */
217 #define LIST_ADDSOMEHOW(l,n,list_addsomehow) \
218 ( LIST_CHECKCANHAVENODE(l,n), \
219 list_addsomehow((struct list*)&(l), NODE((n))), \
223 #define LIST_REMSOMEHOW(l,list_remsomehow) \
227 list_remsomehow((struct list*)&(l)) ) \
233 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
234 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
235 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
236 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
238 #define LIST_INIT(l) ((l).hd, list_new((struct list*)&(l)))
239 #define LIST_HEAD(l) ((typeof((l).hd))(list_head((struct list*)&(l))))
240 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
241 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
243 #define LIST_REMOVE(l,n) \
244 ( LIST_CHECKCANHAVENODE(l,n), \
245 list_remove(NODE((n))), \
249 #define LIST_INSERT(l,n,pred) \
250 ( LIST_CHECKCANHAVENODE(l,n), \
251 LIST_CHECKCANHAVENODE(l,pred), \
252 list_insert((struct list*)&(l), NODE((n)), NODE((pred))), \
256 /*----- type predeclarations -----*/
258 typedef struct Conn Conn;
259 typedef struct Article Article;
260 typedef struct InputFile InputFile;
261 typedef struct XmitDetails XmitDetails;
262 typedef struct Filemon_Perfile Filemon_Perfile;
263 typedef enum StateMachineState StateMachineState;
268 /*----- function predeclarations -----*/
270 static void conn_maybe_write(Conn *conn);
271 static void conn_make_some_xmits(Conn *conn);
272 static void *conn_write_some_xmits(Conn *conn);
274 static void xmit_free(XmitDetails *d);
276 #define SMS(newstate, periods, why) \
277 (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
278 static void statemc_setstate(StateMachineState newsms, int periods,
279 const char *forlog, const char *why);
281 static void statemc_start_flush(const char *why); /* Normal => Flushing */
282 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
284 static void check_assign_articles(void);
285 static void queue_check_input_done(void);
287 static void statemc_check_flushing_done(void);
288 static void statemc_check_backlog_done(void);
290 static void postfork(const char *what);
291 static void postfork_inputfile(InputFile *ipf);
293 static void open_defer(void);
294 static void close_defer(void);
295 static void search_backlog_file(void);
297 static void inputfile_reading_start(InputFile *ipf);
298 static void inputfile_reading_stop(InputFile *ipf);
300 static void filemon_start(InputFile *ipf);
301 static void filemon_stop(InputFile *ipf);
302 static void filemon_callback(InputFile *ipf);
304 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
305 static void connfail(Conn *conn, const char *fmt, ...) PRINTF(2,3);
307 /*----- configuration options -----*/
309 static const char *sitename, *feedfile, *pathoutgoing;
310 static const char *remote_host;
311 static int quiet_multiple=0, become_daemon=1;
313 static int max_connections=10, max_queue_per_conn=200;
314 static int target_max_feedfile_size=100000;
316 static int period_seconds=60;
318 static double max_bad_data_ratio= 0.01;
319 static int max_bad_data_initial= 30;
320 /* in one corrupt 4096-byte block the number of newlines has
321 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
323 static int connection_setup_timeout=200, port=119, try_stream=1;
324 static int inndcomm_flush_timeout=100;
325 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
326 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
327 static int spontaneous_flush_periods, need_activity_periods;
328 static const char *inndconffile;
330 static double nocheck_thresh_pct= 95.0;
331 static double nocheck_thresh; /* computed in main from _pct */
332 static double nocheck_decay_articles= 100; /* converted to _decay */
333 static double nocheck_decay; /* computed in main from _articles */
336 /*----- statistics -----*/
338 typedef enum { /* in queue in conn->sent */
339 art_Unchecked, /* not checked, not sent checking */
340 art_Wanted, /* checked, wanted sent body as requested */
341 art_Unsolicited, /* - sent body without check */
345 #define RESULT_COUNTS(RCS,RCN) \
353 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
354 #define RCI_TRIPLE_VALS_BASE(counts,x) \
355 counts[art_Unchecked] x \
356 + counts[art_Wanted] x \
357 + counts[art_Unsolicited] x, \
358 counts[art_Unchecked] x \
359 , counts[art_Wanted] x \
360 , counts[art_Unsolicited] x
363 #define RC_INDEX(x) RC_##x,
364 RESULT_COUNTS(RC_INDEX, RC_INDEX)
369 /*----- transmission buffers -----*/
374 xk_Malloc, xk_Const, xk_Artdata
386 /*----- core operational data structure types -----*/
389 /* This is also an instance of struct oop_readable */
390 struct oop_readable readable; /* first */
391 oop_readable_call *readable_callback;
392 void *readable_callback_user;
395 Filemon_Perfile *filemon;
397 oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
398 long inprogress; /* no. of articles read but not processed */
402 int counts[art_MaxState][RCI_max];
403 int readcount_ok, readcount_blank, readcount_err;
418 #define SMS_LIST(X) \
426 enum StateMachineState {
427 #define SMS_DEF_ENUM(s) sm_##s,
428 SMS_LIST(SMS_DEF_ENUM)
431 static const char *sms_names[]= {
432 #define SMS_DEF_NAME(s) #s ,
433 SMS_LIST(SMS_DEF_NAME)
439 int fd; /* may be 0, meaning closed (during construction/destruction) */
440 int max_queue, stream, quitting;
441 int since_activity; /* periods */
442 ArticleList waiting; /* not yet told peer */
443 ArticleList priority; /* peer says send it now */
444 ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
445 struct iovec xmit[CONNIOVS];
446 XmitDetails xmitd[CONNIOVS];
451 /*----- general operational variables -----*/
453 /* main initialises */
454 static oop_source *loop;
455 static ConnList conns;
456 static ArticleList queue;
457 static char *path_lock, *path_flushing, *path_defer, *globpat_backlog;
459 /* statemc_init initialises */
460 static StateMachineState sms;
462 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
463 static int sm_period_counter;
465 /* initialisation to 0 is good */
466 static int until_connect, until_backlog_nextscan;
467 static double accept_proportion;
468 static int nocheck, nocheck_reported;
470 /*========== logging ==========*/
472 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
473 static void logcore(int sysloglevel, const char *fmt, ...) {
476 vsyslog(sysloglevel,fmt,al);
478 vfprintf(stderr,fmt,al);
484 static void logv(int sysloglevel, const char *pfx, int errnoval,
485 const char *fmt, va_list al) PRINTF(5,0);
486 static void logv(int sysloglevel, const char *pfx, int errnoval,
487 const char *fmt, va_list al) {
488 char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
489 vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
490 msgbuf[sizeof(msgbuf)-1]= 0;
492 if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
493 sysloglevel= LOG_ERR; /* run by wrong user, probably */
495 logcore(sysloglevel, "<%s>%s: %s%s%s",
496 sitename, pfx, msgbuf,
497 errnoval>=0 ? ": " : "",
498 errnoval>=0 ? strerror(errnoval) : "");
501 #define diewrap(fn, pfx, sysloglevel, err, estatus) \
502 static void fn(const char *fmt, ...) NORET_PRINTF(1,2); \
503 static void fn(const char *fmt, ...) { \
505 logv(sysloglevel, pfx, err, fmt, al); \
509 #define logwrap(fn, pfx, sysloglevel, err) \
510 static void fn(const char *fmt, ...) PRINTF(1,2); \
511 static void fn(const char *fmt, ...) { \
513 logv(sysloglevel, pfx, err, fmt, al); \
517 diewrap(sysdie, " critical", LOG_CRIT, errno, 16);
518 diewrap(die, " critical", LOG_CRIT, -1, 16);
520 diewrap(sysfatal, " fatal", LOG_ERR, errno, 12);
521 diewrap(fatal, " fatal", LOG_ERR, -1, 12);
523 logwrap(syswarn, " warning", LOG_WARNING, errno);
524 logwrap(warn, " warning", LOG_WARNING, -1);
526 logwrap(notice, "", LOG_NOTICE, -1);
527 logwrap(info, " info", LOG_INFO, -1);
528 logwrap(debug, " debug", LOG_DEBUG, -1);
531 /*========== utility functions etc. ==========*/
533 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
534 static char *xvasprintf(const char *fmt, va_list al) {
536 int rc= vasprintf(&str,fmt,al);
537 if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
540 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
541 static char *xasprintf(const char *fmt, ...) {
543 char *str= xvasprintf(fmt,al);
548 static int close_perhaps(int *fd) {
554 static void xclose(int fd, const char *what, const char *what2) {
556 if (r) sysdie("close %s%s",what,what2?what2:"");
558 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
560 xclose(*fd,what,what2);
564 static pid_t xfork(const char *what) {
568 if (child==-1) sysdie("cannot fork for %s",what);
569 if (!child) postfork(what);
570 debug("forked %s %ld", what, (unsigned long)child);
574 static void on_fd_read_except(int fd, oop_call_fd callback) {
575 loop->on_fd(loop, fd, OOP_READ, callback, 0);
576 loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
578 static void cancel_fd_read_except(int fd) {
579 loop->cancel_fd(loop, fd, OOP_READ);
580 loop->cancel_fd(loop, fd, OOP_EXCEPTION);
583 static void report_child_status(const char *what, int status) {
584 if (WIFEXITED(status)) {
585 int es= WEXITSTATUS(status);
587 warn("%s: child died with error exit status %d",es);
588 } else if (WIFSIGNALED(status)) {
589 int sig= WTERMSIG(status);
590 const char *sigstr= strsignal(sig);
591 const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
593 warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
595 warn("%s: child died due to unknown fatal signal %d%s",
596 what, sig, coredump);
598 warn("%s: child died with unknown wait status %d", status);
602 static int xwaitpid(pid_t *pid, const char *what) {
605 int r= kill(*pid, SIGKILL);
606 if (r) sysdie("cannot kill %s child", what);
608 pid_t got= waitpid(*pid, &status, WNOHANG);
609 if (got==-1) sysdie("cannot reap %s child", what);
616 static void xunlink(const char *path, const char *what) {
618 if (r) sysdie("can't unlink %s %s", path, what);
621 static time_t xtime(void) {
623 if (now==-1) sysdie("time(2) failed");
626 static void check_isreg(const struct stat *stab, const char *path,
628 if (!S_ISREG(stab->st_mode))
629 die("%s %s not a plain file (mode 0%lo)",
630 what, path, (unsigned long)stab->st_mode);
633 static void xfstat(int fd, struct stat *stab_r, const char *what) {
634 int r= fstat(fd, stab_r);
635 if (r) sysdie("could not fstat %s", what);
638 static void xfstat_isreg(int fd, struct stat *stab_r,
639 const char *path, const char *what) {
640 xfstat(fd, stab_r, what);
641 check_isreg(stab_r, path, what);
644 static void xlstat_isreg(const char *path, struct stat *stab,
645 int *enoent_r /* 0 means ENOENT is fatal */,
647 int r= lstat(path, stab);
649 if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
650 sysdie("could not lstat %s %s", what, path);
652 if (enoent_r) *enoent_r= 0;
653 check_isreg(stab, path, what);
656 static void setnonblock(int fd, int nonblocking) {
657 int r= fcntl(fd, F_GETFL); if (r<0) sysdie("setnonblocking fcntl F_GETFL");
658 if (nonblocking) r |= O_NONBLOCK;
659 else r &= ~O_NONBLOCK;
660 r= fcntl(fd, F_SETFL, r); if (r<0) sysdie("setnonblocking fcntl F_SETFL");
663 static int samefile(const struct stat *a, const struct stat *b) {
664 assert(S_ISREG(a->st_mode));
665 assert(S_ISREG(b->st_mode));
666 return (a->st_ino == b->st_ino &&
667 a->st_dev == b->st_dev);
670 static char *sanitise(const char *input) {
671 static char sanibuf[100]; /* returns pointer to this buffer! */
673 const char *p= input;
677 if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
679 if (!c) { *q++= '\''; *q=0; break; }
680 if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
681 sprintf(q,"\\x%02x",c);
687 static int isewouldblock(int errnoval) {
688 return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
691 /*========== management of connections ==========*/
693 static void conn_dispose(Conn *conn) {
696 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
697 loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
699 int r= close_perhaps(&conn->fd);
700 if (r) info("C%d error closing socket: %s", conn->fd, strerror(errno));
702 until_connect= reconnect_delay_periods;
705 static void *conn_exception(oop_source *lp, int fd,
706 oop_event ev, void *conn_v) {
709 assert(fd == conn->fd);
710 assert(ev == OOP_EXCEPTION);
711 int r= read(conn->fd, &ch, 1);
712 if (r<0) connfail(conn,"read failed: %s",strerror(errno));
713 else connfail(conn,"exceptional condition on socket (peer sent urgent"
714 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
718 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
719 int requeue[art_MaxState];
722 while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
723 while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
724 while ((art= LIST_REMHEAD(conn->sent))) {
725 requeue[art->state]++;
726 if (art->state==art_Unsolicited) art->state= art_Unchecked;
727 LIST_ADDTAIL(queue,art);
732 for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
735 char *m= xvasprintf(fmt,al);
736 warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
737 conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
740 LIST_REMOVE(conns,conn);
742 check_assign_articles();
745 static void connfail(Conn *conn, const char *fmt, ...) {
748 vconnfail(conn,fmt,al);
752 static void check_idle_conns(void) {
754 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
755 conn->since_activity++;
757 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
758 if (conn->since_activity <= need_activity_periods) continue;
760 /* We need to shut this down */
762 connfail(conn,"timed out waiting for response to QUIT");
763 else if (conn->sent.count)
764 connfail(conn,"timed out waiting for responses");
765 else if (conn->waiting.count || conn->priority.count)
766 connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
767 else if (conn->xmitu)
768 connfail(conn,"peer has been sending responses"
769 " before receiving our commands!");
771 static const char quitcmd[]= "QUIT\r\n";
772 int todo= sizeof(quitcmd)-1;
773 const char *p= quitcmd;
775 int r= write(conn->fd, p, todo);
777 if (isewouldblock(errno))
778 connfail(conn, "blocked writing QUIT to idle connection");
780 connfail(conn, "failed to write QUIT to idle connection: %s",
788 conn->since_activity= 0;
789 debug("C%d is idle, quitting", conn->fd);
798 /*---------- making new connections ----------*/
800 static int connecting_sockets[2]= {-1,-1};
801 static pid_t connecting_child;
803 static void connect_attempt_discard(void) {
804 if (connecting_sockets[0])
805 cancel_fd_read_except(connecting_sockets[0]);
807 xclose_perhaps(&connecting_sockets[0], "connecting socketpair (read)",0);
808 xclose_perhaps(&connecting_sockets[1], "connecting socketpair (write)",0);
810 if (connecting_child) {
811 int r= kill(connecting_child, SIGTERM);
812 if (r) syswarn("failed to kill connecting child");
813 int status= xwaitpid(&connecting_child, "connect");
815 if (!(WIFEXITED(status) ||
816 (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
817 report_child_status("connect", status);
821 #define PREP_DECL_MSG_CMSG(msg) \
823 memset(&msg,0,sizeof(msg)); \
824 char msg##cbuf[CMSG_SPACE(sizeof(fd))]; \
825 msg.msg_control= msg##cbuf; \
826 msg.msg_controllen= sizeof(msg##cbuf);
828 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
831 conn= xmalloc(sizeof(*conn));
832 memset(conn,0,sizeof(*conn));
834 PREP_DECL_MSG_CMSG(msg);
835 struct cmsghdr *h= 0;
836 ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
837 if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
840 pid_t got= waitpid(connecting_child, &status, WNOHANG);
842 assert(got==connecting_child);
844 if (WIFEXITED(status)) {
845 if (WEXITSTATUS(status) != 0 &&
846 WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
847 WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
848 /* child already reported the problem */;
850 warn("connect: connection child exited code %d but no cmsg",
851 WEXITSTATUS(status));
852 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
853 warn("connect: connection attempt timed out");
855 report_child_status("connect", status);
858 /* child is still running apparently, report the socket problem */
860 syswarn("connect: read from child socket failed");
861 else if (e == OOP_EXCEPTION)
862 warn("connect: unexpected exception on child socket");
864 warn("connect: unexpected EOF on child socket");
866 fatal("connect: unexpected lack of cmsg from child");
871 #define CHK(field, val) \
872 if (h->cmsg_##field != val) { \
873 die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
876 CHK(level, SOL_SOCKET);
877 CHK(type, SCM_RIGHTS);
878 CHK(len, CMSG_LEN(sizeof(conn->fd)));
881 if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
883 memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
884 loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
887 pid_t got= waitpid(connecting_child, &status, 0);
888 if (got==-1) sysdie("connect: real wait for child");
889 assert(got == connecting_child);
892 if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
893 int es= WEXITSTATUS(status);
895 case CONNCHILD_ESTATUS_STREAM: conn->stream= 1; break;
896 case CONNCHILD_ESTATUS_NOSTREAM: conn->stream= 0; break;
898 fatal("connect: child gave unexpected exit status %d", es);
902 LIST_INIT(conn->waiting);
903 LIST_INIT(conn->priority);
904 LIST_INIT(conn->sent);
905 setnonblock(conn->fd, 1);
906 conn->max_queue= conn->stream ? max_queue_per_conn : 1;
907 notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
908 LIST_ADDHEAD(conns, conn);
910 connect_attempt_discard();
911 check_assign_articles();
916 connect_attempt_discard();
919 static int allow_connect_start(void) {
920 return conns.count < max_connections
925 static void connect_start(void) {
926 assert(!connecting_sockets[0]);
927 assert(!connecting_sockets[1]);
928 assert(!connecting_child);
930 notice("starting connection attempt");
932 int r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
933 if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
935 connecting_child= xfork("connection");
937 if (!connecting_child) {
938 FILE *cn_from, *cn_to;
939 char buf[NNTP_STRLEN+100];
940 int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
942 r= close(connecting_sockets[0]);
943 if (r) sysdie("connect: close parent socket in child");
945 alarm(connection_setup_timeout);
946 if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
947 if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
948 else sysfatal("connect: connection attempt failed");
950 if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
951 sysfatal("connect: authentication failed");
953 if (fputs("MODE STREAM\r\n", cn_to) ||
955 sysfatal("connect: could not send MODE STREAM");
956 buf[sizeof(buf)-1]= 0;
957 if (!fgets(buf, sizeof(buf)-1, cn_from)) {
959 sysfatal("connect: could not read response to MODE STREAM");
961 fatal("connect: connection close in response to MODE STREAM");
966 fatal("connect: response to MODE STREAM is too long: %.100s...",
967 remote_host, sanitise(buf));
968 l--; if (l>0 && buf[l-1]=='\r') l--;
971 int rcode= strtoul(buf,&ep,10);
973 fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
977 exitstatus= CONNCHILD_ESTATUS_STREAM;
983 warn("connect: unexpected response to MODE STREAM: %.50s",
989 int fd= fileno(cn_from);
991 PREP_DECL_MSG_CMSG(msg);
992 struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
993 cmsg->cmsg_level= SOL_SOCKET;
994 cmsg->cmsg_type= SCM_RIGHTS;
995 cmsg->cmsg_len= CMSG_LEN(sizeof(fd));
996 memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
998 msg.msg_controllen= cmsg->cmsg_len;
999 r= sendmsg(connecting_sockets[1], &msg, 0);
1000 if (r) sysdie("sendmsg failed for new connection");
1005 r= close(connecting_sockets[1]); connecting_sockets[1]= 0;
1006 if (r) sysdie("connect: close child socket in parent");
1008 on_fd_read_except(connecting_sockets[0], connchild_event);
1012 connect_attempt_discard();
1015 /*---------- assigning articles to conns, and transmitting ----------*/
1017 static void check_assign_articles(void) {
1025 /* Find a connection to offer this article. We prefer a busy
1026 * connection to an idle one, provided it's not full. We take the
1027 * first (oldest) and since that's stable, it will mean we fill up
1028 * connections in order. That way if we have too many
1029 * connections, the spare ones will go away eventually.
1031 for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1032 if (walk->quitting) continue;
1033 inqueue= walk->sent.count + walk->priority.count
1034 + walk->waiting.count;
1035 spare= walk->max_queue - inqueue;
1036 assert(inqueue <= max_queue_per_conn);
1038 if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1039 else if (spare>0) /*working*/ { use= walk; break; }
1042 if (!inqueue) use->since_activity= 0; /* reset idle counter */
1044 Article *art= LIST_REMHEAD(queue);
1045 LIST_ADDTAIL(use->waiting, art);
1048 conn_maybe_write(use);
1049 } else if (allow_connect_start()) {
1050 until_connect= reconnect_delay_periods;
1059 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1060 conn_maybe_write(u);
1061 return OOP_CONTINUE;
1064 static void conn_maybe_write(Conn *conn) {
1067 conn_make_some_xmits(conn);
1069 loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1073 void *rp= conn_write_some_xmits(conn);
1074 if (rp==OOP_CONTINUE) {
1075 loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1077 } else if (rp==OOP_HALT) {
1080 /* transmitted everything */
1087 /*========== article transmission ==========*/
1089 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1090 XmitKind kind) { /* caller must then fill in details */
1091 struct iovec *v= &conn->xmit[conn->xmitu];
1092 XmitDetails *d= &conn->xmitd[conn->xmitu++];
1093 v->iov_base= (char*)data;
1099 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1100 xmit_core(conn,data,len, xk_Const);
1102 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1104 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1105 XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1109 static void xmit_free(XmitDetails *d) {
1111 case xk_Malloc: free(d->info.malloc_tofree); break;
1112 case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1113 case xk_Const: break;
1118 static void *conn_write_some_xmits(Conn *conn) {
1120 * 0: nothing more to write, no need to call us again
1121 * OOP_CONTINUE: more to write but fd not writeable
1122 * OOP_HALT: disaster, have destroyed conn
1125 int count= conn->xmitu;
1126 if (!count) return 0;
1128 if (count > IOV_MAX) count= IOV_MAX;
1129 ssize_t rs= writev(conn->fd, conn->xmit, count);
1131 if (isewouldblock(errno)) return OOP_CONTINUE;
1132 connfail(conn, "write failed: %s", strerror(errno));
1138 for (done=0; rs && done<conn->xmitu; done++) {
1139 struct iovec *vp= &conn->xmit[done];
1140 XmitDetails *dp= &conn->xmitd[done];
1141 if (rs > vp->iov_len) {
1149 int newu= conn->xmitu - done;
1150 memmove(conn->xmit, conn->xmit + done, newu * sizeof(*conn->xmit));
1151 memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1156 static void conn_make_some_xmits(Conn *conn) {
1158 if (conn->xmitu+5 > CONNIOVS)
1161 Article *art= LIST_REMHEAD(conn->priority);
1162 if (!art) art= LIST_REMHEAD(conn->waiting);
1165 if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1166 /* actually send it */
1168 ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1172 XMIT_LITERAL("TAKETHIS ");
1173 xmit_noalloc(conn, art->messageid, art->midlen);
1174 XMIT_LITERAL("\r\n");
1175 xmit_artbody(conn, artdata);
1178 /* we got 235 from IHAVE */
1180 xmit_artbody(conn, artdata);
1182 XMIT_LITERAL(".\r\n");
1187 art->state == art_Unchecked ? art_Unsolicited :
1188 art->state == art_Wanted ? art_Wanted :
1190 art->ipf->counts[art->state][RC_sent]++;
1191 LIST_ADDTAIL(conn->sent, art);
1197 XMIT_LITERAL("IHAVE ");
1199 XMIT_LITERAL("CHECK ");
1200 xmit_noalloc(conn, art->messageid, art->midlen);
1201 XMIT_LITERAL("\r\n");
1203 assert(art->state == art_Unchecked);
1204 art->ipf->counts[art->state][RC_sent]++;
1205 LIST_ADDTAIL(conn->sent, art);
1211 /*========== handling responses from peer ==========*/
1213 static const oop_rd_style peer_rd_style= {
1214 OOP_RD_DELIM_STRIP, '\n',
1216 OOP_RD_SHORTREC_FORBID
1219 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
1220 const char *errmsg, int errnoval,
1221 const char *data, size_t recsz, void *conn_v) {
1223 connfail(conn, "error receiving from peer: %s", errmsg);
1224 return OOP_CONTINUE;
1227 static Article *article_reply_check(Conn *conn, const char *response,
1228 int code_indicates_streaming,
1230 /* 1:yes, -1:no, 0:dontcare */,
1231 const char *sanitised_response) {
1232 Article *art= LIST_HEAD(conn->sent);
1236 "peer gave unexpected response when no commands outstanding: %s",
1237 sanitised_response);
1241 if (code_indicates_streaming) {
1242 assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1243 if (!conn->stream) {
1244 connfail(conn, "peer gave streaming response code "
1245 " to IHAVE or subsequent body: %s", sanitised_response);
1248 const char *got_mid= response+4;
1249 int got_midlen= strcspn(got_mid, " \n\r");
1250 if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1251 connfail(conn, "peer gave streaming response with syntactically invalid"
1252 " messageid: %s", sanitised_response);
1255 if (got_midlen != art->midlen ||
1256 memcmp(got_mid, art->messageid, got_midlen)) {
1257 connfail(conn, "peer gave streaming response code to wrong article -"
1258 " probable synchronisation problem; we offered: %s;"
1260 art->messageid, sanitised_response);
1265 connfail(conn, "peer gave non-streaming response code to"
1266 " CHECK/TAKETHIS: %s", sanitised_response);
1271 if (must_have_sent>0 && art->state < art_Wanted) {
1272 connfail(conn, "peer says article accepted but"
1273 " we had not sent the body: %s", sanitised_response);
1276 if (must_have_sent<0 && art->state >= art_Wanted) {
1277 connfail(conn, "peer says please sent the article but we just did: %s",
1278 sanitised_response);
1282 Article *art_again= LIST_REMHEAD(conn->sent);
1283 assert(art_again == art);
1287 static void update_nocheck(int accepted) {
1288 accept_proportion *= nocheck_decay;
1289 accept_proportion += accepted * (1.0 - nocheck_decay);
1290 int new_nocheck= accept_proportion >= nocheck_thresh;
1291 if (new_nocheck && !nocheck_reported) {
1292 notice("entering nocheck mode for the first time");
1293 nocheck_reported= 1;
1294 } else if (new_nocheck != nocheck) {
1295 debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1297 nocheck= new_nocheck;
1300 static void article_done(Conn *conn, Article *art, int whichcount) {
1301 art->ipf->counts[art->state][whichcount]++;
1302 if (whichcount == RC_accepted) update_nocheck(1);
1303 else if (whichcount == RC_unwanted) update_nocheck(0);
1305 InputFile *ipf= art->ipf;
1307 while (art->blanklen) {
1308 static const char spaces[]=
1313 int w= art->blanklen; if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1314 int r= pwrite(ipf->fd, spaces, w, art->offset);
1316 if (errno==EINTR) continue;
1317 sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1318 art->messageid, art->blanklen, art->offset, ipf->path);
1320 assert(r>=0 && r<=w);
1326 assert(ipf->inprogress >= 0);
1329 if (!ipf->inprogress && ipf != main_input_file)
1330 queue_check_input_done();
1333 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
1334 const char *errmsg, int errnoval,
1335 const char *data, size_t recsz, void *conn_v) {
1338 if (ev == OOP_RD_EOF) {
1339 connfail(conn, "unexpected EOF from peer");
1340 return OOP_CONTINUE;
1342 assert(ev == OOP_RD_OK);
1344 char *sani= sanitise(data);
1347 unsigned long code= strtoul(data, &ep, 10);
1348 if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1349 connfail(conn, "badly formatted response from peer: %s", sani);
1350 return OOP_CONTINUE;
1353 if (conn->quitting) {
1354 if (code!=205 && code!=503) {
1355 connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1357 notice("C%d idle connection closed", conn->fd);
1358 assert(!conn->waiting.count);
1359 assert(!conn->priority.count);
1360 assert(!conn->sent.count);
1361 assert(!conn->xmitu);
1362 LIST_REMOVE(conns,conn);
1365 return OOP_CONTINUE;
1368 conn->since_activity= 0;
1371 #define GET_ARTICLE(musthavesent) \
1372 art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1373 if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1375 #define ARTICLE_DEALTWITH(streaming,musthavesent,how) \
1376 code_streaming= (streaming); \
1377 GET_ARTICLE(musthavesent); \
1378 article_done(conn, art, RC_##how); break;
1380 #define PEERBADMSG(m) connfail(conn, m ": %s", sani); return OOP_CONTINUE
1382 int code_streaming= 0;
1386 case 400: PEERBADMSG("peer stopped accepting articles");
1387 case 503: PEERBADMSG("peer timed us out");
1388 default: PEERBADMSG("peer sent unexpected message");
1390 case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1391 case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1393 case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1394 case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1396 case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1397 case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1399 case 238: /* CHECK says send it */
1401 case 335: /* IHAVE says send it */
1403 assert(art->state == art_Unchecked);
1404 art->ipf->counts[art->state][RC_accepted]++;
1405 art->state= art_Wanted;
1406 LIST_ADDTAIL(conn->priority, art);
1409 case 431: /* CHECK or TAKETHIS says try later */
1411 case 436: /* IHAVE says try later */
1414 if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1416 sysfatal("write to defer file %s",path_defer);
1417 article_done(conn, art, RC_deferred);
1422 conn_maybe_write(conn);
1423 check_assign_articles();
1424 return OOP_CONTINUE;
1428 /*========== monitoring of input files ==========*/
1430 static void feedfile_eof(InputFile *ipf) {
1431 assert(ipf != main_input_file); /* promised by tailing_try_read */
1432 inputfile_reading_stop(ipf);
1434 if (ipf == flushing_input_file) {
1435 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1436 if (main_input_file) inputfile_reading_start(main_input_file);
1437 statemc_check_flushing_done();
1438 } else if (ipf == backlog_input_file) {
1439 statemc_check_backlog_done();
1441 abort(); /* supposed to wait rather than get EOF on main input file */
1445 static InputFile *open_input_file(const char *path) {
1446 int fd= open(path, O_RDONLY);
1448 if (errno==ENOENT) return 0;
1449 sysfatal("unable to open input file %s", path);
1453 InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1454 memset(ipf,0,sizeof(*ipf));
1457 strcpy(ipf->path, path);
1462 static void close_input_file(InputFile *ipf) { /* does not free */
1463 assert(!ipf->readable_callback); /* must have had ->on_cancel */
1464 assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1465 assert(!ipf->rd); /* must have had inputfile_reading_stop */
1466 assert(!ipf->inprogress); /* no dangling pointers pointing here */
1467 xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1471 /*---------- dealing with articles read in the input file ----------*/
1473 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1474 const char *data, const char *how) {
1475 warn("corrupted file: %s, offset %lu: %s: %s",
1476 ipf->path, (unsigned long)offset, how, sanitise(data));
1477 ipf->readcount_err++;
1478 if (ipf->readcount_err > max_bad_data_initial +
1479 (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1480 die("too much garbage in input file! (%d errs, %d ok, %d blank)",
1481 ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1482 return OOP_CONTINUE;
1485 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1486 oop_rd_event ev, const char *errmsg,
1487 int errnoval, const char *data, size_t recsz,
1489 InputFile *ipf= ipf_v;
1490 assert(ev == OOP_RD_SYSTEM);
1492 sysdie("error reading input file: %s, offset %lu",
1493 ipf->path, (unsigned long)ipf->offset);
1496 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1497 oop_rd_event ev, const char *errmsg,
1498 int errnoval, const char *data, size_t recsz,
1500 InputFile *ipf= ipf_v;
1502 char tokentextbuf[sizeof(TOKEN)*2+3];
1504 if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1506 off_t old_offset= ipf->offset;
1507 ipf->offset += recsz + 1;
1509 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1511 if (ev==OOP_RD_PARTREC)
1512 feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1513 /* but process it anyway */
1515 if (ipf->skippinglong) {
1516 if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1519 if (ev==OOP_RD_LONG) {
1520 ipf->skippinglong= 1;
1521 X_BAD_DATA("overly long line");
1524 if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1525 if (!recsz) X_BAD_DATA("empty line");
1528 if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1529 ipf->readcount_blank++;
1530 return OOP_CONTINUE;
1533 char *space= strchr(data,' ');
1534 int tokenlen= space-data;
1535 int midlen= (int)recsz-tokenlen-1;
1536 if (midlen <= 2) X_BAD_DATA("no room for messageid");
1537 if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1539 if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1540 memcpy(tokentextbuf, data, tokenlen);
1541 tokentextbuf[tokenlen]= 0;
1542 if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1544 ipf->readcount_ok++;
1546 art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1547 art->state= art_Unchecked;
1548 art->midlen= midlen;
1549 art->ipf= ipf; ipf->inprogress++;
1550 art->token= TextToToken(tokentextbuf);
1551 art->offset= ipf->offset;
1552 art->blanklen= recsz;
1553 strcpy(art->messageid, space+1);
1554 LIST_ADDTAIL(queue, art);
1556 if (sms==sm_NORMAL && ipf==main_input_file &&
1557 ipf->offset >= target_max_feedfile_size)
1558 statemc_start_flush("feed file size");
1560 check_assign_articles();
1561 return OOP_CONTINUE;
1564 /*========== tailing input file ==========*/
1566 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1568 InputFile *ipf= user;
1569 return ipf->readable_callback(loop, &ipf->readable,
1570 ipf->readable_callback_user);
1573 static void tailing_on_cancel(struct oop_readable *rable) {
1574 InputFile *ipf= (void*)rable;
1576 if (ipf->filemon) filemon_stop(ipf);
1577 loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1578 ipf->readable_callback= 0;
1581 static void tailing_queue_readable(InputFile *ipf) {
1582 /* lifetime of ipf here is OK because destruction will cause
1583 * on_cancel which will cancel this callback */
1584 loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1587 static int tailing_on_readable(struct oop_readable *rable,
1588 oop_readable_call *cb, void *user) {
1589 InputFile *ipf= (void*)rable;
1591 tailing_on_cancel(rable);
1592 ipf->readable_callback= cb;
1593 ipf->readable_callback_user= user;
1596 tailing_queue_readable(ipf);
1600 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1602 InputFile *ipf= (void*)rable;
1604 ssize_t r= read(ipf->fd, buffer, length);
1606 if (errno==EINTR) continue;
1610 if (ipf==main_input_file) {
1613 } else if (ipf==flushing_input_file) {
1615 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1616 } else if (ipf==backlog_input_file) {
1626 /*---------- filemon implemented with inotify ----------*/
1628 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1629 #define HAVE_FILEMON
1631 #include <linux/inotify.h>
1633 static int filemon_inotify_fd;
1634 static int filemon_inotify_wdmax;
1635 static InputFile **filemon_inotify_wd2ipf;
1637 struct Filemon_Perfile {
1641 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1642 int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1643 if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1645 if (wd >= filemon_inotify_wdmax) {
1647 filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1648 sizeof(*filemon_inotify_wd2ipf) * newmax);
1649 memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1650 sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1651 filemon_inotify_wdmax= newmax;
1654 assert(!filemon_inotify_wd2ipf[wd]);
1655 filemon_inotify_wd2ipf[wd]= ipf;
1657 debug("filemon inotify startfile %p wd=%d wdmax=%d",
1658 ipf, wd, filemon_inotify_wdmax);
1663 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1665 debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1666 int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1667 if (r) sysdie("inotify_rm_watch");
1668 filemon_inotify_wd2ipf[wd]= 0;
1671 static void *filemon_inotify_readable(oop_source *lp, int fd,
1672 oop_event e, void *u) {
1673 struct inotify_event iev;
1675 int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1677 if (isewouldblock(errno)) break;
1678 sysdie("read from inotify master");
1679 } else if (r==sizeof(iev)) {
1680 assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1682 die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1684 InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1685 debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1686 filemon_callback(ipf);
1688 return OOP_CONTINUE;
1691 static int filemon_method_init(void) {
1692 filemon_inotify_fd= inotify_init();
1693 if (filemon_inotify_fd<0) {
1694 syswarn("could not initialise inotify: inotify_init failed");
1698 loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1700 debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1704 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1706 /*---------- filemon dummy implementation ----------*/
1708 #if !defined(HAVE_FILEMON)
1710 struct Filemon_Perfile { int dummy; };
1712 static int filemon_method_init(void) { return 0; }
1713 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1714 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1716 #endif /* !HAVE_FILEMON */
1718 /*---------- filemon generic interface ----------*/
1720 static void filemon_start(InputFile *ipf) {
1721 assert(!ipf->filemon);
1723 ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1724 memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1725 filemon_method_startfile(ipf, ipf->filemon);
1728 static void filemon_stop(InputFile *ipf) {
1729 if (!ipf->filemon) return;
1730 filemon_method_stopfile(ipf, ipf->filemon);
1735 static void filemon_callback(InputFile *ipf) {
1736 ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1739 /*---------- interface to start and stop an input file ----------*/
1741 static const oop_rd_style feedfile_rdstyle= {
1742 OOP_RD_DELIM_STRIP, '\n',
1744 OOP_RD_SHORTREC_LONG,
1747 static void inputfile_reading_start(InputFile *ipf) {
1749 ipf->readable.on_readable= tailing_on_readable;
1750 ipf->readable.on_cancel= tailing_on_cancel;
1751 ipf->readable.try_read= tailing_try_read;
1752 ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1753 ipf->readable.delete_kill= 0;
1755 ipf->readable_callback= 0;
1756 ipf->readable_callback_user= 0;
1758 ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1761 int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1762 feedfile_got_article,ipf, feedfile_read_err, ipf);
1763 if (r) sysdie("unable start reading feedfile %s",ipf->path);
1766 static void inputfile_reading_stop(InputFile *ipf) {
1768 oop_rd_cancel(ipf->rd);
1769 oop_rd_delete(ipf->rd);
1771 assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1775 /*========== interaction with innd - state machine ==========*/
1777 /* See official state diagram at top of file. We implement
1788 |`---------------------------------------------------.
1790 |`---------------- - - - |
1791 D ENOENT | D EXISTS see OVERALL STATES diagram |
1792 | for full startup logic |
1795 | ============ try to |
1801 | | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT |
1802 ^ | hardlink F to D |
1805 | | our handle onto F is now onto D |
1808 | |<-------------------<---------------------<---------+
1810 | | spawn inndcomm flush |
1812 | ================== |
1813 | FLUSHING[-ABSENT] |
1815 | main D tail/none |
1816 | ================== |
1818 | | INNDCOMM FLUSH FAILS ^
1819 | |`----------------------->----------. |
1821 | | NO SUCH SITE V |
1822 ^ |`--------------->----. ==================== |
1823 | | \ FLUSHFAILED[-ABSENT] |
1825 | | FLUSH OK \ main D tail/none |
1826 | | open F \ ==================== |
1828 | | \ | TIME TO RETRY |
1829 | |`------->----. ,---<---'\ `----------------'
1830 | | D NONE | | D NONE `----.
1832 | ============= V V ============
1833 | SEPARATED-1 | | DROPPING-1
1834 | flsh->fd>0 | | flsh->fd>0
1835 | [Separated] | | [Dropping]
1836 | main F idle | | main none
1837 | old D tail | | old D tail
1838 | ============= | | ============
1840 ^ | EOF ON D | | defer | EOF ON D
1842 | =============== | | ===============
1843 | SEPARATED-2 | | DROPPING-2
1844 | flsh->fd==0 | V flsh->fd==0
1845 | [Finishing] | | [Dropping]
1846 | main F tail | `. main none
1847 | old D closed | `. old D closed
1848 | =============== V `. ===============
1850 | | ALL D PROCESSED `. | ALL D PROCESSED
1851 | V install defer as backlog `. | install defer
1852 ^ | close D `. | close D
1853 | | unlink D `. | unlink D
1856 `----------' ==============
1876 static void startup_set_input_file(InputFile *f) {
1877 assert(!main_input_file);
1879 inputfile_reading_start(f);
1882 static void statemc_init(void) {
1883 struct stat stab, stabf;
1885 path_lock= xasprintf("%s_lock", feedfile);
1886 path_flushing= xasprintf("%s_flushing", feedfile);
1887 path_defer= xasprintf("%s_defer", feedfile);
1888 globpat_backlog= xasprintf("%s_backlog*", feedfile);
1891 int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1892 if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1895 memset(&fl,0,sizeof(fl));
1897 fl.l_whence= SEEK_SET;
1898 int r= fcntl(lockfd, F_SETLK, &fl);
1900 if (errno==EACCES || isewouldblock(errno)) {
1901 if (quiet_multiple) exit(0);
1902 fatal("another duct holds the lockfile");
1904 sysdie("fcntl F_SETLK lockfile %s", path_lock);
1907 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
1909 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1911 if (!lock_noent && samefile(&stab, &stabf))
1915 sysdie("could not close stale lockfile %s", path_lock);
1917 debug("startup: locked");
1919 search_backlog_file();
1922 xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1924 debug("startup: ductdefer ENOENT");
1926 debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1927 switch (stab.st_nlink==1) {
1929 open_defer(); /* so that we will later close it and rename it */
1932 xunlink(path_defer, "stale defer file link"
1933 " (presumably hardlink to backlog file)");
1936 die("defer file %s has unexpected link count %d",
1937 path_defer, stab.st_nlink);
1941 struct stat stab_f, stab_d;
1944 InputFile *file_d= open_input_file(path_flushing);
1945 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
1947 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1949 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1950 debug("startup: F==D => Hardlinked");
1951 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1956 debug("startup: F ENOENT => Moved");
1957 if (file_d) startup_set_input_file(file_d);
1958 spawn_inndcomm_flush("feedfile missing at startup");
1959 /* => Flushing, sms:=FLUSHING */
1962 debug("startup: F!=D => Separated");
1963 startup_set_input_file(file_d);
1964 SMS(SEPARATED, 0, "found both old and current feed files");
1966 debug("startup: F exists, D ENOENT => Normal");
1967 InputFile *file_f= open_input_file(feedfile);
1968 if (!file_f) die("feed file vanished during startup");
1969 startup_set_input_file(file_f);
1970 SMS(NORMAL, flushfail_retry_periods, "normal startup");
1975 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1976 assert(sms == sm_NORMAL);
1978 debug("starting flush (%s) (%lu >?= %lu) (%d)",
1980 (unsigned long)(main_input_file ? main_input_file->offset : 0),
1981 (unsigned long)target_max_feedfile_size,
1984 int r= link(feedfile, path_flushing);
1985 if (r) sysdie("link feedfile %s to flushing file %s",
1986 feedfile, path_flushing);
1989 xunlink(feedfile, "old feedfile link");
1992 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
1995 static void statemc_period_poll(void) {
1996 if (!sm_period_counter) return;
1997 sm_period_counter--;
1998 assert(sm_period_counter>=0);
2000 if (sm_period_counter) return;
2003 statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2005 case sm_FLUSHFAILED:
2006 spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2013 static int inputfile_is_done(InputFile *ipf) {
2015 if (ipf->inprogress) return 0; /* new article in the meantime */
2016 if (ipf->rd) return 0; /* not had EOF */
2020 static void notice_processed(InputFile *ipf, const char *what,
2022 #define RCI_NOTHING(x) /* nothing */
2023 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2024 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2026 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2028 info("processed %s%s read=%d(+%dbl,+%derr)"
2029 " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2030 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2033 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2034 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2035 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2036 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2037 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2038 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
2044 static void statemc_check_backlog_done(void) {
2045 InputFile *ipf= backlog_input_file;
2046 if (!inputfile_is_done(ipf)) return;
2048 const char *slash= strrchr(ipf->path, '/');
2049 const char *leaf= slash ? slash+1 : ipf->path;
2050 const char *under= strchr(slash, '_');
2051 const char *rest= under ? under+1 : leaf;
2052 if (!strncmp(rest,"backlog",7)) rest += 7;
2053 notice_processed(ipf,"backlog:",rest);
2055 close_input_file(ipf);
2056 if (unlink(ipf->path)) {
2057 if (errno != ENOENT)
2058 sysdie("could not unlink processed backlog file %s", ipf->path);
2059 warn("backlog file %s vanished while we were reading it"
2060 " so we couldn't remove it (but it's done now, anyway)",
2064 backlog_input_file= 0;
2065 search_backlog_file();
2069 static void statemc_check_flushing_done(void) {
2070 InputFile *ipf= flushing_input_file;
2071 if (!inputfile_is_done(ipf)) return;
2073 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2075 notice_processed(ipf,"feedfile",0);
2079 xunlink(path_flushing, "old flushing file");
2081 close_input_file(flushing_input_file);
2082 free(flushing_input_file);
2083 flushing_input_file= 0;
2085 if (sms==sm_SEPARATED) {
2086 notice("flush complete");
2087 SMS(NORMAL, 0, "flush complete");
2088 } else if (sms==sm_DROPPING) {
2089 SMS(DROPPED, 0, "old flush complete");
2090 search_backlog_file();
2091 notice("feed dropped, but will continue until backlog is finished");
2095 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2097 assert(!inputfile_is_done(main_input_file));
2098 statemc_check_flushing_done();
2099 statemc_check_backlog_done();
2100 return OOP_CONTINUE;
2103 static void queue_check_input_done(void) {
2104 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2107 static void statemc_setstate(StateMachineState newsms, int periods,
2108 const char *forlog, const char *why) {
2110 sm_period_counter= periods;
2112 const char *xtra= "";
2114 case sm_FLUSHING: sm_FLUSHFAILED:
2115 if (!main_input_file) xtra= "-ABSENT";
2117 case sm_SEPARATED: case sm_DROPPING:
2118 xtra= flushing_input_file->rd ? "-1" : "-2";
2124 info("%s%s[%d] %s",forlog,xtra,periods,why);
2126 info("%s%s %s",forlog,xtra,why);
2130 /*---------- defer and backlog files ----------*/
2132 static void open_defer(void) {
2137 defer= fopen(path_defer, "a+");
2138 if (!defer) sysfatal("could not open defer file %s", path_defer);
2140 /* truncate away any half-written records */
2142 xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2144 if (stab.st_size > LONG_MAX)
2145 die("defer file %s size is far too large", path_defer);
2150 long orgsize= stab.st_size;
2151 long truncto= stab.st_size;
2153 if (!truncto) break; /* was only (if anything) one half-truncated record */
2154 if (fseek(defer, truncto-1, SEEK_SET) < 0)
2155 sysdie("seek in defer file %s while truncating partial", path_defer);
2160 sysdie("failed read from defer file %s", path_defer);
2162 die("defer file %s shrank while we were checking it!", path_defer);
2168 if (stab.st_size != truncto) {
2169 warn("truncating half-record at end of defer file %s -"
2170 " shrinking by %ld bytes from %ld to %ld",
2171 path_defer, orgsize - truncto, orgsize, truncto);
2174 sysfatal("could not flush defer file %s", path_defer);
2175 if (ftruncate(fileno(defer), truncto))
2176 sysdie("could not truncate defer file %s", path_defer);
2179 info("continuing existing defer file %s (%ld bytes)",
2180 path_defer, orgsize);
2182 if (fseek(defer, truncto, SEEK_SET))
2183 sysdie("could not seek to new end of defer file %s", path_defer);
2186 static void close_defer(void) {
2191 xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2193 if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2196 time_t now= xtime();
2198 char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2200 (unsigned long)stab.st_ino);
2201 if (link(path_defer, backlog))
2202 sysfatal("could not install defer file %s as backlog file %s",
2203 path_defer, backlog);
2204 if (unlink(path_defer))
2205 sysdie("could not unlink old defer link %s to backlog file %s",
2206 path_defer, backlog);
2210 if (until_backlog_nextscan < 0 ||
2211 until_backlog_nextscan > backlog_retry_minperiods + 1)
2212 until_backlog_nextscan= backlog_retry_minperiods + 1;
2215 static void poll_backlog_file(void) {
2216 if (until_backlog_nextscan < 0) return;
2217 if (until_backlog_nextscan-- > 0) return;
2218 search_backlog_file();
2221 static void search_backlog_file(void) {
2222 /* returns non-0 iff there are any backlog files */
2227 const char *oldest_path=0;
2228 time_t oldest_mtime, now;
2230 if (backlog_input_file) return;
2234 r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2238 sysdie("failed to expand backlog pattern %s", globpat_backlog);
2240 die("out of memory expanding backlog pattern %s", globpat_backlog);
2242 for (i=0; i<gl.gl_pathc; i++) {
2243 const char *path= gl.gl_pathv[i];
2245 if (strchr(path,'#') || strchr(path,'~')) {
2246 debug("backlog file search skipping %s", path);
2249 r= stat(path, &stab);
2251 syswarn("failed to stat backlog file %s", path);
2254 if (!S_ISREG(stab.st_mode)) {
2255 warn("backlog file %s is not a plain file (or link to one)", path);
2258 if (!oldest_path || stab.st_mtime < oldest_mtime) {
2260 oldest_mtime= stab.st_mtime;
2263 case GLOB_NOMATCH: /* fall through */
2266 sysdie("glob expansion of backlog pattern %s gave unexpected"
2267 " nonzero (error?) return value %d", globpat_backlog, r);
2273 debug("backlog scan: none");
2275 if (sms==sm_DROPPED) {
2276 notice("feed dropped and our work is complete");
2277 xunlink(path_lock, "lockfile for old feed");
2280 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2285 double age= difftime(now, oldest_mtime);
2286 long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2288 if (age_deficiency <= 0) {
2289 debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2290 age, age_deficiency, oldest_path);
2292 backlog_input_file= open_input_file(oldest_path);
2293 if (!backlog_input_file) {
2294 warn("backlog file %s vanished as we opened it", backlog_input_file);
2297 inputfile_reading_start(backlog_input_file);
2298 until_backlog_nextscan= -1;
2302 until_backlog_nextscan= age_deficiency / period_seconds;
2304 if (backlog_spontaneous_rescan_periods >= 0 &&
2305 until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2306 until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2308 debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2309 age, age_deficiency, until_backlog_nextscan, oldest_path);
2313 /*========== flushing the feed ==========*/
2315 static pid_t inndcomm_child;
2317 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2318 assert(inndcomm_child);
2319 int status= xwaitpid(&inndcomm_child, "inndcomm");
2320 cancel_fd_read_except(fd);
2323 assert(!flushing_input_file);
2325 if (WIFEXITED(status)) {
2326 switch (WEXITSTATUS(status)) {
2328 case INNDCOMMCHILD_ESTATUS_FAIL:
2331 case INNDCOMMCHILD_ESTATUS_NONESUCH:
2332 warn("feed has been dropped by innd, finishing up");
2333 flushing_input_file= main_input_file;
2334 tailing_queue_readable(flushing_input_file);
2335 /* we probably previously returned EAGAIN from our fake read method
2336 * when in fact we were at EOF, so signal another readable event
2337 * so we actually see the EOF */
2341 if (flushing_input_file) {
2342 SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2345 SMS(DROPPED, 0, "feed dropped by innd");
2346 search_backlog_file();
2348 return OOP_CONTINUE;
2352 flushing_input_file= main_input_file;
2353 tailing_queue_readable(flushing_input_file);
2355 main_input_file= open_input_file(feedfile);
2356 if (!main_input_file)
2357 die("flush succeeded but feedfile %s does not exist!", feedfile);
2359 if (flushing_input_file) {
2360 SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2363 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2365 return OOP_CONTINUE;
2368 goto unexpected_exitstatus;
2371 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2372 warn("flush timed out trying to talk to innd");
2375 unexpected_exitstatus:
2376 report_child_status("inndcomm child", status);
2380 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2383 static void inndcommfail(const char *what) {
2384 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2385 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2388 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2391 notice("flushing %s",why);
2393 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2394 assert(!inndcomm_child);
2396 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2398 inndcomm_child= xfork("inndcomm child");
2400 if (!inndcomm_child) {
2401 const char *flushargv[2]= { sitename, 0 };
2407 alarm(inndcomm_flush_timeout);
2408 r= ICCopen(); if (r) inndcommfail("connect");
2409 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
2410 if (!r) exit(0); /* yay! */
2412 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2413 syswarn("innd ctlinnd flush failed: innd said %s", reply);
2414 exit(INNDCOMMCHILD_ESTATUS_FAIL);
2418 int sentinel_fd= pipefds[0];
2419 on_fd_read_except(sentinel_fd, inndcomm_event);
2421 SMS(FLUSHING, 0, why);
2424 /*========== main program ==========*/
2426 static void postfork_inputfile(InputFile *ipf) {
2428 xclose(ipf->fd, "(in child) input file ", ipf->path);
2431 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2432 /* we have no stdio streams that are buffered long-term */
2434 if (fclose(f)) sysdie("close (in child) %s%s", what, what2?what2:0);
2437 static void postfork(const char *what) {
2438 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2439 sysdie("%s child: failed to reset SIGPIPE");
2441 postfork_inputfile(main_input_file);
2442 postfork_inputfile(flushing_input_file);
2445 for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2446 close_perhaps(&conn->fd);
2448 postfork_stdio(defer, "defer file ", path_defer);
2451 #define EVERY(what, interval_sec, interval_usec, body) \
2452 static struct timeval what##_timeout = { interval_sec, interval_usec }; \
2453 static void what##_schedule(void); \
2454 static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2456 what##_schedule(); \
2458 static void what##_schedule(void) { \
2459 loop->on_time(loop, what##_timeout, what##_timedout, 0); \
2462 EVERY(filepoll, 5,0, {
2463 if (main_input_file && main_input_file->readable_callback)
2464 filemon_callback(main_input_file);
2467 #define DEBUGF_IPF(wh) " " #wh "=%p/%s:ip=%ld,off=%ld,fd=%d%s"
2468 #define DEBUG_IPF(wh) \
2469 wh##_input_file, debug_ipf_path(wh##_input_file), \
2470 wh##_input_file->inprogress, (long)wh##_input_file->offset, \
2471 wh##_input_file->fd, wh##_input_file->rd ? "+" : ""
2472 static const char *debug_ipf_path(InputFile *ipf) {
2473 char *slash= strrchr(ipf->path,'/');
2474 return slash ? slash+1 : ipf->path;
2477 EVERY(period, -1,0, {
2479 " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2480 " input_files" DEBUGF_IPF(main) DEBUGF_IPF(old) DEBUGF_IPF(flushing)
2481 " children connecting=%ld inndcomm_child"
2483 sms_names[sms], sm_period_counter,
2484 queue.count, conns.count, until_connect,
2485 DEBUG_IPF(main), DEBUG_IPF(flushing), DEBUG_IPF(flushing),
2486 (long)connecting_child, (long)inndcomm_child
2489 if (until_connect) until_connect--;
2491 poll_backlog_file();
2492 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2493 statemc_period_poll();
2494 check_assign_articles();
2499 /*========== option parsing ==========*/
2501 /*---------- generic option parser and logging ----------*/
2503 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2504 static void vbadusage(const char *fmt, va_list al) {
2507 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2508 static void badusage(const char *fmt, ...) {
2515 of_seconds= 001000u,
2516 of_boolean= 002000u,
2519 typedef struct Option Option;
2520 typedef void OptionParser(const Option*, const char *val);
2530 /*---------- specific option types ----------*/
2532 static void op_integer(const Option *o, const char *val) {
2535 unsigned long ul= strtoul(val,&ep,10);
2536 if (*ep || ep==val || errno || ul>INT_MAX)
2537 badusage("bad integer value for %s",o->lng);
2538 int *store= o->store;
2542 static void op_double(const Option *o, const char *val) {
2543 int *store= o->store;
2546 *store= strtod(val, &ep);
2547 if (*ep || ep==val || errno)
2548 badusage("bad floating point value for %s",o->lng);
2551 static void op_string(const Option *o, const char *val) {
2552 const char **store= o->store;
2556 static void op_seconds(const Option *o, const char *val) {
2557 int *store= o->store;
2561 double v= strtod(val,&ep);
2562 if (ep==val) badusage("bad time/duration value for %s",o->lng);
2564 if (!*ep || !strcmp(ep,"s")) unit= 1;
2565 else if (!strcmp(ep,"m")) unit= 60;
2566 else if (!strcmp(ep,"h")) unit= 3600;
2567 else if (!strcmp(ep,"d")) unit= 86400;
2568 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2572 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2576 static void op_periods_rndup(const Option *o, const char *val) {
2577 int *store= o->store;
2579 *store += period_seconds-1;
2580 *store /= period_seconds;
2583 static void op_setint(const Option *o, const char *val) {
2584 int *store= o->store;
2588 /*---------- specific options ----------*/
2590 static const Option options[]= {
2591 {'f',"feedfile", &feedfile, op_string },
2592 {'q',"quiet-multiple", &quiet_multiple, op_setint, 1,1 },
2594 { 0, "max-connections", &max_connections, op_integer },
2595 { 0, "max-queue-per-conn", &max_queue_per_conn, op_integer },
2598 { 0, "streaming", &try_stream, op_setint, 1,1 },
2599 { 0, "no-streaming", &try_stream, op_setint, 1,0 },
2600 {'P',"port", &port, op_integer },
2601 { 0, "inndconf", &inndconffile, op_string },
2602 {'d',"daemon", &become_daemon, op_setint, 1,1 },
2603 { 0, "no-daemon", &become_daemon, op_setint, 1,0 },
2605 { 0, "no-check-proportion", &nocheck_thresh_pct, op_double },
2606 { 0, "no-check-filter", &nocheck_decay_articles, op_double },
2608 { 0, "reconnect-interval", &reconnect_delay_periods, op_periods_rndup },
2609 { 0, "flush-retry-interval", &flushfail_retry_periods, op_periods_rndup },
2610 { 0, "inndcomm-timeout", &inndcomm_flush_timeout, op_seconds },
2613 int main(int argc, char **argv) {
2619 if (*arg != '-') break;
2620 if (!strcmp(arg,"--")) { arg= *++argv; break; }
2622 while ((a= *++arg)) {
2626 char *equals= strchr(arg,'=');
2627 int len= equals ? (equals - arg) : strlen(arg);
2628 for (o=options; o->lng; o++)
2629 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2631 badusage("unknown long option --%s",arg);
2634 if (equals) badusage("option --%s does not take a value",o->lng);
2636 } else if (equals) {
2640 if (!arg) badusage("option --%s needs a value",o->lng);
2643 break; /* eaten the whole argument now */
2645 for (o=options; o->lng; o++)
2648 badusage("unknown short option -%c",a);
2655 if (!arg) badusage("option -%c needs a value",o->shrt);
2658 break; /* eaten the whole argument now */
2663 if (!arg) badusage("need site name argument");
2669 if (*++argv) badusage("too many non-option arguments");
2671 if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2672 badusage("nocheck threshold percentage must be between 0..100");
2673 nocheck_thresh= nocheck_thresh_pct * 0.01;
2675 if (nocheck_decay_articles < 0.1)
2676 badusage("nocheck decay articles must be at least 0.1");
2677 nocheck_decay= 1 - 1/nocheck_decay_articles;
2680 pathoutgoing= innconf->pathoutgoing;
2681 innconf_read(inndconffile);
2684 feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2685 else if (!feedfile[0])
2686 badusage("feed filename must be nonempty");
2687 else if (feedfile[strlen(feedfile)-1]=='/')
2688 feedfile= xasprintf("%s%s",feedfile,sitename);
2690 const char *feedfile_forbidden= "?*[~#";
2692 while ((c= *feedfile_forbidden++))
2693 if (strchr(feedfile, c))
2694 badusage("feed filename may not contain metacharacter %c",c);
2696 oop_source_sys *sysloop= oop_sys_new();
2697 if (!sysloop) sysdie("could not create liboop event loop");
2698 loop= (oop_source*)sysloop;
2700 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2701 sysdie("could not ignore SIGPIPE");
2703 if (become_daemon) {
2705 for (i=3; i<255; i++)
2706 /* do this now before we open syslog, etc. */
2708 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2710 int null= open("/dev/null",O_RDWR);
2711 if (null<0) sysdie("failed to open /dev/null");
2717 pid_t child1= xfork("daemonise first fork");
2718 if (child1) _exit(0);
2720 pid_t sid= setsid();
2721 if (sid != child1) sysdie("setsid failed");
2723 pid_t child2= xfork("daemonise second fork");
2724 if (child2) _exit(0);
2732 if (!filemon_method_init()) {
2733 warn("no file monitoring available, polling");
2734 filepoll_schedule();
2737 period_timeout.tv_sec= period_seconds;
2742 void *r= oop_sys_run(sysloop);
2743 assert(r == OOP_ERROR);
2744 sysdie("event loop failed");