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