chiark / gitweb /
f3be2b7613f07014e5174e4c274b9c70765c0611
[innduct.git] / backends / innduct.c
1 /*
2  * Newsfeeds file entries should look like this:
3  *     host.name.of.site[/exclude,exclude,...]\
4  *             :pattern,pattern...[/distribution,distribution...]\
5  *             :Tf,Wnm
6  *             :
7  * or
8  *     sitename[/exclude,exclude,...]\
9  *             :pattern,pattern...[/distribution,distribution...]\
10  *             :Tf,Wnm
11  *             :host.name.of.site
12  *
13  * Four files full of
14  *    token messageid
15  * or might be blanked out
16  *    <spc><spc><spc><spc>....
17  *
18  *   site.name_duct.lock       lock preventing multiple ducts
19  *                                holder of this lock is "duct"
20  * F site.name                 main feed file
21  *                                opened/created, then written, by innd
22  *                                read by duct
23  *                                unlinked by duct
24  *                                tokens blanked out by duct when processed
25  * D site.name_duct            temporary feed file during flush (or crash)
26  *                                hardlink created by duct
27  *                                unlinked by duct
28  *   site.name_duct.defer      431'd articles, still being written,
29  *                                created, written, used by duct
30  *   site.name_backlog.lock    lock taken out by innxmit wrapper
31  *                                holder and its child are "xmit"
32  *   site.name_backlog_<date>.<inum>
33  *                             431'd articles, ready for innxmit
34  *                                created (link/mv) by duct
35  *                                read by xmit
36  *                                unlinked by xmit
37  *   site.name_backlog_<letters> eg
38  *   site.name_backlog_manual
39  *                             anything the sysadmin likes (eg, feed files
40  *                             from old feeds to be merged into this one)
41  *                                created (link/mv) by admin
42  *                                read by xmit
43  *                                unlinked by xmit
44
45
46
47
48  BLATHER ABOUT NOT USING INNXMIT
49
50  scan for backlog files
51  take "old enough" backlog files one at a time and reprocess them
52  so need another input file - the current backlog file
53  inhibit scanning for backlog files only when
54    - last file not "old enough"
55    - no backlog files found and we haven't made one
56
57  also we have to start a new backlog file every (some interval)
58
59
60
61  
62    OVERALL STATES:
63
64                                                                 START
65                                                                   |
66                                                              check D, F
67                                                                   |
68                           <--------------------------------------'|
69         Nothing                            F, D both ENOENT       |
70          F: ENOENT                                                |
71          D: ENOENT                                                |
72          duct: not not reading anything                           |
73            |                                                      |
74            |`---------------------.                               |
75            |                      | duct times out waiting for F  |
76            V  innd creates F      | duct exits                    |
77            |                      V                               |
78         Noduct                    GO TO Dropped                   |
79          F: innd writing                                          |
80          D: ENOENT                                                |
81          duct: not running or not reading anything                |
82            |                                                      |
83            |                                                      |
84      ,-->--+                   <---------------------------------'|
85      |     |  duct opens F                         F exists       |
86      |     |                                       D ENOENT       |
87      |     V                                                      |
88      |  Normal                                                    |
89      |   F: innd writing, duct reading                            |
90      |   D: ENOENT                                                |
91      |     |                                                      |
92      |     |  duct decides time to flush                          |
93      |     |  duct makes hardlink                                 |
94      |     |                                                      |
95      |     V                            <------------------------'|
96      |  Hardlinked                                  F==D          |
97      |   F == D: innd writing, duct reading         both exist    |
98      ^     |                                                      |
99      |     |  duct unlinks F                                      |
100      |     V                                                      |
101      |  Moved                               <----+------------<--'|
102      |   F: ENOENT                               |  F ENOENT      |
103      |   D: innd writing, duct reading           |  D exists      |
104      |     |                                     |                |
105      |     |  duct requests flush of feed        |                |
106      |     |   (others can too, harmlessly)      |                |
107      |     V                                     |                |
108      |  Flushing                                 |                |
109      |   F: ENOENT                               |                |
110      |   D: innd flushing, duct reading          |                |
111      |     |                                     |                |
112      |     |   inndcomm flush fails              |                |
113      |     |`-------------------------->---------'                |
114      |     |                                                      |
115      |     |   inndcomm reports no such site                      |
116      |     |`---------------------------------------------------- | -.
117      |     |                                                      |  |
118      |     |  innd finishes writing D, creates F                  |  |
119      |     |  inndcomm reports flush successful                   |  |
120      |     |                                                      |  |
121      |     V                                                      |  |
122      |  Separated                                <----------------'  |
123      |   F: innd writing                            F!=D             /
124      |   D: duct reading                             both exist     /
125      |     |                                                       /
126      |     |  duct gets to the end of D                           /
127      |     |  duct opens F too                                   /
128      |     V                                                    /
129      |  Finishing                                              /
130      |   F: innd writing, duct reading                        |
131      |   D: duct finishing                                    V
132      |     |                                            Dropping
133      |     |  duct finishes processing D                 F: ENOENT
134      |     V  duct unlinks D                             D: duct reading
135      |     |                                                  |
136      `--<--'                                                  | duct finishes
137                                                               |  processing D
138                                                               | duct unlinks D
139                                                               | duct exits
140                                                               V
141                                                         Dropped
142                                                          F: ENOENT
143                                                          D: ENOENT
144                                                          duct not running
145
146    "duct reading" means innduct is reading the file but also
147    overwriting processed tokens.
148
149  *
150  *
151  */
152
153
154 /*----- general definitions, probably best not changed -----*/
155
156 #define PERIOD_SECONDS 60
157
158 #define CONNCHILD_ESTATUS_STREAM   4
159 #define CONNCHILD_ESTATUS_NOSTREAM 5
160
161 #define INNDCOMMCHILD_ESTATUS_FAIL     6
162 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
163
164
165 /*----- configuration options -----*/
166
167 static char *sitename, *feedfile;
168 static int max_connections=10, max_queue_per_conn=200;
169 static int connection_setup_timeout=200, port=119, try_stream=1;
170 static int inndcomm_flush_timeout=100, quiet_if_locked=0;
171 static const char *remote_host;
172 static int reconnect_delay_periods, flushfail_retry_periods, open_wait_periods;
173 static const char *inndconffile;
174
175 static double accept_proportion;
176 static double nocheck_thresh_pct= 95.0;
177 static double nocheck_thresh; /* computed in main from _pct */
178 static double nocheck_decay_articles= 100; /* converted to _decay */
179 static double nocheck_decay; /* computed in main from _articles */
180 static int nocheck, nocheck_reported;
181
182
183 /*----- doubly linked lists -----*/
184
185 #define ISNODE(T)    T *next, *back;
186 #define LIST(T)      struct { T *head, *tail, *tailpred; int count; }
187
188 #define NODE(n) ((struct node*)&(n)->head)
189
190 #define LIST_ADDHEAD(l,n)                                               \
191  (list_addhead((struct list*)&(l), NODE((n))), (void)(l).count++)
192 #define LIST_ADDTAIL(l,n)                                               \
193  (list_addtail((struct list*)&(l), NODE((n))), (void)(l).count++)
194
195 #define LIST_REMHEAD(l)                                                   \
196  ((l).count ? ((l).count--, (void*)list_remhead((struct list*)&(l))) : 0)
197 #define LIST_REMTAIL(l)                                                   \
198  ((l).count ? ((l).count--, (void*)list_remtail((struct list*)&(l))) : 0)
199 #define LIST_REMOVE(l,n)                        \
200  (list_remove(NODE((n))), (void)(l).count--)
201 #define LIST_INSERT(l,n,pred) \
202  (list_insert((struct list*)&(l), NODE((n)), NODE((pred))), (void)(l).count++)
203
204
205 /*----- statistics -----*/
206
207 #define RESULT_COUNTS                           \
208   RC(offered)                                   \
209   RC(sent)                                      \
210   RC(unwanted)                                  \
211   RC(accepted)                                  \
212   RC(rejected)                                  \
213   RC(deferred)
214
215 typedef enum {
216 #define RC_INDEX(x) RCI_##x
217   RESULT_COUNTS
218   RCI_max
219 } ResultCountIndex;
220
221 typedef struct {
222   int articles[2 /* checked */][RCI_max];
223 } Counts;
224
225
226 /*----- transmission buffers -----*/
227
228 #define CONNIOVS 128
229
230 typedef enum {
231   xk_Malloc, xk_Const, xk_Artdata;
232 } XmitKind;
233
234 typedef struct {
235   XmitKind kind;
236   union {
237     char *malloc_tofree;
238     ARTHANDLE *sm_art;
239   } info;
240 } XmitDetails;
241
242
243 /*----- core operational data structure types -----*/
244
245 struct Article {
246   int midlen;
247   int checked, sentbody;
248   InputFile *ipf;
249   TOKEN token;
250   off_t offset;
251   int blanklen;
252   char messageid[1];
253 };
254
255 typedef struct {
256   /* This is an instance of struct oop_readable */
257   struct oop_readable readable; /* first */
258   oop_readable_call *readable_callback;
259   void *readable_callback_user;
260
261   int fd;
262   const char *path; /* ptr copy of path_<foo> or feedfile */
263   struct Filemon_Perfile *filemon;
264
265   oop_read *rd;
266   long inprogress; /* no. of articles read but not processed */
267   off_t offset;
268 } InputFile;
269
270 typedef enum {
271   sm_WAITING,
272   sm_NORMAL,
273   sm_FLUSHING,
274   sm_FLUSHFAIL,
275   sm_SEPARATED1,
276   sm_SEPARATED2, /* must follow SEPARATED2 - see feedfile_eof */
277   sm_DROPPING1,
278   sm_DROPPING2, /* must follow DROPPING1 - see feedfile_eof */
279 } StateMachineState;
280
281 struct Conn {
282   ISNODE(Conn);
283   int fd, max_queue, stream;
284   LIST(Article) queue; /* not yet told peer, or CHECK said send it */
285   LIST(Article) sent; /* offered/transmitted - in xmit or waiting reply */
286   struct iovec xmit[CONNIOVS];
287   XmitDetails xmitd[CONNIOVS];
288   int xmitu;
289 };
290
291
292 /*----- operational variables -----*/
293
294 static int since_connect_attempt;
295 static int nconns;
296 static LIST(Conn) idle, working, full;
297 static LIST(Article) *queue;
298
299 static char *path_ductlock, *path_duct, *path_ductdefer;
300
301 #define SMS(newstate, periods, why) \
302    (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
303
304 static StateMachineState sms;
305 static FILE *defer;
306 static InputFile *main_input_file, *old_input_file;
307 static int sm_period_counter;
308
309
310 /*----- function predeclarations -----*/
311
312 static void conn_check_work(Conn *conn);
313
314 static int filemon_init(void);
315 static void filemon_setfile(int mainfeed_fd, const char *mainfeed_path);
316 static void filemon_callback(void);
317
318 static void statemc_setstate(StateMachineState newsms, int periods,
319                              const char *forlog, const char *why);
320
321 /*========== utility functions etc. ==========*/
322
323 static void perhaps_close(int *fd) { if (*fd) { close(*fd); fd=0; } }
324
325 static pid_t xfork(const char *what) {
326   pid_t child;
327
328   child= fork();
329   if (child==-1) sysdie("cannot fork for %s",what);
330   if (!child) postfork(what);
331   return child;
332 }
333
334 static void on_fd_read_except(int fd, oop_call_fd callback) {
335   loop->on_fd(loop, fd, OOP_READ,      callback, 0);
336   loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
337 }
338 static void cancel_fd_read_except(int fd) {
339   loop->cancel_fd(loop, fd, OOP_READ);
340   loop->cancel_fd(loop, fd, OOP_EXCEPTION);
341 }
342
343 static void report_child_status(const char *what, int status) {
344   if (WIFEXITED(status)) {
345     int es= WEXITSTATUS(status);
346     if (es)
347       warn("%s: child died with error exit status %d",es);
348   } else if (WIFSIGNALED(status)) {
349     int sig= WTERMSIG(status);
350     const char *sigstr= strsignal(sig);
351     const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
352     if (sigstr)
353       warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
354     else
355       warn("%s: child died due to unknown fatal signal %d%s",
356            what, sig, coredump);
357   } else {
358     warn("%s: child died with unknown wait status %d", status);
359   }
360 }
361
362 static int xwaitpid(pid_t *pid, const char *what) {
363   int status;
364
365   r= kill(*pid, SIGKILL);
366   if (r) sysdie("cannot kill %s child", what);
367
368   pid_t got= waitpid(*pid, &status, WNOHANG);
369   if (got==-1) sysdie("cannot reap %s child", what);
370
371   *pid= 0;
372
373   return status;
374 }
375
376 /*========== logging ==========*/
377
378 static void logcore(int sysloglevel, const char *fmt, ...)
379      __attribute__((printf,2,3))
380 static void logcore(int sysloglevel, const char *fmt, ...) {
381   va_list al;
382   va_start(al,fmt);
383   if (become_daemon) {
384     vsyslog(sysloglevel,fmt,al);
385   } else {
386     vfprintf(stderr,fmt,al);
387     putc('\n',stderr);
388   }
389 }
390
391 static void logv(int sysloglevel, const char *pfx, int errnoval,
392                  int exitstatus, const char *fmt, va_list al)
393      __attribute__((printf,4,0))
394 static void logv(int sysloglevel, const char *pfx, int errnoval,
395                  int exitstatus, const char *fmt, va_list al) {
396   char msgbuf[256];
397   vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
398   msgbuf[sizeof(msgbuf)-1]= 0;
399
400   if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
401     sysloglevel= LOG_ERR; /* run by wrong user, probably */
402
403   logcore(sysloglevel, "<%s>%s: %s%s%s",
404          sitename, pfx, msgbuf,
405          errnoval>=0 ? ": " : "",
406          errnoval>=0 ? strerror(errnoval) : "");
407 }
408
409 #define logwrap(fn, pfx, sysloglevel, errno, estatus)   \
410   static void fn(const char *fmt, ...)                  \
411       __attribute__((printf,1,2));                      \
412   static void fn(const char *fmt, ...) {                \
413     va_list al;                                         \
414     va_start(al,fmt);                                   \
415     logv(sysloglevel, pfx, errno, estatus, fmt, al);    \
416   }
417
418 logwrap(sysdie,   " critical", LOG_CRIT,   errno, 16);
419 logwrap(die,      " critical", LOG_CRIT,   -1,    16);
420
421 logwrap(sysfatal, " fatal",    LOG_ERR,    errno, 12);
422 logwrap(fatal,    " fatal",    LOG_ERR,    -1,    12);
423
424 logwrap(syswarn,  " warning",  LOG_WARN,   errno, 0);
425 logwrap(warn,     " warning",  LOG_WARN,   -1,    0);
426
427 logwrap(notice,   "",          LOG_NOTICE, -1,    0);
428 logwrap(info,     " info",     LOG_INFO,   -1,    0);
429
430
431 /*========== making new connections ==========*/
432
433 static int connecting_sockets[2]= {-1,-1};
434 static pid_t connecting_child;
435
436 static void connect_attempt_discard(void) {
437   if (connecting_sockets[0])
438     cancel_fd(connecting_sockets[0]);
439
440   perhaps_close(&connecting_sockets[0]);
441   perhaps_close(&connecting_sockets[1]);
442
443   if (connecting_child) {
444     int status= xwaitpid(&connecting_child, "connect");
445
446     if (!(WIFEXITED(status) ||
447           (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
448       report_child_status("connect", status);
449   }
450 }
451
452 #define PREP_DECL_MSG_CMSG(msg)                 \
453   struct msghdr msg;                            \
454   memset(&msg,0,sizeof(msg));                   \
455   char msg##cbuf[CMSG_SPACE(sizeof(fd))];       \
456   msg.msg_control= msg##cbuf;                   \
457   msg.msg_controllen= sizeof(msg##cbuf);
458
459 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
460   Conn *conn= 0;
461
462   conn= xmalloc(sizeof(*conn));
463   memset(conn,0,sizeof(*conn));
464
465   DECL_MSG_CMSG(msg);
466   struct cmsghdr *h= 0;
467   ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
468   if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
469   if (!h) {
470     int status;
471     pid_t got= waitpid(connecting_child, &status, WNOHANG);
472     if (got != -1) {
473       assert(got==connecting_child);
474       connecting_child= 0;
475       if (WIFEXITED(status) &&
476           (WEXITSTATUS(status) != 0
477            WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
478            WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)) {
479         /* child already reported the problem */
480       } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALARM) {
481         warn("connect: connection attempt timed out");
482       } else if (!WIFEXITED(status)) {
483         report_child_status("connect", status);
484         /* that's probably the root cause then */
485       }
486     } else {
487       /* child is still running apparently, report the socket problem */
488       if (rs < 0)
489         syswarn("connect: read from child socket failed");
490       else if (e == OOP_EXCEPTIONN)
491         warn("connect: unexpected exception on child socket");
492       else
493         warn("connect: unexpected EOF on child socket");
494     }
495     goto x;
496   }
497
498 #define CHK(field, val)                                                   \
499   if (h->cmsg_##field != val) {                                           \
500     die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d"); \
501     goto x;                                                               \
502   }
503   CHK(level, SOL_SOCKET);
504   CHK(type,  SCM_RIGHTS);
505   CHK(len,   CMSG_LEN(sizeof(conn-b>fd)));
506 #undef CHK
507
508   if (CMSG_NXTHDR,&msg,h) { die("connect: child sent many cmsgs"); goto x; }
509
510   memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
511
512   pid_t got= waitpid(connecting_child, &status, 0);
513   if (got==-1) sysdie("connect: real wait for child");
514   assert(got == connecting_child);
515   connecting_child= 0;
516
517   if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
518   int es= WEXITSTATUS(status);
519   switch (es) {
520   case CONNCHILD_ESTATUS_STREAM:    conn->stream= 1;   break;
521   case CONNCHILD_ESTATUS_NOSTREAM:  conn->stream= 0;   break;
522   default:
523     fatal("connect: child gave unexpected exit status %d", es);
524   }
525
526   set nonblocking;
527
528   /* Phew! */
529   LIST_ADDHEAD(idle, conn);
530   notice(CN "connected %s", conn->fd, conn->stream ? "streaming" : "plain");
531   connect_attempt_discard();
532   check_master_queue();
533   return 0;
534
535  x:
536   if (conn) {
537     perhaps_close(&conn->fd);
538     free(conn);
539   }
540   connect_attempt_discard();
541 }
542
543 static void connect_start() {
544   assert(!connecting_sockets[0]);
545   assert(!connecting_sockets[1]);
546   assert(!connecting_child);
547
548   notice("starting connection attempt");
549
550   r= socketpair(AF_UNIX, SOCK_STREAM, 0, connecting_sockets);
551   if (r) { syswarn("connect: cannot create socketpair for child"); goto x; }
552
553   connecting_child= xfork("connection");
554
555   if (!connecting_child) {
556     FILE *cn_from, *cn_to;
557     char buf[NNTP_STRLEN+100];
558     int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
559
560     r= close(connecting_sockets[0]);
561     if (r) sysdie("connect: close parent socket in child");
562
563     alarm(connection_setup_timeout);
564     if (NNTPconnect(remote_host, port, &cn_from, &cn_to, buf) < 0) {
565       if (buf[0]) {
566         sanitise_inplace(buf);
567         fatal("connect: rejected: %s", buf);
568       } else {
569         sysfatal("connect: connection attempt failed");
570       }
571     }
572     if (NNTPsendpassword(remote_host, cn_from, cn_to) < 0)
573       sysfatal("connect: authentication failed");
574     if (try_stream) {
575       if (fputs("MODE STREAM\r\n", cn_to) ||
576           fflush(cn_to))
577         sysfatal("connect: could not send MODE STREAM");
578       buf[sizeof(buf)-1]= 0;
579       if (!fgets(buf, sizeof(buf)-1, cn_from)) {
580         if (ferror(cn_from))
581           sysfatal("connect: could not read response to MODE STREAM");
582         else
583           fatal("connect: connection close in response to MODE STREAM");
584       }
585       int l= strlen(buf);
586       assert(l>=1);
587       if (buf[-1]!='\n') {
588         sanitise_inplace(buf);
589         fatal("connect: response to MODE STREAM is too long: %.100s...",
590             remote_host, buf);
591       }
592       l--;  if (l>0 && buf[1-]=='\r') l--;
593       buf[l]= 0;
594       char *ep;
595       int rcode= strtoul(buf,&ep,10);
596       if (ep != buf[3]) {
597         sanitise_inplace(buf);
598         fatal("connect: bad response to MODE STREAM: %.50s", buf);
599       }
600       switch (rcode) {
601       case 203:
602         exitstatus= CONNCHILD_ESTATUS_STREAM;
603         break;
604       case 480:
605       case 500:
606         break;
607       default:
608         sanitise_inplace(buf);
609         warn("connect: unexpected response to MODE STREAM: %.50s", buf);
610         exitstatus= 2;
611         break;
612       }
613     }
614     int fd= fileno(cn_from);
615
616     PREP_DECL_MSG_CMSG(msg);
617     struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
618     cmsg->cmsg_level= SOL_SOCKET;
619     cmsg->cmsg_type=  SCM_RIGHTS;
620     cmsg->cmsg_len=   CMSG_LEN(sizeof(fd));
621     memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
622
623     msg.msg_controllen= cmsg->cmsg_len;
624     r= sendmsg(connecting_sockets[1], &msg, 0);
625     if (r) sysdie("sendmsg failed for new connection");
626
627     _exit(exitstatus);
628   }
629
630   r= close(connecting_sockets[1]);  connecting_sockets[1]= 0;
631   if (r) sysdie("connect: close child socket in parent");
632
633   on_fd_read_except(connecting_sockets[0], connchild_event);
634   return OOP_CONTINUE;
635
636  x:
637   connect_attempt_discard();
638 }
639
640
641 /*========== overall control of article flow ==========*/
642
643 static void check_master_queue(void) {
644   try reading current feed file;
645
646   if (!queue.count)
647     return;
648
649   Conn *last_assigned=0;
650   for (;;) {
651     if (working.head) {
652       conn_assign_one_article(&working, &last_assigned);
653     } else if (idle.head) {
654       conn_assign_one_article(&idle, &last_assigned);
655     } else if (nconns < maxconns && queue.count >= max_queue_per_conn &&
656                !connecting_child && !connect_delay) {
657       connect_delay= reconnect_delay_periods;
658       connect_start();
659     } else {
660       break;
661     }
662   }
663   conn_check_work(last_assigned);
664 }
665
666 static void conn_assign_one_article(LIST(Conn) *connlist,
667                                     Conn **last_assigned) {
668   Conn *conn= connlist->head;
669
670   LIST_REMOVE(*connlist, conn);
671   Article *art= LIST_REMHEAD(queue);
672   LIST_ADDTAIL(conn->queue, art);
673   LIST_ADD(*conn_determine_right_list(conn), conn);
674
675   /* This slightly odd arrangement is so that we call conn_check_work
676    * once after filling the queue for a new connection in
677    * check_master_queue, rather than for each article. */
678   if (conn != *last_assigned && *last_assigned)
679     conn_check_work(*last_assigned);
680   *last_assigned= conn;
681 }
682
683 static int conn_total_queued_articles(Conn *conn) {
684   return conn->sent.count + conn->queue.count;
685 }
686
687 static LIST(Conn) *conn_determine_right_list(Conn *conn) {
688   int inqueue= conn_total_queued_articles(conn);
689   assert(inqueue <= max_queue);
690   if (inqueue == 0) return &idle;
691   if (inqueue == conn->max_queue) return &full;
692   return &working;
693 }
694
695 static void *conn_writeable(oop_source *l, int fd, int ev, void *u) {
696   check_conn_work(u);
697   return OOP_CONTINUE;
698 }
699
700 static void conn_check_work(Conn *conn)  {
701   void *rp= 0;
702   for (;;) {
703     conn_make_some_xmits(conn);
704     if (!conn->xmitu) {
705       loop->cancel_fd(loop, conn->fd, OOP_WRITE);
706       return;
707     }
708
709     void *rp= conn_write_some_xmits(conn);
710     if (rp==OOP_CONTINUE) {
711       loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
712       return;
713     } else if (rp==OOP_HALT) {
714       return;
715     } else if (!rp) {
716       /* transmitted everything */
717     } else {
718       abort();
719     }
720   }
721 }
722
723
724 /*========== article transmission ==========*/
725
726 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
727                   XmitKind kind) { /* caller must then fill in details */
728   struct iovec *v= &conn->xmit[conn->xmitu];
729   XmitDetails *d= &conn->xmitd[conn->xmitu++];
730   v->iov_base= data;
731   v->iov_len= len;
732   d->kind= kind;
733   return d;
734 }
735
736 static void xmit_noalloc(Conn *conn, const char *data, int len) {
737   xmit_core(conn,data,len, xk_Const);
738 }
739 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
740
741 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
742   XmitDetails *d= xmit_core(conn, ah->data, ah->len, sk_Artdata);
743   d->info.sm_art= ah;
744 }
745
746 static void xmit_free(XmitDetails *d) {
747   switch (d->kind) {
748   case xk_Malloc:  free(d->info.malloc_tofree);   break;
749   case xk_Artdata: SMfreearticle(d->info.sm_art); break;
750   case xk_Const:                                  break;
751   default: abort();
752   }
753 }
754
755 static void *conn_write_some_xmits(Conn *conn) {
756   /* return values:
757    *      0:            nothing more to write, no need to call us again
758    *      OOP_CONTINUE: more to write but fd not writeable
759    *      OOP_HALT:     disaster, have destroyed conn
760    */
761   for (;;) {
762     int count= conn->xmitu;
763     if (!count) return 0;
764
765     if (count > IOV_MAX) count= IOV_MAX;
766     ssize_t rs= writev(conn->fd, conn->xmit, count);
767     if (rs < 0) {
768       if (errno == EAGAIN) return OOP_CONTINUE;
769       connfail(conn, "write failed: %s", strerror(errno));
770       return OOP_HALT;
771     }
772     assert(rs > 0);
773
774     for (done=0; rs && done<xmitu; done++) {
775       struct iovec *vp= &conn->xmit[done];
776       XmitDetails *dp= &conn->xmitd[done];
777       if (rs > vp->iov_len) {
778         rs -= vp->iov_len;
779         xmit_free(dp);
780       } else {
781         vp->iov_base += rs;
782         vp->iov_len -= rs;
783       }
784     }
785     int newu= conn->xmitu - done;
786     memmove(conn->xmit,  conn->xmit  + done, newu * sizeof(*conn->xmit));
787     memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
788     conn->xmitu= newu;
789   }
790 }
791
792 static void conn_make_some_xmits(Conn *conn) {
793   for (;;) {
794     if (conn->xmitu+5 > CONNIOVS)
795       break;
796
797     Article *art= LIST_REMHEAD(queue);
798     if (!art) break;
799
800     if (art->checked || (conn->stream && nocheck)) {
801       /* actually send it */
802
803       ARTHANDLE *artdata= SMretrieve();
804
805       if (conn->stream) {
806         if (artdata) {
807           XMIT_LITERAL("TAKETHIS ");
808           xmit_noalloc(conn, art->mid, art->midlen);
809           XMIT_LITERAL("\r\n");
810           xmit_artbody(conn, artdata);
811         }
812       } else {
813         /* we got 235 from IHAVE */
814         if (artdata) {
815           xmit_artbody(conn, artdata);
816         } else {
817           XMIT_LITERAL(".\r\n");
818         }
819       }
820
821       art->sent= 1;
822       LIST_ADDTAIL(conn->sent, art);
823
824       counts[art->checked].sent++;
825
826     } else {
827       /* check it */
828
829       if (conn->stream)
830         XMIT_LITERAL("IHAVE ");
831       else
832         XMIT_LITERAL("CHECK ");
833       xmit_noalloc(art->mid, art->midlen);
834       XMIT_LITERAL("\r\n");
835
836       LIST_ADDTAIL(conn->sent, art);
837       counts[art->checked].offered++;
838     }
839   }
840 }
841
842
843 /*========== handling responses from peer ==========*/
844
845 static const oop_rd_style peer_rd_style= {
846   OOP_RD_DELIM_STRIP, '\n',
847   OOP_RD_NUL_FORBID,
848   OOP_RD_SHORTREC_FORBID
849 };
850
851 static Article *article_reply_check(Connection *conn, const char *response,
852                                     int code_indicates_streaming,
853                                     const char *sanitised_response) {
854   Article *art= LIST_REMHEAD(conn->sent);
855
856   if (!art) {
857     connfail(conn,
858              "peer gave unexpected response when no commands outstanding: %s",
859              sanitised_response);
860     return 0;
861   }
862
863   if (code_indicates_streaming) {
864     assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
865     if (!conn->stream) {
866       connfail("peer gave streaming response code "
867                " to IHAVE or subsequent body: %s", sanitised_response);
868       return 0;
869     }
870     const char *got_mid= response+4;
871     int got_midlen= strcspn(got_mid, " \n\r");
872     if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
873       connfail("peer gave streaming response with syntactically invalid"
874                " messageid: %s", sanitised_response);
875       return 0;
876     }
877     if (got_midlen != art->midlen ||
878         memcmp(got_mid, art->messageid, got_midlen)) {
879       connfail("peer gave streaming response code to wrong article -"
880                " probable synchronisation problem; we offered: %s;"
881                " peer said: %s",
882                art->messageid, sanitised_response);
883       return 0;
884     }
885   } else {
886     if (conn->stream) {
887       connfail("peer gave non-streaming response code to CHECK/TAKETHIS: %s",
888                sanitised_response);
889       return 0;
890     }
891   }
892
893   return art;
894 }
895
896 static void update_nocheck(int accepted) {
897   accept_proportion *= accept_decay;
898   accept_proportion += accepted;
899   nocheck= accept_proportion >= nocheck_thresh;
900   if (nocheck && !nocheck_reported) {
901     notice("entering nocheck mode for the first time");
902     nocheck_reported= 1;
903   }
904 }
905
906 static void article_done(Connection *conn, Article *art, int whichcount) {
907   *count++;
908   counts.articles[art->checked][whichcount]++;
909   if (whichcount == RC_accepted) update_nocheck(1);
910   else if (whichcount == RC_unwanted) update_nocheck(0);
911
912   InputFile *ipf= art->ipf;
913   while (art->blanklen) {
914     static const char spaces[]=
915       "                                                                "
916       "                                                                "
917       "                                                                "
918       "                                                                ";
919     int w= art->blanklen;  if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
920     int r= pwrite(ipf->fd, spaces, w, art->offset);
921     if (r==-1) {
922       if (errno==EINTR) continue;
923       sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
924              art->messageid, art->blanklen, art->offset, ipf->path);
925     }
926     assert(r>=0 && r<=w);
927     art->blanklen -= w;
928     art->offset += w;
929   }
930
931   ipf->inprogress--;
932   assert(ipf->inprogress >= 0);
933
934   if (!ipf->inprogress)
935     loop->on_time(loop, OOP_TIME_NOW, statemc_check_oldinput_done, 0);
936
937   free(art);
938 }
939
940 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_event ev,
941                          const char *errmsg, int errnoval,
942                          const char *data, size_t recsz, void *conn_v) {
943   Conn *conn= conn_v;
944   connfail(conn, "error receiving from peer: %s", errmsg);
945   return OOP_CONTINUE;
946 }
947
948 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_event ev,
949                         const char *errmsg, int errnoval,
950                         const char *data, size_t recsz, void *conn_v) {
951   Conn *conn= conn_v;
952
953   if (ev == OOP_RD_EOF) {
954     connfail(conn, "unexpected EOF from peer");
955     return OOP_CONTINUE;
956   }
957   assert(ev == OOP_RD_OK);
958
959   char *ep;
960   unsigned long code= strtoul(data, &ep, 10);
961   if (ep != data+3 || *ep != ' ' || data[0]=='0') {
962     char sanibuf[100];
963     const char *p= data;
964     char *q= sanibuf;
965     *q++= '`';
966     for (;;) {
967       if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"..."); break; }
968       int c= *p++;
969       if (!c) { *q++= '\''; break; }
970       if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
971       sprintf(q,"\\x%02x",c);
972       q += 4;
973     }
974     connfail(conn, "badly formatted response from peer: %s", sanibuf);
975     return OOP_CONTINUE;
976   }
977
978   if (conn->quitting) {
979     if (code!=205) {
980       connfail(conn, "peer gave failure response to QUIT: %s", sani);
981       return OOP_CONTINUE;
982     }
983     conn close ok;
984     return;
985   }
986
987   Article *art;
988
989 #define GET_ARTICLE                                                         \
990   art= article_reply_check(conn, data, code_streaming, sani);               \
991   if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
992
993 #define ARTICLE_DEALTWITH(streaming,how)                        \
994   code_streaming= (streaming)                                   \
995   GET_ARTICLE;                                                  \
996   article_done(conn, art, RC_##how);  break;
997
998 #define PEERBADMSG(m) connfail(conn, m ": %s", sani);  return OOP_CONTINUE
999
1000   int code_streaming= 0;
1001
1002   switch (code) {
1003
1004   case 400: PEERBADMSG("peer stopped accepting articles");
1005   case 503: PEERBADMSG("peer timed us out");
1006   default:  PEERBADMSG("peer sent unexpected message");
1007
1008   case 435: ARTICLE_DEALTWITH(0,unwanted); /* IHAVE says they have it */
1009   case 438: ARTICLE_DEALTWITH(1,unwanted); /* CHECK/TAKETHIS: they have it */
1010
1011   case 235: ARTICLE_DEALTWITH(0,accepted); /* IHAVE says thanks */
1012   case 239: ARTICLE_DEALTWITH(1,accepted); /* TAKETHIS says thanks */
1013
1014   case 437: ARTICLE_DEALTWITH(0,rejected); /* IHAVE says rejected */
1015   case 439: ARTICLE_DEALTWITH(1,rejected); /* TAKETHIS says rejected */
1016
1017   case 238: /* CHECK says send it */
1018     code_streaming= 1;
1019   case 335: /* IHAVE says send it */
1020     GET_ARTICLE;
1021     count_checkedwanted++;
1022     LIST_ADDTAIL(conn->queue);
1023     if (art->checked) {
1024       connfail("peer gave %d response to article body: %s",code, sani);
1025       return OOP_CONTINUE;
1026     }
1027     art->checked= 1;
1028     break;
1029
1030   case 431: /* CHECK or TAKETHIS says try later */
1031     code_streaming= 1;
1032   case 436: /* IHAVE says try later */
1033     GET_ARTICLE;
1034     if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1035         || fflush(defer))
1036       sysfatal("write to defer file %s",path_ductdefer);
1037     article_done(conn, art, RC_deferred);
1038     break;
1039
1040   }
1041
1042   check_check_work(conn);
1043   return OOP_CONTINUE;
1044 }
1045
1046
1047 /*========== monitoring of input files ==========*/
1048
1049 static void feedfile_eof(InputFile *ipf) {
1050   assert(ipf != main_input_file); /* promised by tailing_try_read */
1051   assert(ipf == old_input_file);
1052
1053   if (sms==sm_SEPARATED1) SMS(SEPARATED2, 0, "eof on old feed file");
1054   else if (sms==sm_DROPPING1) SMS(DROPPING2, 0, "eof on dead feed file");
1055   else abort();
1056   
1057   inputfile_tailing_stop(ipf);
1058   if (main_input_file)
1059     inputfile_tailing_start(main_input_file);
1060 }
1061
1062 static InputFile *open_input_file(const char *path) {
1063   int fd= open(path, O_RDONLY);
1064   if (fd<0) {
1065     if (errno==ENOENT) return 0;
1066     sysfatal("unable to open input file %s", path);
1067   }
1068
1069   InputFile *ipf= xmalloc(sizeof(InputFile));
1070   memset(ipf,0,sizeof(*ipf));
1071
1072   ipf->readable.on_readable= tailing_on_readable;
1073   ipf->readable.on_cancel=   tailing_on_cancel;
1074   ipf->readable.try_read=    tailing_try_read;
1075
1076   ipf->fd= fd;
1077   ipf->path= path;
1078
1079   return ipf;
1080 }
1081
1082 static void close_input_file(InputFile *ipf) {
1083   assert(!ipf->readable_callback); /* must have had ->on_cancel */
1084   assert(!ipf->filemon); /* must have had inputfile_tailing_stop */
1085   assert(!ipf->rd); /* must have had inputfile_tailing_stop */
1086   assert(!ipf->inprogress); /* no dangling pointers pointing here */
1087
1088   if (close(ipf->fd)) sysdie("could not close input file %s", ipf->path);
1089   free(ipf);
1090 }
1091
1092
1093 /*---------- dealing with articles read in the input file ----------*/
1094
1095 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1096                                    oop_rd_event ev, const char *errmsg,
1097                                    int errnoval,
1098                                    const char *data, size_t recsz,
1099                                    void *ipf_v) {
1100   InputFile *ipf= ipf_v;
1101   Article *art;
1102   char tokentextbuf[sizeof(TOKEN)*2+3];
1103
1104   if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1105
1106   if (data[0] && data[0]!=' ') {
1107     char *space= strchr(data,' ');
1108     int tokenlen= space-data;
1109     int midlen= (int)recsz-tokenlen-1;
1110     if (midlen < 0) goto bad_data;
1111
1112     if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1113     memcpy(tokentextbuf, data, tokenlen);
1114     tokentextbuf[tokenlen]= 0;
1115     if (!IsToken(tokentextbuf)) goto bad_data;
1116
1117     art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1118     art->offset= ipf->offset;
1119     art->blanklen= recsz;
1120     art->midlen= midlen;
1121     art->checked= art->sentbody= 0;
1122     art->ipf= ipf;  ipf->inprogress++;
1123     art->token= TextToToken(tokentextbuf);
1124     strcpy(art->messageid, space+1);
1125     LIST_ADDTAIL(queue, art);
1126   }
1127   ipf->offset += recsz + 1;
1128
1129   if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
1130     notice("starting flush (%lu >= %lu)",
1131            (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1132
1133     int r= link(feedfile, duct_path);
1134     if (r) sysdie("link feedfile %s to ductfile %s", feedfile, dut_path);
1135     /* => Hardlinked */
1136
1137     r= unlink(feedfile);
1138     if (r) sysdie("unlink old feedfile link %s", feedfile);
1139     /* => Moved */
1140
1141     spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1142   }
1143
1144   check_master_queue();
1145 }
1146
1147
1148 /*========== tailing input file ==========*/
1149
1150 static void filemon_start(InputFile *ipf) {
1151   assert(!ipf->filemon);
1152
1153   ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1154   memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1155   filemon_method_startfile(ipf, ipf->filemon);
1156 }
1157
1158 static void filemon_stop(InputFile *ipf) {
1159   if (!ipf->filemon) return;
1160   filemon_method_stopfile(ipf, ipf->filemon);
1161   free(ipf->filemon);
1162   ipf->filemon= 0;
1163 }
1164
1165 static void filemon_callback(InputFile *ipf) {
1166   ipf->readable_callback(ipf->readable_callback_user);
1167 }
1168
1169 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1170                                      void *user) {
1171   InputFile *ipf= user;
1172   return ipf->readable_callback(ipf->readable_callback_user);
1173 }
1174
1175 static void on_cancel(struct oop_readable *rable) {
1176   InputFile *ipf= (void*)rable;
1177
1178   if (ipf->filemon) filemon_stopfile(ipf);
1179   loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1180   ipf->readable_callback= 0;
1181 }
1182
1183 static int tailing_on_readable(struct oop_readable *rable,
1184                                 oop_readable_call *cb, void *user) {
1185   InputFile *ipf= (void*)rable;
1186
1187   tailing_on_cancel(rable);
1188   ipf->readable_callback= cb;
1189   ipf->readable_callback_user= user;
1190   filemon_startfile(ipf);
1191
1192   loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1193   return 0;
1194 }
1195
1196 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1197                                 size_t length) {
1198   InputFile *ipf= (void*)rable;
1199   for (;;) {
1200     ssize_t r= read(ipf->fd, buffer, length);
1201     if (r==-1) {
1202       if (errno==EINTR) continue;
1203       return r;
1204     }
1205     if (!r) {
1206       if (ipf==main_input_file) { errno=EAGAIN; return -1; }
1207       assert(sms==sm_SEPARATED1 || sms==sm_DROPPING1);
1208     }
1209     return r;
1210   }
1211 }
1212
1213 /*---------- filemon implemented with inotify ----------*/
1214
1215 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1216 #define HAVE_FILEMON
1217
1218 #include <linux/inotify.h>
1219
1220 static int filemon_inotify_fd;
1221 static int filemon_inotify_wdmax;
1222 static InputFile **filemon_inotify_wd2ipf;
1223
1224 typedef struct Filemon_Perfile {
1225   int wd;
1226 } Filemon_Inotify_Perfile;
1227
1228 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1229   int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1230   if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1231
1232   if (wd >= filemon_inotify_wdmax) {
1233     int newmax= wd+2;
1234     filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1235                                  sizeof(*filemon_inotify_wd2ipf) * newmax);
1236     memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1237            sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1238     filemon_inotify_wdmax= newmax;
1239   }
1240
1241   assert(!filemon_inotify_wd2ipf[wd]);
1242   filemon_inotify_wd2ipf[wd]= ipf;
1243
1244   pf->wd= wd;
1245 }
1246
1247 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1248   int wd= pf->wd;
1249   int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1250   if (r) sysdie("inotify_rm_watch");
1251   filemon_inotify_wd2ipf[wd]= 0;
1252 }
1253
1254 static void *filemon_inotify_readable(oop_source *lp, int fd,
1255                                       oop_event e, void *u) {
1256   struct inotify_event iev;
1257   for (;;) {
1258     int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1259     if (r==-1) {
1260       if (errno==EAGAIN) break;
1261       sysdie("read from inotify master");
1262     } else if (r==sizeof(iev)) {
1263       assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1264     } else {
1265       die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1266     }
1267     InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1268     filemon_callback(ipf);
1269   }
1270   return OOP_CONTINUE;
1271 }
1272
1273 static int filemon_method_init(void) {
1274   filemon_inotify_fd= inotify_init();
1275   if (filemon_inotify_fd<0) {
1276     syswarn("could not initialise inotify: inotify_init failed");
1277     return 0;
1278   }
1279   set nonblock;
1280   loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1281
1282   return 1;
1283 }
1284
1285 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1286
1287 /*---------- filemon dummy implementation ----------*/
1288
1289 #if !defined(HAVE_FILEMON)
1290
1291 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1292
1293 static int filemon_method_init(void) { return 0; }
1294 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1295 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1296
1297 #endif /* !HAVE_FILEMON */
1298
1299 /*---------- interface to start and stop an input file ----------*/
1300
1301 static const oop_rd_style feedfile_rdstyle= {
1302   OOP_RD_DELIM_STRIP, '\n',
1303   OOP_RD_NUL_FORBID,
1304   OOP_RD_SHORTREC_EOF,
1305 };
1306
1307 static void inputfile_tailing_start(InputFile *ipf) {
1308   assert(!ipf->fd);
1309   ipf->readable->on_readable= tailing_on_readable;
1310   ipf->readable->on_cancel=   tailing_on_cancel;
1311   ipf->readable->try_read=    tailing_try_read;
1312   ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1313   ipf->readable->delete_kill= 0;
1314
1315   ipf->readable_callback= 0;
1316   ipf->readable_callback_user= 0;
1317
1318   ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1319   assert(ipf->fd);
1320
1321   int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1322                      feedfile_got_article,ipf, feedfile_problem,ipf);
1323   if (r) sysdie("unable start reading feedfile %s",ipf->path);
1324 }
1325
1326 static void inputfile_tailing_stop(InputFile *ipf) {
1327   assert(ipf->fd);
1328   oop_rd_delete(ipf->rd);
1329   ipf->rd= 0;
1330   assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1331 }
1332
1333
1334 /*========== interaction with innd ==========*/
1335
1336 /* See official state diagram at top of file.  We implement
1337  * this as follows:
1338
1339            ================
1340             WAITING
1341            [Nothing/Noduct]
1342             poll for F
1343            ================
1344                 |
1345                 |     TIMEOUT
1346                 |`--------------------------.
1347                 |                           | install defer as backlog
1348                 | OPEN F SUCCEEDS           | exit
1349      ,--------->|                           V
1350      |          V                         =========
1351      |     ========                        (ESRCH)
1352      |      NORMAL                        [Dropped]
1353      |     [Normal]                       =========
1354      |      main F tail
1355      |     ========
1356      |          |
1357      |          | F IS SO BIG WE SHOULD FLUSH
1358      ^          | hardlink F to D
1359      |     [Hardlinked]
1360      |          | unlink F
1361      |          | our handle onto F is now onto D
1362      |     [Moved]
1363      |          |
1364      |          |<---------------------------------------------------.
1365      |          |                                                    |
1366      |          | spawn inndcomm flush                               |
1367      |          V                                                    |
1368      |     ==========                                                |
1369      |      FLUSHING                                                 |
1370      |     [Flushing]                                                |
1371      |      main D tail                                              |
1372      |     ==========                                                |
1373      |          |                                                    |
1374      |          |   INNDCOMM FLUSH FAILS                             ^
1375      |          |`----------------------->----------.                |
1376      |          |                                   |                |
1377      |          |   NO SUCH SITE                    V                |
1378      ^          |`--------------->----.          ===========         |
1379      |          |                      \         FLUSHFAIL           |
1380      |          |                       \        [Moved]             |
1381      |          |                        \       main D tail         |
1382      |          |                         \      ===========         |
1383      |          |                          \        |                |
1384      |          |                           \       | TIME TO RETRY  |
1385      |          |                            \      `----------------'
1386      |          | FLUSH OK                    \
1387      |          | open F                       \
1388      |          V                               V
1389      |     =============                     ============
1390      |      SEPARATED1                        DROPPING1
1391      |     [Separated]                       [Dropping]
1392      |      main F idle                       main none
1393      |      old  D tail                       old  D tail
1394      |     =============                     ============
1395      |          |                                 |
1396      ^          | EOF ON D                        | EOF ON D
1397      |          V                                 V
1398      |     =============                     ============
1399      |      SEPARATED2                        DROPPING2
1400      |     [Finishing]                       [Dropping]
1401      |      main F tail                       main none
1402      |      old  D idle                       old  D idle
1403      |     =============                     ============
1404      |          |                                |
1405      |          | ALL D PROCESSED                | ALL D PROCESSED
1406      |          V install defer as backlog       V install defer as backlog
1407      ^          | close D                        | close D
1408      |          | unlink D                       | unlink D
1409      |          | start new defer                | exit
1410      |          |                                V
1411      `----------'                            ==========
1412                                               (ESRCH)
1413                                              [Droppped]
1414                                              ==========
1415  */
1416
1417 static void open_defer(void) {
1418   struct stat stab;
1419
1420   assert(!defer);
1421   defer= fopen(path_ductdefer, "a+");
1422   if (!defer) sysfatal("could not open defer file %s", path_ductdefer);
1423
1424   /* truncate away any half-written records */
1425
1426   r= fstat(fileno(defer), &stab);
1427   if (r) sysdie("could not stat newly opened defer file %s", path_ductdefer);
1428
1429   if (stab.st_size > LONG_MAX)
1430     die("defer file %s size is far too large", path_ductdefer);
1431
1432   if (!stab.st_size)
1433     return;
1434
1435   long orgsize= stab.st_size;
1436   long truncto= stab.st_size;
1437   for (;;) {
1438     if (!truncto) break; /* was only (if anything) one half-truncated record */
1439     if (fseek(defer, truncto-1, SEEK_SET) < 0)
1440       sysdie("seek in defer file %s while truncating partial", path_ductdefer);
1441
1442     r= getc(defer);
1443     if (r==EOF) {
1444       if (ferror(defer))
1445         sysdie("failed read from defer file %s", path_ductdefer);
1446       else
1447         die("defer file %s shrank while we were checking it!", path_ductdefer);
1448     }
1449     if (r=='\n') break;
1450     truncto--;
1451   }
1452
1453   if (stab.st_size != truncto) {
1454     warn("truncating half-record at end of defer file %s -"
1455          " shrinking by %ld bytes from %ld to %ld",
1456          path_ductdefer, orgsize - truncto, orgsize, truncto);
1457
1458     if (fflush(defer))
1459       sysfatal("could not flush defer file %s", path_ductdefer);
1460     if (ftruncate(fileno(defer), truncto))
1461       sysdie("could not truncate defer file %s", path_ductdefer);
1462
1463   } else {
1464     info("continuing existing defer file %s (%ld bytes)",
1465          path_ductdefer, orgsize);
1466   }
1467   if (fseek(defer, truncto, SEEK_SET))
1468     sysdie("could not seek to new end of defer file %s", path_ductdefer);
1469 }
1470
1471 static void statemc_init(void) {
1472   struct stat stab;
1473
1474   path_ductlock=  xasprintf("%s_duct.lock",  feedfile);
1475   path_duct=      xasprintf("%s_duct",       feedfile);
1476   path_ductdefer= xasprintf("%s_duct.defer", feedfile);
1477
1478   if (lstat(path_ductdefer, &stab)) {
1479     if (errno!=ENOENT) sysdie("could not check defer file %s", path_defer);
1480   } else {
1481     if (!S_ISREG(stab.st_mode))
1482       die("defer file %s not a plain file (mode 0%lo)",
1483           path_defer, (unsigned long)stab.st_mode);
1484     switch (stab.st_nlink==1) {
1485     case 1: /* ok */ break;
1486     case 2:
1487       if (unlink(path_defer))
1488         sysdie("could not unlink stale defer file link %s (presumably"
1489                " hardlink to backlog file)", path_defer);
1490       break;
1491     default:
1492       die("defer file %s has unexpected link count %d",
1493           path_defer, stab.st_nlink);
1494     }
1495   }
1496   open_defer();
1497
1498   int lockfd= open(path_ductlock, O_CREAT|O_RDWR, 0600);
1499   if (lockfd<0) sysfatal("open lockfile %s", path_ductlock);
1500
1501   struct flock fl;
1502   memset(&fl,0,sizeof(fl));
1503   fl.l_type= F_WRLCK;
1504   fl.l_whence= SEEK_SET;
1505   r= fcntl(lockfd, F_SETLK, &fl);
1506   if (r==-1) {
1507     if (errno==EACCES || errno==EAGAIN) {
1508       if (quiet_if_locked) exit(0);
1509       fatal("another duct holds the lockfile");
1510     }
1511     sysdie("fcntl F_SETLK lockfile %s", path_ductlock);
1512   }
1513
1514   InputFile *file_d= open_input_file(path_duct);
1515
1516   if (file_d) {
1517     struct stat stab_f, stab_d;
1518
1519     r= stat(feedfile, &stab_f);
1520     if (r) {
1521       if (errno!=ENOENT) sysdie("check feed file %s", feedfile);
1522       /* D exists, F ENOENT => Moved */
1523       goto found_moved;
1524     }
1525
1526     /* F and D both exist */
1527
1528     r= fstat(file_d->fd, &stab_d);
1529     if (r) sysdie("check duct file %s", ductfile);
1530
1531     if (stab_d.st_ino == stab_f.st_ino &&
1532         stab_d.st_dev == stab_f.st_dev) {
1533       /* F==D => Hardlinked*/
1534       r= unlink(path_duct);
1535       if (r) sysdie("unlink feed file %s during startup", feedfile);
1536     found_moved:
1537       /* => Moved */
1538       startup_set_input_file(file_d);
1539       spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1540     } else {
1541       /* F!=D => Separated */
1542       SMS(SEPARATED1, 0, "found both old and current feed files");
1543       startup_set_input_file(file_d);
1544     }
1545   } else { /*!file_d*/
1546     SMS(WAITING, open_wait_periods, "no feed file currently exists");
1547   }
1548 }
1549
1550 static void statemc_poll(void) {
1551   if (sms==sm_WAITING) { statemc_waiting_poll(); return; }
1552
1553   if (!sm_period_counter) return;
1554   sm_period_counter--;
1555   assert(sm_period_counter>=0);
1556
1557   if (sm_period_counter) return;
1558   switch (sms) {
1559   case sm_WAITING:
1560     fatal("timed out waiting for innd to create feed file %s", feedfile);
1561   case sm_FLUSHFAIL:
1562     spawn_inndcomm_flush(void);
1563     break;
1564   default:
1565     abort();
1566   }
1567 }
1568
1569 static void statemc_waiting_poll(void) {
1570   InputFile *file_f= open_input_file(feedfile);
1571   if (!file_f) return;
1572   startup_set_input_file(file_d);
1573   SMS(NORMAL, 0, "found and opened feed file");
1574 }
1575
1576 static void startup_set_input_file(InputFile *f) {
1577   assert(!main_input_file);
1578   main_input_file= f;
1579   inputfile_tailing_start(f);
1580 }
1581
1582 static void *statemc_check_oldinput_done(oop_source *lp,
1583                                          struct timeval now, void *u) {
1584   struct stat stab;
1585
1586   int done= (sms==sm_SEPARATED2 || sms==sm_DROPPING2)
1587          && old_input_file->inprogress;
1588   if (!done) return;
1589
1590   r= fstat(fileno(defer), &stab);
1591   if (r) sysdie("check defer file %s", path_defer);
1592
1593   if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1594   defer= 0;
1595
1596   char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1597                            (unsigned long)now.tv_sec,
1598                            (unsigned long)stab.st_ino);
1599   if (link(path_defer, path_backlog))
1600     sysfatal("could not install defer file %s as backlog file %s",
1601            path_defer, backlog);
1602   if (unlink(path_defer))
1603     sysdie("could not unlink old defer link %s to backlog file %s",
1604            path_defer, backlog);
1605
1606   if (unlink(path_duct))
1607     sysdie("could not unlink old duct file %s", path_duct);
1608
1609   if (sms==sm_DROPPING2) {
1610     notice("feed dropped and our work is complete"
1611            " (but check for backlog files)");
1612     exit(0);
1613   }
1614
1615   open_defer();
1616
1617   close_input_file(old_input_file);
1618   old_input_file= 0;
1619
1620   notice("flush complete");
1621   SMS(NORMAL, 0, "flush complete");
1622 }
1623
1624 static void statemc_setstate(StateMachineState newsms, int periods,
1625                              const char *forlog, const char *why) {
1626   sms= newsms;
1627   sm_period_counter= periods;
1628   if (periods) {
1629     info("%s[%d] %s",periods,forlog,why);
1630   } else {
1631     info("%s %s",forlog,why);
1632   }
1633 }
1634
1635 /*========== flushing the feed ==========*/
1636
1637 static pid_t inndcomm_child;
1638
1639 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1640   assert(inndcomm_child);
1641   int status= xwaitpid(&inndcomm_child, "inndcomm");
1642   loop->cancel_fd(fd);
1643   close(fd);
1644
1645   assert(!old_input_file);
1646
1647   if (WIFEXITED(status)) {
1648     switch (WEXITSTATUS(status)) {
1649       
1650     case INNDCOMMCHILD_ESTATUS_FAIL:
1651       goto failed;
1652
1653     case INNDCOMMCHILD_ESTATUS_NONESUCH:
1654       warn("feed has been dropped by innd, finishing up");
1655       old_input_file= main_input_file;
1656       main_input_file= 0;
1657       SMS(DROPPING1, 0, "dropped by innd");
1658       return OOP_CONTINUE;
1659
1660     case 0:
1661       old_input_file= main_input_file;
1662       main_input_file= open_input_file(feedfile);
1663       if (!main_input_file)
1664         die("flush succeeded but feedfile %s does not exist!", feedfile);
1665       SMS(SEPARATED1, 0, "feed file missing");
1666       return OOP_CONTINUE;
1667
1668     default:
1669       goto unexpected_exitstatus;
1670       
1671     }
1672   } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1673     warn("flush timed out trying to talk to innd");
1674     goto failed;
1675   } else {
1676   unexpected_exitstatus:
1677     report_child_status("inndcomm child", status);
1678   }
1679
1680  failed:
1681   SMS(FLUSHFAIL, flushfail_retry_periods, "flush failed, will retry");
1682 }
1683
1684 static void inndcommfail(const char *what) {
1685   syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1686   exit(INNDCOMMCHILD_ESTATUS_FAIL);
1687 }
1688
1689 void spawn_inndcomm_flush(void) {
1690   int pipefds[2];
1691
1692   assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1693   assert(!inndcomm_child);
1694
1695   if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1696
1697   inndcomm_child= xfork();
1698
1699   if (!inndcomm_child) {
1700     static char flushargv[2]= { sitename, 0 };
1701     char *reply;
1702
1703     close(pipefds[0]);
1704
1705     alarm(inndcomm_flush_timeout);
1706     r= ICCopen();                         if (r)   inndcommfail("connect");
1707     r= ICCcommand('f',flushargv,&reply);  if (r<0) inndcommfail("transmit");
1708     if (!r) exit(0); /* yay! */
1709
1710     if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1711     syswarn("innd ctlinnd flush failed: innd said %s", reply);
1712     exit(INNDCOMMCHILD_ESTATUS_FAIL);
1713   }
1714
1715   close(pipefds[1]);
1716   int sentinel_fd= pipefds[0];
1717   on_fd_read_except(sentinel_fd, inndcomm_event);
1718
1719   SMS(FLUSHING, 0, "flush is in progress");
1720 }
1721
1722 /*========== main program ==========*/
1723
1724 static void postfork_inputfile(InputFile *ipf) {
1725   if (!ipf) return;
1726   assert(ipf->fd >= 0);
1727   close(ipf->fd);
1728   ipf->fd= -1;
1729 }
1730
1731 static void postfork_conns(Connection *conn) {
1732   while (conn) {
1733     close(conn->fd);
1734     conn= conn->next;
1735   }
1736 }
1737
1738 static void postfork_stdio(FILE *f) {
1739   /* we have no stdio streams that are buffered long-term */
1740   if (f) fclose(f);
1741 }
1742
1743 static void postfork(const char *what) {
1744   if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1745     sysdie("%s child: failed to reset SIGPIPE");
1746
1747   postfork_inputfile(main_input_file);
1748   postfork_inputfile(old_input_file);
1749   postfork_conns(idle.head);
1750   postfork_conns(working.head);
1751   postfork_conns(full.head);
1752   postfork_stdio(defer);
1753 }
1754
1755
1756 #define EVERY(what, interval, body)                                          \
1757   static const struct timeval what##_timeout = { 5, 0 };                     \
1758   static void what##_schedule(void);                                         \
1759   static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1760     { body }                                                                 \
1761     what##_schedule();                                                       \
1762   }                                                                          \
1763   static void what##_schedule(void) {                                        \
1764     loop->on_time(loop, what##_timeout, what##_timedout, 0);                 \
1765   }
1766
1767 EVERY(filepoll, {5,0}, { check_master_queue(); })
1768
1769 EVERY(period, {PERIOD_SECONDS,0}, {
1770   if (connect_delay) connect_delay--;
1771   statemc_poll();
1772   check_master_queue();
1773 });
1774
1775
1776 /*========== option parsing ==========*/
1777
1778 enum OptFlags {
1779   of_seconds= 001000u;
1780   of_boolean= 002000u;
1781 };
1782
1783 typedef struct Option Option;
1784 typedef void OptionParser(const Option*, const char *val);
1785
1786 struct Option {
1787   int short;
1788   const char *long;
1789   void *store;
1790   OptionParser *fn;
1791   int noarg;
1792 };
1793
1794 void op_integer(const Option *o, const char *val) {
1795   char *ep;
1796   errno= 0;
1797   unsigned long ul= strtoul(val,&ep,10);
1798   if (*ep || ep==val || errno || ul>INT_MAX)
1799     badusage("bad integer value for %s",o->long);
1800   int *store= o->store;
1801   *store= ul;
1802 }
1803
1804 void op_double(const Option *o, const char *val) {
1805   int *store= o->store;
1806   char *ep;
1807   errno= 0;
1808   *store= strtod(val, &ep);
1809   if (*ep || ep==val || errno)
1810     badusage("bad floating point value for %s",o->long);
1811 }
1812
1813 void op_string(const Option *o, const char *val) {
1814   char **store= o->store;
1815   free(*store);
1816   *store= val;
1817 }
1818
1819 void op_seconds(const Option *o, const char *val) {
1820   int *store= o->store;
1821   char *ep;
1822   
1823   double v= strtod(val,&ep);
1824   if (ep==val) badusage("bad time/duration value for %s",o->long);
1825
1826   if (!*ep || !strcmp(ep,"s")) unit= 1;
1827   else if (!strcmp(ep,"m")) unit= 60;
1828   else if (!strcmp(ep,"h")) unit= 3600;
1829   else if (!strcmp(ep,"d")) unit= 86400;
1830   else badusage("bad units %s for time/duration value for %s",ep,o->long);
1831
1832   v *= unit;
1833   v= ceil(v);
1834   if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
1835   *store= v;
1836 }
1837
1838 void op_periods_rndup(const Option *o, const char *val) {
1839   int *store= o->store;
1840   op_seconds(o,val);
1841   *store += PERIOD_SECONDS-1;
1842   *store /= PERIOD_SECONDS;
1843 }
1844
1845 void op_periods_booltrue(const Option *o, const char *val) {
1846   int *store= o->store;
1847   *store= 1;
1848 }
1849 void op_periods_boolfalse(const Option *o, const char *val) {
1850   int *store= o->store;
1851   *store= 0;
1852 }
1853
1854 static const Option options[]= {
1855 { 0, "max-connections",       &max_connections           op_integer          },
1856 { 0, "streaming",             &try_stream,               op_booltrue,  1     },
1857 { 0, "no-streaming",          &try_stream,               op_boolfalse, 1     },
1858 {'h',"host",                  &remote_host,              op_string           },
1859 {'P',"port",                  &port                      op_integer          },
1860 { 0, "inndconf",              &inndconffile,             op_string           },
1861 {'f',"feedfile",              &feedfile,                 op_string           },
1862 {'q',"quiet-multiple",        &quiet_if_locked,          op_booltrue,  1     },
1863 { 0, "no-quiet-multiple",     &quiet_if_locked,          op_boolfalse, 1     },
1864 {'d',"daemon",                &become_daemon,            op_booltrue,  1     },
1865 { 0, "no-daemon",             &become_daemon,            op_boolfalse, 1     },
1866
1867 { 0, "no-check-proportion",   &nocheck_thresh_pct,       op_double           },
1868 { 0, "no-check-filter",       &nocheck_decay_articles,   op_double           },
1869
1870 { 0, "max-queue-size",        &max_queue_per_conn        op_integer          },
1871 { 0, "reconnect-interval",    &reconnect_delay_periods,  op_periods_rndup    },
1872 { 0, "flush-retry-interval",  &flushfail_retry_periods,  op_periods_rndup    },
1873 { 0, "feedfile-open-timeout", &open_wait_periods,        op_periods_rndup    },
1874 { 0, "connection-timeout",    &connection_timeout,       op_seconds          },
1875 { 0, "inndcomm-timeout",      &inndcomm_flush_timeout,   op_seconds          },
1876 };
1877
1878 int main(int argc, char **argv) {
1879   const char *arg;
1880   
1881   for (;;) {
1882     arg= *++argv;
1883     if (!arg) break;
1884     if (*arg != '-') break;
1885     if (!strcmp(arg,"--")) { arg= *++argv; break; }
1886     int a;
1887     while ((a= *++arg)) {
1888       const Option *o;
1889       if (a=='-') {
1890         arg++;
1891         char *equals= strchr(arg,'=');
1892         int len= equals ? (equals - arg) : strlen(arg);
1893         for (o=options; o->long; o++)
1894           if (strlen(o->long) == len && !memcmp(o->long,arg,len))
1895             goto found_long;
1896         badusage("unknown long option --%s",arg);
1897       found_long:
1898         if (o->noarg) {
1899           if (equals) badusage("option --%s does not take a value",o->long);
1900           arg= 0;
1901         } else if (equals) {
1902           arg= equals+1;
1903         } else {
1904           arg= *++argv;
1905           if (!arg) badusage("option --%s needs a value",o->long);
1906         }
1907         o->fn(o, arg);
1908         break; /* eaten the whole argument now */
1909       }
1910       for (o=options; o->long; o++)
1911         if (a == o->short)
1912           goto found_short;
1913       badusage("unknown short option -%c",a);
1914     found_short:
1915       if (o->noarg) {
1916         o->fn(o,0);
1917       } else {
1918         if (!*++arg) {
1919           arg= *++argv;
1920           if (!arg) badusage("option -%c needs a value",o->short);
1921         }
1922         o->fn(o,arg);
1923         break; /* eaten the whole argument now */
1924       }
1925     }
1926   }
1927
1928   if (!arg) badusage("need site name argument");
1929   if (*++argv) badusage("too many non-option arguments");
1930   sitename= arg;
1931
1932   if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
1933     badusage("nocheck threshold percentage must be between 0..100");
1934   nocheck_thresh= nocheck_thresh_pct * 0.01;
1935
1936   if (nocheck_decay_articles < 0.1)
1937     badusage("nocheck decay articles must be at least 0.1");
1938   nocheck_decay= 1 - 1/nocheck_decay_articles;
1939   
1940   innconf_read(inndconffile);
1941
1942   if (!feedfile)
1943     feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
1944   else if (!feedfile[0])
1945     badusage("feed filename must be nonempty");
1946   else if (feedfile[strlen(feedfile)-1]=='/')
1947     feedfile= xasprintf("%s%s",feedfile,sitename);
1948   
1949   if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1950     sysdie("could not ignore SIGPIPE");
1951
1952   if (become_daemon) {
1953     for (i=3; i<255; i++)
1954       /* do this now before we open syslog, etc. */
1955       close(i);
1956     openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
1957
1958     int null= open("/dev/null",O_RDWR);
1959     if (null<0) sysdie("failed to open /dev/null");
1960     dup2(null,0);
1961     dup2(null,1);
1962     dup2(null,2);
1963     close(null);
1964     
1965     pid_t child1= xfork("daemonise first fork");
1966     if (child1) _exit(0);
1967
1968     pid_t sid= setsid();
1969     if (sid != child1) sysdie("setsid failed");
1970
1971     pid_t child2= xfork("daemonise second fork");
1972     if (child2) _exit(0);
1973   }
1974
1975   notice("starting");
1976
1977   if (!filemon_init()) {
1978     warn("no file monitoring available, polling");
1979     filepoll_schedule();
1980   }
1981
1982   period_schedule();
1983
1984   statemc_init();
1985
1986   loop->execute.
1987 }