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