Version 1.2.0
[l2tpns.git] / throttle.c
1 // L2TPNS Throttle Stuff
2 // $Id: throttle.c,v 1.3 2004/05/24 04:29:21 fred_nerk Exp $
3
4 #include <stdio.h>
5 #include <sys/file.h>
6 #include <sys/stat.h>
7 #include <sys/wait.h>
8 #include <sys/types.h>
9 #include <malloc.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include <time.h>
13 #include <arpa/inet.h>
14 #include <errno.h>
15 #include <unistd.h>
16 #include "l2tpns.h"
17 #include "util.h"
18
19 extern radiust *radius;
20 extern sessiont *session;
21 extern u32 sessionid;
22 extern tbft *filter_buckets;
23 extern struct configt *config;
24
25 // Throttle or Unthrottle a session
26 int throttle_session(sessionidt s, int throttle)
27 {
28 if (!config->rl_rate) return 0;
29
30 if (!*session[s].user)
31 return 0; // User not logged in
32
33 if (throttle)
34 {
35 // Throttle them
36 char cmd[2048] = {0};
37 if (!session[s].tbf) session[s].tbf = rl_get_tbf();
38 if (!session[s].tbf)
39 {
40 log(1, 0, s, session[s].tunnel, "Error creating a filtering bucket for user %s\n", session[s].user);
41 return 0;
42 }
43 log(2, 0, s, session[s].tunnel, "Throttling session %d for user %s (bucket %s)\n", s, session[s].user, filter_buckets[session[s].tbf].handle);
44 snprintf(cmd, 2048, "iptables -t mangle -A throttle -d %s -j MARK --set-mark %d",
45 inet_toa(ntohl(session[s].ip)),
46 session[s].tbf);
47 log(4, 0, s, session[s].tunnel, "Running %s\n", cmd);
48 if (WEXITSTATUS(system(cmd)) != 0)
49 {
50 log(2, 0, s, session[s].tunnel, "iptables returned an error. Session is not throttled\n");
51 return 0;
52 }
53 }
54 else
55 {
56 char cmd[2048] = {0};
57 log(2, 0, s, session[s].tunnel, "Unthrottling session %d for user %s\n", s, session[s].user);
58 if (session[s].tbf)
59 {
60 int count = 10;
61 snprintf(cmd, 2048, "iptables -t mangle -D throttle -d %s -j MARK --set-mark %d", inet_toa(ntohl(session[s].ip)), session[s].tbf);
62 log(4, 0, s, session[s].tunnel, "Running %s\n", cmd);
63 while (--count)
64 {
65 int status = system(cmd);
66 if (WEXITSTATUS(status) != 0) break;
67 }
68 system(cmd);
69
70 rl_done_tbf(session[s].tbf);
71 session[s].tbf = 0;
72 }
73 }
74 session[s].throttle = throttle;
75 return session[s].throttle;
76 }
77