-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.rs
301 lines (263 loc) · 10.1 KB
/
main.rs
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
mod tc;
mod utils;
use crate::tc::*;
use crate::utils::ss;
use std::collections::HashMap;
use std::io::{self, Write};
use std::sync::{Arc, Mutex};
pub type CatchAll<T> = Result<T, Box<dyn std::error::Error>>;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.contains(&"-h".to_string()) || args.contains(&"--help".to_string()) {
//TODO helpful message
std::process::exit(0);
}
limit(Some(2), io::stdout(), io::stdin()).unwrap();
}
pub fn limit(delay: Option<usize>, mut tx: io::Stdout, rx: io::Stdin) -> crate::CatchAll<()> {
use TrafficType::*;
let mut program_to_trafficid_map = HashMap::new();
// block till we get an initial interface
// and while we're at it if we get a global limit msg save the values
// also if we get stop msg quit early
let mut global_limit_record: (Option<String>, Option<String>) = Default::default();
let mut msg = String::new();
let mut current_interface = loop {
rx.read_line(&mut msg).unwrap();
if !msg.is_empty() {
match msg.clone().into() {
Message::Stop => {
writeln!(tx, "Stop")?;
return Ok(());
}
Message::Interface(name) => break name,
Message::Global(limit) => {
global_limit_record = limit;
}
Message::Program(_) => (),
}
msg.clear();
}
};
let (mut root_ingress, mut root_egress) = tc_setup(
¤t_interface,
global_limit_record.0.clone(),
global_limit_record.1.clone(),
)?;
let mut filtered_ports: HashMap<(TrafficType, String), String> = HashMap::new();
let msgs = Arc::new(Mutex::new(String::new()));
// Read stdin msg in a new thread
let msgs_c = msgs.clone();
std::thread::spawn(move || {
let mut tmp = String::new();
loop {
rx.read_line(&mut tmp).unwrap();
*msgs_c.lock().unwrap() = tmp.clone();
tmp.clear();
}
});
loop {
// check for new user limits
// and add htb class for them
// TODO remove freed htb classes
let mut active_ports = HashMap::new();
// check if we recieved a new msg on stdin
let msg = msgs.lock().unwrap().clone();
if !msg.is_empty() {
match Message::from(msg) {
Message::Interface(name) => {
tc::clean_up(&root_ingress.interface, ¤t_interface)?;
current_interface = name;
reset_tc(
¤t_interface,
&mut root_ingress,
&mut root_egress,
global_limit_record.clone(),
&mut filtered_ports,
)?;
}
Message::Global(limit) => {
tc::clean_up(&root_ingress.interface, ¤t_interface)?;
// save new values
global_limit_record = limit;
reset_tc(
¤t_interface,
&mut root_ingress,
&mut root_egress,
global_limit_record.clone(),
&mut filtered_ports,
)?;
}
Message::Program((name, (down, up))) => {
let ingress_class_id = if let Some(down) = down {
Some(tc::tc_add_htb_class(&root_ingress, &down)?)
} else {
None
};
let egress_class_id = if let Some(up) = up {
Some(tc::tc_add_htb_class(&root_egress, &up)?)
} else {
None
};
program_to_trafficid_map
.insert(name.clone(), (ingress_class_id, egress_class_id));
}
Message::Stop => {
tc::clean_up(&root_ingress.interface, ¤t_interface)?;
writeln!(tx, "Stop")?;
break Ok(());
}
}
// clear msg
msgs.lock().unwrap().clear();
}
// look for new ports to filter
let active_connections = ss()?;
for (program, connections) in active_connections {
let program_in_map = program_to_trafficid_map
.get(&program)
.map(ToOwned::to_owned);
let (ingress_class_id, egress_class_id) = match program_in_map {
Some(id) => id,
None => {
// this is a new program
// add a placeholder for it in the program_to_trafficid_map
// and send it to the gui
program_to_trafficid_map.insert(program.clone(), (None, None));
let msg = format!("ProgramEntry: {}", program);
writeln!(tx, "{}", msg)?;
continue;
}
};
// filter the connection ports accoding the user specified limits
for con in connections {
if let Some(ingress_class_id) = ingress_class_id {
let ingress_port = (Ingress, con.lport.clone());
if filtered_ports.contains_key(&ingress_port) {
active_ports
.insert(ingress_port.clone(), filtered_ports[&ingress_port].clone());
continue;
} else {
let ingress_filter_id = tc::add_ingress_filter(
&con.lport,
&root_ingress.interface,
root_ingress.qdisc_id,
ingress_class_id,
)?;
active_ports.insert(ingress_port, ingress_filter_id);
}
}
if let Some(egress_class_id) = egress_class_id {
let egress_port = (Egress, con.lport.clone());
if filtered_ports.contains_key(&egress_port) {
active_ports
.insert(egress_port.clone(), filtered_ports[&egress_port].clone());
continue;
} else {
let egress_filter_id = tc::add_egress_filter(
&con.lport,
&root_egress.interface,
root_egress.qdisc_id,
egress_class_id,
)?;
active_ports.insert(egress_port, egress_filter_id);
}
}
}
}
// remove filter for freed ports
for (port, filter_id) in filtered_ports {
if !active_ports.contains_key(&port) {
match port.0 {
Ingress => {
tc::tc_remove_u32_filter(
&root_ingress.interface,
&filter_id,
root_ingress.qdisc_id,
)?;
}
Egress => {
tc::tc_remove_u32_filter(
&root_egress.interface,
&filter_id,
root_egress.qdisc_id,
)?;
}
}
}
}
// update the currently filtered ports
filtered_ports = active_ports;
// delay scanning for active connections
if let Some(delay) = delay {
std::thread::sleep(std::time::Duration::from_secs(delay as u64));
}
}
}
#[derive(PartialEq, Eq, Hash, Clone)]
enum TrafficType {
/// Incomming traffic
Ingress,
/// Outgoing traffic
Egress,
}
fn reset_tc(
current_interface: &str,
ingress: &mut Traffic,
egress: &mut Traffic,
global_limit: (Option<String>, Option<String>),
filtered_ports: &mut HashMap<(TrafficType, String), String>,
) -> CatchAll<()> {
filtered_ports.clear();
let (new_ingress, new_egress) =
tc::tc_setup(current_interface, global_limit.0, global_limit.1)?;
*ingress = new_ingress;
*egress = new_egress;
Ok(())
}
#[derive(PartialEq, Debug)]
pub enum Message {
Stop,
Interface(String),
Global((Option<String>, Option<String>)),
Program((String, (Option<String>, Option<String>))),
}
impl From<String> for Message {
fn from(msg: String) -> Message {
use Message::*;
match msg.trim() {
"Stop" => Stop,
msg if msg.starts_with("Interface: ") => {
Interface(msg.split("Interface: ").nth(1).unwrap().to_string())
}
msg if msg.starts_with("Global: ") => {
let msg = msg.split("Global: ").nth(1).unwrap();
let mut msg = msg.split_whitespace();
let mut up = msg.next().map(ToString::to_string);
let mut down = msg.next().map(ToString::to_string);
if up == Some("None".into()) {
up = None;
}
if down == Some("None".into()) {
down = None;
}
Global((up, down))
}
msg if msg.starts_with("Program: ") => {
let msg = msg.split("Program: ").nth(1).unwrap();
let mut msg = msg.split_whitespace();
let program_name = msg.next().unwrap().to_string();
let mut up = msg.next().map(ToString::to_string);
let mut down = msg.next().map(ToString::to_string);
if up == Some("None".into()) {
up = None;
}
if down == Some("None".into()) {
down = None;
}
Program((program_name, (up, down)))
}
msg => panic!("Uknown msg recieved: {}", msg),
}
}
}