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