Skip to main content

brows3_lib/transfer/
download.rs

1use cap_std::fs::{Dir, OpenOptions};
2use std::ffi::OsString;
3use std::io;
4use std::path::{Component, Path, PathBuf};
5use std::sync::Arc;
6use tokio::io::AsyncWriteExt;
7
8#[derive(Debug)]
9pub struct DownloadDestination {
10    root: Arc<Dir>,
11    relative_path: PathBuf,
12    overwrite: bool,
13}
14
15impl DownloadDestination {
16    pub fn open_root(path: &Path) -> io::Result<Arc<Dir>> {
17        Dir::open_ambient_dir(path, cap_std::ambient_authority()).map(Arc::new)
18    }
19
20    pub fn new(root: Arc<Dir>, relative_path: PathBuf, overwrite: bool) -> io::Result<Self> {
21        if relative_path.as_os_str().is_empty()
22            || relative_path
23                .components()
24                .any(|part| !matches!(part, Component::Normal(_)))
25        {
26            return Err(io::Error::new(
27                io::ErrorKind::InvalidInput,
28                "Invalid download destination",
29            ));
30        }
31        Ok(Self {
32            root,
33            relative_path,
34            overwrite,
35        })
36    }
37
38    pub fn from_path(path: &Path, overwrite: bool) -> io::Result<Self> {
39        let parent = path
40            .parent()
41            .filter(|parent| !parent.as_os_str().is_empty())
42            .ok_or_else(|| {
43                io::Error::new(io::ErrorKind::InvalidInput, "Choose a download directory")
44            })?;
45        let name = path.file_name().ok_or_else(|| {
46            io::Error::new(io::ErrorKind::InvalidInput, "Choose a download filename")
47        })?;
48        Self::new(Self::open_root(parent)?, PathBuf::from(name), overwrite)
49    }
50
51    pub fn begin(&self) -> io::Result<PendingDownload> {
52        let relative_parent = self.relative_path.parent().unwrap_or(Path::new(""));
53        let parent = if relative_parent.as_os_str().is_empty() {
54            self.root.try_clone()?
55        } else {
56            self.root.create_dir_all(relative_parent)?;
57            self.root.open_dir(relative_parent)?
58        };
59        let final_name = self
60            .relative_path
61            .file_name()
62            .ok_or_else(|| {
63                io::Error::new(io::ErrorKind::InvalidInput, "Choose a download filename")
64            })?
65            .to_os_string();
66        if !self.overwrite && parent.symlink_metadata(&final_name).is_ok() {
67            return Err(io::Error::new(
68                io::ErrorKind::AlreadyExists,
69                "The download destination already exists",
70            ));
71        }
72        let temporary_name = format!(".brows3-{}.part", uuid::Uuid::new_v4());
73        let file = parent.open_with(
74            &temporary_name,
75            OpenOptions::new().write(true).create_new(true),
76        )?;
77        Ok(PendingDownload {
78            file: Some(tokio::fs::File::from_std(file.into_std())),
79            parent,
80            temporary_name,
81            final_name,
82            overwrite: self.overwrite,
83        })
84    }
85}
86
87pub struct PendingDownload {
88    file: Option<tokio::fs::File>,
89    parent: Dir,
90    temporary_name: String,
91    final_name: OsString,
92    overwrite: bool,
93}
94
95impl PendingDownload {
96    pub async fn write_all(&mut self, bytes: &[u8]) -> io::Result<()> {
97        let file = self
98            .file
99            .as_mut()
100            .ok_or_else(|| io::Error::other("Download is closed"))?;
101        file.write_all(bytes).await
102    }
103
104    pub async fn finish_writing(&mut self) -> io::Result<()> {
105        let file = self
106            .file
107            .as_mut()
108            .ok_or_else(|| io::Error::other("Download is closed"))?;
109        file.flush().await?;
110        file.sync_all().await?;
111        self.file.take();
112        Ok(())
113    }
114
115    pub fn commit(self) -> io::Result<()> {
116        if self.file.is_some() {
117            return Err(io::Error::other("Download has not finished writing"));
118        }
119        if self.overwrite {
120            self.parent
121                .rename(&self.temporary_name, &self.parent, &self.final_name)?;
122        } else {
123            #[cfg(any(target_os = "linux", target_os = "macos"))]
124            rustix::fs::renameat_with(
125                &self.parent,
126                &self.temporary_name,
127                &self.parent,
128                &self.final_name,
129                rustix::fs::RenameFlags::NOREPLACE,
130            )?;
131            #[cfg(windows)]
132            {
133                let handle = self.parent.try_clone()?.into_std_file();
134                let path = winx::file::get_file_path(&handle)?;
135                tempfile::TempPath::from_path(path.join(&self.temporary_name))
136                    .persist_noclobber(path.join(&self.final_name))
137                    .map_err(|error| error.error)?;
138            }
139            #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
140            self.parent
141                .hard_link(&self.temporary_name, &self.parent, &self.final_name)?;
142        }
143        Ok(())
144    }
145}
146
147impl Drop for PendingDownload {
148    fn drop(&mut self) {
149        self.file.take();
150        if let Err(error) = self.parent.remove_file(&self.temporary_name) {
151            if error.kind() != io::ErrorKind::NotFound {
152                log::warn!("Could not remove download temporary file: {error}");
153            }
154        }
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    struct Fixture(PathBuf);
163    impl Fixture {
164        fn new() -> Self {
165            let path =
166                std::env::temp_dir().join(format!("brows3-download-test-{}", uuid::Uuid::new_v4()));
167            std::fs::create_dir_all(&path).unwrap();
168            Self(path)
169        }
170        fn destination(&self, overwrite: bool) -> DownloadDestination {
171            DownloadDestination::from_path(&self.0.join("result.txt"), overwrite).unwrap()
172        }
173    }
174    impl Drop for Fixture {
175        fn drop(&mut self) {
176            let _ = std::fs::remove_dir_all(&self.0);
177        }
178    }
179
180    #[tokio::test]
181    async fn interrupted_download_preserves_existing_file_and_removes_temporary_file() {
182        let fixture = Fixture::new();
183        let final_path = fixture.0.join("result.txt");
184        std::fs::write(&final_path, b"original").unwrap();
185        let mut pending = fixture.destination(true).begin().unwrap();
186        pending.write_all(b"partial").await.unwrap();
187        drop(pending);
188        assert_eq!(std::fs::read(final_path).unwrap(), b"original");
189        assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 1);
190    }
191
192    #[tokio::test]
193    async fn complete_download_only_replaces_an_existing_file_when_requested() {
194        let fixture = Fixture::new();
195        let final_path = fixture.0.join("result.txt");
196        let mut first = fixture.destination(false).begin().unwrap();
197        first.write_all(b"first").await.unwrap();
198        assert!(!final_path.exists());
199        first.finish_writing().await.unwrap();
200        first.commit().unwrap();
201        assert!(fixture.destination(false).begin().is_err());
202        let mut replacement = fixture.destination(true).begin().unwrap();
203        replacement.write_all(b"replacement").await.unwrap();
204        assert_eq!(std::fs::read(&final_path).unwrap(), b"first");
205        replacement.finish_writing().await.unwrap();
206        replacement.commit().unwrap();
207        assert_eq!(std::fs::read(final_path).unwrap(), b"replacement");
208    }
209
210    #[tokio::test]
211    async fn competing_downloads_cannot_overwrite_each_other() {
212        let fixture = Fixture::new();
213        let mut first = fixture.destination(false).begin().unwrap();
214        let mut second = fixture.destination(false).begin().unwrap();
215        first.write_all(b"first").await.unwrap();
216        second.write_all(b"second").await.unwrap();
217        first.finish_writing().await.unwrap();
218        second.finish_writing().await.unwrap();
219        first.commit().unwrap();
220        assert_eq!(
221            second.commit().unwrap_err().kind(),
222            io::ErrorKind::AlreadyExists
223        );
224        assert_eq!(
225            std::fs::read(fixture.0.join("result.txt")).unwrap(),
226            b"first"
227        );
228        assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 1);
229    }
230
231    #[tokio::test]
232    async fn aborting_a_task_does_not_leave_a_partial_destination() {
233        let fixture = Fixture::new();
234        let destination = fixture.destination(false);
235        let (ready, started) = tokio::sync::oneshot::channel();
236        let task = tokio::spawn(async move {
237            let mut download = destination.begin().unwrap();
238            download.write_all(b"partial").await.unwrap();
239            ready.send(()).unwrap();
240            std::future::pending::<()>().await;
241        });
242        started.await.unwrap();
243        task.abort();
244        assert!(task.await.unwrap_err().is_cancelled());
245        assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
246    }
247
248    #[tokio::test]
249    async fn nested_folder_download_creates_directories_inside_the_root() {
250        let fixture = Fixture::new();
251        let root = DownloadDestination::open_root(&fixture.0).unwrap();
252        let destination =
253            DownloadDestination::new(root, PathBuf::from("reports/2026/result.txt"), false)
254                .unwrap();
255        let mut download = destination.begin().unwrap();
256        download.write_all(b"complete").await.unwrap();
257        download.finish_writing().await.unwrap();
258        download.commit().unwrap();
259        assert_eq!(
260            std::fs::read(fixture.0.join("reports/2026/result.txt")).unwrap(),
261            b"complete"
262        );
263    }
264
265    #[cfg(unix)]
266    #[test]
267    fn symlinks_cannot_redirect_a_folder_download_outside_its_root() {
268        let selected = Fixture::new();
269        let outside = Fixture::new();
270        let root = DownloadDestination::open_root(&selected.0).unwrap();
271        let destination =
272            DownloadDestination::new(root, PathBuf::from("reports/result.txt"), false).unwrap();
273        std::os::unix::fs::symlink(&outside.0, selected.0.join("reports")).unwrap();
274        assert!(destination.begin().is_err());
275        assert!(!outside.0.join("result.txt").exists());
276    }
277}