读 APN 时没取密码,打开弹窗再保存会把基带和连接里的密码清空。现在从 QMI 和 ModemManager 都读出密码, 密码框加显示/隐藏按钮。密码按原样解析,不去首尾空格;写进网络管理器配置时按 keyfile 规则转义开头空格。 基带 1 号配置内容没变就不改写:改写会让基带重新附着,原样保存也会断一次数据连接。
660 lines
23 KiB
Rust
660 lines
23 KiB
Rust
//! 网络能力按方案选择。探测只读,不试写频段。
|
||
//! ModemManager 是通用方案;高通 QMI 只在读到更多内容时使用。
|
||
|
||
use std::fs;
|
||
use std::path::{Path, PathBuf};
|
||
use std::sync::Mutex;
|
||
|
||
use serde::Deserialize;
|
||
|
||
use crate::mmcli::{self, Access, BandStatus, Neighbor};
|
||
|
||
const EMBEDDED: &str = include_str!("../radio-schemes.json");
|
||
|
||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||
enum Source {
|
||
None,
|
||
Mm,
|
||
Qmi,
|
||
}
|
||
|
||
impl Source {
|
||
fn as_str(self) -> &'static str {
|
||
match self {
|
||
Self::None => "none",
|
||
Self::Mm => "mm",
|
||
Self::Qmi => "qmi",
|
||
}
|
||
}
|
||
|
||
fn parse(text: &str) -> Self {
|
||
match text {
|
||
"mm" => Self::Mm,
|
||
"qmi" => Self::Qmi,
|
||
_ => Self::None,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Copy)]
|
||
struct Choice {
|
||
bands: Source,
|
||
access: Source,
|
||
neighbors: Source,
|
||
apn: bool,
|
||
}
|
||
|
||
impl Choice {
|
||
const fn empty() -> Self {
|
||
Self { bands: Source::None, access: Source::None, neighbors: Source::None, apn: false }
|
||
}
|
||
}
|
||
|
||
static CHOICE: Mutex<Choice> = Mutex::new(Choice::empty());
|
||
|
||
#[derive(Deserialize)]
|
||
struct Scheme {
|
||
id: String,
|
||
transport: String,
|
||
#[serde(default)]
|
||
generic: bool,
|
||
#[serde(default)]
|
||
plugins: Vec<String>,
|
||
#[serde(default)]
|
||
bands: bool,
|
||
#[serde(default)]
|
||
access: bool,
|
||
#[serde(default)]
|
||
neighbors: bool,
|
||
#[serde(default)]
|
||
apn: bool,
|
||
}
|
||
|
||
#[derive(Clone, serde::Serialize, serde::Deserialize)]
|
||
struct Record {
|
||
fingerprint: String,
|
||
catalog: u64,
|
||
bands: String,
|
||
access: String,
|
||
neighbors: String,
|
||
apn: bool,
|
||
}
|
||
|
||
#[derive(Clone, serde::Serialize)]
|
||
pub struct Apn {
|
||
pub apn: String,
|
||
pub ip: String,
|
||
pub user: String,
|
||
pub password: String,
|
||
pub auth: String,
|
||
}
|
||
|
||
pub fn prepare(root: &Path) {
|
||
#[cfg(target_os = "linux")]
|
||
{
|
||
prepare_linux(root);
|
||
}
|
||
#[cfg(not(target_os = "linux"))]
|
||
{
|
||
let _ = root;
|
||
}
|
||
}
|
||
|
||
/// 启动时有没有认出这台设备的网络能力。开机太早、基带还没起来时会一样都认不出。
|
||
pub fn ready() -> bool {
|
||
let choice = *CHOICE.lock().unwrap_or_else(|err| err.into_inner());
|
||
choice.bands != Source::None || choice.apn
|
||
}
|
||
|
||
pub fn net_bands() -> bool {
|
||
CHOICE.lock().unwrap_or_else(|err| err.into_inner()).bands != Source::None
|
||
}
|
||
|
||
pub fn net_apn() -> bool {
|
||
CHOICE.lock().unwrap_or_else(|err| err.into_inner()).apn
|
||
}
|
||
|
||
pub fn mark_apn() {
|
||
CHOICE.lock().unwrap_or_else(|err| err.into_inner()).apn = true;
|
||
}
|
||
|
||
pub fn prefer_qmi_bands() -> bool {
|
||
CHOICE.lock().unwrap_or_else(|err| err.into_inner()).bands == Source::Qmi
|
||
}
|
||
|
||
pub fn combine(mm: (Access, Vec<Neighbor>), qmi: Option<(Access, Vec<Neighbor>)>) -> (Access, Vec<Neighbor>) {
|
||
let choice = *CHOICE.lock().unwrap_or_else(|err| err.into_inner());
|
||
let (q_access, q_neighbors) = qmi.unwrap_or_default();
|
||
let access = pick_access(choice.access, &mm.0, &q_access);
|
||
let neighbors = pick_neighbors(choice.neighbors, &mm.1, &q_neighbors);
|
||
(access, neighbors)
|
||
}
|
||
|
||
pub fn apn_get() -> Result<Apn, String> {
|
||
#[cfg(target_os = "linux")]
|
||
{
|
||
if let Some(apn) = qmi_apn_get() {
|
||
return Ok(apn);
|
||
}
|
||
let modem = mmcli::active_modem().map_err(|_| "error.apn.modem".to_string())?;
|
||
Ok(mm_apn_get(modem)?)
|
||
}
|
||
#[cfg(not(target_os = "linux"))]
|
||
{
|
||
Err("error.apn.device".into())
|
||
}
|
||
}
|
||
|
||
pub fn apn_set(apn: &str, ip: &str, user: &str, password: &str, auth: &str) -> Result<(), String> {
|
||
validate_apn(apn, ip, user, password, auth)?;
|
||
#[cfg(target_os = "linux")]
|
||
{
|
||
if qmi_node().is_some() && qmi_apn_set(apn, ip, user, password, auth).is_ok() {
|
||
if let Ok(modem) = mmcli::active_modem() {
|
||
let _ = mm_apn_set(modem, apn, ip, user, password, auth);
|
||
}
|
||
return Ok(());
|
||
}
|
||
let modem = mmcli::active_modem().map_err(|_| "error.apn.modem".to_string())?;
|
||
mm_apn_set(modem, apn, ip, user, password, auth)
|
||
}
|
||
#[cfg(not(target_os = "linux"))]
|
||
{
|
||
Err("error.apn.device".into())
|
||
}
|
||
}
|
||
|
||
fn validate_apn(apn: &str, ip: &str, user: &str, password: &str, auth: &str) -> Result<(), String> {
|
||
if apn.len() > 100 || !token_ok(apn) || apn.chars().any(|ch| ch.is_whitespace() || ch == '\'' || ch == '\\') {
|
||
return Err("error.apn.name".into());
|
||
}
|
||
if user.len() > 64 || !secret_ok(user) || password.len() > 64 || !secret_ok(password) {
|
||
return Err("error.apn.secret".into());
|
||
}
|
||
if !matches!(ip, "ipv4" | "ipv6" | "ipv4v6") {
|
||
return Err("error.apn.ip".into());
|
||
}
|
||
if !matches!(auth, "none" | "pap" | "chap" | "pap-chap") {
|
||
return Err("error.apn.auth".into());
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
fn token_ok(text: &str) -> bool {
|
||
!text.chars().any(|ch| ch == ',' || ch == '"' || ch == '\n' || ch == '\r' || ch == '=')
|
||
}
|
||
|
||
/// 用户名和密码写进命令时用双引号包住,里面可以有空格、逗号、等号和单引号,只是不能再有双引号和换行。
|
||
fn secret_ok(text: &str) -> bool {
|
||
!text.chars().any(|ch| ch == '"' || ch == '\\' || ch.is_control())
|
||
}
|
||
|
||
fn quoted(text: &str) -> String {
|
||
format!("\"{text}\"")
|
||
}
|
||
|
||
fn auth_token(auth: &str) -> &'static str {
|
||
match auth {
|
||
"pap" => "pap",
|
||
"chap" => "chap",
|
||
"pap-chap" => "pap|chap",
|
||
_ => "none",
|
||
}
|
||
}
|
||
|
||
fn pick_access(source: Source, mm: &Access, qmi: &Access) -> Access {
|
||
let mm_score = mmcli::access_score(mm);
|
||
let qmi_score = mmcli::access_score(qmi);
|
||
match source {
|
||
Source::Qmi if qmi_score > 0 => qmi.clone(),
|
||
Source::Mm if mm_score > 0 => mm.clone(),
|
||
_ => match prefer_richer(mm_score, qmi_score) {
|
||
Source::Qmi => qmi.clone(),
|
||
Source::Mm => mm.clone(),
|
||
Source::None => Access::default(),
|
||
},
|
||
}
|
||
}
|
||
|
||
fn pick_neighbors(source: Source, mm: &[Neighbor], qmi: &[Neighbor]) -> Vec<Neighbor> {
|
||
match source {
|
||
Source::Qmi if !qmi.is_empty() => qmi.to_vec(),
|
||
Source::Mm if !mm.is_empty() => mm.to_vec(),
|
||
_ => match prefer_richer(mm.len(), qmi.len()) {
|
||
Source::Qmi => qmi.to_vec(),
|
||
_ => mm.to_vec(),
|
||
},
|
||
}
|
||
}
|
||
|
||
fn prefer_richer(generic_score: usize, vendor_score: usize) -> Source {
|
||
if vendor_score > generic_score {
|
||
Source::Qmi
|
||
} else if generic_score > 0 {
|
||
Source::Mm
|
||
} else if vendor_score > 0 {
|
||
Source::Qmi
|
||
} else {
|
||
Source::None
|
||
}
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn prepare_linux(root: &Path) {
|
||
let (text, hash) = catalog_text();
|
||
let schemes = parse_schemes(&text).unwrap_or_default();
|
||
let device = scan_device();
|
||
let fingerprint = fingerprint(&device);
|
||
if let Some(saved) = load_record(root) {
|
||
if saved.fingerprint == fingerprint && saved.catalog == hash {
|
||
install(choice_from_record(&saved));
|
||
eprintln!("网络方案:锁频 {},接入 {},邻区 {},APN {}", saved.bands, saved.access, saved.neighbors, if saved.apn { "mm" } else { "无" });
|
||
return;
|
||
}
|
||
}
|
||
let choice = probe(&schemes, &device);
|
||
// 什么都没探到多半是基带还没起来。这种结果不记下来,下次启动再探,
|
||
// 否则“这台设备不能锁频”会被永久记住,锁频按钮再也不出现。
|
||
if choice.bands != Source::None || choice.apn {
|
||
save_record(root, &fingerprint, hash, &choice);
|
||
}
|
||
eprintln!(
|
||
"网络方案:锁频 {},接入 {},邻区 {},APN {}",
|
||
choice.bands.as_str(),
|
||
choice.access.as_str(),
|
||
choice.neighbors.as_str(),
|
||
if choice.apn { "mm" } else { "无" }
|
||
);
|
||
install(choice);
|
||
}
|
||
|
||
fn install(choice: Choice) {
|
||
*CHOICE.lock().unwrap_or_else(|err| err.into_inner()) = choice;
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn probe(schemes: &[Scheme], device: &Device) -> Choice {
|
||
let qmi_ok = schemes.iter().any(|item| item.transport == "qmi" && matches_scheme(item, device));
|
||
let mm_ok = schemes.iter().any(|item| item.transport == "mm" && item.generic);
|
||
let mut choice = Choice::empty();
|
||
if mm_ok || qmi_ok {
|
||
let mm_band = if mm_ok { band_score(mmcli::band_status_mm().ok()) } else { 0 };
|
||
let qmi_band = if qmi_ok { band_score(crate::qmi_band::status().ok()) } else { 0 };
|
||
choice.bands = if schemes.iter().any(|item| item.bands && ((item.transport == "mm" && mm_ok) || (item.transport == "qmi" && qmi_ok))) {
|
||
prefer_richer(mm_band, qmi_band)
|
||
} else {
|
||
Source::None
|
||
};
|
||
let modem = mmcli::active_modem().ok();
|
||
let mm_cells = modem.filter(|_| mm_ok).map(mmcli::sample_mm_cells);
|
||
let qmi_cells = if qmi_ok { mmcli::sample_qmi_cells() } else { None };
|
||
let mm_access = mm_cells.as_ref().map(|item| mmcli::access_score(&item.0)).unwrap_or(0);
|
||
let qmi_access = qmi_cells.as_ref().map(|item| mmcli::access_score(&item.0)).unwrap_or(0);
|
||
let mm_neighbors = mm_cells.as_ref().map(|item| item.1.len()).unwrap_or(0);
|
||
let qmi_neighbors = qmi_cells.as_ref().map(|item| item.1.len()).unwrap_or(0);
|
||
if schemes.iter().any(|item| item.access) {
|
||
choice.access = prefer_richer(mm_access, qmi_access);
|
||
}
|
||
if schemes.iter().any(|item| item.neighbors) {
|
||
choice.neighbors = prefer_richer(mm_neighbors, qmi_neighbors);
|
||
}
|
||
if (qmi_ok && device.qmi && schemes.iter().any(|item| item.transport == "qmi" && item.apn))
|
||
|| (mm_ok && schemes.iter().any(|item| item.transport == "mm" && item.apn) && modem.is_some())
|
||
{
|
||
choice.apn = true;
|
||
}
|
||
}
|
||
choice
|
||
}
|
||
|
||
fn band_score(status: Option<BandStatus>) -> usize {
|
||
match status {
|
||
Some(status) if status.ready && !status.supported.is_empty() => 2,
|
||
Some(status) if !status.supported.is_empty() => 1,
|
||
_ => 0,
|
||
}
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn matches_scheme(scheme: &Scheme, device: &Device) -> bool {
|
||
if scheme.transport == "qmi" {
|
||
return device.qmi || scheme.plugins.iter().any(|needle| device.plugin.contains(needle));
|
||
}
|
||
if scheme.transport == "mm" {
|
||
return true;
|
||
}
|
||
false
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
struct Device {
|
||
plugin: String,
|
||
qmi: bool,
|
||
model: String,
|
||
compatible: Vec<String>,
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn scan_device() -> Device {
|
||
let plugin = mmcli::active_modem().ok().and_then(mmcli::modem_plugin).unwrap_or_default();
|
||
let qmi = std::fs::read_dir("/dev").ok().into_iter().flatten().flatten().any(|entry| {
|
||
let name = entry.file_name().to_string_lossy().to_string();
|
||
name.contains("qmi") || name.starts_with("cdc-wdm")
|
||
});
|
||
let model = fs::read("/proc/device-tree/model").map(|bytes| String::from_utf8_lossy(&bytes).trim_matches('\0').trim().to_string()).unwrap_or_default();
|
||
let compatible = fs::read("/proc/device-tree/compatible")
|
||
.map(|bytes| bytes.split(|byte| *byte == 0).filter(|item| !item.is_empty()).map(|item| String::from_utf8_lossy(item).to_string()).collect())
|
||
.unwrap_or_default();
|
||
Device { plugin, qmi, model, compatible }
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn fingerprint(device: &Device) -> String {
|
||
format!("{}\n{}\nqmi:{}", device.model, device.compatible.join("\n"), device.qmi)
|
||
}
|
||
|
||
fn catalog_text() -> (String, u64) {
|
||
let mut paths = Vec::new();
|
||
if let Ok(path) = std::env::var("MIFIPANEL_RADIO_SCHEMES") {
|
||
paths.push(PathBuf::from(path));
|
||
}
|
||
paths.push(PathBuf::from("/usr/local/share/mifipanel/radio-schemes.json"));
|
||
for path in paths {
|
||
if let Ok(text) = fs::read_to_string(&path) {
|
||
if parse_schemes(&text).is_ok() {
|
||
return (text.clone(), digest(&text));
|
||
}
|
||
eprintln!("网络方案清单 {} 无法解析,改用内置清单", path.display());
|
||
}
|
||
}
|
||
(EMBEDDED.to_string(), digest(EMBEDDED))
|
||
}
|
||
|
||
fn parse_schemes(text: &str) -> Result<Vec<Scheme>, ()> {
|
||
#[derive(Deserialize)]
|
||
struct File { schemes: Vec<Scheme> }
|
||
let file: File = serde_json::from_str(text).map_err(|_| ())?;
|
||
if file.schemes.is_empty() { return Err(()); }
|
||
Ok(file.schemes)
|
||
}
|
||
|
||
pub fn catalog_version() -> String {
|
||
version_in(&catalog_text().0)
|
||
}
|
||
|
||
pub fn install_catalog(text: &str) -> Result<String, String> {
|
||
parse_schemes(text).map_err(|_| "error.scheme".to_string())?;
|
||
let version = version_in(text);
|
||
let path = PathBuf::from("/usr/local/share/mifipanel/radio-schemes.json");
|
||
if let Some(parent) = path.parent() {
|
||
fs::create_dir_all(parent).map_err(|_| "error.scheme".to_string())?;
|
||
}
|
||
let tmp = path.with_extension("json.tmp");
|
||
fs::write(&tmp, text).map_err(|_| "error.scheme".to_string())?;
|
||
fs::rename(&tmp, &path).map_err(|_| "error.scheme".to_string())?;
|
||
Ok(version)
|
||
}
|
||
|
||
fn version_in(text: &str) -> String {
|
||
#[derive(Deserialize)]
|
||
struct File { #[serde(default)] version: String }
|
||
let version = serde_json::from_str::<File>(text).map(|file| file.version).unwrap_or_default();
|
||
let version = version.trim().to_string();
|
||
if version.is_empty() { "1.0".into() } else { version }
|
||
}
|
||
|
||
fn digest(text: &str) -> u64 {
|
||
let mut hash = 0xcbf2_9ce4_8422_2325u64;
|
||
for byte in text.as_bytes() {
|
||
hash ^= u64::from(*byte);
|
||
hash = hash.wrapping_mul(0x100_0000_01b3);
|
||
}
|
||
hash
|
||
}
|
||
|
||
fn choice_from_record(record: &Record) -> Choice {
|
||
Choice {
|
||
bands: Source::parse(&record.bands),
|
||
access: Source::parse(&record.access),
|
||
neighbors: Source::parse(&record.neighbors),
|
||
apn: record.apn,
|
||
}
|
||
}
|
||
|
||
fn load_record(root: &Path) -> Option<Record> {
|
||
serde_json::from_str(&fs::read_to_string(root.join("radio-scheme.json")).ok()?).ok()
|
||
}
|
||
|
||
fn save_record(root: &Path, fingerprint: &str, catalog: u64, choice: &Choice) {
|
||
let record = Record {
|
||
fingerprint: fingerprint.to_string(),
|
||
catalog,
|
||
bands: choice.bands.as_str().into(),
|
||
access: choice.access.as_str().into(),
|
||
neighbors: choice.neighbors.as_str().into(),
|
||
apn: choice.apn,
|
||
};
|
||
if fs::create_dir_all(root).is_err() { return; }
|
||
if let Ok(text) = serde_json::to_vec_pretty(&record) {
|
||
let _ = crate::store::write_atomic(&root.join("radio-scheme.json"), text.as_ref());
|
||
}
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn mm_apn_get(modem: u32) -> Result<Apn, String> {
|
||
let text = mmcli_kv(modem)?;
|
||
let mut apn = field(&text, "modem.3gpp.eps.initial-bearer.settings.apn");
|
||
let mut ip = field(&text, "modem.3gpp.eps.initial-bearer.settings.ip-type");
|
||
let mut user = field(&text, "modem.3gpp.eps.initial-bearer.settings.user");
|
||
let mut password = field(&text, "modem.3gpp.eps.initial-bearer.settings.password");
|
||
if apn == "--" { apn.clear(); }
|
||
if user == "--" { user.clear(); }
|
||
if password == "--" { password.clear(); }
|
||
if ip.is_empty() || ip == "--" { ip = "ipv4v6".into(); }
|
||
Ok(Apn { apn, ip, user, password, auth: "none".into() })
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn mm_apn_set(modem: u32, apn: &str, ip: &str, user: &str, password: &str, auth: &str) -> Result<(), String> {
|
||
let mut spec = format!("apn={apn},ip-type={ip},allowed-auth={}", auth_token(auth));
|
||
if !user.is_empty() {
|
||
spec.push_str(&format!(",user={}", quoted(user)));
|
||
}
|
||
if !password.is_empty() {
|
||
spec.push_str(&format!(",password={}", quoted(password)));
|
||
}
|
||
let text = mmcli_set(modem, &format!("--3gpp-set-initial-eps-bearer-settings={spec}"))?;
|
||
if text.to_ascii_lowercase().contains("error") {
|
||
eprintln!("apn set failed: {}", text.trim());
|
||
return Err("error.apn.fail".into());
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn qmi_node() -> Option<String> {
|
||
let mut found = Vec::new();
|
||
for entry in std::fs::read_dir("/dev").ok()?.flatten() {
|
||
let name = entry.file_name().to_string_lossy().to_string();
|
||
if name.contains("qmi") || name.starts_with("cdc-wdm") {
|
||
found.push(format!("/dev/{name}"));
|
||
}
|
||
}
|
||
found.sort();
|
||
found.into_iter().next()
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn qmi_apn_get() -> Option<Apn> {
|
||
let node = qmi_node()?;
|
||
let mut cmd = std::process::Command::new("qmicli");
|
||
cmd.args(["-d", &node, "--device-open-proxy", "--wds-get-profile-list=3gpp"]);
|
||
let output = mmcli::output_within(cmd, std::time::Duration::from_secs(12)).ok()?;
|
||
let text = format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));
|
||
if !output.status.success() { return None; }
|
||
// 保存时改的是 1 号配置,读也只读 1 号,不能拿列表里排在前面的别的配置来显示。
|
||
let text = profile_one(&text);
|
||
let mut apn = quoted_after(&text, "APN:");
|
||
let pdp = quoted_after(&text, "PDP type:");
|
||
let user = quoted_after(&text, "Username:");
|
||
let password = quoted_exact(&text, "Password:");
|
||
let auth = quoted_after(&text, "Auth:");
|
||
if apn == "''" { apn.clear(); }
|
||
let ip = match pdp.as_str() {
|
||
"ipv4" => "ipv4",
|
||
"ipv6" => "ipv6",
|
||
_ => "ipv4v6",
|
||
};
|
||
// 两种都开时 qmicli 印的是 “pap, chap”。认不出来的话页面会显示成“无”,再点保存就把认证清掉了。
|
||
let auth = match (auth.contains("pap") || auth == "both", auth.contains("chap") || auth == "both") {
|
||
(true, true) => "pap-chap",
|
||
(true, false) => "pap",
|
||
(false, true) => "chap",
|
||
_ => "none",
|
||
};
|
||
Some(Apn { apn, ip: ip.into(), user, password, auth: auth.into() })
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn qmi_apn_set(apn: &str, ip: &str, user: &str, password: &str, auth: &str) -> Result<(), String> {
|
||
let node = qmi_node().ok_or_else(|| "error.apn.modem".to_string())?;
|
||
let pdp = match ip {
|
||
"ipv4" => "IP",
|
||
"ipv6" => "IPV6",
|
||
_ => "IPV4V6",
|
||
};
|
||
let qauth = match auth {
|
||
"pap" => "PAP",
|
||
"chap" => "CHAP",
|
||
"pap-chap" => "BOTH",
|
||
_ => "NONE",
|
||
};
|
||
// 用户名和密码即使是空的也要写进去,否则改成“无认证”后旧的用户名密码还留在基带里。
|
||
// 值用双引号包住:不包的话,带空格的密码会让 qmicli 直接报错。
|
||
let spec = format!("3gpp,1,apn={apn},pdp-type={pdp},auth={qauth},username={},password={}", quoted(user), quoted(password));
|
||
let mut cmd = std::process::Command::new("qmicli");
|
||
cmd.args(["-d", &node, "--device-open-proxy", &format!("--wds-modify-profile={spec}")]);
|
||
let output = mmcli::output_within(cmd, std::time::Duration::from_secs(15)).map_err(|_| "error.apn.fail".to_string())?;
|
||
let text = format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));
|
||
if output.status.success() && !text.to_ascii_lowercase().contains("error") {
|
||
Ok(())
|
||
} else {
|
||
eprintln!("qmi apn set failed: {}", text.trim());
|
||
Err("error.apn.fail".into())
|
||
}
|
||
}
|
||
|
||
/// 配置列表里 `[1]` 那一段。找不到这一段就原样返回。
|
||
fn profile_one(text: &str) -> String {
|
||
let mut out = String::new();
|
||
let mut inside = false;
|
||
for line in text.lines() {
|
||
let trimmed = line.trim_start();
|
||
if trimmed.starts_with('[') {
|
||
inside = trimmed.starts_with("[1]");
|
||
continue;
|
||
}
|
||
if inside {
|
||
out.push_str(line);
|
||
out.push('\n');
|
||
}
|
||
}
|
||
if out.is_empty() { text.to_string() } else { out }
|
||
}
|
||
|
||
fn quoted_after(text: &str, label: &str) -> String {
|
||
for line in text.lines() {
|
||
let line = line.trim();
|
||
let Some(rest) = line.strip_prefix(label) else { continue };
|
||
return rest.trim().trim_matches('\'').trim().to_string();
|
||
}
|
||
String::new()
|
||
}
|
||
|
||
/// 密码里可以有空格和单引号,只去掉 qmicli 包在外面的那一对单引号,里面原样保留。
|
||
fn quoted_exact(text: &str, label: &str) -> String {
|
||
for line in text.lines() {
|
||
let Some(rest) = line.trim_start().strip_prefix(label) else { continue };
|
||
let rest = rest.strip_prefix(' ').unwrap_or(rest).trim_end_matches(['\r', '\n']);
|
||
return match rest.strip_prefix('\'').and_then(|inner| inner.strip_suffix('\'')) {
|
||
Some(inner) => inner.to_string(),
|
||
None => rest.trim().to_string(),
|
||
};
|
||
}
|
||
String::new()
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn mmcli_kv(modem: u32) -> Result<String, String> {
|
||
let mut cmd = std::process::Command::new("mmcli");
|
||
cmd.args(["-m", &modem.to_string(), "-K"]);
|
||
let output = mmcli::output_within(cmd, std::time::Duration::from_secs(15)).map_err(|_| "error.apn.modem".to_string())?;
|
||
let text = format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));
|
||
if !output.status.success() {
|
||
return Err("error.apn.modem".into());
|
||
}
|
||
Ok(text)
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn mmcli_set(modem: u32, arg: &str) -> Result<String, String> {
|
||
let mut cmd = std::process::Command::new("mmcli");
|
||
cmd.args(["-m", &modem.to_string(), arg]);
|
||
let output = mmcli::output_within(cmd, std::time::Duration::from_secs(20)).map_err(|_| "error.apn.fail".to_string())?;
|
||
Ok(format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)))
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn field(text: &str, key: &str) -> String {
|
||
for line in text.lines() {
|
||
let Some((name, value)) = line.split_once(':') else { continue };
|
||
if name.trim() == key {
|
||
return value.trim().to_string();
|
||
}
|
||
}
|
||
String::new()
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn vendor_wins_only_when_it_has_more() {
|
||
assert_eq!(prefer_richer(2, 2), Source::Mm);
|
||
assert_eq!(prefer_richer(1, 2), Source::Qmi);
|
||
assert_eq!(prefer_richer(1, 0), Source::Mm);
|
||
assert_eq!(prefer_richer(0, 0), Source::None);
|
||
}
|
||
|
||
#[test]
|
||
fn apn_rejects_separator_characters() {
|
||
assert!(validate_apn("cmnet", "ipv4v6", "", "", "none").is_ok());
|
||
assert_eq!(validate_apn("cm,net", "ipv4v6", "", "", "none"), Err("error.apn.name".into()));
|
||
assert!(validate_apn("cmnet", "ipv4", "user name", "it's, a=b", "pap").is_ok());
|
||
assert_eq!(validate_apn("cmnet", "ipv4", "user", "a\"b", "pap"), Err("error.apn.secret".into()));
|
||
assert_eq!(validate_apn("cm net", "ipv4", "", "", "none"), Err("error.apn.name".into()));
|
||
assert_eq!(validate_apn("'cmnet", "ipv4", "", "", "none"), Err("error.apn.name".into()));
|
||
let list = "Profile list retrieved:\n\t[2] 3gpp - ims\n\t\tAPN: 'ims'\n\t\tAuth: 'none'\n\t[1] 3gpp - profile1\n\t\tAPN: 'cmnet'\n\t\tPDP type: 'ipv4'\n\t\tUsername: 'u'\n\t\tAuth: 'pap, chap'\n";
|
||
let first = profile_one(list);
|
||
assert_eq!(quoted_after(&first, "APN:"), "cmnet");
|
||
assert_eq!(quoted_after(&first, "Auth:"), "pap, chap");
|
||
assert_eq!(validate_apn("cmnet", "ipv5", "", "", "none"), Err("error.apn.ip".into()));
|
||
}
|
||
|
||
#[test]
|
||
fn profile_password_is_read_exactly() {
|
||
let text = "\t\tUsername: 'probeuser'\n\t\tPassword: ' it's a pw '\n\t\tAuth: 'none'\n";
|
||
assert_eq!(quoted_exact(text, "Password:"), " it's a pw ");
|
||
assert_eq!(quoted_exact("\t\tPassword: ''\n", "Password:"), "");
|
||
assert_eq!(quoted_exact("\t\tUsername: ''\n", "Password:"), "");
|
||
}
|
||
|
||
#[test]
|
||
fn embedded_catalog_parses() {
|
||
let schemes = parse_schemes(EMBEDDED).unwrap();
|
||
assert!(schemes.iter().any(|item| item.id == "mm-generic" && item.apn));
|
||
assert!(schemes.iter().any(|item| item.id == "qcom-qmi-nas" && item.bands && item.apn));
|
||
}
|
||
}
|