-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
main.rs
296 lines (267 loc) · 11.2 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
#![deny(clippy::all)]
mod cli;
mod display;
mod network;
mod os;
#[cfg(test)]
mod tests;
use std::{
collections::HashMap,
fs::File,
sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
Arc, Mutex, RwLock,
},
thread::{self, park_timeout},
time::{Duration, Instant},
};
use clap::Parser;
use crossterm::{
event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
terminal,
};
use display::{elapsed_time, RawTerminalBackend, Ui};
use network::{
dns::{self, IpTable},
LocalSocket, Sniffer, Utilization,
};
use pnet::datalink::{DataLinkReceiver, NetworkInterface};
use ratatui::backend::{Backend, CrosstermBackend};
use simplelog::WriteLogger;
use crate::cli::Opt;
const DISPLAY_DELTA: Duration = Duration::from_millis(1000);
fn main() -> anyhow::Result<()> {
let opts = Opt::parse();
// init logging
if let Some(ref log_path) = opts.log_to {
let log_file = File::options()
.write(true)
.create_new(true)
.open(log_path)?;
WriteLogger::init(
opts.verbosity.log_level_filter(),
Default::default(),
log_file,
)?;
}
let os_input = os::get_input(opts.interface.as_deref(), !opts.no_resolve, opts.dns_server)?;
if opts.raw {
let terminal_backend = RawTerminalBackend {};
start(terminal_backend, os_input, opts);
} else {
let Ok(()) = terminal::enable_raw_mode() else {
anyhow::bail!(
"Failed to get stdout: if you are trying to pipe 'bandwhich' you should use the --raw flag"
)
};
let mut stdout = std::io::stdout();
// Ignore enteralternatescreen error
let _ = crossterm::execute!(&mut stdout, terminal::EnterAlternateScreen);
let terminal_backend = CrosstermBackend::new(stdout);
start(terminal_backend, os_input, opts);
}
Ok(())
}
pub struct OpenSockets {
sockets_to_procs: HashMap<LocalSocket, String>,
}
pub struct OsInputOutput {
pub network_interfaces: Vec<NetworkInterface>,
pub network_frames: Vec<Box<dyn DataLinkReceiver>>,
pub get_open_sockets: fn() -> OpenSockets,
pub terminal_events: Box<dyn Iterator<Item = Event> + Send>,
pub dns_client: Option<dns::Client>,
pub write_to_stdout: Box<dyn FnMut(String) + Send>,
}
pub fn start<B>(terminal_backend: B, os_input: OsInputOutput, opts: Opt)
where
B: Backend + Send + 'static,
{
let running = Arc::new(AtomicBool::new(true));
let paused = Arc::new(AtomicBool::new(false));
let last_start_time = Arc::new(RwLock::new(Instant::now()));
let cumulative_time = Arc::new(RwLock::new(Duration::new(0, 0)));
let ui_offset = Arc::new(AtomicUsize::new(0));
let dns_shown = opts.show_dns;
let mut active_threads = vec![];
let terminal_events = os_input.terminal_events;
let get_open_sockets = os_input.get_open_sockets;
let mut write_to_stdout = os_input.write_to_stdout;
let mut dns_client = os_input.dns_client;
let raw_mode = opts.raw;
let network_utilization = Arc::new(Mutex::new(Utilization::new()));
let ui = Arc::new(Mutex::new(Ui::new(terminal_backend, opts.render_opts)));
let display_handler = thread::Builder::new()
.name("display_handler".to_string())
.spawn({
let running = running.clone();
let paused = paused.clone();
let ui_offset = ui_offset.clone();
let network_utilization = network_utilization.clone();
let last_start_time = last_start_time.clone();
let cumulative_time = cumulative_time.clone();
let ui = ui.clone();
move || {
while running.load(Ordering::Acquire) {
let render_start_time = Instant::now();
let utilization = { network_utilization.lock().unwrap().clone_and_reset() };
let OpenSockets { sockets_to_procs } = get_open_sockets();
let mut ip_to_host = IpTable::new();
if let Some(dns_client) = dns_client.as_mut() {
ip_to_host = dns_client.cache();
let unresolved_ips = utilization
.connections
.keys()
.filter(|conn| !ip_to_host.contains_key(&conn.remote_socket.ip))
.map(|conn| conn.remote_socket.ip)
.collect::<Vec<_>>();
dns_client.resolve(unresolved_ips);
}
{
let mut ui = ui.lock().unwrap();
let paused = paused.load(Ordering::SeqCst);
let ui_offset = ui_offset.load(Ordering::SeqCst);
if !paused {
ui.update_state(sockets_to_procs, utilization, ip_to_host);
}
let elapsed_time = elapsed_time(
*last_start_time.read().unwrap(),
*cumulative_time.read().unwrap(),
paused,
);
if raw_mode {
ui.output_text(&mut write_to_stdout);
} else {
ui.draw(paused, dns_shown, elapsed_time, ui_offset);
}
}
let render_duration = render_start_time.elapsed();
if render_duration < DISPLAY_DELTA {
park_timeout(DISPLAY_DELTA - render_duration);
}
}
if !raw_mode {
let mut ui = ui.lock().unwrap();
ui.end();
}
}
})
.unwrap();
let terminal_event_handler = thread::Builder::new()
.name("terminal_events_handler".to_string())
.spawn({
let running = running.clone();
let display_handler = display_handler.thread().clone();
move || {
for evt in terminal_events {
let mut ui = ui.lock().unwrap();
match evt {
Event::Resize(_x, _y) if !raw_mode => {
let paused = paused.load(Ordering::SeqCst);
ui.draw(
paused,
dns_shown,
elapsed_time(
*last_start_time.read().unwrap(),
*cumulative_time.read().unwrap(),
paused,
),
ui_offset.load(Ordering::SeqCst),
);
}
Event::Key(KeyEvent {
modifiers: KeyModifiers::CONTROL,
code: KeyCode::Char('c'),
kind: KeyEventKind::Press,
..
})
| Event::Key(KeyEvent {
modifiers: KeyModifiers::NONE,
code: KeyCode::Char('q'),
kind: KeyEventKind::Press,
..
}) => {
running.store(false, Ordering::Release);
display_handler.unpark();
match terminal::disable_raw_mode() {
Ok(_) => {}
Err(_) => println!("Error could not disable raw input"),
}
let mut stdout = std::io::stdout();
if crossterm::execute!(&mut stdout, terminal::LeaveAlternateScreen)
.is_err()
{
println!("Error could not leave alternte screen");
};
break;
}
Event::Key(KeyEvent {
modifiers: KeyModifiers::NONE,
code: KeyCode::Char(' '),
kind: KeyEventKind::Press,
..
}) => {
let restarting = paused.fetch_xor(true, Ordering::SeqCst);
if restarting {
*last_start_time.write().unwrap() = Instant::now();
} else {
let last_start_time_copy = *last_start_time.read().unwrap();
let current_cumulative_time_copy = *cumulative_time.read().unwrap();
let new_cumulative_time =
current_cumulative_time_copy + last_start_time_copy.elapsed();
*cumulative_time.write().unwrap() = new_cumulative_time;
}
display_handler.unpark();
}
Event::Key(KeyEvent {
modifiers: KeyModifiers::NONE,
code: KeyCode::Tab,
kind: KeyEventKind::Press,
..
}) => {
let paused = paused.load(Ordering::SeqCst);
let elapsed_time = elapsed_time(
*last_start_time.read().unwrap(),
*cumulative_time.read().unwrap(),
paused,
);
let table_count = ui.get_table_count();
let new = ui_offset.load(Ordering::SeqCst) + 1 % table_count;
ui_offset.store(new, Ordering::SeqCst);
ui.draw(paused, dns_shown, elapsed_time, new);
}
_ => (),
};
}
}
})
.unwrap();
active_threads.push(display_handler);
active_threads.push(terminal_event_handler);
let sniffer_threads = os_input
.network_interfaces
.into_iter()
.zip(os_input.network_frames)
.map(|(iface, frames)| {
let name = format!("sniffing_handler_{}", iface.name);
let running = running.clone();
let show_dns = opts.show_dns;
let network_utilization = network_utilization.clone();
thread::Builder::new()
.name(name)
.spawn(move || {
let mut sniffer = Sniffer::new(iface, frames, show_dns);
while running.load(Ordering::Acquire) {
if let Some(segment) = sniffer.next() {
network_utilization.lock().unwrap().update(segment);
}
}
})
.unwrap()
})
.collect::<Vec<_>>();
active_threads.extend(sniffer_threads);
for thread_handler in active_threads {
thread_handler.join().unwrap()
}
}