1395 lines
49 KiB
Rust
1395 lines
49 KiB
Rust
use std::collections::{HashMap, HashSet};
|
|
use std::fs;
|
|
use std::io::Write;
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::{Command, Stdio};
|
|
use std::thread;
|
|
use std::time::Duration;
|
|
|
|
const RUN: &str = "/run/mifipanel";
|
|
const CTRL: &str = "/run/hostapd";
|
|
|
|
pub struct Hw {
|
|
pub iface: String,
|
|
pub bands: Vec<String>,
|
|
}
|
|
|
|
pub struct Ap {
|
|
pub iface: String,
|
|
pub band: String,
|
|
pub enabled: bool,
|
|
pub ssid: String,
|
|
pub password: String,
|
|
pub security: String,
|
|
pub channel: u32,
|
|
pub hidden: bool,
|
|
pub gateway: String,
|
|
pub prefix: u8,
|
|
pub mask: String,
|
|
pub dhcp_start: String,
|
|
pub dhcp_end: String,
|
|
pub cidr: String,
|
|
}
|
|
|
|
/// 随热点一起下发、但不属于某一张网卡的设置。名单和地址都已经校验过。
|
|
#[derive(Clone, Debug)]
|
|
pub struct Extras {
|
|
pub max_sta: u32,
|
|
pub accept: bool,
|
|
pub whitelist: Vec<String>,
|
|
pub reservations: Vec<(String, String)>,
|
|
pub dns: Vec<String>,
|
|
pub ttl: u8,
|
|
}
|
|
|
|
impl Default for Extras {
|
|
fn default() -> Self {
|
|
Self {
|
|
max_sta: 16,
|
|
accept: false,
|
|
whitelist: Vec::new(),
|
|
reservations: Vec::new(),
|
|
dns: Vec::new(),
|
|
ttl: 0,
|
|
}
|
|
}
|
|
}
|
|
|
|
struct Route {
|
|
dev: String,
|
|
via: String,
|
|
}
|
|
|
|
struct Plan {
|
|
mode: String,
|
|
dev: String,
|
|
via: String,
|
|
}
|
|
|
|
struct PhyInfo {
|
|
bands: HashMap<String, Vec<String>>,
|
|
blocked: HashSet<String>,
|
|
ok: bool,
|
|
}
|
|
|
|
pub fn hardware() -> Vec<Hw> {
|
|
let ifaces = wifi_ifaces();
|
|
if ifaces.is_empty() {
|
|
return Vec::new();
|
|
}
|
|
let info = phy_info();
|
|
let mut out = Vec::new();
|
|
for iface in ifaces {
|
|
if info.ok && info.blocked.contains(&iface) {
|
|
continue;
|
|
}
|
|
let mut bands = info.bands.get(&iface).cloned().unwrap_or_else(|| vec!["2.4".into()]);
|
|
if bands.is_empty() {
|
|
bands.push("2.4".into());
|
|
}
|
|
sort_bands(&mut bands);
|
|
out.push(Hw { iface, bands });
|
|
}
|
|
out
|
|
}
|
|
|
|
pub fn ensure_daemon() -> Result<(), String> {
|
|
if hostapd_installed() {
|
|
let _ = command("systemctl", &["mask".into(), "--now".into(), "hostapd.service".into()]);
|
|
return Ok(());
|
|
}
|
|
let Some(deb) = offline_debs().into_iter().find(|path| path.exists()) else {
|
|
return Err("error.wifi.hostapd".into());
|
|
};
|
|
let output = Command::new("dpkg").args(["-i", &deb.to_string_lossy()]).env("LANG", "C").output().map_err(|_| "error.wifi.hostapd".to_string())?;
|
|
if !hostapd_installed() {
|
|
eprintln!("{}", redact(&String::from_utf8_lossy(&output.stderr)));
|
|
return Err("error.wifi.hostapd".into());
|
|
}
|
|
let _ = command("systemctl", &["mask".into(), "--now".into(), "hostapd.service".into()]);
|
|
eprintln!("已从离线包安装 hostapd");
|
|
Ok(())
|
|
}
|
|
|
|
pub fn apply(root: &Path, aps: &[Ap], egress: &str, blacklist: &[String], extras: &Extras) -> Result<(), String> {
|
|
let ifaces = aps.iter().map(|ap| ap.iface.clone()).collect::<Vec<_>>();
|
|
stop_services();
|
|
write_deny(root, blacklist)?;
|
|
write_accept(root, &extras.whitelist)?;
|
|
let enabled = aps.iter().filter(|ap| ap.enabled && valid_dev(&ap.iface)).collect::<Vec<_>>();
|
|
if enabled.is_empty() {
|
|
down_nm();
|
|
release_ifaces(&ifaces);
|
|
clear_routes();
|
|
clear_nat();
|
|
clear_legacy_nft();
|
|
clear_ttl();
|
|
return sync_usb(root, false);
|
|
}
|
|
if !hostapd_installed() {
|
|
return Err("error.wifi.hostapd".into());
|
|
}
|
|
if !Path::new("/usr/sbin/dnsmasq").exists() && command("dnsmasq", &["--version".into()]).is_err() {
|
|
return Err("error.wifi.dhcp".into());
|
|
}
|
|
if let Err(err) = sync_usb(root, egress == "nic") {
|
|
let _ = sync_usb(root, false);
|
|
return Err(err);
|
|
}
|
|
down_nm();
|
|
for ap in aps {
|
|
let managed = if ap.enabled { "no" } else { "yes" };
|
|
let _ = command("nmcli", &["device".into(), "set".into(), ap.iface.clone(), "managed".into(), managed.into()]);
|
|
}
|
|
clear_legacy_nft();
|
|
if let Err(err) = bring_up(root, &enabled, egress, extras) {
|
|
stop_services();
|
|
release_ifaces(&ifaces);
|
|
clear_ttl();
|
|
if egress == "nic" {
|
|
let _ = sync_usb(root, false);
|
|
}
|
|
return Err(err);
|
|
}
|
|
let cidr = enabled.first().map(|ap| ap.cidr.as_str()).unwrap_or("");
|
|
sync_ttl(extras.ttl, cidr);
|
|
Ok(())
|
|
}
|
|
|
|
pub fn refresh(root: &Path, aps: &[Ap], egress: &str, extras: &Extras) -> Result<(), String> {
|
|
let enabled = aps.iter().filter(|ap| ap.enabled && valid_dev(&ap.iface)).collect::<Vec<_>>();
|
|
if enabled.is_empty() {
|
|
clear_ttl();
|
|
return Ok(());
|
|
}
|
|
sync_usb(root, egress == "nic")?;
|
|
let cidrs = lan_cidrs(&enabled);
|
|
let plan = route_plan(egress);
|
|
if install_routes(&plan, &cidrs)? {
|
|
start_dhcp(&enabled, &plan, extras)?;
|
|
install_nat(&plan, &enabled, &cidrs);
|
|
}
|
|
let cidr = enabled.first().map(|ap| ap.cidr.as_str()).unwrap_or("");
|
|
sync_ttl(extras.ttl, cidr);
|
|
Ok(())
|
|
}
|
|
|
|
pub fn reload_dhcp(aps: &[Ap], egress: &str, extras: &Extras) -> Result<(), String> {
|
|
let enabled = aps.iter().filter(|ap| ap.enabled && valid_dev(&ap.iface)).collect::<Vec<_>>();
|
|
if enabled.is_empty() {
|
|
return Ok(());
|
|
}
|
|
let plan = route_plan(egress);
|
|
start_dhcp(&enabled, &plan, extras)
|
|
}
|
|
|
|
pub fn dhcp_running() -> bool {
|
|
pid_alive(&run_path("dnsmasq.pid"))
|
|
}
|
|
|
|
pub fn controls(iface: &str) -> bool {
|
|
pid_alive(&pid_path(iface))
|
|
}
|
|
|
|
pub fn stations(iface: &str) -> String {
|
|
command(hostapd_cli(), &["-p".into(), CTRL.into(), "-i".into(), iface.into(), "all_sta".into()]).unwrap_or_default()
|
|
}
|
|
|
|
pub fn kick(iface: &str, mac: &str) -> Result<(), String> {
|
|
let text = command(hostapd_cli(), &["-p".into(), CTRL.into(), "-i".into(), iface.into(), "deauthenticate".into(), mac.into()])?;
|
|
if text.to_ascii_lowercase().contains("fail") {
|
|
return Err("error.wifi.kick".into());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn deny_mac(iface: &str, mac: &str, deny: bool) -> Result<(), String> {
|
|
let action = if deny { "ADD_MAC" } else { "DEL_MAC" };
|
|
let text = command(hostapd_cli(), &["-p".into(), CTRL.into(), "-i".into(), iface.into(), "DENY_ACL".into(), action.into(), mac.into()])?;
|
|
if text.to_ascii_lowercase().contains("fail") {
|
|
return Err("error.wifi.fail".into());
|
|
}
|
|
if deny {
|
|
let _ = kick(iface, mac);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn write_deny(root: &Path, blacklist: &[String]) -> Result<(), String> {
|
|
write_mac_file(root, "hostapd.deny", blacklist)
|
|
}
|
|
|
|
pub fn write_accept(root: &Path, whitelist: &[String]) -> Result<(), String> {
|
|
write_mac_file(root, "hostapd.accept", whitelist)
|
|
}
|
|
|
|
fn write_mac_file(root: &Path, name: &str, list: &[String]) -> Result<(), String> {
|
|
fs::create_dir_all(root).map_err(|err| err.to_string())?;
|
|
let path = root.join(name);
|
|
let mut text = String::new();
|
|
for mac in list {
|
|
if mac_ok(mac) {
|
|
text.push_str(mac);
|
|
text.push('\n');
|
|
}
|
|
}
|
|
crate::store::write_atomic(&path, text.as_bytes()).map_err(|err| err.to_string())?;
|
|
set_mode(&path, 0o644);
|
|
Ok(())
|
|
}
|
|
|
|
pub fn accept_mac(iface: &str, mac: &str, add: bool) -> Result<(), String> {
|
|
if !mac_ok(mac) {
|
|
return Err("error.wifi.mac".into());
|
|
}
|
|
let action = if add { "ADD_MAC" } else { "DEL_MAC" };
|
|
let text = command(hostapd_cli(), &["-p".into(), CTRL.into(), "-i".into(), iface.into(), "ACCEPT_ACL".into(), action.into(), mac.into()])?;
|
|
if text.to_ascii_lowercase().contains("fail") {
|
|
return Err("error.wifi.fail".into());
|
|
}
|
|
if !add {
|
|
let _ = kick(iface, mac);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn bring_up(root: &Path, enabled: &[&Ap], egress: &str, extras: &Extras) -> Result<(), String> {
|
|
fs::create_dir_all(RUN).map_err(|err| err.to_string())?;
|
|
let _ = fs::create_dir_all(CTRL);
|
|
let deny = root.join("hostapd.deny");
|
|
if !deny.exists() {
|
|
write_deny(root, &[])?;
|
|
}
|
|
let accept = root.join("hostapd.accept");
|
|
if !accept.exists() {
|
|
write_accept(root, &extras.whitelist)?;
|
|
}
|
|
let deny_path = deny.to_string_lossy().to_string();
|
|
let accept_path = accept.to_string_lossy().to_string();
|
|
let mut bridged = ensure_bridge();
|
|
if start_all(enabled, &deny_path, &accept_path, extras, bridged).is_err() {
|
|
stop_services();
|
|
if bridged {
|
|
eprintln!("桥接热点失败,改为直接使用无线网卡");
|
|
bridged = false;
|
|
}
|
|
start_all(enabled, &deny_path, &accept_path, extras, false)?;
|
|
}
|
|
add_lan(enabled, bridged)?;
|
|
let _ = fs::remove_file(run_path("route.plan"));
|
|
let plan = route_plan(egress);
|
|
let cidrs = lan_cidrs(enabled);
|
|
install_routes(&plan, &cidrs)?;
|
|
start_dhcp(enabled, &plan, extras)?;
|
|
install_nat(&plan, enabled, &cidrs);
|
|
Ok(())
|
|
}
|
|
|
|
fn ensure_bridge() -> bool {
|
|
if Path::new("/sys/class/net/br-lan").exists() {
|
|
let _ = command("ip", &["link".into(), "set".into(), "br-lan".into(), "up".into()]);
|
|
return true;
|
|
}
|
|
if command("ip", &["link".into(), "add".into(), "name".into(), "br-lan".into(), "type".into(), "bridge".into()]).is_err() {
|
|
return false;
|
|
}
|
|
let _ = command("ip", &["link".into(), "set".into(), "br-lan".into(), "up".into()]);
|
|
Path::new("/sys/class/net/br-lan").exists()
|
|
}
|
|
|
|
fn start_all(enabled: &[&Ap], deny: &str, accept: &str, extras: &Extras, bridged: bool) -> Result<(), String> {
|
|
for ap in enabled {
|
|
let conf = run_path(&format!("hostapd-{}.conf", ap.iface));
|
|
let bridge = if bridged { "br-lan" } else { "" };
|
|
let text = config_text(&ap.iface, &ap.band, &ap.ssid, &ap.security, &ap.password, ap.hidden, ap.channel, deny, bridge, accept, extras.accept, extras.max_sta);
|
|
fs::write(&conf, text).map_err(|err| err.to_string())?;
|
|
set_mode(&conf, 0o600);
|
|
let pid = pid_path(&ap.iface);
|
|
let output = Command::new(hostapd_bin())
|
|
.args(["-B", "-P", &pid.to_string_lossy(), &conf.to_string_lossy()])
|
|
.env("LANG", "C")
|
|
.output()
|
|
.map_err(|_| "error.wifi.fail".to_string())?;
|
|
if !output.status.success() {
|
|
eprintln!("hostapd: {}", redact(&String::from_utf8_lossy(&output.stderr)));
|
|
let extra = redact(&String::from_utf8_lossy(&output.stdout));
|
|
if !extra.trim().is_empty() {
|
|
eprintln!("hostapd: {extra}");
|
|
}
|
|
return Err("error.wifi.fail".into());
|
|
}
|
|
}
|
|
thread::sleep(Duration::from_millis(300));
|
|
for ap in enabled {
|
|
if !pid_alive(&pid_path(&ap.iface)) {
|
|
eprintln!("hostapd 没有保持运行");
|
|
return Err("error.wifi.fail".into());
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn add_lan(enabled: &[&Ap], bridged: bool) -> Result<(), String> {
|
|
let Some(ap) = enabled.first() else { return Ok(()) };
|
|
if !safe_ip(&ap.gateway) {
|
|
return Err("error.wifi.lan".into());
|
|
}
|
|
let dev = if bridged { "br-lan" } else { ap.iface.as_str() };
|
|
if bridged {
|
|
for item in enabled {
|
|
drop_addrs(&item.iface);
|
|
}
|
|
}
|
|
let _ = command("ip", &["link".into(), "set".into(), dev.into(), "up".into()]);
|
|
command("ip", &["addr".into(), "replace".into(), format!("{}/{}", ap.gateway, ap.prefix), "dev".into(), dev.into()]).map(|_| ())
|
|
}
|
|
|
|
fn start_dhcp(enabled: &[&Ap], plan: &Plan, extras: &Extras) -> Result<(), String> {
|
|
let conf_path = run_path("dnsmasq.conf");
|
|
let text = dhcp_conf(enabled, plan, extras);
|
|
let previous = fs::read_to_string(&conf_path).unwrap_or_default();
|
|
if previous == text && pid_alive(&run_path("dnsmasq.pid")) {
|
|
return Ok(());
|
|
}
|
|
fs::create_dir_all(RUN).map_err(|err| err.to_string())?;
|
|
fs::write(&conf_path, &text).map_err(|err| err.to_string())?;
|
|
stop_pid(&run_path("dnsmasq.pid"));
|
|
let output = Command::new(dnsmasq_bin()).arg(format!("--conf-file={}", conf_path.display())).env("LANG", "C").output().map_err(|_| "error.wifi.dhcp".to_string())?;
|
|
if !output.status.success() || !pid_alive(&run_path("dnsmasq.pid")) {
|
|
eprintln!("dnsmasq: {}", redact(&String::from_utf8_lossy(&output.stderr)));
|
|
return Err("error.wifi.dhcp".into());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn dhcp_conf(enabled: &[&Ap], plan: &Plan, extras: &Extras) -> String {
|
|
let mut lines = vec![
|
|
"bind-interfaces".into(),
|
|
"except-interface=lo".into(),
|
|
"dhcp-authoritative".into(),
|
|
"quiet-dhcp".into(),
|
|
format!("pid-file={RUN}/dnsmasq.pid"),
|
|
format!("dhcp-leasefile={RUN}/dnsmasq.leases"),
|
|
];
|
|
let bridged = using_bridge();
|
|
let rows: Vec<(&str, &Ap)> = if bridged {
|
|
enabled.first().map(|ap| vec![("br-lan", *ap)]).unwrap_or_default()
|
|
} else {
|
|
enabled.iter().map(|ap| (ap.iface.as_str(), *ap)).collect()
|
|
};
|
|
for (pos, (iface, ap)) in rows.iter().enumerate() {
|
|
if !safe_ip(&ap.gateway) || !safe_ip(&ap.dhcp_start) || !safe_ip(&ap.dhcp_end) || !safe_ip(&ap.mask) {
|
|
continue;
|
|
}
|
|
let dns = dhcp_dns(plan, &ap.gateway, &extras.dns);
|
|
let tag = format!("lan{pos}");
|
|
lines.push(format!("interface={iface}"));
|
|
lines.push(format!("listen-address={}", ap.gateway));
|
|
lines.push(format!("dhcp-range=set:{tag},{},{},{},12h", ap.dhcp_start, ap.dhcp_end, ap.mask));
|
|
lines.push(format!("dhcp-option=tag:{tag},3,{}", ap.gateway));
|
|
lines.push(format!("dhcp-option=tag:{tag},6,{dns}"));
|
|
}
|
|
for (mac, ip) in &extras.reservations {
|
|
if mac_ok(mac) && safe_ip(ip) {
|
|
lines.push(format!("dhcp-host={mac},{ip}"));
|
|
}
|
|
}
|
|
lines.join("\n") + "\n"
|
|
}
|
|
|
|
fn dhcp_dns(plan: &Plan, gateway: &str, dns: &[String]) -> String {
|
|
if (1..=2).contains(&dns.len()) && dns.iter().all(|ip| safe_ip(ip)) {
|
|
return dns.join(",");
|
|
}
|
|
dns_server(plan, gateway)
|
|
}
|
|
|
|
fn using_bridge() -> bool {
|
|
let Ok(entries) = fs::read_dir(RUN) else { return false };
|
|
entries.flatten().any(|entry| {
|
|
let name = entry.file_name().to_string_lossy().to_string();
|
|
name.starts_with("hostapd-")
|
|
&& name.ends_with(".conf")
|
|
&& fs::read_to_string(entry.path()).unwrap_or_default().contains("bridge=br-lan")
|
|
})
|
|
}
|
|
|
|
fn lan_cidrs(enabled: &[&Ap]) -> Vec<String> {
|
|
let mut out = Vec::new();
|
|
for ap in enabled {
|
|
if usable_cidr(&ap.cidr) && !out.iter().any(|item| item == &ap.cidr) {
|
|
out.push(ap.cidr.clone());
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn usable_cidr(value: &str) -> bool {
|
|
let Some((ip, prefix)) = value.split_once('/') else { return false };
|
|
let Ok(prefix) = prefix.parse::<u8>() else { return false };
|
|
(8..=30).contains(&prefix) && safe_ip(ip)
|
|
}
|
|
|
|
fn dns_server(plan: &Plan, gateway: &str) -> String {
|
|
if !plan.via.is_empty() && plan.dev.starts_with("usb") && (plan.mode == "nic" || plan.mode == "auto") {
|
|
return plan.via.clone();
|
|
}
|
|
gateway.to_string()
|
|
}
|
|
|
|
fn route_plan(mode: &str) -> Plan {
|
|
let routes = default_routes();
|
|
let cell = routes.iter().find(|route| is_cell(&route.dev));
|
|
let usb = routes.iter().find(|route| route.dev.starts_with("usb"));
|
|
let chosen = match mode {
|
|
"nic" => usb,
|
|
"auto" => cell.or(usb),
|
|
_ => cell,
|
|
};
|
|
Plan {
|
|
mode: mode.to_string(),
|
|
dev: chosen.map(|route| route.dev.clone()).unwrap_or_default(),
|
|
via: chosen.map(|route| route.via.clone()).unwrap_or_default(),
|
|
}
|
|
}
|
|
|
|
fn install_routes(plan: &Plan, cidrs: &[String]) -> Result<bool, String> {
|
|
let stamp = format!("{}|{}|{}|{}", plan.mode, plan.dev, plan.via, cidrs.join(","));
|
|
let stamp_path = run_path("route.plan");
|
|
if fs::read_to_string(&stamp_path).unwrap_or_default() == stamp {
|
|
if let Ok(text) = command("ip", &["route".into(), "show".into(), "table".into(), "180".into()]) {
|
|
if text.contains("default") || text.contains("blackhole") {
|
|
return Ok(false);
|
|
}
|
|
}
|
|
}
|
|
let _ = fs::write("/proc/sys/net/ipv4/ip_forward", "1\n");
|
|
let _ = fs::write("/proc/sys/net/ipv4/conf/all/rp_filter", "2\n");
|
|
clear_routes();
|
|
if plan.dev.is_empty() {
|
|
command("ip", &["route".into(), "replace".into(), "blackhole".into(), "default".into(), "table".into(), "180".into()]).map(|_| ())?;
|
|
} else if plan.via.is_empty() || !safe_ip(&plan.via) {
|
|
command("ip", &["route".into(), "replace".into(), "default".into(), "dev".into(), plan.dev.clone(), "table".into(), "180".into()]).map(|_| ())?;
|
|
} else {
|
|
command("ip", &["route".into(), "replace".into(), "default".into(), "via".into(), plan.via.clone(), "dev".into(), plan.dev.clone(), "table".into(), "180".into()]).map(|_| ())?;
|
|
}
|
|
for (pos, cidr) in cidrs.iter().enumerate() {
|
|
let local = (18010 + pos * 2).to_string();
|
|
let wan = (18011 + pos * 2).to_string();
|
|
command("ip", &["rule".into(), "add".into(), "from".into(), cidr.clone(), "to".into(), cidr.clone(), "lookup".into(), "main".into(), "pref".into(), local]).map(|_| ())?;
|
|
command("ip", &["rule".into(), "add".into(), "from".into(), cidr.clone(), "lookup".into(), "180".into(), "pref".into(), wan]).map(|_| ())?;
|
|
}
|
|
let mut pref = 18040u32;
|
|
for left in cidrs {
|
|
for right in cidrs {
|
|
if left == right {
|
|
continue;
|
|
}
|
|
command("ip", &["rule".into(), "add".into(), "from".into(), left.clone(), "to".into(), right.clone(), "lookup".into(), "main".into(), "pref".into(), pref.to_string()]).map(|_| ())?;
|
|
pref += 1;
|
|
}
|
|
}
|
|
let _ = fs::create_dir_all(RUN);
|
|
let _ = fs::write(&stamp_path, stamp);
|
|
Ok(true)
|
|
}
|
|
|
|
fn clear_routes() {
|
|
if let Ok(text) = command("ip", &["rule".into(), "show".into()]) {
|
|
for line in text.lines() {
|
|
let Some((pref, _)) = line.split_once(':') else { continue };
|
|
let Ok(value) = pref.trim().parse::<u32>() else { continue };
|
|
if (18010..18060).contains(&value) {
|
|
let _ = command("ip", &["rule".into(), "del".into(), "pref".into(), value.to_string()]);
|
|
}
|
|
}
|
|
}
|
|
let _ = command("ip", &["route".into(), "flush".into(), "table".into(), "180".into()]);
|
|
let _ = fs::remove_file(run_path("route.plan"));
|
|
}
|
|
|
|
fn install_nat(plan: &Plan, enabled: &[&Ap], cidrs: &[String]) {
|
|
clear_nat();
|
|
if plan.dev.is_empty() || !valid_dev(&plan.dev) {
|
|
return;
|
|
}
|
|
let mut script = String::from("table ip mifipanel_wan {\n chain forward {\n type filter hook forward priority -10; policy accept;\n");
|
|
let ifaces: Vec<&str> = if using_bridge() {
|
|
vec!["br-lan"]
|
|
} else {
|
|
enabled.iter().map(|ap| ap.iface.as_str()).filter(|name| valid_dev(name)).collect()
|
|
};
|
|
for iface in ifaces {
|
|
script.push_str(&format!(" iifname \"{iface}\" oifname \"{}\" accept\n", plan.dev));
|
|
script.push_str(&format!(" iifname \"{}\" oifname \"{iface}\" ct state established,related accept\n", plan.dev));
|
|
}
|
|
script.push_str(" }\n chain post {\n type nat hook postrouting priority 100; policy accept;\n");
|
|
for cidr in cidrs {
|
|
if usable_cidr(cidr) {
|
|
script.push_str(&format!(" ip saddr {cidr} oifname \"{}\" masquerade\n", plan.dev));
|
|
}
|
|
}
|
|
script.push_str(" }\n}\n");
|
|
nft_apply(&script);
|
|
}
|
|
|
|
fn clear_nat() {
|
|
let _ = command("nft", &["delete".into(), "table".into(), "ip".into(), "mifipanel_wan".into()]);
|
|
}
|
|
|
|
fn clear_legacy_nft() {
|
|
let _ = command("nft", &["delete".into(), "table".into(), "inet".into(), "mifipanel".into()]);
|
|
}
|
|
|
|
fn nft_apply(script: &str) {
|
|
let mut child = Command::new("nft");
|
|
child.args(["-f", "-"]).stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped());
|
|
let Ok(mut child) = child.spawn() else { return };
|
|
if let Some(mut stdin) = child.stdin.take() {
|
|
let _ = stdin.write_all(script.as_bytes());
|
|
}
|
|
let _ = child.wait();
|
|
}
|
|
|
|
fn default_routes() -> Vec<Route> {
|
|
let Ok(text) = command("ip", &["-4".into(), "route".into(), "show".into(), "default".into()]) else { return Vec::new() };
|
|
let mut out = Vec::new();
|
|
for line in text.lines() {
|
|
let parts: Vec<&str> = line.split_whitespace().collect();
|
|
let mut dev = String::new();
|
|
let mut via = String::new();
|
|
let mut index = 0;
|
|
while index + 1 < parts.len() {
|
|
if parts[index] == "dev" {
|
|
dev = parts[index + 1].to_string();
|
|
}
|
|
if parts[index] == "via" {
|
|
via = parts[index + 1].to_string();
|
|
}
|
|
index += 1;
|
|
}
|
|
if valid_dev(&dev) {
|
|
out.push(Route { dev, via });
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn is_cell(dev: &str) -> bool {
|
|
dev.starts_with("wwan") || dev.starts_with("rmnet") || dev.starts_with("wwp") || dev.starts_with("wwx")
|
|
}
|
|
|
|
fn sync_usb(root: &Path, nic: bool) -> Result<(), String> {
|
|
let marker = root.join("usb-nic.mode");
|
|
if nic {
|
|
if !marker.exists() {
|
|
let Some(name) = usb_connection() else {
|
|
eprintln!("没有找到 USB 网卡连接,热点出口仍按当前路由");
|
|
return Ok(());
|
|
};
|
|
let method = nm_get(&name, "ipv4.method").unwrap_or_else(|| "shared".into());
|
|
let address = nm_get(&name, "ipv4.addresses").unwrap_or_default();
|
|
if command("nmcli", &["connection".into(), "modify".into(), name.clone(), "ipv4.method".into(), "auto".into(), "ipv6.method".into(), "disabled".into()]).is_err() {
|
|
return Err("error.wifi.nic".into());
|
|
}
|
|
if !address.is_empty() {
|
|
let _ = command("nmcli", &["connection".into(), "modify".into(), name.clone(), "-ipv4.addresses".into(), address.clone()]);
|
|
}
|
|
fs::write(&marker, format!("{name}\n{method}\n{address}\n")).map_err(|err| err.to_string())?;
|
|
set_mode(&marker, 0o600);
|
|
let _ = command("nmcli", &["-w".into(), "12".into(), "connection".into(), "up".into(), name]);
|
|
} else if !usb_has_v4() {
|
|
if let Some(name) = marker_name(&marker).or_else(usb_connection) {
|
|
let _ = command("nmcli", &["-w".into(), "12".into(), "connection".into(), "up".into(), name]);
|
|
}
|
|
}
|
|
if !usb_has_v4() {
|
|
for _ in 0..6 {
|
|
if usb_has_v4() {
|
|
break;
|
|
}
|
|
thread::sleep(Duration::from_millis(500));
|
|
}
|
|
}
|
|
Ok(())
|
|
} else if marker.exists() {
|
|
let text = fs::read_to_string(&marker).unwrap_or_default();
|
|
let mut lines = text.lines();
|
|
let name = lines.next().unwrap_or("usb-failsafe").to_string();
|
|
let method = lines.next().unwrap_or("shared").to_string();
|
|
let address = lines.next().unwrap_or("").to_string();
|
|
let mut args = vec!["connection".into(), "modify".into(), name.clone(), "ipv4.method".into(), if method.is_empty() { "shared".into() } else { method }, "ipv6.method".into(), "disabled".into()];
|
|
if !address.is_empty() {
|
|
args.push("ipv4.addresses".into());
|
|
args.push(address);
|
|
}
|
|
if command("nmcli", &args).is_err() {
|
|
return Err("error.wifi.nic".into());
|
|
}
|
|
let _ = command("nmcli", &["-w".into(), "12".into(), "connection".into(), "up".into(), name]);
|
|
let _ = fs::remove_file(&marker);
|
|
Ok(())
|
|
} else {
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
fn marker_name(path: &Path) -> Option<String> {
|
|
let text = fs::read_to_string(path).ok()?;
|
|
let name = text.lines().next()?.trim();
|
|
if name.is_empty() { None } else { Some(name.to_string()) }
|
|
}
|
|
|
|
fn usb_connection() -> Option<String> {
|
|
let text = command("nmcli", &["-t".into(), "-f".into(), "NAME,DEVICE".into(), "connection".into(), "show".into()]).ok()?;
|
|
let mut fallback = None;
|
|
for line in text.lines() {
|
|
let Some((name, device)) = line.split_once(':') else { continue };
|
|
if device.starts_with("usb") {
|
|
return Some(name.to_string());
|
|
}
|
|
if name == "usb-failsafe" {
|
|
fallback = Some(name.to_string());
|
|
}
|
|
}
|
|
fallback
|
|
}
|
|
|
|
fn usb_has_v4() -> bool {
|
|
command("ip", &["-4".into(), "-o".into(), "addr".into(), "show".into()]).map(|text| {
|
|
text.lines().any(|line| {
|
|
let dev = line.split_whitespace().nth(1).unwrap_or("");
|
|
dev.starts_with("usb") && line.contains("inet")
|
|
})
|
|
}).unwrap_or(false)
|
|
}
|
|
|
|
fn nm_get(name: &str, field: &str) -> Option<String> {
|
|
let text = command("nmcli", &["-g".into(), field.into(), "connection".into(), "show".into(), name.into()]).ok()?;
|
|
let value = text.lines().next().unwrap_or("").trim();
|
|
if value.is_empty() || value == "--" { None } else { Some(value.to_string()) }
|
|
}
|
|
|
|
fn down_nm() {
|
|
let _ = command("nmcli", &["connection".into(), "modify".into(), "mifipanel".into(), "connection.autoconnect".into(), "no".into()]);
|
|
let _ = command("nmcli", &["connection".into(), "down".into(), "mifipanel".into()]);
|
|
}
|
|
|
|
fn release_ifaces(ifaces: &[String]) {
|
|
for iface in ifaces {
|
|
if valid_dev(iface) {
|
|
let _ = command("nmcli", &["device".into(), "set".into(), iface.clone(), "managed".into(), "yes".into()]);
|
|
drop_addrs(iface);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn drop_addrs(iface: &str) {
|
|
let _ = command("ip", &["-4".into(), "addr".into(), "flush".into(), "dev".into(), iface.into()]);
|
|
}
|
|
|
|
fn stop_services() {
|
|
if let Ok(entries) = fs::read_dir(RUN) {
|
|
for entry in entries.flatten() {
|
|
let name = entry.file_name().to_string_lossy().to_string();
|
|
if let Some(iface) = name.strip_prefix("hostapd-").and_then(|text| text.strip_suffix(".pid")) {
|
|
stop_pid(&entry.path());
|
|
drop_addrs(iface);
|
|
}
|
|
if name.starts_with("hostapd-") && name.ends_with(".conf") {
|
|
let _ = fs::remove_file(entry.path());
|
|
}
|
|
}
|
|
}
|
|
stop_pid(&run_path("dnsmasq.pid"));
|
|
drop_addrs("br-lan");
|
|
}
|
|
|
|
fn stop_pid(path: &Path) {
|
|
let Ok(text) = fs::read_to_string(path) else { return };
|
|
if let Ok(pid) = text.trim().parse::<i32>() {
|
|
signal_term(pid);
|
|
thread::sleep(Duration::from_millis(100));
|
|
}
|
|
let _ = fs::remove_file(path);
|
|
}
|
|
|
|
fn pid_alive(path: &Path) -> bool {
|
|
let Ok(text) = fs::read_to_string(path) else { return false };
|
|
let Ok(pid) = text.trim().parse::<i32>() else { return false };
|
|
pid_exists(pid)
|
|
}
|
|
|
|
fn pid_path(iface: &str) -> PathBuf {
|
|
run_path(&format!("hostapd-{iface}.pid"))
|
|
}
|
|
|
|
fn run_path(name: &str) -> PathBuf {
|
|
Path::new(RUN).join(name)
|
|
}
|
|
|
|
fn wifi_ifaces() -> Vec<String> {
|
|
let Ok(text) = command("nmcli", &["-t".into(), "-f".into(), "DEVICE,TYPE".into(), "device".into()]) else { return Vec::new() };
|
|
let mut out = Vec::new();
|
|
for line in text.lines() {
|
|
let mut parts = line.split(':');
|
|
let name = parts.next().unwrap_or("").trim();
|
|
let kind = parts.next().unwrap_or("").trim();
|
|
if kind == "wifi" && valid_dev(name) && !name.starts_with("p2p") && !out.iter().any(|item| item == name) {
|
|
out.push(name.to_string());
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn hostapd_installed() -> bool {
|
|
Path::new("/usr/sbin/hostapd").exists() || Path::new("/usr/bin/hostapd").exists()
|
|
}
|
|
|
|
fn hostapd_bin() -> &'static str {
|
|
if Path::new("/usr/sbin/hostapd").exists() { "/usr/sbin/hostapd" } else { "hostapd" }
|
|
}
|
|
|
|
fn hostapd_cli() -> &'static str {
|
|
if Path::new("/usr/sbin/hostapd_cli").exists() { "/usr/sbin/hostapd_cli" } else { "hostapd_cli" }
|
|
}
|
|
|
|
fn dnsmasq_bin() -> &'static str {
|
|
if Path::new("/usr/sbin/dnsmasq").exists() { "/usr/sbin/dnsmasq" } else { "dnsmasq" }
|
|
}
|
|
|
|
fn offline_debs() -> Vec<PathBuf> {
|
|
let mut out = vec![
|
|
PathBuf::from("/usr/local/share/mifipanel/offline/hostapd_2.10-24_arm64.deb"),
|
|
PathBuf::from("/usr/local/share/mifipanel/hostapd_2.10-24_arm64.deb"),
|
|
];
|
|
out.extend(hostapd_debs_in(Path::new("/usr/local/share/mifipanel/offline")));
|
|
out.sort();
|
|
out.dedup();
|
|
out
|
|
}
|
|
|
|
fn hostapd_debs_in(dir: &Path) -> Vec<PathBuf> {
|
|
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
|
|
let mut out = Vec::new();
|
|
for entry in entries.flatten() {
|
|
let path = entry.path();
|
|
let Some(name) = path.file_name().and_then(|item| item.to_str()) else { continue };
|
|
if name.starts_with("hostapd") && name.ends_with(".deb") {
|
|
out.push(path);
|
|
}
|
|
}
|
|
out.sort();
|
|
out
|
|
}
|
|
|
|
fn sort_bands(bands: &mut Vec<String>) {
|
|
bands.sort_by_key(|band| match band.as_str() {
|
|
"2.4" => 0,
|
|
"5" => 1,
|
|
"6" => 2,
|
|
_ => 9,
|
|
});
|
|
bands.dedup();
|
|
}
|
|
|
|
pub(crate) fn concrete_channel(band: &str, channel: u32) -> u32 {
|
|
if channel != 0 {
|
|
return channel;
|
|
}
|
|
match band {
|
|
"5" => 36,
|
|
"6" => 5,
|
|
_ => 6,
|
|
}
|
|
}
|
|
|
|
pub(crate) fn subnet_indexes<'a>(bands: impl Iterator<Item = &'a str>) -> Vec<u8> {
|
|
let mut used = HashSet::new();
|
|
let mut out = Vec::new();
|
|
for band in bands {
|
|
let preferred = match band {
|
|
"5" => 1,
|
|
"6" => 2,
|
|
_ => 0,
|
|
};
|
|
let mut index: u8 = preferred;
|
|
if used.contains(&index) {
|
|
index = 3;
|
|
while used.contains(&index) {
|
|
index = index.saturating_add(1);
|
|
}
|
|
}
|
|
used.insert(index);
|
|
out.push(index);
|
|
}
|
|
out
|
|
}
|
|
|
|
pub(crate) fn config_text(iface: &str, band: &str, ssid: &str, security: &str, password: &str, hidden: bool, channel: u32, deny: &str, bridge: &str, accept: &str, acl_accept: bool, max_sta: u32) -> String {
|
|
let channel = concrete_channel(band, channel);
|
|
let mode = if band == "2.4" { "g" } else { "a" };
|
|
let sta = if (1..=32).contains(&max_sta) { max_sta } else { 16 };
|
|
let mut lines = vec![format!("interface={iface}")];
|
|
if !bridge.is_empty() && valid_dev(bridge) {
|
|
lines.push(format!("bridge={bridge}"));
|
|
}
|
|
lines.extend([
|
|
"driver=nl80211".into(),
|
|
format!("ssid={ssid}"),
|
|
format!("hw_mode={mode}"),
|
|
format!("channel={channel}"),
|
|
"auth_algs=1".into(),
|
|
format!("ignore_broadcast_ssid={}", if hidden { 1 } else { 0 }),
|
|
format!("max_num_sta={sta}"),
|
|
]);
|
|
if acl_accept && safe_conf_path(accept) {
|
|
lines.push("macaddr_acl=1".into());
|
|
lines.push(format!("accept_mac_file={accept}"));
|
|
} else if safe_conf_path(deny) {
|
|
lines.push("macaddr_acl=0".into());
|
|
lines.push(format!("deny_mac_file={deny}"));
|
|
} else {
|
|
lines.push("macaddr_acl=0".into());
|
|
}
|
|
lines.extend([
|
|
"ctrl_interface=/run/hostapd".into(),
|
|
"ctrl_interface_group=0".into(),
|
|
]);
|
|
if security != "open" {
|
|
lines.push("wpa=2".into());
|
|
lines.push(format!("wpa_passphrase={password}"));
|
|
lines.push("wpa_key_mgmt=WPA-PSK".into());
|
|
lines.push("rsn_pairwise=CCMP".into());
|
|
lines.push("ieee80211w=0".into());
|
|
}
|
|
if band != "2.4" {
|
|
lines.push("country_code=CN".into());
|
|
lines.push("ieee80211d=1".into());
|
|
lines.push("ieee80211n=1".into());
|
|
if band == "5" {
|
|
lines.push("ieee80211ac=1".into());
|
|
}
|
|
}
|
|
lines.join("\n") + "\n"
|
|
}
|
|
|
|
fn valid_dev(name: &str) -> bool {
|
|
!name.is_empty() && name.len() <= 15 && !name.starts_with('-') && name.chars().all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-' || ch == '.')
|
|
}
|
|
|
|
fn safe_ip(value: &str) -> bool {
|
|
let parts: Vec<&str> = value.split('.').collect();
|
|
parts.len() == 4 && parts.iter().all(|part| !part.is_empty() && part.chars().all(|ch| ch.is_ascii_digit()) && part.parse::<u8>().is_ok())
|
|
}
|
|
|
|
fn mac_ok(value: &str) -> bool {
|
|
let parts: Vec<&str> = value.split(':').collect();
|
|
parts.len() == 6 && parts.iter().all(|part| part.len() == 2 && part.chars().all(|ch| ch.is_ascii_hexdigit()))
|
|
}
|
|
|
|
fn safe_conf_path(value: &str) -> bool {
|
|
!value.is_empty() && value.len() <= 240 && value.chars().all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '/' | '.' | '_' | '-'))
|
|
}
|
|
|
|
pub fn clear_ttl() {
|
|
sync_ttl(0, "");
|
|
}
|
|
|
|
pub fn sync_ttl(ttl: u8, cidr: &str) {
|
|
let desired = ttl_script(ttl, cidr);
|
|
let stamp = run_path("ttl.plan");
|
|
let previous = fs::read_to_string(&stamp).unwrap_or_default();
|
|
if previous == desired && (desired.is_empty() || command("nft", &["list".into(), "table".into(), "ip".into(), "mifipanel_ttl".into()]).is_ok()) {
|
|
return;
|
|
}
|
|
let _ = command("nft", &["delete".into(), "table".into(), "ip".into(), "mifipanel_ttl".into()]);
|
|
if desired.is_empty() {
|
|
let _ = fs::create_dir_all(RUN);
|
|
let _ = fs::write(&stamp, "");
|
|
return;
|
|
}
|
|
if nft_script(&desired) {
|
|
let _ = fs::create_dir_all(RUN);
|
|
let _ = fs::write(&stamp, &desired);
|
|
}
|
|
}
|
|
|
|
pub(crate) fn ttl_script(ttl: u8, cidr: &str) -> String {
|
|
if ttl == 0 || !usable_cidr(cidr) {
|
|
return String::new();
|
|
}
|
|
let ttl = u16::from(ttl);
|
|
let mut out = String::from("table ip mifipanel_ttl {\n chain postrouting {\n type filter hook postrouting priority mangle; policy accept;\n");
|
|
for prefix in ["wwan", "rmnet", "wwp", "ppp"] {
|
|
out.push_str(&format!(" oifname \"{prefix}*\" ip saddr {cidr} ip ttl set {ttl}\n"));
|
|
}
|
|
out.push_str(" }\n}\n");
|
|
out
|
|
}
|
|
|
|
fn nft_script(script: &str) -> bool {
|
|
let mut child = Command::new("nft");
|
|
child.args(["-f", "-"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
|
let Ok(mut child) = child.spawn() else { return false };
|
|
if let Some(mut stdin) = child.stdin.take() {
|
|
let _ = stdin.write_all(script.as_bytes());
|
|
}
|
|
child.wait().map(|status| status.success()).unwrap_or(false)
|
|
}
|
|
|
|
fn redact(text: &str) -> String {
|
|
text.lines().filter(|line| !line.contains("wpa_passphrase=") && !line.contains("psk=")).collect::<Vec<_>>().join("\n")
|
|
}
|
|
|
|
fn command(bin: &str, args: &[String]) -> Result<String, String> {
|
|
let output = Command::new(bin).args(args).env("LANG", "C").output().map_err(|err| format!("error.wifi.start|{err}"))?;
|
|
let stdout = String::from_utf8_lossy(&output.stdout);
|
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
|
let text = if stdout.trim().is_empty() { stderr.trim().to_string() } else { stdout.trim().to_string() };
|
|
if output.status.success() {
|
|
Ok(text)
|
|
} else if text.is_empty() {
|
|
Err("error.wifi.fail".into())
|
|
} else {
|
|
Err(redact(&text).chars().take(240).collect())
|
|
}
|
|
}
|
|
|
|
fn set_mode(path: &Path, mode: u32) {
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::PermissionsExt;
|
|
let _ = fs::set_permissions(path, fs::Permissions::from_mode(mode));
|
|
}
|
|
#[cfg(not(unix))]
|
|
{
|
|
let _ = (path, mode);
|
|
}
|
|
}
|
|
|
|
fn signal_term(pid: i32) {
|
|
#[cfg(target_os = "linux")]
|
|
unsafe {
|
|
libc::kill(pid, libc::SIGTERM);
|
|
}
|
|
#[cfg(not(target_os = "linux"))]
|
|
{
|
|
let _ = pid;
|
|
}
|
|
}
|
|
|
|
fn pid_exists(pid: i32) -> bool {
|
|
#[cfg(target_os = "linux")]
|
|
unsafe {
|
|
libc::kill(pid, 0) == 0
|
|
}
|
|
#[cfg(not(target_os = "linux"))]
|
|
{
|
|
let _ = pid;
|
|
false
|
|
}
|
|
}
|
|
|
|
fn phy_info() -> PhyInfo {
|
|
#[cfg(target_os = "linux")]
|
|
{
|
|
linux_phy_info()
|
|
}
|
|
#[cfg(not(target_os = "linux"))]
|
|
{
|
|
PhyInfo { bands: HashMap::new(), blocked: HashSet::new(), ok: false }
|
|
}
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
fn netlink_addr() -> libc::sockaddr_nl {
|
|
let mut addr: libc::sockaddr_nl = unsafe { std::mem::zeroed() };
|
|
addr.nl_family = libc::AF_NETLINK as _;
|
|
addr
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
fn linux_phy_info() -> PhyInfo {
|
|
let empty = PhyInfo { bands: HashMap::new(), blocked: HashSet::new(), ok: false };
|
|
let Ok(socket) = Netlink::open() else { return empty };
|
|
let Ok(family) = socket.family_id() else { return empty };
|
|
let Ok(phys) = socket.dump(family, 1) else { return empty };
|
|
let Ok(ifaces) = socket.dump(family, 5) else { return empty };
|
|
let mut by_id: HashMap<u32, (Vec<String>, Option<bool>)> = HashMap::new();
|
|
for payload in phys {
|
|
let Some((id, bands, ap)) = wiphy_info(&payload) else { continue };
|
|
let entry = by_id.entry(id).or_insert_with(|| (Vec::new(), None));
|
|
for band in bands {
|
|
if !entry.0.iter().any(|item| item == &band) {
|
|
entry.0.push(band);
|
|
}
|
|
}
|
|
if ap.is_some() {
|
|
entry.1 = ap;
|
|
}
|
|
}
|
|
let mut bands = HashMap::new();
|
|
let mut blocked = HashSet::new();
|
|
for payload in ifaces {
|
|
let Some((id, name)) = iface_info(&payload) else { continue };
|
|
if name.is_empty() || name.starts_with("p2p") {
|
|
continue;
|
|
}
|
|
let Some((phy_bands, ap)) = by_id.get(&id) else { continue };
|
|
if ap == &Some(false) {
|
|
blocked.insert(name);
|
|
continue;
|
|
}
|
|
bands.insert(name, phy_bands.clone());
|
|
}
|
|
PhyInfo { bands, blocked, ok: true }
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
struct Netlink(i32);
|
|
|
|
#[cfg(target_os = "linux")]
|
|
impl Drop for Netlink {
|
|
fn drop(&mut self) {
|
|
unsafe { libc::close(self.0); }
|
|
}
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
impl Netlink {
|
|
fn open() -> Result<Self, ()> {
|
|
unsafe {
|
|
let fd = libc::socket(libc::AF_NETLINK, libc::SOCK_RAW, libc::NETLINK_GENERIC);
|
|
if fd < 0 {
|
|
return Err(());
|
|
}
|
|
let socket = Netlink(fd);
|
|
let addr = netlink_addr();
|
|
if libc::bind(fd, &addr as *const _ as *const libc::sockaddr, std::mem::size_of::<libc::sockaddr_nl>() as libc::socklen_t) != 0 {
|
|
return Err(());
|
|
}
|
|
let tv = libc::timeval { tv_sec: 1, tv_usec: 0 };
|
|
libc::setsockopt(fd, libc::SOL_SOCKET, libc::SO_RCVTIMEO, &tv as *const _ as *const libc::c_void, std::mem::size_of::<libc::timeval>() as libc::socklen_t);
|
|
Ok(socket)
|
|
}
|
|
}
|
|
|
|
fn family_id(&self) -> Result<u16, ()> {
|
|
let mut attrs = Vec::new();
|
|
push_attr(&mut attrs, 2, b"nl80211\0");
|
|
self.send(16, 0x05, 3, &attrs)?;
|
|
let messages = self.recv_all()?;
|
|
for payload in messages {
|
|
if payload.first().copied() != Some(1) {
|
|
continue;
|
|
}
|
|
for (kind, data) in nlas(&payload[4..]) {
|
|
if kind == 1 {
|
|
if data.len() >= 2 {
|
|
return Ok(u16::from_le_bytes([data[0], data[1]]));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
Err(())
|
|
}
|
|
|
|
fn dump(&self, family: u16, cmd: u8) -> Result<Vec<Vec<u8>>, ()> {
|
|
self.send(family, 0x301, cmd, &[])?;
|
|
let messages = self.recv_all()?;
|
|
let mut out = Vec::new();
|
|
for payload in messages {
|
|
if payload.first().copied() == Some(cmd_reply(cmd)) {
|
|
out.push(payload);
|
|
}
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
fn send(&self, kind: u16, flags: u16, cmd: u8, attrs: &[u8]) -> Result<(), ()> {
|
|
let packet = nlmsg(kind, flags, 1, cmd, attrs);
|
|
let addr = netlink_addr();
|
|
let sent = unsafe {
|
|
libc::sendto(self.0, packet.as_ptr() as *const libc::c_void, packet.len(), 0, &addr as *const _ as *const libc::sockaddr, std::mem::size_of::<libc::sockaddr_nl>() as libc::socklen_t)
|
|
};
|
|
if sent == packet.len() as isize { Ok(()) } else { Err(()) }
|
|
}
|
|
|
|
fn recv_all(&self) -> Result<Vec<Vec<u8>>, ()> {
|
|
let mut out = Vec::new();
|
|
let mut buf = vec![0u8; 1024 * 256];
|
|
for _ in 0..64 {
|
|
let size = unsafe { libc::recv(self.0, buf.as_mut_ptr() as *mut libc::c_void, buf.len(), 0) };
|
|
if size <= 0 {
|
|
break;
|
|
}
|
|
let mut offset = 0usize;
|
|
let bytes = &buf[..size as usize];
|
|
let mut done = false;
|
|
while offset + 16 <= bytes.len() {
|
|
let total = u32::from_le_bytes([bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]]) as usize;
|
|
if total < 16 || offset + total > bytes.len() {
|
|
break;
|
|
}
|
|
let kind = u16::from_le_bytes([bytes[offset + 4], bytes[offset + 5]]);
|
|
let payload = &bytes[offset + 16..offset + total];
|
|
if kind < 0x10 && kind == 3 {
|
|
done = true;
|
|
} else if kind < 0x10 && kind == 2 {
|
|
let code = payload.get(..4).map(|item| i32::from_le_bytes([item[0], item[1], item[2], item[3]])).unwrap_or(-1);
|
|
if code != 0 {
|
|
return Err(());
|
|
}
|
|
} else if kind >= 0x10 && payload.len() >= 4 {
|
|
out.push(payload.to_vec());
|
|
}
|
|
offset += (total + 3) & !3;
|
|
}
|
|
if done {
|
|
break;
|
|
}
|
|
}
|
|
Ok(out)
|
|
}
|
|
}
|
|
|
|
fn cmd_reply(cmd: u8) -> u8 {
|
|
match cmd {
|
|
1 => 3,
|
|
5 => 7,
|
|
other => other,
|
|
}
|
|
}
|
|
|
|
fn nlmsg(kind: u16, flags: u16, seq: u32, cmd: u8, attrs: &[u8]) -> Vec<u8> {
|
|
let total = 16 + 4 + attrs.len();
|
|
let mut out = Vec::new();
|
|
out.extend_from_slice(&(total as u32).to_le_bytes());
|
|
out.extend_from_slice(&kind.to_le_bytes());
|
|
out.extend_from_slice(&flags.to_le_bytes());
|
|
out.extend_from_slice(&seq.to_le_bytes());
|
|
out.extend_from_slice(&0u32.to_le_bytes());
|
|
out.push(cmd);
|
|
out.push(1);
|
|
out.extend_from_slice(&0u16.to_le_bytes());
|
|
out.extend_from_slice(attrs);
|
|
out
|
|
}
|
|
|
|
fn push_attr(buf: &mut Vec<u8>, kind: u16, data: &[u8]) {
|
|
let len = 4 + data.len();
|
|
buf.extend_from_slice(&(len as u16).to_le_bytes());
|
|
buf.extend_from_slice(&kind.to_le_bytes());
|
|
buf.extend_from_slice(data);
|
|
while buf.len() % 4 != 0 {
|
|
buf.push(0);
|
|
}
|
|
}
|
|
|
|
fn nlas(buf: &[u8]) -> Vec<(u16, &[u8])> {
|
|
let mut out = Vec::new();
|
|
let mut offset = 0usize;
|
|
while offset + 4 <= buf.len() {
|
|
let len = u16::from_le_bytes([buf[offset], buf[offset + 1]]) as usize;
|
|
let kind = u16::from_le_bytes([buf[offset + 2], buf[offset + 3]]) & 0x3fff;
|
|
if len < 4 || offset + len > buf.len() {
|
|
break;
|
|
}
|
|
out.push((kind, &buf[offset + 4..offset + len]));
|
|
offset += (len + 3) & !3;
|
|
}
|
|
out
|
|
}
|
|
|
|
fn wiphy_info(payload: &[u8]) -> Option<(u32, Vec<String>, Option<bool>)> {
|
|
if payload.len() < 4 {
|
|
return None;
|
|
}
|
|
let attrs = nlas(&payload[4..]);
|
|
let id = attrs.iter().find(|(kind, _)| *kind == 1).and_then(|(_, data)| read_u32(data))?;
|
|
let mut bands = Vec::new();
|
|
if let Some((_, nested)) = attrs.iter().find(|(kind, _)| *kind == 22) {
|
|
for (index, band) in nlas(nested) {
|
|
if let Some(name) = band_name(index) {
|
|
if band_usable(band) {
|
|
bands.push(name.to_string());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let ap = attrs.iter().find(|(kind, _)| *kind == 32).map(|(_, data)| supports_ap(data));
|
|
Some((id, bands, ap))
|
|
}
|
|
|
|
fn iface_info(payload: &[u8]) -> Option<(u32, String)> {
|
|
if payload.len() < 4 {
|
|
return None;
|
|
}
|
|
let attrs = nlas(&payload[4..]);
|
|
let id = attrs.iter().find(|(kind, _)| *kind == 1).and_then(|(_, data)| read_u32(data))?;
|
|
let name = attrs.iter().find(|(kind, _)| *kind == 4).map(|(_, data)| cstr(data))?;
|
|
Some((id, name))
|
|
}
|
|
|
|
fn band_name(index: u16) -> Option<&'static str> {
|
|
match index {
|
|
0 => Some("2.4"),
|
|
1 => Some("5"),
|
|
3 => Some("6"),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
fn band_usable(payload: &[u8]) -> bool {
|
|
let Some((_, freqs)) = nlas(payload).into_iter().find(|(kind, _)| *kind == 1) else { return true };
|
|
let mut any = false;
|
|
let mut usable = false;
|
|
for (_, freq) in nlas(freqs) {
|
|
any = true;
|
|
let disabled = nlas(freq).iter().any(|(kind, _)| *kind == 2);
|
|
if !disabled {
|
|
usable = true;
|
|
}
|
|
}
|
|
!any || usable
|
|
}
|
|
|
|
fn supports_ap(payload: &[u8]) -> bool {
|
|
let children = nlas(payload);
|
|
if children.is_empty() {
|
|
return true;
|
|
}
|
|
children.iter().any(|(kind, _)| *kind == 3)
|
|
}
|
|
|
|
fn read_u32(data: &[u8]) -> Option<u32> {
|
|
if data.len() < 4 {
|
|
return None;
|
|
}
|
|
Some(u32::from_le_bytes([data[0], data[1], data[2], data[3]]))
|
|
}
|
|
|
|
fn cstr(data: &[u8]) -> String {
|
|
let end = data.iter().position(|byte| *byte == 0).unwrap_or(data.len());
|
|
String::from_utf8_lossy(&data[..end]).trim().to_string()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn offline_directory_is_searched_for_hostapd() {
|
|
let dir = std::env::temp_dir().join(format!("mifipanel-deb-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
std::fs::write(dir.join("hostapd_2.10-24_arm64.deb"), b"deb").unwrap();
|
|
std::fs::write(dir.join("ttyd"), b"bin").unwrap();
|
|
std::fs::write(dir.join("notes.txt"), b"no").unwrap();
|
|
let found = hostapd_debs_in(&dir);
|
|
assert_eq!(found.len(), 1);
|
|
assert!(found[0].ends_with("hostapd_2.10-24_arm64.deb"));
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
|
|
#[test]
|
|
fn splits_subnets_and_writes_hostapd() {
|
|
assert_eq!(subnet_indexes(["2.4", "5"].into_iter()), vec![0, 1]);
|
|
assert_eq!(subnet_indexes(["2.4", "2.4"].into_iter()), vec![0, 3]);
|
|
assert_eq!(concrete_channel("2.4", 0), 6);
|
|
assert_eq!(concrete_channel("5", 0), 36);
|
|
let text = config_text("wlan0", "2.4", "UFI003", "wpa2", "testpass1", false, 0, "/var/lib/mifipanel/hostapd.deny", "br-lan", "/var/lib/mifipanel/hostapd.accept", false, 16);
|
|
assert!(text.contains("bridge=br-lan\n"));
|
|
assert!(text.contains("hw_mode=g\n"));
|
|
assert!(text.contains("channel=6\n"));
|
|
assert!(text.contains("ieee80211w=0\n"));
|
|
assert!(text.contains("macaddr_acl=0\n"));
|
|
assert!(text.contains("deny_mac_file=/var/lib/mifipanel/hostapd.deny\n"));
|
|
assert!(text.contains("max_num_sta=16\n"));
|
|
assert!(!text.contains("accept_mac_file"));
|
|
assert!(!text.contains("country_code"));
|
|
let open = config_text("wlan0", "5", "UFI003_5G", "open", "", true, 40, "/tmp/deny", "", "/tmp/accept", false, 16);
|
|
assert!(open.contains("hw_mode=a\n"));
|
|
assert!(open.contains("channel=40\n"));
|
|
assert!(open.contains("ignore_broadcast_ssid=1\n"));
|
|
assert!(!open.contains("wpa_passphrase"));
|
|
let allow = config_text("wlan0", "2.4", "UFI003", "wpa2", "testpass1", false, 6, "/var/lib/mifipanel/hostapd.deny", "br-lan", "/var/lib/mifipanel/hostapd.accept", true, 8);
|
|
assert!(allow.contains("macaddr_acl=1\n"));
|
|
assert!(allow.contains("accept_mac_file=/var/lib/mifipanel/hostapd.accept\n"));
|
|
assert!(allow.contains("max_num_sta=8\n"));
|
|
assert!(!allow.contains("deny_mac_file"));
|
|
assert!(allow.contains("ieee80211w=0\n"));
|
|
}
|
|
|
|
#[test]
|
|
fn writes_dhcp_reservations_and_dns() {
|
|
let ap = Ap {
|
|
iface: "wlan0".into(),
|
|
band: "2.4".into(),
|
|
enabled: true,
|
|
ssid: "UFI003".into(),
|
|
password: "testpass1".into(),
|
|
security: "wpa2".into(),
|
|
channel: 6,
|
|
hidden: false,
|
|
gateway: "192.168.8.1".into(),
|
|
prefix: 24,
|
|
mask: "255.255.255.0".into(),
|
|
dhcp_start: "192.168.8.2".into(),
|
|
dhcp_end: "192.168.8.254".into(),
|
|
cidr: "192.168.8.0/24".into(),
|
|
};
|
|
let plan = Plan { mode: "cellular".into(), dev: String::new(), via: String::new() };
|
|
let extras = Extras {
|
|
dns: vec!["8.8.8.8".into(), "1.1.1.1".into()],
|
|
reservations: vec![("AA:BB:CC:DD:EE:FF".into(), "192.168.8.20".into()), ("bad".into(), "192.168.8.21".into())],
|
|
..Extras::default()
|
|
};
|
|
let text = dhcp_conf(&[&ap], &plan, &extras);
|
|
assert!(text.contains("dhcp-option=tag:lan0,6,8.8.8.8,1.1.1.1\n"));
|
|
assert!(text.contains("dhcp-host=AA:BB:CC:DD:EE:FF,192.168.8.20\n"));
|
|
assert!(!text.contains("dhcp-host=bad"));
|
|
let auto = dhcp_conf(&[&ap], &plan, &Extras::default());
|
|
assert!(auto.contains("dhcp-option=tag:lan0,6,192.168.8.1\n"));
|
|
assert!(!auto.contains("dhcp-host="));
|
|
}
|
|
|
|
#[test]
|
|
fn ttl_rule_is_only_a_number() {
|
|
let text = ttl_script(64, "192.168.8.0/24");
|
|
assert!(text.contains("priority mangle;"));
|
|
assert!(text.contains("oifname \"wwan*\" ip saddr 192.168.8.0/24 ip ttl set 64\n"));
|
|
assert!(text.contains("oifname \"rmnet*\""));
|
|
assert!(text.contains("oifname \"wwp*\""));
|
|
assert!(text.contains("oifname \"ppp*\""));
|
|
assert!(ttl_script(0, "192.168.8.0/24").is_empty());
|
|
assert!(ttl_script(64, "192.168.8.1").is_empty());
|
|
assert!(ttl_script(64, "not a cidr").is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn reads_a_wiphy_band() {
|
|
let mut band = Vec::new();
|
|
let mut freq = Vec::new();
|
|
push_attr(&mut freq, 1, &2412u32.to_le_bytes());
|
|
push_attr(&mut band, 1, &{
|
|
let mut freqs = Vec::new();
|
|
push_attr(&mut freqs, 1, &freq);
|
|
freqs
|
|
});
|
|
let mut attrs = Vec::new();
|
|
push_attr(&mut attrs, 1, &0u32.to_le_bytes());
|
|
push_attr(&mut attrs, 22, &{
|
|
let mut bands = Vec::new();
|
|
push_attr(&mut bands, 0, &band);
|
|
bands
|
|
});
|
|
let mut payload = vec![3, 1, 0, 0];
|
|
payload.extend_from_slice(&attrs);
|
|
let (id, bands, _) = wiphy_info(&payload).unwrap();
|
|
assert_eq!(id, 0);
|
|
assert_eq!(bands, vec!["2.4".to_string()]);
|
|
}
|
|
}
|