1 /*
2 * Copyright (C) 2013 Nikos Mavrogiannopoulos
3 *
4 * This file is part of ocserv.
5 *
6 * ocserv is free software: you can redistribute it and/or modify it
7 * 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 * ocserv is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * 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, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <config.h>
21
22 #include <vpn.h>
23 #include <worker.h>
24 #include <worker-bandwidth.h>
25 #include <gettime.h>
26
27 #include <stdio.h>
28
29
_bandwidth_update(bandwidth_st * b,size_t bytes,struct timespec * now)30 int _bandwidth_update(bandwidth_st* b, size_t bytes, struct timespec *now)
31 {
32 size_t sum;
33 ssize_t t, remain;
34 unsigned int diff;
35 size_t transferred_kb;
36
37 diff = timespec_sub_ms(now, &b->count_start);
38 if (diff >= COUNT_UPDATE_MS) {
39 transferred_kb = b->transferred_bytes / 1000;
40 transferred_kb = (transferred_kb*COUNT_UPDATE_MS)/diff;
41
42 memcpy(&b->count_start, now, sizeof(*now));
43
44 remain = b->allowed_kb - transferred_kb;
45 t = b->allowed_kb_per_count + remain;
46
47 b->allowed_kb = MIN(t, b->kb_per_sec);
48 b->transferred_bytes = bytes;
49
50 return 1;
51 }
52
53 sum = b->transferred_bytes + bytes;
54 if (sum > b->allowed_kb*1000)
55 return 0; /* NO */
56
57 b->transferred_bytes = sum;
58
59 return 1;
60 }
61
62