cargo/sources/registry/
mod.rs

1//! A `Source` for registry-based packages.
2//!
3//! # What's a Registry?
4//!
5//! [Registries] are central locations where packages can be uploaded to,
6//! discovered, and searched for. The purpose of a registry is to have a
7//! location that serves as permanent storage for versions of a crate over time.
8//!
9//! Compared to git sources (see [`GitSource`]), a registry provides many
10//! packages as well as many versions simultaneously. Git sources can also
11//! have commits deleted through rebasings where registries cannot have their
12//! versions deleted.
13//!
14//! In Cargo, [`RegistryData`] is an abstraction over each kind of actual
15//! registry, and [`RegistrySource`] connects those implementations to
16//! [`Source`] trait. Two prominent features these abstractions provide are
17//!
18//! * A way to query the metadata of a package from a registry. The metadata
19//!   comes from the index.
20//! * A way to download package contents (a.k.a source files) that are required
21//!   when building the package itself.
22//!
23//! We'll cover each functionality later.
24//!
25//! [Registries]: https://doc.rust-lang.org/nightly/cargo/reference/registries.html
26//! [`GitSource`]: super::GitSource
27//!
28//! # Different Kinds of Registries
29//!
30//! Cargo provides multiple kinds of registries. Each of them serves the index
31//! and package contents in a slightly different way. Namely,
32//!
33//! * [`LocalRegistry`] --- Serves the index and package contents entirely on
34//!   a local filesystem.
35//! * [`RemoteRegistry`] --- Serves the index ahead of time from a Git
36//!   repository, and package contents are downloaded as needed.
37//! * [`HttpRegistry`] --- Serves both the index and package contents on demand
38//!   over a HTTP-based registry API. This is the default starting from 1.70.0.
39//!
40//! Each registry has its own [`RegistryData`] implementation, and can be
41//! created from either [`RegistrySource::local`] or [`RegistrySource::remote`].
42//!
43//! [`LocalRegistry`]: local::LocalRegistry
44//! [`RemoteRegistry`]: remote::RemoteRegistry
45//! [`HttpRegistry`]: http_remote::HttpRegistry
46//!
47//! # The Index of a Registry
48//!
49//! One of the major difficulties with a registry is that hosting so many
50//! packages may quickly run into performance problems when dealing with
51//! dependency graphs. It's infeasible for cargo to download the entire contents
52//! of the registry just to resolve one package's dependencies, for example. As
53//! a result, cargo needs some efficient method of querying what packages are
54//! available on a registry, what versions are available, and what the
55//! dependencies for each version is.
56//!
57//! To solve the problem, a registry must provide an index of package metadata.
58//! The index of a registry is essentially an easily query-able version of the
59//! registry's database for a list of versions of a package as well as a list
60//! of dependencies for each version. The exact format of the index is
61//! described later.
62//!
63//! See the [`index`] module for topics about the management, parsing, caching,
64//! and versioning for the on-disk index.
65//!
66//! ## The Format of The Index
67//!
68//! The index is a store for the list of versions for all packages known, so its
69//! format on disk is optimized slightly to ensure that `ls registry` doesn't
70//! produce a list of all packages ever known. The index also wants to ensure
71//! that there's not a million files which may actually end up hitting
72//! filesystem limits at some point. To this end, a few decisions were made
73//! about the format of the registry:
74//!
75//! 1. Each crate will have one file corresponding to it. Each version for a
76//!    crate will just be a line in this file (see [`cargo_util_schemas::index::IndexPackage`] for its
77//!    representation).
78//! 2. There will be two tiers of directories for crate names, under which
79//!    crates corresponding to those tiers will be located.
80//!    (See [`cargo_util::registry::make_dep_path`] for the implementation of
81//!    this layout hierarchy.)
82//!
83//! As an example, this is an example hierarchy of an index:
84//!
85//! ```notrust
86//! .
87//! ├── 3
88//! │   └── u
89//! │       └── url
90//! ├── bz
91//! │   └── ip
92//! │       └── bzip2
93//! ├── config.json
94//! ├── en
95//! │   └── co
96//! │       └── encoding
97//! └── li
98//!     ├── bg
99//!     │   └── libgit2
100//!     └── nk
101//!         └── link-config
102//! ```
103//!
104//! The root of the index contains a `config.json` file with a few entries
105//! corresponding to the registry (see [`RegistryConfig`] below).
106//!
107//! Otherwise, there are three numbered directories (1, 2, 3) for crates with
108//! names 1, 2, and 3 characters in length. The 1/2 directories simply have the
109//! crate files underneath them, while the 3 directory is sharded by the first
110//! letter of the crate name.
111//!
112//! Otherwise the top-level directory contains many two-letter directory names,
113//! each of which has many sub-folders with two letters. At the end of all these
114//! are the actual crate files themselves.
115//!
116//! The purpose of this layout is to hopefully cut down on `ls` sizes as well as
117//! efficient lookup based on the crate name itself.
118//!
119//! See [The Cargo Book: Registry Index][registry-index] for the public
120//! interface on the index format.
121//!
122//! [registry-index]: https://doc.rust-lang.org/nightly/cargo/reference/registry-index.html
123//!
124//! ## The Index Files
125//!
126//! Each file in the index is the history of one crate over time. Each line in
127//! the file corresponds to one version of a crate, stored in JSON format (see
128//! the [`cargo_util_schemas::index::IndexPackage`] structure).
129//!
130//! As new versions are published, new lines are appended to this file. **The
131//! only modifications to this file that should happen over time are yanks of a
132//! particular version.**
133//!
134//! # Downloading Packages
135//!
136//! The purpose of the index was to provide an efficient method to resolve the
137//! dependency graph for a package. After resolution has been performed, we need
138//! to download the contents of packages so we can read the full manifest and
139//! build the source code.
140//!
141//! To accomplish this, [`RegistryData::download`] will "make" an HTTP request
142//! per-package requested to download tarballs into a local cache. These
143//! tarballs will then be unpacked into a destination folder.
144//!
145//! Note that because versions uploaded to the registry are frozen forever that
146//! the HTTP download and unpacking can all be skipped if the version has
147//! already been downloaded and unpacked. This caching allows us to only
148//! download a package when absolutely necessary.
149//!
150//! # Filesystem Hierarchy
151//!
152//! Overall, the `$HOME/.cargo` looks like this when talking about the registry
153//! (remote registries, specifically):
154//!
155//! ```notrust
156//! # A folder under which all registry metadata is hosted (similar to
157//! # $HOME/.cargo/git)
158//! $HOME/.cargo/registry/
159//!
160//!     # For each registry that cargo knows about (keyed by hostname + hash)
161//!     # there is a folder which is the checked out version of the index for
162//!     # the registry in this location. Note that this is done so cargo can
163//!     # support multiple registries simultaneously
164//!     index/
165//!         registry1-<hash>/
166//!         registry2-<hash>/
167//!         ...
168//!
169//!     # This folder is a cache for all downloaded tarballs (`.crate` file)
170//!     # from a registry. Once downloaded and verified, a tarball never changes.
171//!     cache/
172//!         registry1-<hash>/<pkg>-<version>.crate
173//!         ...
174//!
175//!     # Location in which all tarballs are unpacked. Each tarball is known to
176//!     # be frozen after downloading, so transitively this folder is also
177//!     # frozen once its unpacked (it's never unpacked again)
178//!     # CAVEAT: They are not read-only. See rust-lang/cargo#9455.
179//!     src/
180//!         registry1-<hash>/<pkg>-<version>/...
181//!         ...
182//! ```
183//!
184
185use std::collections::HashSet;
186use std::fs;
187use std::fs::{File, OpenOptions};
188use std::io;
189use std::io::Read;
190use std::io::Write;
191use std::path::{Path, PathBuf};
192use std::task::{Poll, ready};
193
194use annotate_snippets::Level;
195use anyhow::Context as _;
196use cargo_util::paths::{self, exclude_from_backups_and_indexing};
197use flate2::read::GzDecoder;
198use serde::Deserialize;
199use serde::Serialize;
200use tar::Archive;
201use tracing::debug;
202
203use crate::core::dependency::Dependency;
204use crate::core::global_cache_tracker;
205use crate::core::{Package, PackageId, SourceId};
206use crate::sources::PathSource;
207use crate::sources::source::MaybePackage;
208use crate::sources::source::QueryKind;
209use crate::sources::source::Source;
210use crate::util::cache_lock::CacheLockMode;
211use crate::util::interning::InternedString;
212use crate::util::network::PollExt;
213use crate::util::{CargoResult, Filesystem, GlobalContext, LimitErrorReader, restricted_names};
214use crate::util::{VersionExt, hex};
215
216/// The `.cargo-ok` file is used to track if the source is already unpacked.
217/// See [`RegistrySource::unpack_package`] for more.
218///
219/// Not to be confused with `.cargo-ok` file in git sources.
220const PACKAGE_SOURCE_LOCK: &str = ".cargo-ok";
221
222pub const CRATES_IO_INDEX: &str = "https://github.com/rust-lang/crates.io-index";
223pub const CRATES_IO_HTTP_INDEX: &str = "sparse+https://index.crates.io/";
224pub const CRATES_IO_REGISTRY: &str = "crates-io";
225pub const CRATES_IO_DOMAIN: &str = "crates.io";
226
227/// The content inside `.cargo-ok`.
228/// See [`RegistrySource::unpack_package`] for more.
229#[derive(Deserialize, Serialize)]
230#[serde(rename_all = "kebab-case")]
231struct LockMetadata {
232    /// The version of `.cargo-ok` file
233    v: u32,
234}
235
236/// A [`Source`] implementation for a local or a remote registry.
237///
238/// This contains common functionality that is shared between each registry
239/// kind, with the registry-specific logic implemented as part of the
240/// [`RegistryData`] trait referenced via the `ops` field.
241///
242/// For general concepts of registries, see the [module-level documentation](crate::sources::registry).
243pub struct RegistrySource<'gctx> {
244    /// A unique name of the source (typically used as the directory name
245    /// where its cached content is stored).
246    name: InternedString,
247    /// The unique identifier of this source.
248    source_id: SourceId,
249    /// The path where crate files are extracted (`$CARGO_HOME/registry/src/$REG-HASH`).
250    src_path: Filesystem,
251    /// Local reference to [`GlobalContext`] for convenience.
252    gctx: &'gctx GlobalContext,
253    /// Abstraction for interfacing to the different registry kinds.
254    ops: Box<dyn RegistryData + 'gctx>,
255    /// Interface for managing the on-disk index.
256    index: index::RegistryIndex<'gctx>,
257    /// A set of packages that should be allowed to be used, even if they are
258    /// yanked.
259    ///
260    /// This is populated from the entries in `Cargo.lock` to ensure that
261    /// `cargo update somepkg` won't unlock yanked entries in `Cargo.lock`.
262    /// Otherwise, the resolver would think that those entries no longer
263    /// exist, and it would trigger updates to unrelated packages.
264    yanked_whitelist: HashSet<PackageId>,
265    /// Yanked versions that have already been selected during queries.
266    ///
267    /// As of this writing, this is for not emitting the `--precise <yanked>`
268    /// warning twice, with the assumption of (`dep.package_name()` + `--precise`
269    /// version) being sufficient to uniquely identify the same query result.
270    selected_precise_yanked: HashSet<(InternedString, semver::Version)>,
271}
272
273/// The [`config.json`] file stored in the index.
274///
275/// The config file may look like:
276///
277/// ```json
278/// {
279///     "dl": "https://example.com/api/{crate}/{version}/download",
280///     "api": "https://example.com/api",
281///     "auth-required": false             # unstable feature (RFC 3139)
282/// }
283/// ```
284///
285/// [`config.json`]: https://doc.rust-lang.org/nightly/cargo/reference/registry-index.html#index-configuration
286#[derive(Deserialize, Debug, Clone)]
287#[serde(rename_all = "kebab-case")]
288pub struct RegistryConfig {
289    /// Download endpoint for all crates.
290    ///
291    /// The string is a template which will generate the download URL for the
292    /// tarball of a specific version of a crate. The substrings `{crate}` and
293    /// `{version}` will be replaced with the crate's name and version
294    /// respectively.  The substring `{prefix}` will be replaced with the
295    /// crate's prefix directory name, and the substring `{lowerprefix}` will
296    /// be replaced with the crate's prefix directory name converted to
297    /// lowercase. The substring `{sha256-checksum}` will be replaced with the
298    /// crate's sha256 checksum.
299    ///
300    /// For backwards compatibility, if the string does not contain any
301    /// markers (`{crate}`, `{version}`, `{prefix}`, or `{lowerprefix}`), it
302    /// will be extended with `/{crate}/{version}/download` to
303    /// support registries like crates.io which were created before the
304    /// templating setup was created.
305    ///
306    /// For more on the template of the download URL, see [Index Configuration](
307    /// https://doc.rust-lang.org/nightly/cargo/reference/registry-index.html#index-configuration).
308    pub dl: String,
309
310    /// API endpoint for the registry. This is what's actually hit to perform
311    /// operations like yanks, owner modifications, publish new crates, etc.
312    /// If this is None, the registry does not support API commands.
313    pub api: Option<String>,
314
315    /// Whether all operations require authentication. See [RFC 3139].
316    ///
317    /// [RFC 3139]: https://rust-lang.github.io/rfcs/3139-cargo-alternative-registry-auth.html
318    #[serde(default)]
319    pub auth_required: bool,
320}
321
322/// Result from loading data from a registry.
323pub enum LoadResponse {
324    /// The cache is valid. The cached data should be used.
325    CacheValid,
326
327    /// The cache is out of date. Returned data should be used.
328    Data {
329        raw_data: Vec<u8>,
330        /// Version of this data to determine whether it is out of date.
331        index_version: Option<String>,
332    },
333
334    /// The requested crate was found.
335    NotFound,
336}
337
338/// An abstract interface to handle both a local and remote registry.
339///
340/// This allows [`RegistrySource`] to abstractly handle each registry kind.
341///
342/// For general concepts of registries, see the [module-level documentation](crate::sources::registry).
343pub trait RegistryData {
344    /// Performs initialization for the registry.
345    ///
346    /// This should be safe to call multiple times, the implementation is
347    /// expected to not do any work if it is already prepared.
348    fn prepare(&self) -> CargoResult<()>;
349
350    /// Returns the path to the index.
351    ///
352    /// Note that different registries store the index in different formats
353    /// (remote = git, http & local = files).
354    fn index_path(&self) -> &Filesystem;
355
356    /// Returns the path of the directory that stores the cache of `.crate` files.
357    ///
358    /// The directory is currently expected to contain a flat list of all `.crate` files,
359    /// named `<package-name>-<version>.crate`.
360    fn cache_path(&self) -> &Filesystem;
361
362    /// Loads the JSON for a specific named package from the index.
363    ///
364    /// * `root` is the root path to the index.
365    /// * `path` is the relative path to the package to load (like `ca/rg/cargo`).
366    /// * `index_version` is the version of the requested crate data currently
367    ///    in cache. This is useful for checking if a local cache is outdated.
368    fn load(
369        &mut self,
370        root: &Path,
371        path: &Path,
372        index_version: Option<&str>,
373    ) -> Poll<CargoResult<LoadResponse>>;
374
375    /// Loads the `config.json` file and returns it.
376    ///
377    /// Local registries don't have a config, and return `None`.
378    fn config(&mut self) -> Poll<CargoResult<Option<RegistryConfig>>>;
379
380    /// Invalidates locally cached data.
381    fn invalidate_cache(&mut self);
382
383    /// If quiet, the source should not display any progress or status messages.
384    fn set_quiet(&mut self, quiet: bool);
385
386    /// Is the local cached data up-to-date?
387    fn is_updated(&self) -> bool;
388
389    /// Prepare to start downloading a `.crate` file.
390    ///
391    /// Despite the name, this doesn't actually download anything. If the
392    /// `.crate` is already downloaded, then it returns [`MaybeLock::Ready`].
393    /// If it hasn't been downloaded, then it returns [`MaybeLock::Download`]
394    /// which contains the URL to download. The [`crate::core::package::Downloads`]
395    /// system handles the actual download process. After downloading, it
396    /// calls [`Self::finish_download`] to save the downloaded file.
397    ///
398    /// `checksum` is currently only used by local registries to verify the
399    /// file contents (because local registries never actually download
400    /// anything). Remote registries will validate the checksum in
401    /// `finish_download`. For already downloaded `.crate` files, it does not
402    /// validate the checksum, assuming the filesystem does not suffer from
403    /// corruption or manipulation.
404    fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock>;
405
406    /// Finish a download by saving a `.crate` file to disk.
407    ///
408    /// After [`crate::core::package::Downloads`] has finished a download,
409    /// it will call this to save the `.crate` file. This is only relevant
410    /// for remote registries. This should validate the checksum and save
411    /// the given data to the on-disk cache.
412    ///
413    /// Returns a [`File`] handle to the `.crate` file, positioned at the start.
414    fn finish_download(&mut self, pkg: PackageId, checksum: &str, data: &[u8])
415    -> CargoResult<File>;
416
417    /// Returns whether or not the `.crate` file is already downloaded.
418    fn is_crate_downloaded(&self, _pkg: PackageId) -> bool {
419        true
420    }
421
422    /// Validates that the global package cache lock is held.
423    ///
424    /// Given the [`Filesystem`], this will make sure that the package cache
425    /// lock is held. If not, it will panic. See
426    /// [`GlobalContext::acquire_package_cache_lock`] for acquiring the global lock.
427    ///
428    /// Returns the [`Path`] to the [`Filesystem`].
429    fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path;
430
431    /// Block until all outstanding `Poll::Pending` requests are `Poll::Ready`.
432    fn block_until_ready(&mut self) -> CargoResult<()>;
433}
434
435/// The status of [`RegistryData::download`] which indicates if a `.crate`
436/// file has already been downloaded, or if not then the URL to download.
437pub enum MaybeLock {
438    /// The `.crate` file is already downloaded. [`File`] is a handle to the
439    /// opened `.crate` file on the filesystem.
440    Ready(File),
441    /// The `.crate` file is not downloaded, here's the URL to download it from.
442    ///
443    /// `descriptor` is just a text string to display to the user of what is
444    /// being downloaded.
445    Download {
446        url: String,
447        descriptor: String,
448        authorization: Option<String>,
449    },
450}
451
452mod download;
453mod http_remote;
454pub(crate) mod index;
455pub use index::IndexSummary;
456mod local;
457mod remote;
458
459/// Generates a unique name for [`SourceId`] to have a unique path to put their
460/// index files.
461fn short_name(id: SourceId, is_shallow: bool) -> String {
462    // CAUTION: This should not change between versions. If you change how
463    // this is computed, it will orphan previously cached data, forcing the
464    // cache to be rebuilt and potentially wasting significant disk space. If
465    // you change it, be cautious of the impact. See `test_cratesio_hash` for
466    // a similar discussion.
467    let hash = hex::short_hash(&id);
468    let ident = id.url().host_str().unwrap_or("").to_string();
469    let mut name = format!("{}-{}", ident, hash);
470    if is_shallow {
471        name.push_str("-shallow");
472    }
473    name
474}
475
476impl<'gctx> RegistrySource<'gctx> {
477    /// Creates a [`Source`] of a "remote" registry.
478    /// It could be either an HTTP-based [`http_remote::HttpRegistry`] or
479    /// a Git-based [`remote::RemoteRegistry`].
480    ///
481    /// * `yanked_whitelist` --- Packages allowed to be used, even if they are yanked.
482    pub fn remote(
483        source_id: SourceId,
484        yanked_whitelist: &HashSet<PackageId>,
485        gctx: &'gctx GlobalContext,
486    ) -> CargoResult<RegistrySource<'gctx>> {
487        assert!(source_id.is_remote_registry());
488        let name = short_name(
489            source_id,
490            gctx.cli_unstable()
491                .git
492                .map_or(false, |features| features.shallow_index)
493                && !source_id.is_sparse(),
494        );
495        let ops = if source_id.is_sparse() {
496            Box::new(http_remote::HttpRegistry::new(source_id, gctx, &name)?) as Box<_>
497        } else {
498            Box::new(remote::RemoteRegistry::new(source_id, gctx, &name)) as Box<_>
499        };
500
501        Ok(RegistrySource::new(
502            source_id,
503            gctx,
504            &name,
505            ops,
506            yanked_whitelist,
507        ))
508    }
509
510    /// Creates a [`Source`] of a local registry, with [`local::LocalRegistry`] under the hood.
511    ///
512    /// * `path` --- The root path of a local registry on the file system.
513    /// * `yanked_whitelist` --- Packages allowed to be used, even if they are yanked.
514    pub fn local(
515        source_id: SourceId,
516        path: &Path,
517        yanked_whitelist: &HashSet<PackageId>,
518        gctx: &'gctx GlobalContext,
519    ) -> RegistrySource<'gctx> {
520        let name = short_name(source_id, false);
521        let ops = local::LocalRegistry::new(path, gctx, &name);
522        RegistrySource::new(source_id, gctx, &name, Box::new(ops), yanked_whitelist)
523    }
524
525    /// Creates a source of a registry. This is a inner helper function.
526    ///
527    /// * `name` --- Name of a path segment which may affect where `.crate`
528    ///   tarballs, the registry index and cache are stored. Expect to be unique.
529    /// * `ops` --- The underlying [`RegistryData`] type.
530    /// * `yanked_whitelist` --- Packages allowed to be used, even if they are yanked.
531    fn new(
532        source_id: SourceId,
533        gctx: &'gctx GlobalContext,
534        name: &str,
535        ops: Box<dyn RegistryData + 'gctx>,
536        yanked_whitelist: &HashSet<PackageId>,
537    ) -> RegistrySource<'gctx> {
538        RegistrySource {
539            name: name.into(),
540            src_path: gctx.registry_source_path().join(name),
541            gctx,
542            source_id,
543            index: index::RegistryIndex::new(source_id, ops.index_path(), gctx),
544            yanked_whitelist: yanked_whitelist.clone(),
545            ops,
546            selected_precise_yanked: HashSet::new(),
547        }
548    }
549
550    /// Decode the [configuration](RegistryConfig) stored within the registry.
551    ///
552    /// This requires that the index has been at least checked out.
553    pub fn config(&mut self) -> Poll<CargoResult<Option<RegistryConfig>>> {
554        self.ops.config()
555    }
556
557    /// Unpacks a downloaded package into a location where it's ready to be
558    /// compiled.
559    ///
560    /// No action is taken if the source looks like it's already unpacked.
561    ///
562    /// # History of interruption detection with `.cargo-ok` file
563    ///
564    /// Cargo has always included a `.cargo-ok` file ([`PACKAGE_SOURCE_LOCK`])
565    /// to detect if extraction was interrupted, but it was originally empty.
566    ///
567    /// In 1.34, Cargo was changed to create the `.cargo-ok` file before it
568    /// started extraction to implement fine-grained locking. After it was
569    /// finished extracting, it wrote two bytes to indicate it was complete.
570    /// It would use the length check to detect if it was possibly interrupted.
571    ///
572    /// In 1.36, Cargo changed to not use fine-grained locking, and instead used
573    /// a global lock. The use of `.cargo-ok` was no longer needed for locking
574    /// purposes, but was kept to detect when extraction was interrupted.
575    ///
576    /// In 1.49, Cargo changed to not create the `.cargo-ok` file before it
577    /// started extraction to deal with `.crate` files that inexplicably had
578    /// a `.cargo-ok` file in them.
579    ///
580    /// In 1.64, Cargo changed to detect `.crate` files with `.cargo-ok` files
581    /// in them in response to [CVE-2022-36113], which dealt with malicious
582    /// `.crate` files making `.cargo-ok` a symlink causing cargo to write "ok"
583    /// to any arbitrary file on the filesystem it has permission to.
584    ///
585    /// In 1.71, `.cargo-ok` changed to contain a JSON `{ v: 1 }` to indicate
586    /// the version of it. A failure of parsing will result in a heavy-hammer
587    /// approach that unpacks the `.crate` file again. This is in response to a
588    /// security issue that the unpacking didn't respect umask on Unix systems.
589    ///
590    /// This is all a long-winded way of explaining the circumstances that might
591    /// cause a directory to contain a `.cargo-ok` file that is empty or
592    /// otherwise corrupted. Either this was extracted by a version of Rust
593    /// before 1.34, in which case everything should be fine. However, an empty
594    /// file created by versions 1.36 to 1.49 indicates that the extraction was
595    /// interrupted and that we need to start again.
596    ///
597    /// Another possibility is that the filesystem is simply corrupted, in
598    /// which case deleting the directory might be the safe thing to do. That
599    /// is probably unlikely, though.
600    ///
601    /// To be safe, we delete the directory and start over again if an empty
602    /// `.cargo-ok` file is found.
603    ///
604    /// [CVE-2022-36113]: https://blog.rust-lang.org/2022/09/14/cargo-cves.html#arbitrary-file-corruption-cve-2022-36113
605    fn unpack_package(&self, pkg: PackageId, tarball: &File) -> CargoResult<PathBuf> {
606        let package_dir = format!("{}-{}", pkg.name(), pkg.version());
607        let dst = self.src_path.join(&package_dir);
608        let path = dst.join(PACKAGE_SOURCE_LOCK);
609        let path = self
610            .gctx
611            .assert_package_cache_locked(CacheLockMode::DownloadExclusive, &path);
612        let unpack_dir = path.parent().unwrap();
613        match fs::read_to_string(path) {
614            Ok(ok) => match serde_json::from_str::<LockMetadata>(&ok) {
615                Ok(lock_meta) if lock_meta.v == 1 => {
616                    self.gctx
617                        .deferred_global_last_use()?
618                        .mark_registry_src_used(global_cache_tracker::RegistrySrc {
619                            encoded_registry_name: self.name,
620                            package_dir: package_dir.into(),
621                            size: None,
622                        });
623                    return Ok(unpack_dir.to_path_buf());
624                }
625                _ => {
626                    if ok == "ok" {
627                        tracing::debug!("old `ok` content found, clearing cache");
628                    } else {
629                        tracing::warn!("unrecognized .cargo-ok content, clearing cache: {ok}");
630                    }
631                    // See comment of `unpack_package` about why removing all stuff.
632                    paths::remove_dir_all(dst.as_path_unlocked())?;
633                }
634            },
635            Err(e) if e.kind() == io::ErrorKind::NotFound => {}
636            Err(e) => anyhow::bail!("unable to read .cargo-ok file at {path:?}: {e}"),
637        }
638        dst.create_dir()?;
639
640        let bytes_written = unpack(self.gctx, tarball, unpack_dir, &|_| true)?;
641        update_mtime_for_generated_files(unpack_dir);
642
643        // Now that we've finished unpacking, create and write to the lock file to indicate that
644        // unpacking was successful.
645        let mut ok = OpenOptions::new()
646            .create_new(true)
647            .read(true)
648            .write(true)
649            .open(&path)
650            .with_context(|| format!("failed to open `{}`", path.display()))?;
651
652        let lock_meta = LockMetadata { v: 1 };
653        write!(ok, "{}", serde_json::to_string(&lock_meta).unwrap())?;
654
655        self.gctx
656            .deferred_global_last_use()?
657            .mark_registry_src_used(global_cache_tracker::RegistrySrc {
658                encoded_registry_name: self.name,
659                package_dir: package_dir.into(),
660                size: Some(bytes_written),
661            });
662
663        Ok(unpack_dir.to_path_buf())
664    }
665
666    /// Unpacks the `.crate` tarball of the package in a given directory.
667    ///
668    /// Returns the path to the crate tarball directory,
669    /// which is always `<unpack_dir>/<pkg>-<version>`.
670    ///
671    /// This holds some assumptions
672    ///
673    /// * The associated tarball already exists
674    /// * If this is a local registry,
675    ///   the package cache lock must be externally synchronized.
676    ///   Cargo does not take care of it being locked or not.
677    pub fn unpack_package_in(
678        &self,
679        pkg: &PackageId,
680        unpack_dir: &Path,
681        include: &dyn Fn(&Path) -> bool,
682    ) -> CargoResult<PathBuf> {
683        let path = self.ops.cache_path().join(pkg.tarball_name());
684        let path = self.ops.assert_index_locked(&path);
685        let dst = unpack_dir.join(format!("{}-{}", pkg.name(), pkg.version()));
686        let tarball =
687            File::open(path).with_context(|| format!("failed to open {}", path.display()))?;
688        unpack(self.gctx, &tarball, &dst, include)?;
689        update_mtime_for_generated_files(&dst);
690        Ok(dst)
691    }
692
693    /// Turns the downloaded `.crate` tarball file into a [`Package`].
694    ///
695    /// This unconditionally sets checksum for the returned package, so it
696    /// should only be called after doing integrity check. That is to say,
697    /// you need to call either [`RegistryData::download`] or
698    /// [`RegistryData::finish_download`] before calling this method.
699    fn get_pkg(&mut self, package: PackageId, path: &File) -> CargoResult<Package> {
700        let path = self
701            .unpack_package(package, path)
702            .with_context(|| format!("failed to unpack package `{}`", package))?;
703        let mut src = PathSource::new(&path, self.source_id, self.gctx);
704        src.load()?;
705        let mut pkg = match src.download(package)? {
706            MaybePackage::Ready(pkg) => pkg,
707            MaybePackage::Download { .. } => unreachable!(),
708        };
709
710        // After we've loaded the package configure its summary's `checksum`
711        // field with the checksum we know for this `PackageId`.
712        let cksum = self
713            .index
714            .hash(package, &mut *self.ops)
715            .expect("a downloaded dep now pending!?")
716            .expect("summary not found");
717        pkg.manifest_mut()
718            .summary_mut()
719            .set_checksum(cksum.to_string());
720
721        Ok(pkg)
722    }
723}
724
725impl<'gctx> Source for RegistrySource<'gctx> {
726    fn query(
727        &mut self,
728        dep: &Dependency,
729        kind: QueryKind,
730        f: &mut dyn FnMut(IndexSummary),
731    ) -> Poll<CargoResult<()>> {
732        let mut req = dep.version_req().clone();
733
734        // Handle `cargo update --precise` here.
735        if let Some((_, requested)) = self
736            .source_id
737            .precise_registry_version(dep.package_name().as_str())
738            .filter(|(c, to)| {
739                if to.is_prerelease() && self.gctx.cli_unstable().unstable_options {
740                    req.matches_prerelease(c)
741                } else {
742                    req.matches(c)
743                }
744            })
745        {
746            req.precise_to(&requested);
747        }
748
749        let mut called = false;
750        let callback = &mut |s| {
751            called = true;
752            f(s);
753        };
754
755        // If this is a locked dependency, then it came from a lock file and in
756        // theory the registry is known to contain this version. If, however, we
757        // come back with no summaries, then our registry may need to be
758        // updated, so we fall back to performing a lazy update.
759        if kind == QueryKind::Exact && req.is_locked() && !self.ops.is_updated() {
760            debug!("attempting query without update");
761            ready!(
762                self.index
763                    .query_inner(dep.package_name(), &req, &mut *self.ops, &mut |s| {
764                        if matches!(s, IndexSummary::Candidate(_) | IndexSummary::Yanked(_))
765                            && dep.matches(s.as_summary())
766                        {
767                            // We are looking for a package from a lock file so we do not care about yank
768                            callback(s)
769                        }
770                    },)
771            )?;
772            if called {
773                Poll::Ready(Ok(()))
774            } else {
775                debug!("falling back to an update");
776                self.invalidate_cache();
777                Poll::Pending
778            }
779        } else {
780            let mut precise_yanked_in_use = false;
781            ready!(
782                self.index
783                    .query_inner(dep.package_name(), &req, &mut *self.ops, &mut |s| {
784                        let matched = match kind {
785                            QueryKind::Exact | QueryKind::RejectedVersions => {
786                                if req.is_precise() && self.gctx.cli_unstable().unstable_options {
787                                    dep.matches_prerelease(s.as_summary())
788                                } else {
789                                    dep.matches(s.as_summary())
790                                }
791                            }
792                            QueryKind::AlternativeNames => true,
793                            QueryKind::Normalized => true,
794                        };
795                        if !matched {
796                            return;
797                        }
798                        // Next filter out all yanked packages. Some yanked packages may
799                        // leak through if they're in a whitelist (aka if they were
800                        // previously in `Cargo.lock`
801                        match s {
802                            s @ _ if kind == QueryKind::RejectedVersions => callback(s),
803                            s @ IndexSummary::Candidate(_) => callback(s),
804                            s @ IndexSummary::Yanked(_) => {
805                                if self.yanked_whitelist.contains(&s.package_id()) {
806                                    callback(s);
807                                } else if req.is_precise() {
808                                    precise_yanked_in_use = true;
809                                    callback(s);
810                                }
811                            }
812                            IndexSummary::Unsupported(summary, v) => {
813                                tracing::debug!(
814                                    "unsupported schema version {} ({} {})",
815                                    v,
816                                    summary.name(),
817                                    summary.version()
818                                );
819                            }
820                            IndexSummary::Invalid(summary) => {
821                                tracing::debug!(
822                                    "invalid ({} {})",
823                                    summary.name(),
824                                    summary.version()
825                                );
826                            }
827                            IndexSummary::Offline(summary) => {
828                                tracing::debug!(
829                                    "offline ({} {})",
830                                    summary.name(),
831                                    summary.version()
832                                );
833                            }
834                        }
835                    })
836            )?;
837            if precise_yanked_in_use {
838                let name = dep.package_name();
839                let version = req
840                    .precise_version()
841                    .expect("--precise <yanked-version> in use");
842                if self.selected_precise_yanked.insert((name, version.clone())) {
843                    let mut shell = self.gctx.shell();
844                    shell.print_report(
845                        &[Level::WARNING
846                            .secondary_title(format!(
847                                "selected package `{name}@{version}` was yanked by the author"
848                            ))
849                            .element(
850                                Level::HELP
851                                    .message("if possible, try a compatible non-yanked version"),
852                            )],
853                        false,
854                    )?;
855                }
856            }
857            if called {
858                return Poll::Ready(Ok(()));
859            }
860            let mut any_pending = false;
861            if kind == QueryKind::AlternativeNames || kind == QueryKind::Normalized {
862                // Attempt to handle misspellings by searching for a chain of related
863                // names to the original name. The resolver will later
864                // reject any candidates that have the wrong name, and with this it'll
865                // have enough information to offer "a similar crate exists" suggestions.
866                // For now we only try canonicalizing `-` to `_` and vice versa.
867                // More advanced fuzzy searching become in the future.
868                for name_permutation in [
869                    dep.package_name().replace('-', "_"),
870                    dep.package_name().replace('_', "-"),
871                ] {
872                    let name_permutation = name_permutation.into();
873                    if name_permutation == dep.package_name() {
874                        continue;
875                    }
876                    any_pending |= self
877                        .index
878                        .query_inner(name_permutation, &req, &mut *self.ops, &mut |s| {
879                            if !s.is_yanked() {
880                                f(s);
881                            } else if kind == QueryKind::AlternativeNames {
882                                f(s);
883                            }
884                        })?
885                        .is_pending();
886                }
887            }
888            if any_pending {
889                Poll::Pending
890            } else {
891                Poll::Ready(Ok(()))
892            }
893        }
894    }
895
896    fn supports_checksums(&self) -> bool {
897        true
898    }
899
900    fn requires_precise(&self) -> bool {
901        false
902    }
903
904    fn source_id(&self) -> SourceId {
905        self.source_id
906    }
907
908    fn invalidate_cache(&mut self) {
909        self.index.clear_summaries_cache();
910        self.ops.invalidate_cache();
911    }
912
913    fn set_quiet(&mut self, quiet: bool) {
914        self.ops.set_quiet(quiet);
915    }
916
917    fn download(&mut self, package: PackageId) -> CargoResult<MaybePackage> {
918        let hash = loop {
919            match self.index.hash(package, &mut *self.ops)? {
920                Poll::Pending => self.block_until_ready()?,
921                Poll::Ready(hash) => break hash,
922            }
923        };
924        match self.ops.download(package, hash)? {
925            MaybeLock::Ready(file) => self.get_pkg(package, &file).map(MaybePackage::Ready),
926            MaybeLock::Download {
927                url,
928                descriptor,
929                authorization,
930            } => Ok(MaybePackage::Download {
931                url,
932                descriptor,
933                authorization,
934            }),
935        }
936    }
937
938    fn finish_download(&mut self, package: PackageId, data: Vec<u8>) -> CargoResult<Package> {
939        let hash = loop {
940            match self.index.hash(package, &mut *self.ops)? {
941                Poll::Pending => self.block_until_ready()?,
942                Poll::Ready(hash) => break hash,
943            }
944        };
945        let file = self.ops.finish_download(package, hash, &data)?;
946        self.get_pkg(package, &file)
947    }
948
949    fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
950        Ok(pkg.package_id().version().to_string())
951    }
952
953    fn describe(&self) -> String {
954        self.source_id.display_index()
955    }
956
957    fn add_to_yanked_whitelist(&mut self, pkgs: &[PackageId]) {
958        self.yanked_whitelist.extend(pkgs);
959    }
960
961    fn is_yanked(&mut self, pkg: PackageId) -> Poll<CargoResult<bool>> {
962        self.index.is_yanked(pkg, &mut *self.ops)
963    }
964
965    fn block_until_ready(&mut self) -> CargoResult<()> {
966        // Before starting to work on the registry, make sure that
967        // `<cargo_home>/registry` is marked as excluded from indexing and
968        // backups. Older versions of Cargo didn't do this, so we do it here
969        // regardless of whether `<cargo_home>` exists.
970        //
971        // This does not use `create_dir_all_excluded_from_backups_atomic` for
972        // the same reason: we want to exclude it even if the directory already
973        // exists.
974        //
975        // IO errors in creating and marking it are ignored, e.g. in case we're on a
976        // read-only filesystem.
977        let registry_base = self.gctx.registry_base_path();
978        let _ = registry_base.create_dir();
979        exclude_from_backups_and_indexing(&registry_base.into_path_unlocked());
980
981        self.ops.block_until_ready()
982    }
983}
984
985impl RegistryConfig {
986    /// File name of [`RegistryConfig`].
987    const NAME: &'static str = "config.json";
988}
989
990/// Get the maximum unpack size that Cargo permits
991/// based on a given `size` of your compressed file.
992///
993/// Returns the larger one between `size * max compression ratio`
994/// and a fixed max unpacked size.
995///
996/// In reality, the compression ratio usually falls in the range of 2:1 to 10:1.
997/// We choose 20:1 to cover almost all possible cases hopefully.
998/// Any ratio higher than this is considered as a zip bomb.
999///
1000/// In the future we might want to introduce a configurable size.
1001///
1002/// Some of the real world data from common compression algorithms:
1003///
1004/// * <https://www.zlib.net/zlib_tech.html>
1005/// * <https://cran.r-project.org/web/packages/brotli/vignettes/brotli-2015-09-22.pdf>
1006/// * <https://blog.cloudflare.com/results-experimenting-brotli/>
1007/// * <https://tukaani.org/lzma/benchmarks.html>
1008fn max_unpack_size(gctx: &GlobalContext, size: u64) -> u64 {
1009    const SIZE_VAR: &str = "__CARGO_TEST_MAX_UNPACK_SIZE";
1010    const RATIO_VAR: &str = "__CARGO_TEST_MAX_UNPACK_RATIO";
1011    const MAX_UNPACK_SIZE: u64 = 512 * 1024 * 1024; // 512 MiB
1012    const MAX_COMPRESSION_RATIO: usize = 20; // 20:1
1013
1014    let max_unpack_size = if cfg!(debug_assertions) && gctx.get_env(SIZE_VAR).is_ok() {
1015        // For integration test only.
1016        gctx.get_env(SIZE_VAR)
1017            .unwrap()
1018            .parse()
1019            .expect("a max unpack size in bytes")
1020    } else {
1021        MAX_UNPACK_SIZE
1022    };
1023    let max_compression_ratio = if cfg!(debug_assertions) && gctx.get_env(RATIO_VAR).is_ok() {
1024        // For integration test only.
1025        gctx.get_env(RATIO_VAR)
1026            .unwrap()
1027            .parse()
1028            .expect("a max compression ratio in bytes")
1029    } else {
1030        MAX_COMPRESSION_RATIO
1031    };
1032
1033    u64::max(max_unpack_size, size * max_compression_ratio as u64)
1034}
1035
1036/// Set the current [`umask`] value for the given tarball. No-op on non-Unix
1037/// platforms.
1038///
1039/// On Windows, tar only looks at user permissions and tries to set the "read
1040/// only" attribute, so no-op as well.
1041///
1042/// [`umask`]: https://man7.org/linux/man-pages/man2/umask.2.html
1043#[allow(unused_variables)]
1044fn set_mask<R: Read>(tar: &mut Archive<R>) {
1045    #[cfg(unix)]
1046    tar.set_mask(crate::util::get_umask());
1047}
1048
1049/// Unpack a tarball with zip bomb and overwrite protections.
1050fn unpack(
1051    gctx: &GlobalContext,
1052    tarball: &File,
1053    unpack_dir: &Path,
1054    include: &dyn Fn(&Path) -> bool,
1055) -> CargoResult<u64> {
1056    let mut tar = {
1057        let size_limit = max_unpack_size(gctx, tarball.metadata()?.len());
1058        let gz = GzDecoder::new(tarball);
1059        let gz = LimitErrorReader::new(gz, size_limit);
1060        let mut tar = Archive::new(gz);
1061        set_mask(&mut tar);
1062        tar
1063    };
1064    let mut bytes_written = 0;
1065    let prefix = unpack_dir.file_name().unwrap();
1066    let parent = unpack_dir.parent().unwrap();
1067    for entry in tar.entries()? {
1068        let mut entry = entry.context("failed to iterate over archive")?;
1069        let entry_path = entry
1070            .path()
1071            .context("failed to read entry path")?
1072            .into_owned();
1073
1074        if let Ok(path) = entry_path.strip_prefix(prefix) {
1075            if !include(path) {
1076                continue;
1077            }
1078        } else {
1079            // We're going to unpack this tarball into the global source
1080            // directory, but we want to make sure that it doesn't accidentally
1081            // (or maliciously) overwrite source code from other crates. Cargo
1082            // itself should never generate a tarball that hits this error, and
1083            // crates.io should also block uploads with these sorts of tarballs,
1084            // but be extra sure by adding a check here as well.
1085            anyhow::bail!(
1086                "invalid tarball downloaded, contains \
1087                     a file at {entry_path:?} which isn't under {prefix:?}",
1088            )
1089        }
1090
1091        // Prevent unpacking the lockfile from the crate itself.
1092        if entry_path
1093            .file_name()
1094            .map_or(false, |p| p == PACKAGE_SOURCE_LOCK)
1095        {
1096            continue;
1097        }
1098        // Unpacking failed
1099        bytes_written += entry.size();
1100        let mut result = entry.unpack_in(parent).map_err(anyhow::Error::from);
1101        if cfg!(windows) && restricted_names::is_windows_reserved_path(&entry_path) {
1102            result = result.with_context(|| {
1103                format!(
1104                    "`{}` appears to contain a reserved Windows path, \
1105                        it cannot be extracted on Windows",
1106                    entry_path.display()
1107                )
1108            });
1109        }
1110        result.with_context(|| format!("failed to unpack entry at `{}`", entry_path.display()))?;
1111    }
1112
1113    Ok(bytes_written)
1114}
1115
1116/// Workaround for rust-lang/cargo#16237
1117///
1118/// Generated files should have the same deterministic mtime as other files.
1119/// However, since we forgot to set mtime for those files when uploading, they
1120/// always have older mtime (1973-11-29) that prevents zip from packing (requiring >1980)
1121///
1122/// This workaround updates mtime after we unpack the tarball at the destination.
1123fn update_mtime_for_generated_files(pkg_root: &Path) {
1124    const GENERATED_FILES: &[&str] = &["Cargo.lock", "Cargo.toml", ".cargo_vcs_info.json"];
1125    // Hardcoded value be removed once alexcrichton/tar-rs#420 is merged and released.
1126    // See also rust-lang/cargo#16237
1127    const DETERMINISTIC_TIMESTAMP: i64 = 1153704088;
1128
1129    for file in GENERATED_FILES {
1130        let path = pkg_root.join(file);
1131        let mtime = filetime::FileTime::from_unix_time(DETERMINISTIC_TIMESTAMP, 0);
1132        if let Err(e) = filetime::set_file_mtime(&path, mtime) {
1133            tracing::trace!("failed to set deterministic mtime for {path:?}: {e}");
1134        }
1135    }
1136}