agent_hub_runtime/core/preview/
download_transfer.rs1use super::remote_ssh::validate_target;
3use super::{
4 browser::{Browsers, State},
5 downloads::Download,
6 runtime,
7};
8use crate::core::{cli_process, error::AppError, path_guard};
9use serde::Serialize;
10use std::{
11 io::Write,
12 path::{Path, PathBuf},
13 process::Command,
14 sync::{
15 atomic::{AtomicBool, AtomicU64, Ordering},
16 Arc, Mutex,
17 },
18 time::Duration,
19};
20
21const LIMIT: u64 = 512 * 1024 * 1024;
22#[derive(Clone, Serialize)]
23pub struct Progress {
24 pub state: String,
25 pub received: u64,
26 pub error: Option<String>,
27}
28pub(super) struct Transfer {
29 canceled: AtomicBool,
30 received: AtomicU64,
31 result: Mutex<Option<Result<(), String>>>,
32}
33impl Transfer {
34 fn new() -> Self {
35 Self {
36 canceled: AtomicBool::new(false),
37 received: AtomicU64::new(0),
38 result: Mutex::new(None),
39 }
40 }
41 pub fn cancel(&self) {
42 self.canceled.store(true, Ordering::Release);
43 }
44 pub fn active(&self) -> bool {
45 self.result
46 .lock()
47 .map(|value| value.is_none())
48 .unwrap_or(false)
49 }
50 fn progress(&self) -> Progress {
51 let result = self.result.lock().ok();
52 let result = result.as_deref().and_then(|value| value.as_ref());
53 let (state, error) = match result {
54 Some(Ok(())) => ("completed", None),
55 Some(Err(error)) if error == "canceled" => ("canceled", None),
56 Some(Err(error)) => ("failed", Some(error.clone())),
57 None if self.canceled.load(Ordering::Acquire) => ("canceling", None),
58 None => ("running", None),
59 };
60 Progress {
61 state: state.into(),
62 received: self.received.load(Ordering::Relaxed),
63 error,
64 }
65 }
66}
67pub(super) fn snapshot(state: &State) -> Vec<Download> {
68 state
69 .downloads
70 .iter()
71 .map(|(key, download)| {
72 let mut download = download.clone();
73 download.transfer = state.transfers.get(key).map(|job| job.progress());
74 download
75 })
76 .collect()
77}
78impl Browsers {
79 pub fn fetch_download(self: &Arc<Self>, profile: &str, id: &str) -> Result<(), AppError> {
81 if !cfg!(unix) {
82 return Err(AppError::invalid_input(
83 "SFTP retrieval currently requires macOS or Linux",
84 ));
85 }
86 let key = format!("{profile}:{id}");
87 let job = Arc::new(Transfer::new());
88 let (item, target) = {
89 let mut state = self
90 .state
91 .lock()
92 .map_err(|_| AppError::internal("Browser state unavailable"))?;
93 let config = self
94 .profiles()?
95 .into_iter()
96 .find(|item| item.id == profile && !item.deleting)
97 .ok_or_else(|| AppError::not_found("Browser profile unavailable"))?;
98 let target = config.remote_transfer_target.as_deref().ok_or_else(|| {
99 AppError::invalid_input("Configure the profile's SSH transfer host first")
100 })?;
101 validate_target(target)?;
102 let target = target.to_owned();
103 let endpoint = config
104 .endpoint
105 .as_deref()
106 .map(runtime::validate_endpoint)
107 .transpose()?;
108 if state.closing {
109 return Err(AppError::cancelled("Preview is shutting down"));
110 }
111 if state.transfers.get(&key).is_some_and(|job| job.active()) {
112 return Ok(());
113 }
114 if state.transfers.values().filter(|job| job.active()).count() >= 2 {
115 return Err(AppError::invalid_input(
116 "Wait for one of the two active transfers to finish",
117 ));
118 }
119 let item = state
120 .downloads
121 .get(&key)
122 .cloned()
123 .ok_or_else(|| AppError::not_found("Download unavailable"))?;
124 if item.state != "completed"
125 || !item.remote
126 || item.local
127 || !item.verified
128 || item.source_endpoint != endpoint
129 || item.remote_path.is_none()
130 {
131 return Err(AppError::invalid_input(
132 "A verified completed download from the same remote endpoint is required",
133 ));
134 }
135 if !item.received.is_finite()
136 || item.received < 0.
137 || item.received.fract() != 0.
138 || item.received > LIMIT as f64
139 {
140 return Err(AppError::invalid_input(
141 "Remote transfers support files up to 512 MiB",
142 ));
143 }
144 state.transfers.insert(key.clone(), job.clone());
145 (item, target)
146 };
147 let browsers = self.clone();
148 let worker_job = job.clone();
149 let worker_key = key.clone();
150 let spawn = std::thread::Builder::new()
151 .name("preview-download-transfer".into())
152 .spawn(move || {
153 let result = browsers.retrieve(&worker_key, &item, &target, &worker_job);
154 if let Ok(mut value) = worker_job.result.lock() {
155 *value = Some(result);
156 }
157 });
158 if spawn.is_err() {
159 if let Ok(mut value) = job.result.lock() {
160 *value = Some(Err("failed".into()));
161 }
162 return Err(AppError::internal("Transfer worker unavailable"));
163 }
164 Ok(())
165 }
166 pub fn cancel_transfer(&self, profile: &str, id: &str) -> Result<(), AppError> {
167 let state = self
168 .state
169 .lock()
170 .map_err(|_| AppError::internal("Browser state unavailable"))?;
171 let job = state
172 .transfers
173 .get(&format!("{profile}:{id}"))
174 .ok_or_else(|| AppError::not_found("Transfer unavailable"))?;
175 if job.active() {
176 job.cancel();
177 }
178 Ok(())
179 }
180 fn retrieve(
181 &self,
182 key: &str,
183 item: &Download,
184 target: &str,
185 job: &Arc<Transfer>,
186 ) -> Result<(), String> {
187 self.retrieve_using(key, item, job, |batch| sftp_command(target, batch))
188 }
189 fn retrieve_using(
190 &self,
191 key: &str,
192 item: &Download,
193 job: &Arc<Transfer>,
194 command: impl FnOnce(&Path) -> Result<Command, String>,
195 ) -> Result<(), String> {
196 let directory =
197 destination(&self.root, &item.profile).map_err(|_| "destination".to_string())?;
198 let staging = tempfile::tempdir_in(&directory).map_err(|_| "destination".to_string())?;
199 let payload = tempfile::NamedTempFile::new_in(staging.path())
200 .map_err(|_| "destination".to_string())?;
201 let mut batch = tempfile::NamedTempFile::new_in(staging.path())
202 .map_err(|_| "destination".to_string())?;
203 let remote = item.remote_path.as_deref().ok_or("source")?;
204 writeln!(
205 batch,
206 "@get {} {}",
207 quoted(remote)?,
208 quoted(&payload.path().to_string_lossy())?
209 )
210 .map_err(|_| "destination".to_string())?;
211 batch.flush().map_err(|_| "destination".to_string())?;
212 let command = command(batch.path())?;
213 let expected = item.received as u64;
214 let finished = AtomicBool::new(false);
215 let oversized = AtomicBool::new(false);
216 let result = std::thread::scope(|scope| {
217 scope.spawn(|| {
218 while !finished.load(Ordering::Acquire) {
219 if let Ok(metadata) = payload.as_file().metadata() {
220 job.received.store(metadata.len(), Ordering::Relaxed);
221 if metadata.len() > LIMIT || metadata.len() > expected {
222 oversized.store(true, Ordering::Release);
223 job.cancel();
224 }
225 }
226 std::thread::sleep(Duration::from_millis(30));
227 }
228 });
229 let result = cli_process::capture_prepared(command, "sftp", 300, Some(&job.canceled));
230 finished.store(true, Ordering::Release);
231 result
232 });
233 if oversized.load(Ordering::Acquire) {
234 return Err("size".into());
235 }
236 if job.canceled.load(Ordering::Acquire) {
237 return Err("canceled".into());
238 }
239 result.map_err(|error| transfer_error(&error).to_owned())?;
240 if payload
241 .as_file()
242 .metadata()
243 .map_err(|_| "destination")?
244 .len()
245 != expected
246 {
247 return Err("size".into());
248 }
249 #[cfg(unix)]
250 {
251 use std::os::unix::fs::PermissionsExt;
252 payload
253 .as_file()
254 .set_permissions(std::fs::Permissions::from_mode(0o600))
255 .map_err(|_| "destination")?;
256 }
257 payload.as_file().sync_all().map_err(|_| "destination")?;
258 if destination(&self.root, &item.profile).map_err(|_| "destination")? != directory {
260 return Err("destination".into());
261 }
262 let mut state = self.state.lock().map_err(|_| "failed")?;
263 if state.closing || job.canceled.load(Ordering::Acquire) {
264 return Err("canceled".into());
265 }
266 if !state
267 .transfers
268 .get(key)
269 .is_some_and(|current| Arc::ptr_eq(current, job))
270 {
271 return Err("source".into());
272 }
273 let current = state
274 .downloads
275 .get_mut(key)
276 .filter(|current| {
277 current.source_runtime == item.source_runtime
278 && current.remote_path == item.remote_path
279 && !current.local
280 })
281 .ok_or("source")?;
282 let mut name = path_guard::sanitize_name(&item.name);
283 while name.len() > 180 {
284 name.pop();
285 }
286 let path = directory.join(format!("{}-{name}", uuid::Uuid::new_v4()));
287 payload
288 .persist_noclobber(&path)
289 .map_err(|_| "destination")?;
290 current.local = true;
291 current.path = Some(path);
292 job.received.store(expected, Ordering::Relaxed);
293 Ok(())
294 }
295}
296fn destination(root: &Path, profile: &str) -> Result<PathBuf, AppError> {
297 let root = root.canonicalize()?;
298 let mut path = root;
299 for part in ["downloads", profile, "retrieved"] {
300 if part.is_empty()
301 || !part
302 .bytes()
303 .all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
304 {
305 return Err(AppError::invalid_input("Invalid download profile"));
306 }
307 path.push(part);
308 match std::fs::create_dir(&path) {
309 Ok(()) => {}
310 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
311 Err(error) => return Err(error.into()),
312 }
313 let metadata = std::fs::symlink_metadata(&path)?;
314 if path_guard::is_link_or_reparse_point(&metadata) || !metadata.is_dir() {
315 return Err(AppError::invalid_input("Unsafe download directory"));
316 }
317 }
318 Ok(path)
319}
320fn quoted(path: &str) -> Result<String, String> {
321 if path.is_empty() || path.chars().any(|c| c.is_control()) {
322 return Err("source".into());
323 }
324 Ok(format!(
325 "\"{}\"",
326 path.replace('\\', "\\\\").replace('"', "\\\"")
327 ))
328}
329fn sftp_command(target: &str, batch: &Path) -> Result<Command, String> {
330 let binary = ["/usr/bin/sftp", "/usr/local/bin/sftp"]
331 .into_iter()
332 .find(|path| Path::new(path).is_file())
333 .ok_or("unavailable")?;
334 let mut command = Command::new(binary);
335 command
336 .env("LC_ALL", "C")
337 .args(["-q", "-R", "16", "-B", "65536", "-l", "65536", "-b"])
338 .arg(batch);
339 super::remote_ssh::secure_options(&mut command);
340 command.args(["-oControlMaster=no", "-oControlPath=none"]);
341 command.arg(target);
342 Ok(command)
343}
344fn transfer_error(error: &str) -> &'static str {
345 if error.contains("Host key verification failed")
346 || error.contains("REMOTE HOST IDENTIFICATION HAS CHANGED")
347 {
348 "host_key"
349 } else if error.contains("Permission denied") {
350 "authentication"
351 } else if error.contains("No such file") {
352 "source"
353 } else if error.contains("timed out") {
354 "timeout"
355 } else {
356 "failed"
357 }
358}
359#[cfg(test)]
360mod tests;