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