chiark / gitweb /
d75c51bf1467d70cafc35e7d27fd52b6c7773f40
[inn-innduct.git] / backends / innduct.c
1 /*
2  * TODO
3  *  - actually implement badusage
4  *  - options for all options
5  *  - manpage
6  *  - pid, sitename, hostname in lockfile
7  *  - -k kill mode ?
8  */
9
10 /*
11  * Newsfeeds file entries should look like this:
12  *     host.name.of.site[/exclude,exclude,...]\
13  *             :pattern,pattern...[/distribution,distribution...]\
14  *             :Tf,Wnm
15  *             :
16  * or
17  *     sitename[/exclude,exclude,...]\
18  *             :pattern,pattern...[/distribution,distribution...]\
19  *             :Tf,Wnm
20  *             :host.name.of.site
21  *
22  * Four files full of
23  *    token messageid
24  * or might be blanked out
25  *    <spc><spc><spc><spc>....
26  *
27  * F site.name                 main feed file
28  *                                opened/created, then written, by innd
29  *                                read by duct
30  *                                unlinked by duct
31  *                                tokens blanked out by duct when processed
32  *   site.name_lock            lock preventing multiple ducts
33  *                                to hold lock must open,F_SETLK[W]
34  *                                  and then stat to check that locked file
35  *                                  still has name site.name_lock
36  *                                holder of this lock is "duct"
37  *                                (only) lockholder may remove the lockfile
38  * D site.name_flushing        temporary feed file during flush (or crash)
39  *                                hardlink created by duct
40  *                                unlinked by duct
41  *   site.name_defer           431'd articles, still being written,
42  *                                created, written, used by duct
43  *
44  *   site.name_backlog.<date>.<inum>
45  *                             431'd articles, ready for innxmit or duct
46  *                                created (link/mv) by duct
47  *   site.name_backlog<anything-else>  (where <anything-else> does not
48  *                                      contain '#' or '~') eg
49  *   site.name_backlog.manual
50  *                             anything the sysadmin likes (eg, feed files
51  *                             from old feeds to be merged into this one)
52  *                                created (link/mv) by admin
53  *                                may be symlinks (in which case links
54  *                                may be written through, but only links
55  *                                will be removed.
56  *
57  *                             It is safe to remove backlog files manually,
58  *                             if it's desired to throw away the backlog.
59  *
60  * Backlog files are also processed by innduct.  We find the oldest
61  * backlog file which is at least a certain amount old, and feed it
62  * back into our processing.  When every article in it has been read
63  * and processed, we unlink it and look for another backlog file.
64  *
65  * If we don't have a backlog file that we're reading, we close the
66  * defer file that we're writing and make it into a backlog file at
67  * the first convenient opportunity.
68  * -8<-
69
70
71    OVERALL STATES:
72
73                                                                 START
74                                                                   |
75      ,-->--.                                                 check F, D
76      |     |                                                      |
77      |     |                                                      |
78      |     |  <----------------<---------------------------------'|
79      |     |                                       F exists       |
80      |     |                                       D ENOENT       |
81      |     |  duct opens F                                        |
82      |     V                                                      |
83      |  Normal                                                    |
84      |   F: innd writing, duct reading                            |
85      |   D: ENOENT                                                |
86      |     |                                                      |
87      |     |  duct decides time to flush                          |
88      |     |  duct makes hardlink                                 |
89      |     |                                                      |
90      |     V                            <------------------------'|
91      |  Hardlinked                                  F==D          |
92      |   F == D: innd writing, duct reading         both exist    |
93      ^     |                                                      |
94      |     |  duct unlinks F                                      |
95      |     |                        <-----------<-------------<--'|
96      |     |                           open D         F ENOENT    |
97      |     |                           if exists                  |
98      |     |                                                      |
99      |     V                        <---------------------.       |
100      |  Moved                                             |       |
101      |   F: ENOENT                                        |       |
102      |   D: innd writing, duct reading; or ENOENT         |       |
103      |     |                                              |       |
104      |     |  duct requests flush of feed                 |       |
105      |     |   (others can too, harmlessly)               |       |
106      |     V                                              |       |
107      |  Flushing                                          |       |
108      |   F: ENOENT                                        |       |
109      |   D: innd flushing, duct; or ENOENT                |       |
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; or ENOENT                  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  * ->8- -^L-
149  *
150  * rune for printing diagrams:
151
152 perl -ne 'print if m/-8\<-/..m/-\>8-/; print "\f" if m/-\^L-/' backends/innduct.c |a2ps -R -B -ops
153
154  *
155  */
156
157 /*============================== PROGRAM ==============================*/
158
159 #define _GNU_SOURCE 1
160
161 #include "config.h"
162 #include "storage.h"
163 #include "nntp.h"
164 #include "libinn.h"
165 #include "inndcomm.h"
166
167 #include "inn/list.h"
168 #include "inn/innconf.h"
169
170 #include <sys/uio.h>
171 #include <sys/types.h>
172 #include <sys/wait.h>
173 #include <sys/stat.h>
174 #include <sys/socket.h>
175 #include <unistd.h>
176 #include <string.h>
177 #include <signal.h>
178 #include <stdio.h>
179 #include <errno.h>
180 #include <syslog.h>
181 #include <fcntl.h>
182 #include <stdarg.h>
183 #include <assert.h>
184 #include <stdlib.h>
185 #include <glob.h>
186 #include <time.h>
187 #include <math.h>
188
189 #include <oop.h>
190 #include <oop-read.h>
191
192 /*----- general definitions, probably best not changed -----*/
193
194 #define CONNCHILD_ESTATUS_STREAM   4
195 #define CONNCHILD_ESTATUS_NOSTREAM 5
196
197 #define INNDCOMMCHILD_ESTATUS_FAIL     6
198 #define INNDCOMMCHILD_ESTATUS_NONESUCH 7
199
200 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
201
202 #define VA                va_list al;  va_start(al,fmt)
203 #define PRINTF(f,a)       __attribute__((__format__(printf,f,a)))
204 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
205
206 /*----- doubly linked lists -----*/
207
208 #define ISNODE(T)   struct node list_node
209 #define DEFLIST(T)                              \
210    typedef struct {                             \
211      union { struct list li; T *for_type; } u;  \
212      int count;                                 \
213    } T##List
214
215 #define NODE(n) (assert((void*)&(n)->list_node == &(n)), &(n)->list_node)
216
217 #define LIST_CHECKCANHAVENODE(l,n) \
218   ((void)((n) == ((l).u.for_type))) /* just for the type check */
219
220 #define LIST_ADDSOMEHOW(l,n,list_addsomehow)    \
221  ( LIST_CHECKCANHAVENODE(l,n),                  \
222    list_addsomehow(&(l).u.li, NODE((n))),       \
223    (void)(l).count++                            \
224    )
225
226 #define LIST_REMSOMEHOW(l,list_remsomehow)      \
227  ( (typeof((l).u.for_type))                     \
228    ( (l).count                                  \
229      ? ( (l).count--,                           \
230          list_remsomehow(&(l).u.li) )           \
231      : 0                                        \
232      )                                          \
233    )
234
235
236 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
237 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
238 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
239 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
240
241 #define LIST_INIT(l) (list_new(&(l).u.li))
242 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
243 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
244 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
245
246 #define LIST_REMOVE(l,n)                        \
247  ( LIST_CHECKCANHAVENODE(l,n),                  \
248    list_remove(NODE((n))),                      \
249    (void)(l).count--                            \
250    )
251
252 #define LIST_INSERT(l,n,pred)                                   \
253  ( LIST_CHECKCANHAVENODE(l,n),                                  \
254    LIST_CHECKCANHAVENODE(l,pred),                               \
255    list_insert((struct list*)&(l), NODE((n)), NODE((pred))),    \
256    (void)(l).count++                                            \
257    )
258
259 /*----- type predeclarations -----*/
260
261 typedef struct Conn Conn;
262 typedef struct Article Article;
263 typedef struct InputFile InputFile;
264 typedef struct XmitDetails XmitDetails;
265 typedef struct Filemon_Perfile Filemon_Perfile;
266 typedef enum StateMachineState StateMachineState;
267
268 DEFLIST(Conn);
269 DEFLIST(Article);
270
271 /*----- function predeclarations -----*/
272
273 static void conn_maybe_write(Conn *conn);
274 static void conn_make_some_xmits(Conn *conn);
275 static void *conn_write_some_xmits(Conn *conn);
276
277 static void xmit_free(XmitDetails *d);
278
279 #define SMS(newstate, periods, why) \
280    (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
281 static void statemc_setstate(StateMachineState newsms, int periods,
282                              const char *forlog, const char *why);
283
284 static void statemc_start_flush(const char *why); /* Normal => Flushing */
285 static void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
286
287 static void check_assign_articles(void);
288 static void queue_check_input_done(void);
289
290 static void statemc_check_flushing_done(void);
291 static void statemc_check_backlog_done(void);
292
293 static void postfork(void);
294
295 static void open_defer(void);
296 static void close_defer(void);
297 static void search_backlog_file(void);
298
299 static void inputfile_reading_start(InputFile *ipf);
300 static void inputfile_reading_stop(InputFile *ipf);
301
302 static void filemon_start(InputFile *ipf);
303 static void filemon_stop(InputFile *ipf);
304 static void filemon_callback(InputFile *ipf);
305
306 static void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
307 static void connfail(Conn *conn, const char *fmt, ...)         PRINTF(2,3);
308
309 static const oop_rd_style peer_rd_style;
310 static oop_rd_call peer_rd_err, peer_rd_ok;
311
312 /*----- configuration options -----*/
313
314 static const char *sitename, *feedfile, *pathoutgoing;
315 static const char *remote_host;
316 static int quiet_multiple=0, become_daemon=1;
317
318 static int max_connections=10, max_queue_per_conn=200;
319 static int target_max_feedfile_size=100000;
320
321 static int period_seconds=60;
322
323 static double max_bad_data_ratio= 0.01;
324 static int max_bad_data_initial= 30;
325   /* in one corrupt 4096-byte block the number of newlines has
326    * mean 16 and standard deviation 3.99.  30 corresponds to z=+3.5 */
327
328 static int connection_setup_timeout=200, port=119, try_stream=1;
329 static int inndcomm_flush_timeout=100;
330 static int reconnect_delay_periods, flushfail_retry_periods;
331 static int backlog_retry_minperiods, backlog_spontaneous_rescan_periods;
332 static int spontaneous_flush_periods, need_activity_periods;
333 static const char *inndconffile;
334
335 static double nocheck_thresh_pct= 95.0;
336 static double nocheck_thresh; /* computed in main from _pct */
337 static double nocheck_decay_articles= 100; /* converted to _decay */
338 static double nocheck_decay; /* computed in main from _articles */
339
340
341 /*----- statistics -----*/
342
343 typedef enum {      /* in queue                 in conn->sent             */
344   art_Unchecked,    /*   not checked, not sent    checking                */
345   art_Wanted,       /*   checked, wanted          sent body as requested  */
346   art_Unsolicited,  /*   -                        sent body without check */
347   art_MaxState
348 } ArtState;
349
350 #define RESULT_COUNTS(RCS,RCN)                  \
351   RCS(sent)                                     \
352   RCS(accepted)                                 \
353   RCN(unwanted)                                 \
354   RCN(rejected)                                 \
355   RCN(deferred)                                 \
356   RCN(connretry)
357
358 #define RCI_TRIPLE_FMT_BASE "%d(id%d+bd%d+nc%d)"
359 #define RCI_TRIPLE_VALS_BASE(counts,x)          \
360        counts[art_Unchecked] x                  \
361        + counts[art_Wanted] x                   \
362        + counts[art_Unsolicited] x,             \
363        counts[art_Unchecked] x                  \
364        , counts[art_Wanted] x                   \
365        , counts[art_Unsolicited] x
366
367 typedef enum {
368 #define RC_INDEX(x) RC_##x,
369   RESULT_COUNTS(RC_INDEX, RC_INDEX)
370   RCI_max
371 } ResultCountIndex;
372
373
374 /*----- transmission buffers -----*/
375
376 #define CONNIOVS 128
377
378 typedef enum {
379   xk_Malloc, xk_Const, xk_Artdata
380 } XmitKind;
381
382 struct XmitDetails {
383   XmitKind kind;
384   union {
385     char *malloc_tofree;
386     ARTHANDLE *sm_art;
387   } info;
388 };
389
390
391 /*----- core operational data structure types -----*/
392
393 struct InputFile {
394   /* This is also an instance of struct oop_readable */
395   struct oop_readable readable; /* first */
396   oop_readable_call *readable_callback;
397   void *readable_callback_user;
398
399   int fd;
400   Filemon_Perfile *filemon;
401
402   oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
403   long inprogress; /* no. of articles read but not processed */
404   off_t offset;
405   int skippinglong;
406
407   int counts[art_MaxState][RCI_max];
408   int readcount_ok, readcount_blank, readcount_err;
409   char path[];
410 };
411
412 struct Article {
413   ISNODE(Article);
414   ArtState state;
415   int midlen;
416   InputFile *ipf;
417   TOKEN token;
418   off_t offset;
419   int blanklen;
420   char messageid[1];
421 };
422
423 #define SMS_LIST(X)                             \
424   X(NORMAL)                                     \
425   X(FLUSHING)                                   \
426   X(FLUSHFAILED)                                \
427   X(SEPARATED)                                  \
428   X(DROPPING)                                   \
429   X(DROPPED)
430
431 enum StateMachineState {
432 #define SMS_DEF_ENUM(s) sm_##s,
433   SMS_LIST(SMS_DEF_ENUM)
434 };
435
436 static const char *sms_names[]= {
437 #define SMS_DEF_NAME(s) #s ,
438   SMS_LIST(SMS_DEF_NAME)
439   0
440 };
441
442 struct Conn {
443   ISNODE(Conn);
444   int fd; /* may be 0, meaning closed (during construction/destruction) */
445   oop_read *rd; /* likewise */
446   int max_queue, stream, quitting;
447   int since_activity; /* periods */
448   ArticleList waiting; /* not yet told peer */
449   ArticleList priority; /* peer says send it now */
450   ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
451   struct iovec xmit[CONNIOVS];
452   XmitDetails xmitd[CONNIOVS];
453   int xmitu;
454 };
455
456
457 /*----- general operational variables -----*/
458
459 /* main initialises */
460 static oop_source *loop;
461 static ConnList conns;
462 static ArticleList queue;
463 static char *path_lock, *path_flushing, *path_defer, *globpat_backlog;
464
465 /* statemc_init initialises */
466 static StateMachineState sms;
467 static FILE *defer;
468 static InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
469 static int sm_period_counter;
470
471 /* initialisation to 0 is good */
472 static int until_connect, until_backlog_nextscan;
473 static double accept_proportion;
474 static int nocheck, nocheck_reported;
475
476 /*========== logging ==========*/
477
478 static void logcore(int sysloglevel, const char *fmt, ...) PRINTF(2,3);
479 static void logcore(int sysloglevel, const char *fmt, ...) {
480   VA;
481   if (become_daemon) {
482     vsyslog(sysloglevel,fmt,al);
483   } else {
484     vfprintf(stderr,fmt,al);
485     putc('\n',stderr);
486   }
487   va_end(al);
488 }
489
490 static void logv(int sysloglevel, const char *pfx, int errnoval,
491                  const char *fmt, va_list al) PRINTF(5,0);
492 static void logv(int sysloglevel, const char *pfx, int errnoval,
493                  const char *fmt, va_list al) {
494   char msgbuf[256]; /* NB do not call xvasprintf here or you'll recurse */
495   vsnprintf(msgbuf,sizeof(msgbuf), fmt,al);
496   msgbuf[sizeof(msgbuf)-1]= 0;
497
498   if (sysloglevel >= LOG_ERR && (errnoval==EACCES || errnoval==EPERM))
499     sysloglevel= LOG_ERR; /* run by wrong user, probably */
500
501   logcore(sysloglevel, "<%s>%s: %s%s%s",
502          sitename, pfx, msgbuf,
503          errnoval>=0 ? ": " : "",
504          errnoval>=0 ? strerror(errnoval) : "");
505 }
506
507 #define diewrap(fn, pfx, sysloglevel, err, estatus)             \
508   static void fn(const char *fmt, ...) NORET_PRINTF(1,2);       \
509   static void fn(const char *fmt, ...) {                        \
510     VA;                                                         \
511     logv(sysloglevel, pfx, err, fmt, al);                       \
512     exit(estatus);                                              \
513   }
514
515 #define logwrap(fn, pfx, sysloglevel, err)              \
516   static void fn(const char *fmt, ...) PRINTF(1,2);     \
517   static void fn(const char *fmt, ...) {                \
518     VA;                                                 \
519     logv(sysloglevel, pfx, err, fmt, al);               \
520     va_end(al);                                         \
521   }
522
523 diewrap(sysdie,   " critical", LOG_CRIT,    errno, 16);
524 diewrap(die,      " critical", LOG_CRIT,    -1,    16);
525
526 diewrap(sysfatal, " fatal",    LOG_ERR,     errno, 12);
527 diewrap(fatal,    " fatal",    LOG_ERR,     -1,    12);
528
529 logwrap(syswarn,  " warning",  LOG_WARNING, errno);
530 logwrap(warn,     " warning",  LOG_WARNING, -1);
531
532 logwrap(notice,   "",          LOG_NOTICE,  -1);
533 logwrap(info,     " info",     LOG_INFO,    -1);
534 logwrap(debug,    " debug",    LOG_DEBUG,   -1);
535
536
537 /*========== utility functions etc. ==========*/
538
539 static char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
540 static char *xvasprintf(const char *fmt, va_list al) {
541   char *str;
542   int rc= vasprintf(&str,fmt,al);
543   if (rc<0) sysdie("vasprintf(\"%s\",...) failed", fmt);
544   return str;
545 }
546 static char *xasprintf(const char *fmt, ...) PRINTF(1,2);
547 static char *xasprintf(const char *fmt, ...) {
548   VA;
549   char *str= xvasprintf(fmt,al);
550   va_end(al);
551   return str;
552 }
553
554 static int close_perhaps(int *fd) {
555   if (!*fd) return 0;
556   int r= close(*fd);
557   *fd=0;
558   return r;
559 }
560 static void xclose(int fd, const char *what, const char *what2) {
561   int r= close(fd);
562   if (r) sysdie("close %s%s",what,what2?what2:"");
563 }
564 static void xclose_perhaps(int *fd, const char *what, const char *what2) {
565   if (!*fd) return;
566   xclose(*fd,what,what2);
567   *fd=0;
568 }
569
570 static pid_t xfork(const char *what) {
571   pid_t child;
572
573   child= fork();
574   if (child==-1) sysdie("cannot fork for %s",what);
575   debug("forked %s %ld", what, (unsigned long)child);
576   if (!child) postfork();
577   return child;
578 }
579
580 static void on_fd_read_except(int fd, oop_call_fd callback) {
581   loop->on_fd(loop, fd, OOP_READ,      callback, 0);
582   loop->on_fd(loop, fd, OOP_EXCEPTION, callback, 0);
583 }
584 static void cancel_fd_read_except(int fd) {
585   loop->cancel_fd(loop, fd, OOP_READ);
586   loop->cancel_fd(loop, fd, OOP_EXCEPTION);
587 }
588
589 static void report_child_status(const char *what, int status) {
590   if (WIFEXITED(status)) {
591     int es= WEXITSTATUS(status);
592     if (es)
593       warn("%s: child died with error exit status %d", what, es);
594   } else if (WIFSIGNALED(status)) {
595     int sig= WTERMSIG(status);
596     const char *sigstr= strsignal(sig);
597     const char *coredump= WCOREDUMP(status) ? " (core dumped)" : "";
598     if (sigstr)
599       warn("%s: child died due to fatal signal %s%s", what, sigstr, coredump);
600     else
601       warn("%s: child died due to unknown fatal signal %d%s",
602            what, sig, coredump);
603   } else {
604     warn("%s: child died with unknown wait status %d", what,status);
605   }
606 }
607
608 static int xwaitpid(pid_t *pid, const char *what) {
609   int status;
610
611   int r= kill(*pid, SIGKILL);
612   if (r) sysdie("cannot kill %s child", what);
613
614   pid_t got= waitpid(*pid, &status, WNOHANG);
615   if (got==-1) sysdie("cannot reap %s child", what);
616
617   *pid= 0;
618
619   return status;
620 }
621
622 static void xunlink(const char *path, const char *what) {
623   int r= unlink(path);
624   if (r) sysdie("can't unlink %s %s", path, what);
625 }
626
627 static time_t xtime(void) {
628   time_t now= time(0);
629   if (now==-1) sysdie("time(2) failed");
630   return now;
631 }
632
633 static void check_isreg(const struct stat *stab, const char *path,
634                         const char *what) {
635   if (!S_ISREG(stab->st_mode))
636     die("%s %s not a plain file (mode 0%lo)",
637         what, path, (unsigned long)stab->st_mode);
638 }
639
640 static void xfstat(int fd, struct stat *stab_r, const char *what) {
641   int r= fstat(fd, stab_r);
642   if (r) sysdie("could not fstat %s", what);
643 }
644
645 static void xfstat_isreg(int fd, struct stat *stab_r,
646                          const char *path, const char *what) {
647   xfstat(fd, stab_r, what);
648   check_isreg(stab_r, path, what);
649 }
650
651 static void xlstat_isreg(const char *path, struct stat *stab,
652                          int *enoent_r /* 0 means ENOENT is fatal */,
653                          const char *what) {
654   int r= lstat(path, stab);
655   if (r) {
656     if (errno==ENOENT && enoent_r) { *enoent_r=1; return; }
657     sysdie("could not lstat %s %s", what, path);
658   }
659   if (enoent_r) *enoent_r= 0;
660   check_isreg(stab, path, what);
661 }
662
663 static int samefile(const struct stat *a, const struct stat *b) {
664   assert(S_ISREG(a->st_mode));
665   assert(S_ISREG(b->st_mode));
666   return (a->st_ino == b->st_ino &&
667           a->st_dev == b->st_dev);
668 }
669
670 static char *sanitise(const char *input) {
671   static char sanibuf[100]; /* returns pointer to this buffer! */
672
673   const char *p= input;
674   char *q= sanibuf;
675   *q++= '`';
676   for (;;) {
677     if (q > sanibuf+sizeof(sanibuf)-8) { strcpy(q,"'.."); break; }
678     int c= *p++;
679     if (!c) { *q++= '\''; *q=0; break; }
680     if (c>=' ' && c<=126 && c!='\\') { *q++= c; continue; }
681     sprintf(q,"\\x%02x",c);
682     q += 4;
683   }
684   return sanibuf;
685 }
686
687 static int isewouldblock(int errnoval) {
688   return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
689 }
690
691 /*========== management of connections ==========*/
692
693 static void conn_closefd(Conn *conn, const char *msgprefix) {
694   int r= close_perhaps(&conn->fd);
695   if (r) info("C%d %serror closing socket: %s",
696               conn->fd, msgprefix, strerror(errno));
697 }
698
699 static void conn_dispose(Conn *conn) {
700   if (!conn) return;
701   if (conn->rd) {
702     oop_rd_cancel(conn->rd);
703     oop_rd_delete_kill(conn->rd);
704     conn->rd= 0;
705   }
706   if (conn->fd) {
707     loop->cancel_fd(loop, conn->fd, OOP_WRITE);
708     loop->cancel_fd(loop, conn->fd, OOP_EXCEPTION);
709   }
710   conn_closefd(conn,"");
711   free(conn);
712   until_connect= reconnect_delay_periods;
713 }
714
715 static void *conn_exception(oop_source *lp, int fd,
716                             oop_event ev, void *conn_v) {
717   Conn *conn= conn_v;
718   unsigned char ch;
719   assert(fd == conn->fd);
720   assert(ev == OOP_EXCEPTION);
721   int r= read(conn->fd, &ch, 1);
722   if (r<0) connfail(conn,"read failed: %s",strerror(errno));
723   else connfail(conn,"exceptional condition on socket (peer sent urgent"
724                 " data? read(,&ch,1)=%d,ch='\\x%02x')",r,ch);
725   return OOP_CONTINUE;
726 }  
727
728 static void vconnfail(Conn *conn, const char *fmt, va_list al) {
729   int requeue[art_MaxState];
730
731   Article *art;
732   while ((art= LIST_REMHEAD(conn->priority))) LIST_ADDTAIL(queue, art);
733   while ((art= LIST_REMHEAD(conn->waiting))) LIST_ADDTAIL(queue, art);
734   while ((art= LIST_REMHEAD(conn->sent))) {
735     requeue[art->state]++;
736     if (art->state==art_Unsolicited) art->state= art_Unchecked;
737     LIST_ADDTAIL(queue,art);
738   }
739
740   int i;
741   XmitDetails *d;
742   for (i=0, d=conn->xmitd; i<conn->xmitu; i++, d++)
743     xmit_free(d);
744
745   char *m= xvasprintf(fmt,al);
746   warn("C%d connection failed (requeueing " RCI_TRIPLE_FMT_BASE "): %s",
747        conn->fd, RCI_TRIPLE_VALS_BASE(requeue, /*nothing*/), m);
748   free(m);
749
750   LIST_REMOVE(conns,conn);
751   conn_dispose(conn);
752   check_assign_articles();
753 }
754
755 static void connfail(Conn *conn, const char *fmt, ...) {
756   va_list al;
757   va_start(al,fmt);
758   vconnfail(conn,fmt,al);
759   va_end(al);
760 }
761
762 static void check_idle_conns(void) {
763   Conn *conn;
764   for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
765     conn->since_activity++;
766  search_again:
767   for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn)) {
768     if (conn->since_activity <= need_activity_periods) continue;
769
770     /* We need to shut this down */
771     if (conn->quitting)
772       connfail(conn,"timed out waiting for response to QUIT");
773     else if (conn->sent.count)
774       connfail(conn,"timed out waiting for responses");
775     else if (conn->waiting.count || conn->priority.count)
776       connfail(conn,"BUG IN INNDUCT conn has queue but nothing sent");
777     else if (conn->xmitu)
778       connfail(conn,"peer has been sending responses"
779                " before receiving our commands!");
780     else {
781       static const char quitcmd[]= "QUIT\r\n";
782       int todo= sizeof(quitcmd)-1;
783       const char *p= quitcmd;
784       for (;;) {
785         int r= write(conn->fd, p, todo);
786         if (r<0) {
787           if (isewouldblock(errno))
788             connfail(conn, "blocked writing QUIT to idle connection");
789           else
790             connfail(conn, "failed to write QUIT to idle connection: %s",
791                      strerror(errno));
792           break;
793         }
794         assert(r<=todo);
795         todo -= r;
796         if (!todo) {
797           conn->quitting= 1;
798           conn->since_activity= 0;
799           debug("C%d is idle, quitting", conn->fd);
800           break;
801         }
802       }
803     }
804     goto search_again;
805   }
806 }  
807
808 /*---------- making new connections ----------*/
809
810 static pid_t connecting_child;
811 static int connecting_fdpass_sock;
812
813 static void connect_attempt_discard(void) {
814   if (connecting_child) {
815     int r= kill(connecting_child, SIGTERM);
816     if (r) syswarn("failed to kill connecting child");
817     int status= xwaitpid(&connecting_child, "connect");
818
819     if (!(WIFEXITED(status) ||
820           (WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)))
821       report_child_status("connect", status);
822   }
823   if (connecting_fdpass_sock) {
824     cancel_fd_read_except(connecting_fdpass_sock);
825     xclose_perhaps(&connecting_fdpass_sock, "connecting fdpass socket",0);
826   }
827 }
828
829 #define PREP_DECL_MSG_CMSG(msg)                 \
830   struct msghdr msg;                            \
831   memset(&msg,0,sizeof(msg));                   \
832   char msg##cbuf[CMSG_SPACE(sizeof(fd))];       \
833   msg.msg_control= msg##cbuf;                   \
834   msg.msg_controllen= sizeof(msg##cbuf);
835
836 static void *connchild_event(oop_source *lp, int fd, oop_event e, void *u) {
837   Conn *conn= 0;
838
839   assert(fd == connecting_fdpass_sock);
840
841   conn= xmalloc(sizeof(*conn));
842   memset(conn,0,sizeof(*conn));
843
844   PREP_DECL_MSG_CMSG(msg);
845   struct cmsghdr *h= 0;
846   ssize_t rs= recvmsg(fd, &msg, MSG_DONTWAIT);
847   if (rs >= 0) h= CMSG_FIRSTHDR(&msg);
848   if (!h) {
849     int status;
850     pid_t got= waitpid(connecting_child, &status, WNOHANG);
851     if (got != -1) {
852       assert(got==connecting_child);
853       connecting_child= 0;
854       if (WIFEXITED(status)) {
855         if (WEXITSTATUS(status) != 0 &&
856             WEXITSTATUS(status) != CONNCHILD_ESTATUS_STREAM &&
857             WEXITSTATUS(status) != CONNCHILD_ESTATUS_NOSTREAM)
858           /* child already reported the problem */;
859         else
860           warn("connect: connection child exited code %d but no cmsg",
861                WEXITSTATUS(status));
862       } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
863         warn("connect: connection attempt timed out");
864       } else {
865         report_child_status("connect", status);
866       }
867     } else {
868       /* child is still running apparently, report the socket problem */
869       if (rs < 0)
870         syswarn("connect: read from fdpass socket failed");
871       else if (e == OOP_EXCEPTION)
872         warn("connect: unexpected exception on fdpass socket");
873       else if (!rs)
874         warn("connect: unexpected EOF on fdpass socket");
875       else
876         fatal("connect: unexpected lack of cmsg from child");
877     }
878     goto x;
879   }
880
881 #define CHK(field, val)                                                  \
882   if (h->cmsg_##field != val) {                                          \
883     die("connect: child sent cmsg with cmsg_" #field "=%d, expected %d", \
884         h->cmsg_##field, val);                                           \
885     goto x;                                                              \
886   }
887   CHK(level, SOL_SOCKET);
888   CHK(type,  SCM_RIGHTS);
889   CHK(len,   CMSG_LEN(sizeof(conn->fd)));
890 #undef CHK
891
892   if (CMSG_NXTHDR(&msg,h)) die("connect: child sent many cmsgs");
893
894   memcpy(&conn->fd, CMSG_DATA(h), sizeof(conn->fd));
895
896   int status;
897   pid_t got= waitpid(connecting_child, &status, 0);
898   if (got==-1) sysdie("connect: real wait for child");
899   assert(got == connecting_child);
900   connecting_child= 0;
901
902   if (!WIFEXITED(status)) { report_child_status("connect",status); goto x; }
903   int es= WEXITSTATUS(status);
904   switch (es) {
905   case CONNCHILD_ESTATUS_STREAM:    conn->stream= 1;   break;
906   case CONNCHILD_ESTATUS_NOSTREAM:  conn->stream= 0;   break;
907   default:
908     fatal("connect: child gave unexpected exit status %d", es);
909   }
910
911   /* Phew! */
912   LIST_INIT(conn->waiting);
913   LIST_INIT(conn->priority);
914   LIST_INIT(conn->sent);
915   conn->max_queue= conn->stream ? max_queue_per_conn : 1;
916
917   loop->on_fd(loop, conn->fd, OOP_EXCEPTION, conn_exception, conn);
918   conn->rd= oop_rd_new_fd(loop,conn->fd, 0, 0); /* sets nonblocking, too */
919   if (!conn->fd) sysdie("oop_rd_new_fd (fd=%d)",conn->fd);
920   int r= oop_rd_read(conn->rd, &peer_rd_style, NNTP_STRLEN,
921                      &peer_rd_ok, conn,
922                      &peer_rd_err, conn);
923   if (r) sysdie("oop_rd_read for peer (fd=%d)",conn->fd);
924
925   notice("C%d connected %s", conn->fd, conn->stream ? "streaming" : "plain");
926   LIST_ADDHEAD(conns, conn);
927
928   connect_attempt_discard();
929   check_assign_articles();
930   return 0;
931
932  x:
933   conn_dispose(conn);
934   connect_attempt_discard();
935   return OOP_CONTINUE;
936 }
937
938 static int allow_connect_start(void) {
939   return conns.count < max_connections
940     && !connecting_child
941     && !until_connect;
942 }
943
944 static void connect_start(void) {
945   assert(!connecting_child);
946   assert(!connecting_fdpass_sock);
947
948   notice("starting connection attempt");
949
950   int socks[2];
951   int r= socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
952   if (r) { syswarn("connect: cannot create socketpair for child"); return; }
953
954   connecting_child= xfork("connection");
955
956   if (!connecting_child) {
957     FILE *cn_from, *cn_to;
958     char buf[NNTP_STRLEN+100];
959     int exitstatus= CONNCHILD_ESTATUS_NOSTREAM;
960
961     xclose(socks[0], "(in child) parent's connection fdpass socket",0);
962
963     alarm(connection_setup_timeout);
964     if (NNTPconnect((char*)remote_host, port, &cn_from, &cn_to, buf) < 0) {
965       if (buf[0]) fatal("connect: rejected: %s", sanitise(buf));
966       else sysfatal("connect: connection attempt failed");
967     }
968     if (NNTPsendpassword((char*)remote_host, cn_from, cn_to) < 0)
969       sysfatal("connect: authentication failed");
970     if (try_stream) {
971       if (fputs("MODE STREAM\r\n", cn_to) ||
972           fflush(cn_to))
973         sysfatal("connect: could not send MODE STREAM");
974       buf[sizeof(buf)-1]= 0;
975       if (!fgets(buf, sizeof(buf)-1, cn_from)) {
976         if (ferror(cn_from))
977           sysfatal("connect: could not read response to MODE STREAM");
978         else
979           fatal("connect: connection close in response to MODE STREAM");
980       }
981       int l= strlen(buf);
982       assert(l>=1);
983       if (buf[-1]!='\n')
984         fatal("connect: response to MODE STREAM is too long: %.100s...",
985               sanitise(buf));
986       l--;  if (l>0 && buf[l-1]=='\r') l--;
987       buf[l]= 0;
988       char *ep;
989       int rcode= strtoul(buf,&ep,10);
990       if (ep != &buf[3])
991         fatal("connect: bad response to MODE STREAM: %.50s", sanitise(buf));
992
993       switch (rcode) {
994       case 203:
995         exitstatus= CONNCHILD_ESTATUS_STREAM;
996         break;
997       case 480:
998       case 500:
999         break;
1000       default:
1001         warn("connect: unexpected response to MODE STREAM: %.50s",
1002              sanitise(buf));
1003         exitstatus= 2;
1004         break;
1005       }
1006     }
1007     int fd= fileno(cn_from);
1008
1009     PREP_DECL_MSG_CMSG(msg);
1010     struct cmsghdr *cmsg= CMSG_FIRSTHDR(&msg);
1011     cmsg->cmsg_level= SOL_SOCKET;
1012     cmsg->cmsg_type=  SCM_RIGHTS;
1013     cmsg->cmsg_len=   CMSG_LEN(sizeof(fd));
1014     memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
1015
1016     msg.msg_controllen= cmsg->cmsg_len;
1017     r= sendmsg(socks[1], &msg, 0);
1018     if (r) sysdie("sendmsg failed for new connection");
1019
1020     _exit(exitstatus);
1021   }
1022
1023   xclose(socks[1], "connecting fdpass child's socket",0);
1024   connecting_fdpass_sock= socks[0];
1025   on_fd_read_except(connecting_fdpass_sock, connchild_event);
1026 }
1027
1028 /*---------- assigning articles to conns, and transmitting ----------*/
1029
1030 static void check_assign_articles(void) {
1031   for (;;) {
1032     if (!queue.count)
1033       break;
1034
1035     Conn *walk, *use=0;
1036     int spare=0, inqueue=0;
1037
1038     /* Find a connection to offer this article.  We prefer a busy
1039      * connection to an idle one, provided it's not full.  We take the
1040      * first (oldest) and since that's stable, it will mean we fill up
1041      * connections in order.  That way if we have too many
1042      * connections, the spare ones will go away eventually.
1043      */
1044     for (walk=LIST_HEAD(conns); walk; walk=LIST_NEXT(walk)) {
1045       if (walk->quitting) continue;
1046       inqueue= walk->sent.count + walk->priority.count
1047              + walk->waiting.count;
1048       spare= walk->max_queue - inqueue;
1049       assert(inqueue <= max_queue_per_conn);
1050       assert(spare >= 0);
1051       if (inqueue==0) /*idle*/ { if (!use) use= walk; }
1052       else if (spare>0) /*working*/ { use= walk; break; }
1053     }
1054     if (use) {
1055       if (!inqueue) use->since_activity= 0; /* reset idle counter */
1056       while (spare>0) {
1057         Article *art= LIST_REMHEAD(queue);
1058         LIST_ADDTAIL(use->waiting, art);
1059         spare--;
1060       }
1061       conn_maybe_write(use);
1062     } else if (allow_connect_start()) {
1063       until_connect= reconnect_delay_periods;
1064       connect_start();
1065       break;
1066     } else {
1067       break;
1068     }
1069   }
1070 }
1071
1072 static void *conn_writeable(oop_source *l, int fd, oop_event ev, void *u) {
1073   conn_maybe_write(u);
1074   return OOP_CONTINUE;
1075 }
1076
1077 static void conn_maybe_write(Conn *conn)  {
1078   for (;;) {
1079     conn_make_some_xmits(conn);
1080     if (!conn->xmitu) {
1081       loop->cancel_fd(loop, conn->fd, OOP_WRITE);
1082       return;
1083     }
1084
1085     void *rp= conn_write_some_xmits(conn);
1086     if (rp==OOP_CONTINUE) {
1087       loop->on_fd(loop, conn->fd, OOP_WRITE, conn_writeable, conn);
1088       return;
1089     } else if (rp==OOP_HALT) {
1090       return;
1091     } else if (!rp) {
1092       /* transmitted everything */
1093     } else {
1094       abort();
1095     }
1096   }
1097 }
1098
1099 /*========== article transmission ==========*/
1100
1101 static XmitDetails *xmit_core(Conn *conn, const char *data, int len,
1102                   XmitKind kind) { /* caller must then fill in details */
1103   struct iovec *v= &conn->xmit[conn->xmitu];
1104   XmitDetails *d= &conn->xmitd[conn->xmitu++];
1105   v->iov_base= (char*)data;
1106   v->iov_len= len;
1107   d->kind= kind;
1108   return d;
1109 }
1110
1111 static void xmit_noalloc(Conn *conn, const char *data, int len) {
1112   xmit_core(conn,data,len, xk_Const);
1113 }
1114 #define XMIT_LITERAL(lit) (xmit_noalloc(conn, (lit), sizeof(lit)-1))
1115
1116 static void xmit_artbody(Conn *conn, ARTHANDLE *ah /* consumed */) {
1117   XmitDetails *d= xmit_core(conn, ah->data, ah->len, xk_Artdata);
1118   d->info.sm_art= ah;
1119 }
1120
1121 static void xmit_free(XmitDetails *d) {
1122   switch (d->kind) {
1123   case xk_Malloc:  free(d->info.malloc_tofree);   break;
1124   case xk_Artdata: SMfreearticle(d->info.sm_art); break;
1125   case xk_Const:                                  break;
1126   default: abort();
1127   }
1128 }
1129
1130 static void *conn_write_some_xmits(Conn *conn) {
1131   /* return values:
1132    *      0:            nothing more to write, no need to call us again
1133    *      OOP_CONTINUE: more to write but fd not writeable
1134    *      OOP_HALT:     disaster, have destroyed conn
1135    */
1136   for (;;) {
1137     int count= conn->xmitu;
1138     if (!count) return 0;
1139
1140     if (count > IOV_MAX) count= IOV_MAX;
1141     ssize_t rs= writev(conn->fd, conn->xmit, count);
1142     if (rs < 0) {
1143       if (isewouldblock(errno)) return OOP_CONTINUE;
1144       connfail(conn, "write failed: %s", strerror(errno));
1145       return OOP_HALT;
1146     }
1147     assert(rs > 0);
1148
1149     int done;
1150     for (done=0; rs && done<conn->xmitu; done++) {
1151       struct iovec *vp= &conn->xmit[done];
1152       XmitDetails *dp= &conn->xmitd[done];
1153       if (rs > vp->iov_len) {
1154         rs -= vp->iov_len;
1155         xmit_free(dp);
1156       } else {
1157         vp->iov_base= (char*)vp->iov_base + rs;
1158         vp->iov_len -= rs;
1159       }
1160     }
1161     int newu= conn->xmitu - done;
1162     memmove(conn->xmit,  conn->xmit  + done, newu * sizeof(*conn->xmit));
1163     memmove(conn->xmitd, conn->xmitd + done, newu * sizeof(*conn->xmitd));
1164     conn->xmitu= newu;
1165   }
1166 }
1167
1168 static void conn_make_some_xmits(Conn *conn) {
1169   for (;;) {
1170     if (conn->xmitu+5 > CONNIOVS)
1171       break;
1172
1173     Article *art= LIST_REMHEAD(conn->priority);
1174     if (!art) art= LIST_REMHEAD(conn->waiting);
1175     if (!art) break;
1176
1177     if (art->state >= art_Wanted || (conn->stream && nocheck)) {
1178       /* actually send it */
1179
1180       ARTHANDLE *artdata= SMretrieve(art->token, RETR_ALL);
1181
1182       if (conn->stream) {
1183         if (artdata) {
1184           XMIT_LITERAL("TAKETHIS ");
1185           xmit_noalloc(conn, art->messageid, art->midlen);
1186           XMIT_LITERAL("\r\n");
1187           xmit_artbody(conn, artdata);
1188         }
1189       } else {
1190         /* we got 235 from IHAVE */
1191         if (artdata) {
1192           xmit_artbody(conn, artdata);
1193         } else {
1194           XMIT_LITERAL(".\r\n");
1195         }
1196       }
1197
1198       art->state=
1199         art->state == art_Unchecked ? art_Unsolicited :
1200         art->state == art_Wanted    ? art_Wanted      :
1201         (abort(),-1);
1202       art->ipf->counts[art->state][RC_sent]++;
1203       LIST_ADDTAIL(conn->sent, art);
1204
1205     } else {
1206       /* check it */
1207
1208       if (conn->stream)
1209         XMIT_LITERAL("IHAVE ");
1210       else
1211         XMIT_LITERAL("CHECK ");
1212       xmit_noalloc(conn, art->messageid, art->midlen);
1213       XMIT_LITERAL("\r\n");
1214
1215       assert(art->state == art_Unchecked);
1216       art->ipf->counts[art->state][RC_sent]++;
1217       LIST_ADDTAIL(conn->sent, art);
1218     }
1219   }
1220 }
1221
1222
1223 /*========== handling responses from peer ==========*/
1224
1225 static const oop_rd_style peer_rd_style= {
1226   OOP_RD_DELIM_STRIP, '\n',
1227   OOP_RD_NUL_FORBID,
1228   OOP_RD_SHORTREC_FORBID
1229 };
1230
1231 static void *peer_rd_err(oop_source *lp, oop_read *oread, oop_rd_event ev,
1232                          const char *errmsg, int errnoval,
1233                          const char *data, size_t recsz, void *conn_v) {
1234   Conn *conn= conn_v;
1235   connfail(conn, "error receiving from peer: %s", errmsg);
1236   return OOP_CONTINUE;
1237 }
1238
1239 static Article *article_reply_check(Conn *conn, const char *response,
1240                                     int code_indicates_streaming,
1241                                     int must_have_sent
1242                                         /* 1:yes, -1:no, 0:dontcare */,
1243                                     const char *sanitised_response) {
1244   Article *art= LIST_HEAD(conn->sent);
1245
1246   if (!art) {
1247     connfail(conn,
1248              "peer gave unexpected response when no commands outstanding: %s",
1249              sanitised_response);
1250     return 0;
1251   }
1252
1253   if (code_indicates_streaming) {
1254     assert(!memchr(response, 0, 4)); /* ensured by peer_rd_ok */
1255     if (!conn->stream) {
1256       connfail(conn, "peer gave streaming response code "
1257                " to IHAVE or subsequent body: %s", sanitised_response);
1258       return 0;
1259     }
1260     const char *got_mid= response+4;
1261     int got_midlen= strcspn(got_mid, " \n\r");
1262     if (got_midlen<3 || got_mid[0]!='<' || got_mid[got_midlen-1]!='>') {
1263       connfail(conn, "peer gave streaming response with syntactically invalid"
1264                " messageid: %s", sanitised_response);
1265       return 0;
1266     }
1267     if (got_midlen != art->midlen ||
1268         memcmp(got_mid, art->messageid, got_midlen)) {
1269       connfail(conn, "peer gave streaming response code to wrong article -"
1270                " probable synchronisation problem; we offered: %s;"
1271                " peer said: %s",
1272                art->messageid, sanitised_response);
1273       return 0;
1274     }
1275   } else {
1276     if (conn->stream) {
1277       connfail(conn, "peer gave non-streaming response code to"
1278                " CHECK/TAKETHIS: %s", sanitised_response);
1279       return 0;
1280     }
1281   }
1282
1283   if (must_have_sent>0 && art->state < art_Wanted) {
1284     connfail(conn, "peer says article accepted but"
1285              " we had not sent the body: %s", sanitised_response);
1286     return 0;
1287   }
1288   if (must_have_sent<0 && art->state >= art_Wanted) {
1289     connfail(conn, "peer says please sent the article but we just did: %s",
1290              sanitised_response);
1291     return 0;
1292   }
1293
1294   Article *art_again= LIST_REMHEAD(conn->sent);
1295   assert(art_again == art);
1296   return art;
1297 }
1298
1299 static void update_nocheck(int accepted) {
1300   accept_proportion *= nocheck_decay;
1301   accept_proportion += accepted * (1.0 - nocheck_decay);
1302   int new_nocheck= accept_proportion >= nocheck_thresh;
1303   if (new_nocheck && !nocheck_reported) {
1304     notice("entering nocheck mode for the first time");
1305     nocheck_reported= 1;
1306   } else if (new_nocheck != nocheck) {
1307     debug("nocheck mode %s", new_nocheck ? "start" : "stop");
1308   }
1309   nocheck= new_nocheck;
1310 }
1311
1312 static void article_done(Conn *conn, Article *art, int whichcount) {
1313   art->ipf->counts[art->state][whichcount]++;
1314   if (whichcount == RC_accepted) update_nocheck(1);
1315   else if (whichcount == RC_unwanted) update_nocheck(0);
1316
1317   InputFile *ipf= art->ipf;
1318
1319   while (art->blanklen) {
1320     static const char spaces[]=
1321       "                                                                "
1322       "                                                                "
1323       "                                                                "
1324       "                                                                ";
1325     int w= art->blanklen;  if (w >= sizeof(spaces)) w= sizeof(spaces)-1;
1326     int r= pwrite(ipf->fd, spaces, w, art->offset);
1327     if (r==-1) {
1328       if (errno==EINTR) continue;
1329       sysdie("failed to blank entry for %s (length %d at offset %lu) in %s",
1330              art->messageid, art->blanklen,
1331              (unsigned long)art->offset, ipf->path);
1332     }
1333     assert(r>=0 && r<=w);
1334     art->blanklen -= w;
1335     art->offset += w;
1336   }
1337
1338   ipf->inprogress--;
1339   assert(ipf->inprogress >= 0);
1340   free(art);
1341
1342   if (!ipf->inprogress && ipf != main_input_file)
1343     queue_check_input_done();
1344 }
1345
1346 static void *peer_rd_ok(oop_source *lp, oop_read *oread, oop_rd_event ev,
1347                         const char *errmsg, int errnoval,
1348                         const char *data, size_t recsz, void *conn_v) {
1349   Conn *conn= conn_v;
1350
1351   if (ev == OOP_RD_EOF) {
1352     connfail(conn, "unexpected EOF from peer");
1353     return OOP_CONTINUE;
1354   }
1355   assert(ev == OOP_RD_OK);
1356
1357   char *sani= sanitise(data);
1358
1359   char *ep;
1360   unsigned long code= strtoul(data, &ep, 10);
1361   if (ep != data+3 || *ep != ' ' || data[0]=='0') {
1362     connfail(conn, "badly formatted response from peer: %s", sani);
1363     return OOP_CONTINUE;
1364   }
1365
1366   if (conn->quitting) {
1367     if (code!=205 && code!=503) {
1368       connfail(conn, "peer gave unexpected response to QUIT: %s", sani);
1369     } else {
1370       notice("C%d idle connection closed", conn->fd);
1371       assert(!conn->waiting.count);
1372       assert(!conn->priority.count);
1373       assert(!conn->sent.count);
1374       assert(!conn->xmitu);
1375       LIST_REMOVE(conns,conn);
1376       conn_dispose(conn);
1377     }
1378     return OOP_CONTINUE;
1379   }
1380
1381   conn->since_activity= 0;
1382   Article *art;
1383
1384 #define GET_ARTICLE(musthavesent)                                           \
1385   art= article_reply_check(conn, data, musthavesent, code_streaming, sani); \
1386   if (art) ; else return OOP_CONTINUE /* reply_check has failed the conn */
1387
1388 #define ARTICLE_DEALTWITH(streaming,musthavesent,how)           \
1389   code_streaming= (streaming);                                  \
1390   GET_ARTICLE(musthavesent);                                    \
1391   article_done(conn, art, RC_##how);  break;
1392
1393 #define PEERBADMSG(m) connfail(conn, m ": %s", sani);  return OOP_CONTINUE
1394
1395   int code_streaming= 0;
1396
1397   switch (code) {
1398
1399   case 400: PEERBADMSG("peer stopped accepting articles");
1400   case 503: PEERBADMSG("peer timed us out");
1401   default:  PEERBADMSG("peer sent unexpected message");
1402
1403   case 435: ARTICLE_DEALTWITH(0,0,unwanted); /* IHAVE says they have it */
1404   case 438: ARTICLE_DEALTWITH(1,0,unwanted); /* CHECK/TAKETHIS: they have it */
1405
1406   case 235: ARTICLE_DEALTWITH(0,1,accepted); /* IHAVE says thanks */
1407   case 239: ARTICLE_DEALTWITH(1,1,accepted); /* TAKETHIS says thanks */
1408
1409   case 437: ARTICLE_DEALTWITH(0,0,rejected); /* IHAVE says rejected */
1410   case 439: ARTICLE_DEALTWITH(1,0,rejected); /* TAKETHIS says rejected */
1411
1412   case 238: /* CHECK says send it */
1413     code_streaming= 1;
1414   case 335: /* IHAVE says send it */
1415     GET_ARTICLE(-1);
1416     assert(art->state == art_Unchecked);
1417     art->ipf->counts[art->state][RC_accepted]++;
1418     art->state= art_Wanted;
1419     LIST_ADDTAIL(conn->priority, art);
1420     break;
1421
1422   case 431: /* CHECK or TAKETHIS says try later */
1423     code_streaming= 1;
1424   case 436: /* IHAVE says try later */
1425     GET_ARTICLE(0);
1426     open_defer();
1427     if (fprintf(defer, "%s %s\n", TokenToText(art->token), art->messageid) <0
1428         || fflush(defer))
1429       sysfatal("write to defer file %s",path_defer);
1430     article_done(conn, art, RC_deferred);
1431     break;
1432
1433   }
1434
1435   conn_maybe_write(conn);
1436   check_assign_articles();
1437   return OOP_CONTINUE;
1438 }
1439
1440
1441 /*========== monitoring of input files ==========*/
1442
1443 static void feedfile_eof(InputFile *ipf) {
1444   assert(ipf != main_input_file); /* promised by tailing_try_read */
1445   inputfile_reading_stop(ipf);
1446
1447   if (ipf == flushing_input_file) {
1448     assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1449     if (main_input_file) inputfile_reading_start(main_input_file);
1450     statemc_check_flushing_done();
1451   } else if (ipf == backlog_input_file) {
1452     statemc_check_backlog_done();
1453   } else {
1454     abort(); /* supposed to wait rather than get EOF on main input file */
1455   }
1456 }
1457
1458 static InputFile *open_input_file(const char *path) {
1459   int fd= open(path, O_RDONLY);
1460   if (fd<0) {
1461     if (errno==ENOENT) return 0;
1462     sysfatal("unable to open input file %s", path);
1463   }
1464   assert(fd>0);
1465
1466   InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
1467   memset(ipf,0,sizeof(*ipf));
1468
1469   ipf->fd= fd;
1470   strcpy(ipf->path, path);
1471
1472   return ipf;
1473 }
1474
1475 static void close_input_file(InputFile *ipf) { /* does not free */
1476   assert(!ipf->readable_callback); /* must have had ->on_cancel */
1477   assert(!ipf->filemon); /* must have had inputfile_reading_stop */
1478   assert(!ipf->rd); /* must have had inputfile_reading_stop */
1479   assert(!ipf->inprogress); /* no dangling pointers pointing here */
1480   xclose_perhaps(&ipf->fd, "input file ", ipf->path);
1481 }
1482
1483
1484 /*---------- dealing with articles read in the input file ----------*/
1485
1486 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
1487                                    const char *data, const char *how) {
1488   warn("corrupted file: %s, offset %lu: %s: %s",
1489        ipf->path, (unsigned long)offset, how, sanitise(data));
1490   ipf->readcount_err++;
1491   if (ipf->readcount_err > max_bad_data_initial +
1492       (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
1493     die("too much garbage in input file!  (%d errs, %d ok, %d blank)",
1494         ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
1495   return OOP_CONTINUE;
1496 }
1497
1498 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
1499                                oop_rd_event ev, const char *errmsg,
1500                                int errnoval, const char *data, size_t recsz,
1501                                void *ipf_v) {
1502   InputFile *ipf= ipf_v;
1503   assert(ev == OOP_RD_SYSTEM);
1504   errno= errnoval;
1505   sysdie("error reading input file: %s, offset %lu",
1506          ipf->path, (unsigned long)ipf->offset);
1507 }
1508
1509 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
1510                                   oop_rd_event ev, const char *errmsg,
1511                                   int errnoval, const char *data, size_t recsz,
1512                                   void *ipf_v) {
1513   InputFile *ipf= ipf_v;
1514   Article *art;
1515   char tokentextbuf[sizeof(TOKEN)*2+3];
1516
1517   if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
1518
1519   off_t old_offset= ipf->offset;
1520   ipf->offset += recsz + 1;
1521
1522 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
1523
1524   if (ev==OOP_RD_PARTREC)
1525     feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
1526     /* but process it anyway */
1527
1528   if (ipf->skippinglong) {
1529     if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
1530     return OOP_CONTINUE;
1531   }
1532   if (ev==OOP_RD_LONG) {
1533     ipf->skippinglong= 1;
1534     X_BAD_DATA("overly long line");
1535   }
1536
1537   if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
1538   if (!recsz) X_BAD_DATA("empty line");
1539
1540   if (data[0]==' ') {
1541     if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
1542     ipf->readcount_blank++;
1543     return OOP_CONTINUE;
1544   }
1545
1546   char *space= strchr(data,' ');
1547   int tokenlen= space-data;
1548   int midlen= (int)recsz-tokenlen-1;
1549   if (midlen <= 2) X_BAD_DATA("no room for messageid");
1550   if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
1551
1552   if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
1553   memcpy(tokentextbuf, data, tokenlen);
1554   tokentextbuf[tokenlen]= 0;
1555   if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
1556
1557   ipf->readcount_ok++;
1558
1559   art= xmalloc(sizeof(*art) - 1 + midlen + 1);
1560   art->state= art_Unchecked;
1561   art->midlen= midlen;
1562   art->ipf= ipf;  ipf->inprogress++;
1563   art->token= TextToToken(tokentextbuf);
1564   art->offset= ipf->offset;
1565   art->blanklen= recsz;
1566   strcpy(art->messageid, space+1);
1567   LIST_ADDTAIL(queue, art);
1568
1569   if (sms==sm_NORMAL && ipf==main_input_file &&
1570       ipf->offset >= target_max_feedfile_size)
1571     statemc_start_flush("feed file size");
1572
1573   check_assign_articles();
1574   return OOP_CONTINUE;
1575 }
1576
1577 /*========== tailing input file ==========*/
1578
1579 static void *tailing_rable_call_time(oop_source *loop, struct timeval tv,
1580                                      void *user) {
1581   InputFile *ipf= user;
1582   return ipf->readable_callback(loop, &ipf->readable,
1583                                 ipf->readable_callback_user);
1584 }
1585
1586 static void tailing_on_cancel(struct oop_readable *rable) {
1587   InputFile *ipf= (void*)rable;
1588
1589   if (ipf->filemon) filemon_stop(ipf);
1590   loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1591   ipf->readable_callback= 0;
1592 }
1593
1594 static void tailing_queue_readable(InputFile *ipf) {
1595   /* lifetime of ipf here is OK because destruction will cause
1596    * on_cancel which will cancel this callback */
1597   loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
1598 }
1599
1600 static int tailing_on_readable(struct oop_readable *rable,
1601                                 oop_readable_call *cb, void *user) {
1602   InputFile *ipf= (void*)rable;
1603
1604   tailing_on_cancel(rable);
1605   ipf->readable_callback= cb;
1606   ipf->readable_callback_user= user;
1607   filemon_start(ipf);
1608
1609   tailing_queue_readable(ipf);
1610   return 0;
1611 }
1612
1613 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
1614                                 size_t length) {
1615   InputFile *ipf= (void*)rable;
1616   for (;;) {
1617     ssize_t r= read(ipf->fd, buffer, length);
1618     if (r==-1) {
1619       if (errno==EINTR) continue;
1620       return r;
1621     }
1622     if (!r) {
1623       if (ipf==main_input_file) {
1624         errno=EAGAIN;
1625         return -1;
1626       } else if (ipf==flushing_input_file) {
1627         assert(ipf->rd);
1628         assert(sms==sm_SEPARATED || sms==sm_DROPPING);
1629       } else if (ipf==backlog_input_file) {
1630         assert(ipf->rd);
1631       } else {
1632         abort();
1633       }
1634     }
1635     return r;
1636   }
1637 }
1638
1639 /*---------- filemon implemented with inotify ----------*/
1640
1641 #if defined(HAVE_INOTIFY) && !defined(HAVE_FILEMON)
1642 #define HAVE_FILEMON
1643
1644 #include <linux/inotify.h>
1645
1646 static int filemon_inotify_fd;
1647 static int filemon_inotify_wdmax;
1648 static InputFile **filemon_inotify_wd2ipf;
1649
1650 struct Filemon_Perfile {
1651   int wd;
1652 };
1653
1654 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) {
1655   int wd= inotify_add_watch(filemon_inotify_fd, ipf->path, IN_MODIFY);
1656   if (wd < 0) sysdie("inotify_add_watch %s", ipf->path);
1657
1658   if (wd >= filemon_inotify_wdmax) {
1659     int newmax= wd+2;
1660     filemon_inotify_wd= xrealloc(filemon_inotify_wd2ipf,
1661                                  sizeof(*filemon_inotify_wd2ipf) * newmax);
1662     memset(filemon_inotify_wd2ipf + filemon_inotify_wdmax, 0,
1663            sizeof(*filemon_inotify_wd2ipf) * (newmax - filemon_inotify_wdmax));
1664     filemon_inotify_wdmax= newmax;
1665   }
1666
1667   assert(!filemon_inotify_wd2ipf[wd]);
1668   filemon_inotify_wd2ipf[wd]= ipf;
1669
1670   debug("filemon inotify startfile %p wd=%d wdmax=%d",
1671         ipf, wd, filemon_inotify_wdmax);
1672
1673   pf->wd= wd;
1674 }
1675
1676 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) {
1677   int wd= pf->wd;
1678   debug("filemon inotify stopfile %p wd=%d", ipf, wd);
1679   int r= inotify_rm_watch(filemon_inotify_fd, filemon_inotify_wd);
1680   if (r) sysdie("inotify_rm_watch");
1681   filemon_inotify_wd2ipf[wd]= 0;
1682 }
1683
1684 static void *filemon_inotify_readable(oop_source *lp, int fd,
1685                                       oop_event e, void *u) {
1686   struct inotify_event iev;
1687   for (;;) {
1688     int r= read(filemon_inotify_fd, &iev, sizeof(iev));
1689     if (r==-1) {
1690       if (isewouldblock(errno)) break;
1691       sysdie("read from inotify master");
1692     } else if (r==sizeof(iev)) {
1693       assert(iev.wd >= 0 && iev.wd < filemon_inotify_wdmax);
1694     } else {
1695       die("inotify read %d bytes wanted struct of %d", r, (int)sizeof(iev));
1696     }
1697     InputFile *ipf= filemon_inotify_wd2ipf[iev.wd];
1698     debug("filemon inotify readable read %p wd=%p", iev.wd, ipf);
1699     filemon_callback(ipf);
1700   }
1701   return OOP_CONTINUE;
1702 }
1703
1704 static int filemon_method_init(void) {
1705   filemon_inotify_fd= inotify_init();
1706   if (filemon_inotify_fd<0) {
1707     syswarn("could not initialise inotify: inotify_init failed");
1708     return 0;
1709   }
1710   set nonblock;
1711   loop->on_fd(loop, filemon_inotify_fd, OOP_READ, filemon_inotify_readable);
1712
1713   debug("filemon inotify init filemon_inotify_fd=%d", filemon_inotify_fd);
1714   return 1;
1715 }
1716
1717 #endif /* HAVE_INOTIFY && !HAVE_FILEMON */
1718
1719 /*---------- filemon dummy implementation ----------*/
1720
1721 #if !defined(HAVE_FILEMON)
1722
1723 struct Filemon_Perfile { int dummy; };
1724
1725 static int filemon_method_init(void) { return 0; }
1726 static void filemon_method_startfile(InputFile *ipf, Filemon_Perfile *pf) { }
1727 static void filemon_method_stopfile(InputFile *ipf, Filemon_Perfile *pf) { }
1728
1729 #endif /* !HAVE_FILEMON */
1730
1731 /*---------- filemon generic interface ----------*/
1732
1733 static void filemon_start(InputFile *ipf) {
1734   assert(!ipf->filemon);
1735
1736   ipf->filemon= xmalloc(sizeof(*ipf->filemon));
1737   memset(ipf->filemon, 0, sizeof(*ipf->filemon));
1738   filemon_method_startfile(ipf, ipf->filemon);
1739 }
1740
1741 static void filemon_stop(InputFile *ipf) {
1742   if (!ipf->filemon) return;
1743   filemon_method_stopfile(ipf, ipf->filemon);
1744   free(ipf->filemon);
1745   ipf->filemon= 0;
1746 }
1747
1748 static void filemon_callback(InputFile *ipf) {
1749   ipf->readable_callback(loop, &ipf->readable, ipf->readable_callback_user);
1750 }
1751
1752 /*---------- interface to start and stop an input file ----------*/
1753
1754 static const oop_rd_style feedfile_rdstyle= {
1755   OOP_RD_DELIM_STRIP, '\n',
1756   OOP_RD_NUL_PERMIT,
1757   OOP_RD_SHORTREC_LONG,
1758 };
1759
1760 static void inputfile_reading_start(InputFile *ipf) {
1761   assert(!ipf->rd);
1762   ipf->readable.on_readable= tailing_on_readable;
1763   ipf->readable.on_cancel=   tailing_on_cancel;
1764   ipf->readable.try_read=    tailing_try_read;
1765   ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
1766   ipf->readable.delete_kill= 0;
1767
1768   ipf->readable_callback= 0;
1769   ipf->readable_callback_user= 0;
1770
1771   ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
1772   assert(ipf->rd);
1773
1774   int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
1775                      feedfile_got_article,ipf, feedfile_read_err, ipf);
1776   if (r) sysdie("unable start reading feedfile %s",ipf->path);
1777 }
1778
1779 static void inputfile_reading_stop(InputFile *ipf) {
1780   assert(ipf->rd);
1781   oop_rd_cancel(ipf->rd);
1782   oop_rd_delete(ipf->rd);
1783   ipf->rd= 0;
1784   assert(!ipf->filemon); /* we shouldn't be monitoring it now */
1785 }
1786
1787
1788 /*========== interaction with innd - state machine ==========*/
1789
1790 /* See official state diagram at top of file.  We implement
1791  * this as follows:
1792  * -8<-
1793
1794             .=======.
1795             ||START||
1796             `======='
1797                 |
1798                 | open F
1799                 |
1800                 |    F ENOENT
1801                 |`---------------------------------------------------.
1802       F OPEN OK |                                                    |
1803                 |`---------------- - - -                             |
1804        D ENOENT |       D EXISTS   see OVERALL STATES diagram        |
1805                 |                  for full startup logic            |
1806      ,--------->|                                                    |
1807      |          V                                                    |
1808      |     ============                                       try to |
1809      |      NORMAL                                            open D |
1810      |     [Normal]                                                  |
1811      |      main F tail                                              |
1812      |     ============                                              V
1813      |          |                                                    |
1814      |          | F IS SO BIG WE SHOULD FLUSH, OR TIMEOUT            |
1815      ^          | hardlink F to D                                    |
1816      |     [Hardlinked]                                              |
1817      |          | unlink F                                           |
1818      |          | our handle onto F is now onto D                    |
1819      |     [Moved]                                                   |
1820      |          |                                                    |
1821      |          |<-------------------<---------------------<---------+
1822      |          |                                                    |
1823      |          | spawn inndcomm flush                               |
1824      |          V                                                    |
1825      |     ==================                                        |
1826      |      FLUSHING[-ABSENT]                                        |
1827      |     [Flushing]                                                |
1828      |     main D tail/none                                          |
1829      |     ==================                                        |
1830      |          |                                                    |
1831      |          |   INNDCOMM FLUSH FAILS                             ^
1832      |          |`----------------------->----------.                |
1833      |          |                                   |                |
1834      |          |   NO SUCH SITE                    V                |
1835      ^          |`--------------->----.         ==================== |
1836      |          |                      \        FLUSHFAILED[-ABSENT] |
1837      |          |                       \         [Moved]            |
1838      |          | FLUSH OK               \       main D tail/none    |
1839      |          | open F                  \     ==================== |
1840      |          |                          \        |                |
1841      |          |                           \       | TIME TO RETRY  |
1842      |          |`------->----.     ,---<---'\      `----------------'
1843      |          |    D NONE   |     | D NONE  `----.
1844      |          V             |     |              V
1845      |     =============      V     V             ============
1846      |      SEPARATED-1       |     |              DROPPING-1
1847      |      flsh->rd!=0       |     |              flsh->rd!=0
1848      |     [Separated]        |     |             [Dropping]
1849      |      main F idle       |     |              main none
1850      |      old D tail        |     |              old D tail
1851      |     =============      |     |             ============
1852      |          |             |     | install       |
1853      ^          | EOF ON D    |     |  defer        | EOF ON D
1854      |          V             |     |               V
1855      |     ===============    |     |             ===============
1856      |      SEPARATED-2       |     |              DROPPING-2
1857      |      flsh->rd==0       |     V              flsh->rd==0
1858      |     [Finishing]        |     |             [Dropping]
1859      |      main F tail       |     `.             main none
1860      |      old D closed      |       `.           old D closed
1861      |     ===============    V         `.        ===============
1862      |          |                         `.          |
1863      |          | ALL D PROCESSED           `.        | ALL D PROCESSED
1864      |          V install defer as backlog    `.      | install defer
1865      ^          | close D                       `.    | close D
1866      |          | unlink D                        `.  | unlink D
1867      |          |                                  |  |
1868      |          |                                  V  V
1869      `----------'                               ==============
1870                                                  DROPPED
1871                                                 [Dropped]
1872                                                  main none
1873                                                  old none
1874                                                  some backlog
1875                                                 ==============
1876                                                       |
1877                                                       | ALL BACKLOG DONE
1878                                                       |
1879                                                       | unlink lock
1880                                                       | exit
1881                                                       V
1882                                                   ==========
1883                                                    (ESRCH)
1884                                                   [Droppped]
1885                                                   ==========
1886  * ->8-
1887  */
1888
1889 static void startup_set_input_file(InputFile *f) {
1890   assert(!main_input_file);
1891   main_input_file= f;
1892   inputfile_reading_start(f);
1893 }
1894
1895 static void statemc_init(void) {
1896   struct stat stab, stabf;
1897
1898   path_lock=        xasprintf("%s_lock",      feedfile);
1899   path_flushing=    xasprintf("%s_flushing",  feedfile);
1900   path_defer=       xasprintf("%s_defer",     feedfile);
1901   globpat_backlog=  xasprintf("%s_backlog*",  feedfile);
1902
1903   for (;;) {
1904     int lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
1905     if (lockfd<0) sysfatal("open lockfile %s", path_lock);
1906
1907     struct flock fl;
1908     memset(&fl,0,sizeof(fl));
1909     fl.l_type= F_WRLCK;
1910     fl.l_whence= SEEK_SET;
1911     int r= fcntl(lockfd, F_SETLK, &fl);
1912     if (r==-1) {
1913       if (errno==EACCES || isewouldblock(errno)) {
1914         if (quiet_multiple) exit(0);
1915         fatal("another duct holds the lockfile");
1916       }
1917       sysdie("fcntl F_SETLK lockfile %s", path_lock);
1918     }
1919
1920     xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
1921     int lock_noent;
1922     xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
1923
1924     if (!lock_noent && samefile(&stab, &stabf))
1925       break;
1926
1927     xclose(lockfd, "stale lockfile ", path_lock);
1928   }
1929   debug("startup: locked");
1930
1931   search_backlog_file();
1932
1933   int defer_noent;
1934   xlstat_isreg(path_defer, &stab, &defer_noent, "defer file");
1935   if (defer_noent) {
1936     debug("startup: ductdefer ENOENT");
1937   } else {
1938     debug("startup: ductdefer nlink=%ld", (long)stab.st_nlink);
1939     switch (stab.st_nlink==1) {
1940     case 1:
1941       open_defer(); /* so that we will later close it and rename it */
1942       break;
1943     case 2:
1944       xunlink(path_defer, "stale defer file link"
1945               " (presumably hardlink to backlog file)");
1946       break;
1947     default:
1948       die("defer file %s has unexpected link count %d",
1949           path_defer, stab.st_nlink);
1950     }
1951   }
1952
1953   struct stat stab_f, stab_d;
1954   int noent_f;
1955
1956   InputFile *file_d= open_input_file(path_flushing);
1957   if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
1958
1959   xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
1960
1961   if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
1962     debug("startup: F==D => Hardlinked");
1963     xunlink(feedfile, "feed file (during startup)"); /* => Moved */
1964     noent_f= 1;
1965   }
1966
1967   if (noent_f) {
1968     debug("startup: F ENOENT => Moved");
1969     if (file_d) startup_set_input_file(file_d);
1970     spawn_inndcomm_flush("feedfile missing at startup");
1971     /* => Flushing, sms:=FLUSHING */
1972   } else {
1973     if (file_d) {
1974       debug("startup: F!=D => Separated");
1975       startup_set_input_file(file_d);
1976       SMS(SEPARATED, 0, "found both old and current feed files");
1977     } else {
1978       debug("startup: F exists, D ENOENT => Normal");
1979       InputFile *file_f= open_input_file(feedfile);
1980       if (!file_f) die("feed file vanished during startup");
1981       startup_set_input_file(file_f);
1982       SMS(NORMAL, flushfail_retry_periods, "normal startup");
1983     }
1984   }
1985 }
1986
1987 static void statemc_start_flush(const char *why) { /* Normal => Flushing */
1988   assert(sms == sm_NORMAL);
1989
1990   debug("starting flush (%s) (%lu >?= %lu) (%d)",
1991         why,
1992         (unsigned long)(main_input_file ? main_input_file->offset : 0),
1993         (unsigned long)target_max_feedfile_size,
1994         sm_period_counter);
1995
1996   int r= link(feedfile, path_flushing);
1997   if (r) sysdie("link feedfile %s to flushing file %s",
1998                 feedfile, path_flushing);
1999   /* => Hardlinked */
2000
2001   xunlink(feedfile, "old feedfile link");
2002   /* => Moved */
2003
2004   spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
2005 }
2006
2007 static void statemc_period_poll(void) {
2008   if (!sm_period_counter) return;
2009   sm_period_counter--;
2010   assert(sm_period_counter>=0);
2011
2012   if (sm_period_counter) return;
2013   switch (sms) {
2014   case sm_NORMAL:
2015     statemc_start_flush("periodic"); /* Normal => Flushing; => FLUSHING */
2016     break;
2017   case sm_FLUSHFAILED:
2018     spawn_inndcomm_flush("retry"); /* Moved => Flushing; => FLUSHING */
2019     break;
2020   default:
2021     abort();
2022   }
2023 }
2024
2025 static int inputfile_is_done(InputFile *ipf) {
2026   if (!ipf) return 0;
2027   if (ipf->inprogress) return 0; /* new article in the meantime */
2028   if (ipf->rd) return 0; /* not had EOF */
2029   return 1;
2030 }
2031
2032 static void notice_processed(InputFile *ipf, const char *what,
2033                              const char *spec) {
2034 #define RCI_NOTHING(x) /* nothing */
2035 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
2036 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
2037
2038 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
2039
2040   info("processed %s%s read=%d(+%dbl,+%derr)"
2041        " offered=%d(ch%d,nc%d) accepted=%d(ch%d+nc%d)"
2042        RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
2043        ,
2044        what, spec,
2045        ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
2046        CNT(Unchecked,sent) + CNT(Unsolicited,sent)
2047        , CNT(Unchecked,sent), CNT(Unsolicited,sent),
2048        CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
2049        , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
2050        RESULT_COUNTS(RCI_NOTHING,  RCI_TRIPLE_VALS)
2051        );
2052
2053 #undef CNT
2054 }
2055
2056 static void statemc_check_backlog_done(void) {
2057   InputFile *ipf= backlog_input_file;
2058   if (!inputfile_is_done(ipf)) return;
2059
2060   const char *slash= strrchr(ipf->path, '/');
2061   const char *leaf= slash ? slash+1 : ipf->path;
2062   const char *under= strchr(slash, '_');
2063   const char *rest= under ? under+1 : leaf;
2064   if (!strncmp(rest,"backlog",7)) rest += 7;
2065   notice_processed(ipf,"backlog:",rest);
2066
2067   close_input_file(ipf);
2068   if (unlink(ipf->path)) {
2069     if (errno != ENOENT)
2070       sysdie("could not unlink processed backlog file %s", ipf->path);
2071     warn("backlog file %s vanished while we were reading it"
2072          " so we couldn't remove it (but it's done now, anyway)",
2073          ipf->path);
2074   }
2075   free(ipf);
2076   backlog_input_file= 0;
2077   search_backlog_file();
2078   return;
2079 }
2080
2081 static void statemc_check_flushing_done(void) {
2082   InputFile *ipf= flushing_input_file;
2083   if (!inputfile_is_done(ipf)) return;
2084
2085   assert(sms==sm_SEPARATED || sms==sm_DROPPING);
2086
2087   notice_processed(ipf,"feedfile",0);
2088
2089   close_defer();
2090
2091   xunlink(path_flushing, "old flushing file");
2092
2093   close_input_file(flushing_input_file);
2094   free(flushing_input_file);
2095   flushing_input_file= 0;
2096
2097   if (sms==sm_SEPARATED) {
2098     notice("flush complete");
2099     SMS(NORMAL, 0, "flush complete");
2100   } else if (sms==sm_DROPPING) {
2101     SMS(DROPPED, 0, "old flush complete");
2102     search_backlog_file();
2103     notice("feed dropped, but will continue until backlog is finished");
2104   }
2105 }
2106
2107 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
2108                                       void *u) {
2109   assert(!inputfile_is_done(main_input_file));
2110   statemc_check_flushing_done();
2111   statemc_check_backlog_done();
2112   return OOP_CONTINUE;
2113 }
2114
2115 static void queue_check_input_done(void) {
2116   loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
2117 }
2118
2119 static void statemc_setstate(StateMachineState newsms, int periods,
2120                              const char *forlog, const char *why) {
2121   sms= newsms;
2122   sm_period_counter= periods;
2123
2124   const char *xtra= "";
2125   switch (sms) {
2126   case sm_FLUSHING:
2127   case sm_FLUSHFAILED:
2128     if (!main_input_file) xtra= "-ABSENT";
2129     break;
2130   case sm_SEPARATED:
2131   case sm_DROPPING:
2132     xtra= flushing_input_file->rd ? "-1" : "-2";
2133     break;
2134   default:;
2135   }
2136
2137   if (periods) {
2138     info("%s%s[%d] %s",forlog,xtra,periods,why);
2139   } else {
2140     info("%s%s %s",forlog,xtra,why);
2141   }
2142 }
2143
2144 /*---------- defer and backlog files ----------*/
2145
2146 static void open_defer(void) {
2147   struct stat stab;
2148
2149   if (defer) return;
2150
2151   defer= fopen(path_defer, "a+");
2152   if (!defer) sysfatal("could not open defer file %s", path_defer);
2153
2154   /* truncate away any half-written records */
2155
2156   xfstat_isreg(fileno(defer), &stab, path_defer, "newly opened defer file");
2157
2158   if (stab.st_size > LONG_MAX)
2159     die("defer file %s size is far too large", path_defer);
2160
2161   if (!stab.st_size)
2162     return;
2163
2164   long orgsize= stab.st_size;
2165   long truncto= stab.st_size;
2166   for (;;) {
2167     if (!truncto) break; /* was only (if anything) one half-truncated record */
2168     if (fseek(defer, truncto-1, SEEK_SET) < 0)
2169       sysdie("seek in defer file %s while truncating partial", path_defer);
2170
2171     int r= getc(defer);
2172     if (r==EOF) {
2173       if (ferror(defer))
2174         sysdie("failed read from defer file %s", path_defer);
2175       else
2176         die("defer file %s shrank while we were checking it!", path_defer);
2177     }
2178     if (r=='\n') break;
2179     truncto--;
2180   }
2181
2182   if (stab.st_size != truncto) {
2183     warn("truncating half-record at end of defer file %s -"
2184          " shrinking by %ld bytes from %ld to %ld",
2185          path_defer, orgsize - truncto, orgsize, truncto);
2186
2187     if (fflush(defer))
2188       sysfatal("could not flush defer file %s", path_defer);
2189     if (ftruncate(fileno(defer), truncto))
2190       sysdie("could not truncate defer file %s", path_defer);
2191
2192   } else {
2193     info("continuing existing defer file %s (%ld bytes)",
2194          path_defer, orgsize);
2195   }
2196   if (fseek(defer, truncto, SEEK_SET))
2197     sysdie("could not seek to new end of defer file %s", path_defer);
2198 }
2199
2200 static void close_defer(void) {
2201   if (!defer)
2202     return;
2203
2204   struct stat stab;
2205   xfstat_isreg(fileno(defer), &stab, path_defer, "defer file");
2206
2207   if (fclose(defer)) sysfatal("could not close defer file %s", path_defer);
2208   defer= 0;
2209
2210   time_t now= xtime();
2211
2212   char *backlog= xasprintf("%s_backlog_%lu.%lu", feedfile,
2213                            (unsigned long)now,
2214                            (unsigned long)stab.st_ino);
2215   if (link(path_defer, backlog))
2216     sysfatal("could not install defer file %s as backlog file %s",
2217            path_defer, backlog);
2218   if (unlink(path_defer))
2219     sysdie("could not unlink old defer link %s to backlog file %s",
2220            path_defer, backlog);
2221
2222   free(backlog);
2223
2224   if (until_backlog_nextscan < 0 ||
2225       until_backlog_nextscan > backlog_retry_minperiods + 1)
2226     until_backlog_nextscan= backlog_retry_minperiods + 1;
2227 }
2228
2229 static void poll_backlog_file(void) {
2230   if (until_backlog_nextscan < 0) return;
2231   if (until_backlog_nextscan-- > 0) return;
2232   search_backlog_file();
2233 }
2234
2235 static void search_backlog_file(void) {
2236   /* returns non-0 iff there are any backlog files */
2237
2238   glob_t gl;
2239   int r, i;
2240   struct stat stab;
2241   const char *oldest_path=0;
2242   time_t oldest_mtime=0, now;
2243
2244   if (backlog_input_file) return;
2245
2246  try_again:
2247
2248   r= glob(globpat_backlog, GLOB_ERR|GLOB_MARK|GLOB_NOSORT, 0, &gl);
2249
2250   switch (r) {
2251   case GLOB_ABORTED:
2252     sysdie("failed to expand backlog pattern %s", globpat_backlog);
2253   case GLOB_NOSPACE:
2254     die("out of memory expanding backlog pattern %s", globpat_backlog);
2255   case 0:
2256     for (i=0; i<gl.gl_pathc; i++) {
2257       const char *path= gl.gl_pathv[i];
2258
2259       if (strchr(path,'#') || strchr(path,'~')) {
2260         debug("backlog file search skipping %s", path);
2261         continue;
2262       }
2263       r= stat(path, &stab);
2264       if (r) {
2265         syswarn("failed to stat backlog file %s", path);
2266         continue;
2267       }
2268       if (!S_ISREG(stab.st_mode)) {
2269         warn("backlog file %s is not a plain file (or link to one)", path);
2270         continue;
2271       }
2272       if (!oldest_path || stab.st_mtime < oldest_mtime) {
2273         oldest_path= path;
2274         oldest_mtime= stab.st_mtime;
2275       }
2276     }
2277   case GLOB_NOMATCH: /* fall through */
2278     break;
2279   default:
2280     sysdie("glob expansion of backlog pattern %s gave unexpected"
2281            " nonzero (error?) return value %d", globpat_backlog, r);
2282   }
2283
2284   if (!oldest_path) {
2285     debug("backlog scan: none");
2286
2287     if (sms==sm_DROPPED) {
2288       notice("feed dropped and our work is complete");
2289       xunlink(path_lock, "lockfile for old feed");
2290       exit(0);
2291     }
2292     until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2293     goto xfree;
2294   }
2295
2296   now= xtime();
2297   double age= difftime(now, oldest_mtime);
2298   long age_deficiency= (backlog_retry_minperiods * period_seconds) - age;
2299
2300   if (age_deficiency <= 0) {
2301     debug("backlog scan: found age=%f deficiency=%ld oldest=%s",
2302           age, age_deficiency, oldest_path);
2303
2304     backlog_input_file= open_input_file(oldest_path);
2305     if (!backlog_input_file) {
2306       warn("backlog file %s vanished as we opened it", oldest_path);
2307       globfree(&gl);
2308       goto try_again;
2309     }
2310     inputfile_reading_start(backlog_input_file);
2311     until_backlog_nextscan= -1;
2312     goto xfree;
2313   }
2314
2315   until_backlog_nextscan= age_deficiency / period_seconds;
2316
2317   if (backlog_spontaneous_rescan_periods >= 0 &&
2318       until_backlog_nextscan > backlog_spontaneous_rescan_periods)
2319     until_backlog_nextscan= backlog_spontaneous_rescan_periods;
2320
2321   debug("backlog scan: young age=%f deficiency=%ld nextscan=%d oldest=%s",
2322         age, age_deficiency, until_backlog_nextscan, oldest_path);
2323
2324  xfree:
2325   globfree(&gl);
2326   return;
2327 }
2328
2329 /*========== flushing the feed ==========*/
2330
2331 static pid_t inndcomm_child;
2332 static int inndcomm_sentinel_fd;
2333
2334 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
2335   assert(inndcomm_child);
2336   assert(fd == inndcomm_sentinel_fd);
2337   int status= xwaitpid(&inndcomm_child, "inndcomm");
2338   cancel_fd_read_except(fd);
2339   xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
2340
2341   assert(!flushing_input_file);
2342
2343   if (WIFEXITED(status)) {
2344     switch (WEXITSTATUS(status)) {
2345
2346     case INNDCOMMCHILD_ESTATUS_FAIL:
2347       goto failed;
2348
2349     case INNDCOMMCHILD_ESTATUS_NONESUCH:
2350       warn("feed has been dropped by innd, finishing up");
2351       flushing_input_file= main_input_file;
2352       tailing_queue_readable(flushing_input_file);
2353         /* we probably previously returned EAGAIN from our fake read method
2354          * when in fact we were at EOF, so signal another readable event
2355          * so we actually see the EOF */
2356
2357       main_input_file= 0;
2358
2359       if (flushing_input_file) {
2360         SMS(DROPPING, 0, "feed dropped by innd, but must finish last flush");
2361       } else {
2362         close_defer();
2363         SMS(DROPPED, 0, "feed dropped by innd");
2364         search_backlog_file();
2365       }
2366       return OOP_CONTINUE;
2367
2368     case 0:
2369       /* as above */
2370       flushing_input_file= main_input_file;
2371       tailing_queue_readable(flushing_input_file);
2372
2373       main_input_file= open_input_file(feedfile);
2374       if (!main_input_file)
2375         die("flush succeeded but feedfile %s does not exist!", feedfile);
2376
2377       if (flushing_input_file) {
2378         SMS(SEPARATED, spontaneous_flush_periods, "recovery flush complete");
2379       } else {
2380         close_defer();
2381         SMS(NORMAL, spontaneous_flush_periods, "flush complete");
2382       }
2383       return OOP_CONTINUE;
2384
2385     default:
2386       goto unexpected_exitstatus;
2387
2388     }
2389   } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
2390     warn("flush timed out trying to talk to innd");
2391     goto failed;
2392   } else {
2393   unexpected_exitstatus:
2394     report_child_status("inndcomm child", status);
2395   }
2396
2397  failed:
2398   SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
2399   return OOP_CONTINUE;
2400 }
2401
2402 static void inndcommfail(const char *what) {
2403   syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
2404   exit(INNDCOMMCHILD_ESTATUS_FAIL);
2405 }
2406
2407 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
2408   int pipefds[2];
2409
2410   notice("flushing %s",why);
2411
2412   assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
2413   assert(!inndcomm_child);
2414   assert(!inndcomm_sentinel_fd);
2415
2416   if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
2417
2418   inndcomm_child= xfork("inndcomm child");
2419
2420   if (!inndcomm_child) {
2421     const char *flushargv[2]= { sitename, 0 };
2422     char *reply;
2423     int r;
2424
2425     xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
2426     /* parent spots the autoclose of pipefds[1] when we die or exit */
2427
2428     alarm(inndcomm_flush_timeout);
2429     r= ICCopen();                         if (r)   inndcommfail("connect");
2430     r= ICCcommand('f',flushargv,&reply);  if (r<0) inndcommfail("transmit");
2431     if (!r) exit(0); /* yay! */
2432
2433     if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
2434     syswarn("innd ctlinnd flush failed: innd said %s", reply);
2435     exit(INNDCOMMCHILD_ESTATUS_FAIL);
2436   }
2437
2438   xclose(pipefds[1], "inndcomm sentinel child's end",0);
2439   inndcomm_sentinel_fd= pipefds[0];
2440   assert(inndcomm_sentinel_fd);
2441   on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
2442
2443   SMS(FLUSHING, 0, why);
2444 }
2445
2446 /*========== main program ==========*/
2447
2448 static void postfork_inputfile(InputFile *ipf) {
2449   if (!ipf) return;
2450   xclose(ipf->fd, "(in child) input file ", ipf->path);
2451 }
2452
2453 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
2454   /* we have no stdio streams that are buffered long-term */
2455   if (!f) return;
2456   if (fclose(f)) sysdie("(in child) close %s%s", what, what2?what2:0);
2457 }
2458
2459 static void postfork(void) {
2460   if (signal(SIGPIPE, SIG_DFL) == SIG_ERR)
2461     sysdie("(in child) failed to reset SIGPIPE");
2462
2463   postfork_inputfile(main_input_file);
2464   postfork_inputfile(flushing_input_file);
2465
2466   Conn *conn;
2467   for (conn=LIST_HEAD(conns); conn; conn=LIST_NEXT(conn))
2468     conn_closefd(conn,"(in child) ");
2469
2470   postfork_stdio(defer, "defer file ", path_defer);
2471 }
2472
2473 #define EVERY(what, interval_sec, interval_usec, body)                       \
2474   static struct timeval what##_timeout = { interval_sec, interval_usec };    \
2475   static void what##_schedule(void);                                         \
2476   static void *what##_timedout(oop_source *lp, struct timeval tv, void *u) { \
2477     body;                                                                    \
2478     what##_schedule();                                                       \
2479     return OOP_CONTINUE;                                                     \
2480   }                                                                          \
2481   static void what##_schedule(void) {                                        \
2482     loop->on_time(loop, what##_timeout, what##_timedout, 0);                 \
2483   }
2484
2485 EVERY(filepoll, 5,0, ({
2486   if (main_input_file && main_input_file->readable_callback)
2487     filemon_callback(main_input_file);
2488 }));
2489
2490 static char *debug_report_ipf(InputFile *ipf) {
2491   if (!ipf) return xasprintf("-");
2492
2493   const char *slash= strrchr(ipf->path,'/');
2494   const char *path= slash ? slash+1 : ipf->path;
2495
2496   return xasprintf("%p/%s:ip=%ld,off=%ld,fd=%d%s",
2497                    ipf, path,
2498                    ipf->inprogress, (long)ipf->offset,
2499                    ipf->fd, ipf->rd ? "+" : "");
2500 }
2501
2502 EVERY(period, -1,0, ({
2503   char *dipf_main=     debug_report_ipf(main_input_file);
2504   char *dipf_flushing= debug_report_ipf(flushing_input_file);
2505   char *dipf_backlog=  debug_report_ipf(backlog_input_file);
2506
2507   debug("PERIOD"
2508         " sms=%s[%d] conns=%d queue=%d until_connect=%d"
2509         " input_files main:%s old:%s flushing:%s"
2510         " children connecting=%ld inndcomm_child=%ld"
2511         ,
2512         sms_names[sms], sm_period_counter,
2513           conns.count, queue.count, until_connect,
2514         dipf_main, dipf_flushing, dipf_backlog,
2515         (long)connecting_child, (long)inndcomm_child
2516         );
2517
2518   free(dipf_main);
2519   free(dipf_flushing);
2520   free(dipf_backlog);
2521
2522   if (until_connect) until_connect--;
2523
2524   poll_backlog_file();
2525   if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
2526   statemc_period_poll();
2527   check_assign_articles();
2528   check_idle_conns();
2529 }));
2530
2531
2532 /*========== option parsing ==========*/
2533
2534 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
2535 static void vbadusage(const char *fmt, va_list al) {
2536   char *m= xvasprintf(fmt,al);
2537   fprintf(stderr, "bad usage: %s\n"
2538           "say --help for help, or read the manpage\n",
2539           m);
2540   if (become_daemon)
2541     syslog(LOG_CRIT,"innduct: invoked with bad usage: %s",m);
2542   exit(8);
2543 }
2544
2545 /*---------- generic option parser ----------*/
2546
2547 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
2548 static void badusage(const char *fmt, ...) {
2549   va_list al;
2550   va_start(al,fmt);
2551   vbadusage(fmt,al);
2552 }
2553
2554 enum OptFlags {
2555   of_seconds= 001000u,
2556   of_boolean= 002000u,
2557 };
2558
2559 typedef struct Option Option;
2560 typedef void OptionParser(const Option*, const char *val);
2561
2562 struct Option {
2563   int shrt;
2564   const char *lng, *formarg;
2565   void *store;
2566   OptionParser *fn;
2567   int intval;
2568 };
2569
2570 static void parse_options(const Option *options, char ***argvp) {
2571   /* on return *argvp is first non-option arg; argc is not updated */
2572
2573   for (;;) {
2574     const char *arg= *++(*argvp);
2575     if (!arg) break;
2576     if (*arg != '-') break;
2577     if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
2578     int a;
2579     while ((a= *++arg)) {
2580       const Option *o;
2581       if (a=='-') {
2582         arg++;
2583         char *equals= strchr(arg,'=');
2584         int len= equals ? (equals - arg) : strlen(arg);
2585         for (o=options; o->shrt || o->lng; o++)
2586           if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
2587             goto found_long;
2588         badusage("unknown long option --%s",arg);
2589       found_long:
2590         if (!o->formarg) {
2591           if (equals) badusage("option --%s does not take a value",o->lng);
2592           arg= 0;
2593         } else if (equals) {
2594           arg= equals+1;
2595         } else {
2596           arg= *++(*argvp);
2597           if (!arg) badusage("option --%s needs a value for %s",
2598                              o->lng, o->formarg);
2599         }
2600         o->fn(o, arg);
2601         break; /* eaten the whole argument now */
2602       }
2603       for (o=options; o->shrt || o->lng; o++)
2604         if (a == o->shrt)
2605           goto found_short;
2606       badusage("unknown short option -%c",a);
2607     found_short:
2608       if (!o->formarg) {
2609         o->fn(o,0);
2610       } else {
2611         if (!*++arg) {
2612           arg= *++(*argvp);
2613           if (!arg) badusage("option -%c needs a value for %s",
2614                              o->shrt, o->formarg);
2615         }
2616         o->fn(o,arg);
2617         break; /* eaten the whole argument now */
2618       }
2619     }
2620   }
2621 }
2622
2623 #define DELIMPERHAPS(delim,str)  (str) ? (delim) : "", (str) ? (str) : ""
2624
2625 static void print_options(const Option *options, FILE *f) {
2626   const Option *o;
2627   for (o=options; o->shrt || o->lng; o++) {
2628     char shrt[2] = { o->shrt, 0 };
2629     char *optspec= xasprintf("%s%s%s%s%s",
2630                              o->shrt ? "-" : "", shrt,
2631                              o->shrt && o->lng ? "|" : "",
2632                              DELIMPERHAPS("--", o->lng));
2633     fprintf(f, "  %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
2634     free(optspec);
2635   }
2636 }
2637
2638 /*---------- specific option types ----------*/
2639
2640 static void op_integer(const Option *o, const char *val) {
2641   char *ep;
2642   errno= 0;
2643   unsigned long ul= strtoul(val,&ep,10);
2644   if (*ep || ep==val || errno || ul>INT_MAX)
2645     badusage("bad integer value for %s",o->lng);
2646   int *store= o->store;
2647   *store= ul;
2648 }
2649
2650 static void op_double(const Option *o, const char *val) {
2651   int *store= o->store;
2652   char *ep;
2653   errno= 0;
2654   *store= strtod(val, &ep);
2655   if (*ep || ep==val || errno)
2656     badusage("bad floating point value for %s",o->lng);
2657 }
2658
2659 static void op_string(const Option *o, const char *val) {
2660   const char **store= o->store;
2661   *store= val;
2662 }
2663
2664 static void op_seconds(const Option *o, const char *val) {
2665   int *store= o->store;
2666   char *ep;
2667   int unit;
2668
2669   double v= strtod(val,&ep);
2670   if (ep==val) badusage("bad time/duration value for %s",o->lng);
2671
2672   if (!*ep || !strcmp(ep,"s")) unit= 1;
2673   else if (!strcmp(ep,"m")) unit= 60;
2674   else if (!strcmp(ep,"h")) unit= 3600;
2675   else if (!strcmp(ep,"d")) unit= 86400;
2676   else badusage("bad units %s for time/duration value for %s",ep,o->lng);
2677
2678   v *= unit;
2679   v= ceil(v);
2680   if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
2681   *store= v;
2682 }
2683
2684 static void op_periods_rndup(const Option *o, const char *val) {
2685   int *store= o->store;
2686   op_seconds(o,val);
2687   *store += period_seconds-1;
2688   *store /= period_seconds;
2689 }
2690
2691 static void op_setint(const Option *o, const char *val) {
2692   int *store= o->store;
2693   *store= o->intval;
2694 }
2695
2696 /*---------- specific options ----------*/
2697
2698 static void help(const Option *o, const char *val);
2699
2700 static const Option innduct_options[]= {
2701 {'f',"feedfile",         "F",   &feedfile,             op_string           },
2702 {'q',"quiet-multiple",   0,     &quiet_multiple,       op_setint,   1    },
2703 {0,"help",               0,                            help             },
2704
2705 {0,"max-connections",    "N",   &max_connections,      op_integer          },
2706 {0,"max-queue-per-conn", "N",   &max_queue_per_conn,   op_integer          },
2707
2708
2709 {0,"streaming",          0,     &try_stream,           op_setint,  1     },
2710 {0,"no-streaming",       0,     &try_stream,           op_setint,  0     },
2711 {'P',"port",             "PORT",&port,                 op_integer          },
2712 {0,"inndconf",           "F",   &inndconffile,         op_string           },
2713 {0,"no-daemon",          0,     &become_daemon,        op_setint,  0     },
2714
2715 {0,"no-check-proportion","PERCENT", &nocheck_thresh_pct,      op_double },
2716 {0,"no-check-filter",    "ARTICLES", &nocheck_decay_articles, op_double },
2717
2718 {0,"reconnect-interval",  "TIME", &reconnect_delay_periods, op_periods_rndup },
2719 {0,"flush-retry-interval","TIME", &flushfail_retry_periods, op_periods_rndup },
2720 {0,"inndcomm-timeout",    "TIME",  &inndcomm_flush_timeout,   op_seconds },
2721 {0,0}
2722 };
2723
2724 static void printusage(FILE *f) {
2725   fputs("usage: innduct [options] site [fqdn]\n"
2726         "available options are:\n", f);
2727   print_options(innduct_options, f);
2728 }
2729
2730 static void help(const Option *o, const char *val) {
2731   printusage(stdout);
2732   if (ferror(stdout) || fflush(stdout)) {
2733     perror("innduct: writing help");
2734     exit(12);
2735   }
2736   exit(0);
2737 }
2738
2739 int main(int argc, char **argv) {
2740   if (!argv[1]) {
2741     printusage(stderr);
2742     exit(12);
2743   }
2744
2745   parse_options(innduct_options, &argv);
2746
2747   /* arguments */
2748
2749   sitename= *argv++;
2750   if (!sitename) badusage("need site name argument");
2751   remote_host= *argv++;
2752   if (*argv) badusage("too many non-option arguments");
2753
2754   /* defaults */
2755
2756   if (!remote_host) remote_host= sitename;
2757
2758   if (nocheck_thresh_pct < 0 || nocheck_thresh_pct > 100)
2759     badusage("nocheck threshold percentage must be between 0..100");
2760   nocheck_thresh= nocheck_thresh_pct * 0.01;
2761
2762   if (nocheck_decay_articles < 0.1)
2763     badusage("nocheck decay articles must be at least 0.1");
2764   nocheck_decay= 1 - 1/nocheck_decay_articles;
2765
2766   if (!pathoutgoing)
2767     pathoutgoing= innconf->pathoutgoing;
2768   innconf_read(inndconffile);
2769
2770   if (!feedfile)
2771     feedfile= xasprintf("%s/%s",pathoutgoing,sitename);
2772   else if (!feedfile[0])
2773     badusage("feed filename must be nonempty");
2774   else if (feedfile[strlen(feedfile)-1]=='/')
2775     feedfile= xasprintf("%s%s",feedfile,sitename);
2776
2777   const char *feedfile_forbidden= "?*[~#";
2778   int c;
2779   while ((c= *feedfile_forbidden++))
2780     if (strchr(feedfile, c))
2781       badusage("feed filename may not contain metacharacter %c",c);
2782
2783   /* set things up */
2784
2785   oop_source_sys *sysloop= oop_sys_new();
2786   if (!sysloop) sysdie("could not create liboop event loop");
2787   loop= (oop_source*)sysloop;
2788
2789   if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2790     sysdie("could not ignore SIGPIPE");
2791
2792   LIST_INIT(conns);
2793   LIST_INIT(queue);
2794
2795   if (become_daemon) {
2796     int i;
2797     for (i=3; i<255; i++)
2798       /* do this now before we open syslog, etc. */
2799       close(i);
2800     openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
2801
2802     int null= open("/dev/null",O_RDWR);
2803     if (null<0) sysdie("failed to open /dev/null");
2804     dup2(null,0);
2805     dup2(null,1);
2806     dup2(null,2);
2807     xclose(null, "/dev/null original fd",0);
2808
2809     pid_t child1= xfork("daemonise first fork");
2810     if (child1) _exit(0);
2811
2812     pid_t sid= setsid();
2813     if (sid != child1) sysdie("setsid failed");
2814
2815     pid_t child2= xfork("daemonise second fork");
2816     if (child2) _exit(0);
2817   }
2818
2819   notice("starting");
2820
2821   if (!filemon_method_init()) {
2822     warn("no file monitoring available, polling");
2823     filepoll_schedule();
2824   }
2825
2826   period_timeout.tv_sec= period_seconds;
2827   period_schedule();
2828
2829   statemc_init();
2830
2831   /* let's go */
2832
2833   void *r= oop_sys_run(sysloop);
2834   assert(r == OOP_ERROR);
2835   sysdie("event loop failed");
2836 }