forked from servalproject/serval-dna
-
Notifications
You must be signed in to change notification settings - Fork 0
/
limit.c
75 lines (62 loc) · 2.17 KB
/
limit.c
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
/*
Copyright (C) 2014 Serval Project Inc.
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 2
of the License, 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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <unistd.h>
#include "os.h"
#include "limit.h"
#define MIN_BURST_LENGTH 5000
static void update_limit_state(struct limit_state *state, time_ms_t now){
if (state->next_interval > now || state->burst_size==0){
return;
}
if (state->next_interval + state->burst_length>now)
state->next_interval+=state->burst_length;
else
state->next_interval=now + state->burst_length;
state->sent = 0;
}
/* When should we next allow this thing to occur? */
time_ms_t limit_next_allowed(struct limit_state *state){
time_ms_t now = gettime_ms();
if (!state->burst_size)
return now;
update_limit_state(state, now);
if (state->sent < state->burst_size)
return now;
return state->next_interval;
}
/* Can we do this now? if so, track it */
int limit_is_allowed(struct limit_state *state){
time_ms_t now = gettime_ms();
if (!state->burst_size)
return 0;
update_limit_state(state, now);
if (state->sent >= state->burst_size){
return -1;
}
state->sent ++;
return 0;
}
/* Initialise burst size and length based on the number we can do in one MIN_BURST */
int limit_init(struct limit_state *state, uint32_t rate_micro_seconds){
state->rate_micro_seconds = rate_micro_seconds;
if (rate_micro_seconds==0){
state->burst_size=0;
state->burst_length=0;
}else{
state->burst_size = (MIN_BURST_LENGTH / rate_micro_seconds)+1;
state->burst_length = (state->burst_size * rate_micro_seconds) / 1000.0;
}
return 0;
}