1use 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#[derive(Debug, Clone, PartialEq, Eq)]
69#[non_exhaustive]
70pub struct StreamedDownload {
71 pub bytes_written: u64,
73 pub content_type: Option<String>,
75 pub content_encoding: Option<String>,
77 pub etag: Option<String>,
79 pub strong_etag: bool,
81 pub final_url: String,
83 pub integrity: IntegrityReport,
87}
88
89#[derive(Debug, Clone, PartialEq, Eq)]
93#[non_exhaustive]
94pub struct FileDownload {
95 pub path: PathBuf,
97 pub download: StreamedDownload,
99}
100
101#[derive(Debug, Clone, Default, PartialEq, Eq)]
105#[non_exhaustive]
106pub struct FileDownloadOptions {
107 pub overwrite: bool,
111}
112
113impl FileDownloadOptions {
114 #[must_use]
116 pub fn new() -> Self {
117 Self::default()
118 }
119
120 #[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 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 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 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 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 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 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 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 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 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 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 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 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
509async 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
518fn 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
534async 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 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
601struct 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
617fn 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
640const STALE_PART_AGE: std::time::Duration = std::time::Duration::from_secs(60 * 60);
642
643fn 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 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
708fn 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}