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