chiark / gitweb /
Show backlog file completion to debug log
[innduct.git] / innduct.h
1 /*
2  *  innduct
3  *  tailing reliable realtime streaming feeder for inn
4  *
5  *  Copyright (C) 2010 Ian Jackson <ijackson@chiark.greenend.org.uk>
6  * 
7  *  This program is free software: you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation, either version 3 of the License, or
10  *  (at your option) any later version.
11  * 
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  * 
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  *
20  *  (I believe that when you compile and link this as part of the inn2
21  *  build, with the Makefile runes I have provided, all the libraries
22  *  and files which end up included in innduct are licence-compatible
23  *  with GPLv3.  If not then please let me know.  -Ian Jackson.)
24  */
25
26 #ifndef INNDUCT_H
27 #define INNDUCT_H
28
29 #define _GNU_SOURCE 1
30
31 #include "config.h"
32 #include "storage.h"
33 #include "nntp.h"
34 #include "libinn.h"
35 #include "inndcomm.h"
36
37 #include "inn/list.h"
38 #include "inn/innconf.h"
39 #include "inn/messages.h"
40
41 #include <sys/uio.h>
42 #include <sys/types.h>
43 #include <sys/wait.h>
44 #include <sys/stat.h>
45 #include <sys/socket.h>
46 #include <sys/un.h>
47 #include <unistd.h>
48 #include <string.h>
49 #include <signal.h>
50 #include <stdio.h>
51 #include <errno.h>
52 #include <syslog.h>
53 #include <fcntl.h>
54 #include <stdarg.h>
55 #include <assert.h>
56 #include <stdlib.h>
57 #include <stddef.h>
58 #include <glob.h>
59 #include <time.h>
60 #include <math.h>
61 #include <ctype.h>
62
63 #include <oop.h>
64 #include <oop-read.h>
65
66 /*----- general definitions, probably best not changed -----*/
67
68 #define CONNCHILD_ESTATUS_STREAM   24
69 #define CONNCHILD_ESTATUS_NOSTREAM 25
70
71 #define INNDCOMMCHILD_ESTATUS_FAIL     26
72 #define INNDCOMMCHILD_ESTATUS_NONESUCH 27
73
74 #define MAX_LINE_FEEDFILE (NNTP_MSGID_MAXLEN + sizeof(TOKEN)*2 + 10)
75 #define MAX_CLI_COMMAND 1000
76
77 #define VA                va_list al;  va_start(al,fmt)
78 #define PRINTF(f,a)       __attribute__((__format__(printf,f,a)))
79 #define NORET_PRINTF(f,a) __attribute__((__noreturn__,__format__(printf,f,a)))
80 #define NORET             __attribute__((__noreturn__))
81
82 #define NEW(ptr)              ((ptr)= zxmalloc(sizeof(*(ptr))))
83 #define NEW_DECL(type,ptr) type ptr = zxmalloc(sizeof(*(ptr)))
84
85 #define DUMPV(fmt,pfx,v) fprintf(f, " " #v "=" fmt, pfx v);
86
87 #define FOR_LIST_NODE(nodevar, list) \
88   for ((nodevar)=LIST_HEAD(list); (nodevar); (nodevar)=LIST_NEXT((nodevar)))
89
90 #define FOR_CONN(conn) FOR_LIST_NODE(conn, conns)
91
92 /*----- doubly linked lists -----*/
93
94 #define ISNODE(T)   struct node list_node
95 #define DEFLIST(T)                              \
96    typedef struct {                             \
97      union { struct list li; T *for_type; } u;  \
98      int count;                                 \
99    } T##List
100
101 #define NODE(n) (assert((void*)&(n)->list_node == (n)), &(n)->list_node)
102
103 #define LIST_CHECKCANHAVENODE(l,n) \
104   ((void)((n) == ((l).u.for_type))) /* just for the type check */
105
106 #define LIST_ADDSOMEHOW(l,n,list_addsomehow)    \
107  ( LIST_CHECKCANHAVENODE(l,n),                  \
108    list_addsomehow(&(l).u.li, NODE((n))),       \
109    (void)(l).count++                            \
110    )
111
112 #define LIST_REMSOMEHOW(l,list_remsomehow)      \
113  ( (typeof((l).u.for_type))                     \
114    ( (l).count                                  \
115      ? ( (l).count--,                           \
116          list_remsomehow(&(l).u.li) )           \
117      : 0                                        \
118      )                                          \
119    )
120
121
122 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
123 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
124 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
125 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
126
127 #define LIST_INIT(l) ((l).count=0, list_new(&(l).u.li))
128 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
129 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
130 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
131
132 #define LIST_REMOVE(l,n)                        \
133  ( LIST_CHECKCANHAVENODE(l,n),                  \
134    list_remove(NODE((n))),                      \
135    (void)(l).count--                            \
136    )
137
138 #define LIST_INSERT(l,n,pred)                                   \
139  ( LIST_CHECKCANHAVENODE(l,n),                                  \
140    LIST_CHECKCANHAVENODE(l,pred),                               \
141    list_insert((struct list*)&(l), NODE((n)), NODE((pred))),    \
142    (void)(l).count++                                            \
143    )
144
145 /*----- type predeclarations -----*/
146
147 typedef struct Conn Conn;
148 typedef struct Article Article;
149 typedef struct InputFile InputFile;
150 typedef struct XmitDetails XmitDetails;
151 typedef struct Filemon_Perfile Filemon_Perfile;
152 typedef enum StateMachineState StateMachineState;
153 typedef struct CliCommand CliCommand;
154
155 DEFLIST(Conn);
156 DEFLIST(Article);
157
158
159 /*----- configuration options -----*/
160
161 extern const char *sitename, *remote_host;
162 extern const char *feedfile, *path_run, *path_cli, *path_cli_dir;
163 extern int quiet_multiple, interactive, try_filemon, try_stream, port;
164 extern const char *inndconffile;
165
166 extern int max_connections, max_queue_per_conn, target_max_feedfile_size;
167 extern int period_seconds, filepoll_seconds, max_queue_per_ipf;
168 extern int connection_setup_timeout, inndcomm_flush_timeout;
169
170 extern double nocheck_thresh;
171 extern double nocheck_decay;
172
173 /* all these are initialised to seconds, and converted to periods in main */
174 extern int reconnect_delay_periods;
175 extern int flushfail_retry_periods;
176 extern int backlog_retry_minperiods;
177 extern int backlog_spontrescan_periods;
178 extern int spontaneous_flush_periods;
179 extern int max_separated_periods;
180 extern int need_activity_periods;
181 extern int stats_log_periods;
182 extern int lowvol_thresh;
183 extern int lowvol_periods;
184
185 extern double max_bad_data_ratio;
186 extern int max_bad_data_initial;
187
188
189 /*----- statistics -----*/
190
191 typedef enum {      /* in queue                 in conn->sent             */
192   art_Unchecked,    /*   not checked, not sent    checking                */
193   art_Wanted,       /*   checked, wanted          sent body as requested  */
194   art_Unsolicited,  /*   -                        sent body without check */
195   art_MaxState,
196 } ArtState;
197 extern const char *const artstate_names[]; /* xmit.c */
198
199 #define RESULT_COUNTS(RCS,RCN)                  \
200   RCS(sent)                                     \
201   RCS(accepted)                                 \
202   RCN(unwanted)                                 \
203   RCN(rejected)                                 \
204   RCN(deferred)                                 \
205   RCN(missing)                                  \
206   RCN(connretry)
207
208 #define RCI_TRIPLE_FMT_BASE "%d (id=%d,bod=%d,nc=%d)"
209 #define RCI_TRIPLE_VALS_BASE(counts,x)          \
210        counts[art_Unchecked] x                  \
211        + counts[art_Wanted] x                   \
212        + counts[art_Unsolicited] x,             \
213        counts[art_Unchecked] x                  \
214        , counts[art_Wanted] x                   \
215        , counts[art_Unsolicited] x
216
217 typedef enum {
218 #define RC_INDEX(x) RC_##x,
219   RESULT_COUNTS(RC_INDEX, RC_INDEX)
220   RCI_max
221 } ResultCountIndex;
222
223 typedef enum {
224   read_ok, read_blank, read_err, nooffer_missing,
225   ECI_max
226 } EventCountIndex;
227
228 /*----- transmission buffers -----*/
229
230 #define CONNIOVS 128
231
232 typedef enum {
233   xk_Const, xk_Artdata
234 } XmitKind;
235
236 struct XmitDetails {
237   XmitKind kind;
238   union {
239     ARTHANDLE *sm_art;
240   } info;
241 };
242
243
244 /*----- core operational data structure types -----*/
245
246 typedef struct {
247   int results[art_MaxState][RCI_max];
248   int events[ECI_max];
249 } Counts;
250
251 struct InputFile {
252   /* This is also an instance of struct oop_readable */
253   struct oop_readable readable; /* first */
254   oop_readable_call *readable_callback;
255   void *readable_callback_user;
256
257   int fd;
258   Filemon_Perfile *filemon;
259
260   oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
261   off_t offset;
262   int skippinglong, paused, fake_readable;
263
264   ArticleList queue;
265   long inprogress; /* includes queue.count and also articles in conns */
266   long autodefer; /* -1 means not doing autodefer */
267
268   Counts counts;
269   char path[];
270 };
271
272 struct Article {
273   ISNODE(Article);
274   ArtState state;
275   int midlen, missing;
276   InputFile *ipf;
277   TOKEN token;
278   off_t offset;
279   int blanklen;
280   char messageid[1];
281 };
282
283 struct Conn {
284   ISNODE(Conn);
285   int fd; /* may be 0, meaning closed (during construction/destruction) */
286   oop_read *rd; /* likewise */
287   int oopwriting; /* since on_fd is not idempotent */
288   int max_queue, stream;
289   const char *quitting;
290   int since_activity; /* periods */
291   ArticleList waiting; /* not yet told peer */
292   ArticleList priority; /* peer says send it now */
293   ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
294   struct iovec xmit[CONNIOVS];
295   XmitDetails xmitd[CONNIOVS];
296   int xmitu;
297 };
298
299 #define SMS_LIST(X)                             \
300   X(NORMAL)                                     \
301   X(FLUSHING)                                   \
302   X(FLUSHFAILED)                                \
303   X(SEPARATED)                                  \
304   X(DROPPING)                                   \
305   X(DROPPED)
306
307 enum StateMachineState {
308 #define SMS_DEF_ENUM(s) sm_##s,
309   SMS_LIST(SMS_DEF_ENUM)
310 };
311
312 extern const char *sms_names[];
313
314 /*========== function declarations ==========*/
315
316 /*----- help.c -----*/
317
318 void syscrash(const char *fmt, ...) NORET_PRINTF(1,2);
319 void crash(const char *fmt, ...) NORET_PRINTF(1,2);
320 void info(const char *fmt, ...) PRINTF(1,2);
321 void dbg(const char *fmt, ...) PRINTF(1,2);
322
323 void logv(int sysloglevel, const char *pfx, int errnoval,
324           const char *fmt, va_list al) PRINTF(5,0);
325
326 char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
327 char *xasprintf(const char *fmt, ...) PRINTF(1,2);
328
329 int close_perhaps(int *fd);
330 void xclose(int fd, const char *what, const char *what2);
331 void xclose_perhaps(int *fd, const char *what, const char *what2);
332 pid_t xfork(const char *what); /* also runs postfork in child */
333 pid_t xfork_bare(const char *what);
334
335 void on_fd_read_except(int fd, oop_call_fd callback);
336 void cancel_fd_read_except(int fd);
337
338 void report_child_status(const char *what, int status);
339 int xwaitpid(pid_t *pid, const char *what);
340
341 void *zxmalloc(size_t sz);
342 void xunlink(const char *path, const char *what);
343 time_t xtime(void);
344 void xsigaction(int signo, const struct sigaction *sa);
345 void xsigsetdefault(int signo);
346 void raise_default(int signo) NORET;
347
348 void xgettimeofday(struct timeval *tv_r);
349 void xsetnonblock(int fd, int nonb);
350
351 void check_isreg(const struct stat *stab, const char *path,
352                         const char *what);
353 void xfstat(int fd, struct stat *stab_r, const char *what);
354 void xfstat_isreg(int fd, struct stat *stab_r,
355                   const char *path, const char *what);
356 void xlstat_isreg(const char *path, struct stat *stab,
357                   int *enoent_r /* 0 means ENOENT is fatal */,
358                   const char *what);
359 int samefile(const struct stat *a, const struct stat *b);
360
361 char *sanitise(const char *input, int len);
362
363 static inline int isewouldblock(int errnoval) {
364   return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
365 }
366
367 #define INNLOGSETS(INNLOGSET)                   \
368   INNLOGSET(die,      "fatal",    LOG_ERR)      \
369   INNLOGSET(warn,     "warning",  LOG_WARNING)  \
370   INNLOGSET(notice,   "notice",   LOG_NOTICE)   \
371   INNLOGSET(trace,    "trace",    LOG_NOTICE)
372 #define INNLOGSET_DECLARE(fn, pfx, sysloglevel)                         \
373   void duct_log_##fn(int l, const char *fmt, va_list al, int errval)    \
374     PRINTF(3,0);
375 INNLOGSETS(INNLOGSET_DECLARE)
376
377 /*----- duct.c -----*/
378
379 void postfork(void);
380 void period(void);
381
382 /*----- cli.c -----*/
383
384 void cli_init(void);
385 void cli_stdio(void);
386
387 /*----- conn.c -----*/
388
389 void conn_closefd(Conn *conn, const char *msgprefix);
390 void check_idle_conns(void);
391 int conn_busy(Conn *conn);
392 void conn_dispose(Conn *conn);
393
394 void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
395 void connfail(Conn *conn, const char *fmt, ...)         PRINTF(2,3);
396
397 void notice_conns_more(const char *new_kind);
398 void notice_conns_fewer(void);
399 void notice_conns_stats(void);
400
401 int allow_connect_start(void);
402 void connect_start(void);
403
404 /*----- defer.c -----*/
405
406 void poll_backlog_file(void);
407 void search_backlog_file(void);
408 void open_defer(void);
409 void close_defer(void);
410
411 /*----- filemon.c -----*/
412
413 int filemon_method_init(void);
414 void filemon_method_dump_info(FILE *f);
415
416 void filemon_start(InputFile *ipf);
417 void filemon_stop(InputFile *ipf);
418
419 /*----- infile.c -----*/
420
421 void filepoll(void);
422
423 void inputfile_reading_start(InputFile *ipf);
424 void inputfile_reading_stop(InputFile *ipf);
425 void inputfile_reading_pause(InputFile *ipf);
426 void inputfile_reading_resume(InputFile *ipf);
427   /* pause and resume are idempotent, and no-op if not done _reading_start */
428
429 InputFile *open_input_file(const char *path);
430 void close_input_file(InputFile *ipf); /* does not free */
431 char *dbg_report_ipf(InputFile *ipf);
432
433 void tailing_make_readable(InputFile *ipf);
434
435 /*----- recv.c -----*/
436
437 extern const oop_rd_style peer_rd_style;
438 oop_rd_call peer_rd_ok, peer_rd_err;
439
440 void article_done(Article *art, int whichcount);
441
442 /*----- statemc.c -----*/
443
444 void statemc_check_flushing_done(void);
445 void statemc_check_backlog_done(void);
446
447 extern sig_atomic_t terminate_sig_flag;
448 void statemc_period_poll(void);
449 void statemc_lock(void);
450 void init_signals(void);
451 void statemc_init(void);
452 void showstats(void);
453
454 #define SMS(newstate, periods, why) \
455    (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
456 void statemc_setstate(StateMachineState newsms, int periods,
457                              const char *forlog, const char *why);
458
459 void statemc_start_flush(const char *why); /* Normal => Flushing */
460 void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
461 int trigger_flush_ok(const char *why /* 0 means timeout */);
462                                   /* => Flushing,FLUSHING, ret 1; or ret 0 */
463
464 void preterminate(void);
465
466 /*----- xmit.c -----*/
467
468 void inputfile_queue_check_expired(InputFile *ipf);
469 void check_assign_articles(void);
470 void queue_check_input_done(void);
471 void check_reading_pause_resume(InputFile *ipf);
472
473 void conn_maybe_write(Conn *conn);
474 void conn_make_some_xmits(Conn *conn);
475 void *conn_write_some_xmits(Conn *conn);
476
477 void xmit_free(XmitDetails *d);
478
479 int article_check_expired(Article *art /* must be queued, not conn */);
480 void article_autodefer(InputFile *ipf, Article *art);
481 void article_defer(Article *art /* not on a queue */, int whichcount);
482 void autodefer_input_file(InputFile *ipf);
483
484 /*----- external linkage for debug/dump only -----*/
485
486 extern pid_t connecting_child;
487 extern int connecting_fdpass_sock;
488 extern pid_t inndcomm_child;
489
490 /*========== general operational variables ==========*/
491
492 /* duct.c */
493 extern oop_source *loop;
494 extern ConnList conns;
495 extern char *path_lock, *path_flushing, *path_defer, *path_dump;
496 extern char *globpat_backlog;
497 extern pid_t self_pid;
498 extern int *lowvol_perperiod;
499 extern int lowvol_circptr;
500 extern int lowvol_total; /* does not include current period */
501 extern int until_stats_log;
502
503 /* statemc.c */
504 extern StateMachineState sms;
505 extern int until_flush;
506 extern InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
507 extern Counts backlog_counts;
508 extern int backlog_counts_report;
509 extern FILE *defer;
510 extern int until_connect, until_backlog_nextscan;
511 extern double accept_proportion;
512 extern int nocheck, nocheck_reported, in_child;
513
514 /* help.c */
515 extern int simulate_flush;
516 extern int logv_use_syslog;
517 extern const char *logv_prefix;
518
519
520 #endif /*INNDUCT_H*/