From e733b38ab7c713f3ecddd68e137ce49d1f141e82 Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Sun, 19 Apr 2026 00:40:00 +0800 Subject: [PATCH] refactor: backport xmltree parser migration to 2.3.x --- Cargo.lock | 8 +-- Cargo.toml | 2 +- crates/gpapi/Cargo.toml | 2 +- crates/gpapi/src/gateway/hip.rs | 29 ++++---- crates/gpapi/src/gateway/login.rs | 19 +++--- crates/gpapi/src/gateway/parse_gateways.rs | 47 ++++++------- crates/gpapi/src/portal/config.rs | 17 +++-- crates/gpapi/src/portal/prelogin.rs | 49 ++++++-------- crates/gpapi/src/utils/xml.rs | 79 +++++++++++++++++----- 9 files changed, 138 insertions(+), 114 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6faf9fc..4d59077 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1598,7 +1598,6 @@ dependencies = [ "redact-engine", "regex", "reqwest", - "roxmltree", "serde", "serde_json", "serde_urlencoded", @@ -1616,6 +1615,7 @@ dependencies = [ "webbrowser", "which", "whoami", + "xmltree", ] [[package]] @@ -3788,12 +3788,6 @@ dependencies = [ "winreg 0.50.0", ] -[[package]] -name = "roxmltree" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" - [[package]] name = "rustc_version" version = "0.4.1" diff --git a/Cargo.toml b/Cargo.toml index 2d8384c..c0cb48e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,7 +31,7 @@ regex = "1" reqwest = { version = "0.11", features = ["native-tls-vendored", "json"] } openssl = "0.10" pem = "3" -roxmltree = "0.20" +xmltree = "0.11" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" sysinfo = "0.30" diff --git a/crates/gpapi/Cargo.toml b/crates/gpapi/Cargo.toml index 3e3754f..d04e191 100644 --- a/crates/gpapi/Cargo.toml +++ b/crates/gpapi/Cargo.toml @@ -12,7 +12,7 @@ log.workspace = true reqwest.workspace = true openssl.workspace = true pem.workspace = true -roxmltree.workspace = true +xmltree.workspace = true serde.workspace = true specta.workspace = true specta-macros.workspace = true diff --git a/crates/gpapi/src/gateway/hip.rs b/crates/gpapi/src/gateway/hip.rs index 1620002..bff6af3 100644 --- a/crates/gpapi/src/gateway/hip.rs +++ b/crates/gpapi/src/gateway/hip.rs @@ -2,9 +2,13 @@ use std::collections::HashMap; use log::{info, warn}; use reqwest::Client; -use roxmltree::Document; +use xmltree::Element; -use crate::{gp_params::GpParams, process::hip_launcher::HipLauncher, utils::normalize_server}; +use crate::{ + gp_params::GpParams, + process::hip_launcher::HipLauncher, + utils::{normalize_server, xml::ElementExt}, +}; struct HipReporter<'a> { server: String, @@ -65,16 +69,12 @@ impl HipReporter<'_> { let res = self.client.post(&config_url).form(¶ms).send().await?; let res_xml = res.error_for_status()?.text().await?; - let doc = Document::parse(&res_xml)?; - - // Get - let ip = doc - .descendants() - .find(|n| n.has_tag_name("ip-address")) - .and_then(|n| n.text()) + let root = Element::parse(res_xml.as_bytes())?; + let ip = root + .descendant_text("ip-address") .ok_or_else(|| anyhow::anyhow!("ip-address not found"))?; - Ok(ip.to_string()) + Ok(ip) } async fn check_hip(&self, client_ip: &str) -> anyhow::Result { @@ -122,12 +122,9 @@ impl HipReporter<'_> { } fn is_hip_needed(res_xml: &str) -> anyhow::Result { - let doc = Document::parse(res_xml)?; - - let hip_needed = doc - .descendants() - .find(|n| n.has_tag_name("hip-report-needed")) - .and_then(|n| n.text()) + let root = Element::parse(res_xml.as_bytes())?; + let hip_needed = root + .descendant_text("hip-report-needed") .ok_or_else(|| anyhow::anyhow!("hip-report-needed not found"))?; Ok(hip_needed == "yes") diff --git a/crates/gpapi/src/gateway/login.rs b/crates/gpapi/src/gateway/login.rs index 0188e22..ec66bef 100644 --- a/crates/gpapi/src/gateway/login.rs +++ b/crates/gpapi/src/gateway/login.rs @@ -1,14 +1,14 @@ use anyhow::bail; use log::{info, warn}; use reqwest::Client; -use roxmltree::Document; use urlencoding::encode; +use xmltree::Element; use crate::{ credential::Credential, error::PortalError, gp_params::GpParams, - utils::{normalize_server, parse_gp_response, remove_url_scheme}, + utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, }; pub enum GatewayLogin { @@ -52,18 +52,17 @@ pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParam return Ok(GatewayLogin::Mfa(message, input_str)); } - let doc = Document::parse(&res)?; - - let cookie = build_gateway_token(&doc, gp_params.computer())?; + let root = Element::parse(res.as_bytes())?; + let cookie = build_gateway_token(&root, gp_params.computer())?; Ok(GatewayLogin::Cookie(cookie)) } -fn build_gateway_token(doc: &Document, computer: &str) -> anyhow::Result { - let args = doc - .descendants() - .filter(|n| n.has_tag_name("argument")) - .map(|n| n.text().unwrap_or("").to_string()) +fn build_gateway_token(root: &Element, computer: &str) -> anyhow::Result { + let args = root + .descendants("argument") + .iter() + .map(|element| element.get_text().unwrap_or_default().to_string()) .collect::>(); let params = [ diff --git a/crates/gpapi/src/gateway/parse_gateways.rs b/crates/gpapi/src/gateway/parse_gateways.rs index 9ed8d41..c56ae7b 100644 --- a/crates/gpapi/src/gateway/parse_gateways.rs +++ b/crates/gpapi/src/gateway/parse_gateways.rs @@ -1,62 +1,59 @@ use log::info; -use roxmltree::Node; +use xmltree::Element; -use crate::utils::xml::NodeExt; +use crate::utils::xml::ElementExt; use super::{Gateway, PriorityRule}; -pub(crate) fn parse_gateways(node: &Node, prefer_internal: bool) -> Option> { - let node_gateways = node.find_descendant("gateways")?; +pub(crate) fn parse_gateways(root: &Element, prefer_internal: bool) -> Option> { + let node_gateways = root.descendant("gateways")?; let internal_gateway_list = if prefer_internal { info!("Try to parse the internal gateways..."); - node_gateways.find_descendant("internal").and_then(|n| n.find_child("list")) + node_gateways.descendant("internal").and_then(|node| node.child("list")) } else { None }; let gateway_list = internal_gateway_list.or_else(|| { info!("Try to parse the external gateways..."); - node_gateways.find_descendant("external").and_then(|n| n.find_child("list")) + node_gateways.descendant("external").and_then(|node| node.child("list")) })?; let gateways = gateway_list - .children() - .filter_map(|gateway_item| { - if !gateway_item.has_tag_name("entry") { - return None; - } - let address = gateway_item.attribute("name").unwrap_or_default().to_string(); - let name = gateway_item.child_text("description").unwrap_or_default().to_string(); + .children("entry") + .iter() + .map(|gateway_item| { + let address = gateway_item.attr("name").unwrap_or_default().to_string(); + let name = gateway_item.child_text("description").unwrap_or_default(); let priority = gateway_item .child_text("priority") .and_then(|s| s.parse().ok()) .unwrap_or(u32::MAX); let priority_rules = gateway_item - .find_child("priority-rule") - .map(|n| { - n.children() - .filter_map(|n| { - if !n.has_tag_name("entry") { - return None; - } - let name = n.attribute("name").unwrap_or_default().to_string(); - let priority: u32 = n + .child("priority-rule") + .map(|node| { + node + .children("entry") + .iter() + .map(|entry| { + let name = entry.attr("name").unwrap_or_default().to_string(); + let priority: u32 = entry .child_text("priority") .and_then(|s| s.parse().ok()) .unwrap_or(u32::MAX); - Some(PriorityRule { name, priority }) + PriorityRule { name, priority } }) .collect() }) .unwrap_or_default(); - Some(Gateway { + Gateway { name, address, priority, priority_rules, - }) + } }) .collect(); diff --git a/crates/gpapi/src/portal/config.rs b/crates/gpapi/src/portal/config.rs index 3db25d6..7d5b071 100644 --- a/crates/gpapi/src/portal/config.rs +++ b/crates/gpapi/src/portal/config.rs @@ -2,16 +2,16 @@ use anyhow::bail; use dns_lookup::lookup_addr; use log::{debug, info, warn}; use reqwest::{Client, StatusCode}; -use roxmltree::{Document, Node}; use serde::Serialize; use specta::Type; +use xmltree::Element; use crate::{ credential::{AuthCookieCredential, Credential}, error::PortalError, gateway::{parse_gateways, Gateway}, gp_params::GpParams, - utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::NodeExt}, + utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, }; #[derive(Debug, Serialize, Type)] @@ -137,14 +137,13 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara debug!("Portal config response: {}", res_xml); - let doc = Document::parse(&res_xml).map_err(|e| PortalError::ConfigError(e.to_string()))?; - let root = doc.root(); + let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?; let mut ihd_enabled = false; let mut prefer_internal = false; - if let Some(ihd_node) = root.find_descendant("internal-host-detection") { + if let Some(ihd_node) = root.descendant("internal-host-detection") { ihd_enabled = true; - prefer_internal = internal_host_detect(&ihd_node) + prefer_internal = internal_host_detect(ihd_node) } let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| { @@ -164,16 +163,16 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara Ok(PortalConfig { portal: server.to_string(), - auth_cookie: AuthCookieCredential::new(cred.username(), user_auth_cookie, prelogon_user_auth_cookie), + auth_cookie: AuthCookieCredential::new(cred.username(), &user_auth_cookie, &prelogon_user_auth_cookie), config_cred: cred.clone(), gateways, - config_digest: config_digest.map(|s| s.to_string()), + config_digest, internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None }, }) } // Perform DNS lookup and compare the result with the expected hostname -fn internal_host_detect(node: &Node) -> bool { +fn internal_host_detect(node: &Element) -> bool { let ip_info = [ (node.child_text("ip-address"), node.child_text("host")), (node.child_text("ipv6-address"), node.child_text("ipv6-host")), diff --git a/crates/gpapi/src/portal/prelogin.rs b/crates/gpapi/src/portal/prelogin.rs index 4c10d2a..a99bd2d 100644 --- a/crates/gpapi/src/portal/prelogin.rs +++ b/crates/gpapi/src/portal/prelogin.rs @@ -1,14 +1,14 @@ use anyhow::{anyhow, bail}; use log::{info, warn}; use reqwest::{Client, StatusCode}; -use roxmltree::Document; use serde::Serialize; use specta::Type; +use xmltree::Element; use crate::{ error::PortalError, gp_params::GpParams, - utils::{base64, normalize_server, parse_gp_response, xml::NodeExt}, + utils::{base64, normalize_server, parse_gp_response, xml::ElementExt}, }; const REQUIRED_PARAMS: [&str; 8] = [ @@ -147,32 +147,30 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result anyhow::Result { - let doc = Document::parse(res_xml)?; - let root = doc.root(); + let root = Element::parse(res_xml.as_bytes())?; let status = root .descendant_text("status") .ok_or_else(|| anyhow::anyhow!("Prelogin response does not contain status element"))?; // Check the status of the prelogin response if status.to_uppercase() != "SUCCESS" { - let msg = root.descendant_text("msg").unwrap_or("Unknown error"); + let msg = root + .descendant_text("msg") + .unwrap_or_else(|| "Unknown error".to_string()); bail!("{}", msg) } - let region = root - .descendant_text("region") - .unwrap_or_else(|| { - info!("Prelogin response does not contain region element"); - "Unknown" - }) - .to_string(); + let region = root.descendant_text("region").unwrap_or_else(|| { + info!("Prelogin response does not contain region element"); + "Unknown".to_string() + }); let saml_method = root.descendant_text("saml-auth-method"); let saml_request = root.descendant_text("saml-request"); let saml_default_browser = root.descendant_text("saml-default-browser"); // Check if the prelogin response is SAML if saml_method.is_some() && saml_request.is_some() { - let saml_request = base64::decode_to_string(saml_request.unwrap())?; + let saml_request = base64::decode_to_string(&saml_request.unwrap())?; let support_default_browser = saml_default_browser.map(|s| s.to_lowercase() == "yes").unwrap_or(false); let saml_prelogin = SamlPrelogin { @@ -185,25 +183,18 @@ fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result { return Ok(Prelogin::Saml(saml_prelogin)); } - let label_username = root - .descendant_text("username-label") - .unwrap_or_else(|| { - info!("Username label has no value, using default"); - "Username" - }) - .to_string(); - let label_password = root - .descendant_text("password-label") - .unwrap_or_else(|| { - info!("Password label has no value, using default"); - "Password" - }) - .to_string(); + let label_username = root.descendant_text("username-label").unwrap_or_else(|| { + info!("Username label has no value, using default"); + "Username".to_string() + }); + let label_password = root.descendant_text("password-label").unwrap_or_else(|| { + info!("Password label has no value, using default"); + "Password".to_string() + }); let auth_message = root .descendant_text("authentication-message") - .unwrap_or("Please enter the login credentials") - .to_string(); + .unwrap_or_else(|| "Please enter the login credentials".to_string()); let standard_prelogin = StandardPrelogin { region, is_gateway, diff --git a/crates/gpapi/src/utils/xml.rs b/crates/gpapi/src/utils/xml.rs index 2885130..3f2a79a 100644 --- a/crates/gpapi/src/utils/xml.rs +++ b/crates/gpapi/src/utils/xml.rs @@ -1,27 +1,74 @@ -use roxmltree::Node; +use xmltree::Element; -pub(crate) trait NodeExt<'a> { - fn find_descendant(&self, name: &str) -> Option>; - fn descendant_text(&self, name: &str) -> Option<&'a str>; - - fn find_child(&self, name: &str) -> Option>; - fn child_text(&self, name: &str) -> Option<&'a str>; +pub(crate) trait ElementExt { + fn descendants(&self, name: &str) -> Vec<&Element>; + fn descendant(&self, name: &str) -> Option<&Element>; + fn descendant_text(&self, name: &str) -> Option; + fn child(&self, name: &str) -> Option<&Element>; + fn child_text(&self, name: &str) -> Option; + fn children(&self, name: &str) -> Vec<&Element>; + fn attr(&self, name: &str) -> Option<&str>; } -impl<'a> NodeExt<'a> for Node<'a, 'a> { - fn find_descendant(&self, name: &str) -> Option> { - self.descendants().find(|n| n.has_tag_name(name)) +impl ElementExt for Element { + fn descendants(&self, name: &str) -> Vec<&Element> { + let mut results = Vec::new(); + + if self.name == name { + results.push(self); + } + + for child in &self.children { + if let Some(element) = child.as_element() { + results.extend(element.descendants(name)); + } + } + + results } - fn descendant_text(&self, name: &str) -> Option<&'a str> { - self.find_descendant(name).and_then(|node| node.text()) + fn descendant(&self, name: &str) -> Option<&Element> { + if self.name == name { + return Some(self); + } + + for child in &self.children { + if let Some(element) = child.as_element() { + if let Some(found) = element.descendant(name) { + return Some(found); + } + } + } + + None } - fn find_child(&self, name: &str) -> Option> { - self.children().find(|n| n.has_tag_name(name)) + fn descendant_text(&self, name: &str) -> Option { + self + .descendant(name) + .and_then(|element| element.get_text().map(|s| s.to_string())) } - fn child_text(&self, name: &str) -> Option<&'a str> { - self.find_child(name).and_then(|node| node.text()) + fn child(&self, name: &str) -> Option<&Element> { + self.get_child(name) + } + + fn child_text(&self, name: &str) -> Option { + self + .get_child(name) + .and_then(|element| element.get_text().map(|s| s.to_string())) + } + + fn children(&self, name: &str) -> Vec<&Element> { + self + .children + .iter() + .filter_map(|child| child.as_element()) + .filter(|element| element.name == name) + .collect() + } + + fn attr(&self, name: &str) -> Option<&str> { + self.attributes.get(name).map(|s| s.as_str()) } }