refactor: backport xmltree parser migration to 2.3.x

This commit is contained in:
Kevin Yue committed 2026-04-19 00:40:00 +08:00
1 parent c206e72885
commit e733b38ab7
9 files changed
+138 -114

No files matched your search

Generated
+1 -7
View File
@@ -1598,7 +1598,6 @@ dependencies = [
"redact-engine", "redact-engine",
"regex", "regex",
"reqwest", "reqwest",
"roxmltree",
"serde", "serde",
"serde_json", "serde_json",
"serde_urlencoded", "serde_urlencoded",
@@ -1616,6 +1615,7 @@ dependencies = [
"webbrowser", "webbrowser",
"which", "which",
"whoami", "whoami",
"xmltree",
] ]
[[package]] [[package]]
@@ -3788,12 +3788,6 @@ dependencies = [
"winreg 0.50.0", "winreg 0.50.0",
] ]
[[package]]
name = "roxmltree"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
[[package]] [[package]]
name = "rustc_version" name = "rustc_version"
version = "0.4.1" version = "0.4.1"
+1 -1
View File
@@ -31,7 +31,7 @@ regex = "1"
reqwest = { version = "0.11", features = ["native-tls-vendored", "json"] } reqwest = { version = "0.11", features = ["native-tls-vendored", "json"] }
openssl = "0.10" openssl = "0.10"
pem = "3" pem = "3"
roxmltree = "0.20" xmltree = "0.11"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
sysinfo = "0.30" sysinfo = "0.30"
+1 -1
View File
@@ -12,7 +12,7 @@ log.workspace = true
reqwest.workspace = true reqwest.workspace = true
openssl.workspace = true openssl.workspace = true
pem.workspace = true pem.workspace = true
roxmltree.workspace = true xmltree.workspace = true
serde.workspace = true serde.workspace = true
specta.workspace = true specta.workspace = true
specta-macros.workspace = true specta-macros.workspace = true
+13 -16
View File
@@ -2,9 +2,13 @@ use std::collections::HashMap;
use log::{info, warn}; use log::{info, warn};
use reqwest::Client; 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> { struct HipReporter<'a> {
server: String, server: String,
@@ -65,16 +69,12 @@ impl HipReporter<'_> {
let res = self.client.post(&config_url).form(&params).send().await?; let res = self.client.post(&config_url).form(&params).send().await?;
let res_xml = res.error_for_status()?.text().await?; let res_xml = res.error_for_status()?.text().await?;
let doc = Document::parse(&res_xml)?; let root = Element::parse(res_xml.as_bytes())?;
let ip = root
// Get <ip-address> .descendant_text("ip-address")
let ip = doc
.descendants()
.find(|n| n.has_tag_name("ip-address"))
.and_then(|n| n.text())
.ok_or_else(|| anyhow::anyhow!("ip-address not found"))?; .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<bool> { async fn check_hip(&self, client_ip: &str) -> anyhow::Result<bool> {
@@ -122,12 +122,9 @@ impl HipReporter<'_> {
} }
fn is_hip_needed(res_xml: &str) -> anyhow::Result<bool> { fn is_hip_needed(res_xml: &str) -> anyhow::Result<bool> {
let doc = Document::parse(res_xml)?; let root = Element::parse(res_xml.as_bytes())?;
let hip_needed = root
let hip_needed = doc .descendant_text("hip-report-needed")
.descendants()
.find(|n| n.has_tag_name("hip-report-needed"))
.and_then(|n| n.text())
.ok_or_else(|| anyhow::anyhow!("hip-report-needed not found"))?; .ok_or_else(|| anyhow::anyhow!("hip-report-needed not found"))?;
Ok(hip_needed == "yes") Ok(hip_needed == "yes")
+9 -10
View File
@@ -1,14 +1,14 @@
use anyhow::bail; use anyhow::bail;
use log::{info, warn}; use log::{info, warn};
use reqwest::Client; use reqwest::Client;
use roxmltree::Document;
use urlencoding::encode; use urlencoding::encode;
use xmltree::Element;
use crate::{ use crate::{
credential::Credential, credential::Credential,
error::PortalError, error::PortalError,
gp_params::GpParams, 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 { 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)); return Ok(GatewayLogin::Mfa(message, input_str));
} }
let doc = Document::parse(&res)?; let root = Element::parse(res.as_bytes())?;
let cookie = build_gateway_token(&root, gp_params.computer())?;
let cookie = build_gateway_token(&doc, gp_params.computer())?;
Ok(GatewayLogin::Cookie(cookie)) Ok(GatewayLogin::Cookie(cookie))
} }
fn build_gateway_token(doc: &Document, computer: &str) -> anyhow::Result<String> { fn build_gateway_token(root: &Element, computer: &str) -> anyhow::Result<String> {
let args = doc let args = root
.descendants() .descendants("argument")
.filter(|n| n.has_tag_name("argument")) .iter()
.map(|n| n.text().unwrap_or("").to_string()) .map(|element| element.get_text().unwrap_or_default().to_string())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let params = [ let params = [
+22 -25
View File
@@ -1,62 +1,59 @@
use log::info; use log::info;
use roxmltree::Node; use xmltree::Element;
use crate::utils::xml::NodeExt; use crate::utils::xml::ElementExt;
use super::{Gateway, PriorityRule}; use super::{Gateway, PriorityRule};
pub(crate) fn parse_gateways(node: &Node, prefer_internal: bool) -> Option<Vec<Gateway>> { pub(crate) fn parse_gateways(root: &Element, prefer_internal: bool) -> Option<Vec<Gateway>> {
let node_gateways = node.find_descendant("gateways")?; let node_gateways = root.descendant("gateways")?;
let internal_gateway_list = if prefer_internal { let internal_gateway_list = if prefer_internal {
info!("Try to parse the internal gateways..."); 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 { } else {
None None
}; };
let gateway_list = internal_gateway_list.or_else(|| { let gateway_list = internal_gateway_list.or_else(|| {
info!("Try to parse the external gateways..."); 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 let gateways = gateway_list
.children() .children("entry")
.filter_map(|gateway_item| { .iter()
if !gateway_item.has_tag_name("entry") { .map(|gateway_item| {
return None; let address = gateway_item.attr("name").unwrap_or_default().to_string();
} let name = gateway_item.child_text("description").unwrap_or_default();
let address = gateway_item.attribute("name").unwrap_or_default().to_string();
let name = gateway_item.child_text("description").unwrap_or_default().to_string();
let priority = gateway_item let priority = gateway_item
.child_text("priority") .child_text("priority")
.and_then(|s| s.parse().ok()) .and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX); .unwrap_or(u32::MAX);
let priority_rules = gateway_item let priority_rules = gateway_item
.find_child("priority-rule") .child("priority-rule")
.map(|n| { .map(|node| {
n.children() node
.filter_map(|n| { .children("entry")
if !n.has_tag_name("entry") { .iter()
return None; .map(|entry| {
} let name = entry.attr("name").unwrap_or_default().to_string();
let name = n.attribute("name").unwrap_or_default().to_string(); let priority: u32 = entry
let priority: u32 = n
.child_text("priority") .child_text("priority")
.and_then(|s| s.parse().ok()) .and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX); .unwrap_or(u32::MAX);
Some(PriorityRule { name, priority }) PriorityRule { name, priority }
}) })
.collect() .collect()
}) })
.unwrap_or_default(); .unwrap_or_default();
Some(Gateway { Gateway {
name, name,
address, address,
priority, priority,
priority_rules, priority_rules,
}) }
}) })
.collect(); .collect();
+8 -9
View File
@@ -2,16 +2,16 @@ use anyhow::bail;
use dns_lookup::lookup_addr; use dns_lookup::lookup_addr;
use log::{debug, info, warn}; use log::{debug, info, warn};
use reqwest::{Client, StatusCode}; use reqwest::{Client, StatusCode};
use roxmltree::{Document, Node};
use serde::Serialize; use serde::Serialize;
use specta::Type; use specta::Type;
use xmltree::Element;
use crate::{ use crate::{
credential::{AuthCookieCredential, Credential}, credential::{AuthCookieCredential, Credential},
error::PortalError, error::PortalError,
gateway::{parse_gateways, Gateway}, gateway::{parse_gateways, Gateway},
gp_params::GpParams, 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)] #[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); debug!("Portal config response: {}", res_xml);
let doc = Document::parse(&res_xml).map_err(|e| PortalError::ConfigError(e.to_string()))?; let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
let root = doc.root();
let mut ihd_enabled = false; let mut ihd_enabled = false;
let mut prefer_internal = 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; 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(|| { 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 { Ok(PortalConfig {
portal: server.to_string(), 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(), config_cred: cred.clone(),
gateways, gateways,
config_digest: config_digest.map(|s| s.to_string()), config_digest,
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None }, internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
}) })
} }
// Perform DNS lookup and compare the result with the expected hostname // 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 = [ let ip_info = [
(node.child_text("ip-address"), node.child_text("host")), (node.child_text("ip-address"), node.child_text("host")),
(node.child_text("ipv6-address"), node.child_text("ipv6-host")), (node.child_text("ipv6-address"), node.child_text("ipv6-host")),
+20 -29
View File
@@ -1,14 +1,14 @@
use anyhow::{anyhow, bail}; use anyhow::{anyhow, bail};
use log::{info, warn}; use log::{info, warn};
use reqwest::{Client, StatusCode}; use reqwest::{Client, StatusCode};
use roxmltree::Document;
use serde::Serialize; use serde::Serialize;
use specta::Type; use specta::Type;
use xmltree::Element;
use crate::{ use crate::{
error::PortalError, error::PortalError,
gp_params::GpParams, 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] = [ const REQUIRED_PARAMS: [&str; 8] = [
@@ -147,32 +147,30 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prel
} }
fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> { fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
let doc = Document::parse(res_xml)?; let root = Element::parse(res_xml.as_bytes())?;
let root = doc.root();
let status = root let status = root
.descendant_text("status") .descendant_text("status")
.ok_or_else(|| anyhow::anyhow!("Prelogin response does not contain status element"))?; .ok_or_else(|| anyhow::anyhow!("Prelogin response does not contain status element"))?;
// Check the status of the prelogin response // Check the status of the prelogin response
if status.to_uppercase() != "SUCCESS" { 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) bail!("{}", msg)
} }
let region = root let region = root.descendant_text("region").unwrap_or_else(|| {
.descendant_text("region") info!("Prelogin response does not contain region element");
.unwrap_or_else(|| { "Unknown".to_string()
info!("Prelogin response does not contain region element"); });
"Unknown"
})
.to_string();
let saml_method = root.descendant_text("saml-auth-method"); let saml_method = root.descendant_text("saml-auth-method");
let saml_request = root.descendant_text("saml-request"); let saml_request = root.descendant_text("saml-request");
let saml_default_browser = root.descendant_text("saml-default-browser"); let saml_default_browser = root.descendant_text("saml-default-browser");
// Check if the prelogin response is SAML // Check if the prelogin response is SAML
if saml_method.is_some() && saml_request.is_some() { 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 support_default_browser = saml_default_browser.map(|s| s.to_lowercase() == "yes").unwrap_or(false);
let saml_prelogin = SamlPrelogin { let saml_prelogin = SamlPrelogin {
@@ -185,25 +183,18 @@ fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
return Ok(Prelogin::Saml(saml_prelogin)); return Ok(Prelogin::Saml(saml_prelogin));
} }
let label_username = root let label_username = root.descendant_text("username-label").unwrap_or_else(|| {
.descendant_text("username-label") info!("Username label has no value, using default");
.unwrap_or_else(|| { "Username".to_string()
info!("Username label has no value, using default"); });
"Username" let label_password = root.descendant_text("password-label").unwrap_or_else(|| {
}) info!("Password label has no value, using default");
.to_string(); "Password".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 let auth_message = root
.descendant_text("authentication-message") .descendant_text("authentication-message")
.unwrap_or("Please enter the login credentials") .unwrap_or_else(|| "Please enter the login credentials".to_string());
.to_string();
let standard_prelogin = StandardPrelogin { let standard_prelogin = StandardPrelogin {
region, region,
is_gateway, is_gateway,
+63 -16
View File
@@ -1,27 +1,74 @@
use roxmltree::Node; use xmltree::Element;
pub(crate) trait NodeExt<'a> { pub(crate) trait ElementExt {
fn find_descendant(&self, name: &str) -> Option<Node<'a, 'a>>; fn descendants(&self, name: &str) -> Vec<&Element>;
fn descendant_text(&self, name: &str) -> Option<&'a str>; fn descendant(&self, name: &str) -> Option<&Element>;
fn descendant_text(&self, name: &str) -> Option<String>;
fn find_child(&self, name: &str) -> Option<Node<'a, 'a>>; fn child(&self, name: &str) -> Option<&Element>;
fn child_text(&self, name: &str) -> Option<&'a str>; fn child_text(&self, name: &str) -> Option<String>;
fn children(&self, name: &str) -> Vec<&Element>;
fn attr(&self, name: &str) -> Option<&str>;
} }
impl<'a> NodeExt<'a> for Node<'a, 'a> { impl ElementExt for Element {
fn find_descendant(&self, name: &str) -> Option<Node<'a, 'a>> { fn descendants(&self, name: &str) -> Vec<&Element> {
self.descendants().find(|n| n.has_tag_name(name)) 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> { fn descendant(&self, name: &str) -> Option<&Element> {
self.find_descendant(name).and_then(|node| node.text()) 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<Node<'a, 'a>> { fn descendant_text(&self, name: &str) -> Option<String> {
self.children().find(|n| n.has_tag_name(name)) self
.descendant(name)
.and_then(|element| element.get_text().map(|s| s.to_string()))
} }
fn child_text(&self, name: &str) -> Option<&'a str> { fn child(&self, name: &str) -> Option<&Element> {
self.find_child(name).and_then(|node| node.text()) self.get_child(name)
}
fn child_text(&self, name: &str) -> Option<String> {
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())
} }
} }