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