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