chiark / gitweb /
Rename some of the files
[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   const char *path; /* ptr copy of path_<foo> or feedfile */
263   struct Filemon_Perfile *filemon;
264
265   oop_read *rd;
266   long inprogress; /* no. of articles read but not processed */
267   off_t offset;
268
269   Counts counts;
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(InputFile));
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   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   fixme maybe free ipf->path;
1139
1140   free(ipf);
1141 }
1142
1143
1144 /*---------- dealing with articles read in the input file ----------*/
1145
1146 typedef void *feedfile_got_article(oop_source *lp, oop_read *rd,
1147                                    oop_rd_event ev, const char *errmsg,
1148                                    int errnoval,
1149                                    const char *data, size_t recsz,
1150                                    void *ipf_v) {
1151   InputFile *ipf= ipf_v;
1152   Article *art;
1153   char tokentextbuf[sizeof(TOKEN)*2+3];
1154
1155   if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1156
1157   if (data[0] && data[0]!=' ') {
1158     char *space= strchr(data,' ');
1159     int tokenlen= space-data;
1160     int midlen= (int)recsz-tokenlen-1;
1161     if (midlen < 0) goto bad_data;
1162
1163     if (tokenlen != sizeof(TOKEN)*2+2) goto bad_data;
1164     memcpy(tokentextbuf, data, tokenlen);
1165     tokentextbuf[tokenlen]= 0;
1166     if (!IsToken(tokentextbuf)) goto bad_data;
1167
1168     art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1169     art->offset= ipf->offset;
1170     art->blanklen= recsz;
1171     art->midlen= midlen;
1172     art->checked= art->sentbody= 0;
1173     art->ipf= ipf;  ipf->inprogress++;
1174     art->token= TextToToken(tokentextbuf);
1175     strcpy(art->messageid, space+1);
1176     LIST_ADDTAIL(queue, art);
1177   }
1178   ipf->offset += recsz + 1;
1179
1180   if (sms==sm_NORMAL && ipf->offset >= flush_threshold) {
1181     notice("starting flush (%lu >= %lu)",
1182            (unsigned long)ipf->offset, (unsigned long)flush_threshold);
1183
1184     int r= link(feedfile, duct_path);
1185     if (r) sysdie("link feedfile %s to flushing file %s", feedfile, dut_path);
1186     /* => Hardlinked */
1187
1188     r= unlink(feedfile);
1189     if (r) sysdie("unlink old feedfile link %s", feedfile);
1190     /* => Moved */
1191
1192     spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1193   }
1194
1195   check_master_queue();
1196 }
1197
1198
1199 /*========== tailing input file ==========*/
1200
1201 static void filemon_start(InputFile *ipf) {
1202   assert(!ipf->filemon);
1203
1204   ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1205   memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1206   filemon_method_startfile(ipf, ipf->filemon);
1207 }
1208
1209 static void filemon_stop(InputFile *ipf) {
1210   if (!ipf->filemon) return;
1211   filemon_method_stopfile(ipf, ipf->filemon);
1212   free(ipf->filemon);
1213   ipf->filemon= 0;
1214 }
1215
1216 static void filemon_callback(InputFile *ipf) {
1217   ipf->readable_callback(ipf->readable_callback_user);
1218 }
1219
1220 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1221                                      void *user) {
1222   InputFile *ipf= user;
1223   return ipf->readable_callback(ipf->readable_callback_user);
1224 }
1225
1226 static void on_cancel(struct oop_readable *rable) {
1227   InputFile *ipf= (void*)rable;
1228
1229   if (ipf->filemon) filemon_stopfile(ipf);
1230   loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1231   ipf->readable_callback= 0;
1232 }
1233
1234 static int tailing_on_readable(struct oop_readable *rable,
1235                                 oop_readable_call *cb, void *user) {
1236   InputFile *ipf= (void*)rable;
1237
1238   tailing_on_cancel(rable);
1239   ipf->readable_callback= cb;
1240   ipf->readable_callback_user= user;
1241   filemon_startfile(ipf);
1242
1243   loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1244   return 0;
1245 }
1246
1247 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1248                                 size_t length) {
1249   InputFile *ipf= (void*)rable;
1250   for (;;) {
1251     ssize_t r= read(ipf->fd, buffer, length);
1252     if (r==-1) {
1253       if (errno==EINTR) continue;
1254       return r;
1255     }
1256     if (!r) {
1257       if (ipf==main_input_file) {
1258         errno=EAGAIN;
1259         return -1;
1260       } else if (ipf==old_input_file) {
1261         assert(ipf->fd>=0);
1262         assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1263       } else if (ipf==backlog_input_file) {
1264         assert(ipf->fd>=0);
1265       } else {
1266         abort();
1267       }
1268     }
1269     return r;
1270   }
1271 }
1272
1273 /*---------- filemon implemented with inotify ----------*/
1274
1275 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1276 #define HAVE_FILEMON
1277
1278 #include <linux/inotify.h>
1279
1280 static int filemon_inotify_fd;
1281 static int filemon_inotify_wdmax;
1282 static InputFile **filemon_inotify_wd2ipf;
1283
1284 typedef struct Filemon_Perfile {
1285   int wd;
1286 } Filemon_Inotify_Perfile;
1287
1288 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1289   int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1290   if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1291
1292   if (wd >= filemon_inotify_wdmax) {
1293     int newmax= wd+2;
1294     filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1295                                  sizeof(*filemon_inotify_wd2ipf) * newmax);
1296     memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1297            sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1298     filemon_inotify_wdmax= newmax;
1299   }
1300
1301   assert(!filemon_inotify_wd2ipf[wd]);
1302   filemon_inotify_wd2ipf[wd]= ipf;
1303
1304   pf->wd= wd;
1305 }
1306
1307 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1308   int wd= pf->wd;
1309   int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1310   if (r) sysdie("inotify_rm_watch");
1311   filemon_inotify_wd2ipf[wd]= 0;
1312 }
1313
1314 static void *filemon_inotify_readable(oop_source *lp, int fd,
1315                                       oop_event e, void *u) {
1316   struct inotify_event iev;
1317   for (;;) {
1318     int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1319     if (r==-1) {
1320       if (errno==EAGAIN) break;
1321       sysdie("read from inotify master");
1322     } else if (r==sizeof(iev)) {
1323       assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1324     } else {
1325       die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1326     }
1327     InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1328     filemon_callback(ipf);
1329   }
1330   return OOP_CONTINUE;
1331 }
1332
1333 static int filemon_method_init(void) {
1334   filemon_inotify_fd= inotify_init();
1335   if (filemon_inotify_fd<0) {
1336     syswarn("could not initialise inotify: inotify_init failed");
1337     return 0;
1338   }
1339   set nonblock;
1340   loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1341
1342   return 1;
1343 }
1344
1345 #endif /* HAVE_INOTIFY && !HAVE_FILEMON *//
1346
1347 /*---------- filemon dummy implementation ----------*/
1348
1349 #if !defined(HAVE_FILEMON)
1350
1351 typedef struct Filemon_Perfile { int dummy; } Filemon_Dummy_Perfile;
1352
1353 static int filemon_method_init(void) { return 0; }
1354 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1355 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1356
1357 #endif /* !HAVE_FILEMON */
1358
1359 /*---------- interface to start and stop an input file ----------*/
1360
1361 static const oop_rd_style feedfile_rdstyle= {
1362   OOP_RD_DELIM_STRIP, '\n',
1363   OOP_RD_NUL_FORBID,
1364   OOP_RD_SHORTREC_EOF,
1365 };
1366
1367 static void inputfile_tailing_start(InputFile *ipf) {
1368   assert(!ipf->fd);
1369   ipf->readable->on_readable= tailing_on_readable;
1370   ipf->readable->on_cancel=   tailing_on_cancel;
1371   ipf->readable->try_read=    tailing_try_read;
1372   ipf->readable->delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1373   ipf->readable->delete_kill= 0;
1374
1375   ipf->readable_callback= 0;
1376   ipf->readable_callback_user= 0;
1377
1378   ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1379   assert(ipf->fd);
1380
1381   int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1382                      feedfile_got_article,ipf, feedfile_problem,ipf);
1383   if (r) sysdie("unable start reading feedfile %s",ipf->path);
1384 }
1385
1386 static void inputfile_tailing_stop(InputFile *ipf) {
1387   assert(ipf->fd);
1388   oop_rd_cancel(ipf->rd);
1389   oop_rd_delete(ipf->rd);
1390   ipf->rd= 0;
1391   assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1392 }
1393
1394
1395 /*========== interaction with innd - state machine ==========*/
1396
1397 /* See official state diagram at top of file.  We implement
1398  * this as follows:
1399
1400            ================
1401             WAITING
1402            [Nothing/Noduct]
1403             poll for F
1404            ================
1405                 |
1406                 |     TIMEOUT and no defer, no backlog
1407                 |`--------------------------.
1408                 |                           |
1409                 | OPEN F SUCCEEDS           | exit
1410      ,--------->|                           V
1411      |          V                         =========
1412      |     ========                        (ESRCH)
1413      |      NORMAL                        [Dropped]
1414      |     [Normal]                       =========
1415      |      main F tail
1416      |     ========
1417      |          |
1418      |          | F IS SO BIG WE SHOULD FLUSH
1419      ^          | hardlink F to D
1420      |     [Hardlinked]
1421      |          | unlink F
1422      |          | our handle onto F is now onto D
1423      |     [Moved]
1424      |          |
1425      |          |<---------------------------------------------------.
1426      |          |                                                    |
1427      |          | spawn inndcomm flush                               |
1428      |          V                                                    |
1429      |     ==========                                                |
1430      |      FLUSHING                                                 |
1431      |     [Flushing]                                                |
1432      |      main D tail                                              |
1433      |     ==========                                                |
1434      |          |                                                    |
1435      |          |   INNDCOMM FLUSH FAILS                             ^
1436      |          |`----------------------->----------.                |
1437      |          |                                   |                |
1438      |          |   NO SUCH SITE                    V                |
1439      ^          |`--------------->----.          ===========         |
1440      |          |                      \         FLUSHFAIL           |
1441      |          |                       \        [Moved]             |
1442      |          |                        \       main D tail         |
1443      |          |                         \      ===========         |
1444      |          |                          \        |                |
1445      |          |                           \       | TIME TO RETRY  |
1446      |          |                            \      `----------------'
1447      |          | FLUSH OK                    \
1448      |          | open F                       \
1449      |          V                               V
1450      |     =============                     ============
1451      |      SEPARATED/                        DROPPING/
1452      |      old->fd>=0                        old->fd>=0
1453      |     [Separated]                       [Dropping]
1454      |      main F idle                       main none
1455      |      old  D tail                       old  D tail
1456      |     =============                     ============
1457      |          |                                 |
1458      ^          | EOF ON D                        | EOF ON D
1459      |          V                                 V
1460      |     ===============                   ===============
1461      |      SEPARATED/                        DROPPING/
1462      |      old->fd==-1                       old->fd==-1
1463      |     [Finishing]                       [Dropping]
1464      |      main F tail                       main none
1465      |      old  D closed                     old  D closed
1466      |     ===============                   ===============
1467      |          |                                |
1468      |          | ALL D PROCESSED                | ALL D PROCESSED
1469      |          V install defer as backlog       V install defer as backlog
1470      ^          | close D                        | close D
1471      |          | unlink D                       | unlink D
1472      |          |                                | exit
1473      `----------'                                V
1474                                              ==========
1475                                               (ESRCH)
1476                                              [Droppped]
1477                                              ==========
1478  */
1479
1480 static void statemc_init(void) {
1481   struct stat stab, stabf;
1482   int noent;
1483
1484   path_lock=        xasprintf("%s_lock",      feedfile);
1485   path_flushing=    xasprintf("%s_flushing",  feedfile);
1486   path_defer=       xasprintf("%s_defer",     feedfile);
1487   globpat_backlog=  xasprintf("%s_backlog*",  feedfile);
1488
1489   for (;;) {
1490     int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1491     if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1492
1493     struct flock fl;
1494     memset(&fl,0,sizeof(fl));
1495     fl.l_type= F_WRLCK;
1496     fl.l_whence= SEEK_SET;
1497     r= fcntl(lockfd, F_SETLK, &fl);
1498     if (r==-1) {
1499       if (errno==EACCES || errno==EAGAIN) {
1500         if (quiet_if_locked) exit(0);
1501         fatal("another duct holds the lockfile");
1502       }
1503       sysdie("fcntl F_SETLK lockfile %s", path_lock);
1504     }
1505
1506     xfstat_isreg(lockfd, &stabf, "lockfile");
1507     xlstat_isreg(path_lock, &stab, &noent, "lockfile");
1508
1509     if (!noent && samefile(&stab, &stabf))
1510       break;
1511
1512     if (close(lockfd))
1513       sysdie("could not close stale lockfile %s", path_lock);
1514   }
1515   debug("startup: locked");
1516
1517   search_backlog_file();
1518
1519   xlstat_isreg(path_defer, &stab, &noent, "defer file");
1520   if (noent) {
1521     debug("startup: ductdefer ENOENT");
1522   } else {
1523     debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1524     switch (stab.st_nlink==1) {
1525     case 1:
1526       open_defer(); /* so that we will later close it and rename it */
1527       break;
1528     case 2:
1529       if (unlink(path_defer))
1530         sysdie("could not unlink stale defer file link %s (presumably"
1531                " hardlink to backlog file)", path_defer);
1532       break;
1533     default:
1534       die("defer file %s has unexpected link count %d",
1535           path_defer, stab.st_nlink);
1536     }
1537   }
1538
1539   InputFile *file_d= open_input_file(path_flushing);
1540
1541   if (file_d) {
1542     struct stat stab_f, stab_d;
1543
1544     xlstat_isreg(feedfile, &stab_f, &noent, "feed file");
1545     if (noent) {
1546       debug("startup: D exists, F ENOENT => Moved");
1547       goto found_moved;
1548     }
1549
1550     debug("startup: F and D both exist");
1551
1552     xfstat_isreg(file_d->fd, &stab_d, "flushing file");
1553
1554     if (samefile(&stab_d, &stab_f)) {
1555       debug("startup: F==D => Hardlinked");
1556       r= unlink(path_flushing);
1557       if (r) sysdie("unlink feed file %s during startup", feedfile);
1558     found_moved:
1559       debug(" => Moved");
1560       startup_set_input_file(file_d);
1561       spawn_inndcomm_flush(); /* => Flushing, sets sms to sm_FLUSHING */
1562     } else {
1563       debug("F!=D => Separated");
1564       SMS(SEPARATED, 0, "found both old and current feed files");
1565       startup_set_input_file(file_d);
1566     }
1567   } else {
1568     debug("startup: D ENOENT => Nothing");
1569     SMS(WAITING, open_wait_periods, "no feed file currently exists");
1570   }
1571 }
1572
1573 static void statemc_poll(void) {
1574   if (sms==sm_WAITING) { statemc_waiting_poll(); return; }
1575
1576   if (!sm_period_counter) return;
1577   sm_period_counter--;
1578   assert(sm_period_counter>=0);
1579
1580   if (sm_period_counter) return;
1581   switch (sms) {
1582   case sm_WAITING:
1583     fatal("timed out waiting for innd to create feed file %s", feedfile);
1584   case sm_FLUSHFAIL:
1585     spawn_inndcomm_flush(void);
1586     break;
1587   default:
1588     abort();
1589   }
1590 }
1591
1592 static void statemc_waiting_poll(void) {
1593   InputFile *file_f= open_input_file(feedfile);
1594   if (!file_f) return;
1595   startup_set_input_file(file_d);
1596   SMS(NORMAL, 0, "found and opened feed file");
1597 }
1598
1599 static void startup_set_input_file(InputFile *f) {
1600   assert(!main_input_file);
1601   main_input_file= f;
1602   inputfile_tailing_start(f);
1603 }
1604
1605 static void *statemc_check_input_done(oop_source *lp,
1606                                       struct timeval now, void *ipf_v) {
1607   InputFile *ipf= ipf_v;
1608   struct stat stab;
1609
1610   if (ipf->inprogress) return; /* new article in the meantime */
1611   if (ipf->fd >= 0); return; /* not had EOF */
1612
1613   if (ipf == backlog_input_file) {
1614     notice_processed(ipf,"backlog file",ipf->path);
1615     close_input_file(ipf);
1616     if (unlink(ipf->path)) {
1617       if (errno != ENOENT)
1618         sysdie("could not unlink processed backlog file %s", ipf->path);
1619       warn("backlog file %s vanished while we were reading it"
1620            " so we couldn't remove it (but it's done now, anyway)",
1621            ipf->path);
1622     }
1623     backlog_input_file= 0;
1624     search_backlog_file();
1625     return;
1626   }
1627
1628   assert(ipf == old_input_file);
1629   assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1630
1631   notice_processed(ipf,"feed file",0);
1632
1633   close_defer();
1634
1635   if (unlink(path_flushing))
1636     sysdie("could not unlink old flushing file %s", path_flushing);
1637
1638   if (sms==sm_DROPPING) {
1639     if (search_backlog_file()) {
1640       debug("feed dropped but still backlogs to process");
1641       return;
1642     }
1643     notice("feed dropped and our work is complete");
1644     r= unlink(path_lock);
1645     if (r) sysdie("unlink lockfile for old feed %s", path_lock);
1646     exit(0);
1647   }
1648
1649   open_defer();
1650
1651   close_input_file(old_input_file);
1652   old_input_file= 0;
1653
1654   notice("flush complete");
1655   SMS(NORMAL, 0, "flush complete");
1656 }
1657
1658 static void statemc_setstate(StateMachineState newsms, int periods,
1659                              const char *forlog, const char *why) {
1660   sms= newsms;
1661   sm_period_counter= periods;
1662   if (periods) {
1663     info("%s[%d] %s",periods,forlog,why);
1664   } else {
1665     info("%s %s",forlog,why);
1666   }
1667 }
1668
1669 /*---------- defer and backlog files ----------*/
1670
1671 static void open_defer(void) {
1672   struct stat stab;
1673
1674   if (defer) return;
1675
1676   defer= fopen(path_defer, "a+");
1677   if (!defer) sysfatal("could not open defer file %s", path_defer);
1678
1679   /* truncate away any half-written records */
1680
1681   xfstat_isreg(fileno(defer), &stab, "newly opened defer file");
1682
1683   if (stab.st_size > LONG_MAX)
1684     die("defer file %s size is far too large", path_defer);
1685
1686   if (!stab.st_size)
1687     return;
1688
1689   long orgsize= stab.st_size;
1690   long truncto= stab.st_size;
1691   for (;;) {
1692     if (!truncto) break; /* was only (if anything) one half-truncated record */
1693     if (fseek(defer, truncto-1, SEEK_SET) < 0)
1694       sysdie("seek in defer file %s while truncating partial", path_defer);
1695
1696     r= getc(defer);
1697     if (r==EOF) {
1698       if (ferror(defer))
1699         sysdie("failed read from defer file %s", path_defer);
1700       else
1701         die("defer file %s shrank while we were checking it!", path_defer);
1702     }
1703     if (r=='\n') break;
1704     truncto--;
1705   }
1706
1707   if (stab.st_size != truncto) {
1708     warn("truncating half-record at end of defer file %s -"
1709          " shrinking by %ld bytes from %ld to %ld",
1710          path_defer, orgsize - truncto, orgsize, truncto);
1711
1712     if (fflush(defer))
1713       sysfatal("could not flush defer file %s", path_defer);
1714     if (ftruncate(fileno(defer), truncto))
1715       sysdie("could not truncate defer file %s", path_defer);
1716
1717   } else {
1718     info("continuing existing defer file %s (%ld bytes)",
1719          path_defer, orgsize);
1720   }
1721   if (fseek(defer, truncto, SEEK_SET))
1722     sysdie("could not seek to new end of defer file %s", path_defer);
1723 }
1724
1725 static void close_defer(void) {
1726   if (!defer)
1727     return;
1728
1729   xfstat(fileno(defer), &stab, "defer file");
1730
1731   if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
1732   defer= 0;
1733
1734   char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
1735                            (unsigned long)now.tv_sec,
1736                            (unsigned long)stab.st_ino);
1737   if (link(path_defer, path_backlog))
1738     sysfatal("could not install defer file %s as backlog file %s",
1739            path_defer, backlog);
1740   if (unlink(path_defer))
1741     sysdie("could not unlink old defer link %s to backlog file %s",
1742            path_defer, backlog);
1743
1744   if (backlog_nextscan_periods < 0 ||
1745       backlog_nextscan_periods > backlog_retry_minperiods + 1)
1746     backlog_nextscan_periods= backlog_retry_minperiods + 1;
1747 }
1748
1749 static void poll_backlog_file(void) {
1750   if (backlog_nextscan_periods < 0) return;
1751   if (backlog_nextscan_periods-- > 0) return;
1752   search_backlog_file();
1753 }
1754
1755 static int search_backlog_file(void) {
1756   /* returns non-0 iff there are any backlog files */
1757
1758   glob_t gl;
1759   int r;
1760   struct stat stab;
1761   const char *oldest_path=0;
1762   time_t oldest_mtime, now;
1763
1764   if (backlog_input_file) return 3;
1765
1766  try_again:
1767
1768   r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
1769
1770   switch (r) {
1771   case GLOB_ABORTED:
1772     sysdie("failed to expand backlog pattern %s", globpat_backlog);
1773   case GLOB_NOSPACE:
1774     die("out of memory expanding backlog pattern %s", globpat_backlog);
1775   case 0:
1776     for (i=0; i<gl.gl_pathc; i++) {
1777       const char *path= gl.gl_pathv[i];
1778
1779       if (strchr(path,'#') || strchr(path,'~')) {
1780         debug("backlog file search skipping %s", path);
1781         continue;
1782       }
1783       r= stat(path, &stab);
1784       if (r) {
1785         syswarn("failed to stat backlog file %s", path);
1786         continue;
1787       }
1788       if (!S_ISREG(stab.st_mode)) {
1789         warn("backlog file %s is not a plain file (or link to one)", path);
1790         continue;
1791       }
1792       if (!oldest_path || stab.st_mtime < oldest_mtime) {
1793         oldest_path= path;
1794         oldest_mtime= stab.st_mtime;
1795       }
1796     }
1797   case GLOB_NOMATCH: /* fall through */
1798     break;
1799   default:
1800     sysdie("glob expansion of backlog pattern %s gave unexpected"
1801            " nonzero (error?) return value %d", globpat_backlog, r);
1802   }
1803
1804   globfree(&gl);
1805
1806   if (!oldest_path) {
1807     debug("backlog scan: none");
1808     backlog_nextscan_periods= backlog_spontaneous_rescan_periods;
1809     return 0;
1810   }
1811
1812   now= time();  if (now==-1) sysdie("time(2) failed");
1813   double age= difftime(now, oldest_mtime);
1814   long age_deficiency= (backlog_retry_minperiods * PERIOD_SECONDS) - age;
1815
1816   if (age_deficiency <= 0) {
1817     debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
1818           age, age_deficiency, oldest_path);
1819
1820     backlog_input_file= open_input_file();
1821     if (!backlog_input_file) {
1822       warn("backlog file %s vanished as we opened it", backlog_input_file);
1823       goto try_again;
1824     }
1825     inputfile_tailing_start(backlog_input_file);
1826     backlog_nextscan_periods= -1;
1827     return 1;
1828   }
1829
1830   backlog_nextscan_periods= age_deficiency / PERIOD_SECONDS;
1831
1832   if (backlog_spontaneous_rescan_periods >= 0 &&
1833       backlog_nextscan_periods > backlog_spontaneous_rescan_periods)
1834     backlog_nextscan_periods= backlog_spontaneous_rescan_periods;
1835
1836   debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
1837         age, age_deficiency, backlog_nextscan_periods, oldest_path);
1838   return 2;
1839 }
1840
1841 /*========== flushing the feed ==========*/
1842
1843 static pid_t inndcomm_child;
1844
1845 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
1846   assert(inndcomm_child);
1847   int status= xwaitpid(&inndcomm_child, "inndcomm");
1848   loop->cancel_fd(fd);
1849   close(fd);
1850
1851   assert(!old_input_file);
1852
1853   if (WIFEXITED(status)) {
1854     switch (WEXITSTATUS(status)) {
1855
1856     case INNDCOMMCHILD_ESTATUS_FAIL:
1857       goto failed;
1858
1859     case INNDCOMMCHILD_ESTATUS_NONESUCH:
1860       warn("feed has been dropped by innd, finishing up");
1861       old_input_file= main_input_file;
1862       main_input_file= 0;
1863       SMS(DROPPING, 0, "dropped by innd");
1864       return OOP_CONTINUE;
1865
1866     case 0:
1867       old_input_file= main_input_file;
1868       main_input_file= open_input_file(feedfile);
1869       if (!main_input_file)
1870         die("flush succeeded but feedfile %s does not exist!", feedfile);
1871       SMS(SEPARATED, 0, "feed file missing");
1872       return OOP_CONTINUE;
1873
1874     default:
1875       goto unexpected_exitstatus;
1876
1877     }
1878   } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
1879     warn("flush timed out trying to talk to innd");
1880     goto failed;
1881   } else {
1882   unexpected_exitstatus:
1883     report_child_status("inndcomm child", status);
1884   }
1885
1886  failed:
1887   SMS(FLUSHFAIL, flushfail_retry_periods, "flush failed, will retry");
1888 }
1889
1890 static void inndcommfail(const char *what) {
1891   syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
1892   exit(INNDCOMMCHILD_ESTATUS_FAIL);
1893 }
1894
1895 void spawn_inndcomm_flush(void) {
1896   int pipefds[2];
1897
1898   assert(sms==sm_NORMAL || sms==sm_FLUSHFAIL);
1899   assert(!inndcomm_child);
1900
1901   if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
1902
1903   inndcomm_child= xfork();
1904
1905   if (!inndcomm_child) {
1906     static char flushargv[2]= { sitename, 0 };
1907     char *reply;
1908
1909     close(pipefds[0]);
1910
1911     alarm(inndcomm_flush_timeout);
1912     r= ICCopen();                         if (r)   inndcommfail("connect");
1913     r= ICCcommand('f',flushargv,&reply);  if (r<0) inndcommfail("transmit");
1914     if (!r) exit(0); /* yay! */
1915
1916     if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
1917     syswarn("innd ctlinnd flush failed: innd said %s", reply);
1918     exit(INNDCOMMCHILD_ESTATUS_FAIL);
1919   }
1920
1921   close(pipefds[1]);
1922   int sentinel_fd= pipefds[0];
1923   on_fd_read_except(sentinel_fd, inndcomm_event);
1924
1925   SMS(FLUSHING, 0, "flush is in progress");
1926 }
1927
1928 /*========== main program ==========*/
1929
1930 static void postfork_inputfile(InputFile *ipf) {
1931   if (!ipf) return;
1932   assert(ipf->fd >= 0);
1933   close(ipf->fd);
1934   ipf->fd= -1;
1935 }
1936
1937 static void postfork_conns(Connection *conn) {
1938   while (conn) {
1939     close(conn->fd);
1940     conn= conn->next;
1941   }
1942 }
1943
1944 static void postfork_stdio(FILE *f) {
1945   /* we have no stdio streams that are buffered long-term */
1946   if (f) fclose(f);
1947 }
1948
1949 static void postfork(const char *what) {
1950   if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
1951     sysdie("%s child: failed to reset SIGPIPE");
1952
1953   postfork_inputfile(main_input_file);
1954   postfork_inputfile(old_input_file);
1955   postfork_conns(idle.head);
1956   postfork_conns(working.head);
1957   postfork_conns(full.head);
1958   postfork_stdio(defer);
1959 }
1960
1961 #define EVERY(what, interval, body)                                          \
1962   static const struct timeval what##_timeout = { 5, 0 };                     \
1963   static void what##_schedule(void);                                         \
1964   static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
1965     { body }                                                                 \
1966     what##_schedule();                                                       \
1967   }                                                                          \
1968   static void what##_schedule(void) {                                        \
1969     loop->on_time(loop, what##_timeout, what##_timedout, 0);                 \
1970   }
1971
1972 EVERY(filepoll, {5,0}, {
1973   if (main_input_file && main_input_file->readable_callback)
1974     filemon_callback(main_input_file);
1975 });
1976
1977 EVERY(period, {PERIOD_SECONDS,0}, {
1978   if (connect_delay) connect_delay--;
1979   poll_backlog_file();
1980   if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
1981   statemc_poll();
1982   check_master_queue();
1983 });
1984
1985
1986 /*========== option parsing ==========*/
1987
1988 enum OptFlags {
1989   of_seconds= 001000u;
1990   of_boolean= 002000u;
1991 };
1992
1993 typedef struct Option Option;
1994 typedef void OptionParser(const Option*, const char *val);
1995
1996 struct Option {
1997   int short;
1998   const char *long;
1999   void *store;
2000   OptionParser *fn;
2001   int noarg;
2002 };
2003
2004 void op_integer(const Option *o, const char *val) {
2005   char *ep;
2006   errno= 0;
2007   unsigned long ul= strtoul(val,&ep,10);
2008   if (*ep || ep==val || errno || ul>INT_MAX)
2009     badusage("bad integer value for %s",o->long);
2010   int *store= o->store;
2011   *store= ul;
2012 }
2013
2014 void op_double(const Option *o, const char *val) {
2015   int *store= o->store;
2016   char *ep;
2017   errno= 0;
2018   *store= strtod(val, &ep);
2019   if (*ep || ep==val || errno)
2020     badusage("bad floating point value for %s",o->long);
2021 }
2022
2023 void op_string(const Option *o, const char *val) {
2024   char **store= o->store;
2025   free(*store);
2026   *store= val;
2027 }
2028
2029 void op_seconds(const Option *o, const char *val) {
2030   int *store= o->store;
2031   char *ep;
2032
2033   double v= strtod(val,&ep);
2034   if (ep==val) badusage("bad time/duration value for %s",o->long);
2035
2036   if (!*ep || !strcmp(ep,"s")) unit= 1;
2037   else if (!strcmp(ep,"m")) unit= 60;
2038   else if (!strcmp(ep,"h")) unit= 3600;
2039   else if (!strcmp(ep,"d")) unit= 86400;
2040   else badusage("bad units %s for time/duration value for %s",ep,o->long);
2041
2042   v *= unit;
2043   v= ceil(v);
2044   if (v > INT_MAX) badusage("time/duration value for %s out of range",o->long);
2045   *store= v;
2046 }
2047
2048 void op_periods_rndup(const Option *o, const char *val) {
2049   int *store= o->store;
2050   op_seconds(o,val);
2051   *store += PERIOD_SECONDS-1;
2052   *store /= PERIOD_SECONDS;
2053 }
2054
2055 void op_periods_booltrue(const Option *o, const char *val) {
2056   int *store= o->store;
2057   *store= 1;
2058 }
2059 void op_periods_boolfalse(const Option *o, const char *val) {
2060   int *store= o->store;
2061   *store= 0;
2062 }
2063
2064 static const Option options[]= {
2065 { 0, "max-connections",       &max_connections           op_integer          },
2066 { 0, "streaming",             &try_stream,               op_booltrue,  1     },
2067 { 0, "no-streaming",          &try_stream,               op_boolfalse, 1     },
2068 {'h',"host",                  &remote_host,              op_string           },
2069 {'P',"port",                  &port                      op_integer          },
2070 { 0, "inndconf",              &inndconffile,             op_string           },
2071 {'f',"feedfile",              &feedfile,                 op_string           },
2072 {'q',"quiet-multiple",        &quiet_if_locked,          op_booltrue,  1     },
2073 { 0, "no-quiet-multiple",     &quiet_if_locked,          op_boolfalse, 1     },
2074 {'d',"daemon",                &become_daemon,            op_booltrue,  1     },
2075 { 0, "no-daemon",             &become_daemon,            op_boolfalse, 1     },
2076
2077 { 0, "no-check-proportion",   &nocheck_thresh_pct,       op_double           },
2078 { 0, "no-check-filter",       &nocheck_decay_articles,   op_double           },
2079
2080 { 0, "max-queue-size",        &max_queue_per_conn        op_integer          },
2081 { 0, "reconnect-interval",    &reconnect_delay_periods,  op_periods_rndup    },
2082 { 0, "flush-retry-interval",  &flushfail_retry_periods,  op_periods_rndup    },
2083 { 0, "feedfile-open-timeout", &open_wait_periods,        op_periods_rndup    },
2084 { 0, "connection-timeout",    &connection_timeout,       op_seconds          },
2085 { 0, "inndcomm-timeout",      &inndcomm_flush_timeout,   op_seconds          },
2086 };
2087
2088 int main(int argc, char **argv) {
2089   const char *arg;
2090
2091   for (;;) {
2092     arg= *++argv;
2093     if (!arg) break;
2094     if (*arg != '-') break;
2095     if (!strcmp(arg,"--")) { arg= *++argv; break; }
2096     int a;
2097     while ((a= *++arg)) {
2098       const Option *o;
2099       if (a=='-') {
2100         arg++;
2101         char *equals= strchr(arg,'=');
2102         int len= equals ? (equals - arg) : strlen(arg);
2103         for (o=options; o->long; o++)
2104           if (strlen(o->long) == len && !memcmp(o->long,arg,len))
2105             goto found_long;
2106         badusage("unknown long option --%s",arg);
2107       found_long:
2108         if (o->noarg) {
2109           if (equals) badusage("option --%s does not take a value",o->long);
2110           arg= 0;
2111         } else if (equals) {
2112           arg= equals+1;
2113         } else {
2114           arg= *++argv;
2115           if (!arg) badusage("option --%s needs a value",o->long);
2116         }
2117         o->fn(o, arg);
2118         break; /* eaten the whole argument now */
2119       }
2120       for (o=options; o->long; o++)
2121         if (a == o->short)
2122           goto found_short;
2123       badusage("unknown short option -%c",a);
2124     found_short:
2125       if (o->noarg) {
2126         o->fn(o,0);
2127       } else {
2128         if (!*++arg) {
2129           arg= *++argv;
2130           if (!arg) badusage("option -%c needs a value",o->short);
2131         }
2132         o->fn(o,arg);
2133         break; /* eaten the whole argument now */
2134       }
2135     }
2136   }
2137
2138   if (!arg) badusage("need site name argument");
2139   if (*++argv) badusage("too many non-option arguments");
2140   sitename= arg;
2141
2142   if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2143     badusage("nocheck threshold percentage must be between 0..100");
2144   nocheck_thresh= nocheck_thresh_pct * 0.01;
2145
2146   if (nocheck_decay_articles < 0.1)
2147     badusage("nocheck decay articles must be at least 0.1");
2148   nocheck_decay= 1 - 1/nocheck_decay_articles;
2149
2150   innconf_read(inndconffile);
2151
2152   if (!feedfile)
2153     feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2154   else if (!feedfile[0])
2155     badusage("feed filename must be nonempty");
2156   else if (feedfile[strlen(feedfile)-1]=='/')
2157     feedfile= xasprintf("%s%s",feedfile,sitename);
2158
2159   const char *feedfile_forbidden= "?*[";
2160   int c;
2161   while ((c= *feedfile_forbidden++))
2162     if (strchr(feedfile, c))
2163       badusage("feed filename may not contain glob metacharacter %c",c);
2164
2165   if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2166     sysdie("could not ignore SIGPIPE");
2167
2168   if (become_daemon) {
2169     for (i=3; i<255; i++)
2170       /* do this now before we open syslog, etc. */
2171       close(i);
2172     openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2173
2174     int null= open("/dev/null",O_RDWR);
2175     if (null<0) sysdie("failed to open /dev/null");
2176     dup2(null,0);
2177     dup2(null,1);
2178     dup2(null,2);
2179     close(null);
2180
2181     pid_t child1= xfork("daemonise first fork");
2182     if (child1) _exit(0);
2183
2184     pid_t sid= setsid();
2185     if (sid != child1) sysdie("setsid failed");
2186
2187     pid_t child2= xfork("daemonise second fork");
2188     if (child2) _exit(0);
2189   }
2190
2191   notice("starting");
2192
2193   if (!filemon_init()) {
2194     warn("no file monitoring available, polling");
2195     filepoll_schedule();
2196   }
2197
2198   period_schedule();
2199
2200   statemc_init();
2201
2202   loop->execute.
2203 }