Initial import (again)
[srvx.git] / src / policer.c
1 /* policer.c - Leaky bucket
2  * Copyright 2000-2002 srvx Development Team
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.  Important limitations are
8  * listed in the COPYING file that accompanies this software.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, email srvx-maintainers@srvx.net.
17  */
18
19 #include "common.h"
20 #include "policer.h"
21
22 /* This policer uses the "leaky bucket" (GCRA) algorithm. */ 
23
24 struct policer_params {
25     double bucket_size;
26     double drain_rate;
27 };
28
29 struct policer_params *
30 policer_params_new(void)
31 {
32     struct policer_params *params = malloc(sizeof(struct policer_params));
33     params->bucket_size = 0.0;
34     params->drain_rate = 0.0;
35     return params;
36 }
37
38 int
39 policer_params_set(struct policer_params *params, const char *param, const char *value)
40 {
41     if (!irccasecmp(param, "size")) {
42         params->bucket_size = strtod(value, NULL);
43     } else if (!irccasecmp(param, "drain-rate")) {
44         params->drain_rate = strtod(value, NULL);
45     } else {
46         return 0;
47     }
48     return 1;
49 }
50
51 void
52 policer_params_delete(struct policer_params *params)
53 {
54     free(params);
55 }
56
57 int
58 policer_conforms(struct policer *pol, time_t reqtime, double weight)
59 {
60     int res;
61     pol->level -= pol->params->drain_rate * (reqtime - pol->last_req);
62     if (pol->level < 0.0) pol->level = 0.0;
63     res = pol->level < pol->params->bucket_size;
64     pol->level += weight;
65     pol->last_req = reqtime;
66     return res;
67 }