//! sing-box's Clash API on loopback: what selectors pick, and outbound latency. use std::time::Duration; use anyhow::{Context, Result, bail}; use serde_json::Value; pub struct Clash { base: String, secret: String, http: reqwest::Client, } fn encode(segment: &str) -> String { let mut out = String::new(); for b in segment.bytes() { if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { out.push(b as char); } else { out.push_str(&format!("%{b:02X}")); } } out } #[allow(dead_code, reason = "for switching the selection live, which is to come")] impl Clash { pub fn new(port: u16, secret: &str) -> Self { let http = reqwest::Client::builder() .no_proxy() .timeout(Duration::from_secs(20)) .build() .expect("an HTTP client"); Self { base: format!("http://127.0.0.1:{port}"), secret: secret.to_owned(), http } } async fn get(&self, path: &str) -> Result { let resp = self.http.get(format!("{}{path}", self.base)).bearer_auth(&self.secret).send().await?; let status = resp.status(); let body: Value = resp.json().await.unwrap_or(Value::Null); if !status.is_success() { bail!("{}", body["message"].as_str().unwrap_or(status.as_str())); } Ok(body) } /// The connections open now, with where each goes and through what. pub async fn connections(&self) -> Result { self.get("/connections").await } /// Every proxy (outbound or group) with what a selector holds now. pub async fn proxies(&self) -> Result { self.get("/proxies").await.map(|v| v["proxies"].clone()) } /// What `group` (a selector or urltest) uses now. pub async fn current(&self, group: &str) -> Result> { let v = self.get(&format!("/proxies/{}", encode(group))).await?; Ok(v["now"].as_str().map(str::to_owned)) } /// Switches the selector `group` to `tag`, live. pub async fn select(&self, group: &str, tag: &str) -> Result<()> { let resp = self .http .put(format!("{}/proxies/{}", self.base, encode(group))) .bearer_auth(&self.secret) .json(&serde_json::json!({ "name": tag })) .send() .await .context("the Clash API")?; if !resp.status().is_success() { let body: Value = resp.json().await.unwrap_or(Value::Null); bail!("cannot switch {group} to {tag}: {}", body["message"].as_str().unwrap_or("refused")); } Ok(()) } /// The delay to `url` through `tag`, in milliseconds. pub async fn delay(&self, tag: &str, url: &str, timeout_ms: u32) -> Result { let resp = self .http .get(format!("{}/proxies/{}/delay", self.base, encode(tag))) .bearer_auth(&self.secret) .query(&[("url", url), ("timeout", &timeout_ms.to_string())]) .send() .await?; let status = resp.status(); let body: Value = resp.json().await.unwrap_or(Value::Null); if !status.is_success() { bail!("{}", body["message"].as_str().unwrap_or("timed out")); } body["delay"].as_u64().map(|d| d as u32).context("no delay in the answer") } }