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