Skip to main content

libtea_client/
download.rs

1//! Streaming artifact download: hash while writing, release only after the check.
2//!
3//! *Experimental until 0.9.* The types and methods in this module may change in
4//! a minor release.
5//!
6//! The whole-body methods on [`crate::Service`] hold the decoded artifact in
7//! memory. The methods here write the decoded bytes to a sink as they arrive
8//! and feed a [`libtea_core::ChecksumVerifier`] with the same bytes, so memory
9//! use does not grow with the artifact. The same limits apply as for the
10//! whole-body methods: [`crate::Limits::max_artifact_bytes`] caps the encoded
11//! and the decoded size, redirects and destinations go through the same
12//! policy, and only one content coding is accepted.
13//!
14//! **Verified means checksum integrity.** A declared checksum that matches the
15//! decoded bytes is integrity of those bytes, not publisher authenticity.
16//!
17//! **Nothing is released as verified before the check completes.**
18//!
19//! - [`Service::download_format_to_file`] and its siblings write to a
20//!   temporary file next to the destination, then rename it over the
21//!   destination only after the stream ended cleanly and the checksums passed
22//!   the client's policy. On any failure the temporary file is removed and the
23//!   destination is untouched.
24//!   The temporary file is created private (mode 0600 on Unix, with
25//!   `create_new`, so it never follows a link) because it holds unverified
26//!   bytes, and the finished file keeps that mode. A `.part` file left by a
27//!   killed process is removed by the next download to the same destination
28//!   name once it is an hour old.
29//! - Without [`FileDownloadOptions::overwrite`] the file is put in place with a
30//!   hard link, which fails if the destination exists or appears meanwhile. A
31//!   filesystem without hard links therefore needs `overwrite`; this client
32//!   does not fall back to a rename that could replace a file that appeared in
33//!   the window.
34//! - [`Service::download_format_to_writer`] cannot take bytes back from a
35//!   writer it does not own. The writer sees unverified bytes. Treat what it
36//!   received as untrusted unless the call returned `Ok`, and discard it on
37//!   `Err`.
38//!
39//! **Resume is not supported.** There is no `Range` request. A `Range` over a
40//! content-coded representation does not line up with the decoded bytes that
41//! the checksum covers, a partial file would have to be re-read to rebuild the
42//! hash state, and TEA 1.0.0 does not define range semantics for artifact
43//! downloads. A failed download starts over.
44
45use std::path::{Path, PathBuf};
46use std::sync::atomic::{AtomicU64, Ordering};
47use std::sync::Arc;
48
49use libtea_core::checksum::ContentDecoder;
50use libtea_core::http_cache::{CacheEntryMeta, NotStored};
51use libtea_core::{
52    escape_control_chars, Artifact, ChecksumVerifier, IntegrityOutcome, IntegrityReport,
53};
54use reqwest::header::{CONTENT_ENCODING, CONTENT_TYPE, ETAG};
55use tokio::io::{AsyncWrite, AsyncWriteExt};
56use url::Url;
57
58use crate::cache::{now_secs, Cache};
59use crate::error::ClientError;
60use crate::transport::{
61    decide_storage, display_url, header_str, map_api_error, storable_headers, Call, StreamStart,
62};
63use crate::Service;
64
65/// What a streamed download reports. The bytes went to the sink.
66///
67/// *Experimental.*
68#[derive(Debug, Clone, PartialEq, Eq)]
69#[non_exhaustive]
70pub struct StreamedDownload {
71    /// Number of decoded bytes written to the sink.
72    pub bytes_written: u64,
73    /// Response `Content-Type`.
74    pub content_type: Option<String>,
75    /// HTTP content coding that was removed, when one was declared.
76    pub content_encoding: Option<String>,
77    /// `ETag` as received. This is not a checksum.
78    pub etag: Option<String>,
79    /// Whether the tag is strong. A weak tag is not byte-identity proof.
80    pub strong_etag: bool,
81    /// Final URL after redirects.
82    pub final_url: String,
83    /// Checksum report over the decoded bytes. [`IntegrityOutcome::Verified`]
84    /// is integrity of those bytes, not publisher authenticity.
85    /// [`IntegrityOutcome::NotDeclared`] means nothing was checked.
86    pub integrity: IntegrityReport,
87}
88
89/// A streamed download that was committed to a file.
90///
91/// *Experimental.*
92#[derive(Debug, Clone, PartialEq, Eq)]
93#[non_exhaustive]
94pub struct FileDownload {
95    /// The destination path, as given.
96    pub path: PathBuf,
97    /// Details of the download.
98    pub download: StreamedDownload,
99}
100
101/// Options for the file-writing download methods.
102///
103/// *Experimental.*
104#[derive(Debug, Clone, Default, PartialEq, Eq)]
105#[non_exhaustive]
106pub struct FileDownloadOptions {
107    /// Replace an existing regular file at the destination. Default `false`:
108    /// an existing path is refused. A symbolic link at the destination is
109    /// refused either way.
110    pub overwrite: bool,
111}
112
113impl FileDownloadOptions {
114    /// Default options: refuse an existing destination.
115    #[must_use]
116    pub fn new() -> Self {
117        Self::default()
118    }
119
120    /// Set [`Self::overwrite`].
121    #[must_use]
122    pub fn with_overwrite(mut self, overwrite: bool) -> Self {
123        self.overwrite = overwrite;
124        self
125    }
126}
127
128fn io_error(context: &str, err: &std::io::Error) -> ClientError {
129    ClientError::Io(escape_control_chars(&format!("{context}: {}", err.kind())))
130}
131
132impl Service {
133    /// Stream one format of an artifact revision into `writer`.
134    ///
135    /// *Experimental.* The writer receives bytes **before** the checksum
136    /// comparison is possible. Use it only if you can discard them on error;
137    /// prefer [`Service::download_format_to_file`]. The writer is flushed on
138    /// success.
139    ///
140    /// Like [`Service::download_format`], an external `url` is fetched without
141    /// the TEA access token.
142    ///
143    /// # Errors
144    ///
145    /// As [`Service::download_format`], plus [`ClientError::Io`] when the
146    /// writer fails. [`ClientError::Integrity`] is returned after the bytes
147    /// were written.
148    pub async fn download_format_to_writer<W>(
149        &self,
150        artifact: &Artifact,
151        media_type: &str,
152        writer: &mut W,
153    ) -> Result<StreamedDownload, ClientError>
154    where
155        W: AsyncWrite + Unpin + Send,
156    {
157        let (url, api_prefix, checksums) = self.format_source(artifact, media_type)?;
158        self.stream_to_writer(url, api_prefix, &checksums, writer)
159            .await
160    }
161
162    /// Stream one format of an artifact revision into a file.
163    ///
164    /// *Experimental.* The file at `dest` appears only after the stream ended
165    /// cleanly and the checksums passed the client's policy; see the module
166    /// documentation. `dest`'s parent directory must exist.
167    ///
168    /// A `NotDeclared` integrity outcome is committed, as in
169    /// [`Service::download_format`]; inspect
170    /// [`StreamedDownload::integrity`] when that matters.
171    ///
172    /// # Errors
173    ///
174    /// As [`Service::download_format_to_writer`]; also [`ClientError::Io`]
175    /// when `dest` exists and `overwrite` is not set, is a symbolic link, or
176    /// cannot be created.
177    pub async fn download_format_to_file(
178        &self,
179        artifact: &Artifact,
180        media_type: &str,
181        dest: &Path,
182        options: &FileDownloadOptions,
183    ) -> Result<FileDownload, ClientError> {
184        let (url, api_prefix, checksums) = self.format_source(artifact, media_type)?;
185        self.stream_to_file(url, api_prefix, &checksums, dest, options)
186            .await
187    }
188
189    /// Stream `GET /artifact/{uuid}/{version}/download` into a file.
190    ///
191    /// *Experimental.* `checksums` are the ones declared for the selected
192    /// format; with none, the outcome is `NotDeclared`.
193    ///
194    /// # Errors
195    ///
196    /// As [`Service::download_format_to_file`].
197    pub async fn download_artifact_to_file(
198        &self,
199        id: libtea_core::ArtifactId,
200        version: u64,
201        media_type: Option<&str>,
202        checksums: &[libtea_core::Checksum],
203        dest: &Path,
204        options: &FileDownloadOptions,
205    ) -> Result<FileDownload, ClientError> {
206        let (url, api_prefix) =
207            self.api_source(&format!("artifact/{id}/{version}/download"), media_type)?;
208        self.stream_to_file(url, api_prefix, checksums, dest, options)
209            .await
210    }
211
212    /// Stream `GET /artifact/{uuid}/latest/download` into a file.
213    ///
214    /// *Experimental.* See [`Service::download_artifact_to_file`].
215    ///
216    /// # Errors
217    ///
218    /// As [`Service::download_format_to_file`].
219    pub async fn download_latest_artifact_to_file(
220        &self,
221        id: libtea_core::ArtifactId,
222        media_type: Option<&str>,
223        checksums: &[libtea_core::Checksum],
224        dest: &Path,
225        options: &FileDownloadOptions,
226    ) -> Result<FileDownload, ClientError> {
227        let (url, api_prefix) =
228            self.api_source(&format!("artifact/{id}/latest/download"), media_type)?;
229        self.stream_to_file(url, api_prefix, checksums, dest, options)
230            .await
231    }
232
233    fn format_source(
234        &self,
235        artifact: &Artifact,
236        media_type: &str,
237    ) -> Result<(Url, Option<Url>, Vec<libtea_core::Checksum>), ClientError> {
238        let format = artifact.format(media_type).ok_or_else(|| {
239            ClientError::Model(libtea_core::ModelError::Invalid(format!(
240                "artifact has no format `{media_type}`"
241            )))
242        })?;
243        format.validate()?;
244        let checksums = format.checksums.clone().unwrap_or_default();
245        if let Some(external) = &format.url {
246            let url = Url::parse(external).map_err(|_| {
247                ClientError::Model(libtea_core::ModelError::Invalid(
248                    "external artifact URL".into(),
249                ))
250            })?;
251            return Ok((url, None, checksums));
252        }
253        let (url, prefix) = self.api_source(
254            &format!("artifact/{}/{}/download", artifact.uuid, artifact.version),
255            Some(media_type),
256        )?;
257        Ok((url, prefix, checksums))
258    }
259
260    fn api_source(
261        &self,
262        path: &str,
263        media_type: Option<&str>,
264    ) -> Result<(Url, Option<Url>), ClientError> {
265        let mut query = Vec::new();
266        if let Some(media_type) = media_type {
267            query.push(("mediaType", media_type));
268        }
269        let url = crate::transport::operation_url(self.prefix_ref(), path, &query)?;
270        Ok((url, Some(self.prefix_ref().clone())))
271    }
272
273    async fn stream_to_file(
274        &self,
275        url: Url,
276        api_prefix: Option<Url>,
277        checksums: &[libtea_core::Checksum],
278        dest: &Path,
279        options: &FileDownloadOptions,
280    ) -> Result<FileDownload, ClientError> {
281        let name = dest.file_name().ok_or_else(|| {
282            ClientError::Io(escape_control_chars(&format!(
283                "{} has no file name",
284                dest.display()
285            )))
286        })?;
287        check_destination(dest, options)?;
288        let dir = dest
289            .parent()
290            .filter(|parent| !parent.as_os_str().is_empty())
291            .unwrap_or_else(|| Path::new("."));
292
293        remove_stale_parts(dir, name);
294        let (temp_path, file) = create_temp(dir, name).await?;
295        // Declared before the writer, so it is dropped (and removes the file)
296        // after the writer closed it.
297        let mut guard = TempFile {
298            path: Some(temp_path.clone()),
299        };
300        let mut writer = tokio::io::BufWriter::new(file);
301        let download = self
302            .stream_to_writer(url, api_prefix, checksums, &mut writer)
303            .await?;
304        writer
305            .get_ref()
306            .sync_all()
307            .await
308            .map_err(|err| io_error("syncing the download", &err))?;
309        drop(writer);
310
311        // The destination may have changed while the download ran.
312        check_destination(dest, options)?;
313        commit_file(&temp_path, dest, options)?;
314        guard.path = None;
315        Ok(FileDownload {
316            path: dest.to_path_buf(),
317            download,
318        })
319    }
320
321    async fn stream_to_writer<W>(
322        &self,
323        url: Url,
324        api_prefix: Option<Url>,
325        checksums: &[libtea_core::Checksum],
326        writer: &mut W,
327    ) -> Result<StreamedDownload, ClientError>
328    where
329        W: AsyncWrite + Unpin + Send,
330    {
331        let inner = &self.client_ref().inner;
332        let max = inner.limits.max_artifact_bytes;
333        let mut call = Call {
334            method: reqwest::Method::GET,
335            url,
336            api_prefix,
337            artifact: true,
338            body: None,
339            content_type: None,
340            basic_auth: false,
341            if_none_match: None,
342            if_modified_since: None,
343            max_body: max,
344        };
345
346        // Cache lookup. A streamed body is stored already decoded, so an entry
347        // that says otherwise is not used.
348        let cache = inner.cache.clone();
349        let key = cache.as_ref().and_then(|_| inner.cache_key_for(&call.url));
350        let mut existing = None;
351        if let Some(cache) = &cache {
352            let Some(key) = &key else {
353                return if cache.offline {
354                    Err(ClientError::Offline)
355                } else {
356                    self.stream_network(call, checksums, writer, None, None)
357                        .await
358                };
359            };
360            // A cache hit is subject to the destination rules and the size limit
361            // of this client, whoever stored it and whenever.
362            inner.policy.check_url(&call.url)?;
363            existing = cache.load(key).await.filter(|(meta, _)| meta.decoded);
364            if existing.as_ref().is_some_and(|(_, body)| body.len() > max) {
365                cache.remove(key).await;
366                if cache.offline {
367                    return Err(ClientError::TooLarge);
368                }
369                existing = None;
370            }
371            if cache.offline {
372                let (meta, body) = existing.ok_or(ClientError::Offline)?;
373                return serve_cached(
374                    inner,
375                    Some((cache, key)),
376                    &call.url,
377                    &meta,
378                    &body,
379                    checksums,
380                    writer,
381                )
382                .await;
383            }
384            if let Some((meta, _)) = &existing {
385                call.if_none_match = meta.header("etag").map(str::to_owned);
386                call.if_modified_since = meta.header("last-modified").map(str::to_owned);
387            }
388        }
389        self.stream_network(call, checksums, writer, key, existing)
390            .await
391    }
392
393    async fn stream_network<W>(
394        &self,
395        call: Call,
396        checksums: &[libtea_core::Checksum],
397        writer: &mut W,
398        key: Option<String>,
399        existing: Option<(CacheEntryMeta, Vec<u8>)>,
400    ) -> Result<StreamedDownload, ClientError>
401    where
402        W: AsyncWrite + Unpin + Send,
403    {
404        let inner = &self.client_ref().inner;
405        let max = inner.limits.max_artifact_bytes;
406        let cache = inner.cache.clone();
407        let url = call.url.clone();
408        let start = inner.send_streaming(call).await?;
409        let mut body = match start {
410            StreamStart::Body(body) => body,
411            StreamStart::Other(raw) => {
412                if let (Some(cache), Some(key)) = (&cache, &key) {
413                    if raw.status.as_u16() == 304 {
414                        if let Some((meta, data)) = existing {
415                            let revalidated =
416                                inner.revalidated_meta(cache, meta.clone(), &raw.headers, false);
417                            let shown = revalidated.as_ref().unwrap_or(&meta);
418                            let served = serve_cached(
419                                inner,
420                                Some((cache, key)),
421                                &url,
422                                shown,
423                                &data,
424                                checksums,
425                                writer,
426                            )
427                            .await;
428                            // The entry's age restarts only after its bytes passed
429                            // the checksum check; a failure has already evicted it.
430                            if served.is_ok() {
431                                match revalidated {
432                                    Some(meta) => cache.store(key, meta, data).await,
433                                    None => cache.remove(key).await,
434                                }
435                            }
436                            return served;
437                        }
438                    } else if matches!(raw.status.as_u16(), 404 | 410) {
439                        cache.remove(key).await;
440                    }
441                }
442                return Err(map_api_error(&raw));
443            }
444        };
445
446        // Decide whether to keep a copy while the body streams past.
447        let mut tee = None;
448        if let (Some(cache), Some(key)) = (&cache, &key) {
449            if body.status.as_u16() == 200 {
450                match decide_storage(
451                    &body.headers,
452                    body.authenticated,
453                    cache.config.authenticated,
454                ) {
455                    Ok(()) => tee = cache.start_tee(key).await,
456                    Err(NotStored::NoStore) => cache.remove(key).await,
457                    Err(_) => {}
458                }
459            }
460        }
461
462        let encoding = header_str(&body.headers, CONTENT_ENCODING).map(str::to_owned);
463        let mut decoder = ContentDecoder::new(encoding.as_deref(), max)?;
464        let mut verifier = ChecksumVerifier::with_policy(checksums, inner.checksum_policy);
465        let mut written = 0u64;
466        while let Some(chunk) = body.chunk().await? {
467            decoder.push(&chunk)?;
468            let out = decoder.take_output();
469            tee_write(&mut tee, &out).await;
470            sink(&mut verifier, writer, &mut written, &out).await?;
471        }
472        // `finish` is what rejects a truncated coding stream.
473        let rest = decoder.finish()?;
474        tee_write(&mut tee, &rest).await;
475        sink(&mut verifier, writer, &mut written, &rest).await?;
476        writer
477            .flush()
478            .await
479            .map_err(|err| io_error("flushing the download", &err))?;
480        let integrity = checked(verifier)?;
481        // Only a body that passed its checks reaches the cache.
482        if let (Some(tee), Some(key)) = (tee.take(), &key) {
483            let meta = CacheEntryMeta::new(
484                key,
485                display_url(&url),
486                200,
487                now_secs(),
488                true,
489                &storable_headers(&body.headers),
490            );
491            tee.finish(meta).await;
492        }
493        let etag = header_str(&body.headers, ETAG).map(str::to_owned);
494        let strong_etag = etag
495            .as_ref()
496            .is_some_and(|value| !value.trim().starts_with("W/"));
497        Ok(StreamedDownload {
498            bytes_written: written,
499            content_type: header_str(&body.headers, CONTENT_TYPE).map(str::to_owned),
500            content_encoding: encoding,
501            etag,
502            strong_etag,
503            final_url: body.final_url.to_string(),
504            integrity,
505        })
506    }
507}
508
509/// Add decoded bytes to the cache copy; drop the copy if it cannot continue.
510async fn tee_write(tee: &mut Option<crate::cache::CacheTee>, bytes: &[u8]) {
511    if let Some(active) = tee.as_mut() {
512        if !active.write(bytes).await {
513            *tee = None;
514        }
515    }
516}
517
518/// The integrity report, or the error when the outcome is not acceptable.
519fn checked(verifier: ChecksumVerifier) -> Result<IntegrityReport, ClientError> {
520    let integrity = verifier.finish();
521    if matches!(
522        integrity.outcome,
523        IntegrityOutcome::Verified | IntegrityOutcome::NotDeclared
524    ) {
525        Ok(integrity)
526    } else {
527        Err(ClientError::Integrity {
528            outcome: integrity.outcome.clone(),
529            report: integrity,
530        })
531    }
532}
533
534/// Answer from a cache entry. The bytes go through the same checksum check as
535/// a download: the cache is not trusted.
536async fn serve_cached<W>(
537    inner: &crate::transport::ClientInner,
538    origin: Option<(&Arc<Cache>, &str)>,
539    url: &Url,
540    meta: &CacheEntryMeta,
541    body: &[u8],
542    checksums: &[libtea_core::Checksum],
543    writer: &mut W,
544) -> Result<StreamedDownload, ClientError>
545where
546    W: AsyncWrite + Unpin + Send,
547{
548    let mut verifier = ChecksumVerifier::with_policy(checksums, inner.checksum_policy);
549    let mut written = 0u64;
550    sink(&mut verifier, writer, &mut written, body).await?;
551    writer
552        .flush()
553        .await
554        .map_err(|err| io_error("flushing the download", &err))?;
555    let integrity = match checked(verifier) {
556        Ok(integrity) => integrity,
557        Err(error) => {
558            // Bytes from the cache that fail their checksums are not kept.
559            if let Some((cache, key)) = origin {
560                cache.remove(key).await;
561            }
562            return Err(error);
563        }
564    };
565    let etag = meta.header("etag").map(str::to_owned);
566    let strong_etag = etag
567        .as_ref()
568        .is_some_and(|value| !value.trim().starts_with("W/"));
569    Ok(StreamedDownload {
570        bytes_written: written,
571        content_type: meta.header("content-type").map(str::to_owned),
572        content_encoding: meta.header("content-encoding").map(str::to_owned),
573        etag,
574        strong_etag,
575        final_url: url.to_string(),
576        integrity,
577    })
578}
579
580async fn sink<W>(
581    verifier: &mut ChecksumVerifier,
582    writer: &mut W,
583    written: &mut u64,
584    bytes: &[u8],
585) -> Result<(), ClientError>
586where
587    W: AsyncWrite + Unpin + Send,
588{
589    if bytes.is_empty() {
590        return Ok(());
591    }
592    verifier.update(bytes);
593    writer
594        .write_all(bytes)
595        .await
596        .map_err(|err| io_error("writing the download", &err))?;
597    *written = written.saturating_add(bytes.len() as u64);
598    Ok(())
599}
600
601/// Removes the temporary file unless it was committed. Runs on drop, so a
602/// cancelled future cleans up too (best effort; a failed removal is ignored).
603struct TempFile {
604    path: Option<PathBuf>,
605}
606
607impl Drop for TempFile {
608    fn drop(&mut self) {
609        if let Some(path) = self.path.take() {
610            let _ = std::fs::remove_file(path);
611        }
612    }
613}
614
615static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
616
617/// Refuse a destination that must not be written, before and after the download.
618fn check_destination(dest: &Path, options: &FileDownloadOptions) -> Result<(), ClientError> {
619    match std::fs::symlink_metadata(dest) {
620        Ok(meta) if meta.file_type().is_symlink() => {
621            Err(ClientError::Io(escape_control_chars(&format!(
622                "refusing to write {}: it is a symbolic link",
623                dest.display()
624            ))))
625        }
626        Ok(_) if !options.overwrite => Err(ClientError::Io(escape_control_chars(&format!(
627            "{} already exists; overwrite was not requested",
628            dest.display()
629        )))),
630        Ok(meta) if !meta.is_file() => Err(ClientError::Io(escape_control_chars(&format!(
631            "{} exists and is not a regular file",
632            dest.display()
633        )))),
634        Ok(_) => Ok(()),
635        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
636        Err(err) => Err(io_error("inspecting the destination", &err)),
637    }
638}
639
640/// Partial files older than this, left by a killed process, are removed.
641const STALE_PART_AGE: std::time::Duration = std::time::Duration::from_secs(60 * 60);
642
643/// Remove `.<name>.libtea-*.part` files in `dir` that have not been written to
644/// for an hour. A download in progress touches its file continuously, so a
645/// concurrent one is left alone; so is every file with another name.
646fn remove_stale_parts(dir: &Path, name: &std::ffi::OsStr) {
647    let mut prefix = std::ffi::OsString::from(".");
648    prefix.push(name);
649    prefix.push(".libtea-");
650    let prefix = prefix.to_string_lossy().into_owned();
651    let Ok(read) = std::fs::read_dir(dir) else {
652        return;
653    };
654    let now = std::time::SystemTime::now();
655    for item in read.flatten() {
656        let file_name = item.file_name().to_string_lossy().into_owned();
657        if !file_name.starts_with(&prefix) || !file_name.ends_with(".part") {
658            continue;
659        }
660        let path = item.path();
661        let Ok(meta) = std::fs::symlink_metadata(&path) else {
662            continue;
663        };
664        let stale = meta
665            .modified()
666            .ok()
667            .and_then(|modified| now.duration_since(modified).ok())
668            .is_some_and(|age| age > STALE_PART_AGE);
669        if meta.file_type().is_file() && stale {
670            let _ = std::fs::remove_file(&path);
671        }
672    }
673}
674
675async fn create_temp(
676    dir: &Path,
677    name: &std::ffi::OsStr,
678) -> Result<(PathBuf, tokio::fs::File), ClientError> {
679    let mut last = None;
680    for _ in 0..16 {
681        let mut temp_name = std::ffi::OsString::from(".");
682        temp_name.push(name);
683        temp_name.push(format!(
684            ".libtea-{}-{}.part",
685            std::process::id(),
686            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
687        ));
688        let path = dir.join(temp_name);
689        // `create_new` never follows a symbolic link and fails if the name exists.
690        // The file is private (0600) while its bytes are unverified, and stays
691        // so when it is renamed into place: loosen it deliberately if you want.
692        let mut options = tokio::fs::OpenOptions::new();
693        options.write(true).create_new(true);
694        #[cfg(unix)]
695        options.mode(0o600);
696        match options.open(&path).await {
697            Ok(file) => return Ok((path, file)),
698            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => last = Some(err),
699            Err(err) => return Err(io_error("creating the temporary file", &err)),
700        }
701    }
702    Err(match last {
703        Some(err) => io_error("creating the temporary file", &err),
704        None => ClientError::Io("creating the temporary file".into()),
705    })
706}
707
708/// Move the finished temporary file to `dest`.
709///
710/// Without `overwrite` the move is a hard link, which fails if `dest` exists or
711/// appears in the meantime. Any failure to link is an error: this does not fall
712/// back to a rename, which would silently replace a file that appeared in the
713/// window. A filesystem without hard links therefore needs `overwrite`.
714fn commit_file(temp: &Path, dest: &Path, options: &FileDownloadOptions) -> Result<(), ClientError> {
715    commit_with(temp, dest, options, |from, to| std::fs::hard_link(from, to))
716}
717
718fn commit_with(
719    temp: &Path,
720    dest: &Path,
721    options: &FileDownloadOptions,
722    link: impl Fn(&Path, &Path) -> std::io::Result<()>,
723) -> Result<(), ClientError> {
724    if options.overwrite {
725        return std::fs::rename(temp, dest)
726            .map_err(|err| io_error("committing the download", &err));
727    }
728    match link(temp, dest) {
729        Ok(()) => {
730            let _ = std::fs::remove_file(temp);
731            Ok(())
732        }
733        Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
734            Err(io_error("committing the download (the destination exists)", &err))
735        }
736        Err(err) => Err(ClientError::Io(escape_control_chars(&format!(
737            "committing the download: {} (without `overwrite` this needs a filesystem with hard links)",
738            err.kind()
739        )))),
740    }
741}
742
743#[cfg(all(test, unix))]
744mod commit_tests {
745    use super::*;
746    use std::io::{Error, ErrorKind};
747
748    fn dir(tag: &str) -> PathBuf {
749        let dir = std::env::temp_dir().join(format!("libtea-commit-{tag}-{}", std::process::id()));
750        let _ = std::fs::remove_dir_all(&dir);
751        std::fs::create_dir_all(&dir).unwrap();
752        dir
753    }
754
755    #[test]
756    fn a_link_failure_other_than_exists_is_an_error_and_never_renames() {
757        let d = dir("nolink");
758        let (temp, dest) = (d.join("t.part"), d.join("out"));
759        for kind in [
760            ErrorKind::Unsupported,
761            ErrorKind::PermissionDenied,
762            ErrorKind::Other,
763        ] {
764            std::fs::write(&temp, b"new").unwrap();
765            let result = commit_with(&temp, &dest, &FileDownloadOptions::new(), |_, _| {
766                Err(Error::from(kind))
767            });
768            assert!(matches!(result, Err(ClientError::Io(_))), "{kind:?}");
769            assert!(
770                !dest.exists(),
771                "{kind:?}: the destination was written anyway"
772            );
773            assert!(temp.exists(), "the caller's guard owns the temporary file");
774        }
775        let _ = std::fs::remove_dir_all(d);
776    }
777
778    #[test]
779    fn an_existing_destination_is_refused_and_a_free_one_is_linked() {
780        let d = dir("exists");
781        let (temp, dest) = (d.join("t.part"), d.join("out"));
782        std::fs::write(&temp, b"new").unwrap();
783        std::fs::write(&dest, b"old").unwrap();
784        let refused = commit_file(&temp, &dest, &FileDownloadOptions::new());
785        assert!(matches!(refused, Err(ClientError::Io(_))));
786        assert_eq!(std::fs::read(&dest).unwrap(), b"old");
787        std::fs::remove_file(&dest).unwrap();
788        commit_file(&temp, &dest, &FileDownloadOptions::new()).unwrap();
789        assert_eq!(std::fs::read(&dest).unwrap(), b"new");
790        assert!(!temp.exists());
791        let _ = std::fs::remove_dir_all(d);
792    }
793
794    #[test]
795    fn overwrite_renames_and_never_tries_to_link() {
796        let d = dir("overwrite");
797        let (temp, dest) = (d.join("t.part"), d.join("out"));
798        std::fs::write(&temp, b"new").unwrap();
799        std::fs::write(&dest, b"old").unwrap();
800        commit_with(
801            &temp,
802            &dest,
803            &FileDownloadOptions::new().with_overwrite(true),
804            |_, _| panic!("link must not be used with overwrite"),
805        )
806        .unwrap();
807        assert_eq!(std::fs::read(&dest).unwrap(), b"new");
808        let _ = std::fs::remove_dir_all(d);
809    }
810}