Skip to content

Commit

Permalink
Fixes suggested by Chleba
Browse files Browse the repository at this point in the history
  • Loading branch information
zanderlewis committed Oct 19, 2024
1 parent 8b91326 commit 10e77e5
Show file tree
Hide file tree
Showing 5 changed files with 226 additions and 226 deletions.
48 changes: 24 additions & 24 deletions src/components/discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ impl Discovery {
if let Some(active_interface_mac) = active_interface.mac {
let ipv4 = active_interface.ips.iter().find(|f| f.is_ipv4()).unwrap();
let source_ip: Ipv4Addr = ipv4.ip().to_string().parse().unwrap();

let (mut sender, _) =
match pnet::datalink::channel(active_interface, Default::default()) {
Ok(Channel::Ethernet(tx, rx)) => (tx, rx),
Expand All @@ -153,17 +153,17 @@ impl Discovery {
return;
}
};

let mut ethernet_buffer = [0u8; 42];
let mut ethernet_packet = MutableEthernetPacket::new(&mut ethernet_buffer).unwrap();

ethernet_packet.set_destination(MacAddr::broadcast());
ethernet_packet.set_source(active_interface_mac);
ethernet_packet.set_ethertype(EtherTypes::Arp);

let mut arp_buffer = [0u8; 28];
let mut arp_packet = MutableArpPacket::new(&mut arp_buffer).unwrap();

arp_packet.set_hardware_type(ArpHardwareTypes::Ethernet);
arp_packet.set_protocol_type(EtherTypes::Ipv4);
arp_packet.set_hw_addr_len(6);
Expand All @@ -173,9 +173,9 @@ impl Discovery {
arp_packet.set_sender_proto_addr(source_ip);
arp_packet.set_target_hw_addr(MacAddr::zero());
arp_packet.set_target_proto_addr(target_ip);

ethernet_packet.set_payload(arp_packet.packet_mut());

sender
.send_to(ethernet_packet.packet(), None)
.unwrap()
Expand All @@ -186,7 +186,7 @@ impl Discovery {

fn scan(&mut self) {
self.reset_scan();

if let Some(cidr) = self.cidr {
self.is_scanning = true;
let tx = self.action_tx.as_ref().unwrap().clone();
Expand All @@ -206,7 +206,7 @@ impl Discovery {
.pinger(IpAddr::V4(ip), PingIdentifier(random()))
.await;
pinger.timeout(Duration::from_secs(2));

match pinger.ping(PingSequence(2), &payload).await {
Ok((IcmpPacket::V4(packet), dur)) => {
tx.send(Action::PingIp(packet.get_real_dest().to_string()))
Expand All @@ -224,7 +224,7 @@ impl Discovery {
task::spawn(closure())
})
.collect();

let _ = join_all(tasks).await;
}
});
Expand Down Expand Up @@ -255,7 +255,7 @@ impl Discovery {
let tx = self.action_tx.as_ref().unwrap();
let ipv4: Ipv4Addr = ip.parse().unwrap();
self.send_arp(ipv4);

if let Some(n) = self.scanned_ips.iter_mut().find(|item| item.ip == ip) {
let hip: IpAddr = ip.parse().unwrap();
let host = lookup_addr(&hip).unwrap_or_default();
Expand All @@ -270,14 +270,14 @@ impl Discovery {
hostname: host,
vendor: String::new(),
});

self.scanned_ips.sort_by(|a, b| {
let a_ip: Ipv4Addr = a.ip.parse::<Ipv4Addr>().unwrap();
let b_ip: Ipv4Addr = b.ip.parse::<Ipv4Addr>().unwrap();
a_ip.partial_cmp(&b_ip).unwrap()
});
}

self.set_scrollbar_height();
}

Expand Down Expand Up @@ -352,7 +352,7 @@ impl Discovery {
Some(c) => count_ipv4_net_length(c.network_length() as u32),
None => 0,
};

for sip in scanned_ips {
let ip = &sip.ip;
rows.push(Row::new(vec![
Expand All @@ -365,7 +365,7 @@ impl Discovery {
Cell::from(sip.vendor.as_str().yellow()),
]));
}

let table = Table::new(
rows,
[
Expand Down Expand Up @@ -653,15 +653,15 @@ impl Component for Discovery {
fn draw(&mut self, f: &mut Frame<'_>, area: Rect) -> Result<()> {
if self.active_tab == TabsEnum::Discovery {
let layout = get_vertical_layout(area);

// -- TABLE
let mut table_rect = layout.bottom;
table_rect.y += 1;
table_rect.height -= 1;

let table = Self::make_table(&self.scanned_ips, self.cidr, self.ip_num);
f.render_stateful_widget(table, table_rect, &mut self.table_state);

// -- SCROLLBAR
let scrollbar = Self::make_scrollbar();
let mut scroll_rect = table_rect;
Expand All @@ -675,14 +675,14 @@ impl Component for Discovery {
}),
&mut self.scrollbar_state,
);

// -- ERROR
if self.cidr_error {
let error_rect = Rect::new(table_rect.width - (19 + 41), table_rect.y + 1, 18, 3);
let block = self.make_error();
f.render_widget(block, error_rect);
}

// -- INPUT
let input_size: u16 = INPUT_SIZE as u16;
let input_rect = Rect::new(
Expand All @@ -691,15 +691,15 @@ impl Component for Discovery {
input_size,
3,
);

// -- INPUT_SIZE - 3 is offset for border + 1char for cursor
let scroll = self.input.visual_scroll(INPUT_SIZE - 3);
let mut block = self.make_input(scroll);
if self.is_scanning {
block = block.add_modifier(Modifier::DIM);
}
f.render_widget(block, input_rect);

// -- cursor
match self.mode {
Mode::Input => {
Expand All @@ -712,15 +712,15 @@ impl Component for Discovery {
}
Mode::Normal => {}
}

// -- THROBBER
if self.is_scanning {
let throbber = self.make_spinner();
let throbber_rect = Rect::new(input_rect.x + 1, input_rect.y, 12, 1);
f.render_widget(throbber, throbber_rect);
}
}

Ok(())
}
}
12 changes: 6 additions & 6 deletions src/components/packetdump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,11 +426,11 @@ impl PacketDump {
return;
}
};

loop {
let mut buf: [u8; 1600] = [0u8; 1600];
let mut fake_ethernet_frame = MutableEthernetPacket::new(&mut buf[..]).unwrap();

match receiver.next() {
Ok(packet) => {
let payload_offset;
Expand Down Expand Up @@ -489,9 +489,9 @@ impl PacketDump {

fn start_loop(&mut self) {
if self.loop_thread.is_none() {
let tx = self.action_tx.take().unwrap();
let interface = self.active_interface.take().unwrap();
let paused = Arc::clone(&self.dump_paused);
let tx = self.action_tx.clone().unwrap();
let interface = self.active_interface.clone().unwrap();
let paused = self.dump_paused.clone();
let t_handle = thread::spawn(move || {
Self::t_logic(tx, interface, paused);
});
Expand All @@ -515,7 +515,7 @@ impl PacketDump {

pub fn get_arp_packages(&self) -> Vec<(DateTime<Local>, PacketsInfoTypesEnum)> {
let a = &self.arp_packets.get_vec().to_vec();
a.to_vec()
a.clone()
}

pub fn clone_array_by_packet_type(
Expand Down
63 changes: 37 additions & 26 deletions src/components/wifi_scan.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use chrono::{DateTime, Local, Timelike};
use config::Source;
use std::collections::HashMap;
use std::time::Instant;
use tokio::sync::mpsc::UnboundedSender;
use tokio_wifiscanner::Wifi;
Expand Down Expand Up @@ -172,44 +171,56 @@ impl WifiScan {
let networks = tokio_wifiscanner::scan().await;
match networks {
Ok(nets) => {
let mut wifi_nets: Vec<WifiInfo> = Vec::new();
let now = Local::now();
let wifi_nets: Vec<WifiInfo> = nets.iter().map(|w| {
WifiInfo {
time: now,
ssid: w.ssid.to_string(),
channel: w.channel.parse::<u8>().unwrap_or(0),
signal: w.signal_level.parse::<f32>().unwrap_or(-100.00),
mac: w.mac.to_string(),
color: COLORS_NAMES[nets.len() % COLORS_NAMES.len()],
for w in nets {
if let Some(n) = wifi_nets.iter_mut().find(|item| item.ssid == w.ssid) {
let signal: f32 = w.signal_level.parse().unwrap_or(-100.00);
if n.signal < signal {
n.signal = signal;
n.mac = w.mac;
let channel = w.channel.parse::<u8>().unwrap_or(0);
n.channel = channel;
}
} else {
wifi_nets.push(WifiInfo {
time: now,
ssid: w.ssid,
channel: w.channel.parse::<u8>().unwrap_or(0),
signal: w.signal_level.parse::<f32>().unwrap_or(-100.00),
mac: w.mac,
color: COLORS_NAMES[wifi_nets.len() % COLORS_NAMES.len()],
});
}
}).collect();
}

if tx.send(Action::Scan(wifi_nets)).is_err() {
// Handle error
let t_send = tx.send(Action::Scan(wifi_nets));
match t_send {
Ok(n) => (),
Err(e) => (),
}
}
Err(_) => {
// Handle error
}
}
Err(_e) => (),
};
});
}

fn parse_networks_data(&mut self, nets: &Vec<WifiInfo>) {
let mut wifi_map: HashMap<String, WifiInfo> = self.wifis.drain(..)
.map(|w| (w.ssid.clone(), w))
.collect();

// -- clear signal values
self.wifis.iter_mut().for_each(|item| {
item.signal = 0.0;
});
// -- add or update wifi info
for w in nets {
if let Some(existing) = wifi_map.get_mut(&w.ssid) {
existing.copy_values(w.clone());
if let Some(n) = self.wifis.iter_mut().find(|item| item.ssid == w.ssid) {
n.copy_values(w.clone());
} else {
wifi_map.insert(w.ssid.clone(), w.clone());
self.wifis.push(w.clone());
}
}

self.wifis = wifi_map.into_values().collect();
self.wifis.sort_by(|a, b| b.signal.partial_cmp(&a.signal).unwrap());
// -- sort wifi networks by it's signal strength
self.wifis
.sort_by(|a, b| b.signal.partial_cmp(&a.signal).unwrap());
}

fn app_tick(&mut self) -> Result<()> {
Expand Down
70 changes: 35 additions & 35 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,47 +37,47 @@ pub struct Config {

impl Config {
pub fn new() -> Result<Self, config::ConfigError> {
let default_config: Config = json5::from_str(CONFIG).unwrap();
let data_dir = crate::utils::get_data_dir();
let config_dir = crate::utils::get_config_dir();
let mut builder = config::Config::builder()
.set_default("_data_dir", data_dir.to_str().unwrap())?
.set_default("_config_dir", config_dir.to_str().unwrap())?;

let config_files = [
("config.json5", config::FileFormat::Json5),
("config.json", config::FileFormat::Json),
("config.yaml", config::FileFormat::Yaml),
("config.toml", config::FileFormat::Toml),
("config.ini", config::FileFormat::Ini),
];
let mut found_config = false;
for (file, format) in &config_files {
builder = builder.add_source(config::File::from(config_dir.join(file)).format(*format).required(false));
if config_dir.join(file).exists() {
found_config = true
}
}
if !found_config {
log::error!("No configuration file found. Application may not behave as expected");
let default_config: Config = json5::from_str(CONFIG).unwrap();
let data_dir = crate::utils::get_data_dir();
let config_dir = crate::utils::get_config_dir();
let mut builder = config::Config::builder()
.set_default("_data_dir", data_dir.to_str().unwrap())?
.set_default("_config_dir", config_dir.to_str().unwrap())?;

let config_files = [
("config.json5", config::FileFormat::Json5),
("config.json", config::FileFormat::Json),
("config.yaml", config::FileFormat::Yaml),
("config.toml", config::FileFormat::Toml),
("config.ini", config::FileFormat::Ini),
];
let mut found_config = false;
for (file, format) in &config_files {
builder = builder.add_source(config::File::from(config_dir.join(file)).format(*format).required(false));
if config_dir.join(file).exists() {
found_config = true
}
}
if !found_config {
log::error!("No configuration file found. Application may not behave as expected");
}

let mut cfg: Self = builder.build()?.try_deserialize()?;
let mut cfg: Self = builder.build()?.try_deserialize()?;

for (mode, default_bindings) in &(*default_config.keybindings) {
let user_bindings = cfg.keybindings.entry(*mode).or_default();
for (key, cmd) in default_bindings {
user_bindings.entry(key.to_owned()).or_insert_with(|| cmd.to_owned());
}
for (mode, default_bindings) in default_config.keybindings.iter() {
let user_bindings = cfg.keybindings.entry(*mode).or_default();
for (key, cmd) in default_bindings.iter() {
user_bindings.entry(key.clone()).or_insert_with(|| cmd.clone());
}
for (mode, default_styles) in &(*default_config.styles) {
let user_styles = cfg.styles.entry(*mode).or_default();
for (style_key, style) in default_styles {
user_styles.entry(style_key.to_owned()).or_insert_with(|| style.to_owned());
}
}
for (mode, default_styles) in default_config.styles.iter() {
let user_styles = cfg.styles.entry(*mode).or_default();
for (style_key, style) in default_styles.iter() {
user_styles.entry(style_key.clone()).or_insert_with(|| style.clone());
}
}

Ok(cfg)
Ok(cfg)
}
}

Expand Down
Loading

0 comments on commit 10e77e5

Please sign in to comment.