Skip to main content

proxy_pilot/core/xray/
mod.rs

1pub mod benchmark;
2pub mod vless;
3
4use std::path::{Path, PathBuf};
5use std::time::Duration;
6
7use async_trait::async_trait;
8use serde_json::Value;
9use tokio::process::Command;
10
11use crate::core::{BenchmarkSession, ProxyCore};
12use crate::error::{PilotError, Result};
13
14pub struct XrayCore {
15    pub binary_path: PathBuf,
16    pub config_path: PathBuf,
17    pub service_name: String,
18}
19
20impl XrayCore {
21    pub fn new(
22        binary_path: impl Into<PathBuf>,
23        config_path: impl Into<PathBuf>,
24        service_name: String,
25    ) -> Self {
26        Self {
27            binary_path: binary_path.into(),
28            config_path: config_path.into(),
29            service_name,
30        }
31    }
32
33    async fn read_config_json(&self) -> Result<Value> {
34        let raw = tokio::fs::read_to_string(&self.config_path)
35            .await
36            .map_err(|err| {
37                PilotError::Core(format!(
38                    "failed to read xray config {}: {err}",
39                    self.config_path.display()
40                ))
41            })?;
42        serde_json::from_str(&raw)
43            .map_err(|err| PilotError::Core(format!("invalid xray json: {err}")))
44    }
45
46    async fn write_config_atomic(path: &Path, value: &Value) -> Result<()> {
47        let parent = path.parent().ok_or_else(|| {
48            PilotError::Core(format!("config path has no parent: {}", path.display()))
49        })?;
50        let tmp_path = parent.join(format!(".{}.tmp", std::process::id()));
51        let serialized = serde_json::to_string_pretty(value)
52            .map_err(|err| PilotError::Core(format!("failed to serialize xray json: {err}")))?;
53        tokio::fs::write(&tmp_path, serialized).await?;
54        tokio::fs::rename(&tmp_path, path).await?;
55        Ok(())
56    }
57
58    /// Add or replace an outbound in Xray's `config.json` atomically.
59    pub async fn upsert_outbound(&self, tag: &str, outbound: Value) -> Result<()> {
60        let mut json = self.read_config_json().await?;
61        let outbounds = json
62            .get_mut("outbounds")
63            .and_then(Value::as_array_mut)
64            .ok_or_else(|| PilotError::Core("xray config missing 'outbounds' array".into()))?;
65
66        if let Some(existing) = outbounds
67            .iter_mut()
68            .find(|item| item.get("tag").and_then(Value::as_str) == Some(tag))
69        {
70            *existing = outbound;
71        } else {
72            outbounds.push(outbound);
73        }
74        Self::write_config_atomic(&self.config_path, &json).await
75    }
76}
77
78#[async_trait]
79impl ProxyCore for XrayCore {
80    fn name(&self) -> &'static str {
81        "xray"
82    }
83
84    async fn is_installed(&self) -> bool {
85        tokio::fs::try_exists(&self.binary_path)
86            .await
87            .unwrap_or(false)
88    }
89
90    async fn install(&self) -> Result<()> {
91        Err(PilotError::Core(
92            "automatic xray binary downloader is planned for the next milestone".into(),
93        ))
94    }
95
96    async fn active_profile(&self) -> Result<Option<String>> {
97        let json = self.read_config_json().await?;
98        let tag = json
99            .get("outbounds")
100            .and_then(Value::as_array)
101            .and_then(|arr| arr.first())
102            .and_then(|item| item.get("tag"))
103            .and_then(Value::as_str)
104            .map(ToString::to_string);
105        Ok(tag)
106    }
107
108    async fn switch_profile(&self, outbound_tag: &str) -> Result<()> {
109        let mut json = self.read_config_json().await?;
110        let outbounds = json
111            .get_mut("outbounds")
112            .and_then(Value::as_array_mut)
113            .ok_or_else(|| PilotError::Core("xray config missing 'outbounds' array".into()))?;
114
115        let pos = outbounds
116            .iter()
117            .position(|item| item.get("tag").and_then(Value::as_str) == Some(outbound_tag))
118            .ok_or_else(|| {
119                PilotError::Core(format!(
120                    "outbound tag '{outbound_tag}' not found in xray config"
121                ))
122            })?;
123
124        if pos > 0 {
125            let selected = outbounds.remove(pos);
126            outbounds.insert(0, selected);
127            Self::write_config_atomic(&self.config_path, &json).await?;
128        }
129        Ok(())
130    }
131
132    async fn reload(&self) -> Result<()> {
133        #[cfg(target_os = "linux")]
134        {
135            let _ = Command::new("systemctl")
136                .args(["reset-failed", &self.service_name])
137                .status()
138                .await;
139            let status = Command::new("systemctl")
140                .args(["reload-or-restart", &self.service_name])
141                .status()
142                .await
143                .map_err(|err| PilotError::Core(format!("failed to invoke systemctl: {err}")))?;
144            if !status.success() {
145                return Err(PilotError::Core(format!(
146                    "systemctl reload-or-restart {} exited with {status}",
147                    self.service_name
148                )));
149            }
150            tokio::time::sleep(Duration::from_millis(400)).await;
151            return Ok(());
152        }
153
154        #[cfg(target_os = "macos")]
155        {
156            let status = Command::new("brew")
157                .args(["services", "restart", &self.service_name])
158                .status()
159                .await
160                .map_err(|err| {
161                    PilotError::Core(format!("failed to invoke brew services: {err}"))
162                })?;
163            if !status.success() {
164                return Err(PilotError::Core(format!(
165                    "brew services restart {} exited with {status}",
166                    self.service_name
167                )));
168            }
169            tokio::time::sleep(Duration::from_millis(400)).await;
170            return Ok(());
171        }
172
173        #[cfg(target_os = "windows")]
174        {
175            let _ = Command::new("taskkill")
176                .args(["/F", "/IM", "xray.exe"])
177                .status()
178                .await;
179            Command::new(&self.binary_path)
180                .args(["run", "-c"])
181                .arg(&self.config_path)
182                .spawn()
183                .map_err(|err| PilotError::Core(format!("failed to start xray.exe: {err}")))?;
184            tokio::time::sleep(Duration::from_millis(400)).await;
185            return Ok(());
186        }
187
188        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
189        Err(PilotError::Core(
190            "unsupported operating system for xray reload".into(),
191        ))
192    }
193
194    async fn start_benchmark_session(
195        &self,
196        outbound_tags: &[String],
197    ) -> Result<Option<Box<dyn BenchmarkSession>>> {
198        if outbound_tags.is_empty() || !self.is_installed().await {
199            return Ok(None);
200        }
201        let source_config = self.read_config_json().await?;
202        benchmark::start_xray_benchmark_session(&self.binary_path, &source_config, outbound_tags)
203            .await
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use tempfile::TempDir;
211
212    #[tokio::test]
213    async fn switches_outbound_atomically_and_reads_active_profile() {
214        let dir = TempDir::new().unwrap();
215        let cfg_path = dir.path().join("config.json");
216        let sample = r#"{
217            "outbounds": [
218                {"tag": "proxy-de-1", "protocol": "vless"},
219                {"tag": "proxy-fi-2", "protocol": "vless"}
220            ]
221        }"#;
222        tokio::fs::write(&cfg_path, sample).await.unwrap();
223
224        let core = XrayCore::new("/usr/local/bin/xray", &cfg_path, "xray".into());
225        assert_eq!(
226            core.active_profile().await.unwrap().as_deref(),
227            Some("proxy-de-1")
228        );
229
230        core.switch_profile("proxy-fi-2").await.unwrap();
231        assert_eq!(
232            core.active_profile().await.unwrap().as_deref(),
233            Some("proxy-fi-2")
234        );
235    }
236
237    #[tokio::test]
238    async fn returns_error_for_unknown_outbound_tag() {
239        let dir = TempDir::new().unwrap();
240        let cfg_path = dir.path().join("config.json");
241        tokio::fs::write(&cfg_path, r#"{"outbounds": [{"tag": "proxy-de-1"}]}"#)
242            .await
243            .unwrap();
244
245        let core = XrayCore::new("/usr/local/bin/xray", &cfg_path, "xray".into());
246        assert!(core.switch_profile("missing-tag").await.is_err());
247    }
248}