Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add support for nmcli #2

Merged
merged 3 commits into from
Jul 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "wifiscanner"
version = "0.5.1"
version = "0.6.0"
authors = ["Mark Sta Ana <[email protected]>"]
description = "List WiFi hotspots in your area"
repository = "https://github.com/booyaa/wifiscanner"
Expand Down
98 changes: 74 additions & 24 deletions src/sys/linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,64 @@
use std::env;
use std::process::Command;

/// Returns a list of WiFi hotspots in your area - (Linux) uses `iw`
/// Returns a list of WiFi hotspots in your area - (Linux). uses `nmcli` or `iw`.
pub(crate) fn scan() -> Result<Vec<Wifi>> {
scan_nm().and_then(|_| scan_iw())
}

/// Returns a list of WiFi hotspots in your area - (Linux) uses `nmcli`
fn scan_nm() -> Result<Vec<Wifi>> {
let output = Command::new("nmcli")
.arg("--color")
.arg("no")
.arg("--terse")
.arg("-f")
.arg("ssid,chan,signal,security,bssid")
.arg("dev")
.arg("wifi")
.arg("list")
.output()
.map_err(|_| Error::CommandNotFound)?;

let data = String::from_utf8_lossy(&output.stdout);

let mut result = vec![];
for line in data.lines() {
let mut wifi = Wifi::default();
let mut fs = line.splitn(5, ':');
if let Some(ssid) = fs.next() {
wifi.ssid = ssid.to_string();
} else {
continue;
}
if let Some(channel) = fs.next() {
wifi.channel = channel.to_string();
} else {
continue;
}
if let Some(signal_level) = fs.next() {
wifi.signal_level = signal_level.to_string();
} else {
continue;
}
if let Some(security) = fs.next() {
wifi.security = security.to_string();
} else {
continue;
}
if let Some(mac) = fs.next() {
wifi.mac = mac.replace(r"\:", ":").to_string();
} else {
continue;
}
result.push(wifi);
}
Ok(result)
}

/// Returns a list of WiFi hotspots in your area - (Linux) uses `iw`
fn scan_iw() -> Result<Vec<Wifi>> {
const PATH_ENV: &'static str = "PATH";

Check warning on line 62 in src/sys/linux.rs

View workflow job for this annotation

GitHub Actions / Check/Rustfmt/Clippy

constants have by default a `'static` lifetime

Check warning on line 62 in src/sys/linux.rs

View workflow job for this annotation

GitHub Actions / Check/Rustfmt/Clippy

constants have by default a `'static` lifetime
let path_system = "/usr/sbin:/sbin";
let path = env::var_os(PATH_ENV).map_or(path_system.to_string(), |v| {
format!("{}:{}", v.to_string_lossy().into_owned(), path_system)
Expand Down Expand Up @@ -36,12 +91,12 @@
}

fn parse_iw_dev(interfaces: &str) -> Result<String> {
interfaces

Check warning on line 94 in src/sys/linux.rs

View workflow job for this annotation

GitHub Actions / Check/Rustfmt/Clippy

called `.nth(0)` on a `std::iter::Iterator`, when `.next()` is equivalent

Check warning on line 94 in src/sys/linux.rs

View workflow job for this annotation

GitHub Actions / Check/Rustfmt/Clippy

called `.nth(0)` on a `std::iter::Iterator`, when `.next()` is equivalent
.split("\tInterface ")
.take(2)
.last()
.ok_or(Error::NoValue)?
.split("\n")

Check warning on line 99 in src/sys/linux.rs

View workflow job for this annotation

GitHub Actions / Check/Rustfmt/Clippy

single-character string constant used as pattern

Check warning on line 99 in src/sys/linux.rs

View workflow job for this annotation

GitHub Actions / Check/Rustfmt/Clippy

single-character string constant used as pattern
.nth(0)
.ok_or(Error::NoValue)
.map(|text| text.to_string())
Expand All @@ -50,7 +105,7 @@
fn parse_iw_dev_scan(network_list: &str) -> Result<Vec<Wifi>> {
let mut wifis: Vec<Wifi> = Vec::new();
let mut wifi = Wifi::default();
for line in network_list.split("\n") {
for line in network_list.lines() {
if let Ok(mac) = extract_value(line, "BSS ", Some("(")) {
if !wifi.mac.is_empty()
&& !wifi.signal_level.is_empty()
Expand Down Expand Up @@ -103,20 +158,23 @@
use std::io::Read;
use std::path::PathBuf;

#[test]
fn test_nmcli() {
if let Err(e) = Command::new("nmcli").arg("--version").output() {
eprintln!("nmlci is not found: {e}");
return;
}
let wifis = scan_nm().expect("failed to scan");
println!("Wifis: {wifis:?}");
}

#[test]
fn should_parse_iw_dev() {
let expected = "wlp2s0";

// FIXME: should be a better way to create test fixtures
let mut path = PathBuf::new();
path.push("tests");
path.push("fixtures");
path.push("iw");
path.push("iw_dev_01.txt");

let file_path = path.as_os_str();

let mut file = File::open(&file_path).unwrap();
let path = PathBuf::from("tests/fixtures/iw/iw_dev_01.txt");
let mut file = File::open(&path).unwrap();

let mut filestr = String::new();
let _ = file.read_to_string(&mut filestr).unwrap();
Expand All @@ -133,33 +191,25 @@
ssid: "hello".to_string(),
channel: "10".to_string(),
signal_level: "-67.00".to_string(),
security: "".to_string(),
security: "PSK".to_string(),
});

expected.push(Wifi {
mac: "66:77:88:99:aa:bb".to_string(),
ssid: "hello-world-foo-bar".to_string(),
channel: "8".to_string(),
signal_level: "-89.00".to_string(),
security: "".to_string(),
security: "PSK".to_string(),
});

// FIXME: should be a better way to create test fixtures
let mut path = PathBuf::new();
path.push("tests");
path.push("fixtures");
path.push("iw");
path.push("iw_dev_scan_01.txt");

let file_path = path.as_os_str();

let mut file = File::open(&file_path).unwrap();

let path = PathBuf::from("tests/fixtures/iw/iw_dev_scan_01.txt");
let mut file = File::open(&path).unwrap();
let mut filestr = String::new();
let _ = file.read_to_string(&mut filestr).unwrap();

let result = parse_iw_dev_scan(&filestr).unwrap();
assert_eq!(expected[0], result[0]);
assert_eq!(expected[1], result[5]);
assert_eq!(expected[1], result[4]);
}
}
Loading