jabberd2  2.7.0
rate.c
Go to the documentation of this file.
1 /*
2  * jabberd - Jabber Open Source Server
3  * Copyright (c) 2002 Jeremie Miller, Thomas Muldowney,
4  * Ryan Eatmon, Robert Norris
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA02111-1307USA
19  */
20 
21 /* rate controls (for implementing connect-limiting or karma) */
22 
23 #include "util.h"
24 
25 rate_t rate_new(int total, int seconds, int wait)
26 {
27  rate_t rt = (rate_t) calloc(1, sizeof(struct rate_st));
28 
29  rt->total = total;
30  rt->seconds = seconds;
31  rt->wait = wait;
32 
33  return rt;
34 }
35 
36 void rate_free(rate_t rt)
37 {
38  free(rt);
39 }
40 
42 {
43  rt->time = 0;
44  rt->count = 0;
45  rt->bad = 0;
46 }
47 
48 void rate_add(rate_t rt, int count)
49 {
50  time_t now;
51 
52  now = time(NULL);
53 
54  /* rate expired */
55  if(now - rt->time >= rt->seconds)
56  rate_reset(rt);
57 
58  rt->count += count;
59 
60  /* first event, so set the time */
61  if(rt->time == 0)
62  rt->time = now;
63 
64  /* uhoh, they stuffed up */
65  if(rt->count >= rt->total)
66  rt->bad = now;
67 }
68 
70 {
71  /* if we're bad, then there's none left */
72  if(rt->bad != 0)
73  return 0;
74 
75  return rt->total - rt->count;
76 }
77 
79 {
80  /* not tracking */
81  if(rt->time == 0)
82  return 1;
83 
84  /* under the limit */
85  if(rt->count < rt->total)
86  return 1;
87 
88  /* currently bad */
89  if(rt->bad != 0)
90  {
91  /* wait over, they're good again */
92  if(time(NULL) - rt->bad >= rt->wait)
93  {
94  rate_reset(rt);
95  return 1;
96  }
97 
98  /* keep them waiting */
99  return 0;
100  }
101 
102  /* they're inside the time, and not bad yet */
103  return 1;
104 }
void rate_add(rate_t rt, int count)
Add a number of events to the counter.
Definition: rate.c:48
rate_t rate_new(int total, int seconds, int wait)
Definition: rate.c:25
int wait
Definition: util.h:262
int count
Definition: util.h:265
void rate_free(rate_t rt)
Definition: rate.c:36
struct rate_st * rate_t
time_t bad
Definition: util.h:267
int seconds
Definition: util.h:261
int rate_check(rate_t rt)
Definition: rate.c:78
int rate_left(rate_t rt)
Definition: rate.c:69
Definition: util.h:258
void rate_reset(rate_t rt)
Definition: rate.c:41
time_t time
Definition: util.h:264
int total
Definition: util.h:260