about summary refs log tree commit diff
path: root/src/main.rs
blob: defd70bb30167fc662758f367c39d518d99989f4 (plain)
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
use std::{
	error::Error,
	net::{Ipv4Addr, Shutdown},
	sync::mpsc::{self, Receiver, Sender, channel},
	thread::JoinHandle,
	time::{Duration, Instant},
};

use ethertype::EtherType;
use ippacket::{IpNextHeader, Ipv4Packet};
use layer3::{Tcp, Udp};
use pnet_datalink::{Channel, Config};
use scurvy::{Argument, Scurvy};

mod ethertype;
mod ippacket;
mod layer3;

fn main() -> Result<(), Box<dyn Error>> {
	let args = vec![
		Argument::new(&["interface", "iface"]).arg("dev"),
		Argument::new("ip").arg("addr"),
	];
	let scurvy = Scurvy::make(args);

	let interface_name = scurvy.get("interface").unwrap();
	let interface = match pnet_datalink::interfaces().iter().find(|i| i.name == interface_name) {
		None => {
			eprintln!("No interface found named '{interface_name}'");
			return Ok(());
		}
		Some(i) => i.clone(),
	};

	let ip_want: Ipv4Addr = scurvy.get("ip").unwrap().parse()?;

	let mut channel = match pnet_datalink::channel(&interface, Config::default())? {
		Channel::Ethernet(_tx, rx) => rx,
		_ => unimplemented!(),
	};

	let stat = stat_thread();

	let tx_clone = stat.tx.clone();
	std::thread::spawn(move || {
		std::thread::sleep(Duration::from_secs(30));
		tx_clone.send(Meow::Show).unwrap();
	});

	loop {
		let pkt = channel.next()?;

		let ethertype = EtherType::new(u16::from_be_bytes([pkt[12], pkt[13]]));
		let eth_payload = &pkt[14..];

		match ethertype {
			EtherType::IPv4 => {
				let ip = Ipv4Packet::new(eth_payload);
				let ip_payload = ip.get_payload();

				// 6 byte per MAC (x2), 2 byte ethertype, 2 byte crc
				let total_l2_len = ip.get_packet_len() + 18;

				match ip.get_next_header() {
					IpNextHeader::Tcp => {
						let tcp = Tcp::new(ip_payload);

						let tcp_tx = if ip.src == ip_want {
							true
						} else if ip.dst == ip_want {
							false
						} else {
							continue;
						};

						stat.tx.send(Meow::Tcp {
							tx: tcp_tx,
							src: tcp.source_port(),
							dst: tcp.destination_port(),
							len: total_l2_len,
						})?;
					}
					IpNextHeader::Udp => {
						let udp = Udp::new(ip_payload);

						let udp_tx = if ip.src == ip_want {
							true
						} else if ip.dst == ip_want {
							false
						} else {
							continue;
						};

						stat.tx.send(Meow::Udp {
							tx: udp_tx,
							src: udp.source_port(),
							dst: udp.destination_port(),
							len: total_l2_len,
						})?;
					}
					_ => (),
				}
			}
			_ => (),
		}
	}
}

struct StatHandle {
	hwnd: JoinHandle<()>,
	tx: Sender<Meow>,
}

enum Meow {
	Tcp {
		tx: bool,
		src: u16,
		dst: u16,
		len: usize,
	},
	Udp {
		tx: bool,
		src: u16,
		dst: u16,
		len: usize,
	},
	Show,
	Shutdown,
}

fn stat_thread() -> StatHandle {
	let (tx, rx) = channel();

	let hwnd = std::thread::spawn(|| stat(rx));

	StatHandle { hwnd, tx }
}

fn stat(rx: Receiver<Meow>) {
	let mut tcp_tx = vec![0; u16::MAX as usize];
	let mut tcp_rx = vec![0; u16::MAX as usize];

	let mut last_print = Instant::now();
	loop {
		if last_print.elapsed() > Duration::from_secs(10) {
			let http_s = tcp_rx[80] + tcp_rx[443];
			let http_s_kb = http_s / 1000;

			let http_s_tx = tcp_tx[80] + tcp_tx[443];
			let http_s_tx_kb = http_s_tx / 1000;

			println!("HTTP(S) rx {}kB // tx {}kB", http_s_kb, http_s_tx_kb);

			last_print = Instant::now();
		}

		match rx.recv() {
			Err(_e) => {
				eprintln!("error receiving! breaking from loop");
				break;
			}
			Ok(Meow::Show) => {
				if last_print.elapsed() > Duration::from_secs(30) {
					println!("Activated by Meow::Show");
				}
			}
			Ok(Meow::Shutdown) => {
				eprintln!("got shutdown! breaking from loop");
				break;
			}
			Ok(Meow::Tcp {
				tx: tcp_tx_flag,
				src,
				dst,
				len,
			}) => {
				if tcp_tx_flag {
					tcp_tx[src as usize] += len;
				} else {
					tcp_rx[dst as usize] += len;
				}
			}
			_ => (),
		}
	}
}