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