File: rate.c

package info (click to toggle)
jabberd2 2.7.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 4,016 kB
  • sloc: ansic: 37,099; sh: 1,108; perl: 656; xml: 561; makefile: 511; python: 238; ruby: 145; sql: 55
file content (104 lines) | stat: -rw-r--r-- 2,298 bytes parent folder | download | duplicates (5)
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
/*
 * jabberd - Jabber Open Source Server
 * Copyright (c) 2002 Jeremie Miller, Thomas Muldowney,
 *                    Ryan Eatmon, Robert Norris
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA02111-1307USA
 */

/* rate controls (for implementing connect-limiting or karma) */

#include "util.h"

rate_t rate_new(int total, int seconds, int wait)
{
    rate_t rt = (rate_t) calloc(1, sizeof(struct rate_st));

    rt->total = total;
    rt->seconds = seconds;
    rt->wait = wait;

    return rt;
}

void rate_free(rate_t rt)
{
    free(rt);
}

void rate_reset(rate_t rt)
{
    rt->time = 0;
    rt->count = 0;
    rt->bad = 0;
}

void rate_add(rate_t rt, int count)
{
    time_t now;

    now = time(NULL);

    /* rate expired */
    if(now - rt->time >= rt->seconds)
        rate_reset(rt);

    rt->count += count;

    /* first event, so set the time */
    if(rt->time == 0)
        rt->time = now;

    /* uhoh, they stuffed up */
    if(rt->count >= rt->total)
        rt->bad = now;
}

int rate_left(rate_t rt)
{
    /* if we're bad, then there's none left */
    if(rt->bad != 0)
        return 0;

    return rt->total - rt->count;
}

int rate_check(rate_t rt)
{
    /* not tracking */
    if(rt->time == 0)
        return 1;

    /* under the limit */
    if(rt->count < rt->total)
        return 1;

    /* currently bad */
    if(rt->bad != 0)
    {
        /* wait over, they're good again */
        if(time(NULL) - rt->bad >= rt->wait)
        {
            rate_reset(rt);
            return 1;
        }

        /* keep them waiting */
        return 0;
    }

    /* they're inside the time, and not bad yet */
    return 1;
}