aboutsummaryrefslogtreecommitdiff
path: root/lib/tbf_rate.c
blob: 5a71470635f9ea3acbe6e9df4cd75ce0d7efbde6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/* 
   This file is part of Mailfromd.
   Copyright (C) 2005, 2006, 2007, 2008, 2010, 2011 Sergey Poznyakoff
   Copyright (C) 2009 Netservers Ltd

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <mailutils/mailutils.h>
#include "libmf.h"
#include "mfdb.h"
#include "filenames.h"
#include "inttypes.h"

static void tbf_rate_print_item(struct mu_dbm_datum const *key,
				struct mu_dbm_datum const *val);
static int tbf_rate_expire_item(const void *content);

static struct db_format tbf_rate_format_struct = {
	"tbf",
	"tbf.db",
	1,
	0,
	DEFAULT_EXPIRE_INTERVAL,
	tbf_rate_print_item,
	tbf_rate_expire_item
};

struct db_format *tbf_rate_format = &tbf_rate_format_struct;


/*
  This implements a classical token bucket filter algorithm, with
  the minor optimization that the number of tokens in each bucket
  is interpolated and thus only recalculated when needed.
  
  Tokens are added to the bucket indentified by the key 'email'
  at constant rate of 1 token per 'interval' microseconds, to a
  maximum of 'burst_size' tokens.

  Each call to check_tbf_rate() will:
     return ret=1 (true) if 'cost' tokens are available, and
                         remove 'cost' tokens from the bucket

  or return ret=0 (false) if there are less than 'cost' tokens
                          available.

  If no bucket is found for the specified key, a new bucket is
  created and initialized to contain 'burst_size' tokens.
  
  Ben McKeegan <ben@netservers.co.uk>
*/

struct tbf_rate_result {
	uint64_t timestamp;  /* microseconds since epoch */
	time_t expirytime;
	size_t tokens;       /* tokens available */
};

#ifndef USEC_PER_SEC
# define USEC_PER_SEC  1000000L
#endif

mf_status
check_tbf_rate(char *email, int *ret,
	       size_t cost, size_t interval, size_t burst_size)
{
	mu_dbm_file_t db;
	struct mu_dbm_datum key;
	struct mu_dbm_datum contents;
	int local_contents = 0;
	struct tbf_rate_result *rp, tbf_rate;
	struct timeval tv;
	uint64_t now;
	int res;

	if (interval == 0 || burst_size == 0)
		return mf_failure;

	if (!cost) {
		/* cost free, so don't waste time on database access */
		*ret = 1;
		return mf_success;
	}
	if (cost > burst_size) {
		/* impossibly expensive, so don't waste time on
		   database access */
		*ret = 0;
		return mf_success;
	}

	mu_debug(tbf_rate_format->debug_handle, MU_DEBUG_TRACE5,
		 ("getting TBF rate info for %s", email));
	db = mf_dbm_open(tbf_rate_format->dbname, MU_STREAM_RDWR, 0600);\
	if (!db) {
		mu_error(_("mf_dbm_open(%s) failed: %s"),
			 tbf_rate_format->dbname,
			 mu_dbm_strerror(db));
		return mf_failure;
	}
  
	memset(&key, 0, sizeof key);
	memset(&contents, 0, sizeof contents);
	key.mu_dptr = email;
	key.mu_dsize = strlen(email) + 1;
	
	gettimeofday(&tv,NULL);
	now = (uint64_t)tv.tv_sec * USEC_PER_SEC + (uint64_t)tv.tv_usec;

	if ((res = mu_dbm_fetch(db, &key, &contents)) == 0) {
		uint64_t elapsed;
		uint64_t tokens;
		
		rp = (struct tbf_rate_result *) contents.mu_dptr;
		/* calculate elapsed time and number of new tokens since
		   last add */;
		elapsed = now - rp->timestamp;
		tokens = elapsed / interval; /* partial tokens ignored */
		/* timestamp set to time of most recent token */
		rp->timestamp += tokens * interval; 
		
		/* add existing tokens to 64bit counter to prevent overflow
		   in range check */
		tokens += rp->tokens;
		if (tokens >= burst_size)
			rp->tokens = burst_size;
		else
			rp->tokens = (size_t)tokens;
		
		mu_debug(tbf_rate_format->debug_handle, MU_DEBUG_TRACE5,
			 ("found, elapsed time: %"PRIu64
			  " us, new tokens: %"PRIu64", total: %lu ",
			  elapsed, tokens, (unsigned long) rp->tokens));
 	} else {
		if (res != MU_ERR_NOENT)
			mu_error(_("cannot fetch `%s' from `%s': %s"),
				 email, tbf_rate_format->dbname,
				 mu_dbm_strerror(db));	
		/* Initialize the structure */
		tbf_rate.timestamp = now;
		tbf_rate.tokens = burst_size;
		rp = &tbf_rate;
		local_contents = 1;
	}
  
	if (cost <= rp->tokens) {
		*ret = 1;
		rp->tokens -= cost;
		mu_debug(tbf_rate_format->debug_handle, MU_DEBUG_TRACE5,
			 ("tbf_rate matched %s", email));
	} else {
		*ret = 0;
		mu_debug(tbf_rate_format->debug_handle, MU_DEBUG_TRACE5,
			 ("tbf_rate overlimit on %s", email));
	}

	/* record may expire as soon as enough tokens have been
	   delivered to overflow the bucket, since a new
	   record may be created on demand with a full bucket */
	rp->expirytime = (time_t)
		(((uint64_t)interval *
		  (uint64_t)(1 + burst_size - rp->tokens) +
		  rp->timestamp) / USEC_PER_SEC) + 1;

	/* Update the db */
	contents.mu_dptr = (void*)rp;
	contents.mu_dsize = sizeof(*rp);
	res = mu_dbm_store(db, &key, &contents, 1);
	if (res)
		mu_error (_("cannot store datum `%s' into `%s': %s"),
			  email, tbf_rate_format->dbname,
			  res == MU_ERR_FAILURE ?
			   mu_dbm_strerror(db) : mu_strerror(res));

	if (!local_contents)
		mu_dbm_datum_free(&contents);
  
	mu_dbm_close(db);
	return mf_success;
}

static void
tbf_rate_print_item(struct mu_dbm_datum const *key,
		    struct mu_dbm_datum const *val)
{
	const struct tbf_rate_result *res = (const struct tbf_rate_result *)
		                              val->mu_dptr;
	int size = key->mu_dsize - 1; /* Size includes the trailing nul */

	printf("%*.*s tok:%lu@", size, size, key->mu_dptr,
	       (unsigned long) res->tokens);
	format_time_str(stdout, (time_t) (res->timestamp / USEC_PER_SEC));
	printf(" exp:");
	format_time_str(stdout, res->expirytime);
	printf("\n");
}

static int
tbf_rate_expire_item(const void *content)
{
	const struct tbf_rate_result *res = content;
	return tbf_rate_format->expire_interval &&
		time(NULL) - res->expirytime >
		tbf_rate_format->expire_interval;
}

Return to:

Send suggestions and report system problems to the System administrator.