1 /*
2  * Copyright (C) 2013 Nikos Mavrogiannopoulos
3  *
4  * Author: Nikos Mavrogiannopoulos
5  *
6  * This file is part of ocserv.
7  *
8  * ocserv is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public License
10  * as published by the Free Software Foundation; either version 2.1 of
11  * the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>
20  */
21 #ifndef WORKER_BANDWIDTH_H
22 # define WORKER_BANDWIDTH_H
23 
24 #include <gettime.h>
25 #include <time.h>
26 #include <unistd.h>
27 
28 #define COUNT_UPDATE_MS 500
29 
30 typedef struct bandwidth_st {
31 	struct timespec count_start;
32 	size_t transferred_bytes;
33 	size_t allowed_kb;
34 
35 	/* only touched once */
36 	size_t allowed_kb_per_count;
37 	size_t kb_per_sec;
38 } bandwidth_st;
39 
bandwidth_init(bandwidth_st * b,size_t kb_per_sec)40 inline static void bandwidth_init(bandwidth_st* b, size_t kb_per_sec)
41 {
42 	memset(b, 0, sizeof(*b));
43 	b->kb_per_sec = kb_per_sec;
44 	b->allowed_kb_per_count = (b->kb_per_sec*COUNT_UPDATE_MS)/1000;
45 }
46 
47 int _bandwidth_update(bandwidth_st* b, size_t bytes, struct timespec* now);
48 
49 /* returns true or false, depending on whether to send
50  * the bytes */
51 inline static
bandwidth_update(bandwidth_st * b,size_t bytes,struct timespec * now)52 int bandwidth_update(bandwidth_st* b, size_t bytes, struct timespec* now)
53 {
54 	/* if bandwidth control is disabled */
55 	if (b->kb_per_sec == 0)
56 		return 1;
57 
58 	return _bandwidth_update(b, bytes, now);
59 }
60 
61 
62 #endif
63