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