chiark / gitweb /
logstats control command
[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_CONN(conn) \
88   for ((conn)=LIST_HEAD(conns); (conn); (conn)=LIST_NEXT((conn)))
89
90 /*----- doubly linked lists -----*/
91
92 #define ISNODE(T)   struct node list_node
93 #define DEFLIST(T)                              \
94    typedef struct {                             \
95      union { struct list li; T *for_type; } u;  \
96      int count;                                 \
97    } T##List
98
99 #define NODE(n) (assert((void*)&(n)->list_node == (n)), &(n)->list_node)
100
101 #define LIST_CHECKCANHAVENODE(l,n) \
102   ((void)((n) == ((l).u.for_type))) /* just for the type check */
103
104 #define LIST_ADDSOMEHOW(l,n,list_addsomehow)    \
105  ( LIST_CHECKCANHAVENODE(l,n),                  \
106    list_addsomehow(&(l).u.li, NODE((n))),       \
107    (void)(l).count++                            \
108    )
109
110 #define LIST_REMSOMEHOW(l,list_remsomehow)      \
111  ( (typeof((l).u.for_type))                     \
112    ( (l).count                                  \
113      ? ( (l).count--,                           \
114          list_remsomehow(&(l).u.li) )           \
115      : 0                                        \
116      )                                          \
117    )
118
119
120 #define LIST_ADDHEAD(l,n) LIST_ADDSOMEHOW((l),(n),list_addhead)
121 #define LIST_ADDTAIL(l,n) LIST_ADDSOMEHOW((l),(n),list_addtail)
122 #define LIST_REMHEAD(l) LIST_REMSOMEHOW((l),list_remhead)
123 #define LIST_REMTAIL(l) LIST_REMSOMEHOW((l),list_remtail)
124
125 #define LIST_INIT(l) ((l).count=0, list_new(&(l).u.li))
126 #define LIST_HEAD(l) ((typeof((l).u.for_type))(list_head((struct list*)&(l))))
127 #define LIST_NEXT(n) ((typeof(n))list_succ(NODE((n))))
128 #define LIST_BACK(n) ((typeof(n))list_pred(NODE((n))))
129
130 #define LIST_REMOVE(l,n)                        \
131  ( LIST_CHECKCANHAVENODE(l,n),                  \
132    list_remove(NODE((n))),                      \
133    (void)(l).count--                            \
134    )
135
136 #define LIST_INSERT(l,n,pred)                                   \
137  ( LIST_CHECKCANHAVENODE(l,n),                                  \
138    LIST_CHECKCANHAVENODE(l,pred),                               \
139    list_insert((struct list*)&(l), NODE((n)), NODE((pred))),    \
140    (void)(l).count++                                            \
141    )
142
143 /*----- type predeclarations -----*/
144
145 typedef struct Conn Conn;
146 typedef struct Article Article;
147 typedef struct InputFile InputFile;
148 typedef struct XmitDetails XmitDetails;
149 typedef struct Filemon_Perfile Filemon_Perfile;
150 typedef enum StateMachineState StateMachineState;
151 typedef struct CliCommand CliCommand;
152
153 DEFLIST(Conn);
154 DEFLIST(Article);
155
156
157 /*----- configuration options -----*/
158
159 extern const char *sitename, *remote_host;
160 extern const char *feedfile, *path_run, *path_cli, *path_cli_dir;
161 extern int quiet_multiple, interactive, try_filemon, try_stream, port;
162 extern const char *inndconffile;
163
164 extern int max_connections, max_queue_per_conn, target_max_feedfile_size;
165 extern int period_seconds, filepoll_seconds, max_queue_per_ipf;
166 extern int connection_setup_timeout, inndcomm_flush_timeout;
167
168 extern double nocheck_thresh;
169 extern double nocheck_decay;
170
171 /* all these are initialised to seconds, and converted to periods in main */
172 extern int reconnect_delay_periods;
173 extern int flushfail_retry_periods;
174 extern int backlog_retry_minperiods;
175 extern int backlog_spontrescan_periods;
176 extern int spontaneous_flush_periods;
177 extern int max_separated_periods;
178 extern int need_activity_periods;
179 extern int lowvol_thresh;
180 extern int lowvol_periods;
181
182 extern double max_bad_data_ratio;
183 extern int max_bad_data_initial;
184
185
186 /*----- statistics -----*/
187
188 typedef enum {      /* in queue                 in conn->sent             */
189   art_Unchecked,    /*   not checked, not sent    checking                */
190   art_Wanted,       /*   checked, wanted          sent body as requested  */
191   art_Unsolicited,  /*   -                        sent body without check */
192   art_MaxState,
193 } ArtState;
194 extern const char *const artstate_names[]; /* xmit.c */
195
196 #define RESULT_COUNTS(RCS,RCN)                  \
197   RCS(sent)                                     \
198   RCS(accepted)                                 \
199   RCN(unwanted)                                 \
200   RCN(rejected)                                 \
201   RCN(deferred)                                 \
202   RCN(missing)                                  \
203   RCN(connretry)
204
205 #define RCI_TRIPLE_FMT_BASE "%d (id=%d,bod=%d,nc=%d)"
206 #define RCI_TRIPLE_VALS_BASE(counts,x)          \
207        counts[art_Unchecked] x                  \
208        + counts[art_Wanted] x                   \
209        + counts[art_Unsolicited] x,             \
210        counts[art_Unchecked] x                  \
211        , counts[art_Wanted] x                   \
212        , counts[art_Unsolicited] x
213
214 typedef enum {
215 #define RC_INDEX(x) RC_##x,
216   RESULT_COUNTS(RC_INDEX, RC_INDEX)
217   RCI_max
218 } ResultCountIndex;
219
220
221 /*----- transmission buffers -----*/
222
223 #define CONNIOVS 128
224
225 typedef enum {
226   xk_Const, xk_Artdata
227 } XmitKind;
228
229 struct XmitDetails {
230   XmitKind kind;
231   union {
232     ARTHANDLE *sm_art;
233   } info;
234 };
235
236
237 /*----- core operational data structure types -----*/
238
239 struct InputFile {
240   /* This is also an instance of struct oop_readable */
241   struct oop_readable readable; /* first */
242   oop_readable_call *readable_callback;
243   void *readable_callback_user;
244
245   int fd;
246   Filemon_Perfile *filemon;
247
248   oop_read *rd; /* non-0: reading; 0: constructing, or had EOF */
249   off_t offset;
250   int skippinglong, paused, fake_readable;
251
252   ArticleList queue;
253   long inprogress; /* includes queue.count and also articles in conns */
254   long autodefer; /* -1 means not doing autodefer */
255
256   int counts[art_MaxState][RCI_max];
257   int readcount_ok, readcount_blank, readcount_err, count_nooffer_missing;
258   char path[];
259 };
260
261 struct Article {
262   ISNODE(Article);
263   ArtState state;
264   int midlen, missing;
265   InputFile *ipf;
266   TOKEN token;
267   off_t offset;
268   int blanklen;
269   char messageid[1];
270 };
271
272 struct Conn {
273   ISNODE(Conn);
274   int fd; /* may be 0, meaning closed (during construction/destruction) */
275   oop_read *rd; /* likewise */
276   int oopwriting; /* since on_fd is not idempotent */
277   int max_queue, stream;
278   const char *quitting;
279   int since_activity; /* periods */
280   ArticleList waiting; /* not yet told peer */
281   ArticleList priority; /* peer says send it now */
282   ArticleList sent; /* offered/transmitted - in xmit or waiting reply */
283   struct iovec xmit[CONNIOVS];
284   XmitDetails xmitd[CONNIOVS];
285   int xmitu;
286 };
287
288 #define SMS_LIST(X)                             \
289   X(NORMAL)                                     \
290   X(FLUSHING)                                   \
291   X(FLUSHFAILED)                                \
292   X(SEPARATED)                                  \
293   X(DROPPING)                                   \
294   X(DROPPED)
295
296 enum StateMachineState {
297 #define SMS_DEF_ENUM(s) sm_##s,
298   SMS_LIST(SMS_DEF_ENUM)
299 };
300
301 extern const char *sms_names[];
302
303 /*========== function declarations ==========*/
304
305 /*----- help.c -----*/
306
307 void syscrash(const char *fmt, ...) NORET_PRINTF(1,2);
308 void crash(const char *fmt, ...) NORET_PRINTF(1,2);
309 void info(const char *fmt, ...) PRINTF(1,2);
310 void dbg(const char *fmt, ...) PRINTF(1,2);
311
312 void logv(int sysloglevel, const char *pfx, int errnoval,
313           const char *fmt, va_list al) PRINTF(5,0);
314
315 char *xvasprintf(const char *fmt, va_list al) PRINTF(1,0);
316 char *xasprintf(const char *fmt, ...) PRINTF(1,2);
317
318 int close_perhaps(int *fd);
319 void xclose(int fd, const char *what, const char *what2);
320 void xclose_perhaps(int *fd, const char *what, const char *what2);
321 pid_t xfork(const char *what);
322
323 void on_fd_read_except(int fd, oop_call_fd callback);
324 void cancel_fd_read_except(int fd);
325
326 void report_child_status(const char *what, int status);
327 int xwaitpid(pid_t *pid, const char *what);
328
329 void *zxmalloc(size_t sz);
330 void xunlink(const char *path, const char *what);
331 time_t xtime(void);
332 void xsigaction(int signo, const struct sigaction *sa);
333 void xsigsetdefault(int signo);
334 void raise_default(int signo) NORET;
335
336 void xgettimeofday(struct timeval *tv_r);
337 void xsetnonblock(int fd, int nonb);
338
339 void check_isreg(const struct stat *stab, const char *path,
340                         const char *what);
341 void xfstat(int fd, struct stat *stab_r, const char *what);
342 void xfstat_isreg(int fd, struct stat *stab_r,
343                   const char *path, const char *what);
344 void xlstat_isreg(const char *path, struct stat *stab,
345                   int *enoent_r /* 0 means ENOENT is fatal */,
346                   const char *what);
347 int samefile(const struct stat *a, const struct stat *b);
348
349 char *sanitise(const char *input, int len);
350
351 static inline int isewouldblock(int errnoval) {
352   return errnoval==EWOULDBLOCK || errnoval==EAGAIN;
353 }
354
355 #define INNLOGSETS(INNLOGSET)                   \
356   INNLOGSET(die,      "fatal",    LOG_ERR)      \
357   INNLOGSET(warn,     "warning",  LOG_WARNING)  \
358   INNLOGSET(notice,   "notice",   LOG_NOTICE)   \
359   INNLOGSET(trace,    "trace",    LOG_NOTICE)
360 #define INNLOGSET_DECLARE(fn, pfx, sysloglevel)                         \
361   void duct_log_##fn(int l, const char *fmt, va_list al, int errval)    \
362     PRINTF(3,0);
363 INNLOGSETS(INNLOGSET_DECLARE)
364
365 /*----- duct.c -----*/
366
367 void postfork(void);
368 void period(void);
369
370 /*----- cli.c -----*/
371
372 void cli_init(void);
373 void cli_stdio(void);
374
375 /*----- conn.c -----*/
376
377 void conn_closefd(Conn *conn, const char *msgprefix);
378 void check_idle_conns(void);
379 int conn_busy(Conn *conn);
380 void conn_dispose(Conn *conn);
381
382 void vconnfail(Conn *conn, const char *fmt, va_list al) PRINTF(2,0);
383 void connfail(Conn *conn, const char *fmt, ...)         PRINTF(2,3);
384
385 int allow_connect_start(void);
386 void connect_start(void);
387
388 /*----- defer.c -----*/
389
390 void poll_backlog_file(void);
391 void search_backlog_file(void);
392 void open_defer(void);
393 void close_defer(void);
394
395 /*----- filemon.c -----*/
396
397 int filemon_method_init(void);
398 void filemon_method_dump_info(FILE *f);
399
400 void filemon_start(InputFile *ipf);
401 void filemon_stop(InputFile *ipf);
402
403 /*----- infile.c -----*/
404
405 void filepoll(void);
406
407 void inputfile_reading_start(InputFile *ipf);
408 void inputfile_reading_stop(InputFile *ipf);
409 void inputfile_reading_pause(InputFile *ipf);
410 void inputfile_reading_resume(InputFile *ipf);
411   /* pause and resume are idempotent, and no-op if not done _reading_start */
412
413 InputFile *open_input_file(const char *path);
414 void close_input_file(InputFile *ipf); /* does not free */
415 char *dbg_report_ipf(InputFile *ipf);
416
417 void tailing_make_readable(InputFile *ipf);
418
419 /*----- recv.c -----*/
420
421 extern const oop_rd_style peer_rd_style;
422 oop_rd_call peer_rd_ok, peer_rd_err;
423
424 void article_done(Article *art, int whichcount);
425
426 /*----- statemc.c -----*/
427
428 void statemc_check_flushing_done(void);
429 void statemc_check_backlog_done(void);
430
431 extern sig_atomic_t terminate_sig_flag;
432 void statemc_period_poll(void);
433 void statemc_lock(void);
434 void init_signals(void);
435 void statemc_init(void);
436 void showstats(void);
437
438 #define SMS(newstate, periods, why) \
439    (statemc_setstate(sm_##newstate,(periods),#newstate,(why)))
440 void statemc_setstate(StateMachineState newsms, int periods,
441                              const char *forlog, const char *why);
442
443 void statemc_start_flush(const char *why); /* Normal => Flushing */
444 void spawn_inndcomm_flush(const char *why); /* Moved => Flushing */
445 int trigger_flush_ok(const char *why /* 0 means timeout */);
446                                   /* => Flushing,FLUSHING, ret 1; or ret 0 */
447
448 void preterminate(void);
449
450 /*----- xmit.c -----*/
451
452 void inputfile_queue_check_expired(InputFile *ipf);
453 void check_assign_articles(void);
454 void queue_check_input_done(void);
455 void check_reading_pause_resume(InputFile *ipf);
456
457 void conn_maybe_write(Conn *conn);
458 void conn_make_some_xmits(Conn *conn);
459 void *conn_write_some_xmits(Conn *conn);
460
461 void xmit_free(XmitDetails *d);
462
463 int article_check_expired(Article *art /* must be queued, not conn */);
464 void article_autodefer(InputFile *ipf, Article *art);
465 void article_defer(Article *art /* not on a queue */, int whichcount);
466 void autodefer_input_file(InputFile *ipf);
467
468 /*----- external linkage for debug/dump only -----*/
469
470 extern pid_t connecting_child;
471 extern int connecting_fdpass_sock;
472 extern pid_t inndcomm_child;
473
474 /*========== general operational variables ==========*/
475
476 /* innduct.c */
477 extern oop_source *loop;
478 extern ConnList conns;
479 extern char *path_lock, *path_flushing, *path_defer, *path_dump;
480 extern char *globpat_backlog;
481 extern pid_t self_pid;
482 extern int *lowvol_perperiod;
483 extern int lowvol_circptr;
484 extern int lowvol_total; /* does not include current period */
485
486 /* statemc.c */
487 extern StateMachineState sms;
488 extern int until_flush;
489 extern InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
490 extern FILE *defer;
491 extern int until_connect, until_backlog_nextscan;
492 extern double accept_proportion;
493 extern int nocheck, nocheck_reported, in_child;
494
495 /* help.c */
496 extern int simulate_flush;
497 extern int logv_use_syslog;
498 extern const char *logv_prefix;
499
500
501 #endif /*INNDUCT_H*/