Skip to main content

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, a registry provides many packages as well as many
10//! versions simultaneously. Git sources can also have commits deleted through
11//! rebasings where registries cannot have their versions deleted.
12//!
13//! # The Index of a Registry
14//!
15//! One of the major difficulties with a registry is that hosting so many
16//! packages may quickly run into performance problems when dealing with
17//! dependency graphs. It's infeasible for cargo to download the entire contents
18//! of the registry just to resolve one package's dependencies, for example. As
19//! a result, cargo needs some efficient method of querying what packages are
20//! available on a registry, what versions are available, and what the
21//! dependencies for each version is.
22//!
23//! One method of doing so would be having the registry expose an HTTP endpoint
24//! which can be queried with a list of packages and a response of their
25//! dependencies and versions is returned. This is somewhat inefficient however
26//! as we may have to hit the endpoint many times and we may have already
27//! queried for much of the data locally already (for other packages, for
28//! example). This also involves inventing a transport format between the
29//! registry and Cargo itself, so this route was not taken.
30//!
31//! Instead, Cargo communicates with registries through a git repository
32//! referred to as the Index. The Index of a registry is essentially an easily
33//! query-able version of the registry's database for a list of versions of a
34//! package as well as a list of dependencies for each version.
35//!
36//! Using git to host this index provides a number of benefits:
37//!
38//! * The entire index can be stored efficiently locally on disk. This means
39//!   that all queries of a registry can happen locally and don't need to touch
40//!   the network.
41//!
42//! * Updates of the index are quite efficient. Using git buys incremental
43//!   updates, compressed transmission, etc for free. The index must be updated
44//!   each time we need fresh information from a registry, but this is one
45//!   update of a git repository that probably hasn't changed a whole lot so
46//!   it shouldn't be too expensive.
47//!
48//!   Additionally, each modification to the index is just appending a line at
49//!   the end of a file (the exact format is described later). This means that
50//!   the commits for an index are quite small and easily applied/compressable.
51//!
52//! ## The format of the Index
53//!
54//! The index is a store for the list of versions for all packages known, so its
55//! format on disk is optimized slightly to ensure that `ls registry` doesn't
56//! produce a list of all packages ever known. The index also wants to ensure
57//! that there's not a million files which may actually end up hitting
58//! filesystem limits at some point. To this end, a few decisions were made
59//! about the format of the registry:
60//!
61//! 1. Each crate will have one file corresponding to it. Each version for a
62//!    crate will just be a line in this file.
63//! 2. There will be two tiers of directories for crate names, under which
64//!    crates corresponding to those tiers will be located.
65//!
66//! As an example, this is an example hierarchy of an index:
67//!
68//! ```notrust
69//! .
70//! ├── 3
71//! │   └── u
72//! │       └── url
73//! ├── bz
74//! │   └── ip
75//! │       └── bzip2
76//! ├── config.json
77//! ├── en
78//! │   └── co
79//! │       └── encoding
80//! └── li
81//!     ├── bg
82//!     │   └── libgit2
83//!     └── nk
84//!         └── link-config
85//! ```
86//!
87//! The root of the index contains a `config.json` file with a few entries
88//! corresponding to the registry (see `RegistryConfig` below).
89//!
90//! Otherwise, there are three numbered directories (1, 2, 3) for crates with
91//! names 1, 2, and 3 characters in length. The 1/2 directories simply have the
92//! crate files underneath them, while the 3 directory is sharded by the first
93//! letter of the crate name.
94//!
95//! Otherwise the top-level directory contains many two-letter directory names,
96//! each of which has many sub-folders with two letters. At the end of all these
97//! are the actual crate files themselves.
98//!
99//! The purpose of this layout is to hopefully cut down on `ls` sizes as well as
100//! efficient lookup based on the crate name itself.
101//!
102//! ## Crate files
103//!
104//! Each file in the index is the history of one crate over time. Each line in
105//! the file corresponds to one version of a crate, stored in JSON format (see
106//! the `RegistryPackage` structure below).
107//!
108//! As new versions are published, new lines are appended to this file. The only
109//! modifications to this file that should happen over time are yanks of a
110//! particular version.
111//!
112//! # Downloading Packages
113//!
114//! The purpose of the Index was to provide an efficient method to resolve the
115//! dependency graph for a package. So far we only required one network
116//! interaction to update the registry's repository (yay!). After resolution has
117//! been performed, however we need to download the contents of packages so we
118//! can read the full manifest and build the source code.
119//!
120//! To accomplish this, this source's `download` method will make an HTTP
121//! request per-package requested to download tarballs into a local cache. These
122//! tarballs will then be unpacked into a destination folder.
123//!
124//! Note that because versions uploaded to the registry are frozen forever that
125//! the HTTP download and unpacking can all be skipped if the version has
126//! already been downloaded and unpacked. This caching allows us to only
127//! download a package when absolutely necessary.
128//!
129//! # Filesystem Hierarchy
130//!
131//! Overall, the `$HOME/.cargo` looks like this when talking about the registry:
132//!
133//! ```notrust
134//! # A folder under which all registry metadata is hosted (similar to
135//! # $HOME/.cargo/git)
136//! $HOME/.cargo/registry/
137//!
138//!     # For each registry that cargo knows about (keyed by hostname + hash)
139//!     # there is a folder which is the checked out version of the index for
140//!     # the registry in this location. Note that this is done so cargo can
141//!     # support multiple registries simultaneously
142//!     index/
143//!         registry1-<hash>/
144//!         registry2-<hash>/
145//!         ...
146//!
147//!     # This folder is a cache for all downloaded tarballs from a registry.
148//!     # Once downloaded and verified, a tarball never changes.
149//!     cache/
150//!         registry1-<hash>/<pkg>-<version>.crate
151//!         ...
152//!
153//!     # Location in which all tarballs are unpacked. Each tarball is known to
154//!     # be frozen after downloading, so transitively this folder is also
155//!     # frozen once its unpacked (it's never unpacked again)
156//!     src/
157//!         registry1-<hash>/<pkg>-<version>/...
158//!         ...
159//! ```
160
161use std::borrow::Cow;
162use std::collections::BTreeMap;
163use std::fs::File;
164use std::path::{Path, PathBuf};
165
166use flate2::read::GzDecoder;
167use log::debug;
168use semver::Version;
169use serde::Deserialize;
170use tar::Archive;
171
172use crate::core::dependency::{Dependency, Kind};
173use crate::core::source::MaybePackage;
174use crate::core::{Package, PackageId, Source, SourceId, Summary};
175use crate::sources::PathSource;
176use crate::util::errors::CargoResultExt;
177use crate::util::hex;
178use crate::util::to_url::ToUrl;
179use crate::util::{internal, CargoResult, Config, FileLock, Filesystem};
180
181const INDEX_LOCK: &str = ".cargo-index-lock";
182pub const CRATES_IO_INDEX: &str = "https://github.com/rust-lang/crates.io-index";
183pub const CRATES_IO_REGISTRY: &str = "crates-io";
184const CRATE_TEMPLATE: &str = "{crate}";
185const VERSION_TEMPLATE: &str = "{version}";
186
187pub struct RegistrySource<'cfg> {
188    source_id: SourceId,
189    src_path: Filesystem,
190    config: &'cfg Config,
191    updated: bool,
192    ops: Box<dyn RegistryData + 'cfg>,
193    index: index::RegistryIndex<'cfg>,
194    index_locked: bool,
195}
196
197#[derive(Deserialize)]
198pub struct RegistryConfig {
199    /// Download endpoint for all crates.
200    ///
201    /// The string is a template which will generate the download URL for the
202    /// tarball of a specific version of a crate. The substrings `{crate}` and
203    /// `{version}` will be replaced with the crate's name and version
204    /// respectively.
205    ///
206    /// For backwards compatibility, if the string does not contain `{crate}` or
207    /// `{version}`, it will be extended with `/{crate}/{version}/download` to
208    /// support registries like crates.io which were crated before the
209    /// templating setup was created.
210    pub dl: String,
211
212    /// API endpoint for the registry. This is what's actually hit to perform
213    /// operations like yanks, owner modifications, publish new crates, etc.
214    /// If this is None, the registry does not support API commands.
215    pub api: Option<String>,
216}
217
218#[derive(Deserialize)]
219pub struct RegistryPackage<'a> {
220    name: Cow<'a, str>,
221    vers: Version,
222    deps: Vec<RegistryDependency<'a>>,
223    features: BTreeMap<Cow<'a, str>, Vec<Cow<'a, str>>>,
224    cksum: String,
225    yanked: Option<bool>,
226    links: Option<Cow<'a, str>>,
227}
228
229#[test]
230fn escaped_cher_in_json() {
231    let _: RegistryPackage<'_> = serde_json::from_str(
232        r#"{"name":"a","vers":"0.0.1","deps":[],"cksum":"bae3","features":{}}"#,
233    )
234    .unwrap();
235    let _: RegistryPackage<'_> = serde_json::from_str(
236        r#"{"name":"a","vers":"0.0.1","deps":[],"cksum":"bae3","features":{"test":["k","q"]},"links":"a-sys"}"#
237    ).unwrap();
238
239    // Now we add escaped cher all the places they can go
240    // these are not valid, but it should error later than json parsing
241    let _: RegistryPackage<'_> = serde_json::from_str(
242        r#"{
243        "name":"This name has a escaped cher in it \n\t\" ",
244        "vers":"0.0.1",
245        "deps":[{
246            "name": " \n\t\" ",
247            "req": " \n\t\" ",
248            "features": [" \n\t\" "],
249            "optional": true,
250            "default_features": true,
251            "target": " \n\t\" ",
252            "kind": " \n\t\" ",
253            "registry": " \n\t\" "
254        }],
255        "cksum":"bae3",
256        "features":{"test \n\t\" ":["k \n\t\" ","q \n\t\" "]},
257        "links":" \n\t\" "}"#,
258    )
259    .unwrap();
260}
261
262#[derive(Deserialize)]
263#[serde(field_identifier, rename_all = "lowercase")]
264enum Field {
265    Name,
266    Vers,
267    Deps,
268    Features,
269    Cksum,
270    Yanked,
271    Links,
272}
273
274#[derive(Deserialize)]
275struct RegistryDependency<'a> {
276    name: Cow<'a, str>,
277    req: Cow<'a, str>,
278    features: Vec<Cow<'a, str>>,
279    optional: bool,
280    default_features: bool,
281    target: Option<Cow<'a, str>>,
282    kind: Option<Cow<'a, str>>,
283    registry: Option<Cow<'a, str>>,
284    package: Option<Cow<'a, str>>,
285}
286
287impl<'a> RegistryDependency<'a> {
288    /// Converts an encoded dependency in the registry to a cargo dependency
289    pub fn into_dep(self, default: SourceId) -> CargoResult<Dependency> {
290        let RegistryDependency {
291            name,
292            req,
293            mut features,
294            optional,
295            default_features,
296            target,
297            kind,
298            registry,
299            package,
300        } = self;
301
302        let id = if let Some(registry) = &registry {
303            SourceId::for_registry(&registry.to_url()?)?
304        } else {
305            default
306        };
307
308        let mut dep =
309            Dependency::parse_no_deprecated(package.as_ref().unwrap_or(&name), Some(&req), id)?;
310        if package.is_some() {
311            dep.set_explicit_name_in_toml(&name);
312        }
313        let kind = match kind.as_ref().map(|s| &s[..]).unwrap_or("") {
314            "dev" => Kind::Development,
315            "build" => Kind::Build,
316            _ => Kind::Normal,
317        };
318
319        let platform = match target {
320            Some(target) => Some(target.parse()?),
321            None => None,
322        };
323
324        // Unfortunately older versions of cargo and/or the registry ended up
325        // publishing lots of entries where the features array contained the
326        // empty feature, "", inside. This confuses the resolution process much
327        // later on and these features aren't actually valid, so filter them all
328        // out here.
329        features.retain(|s| !s.is_empty());
330
331        // In index, "registry" is null if it is from the same index.
332        // In Cargo.toml, "registry" is None if it is from the default
333        if !id.is_default_registry() {
334            dep.set_registry_id(id);
335        }
336
337        dep.set_optional(optional)
338            .set_default_features(default_features)
339            .set_features(features)
340            .set_platform(platform)
341            .set_kind(kind);
342
343        Ok(dep)
344    }
345}
346
347pub trait RegistryData {
348    fn prepare(&self) -> CargoResult<()>;
349    fn index_path(&self) -> &Filesystem;
350    fn load(
351        &self,
352        _root: &Path,
353        path: &Path,
354        data: &mut dyn FnMut(&[u8]) -> CargoResult<()>,
355    ) -> CargoResult<()>;
356    fn config(&mut self) -> CargoResult<Option<RegistryConfig>>;
357    fn update_index(&mut self) -> CargoResult<()>;
358    fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock>;
359    fn finish_download(
360        &mut self,
361        pkg: PackageId,
362        checksum: &str,
363        data: &[u8],
364    ) -> CargoResult<FileLock>;
365
366    fn is_crate_downloaded(&self, _pkg: PackageId) -> bool {
367        true
368    }
369}
370
371pub enum MaybeLock {
372    Ready(FileLock),
373    Download { url: String, descriptor: String },
374}
375
376mod index;
377mod local;
378mod remote;
379
380fn short_name(id: SourceId) -> String {
381    let hash = hex::short_hash(&id);
382    let ident = id.url().host_str().unwrap_or("").to_string();
383    format!("{}-{}", ident, hash)
384}
385
386impl<'cfg> RegistrySource<'cfg> {
387    pub fn remote(source_id: SourceId, config: &'cfg Config) -> RegistrySource<'cfg> {
388        let name = short_name(source_id);
389        let ops = remote::RemoteRegistry::new(source_id, config, &name);
390        RegistrySource::new(source_id, config, &name, Box::new(ops), true)
391    }
392
393    pub fn local(source_id: SourceId, path: &Path, config: &'cfg Config) -> RegistrySource<'cfg> {
394        let name = short_name(source_id);
395        let ops = local::LocalRegistry::new(path, config, &name);
396        RegistrySource::new(source_id, config, &name, Box::new(ops), false)
397    }
398
399    fn new(
400        source_id: SourceId,
401        config: &'cfg Config,
402        name: &str,
403        ops: Box<dyn RegistryData + 'cfg>,
404        index_locked: bool,
405    ) -> RegistrySource<'cfg> {
406        RegistrySource {
407            src_path: config.registry_source_path().join(name),
408            config,
409            source_id,
410            updated: false,
411            index: index::RegistryIndex::new(source_id, ops.index_path(), config, index_locked),
412            index_locked,
413            ops,
414        }
415    }
416
417    /// Decode the configuration stored within the registry.
418    ///
419    /// This requires that the index has been at least checked out.
420    pub fn config(&mut self) -> CargoResult<Option<RegistryConfig>> {
421        self.ops.config()
422    }
423
424    /// Unpacks a downloaded package into a location where it's ready to be
425    /// compiled.
426    ///
427    /// No action is taken if the source looks like it's already unpacked.
428    fn unpack_package(&self, pkg: PackageId, tarball: &FileLock) -> CargoResult<PathBuf> {
429        let dst = self
430            .src_path
431            .join(&format!("{}-{}", pkg.name(), pkg.version()));
432        dst.create_dir()?;
433        // Note that we've already got the `tarball` locked above, and that
434        // implies a lock on the unpacked destination as well, so this access
435        // via `into_path_unlocked` should be ok.
436        let dst = dst.into_path_unlocked();
437        let ok = dst.join(".cargo-ok");
438        if ok.exists() {
439            return Ok(dst);
440        }
441
442        let gz = GzDecoder::new(tarball.file());
443        let mut tar = Archive::new(gz);
444        let prefix = dst.file_name().unwrap();
445        let parent = dst.parent().unwrap();
446        for entry in tar.entries()? {
447            let mut entry = entry.chain_err(|| "failed to iterate over archive")?;
448            let entry_path = entry
449                .path()
450                .chain_err(|| "failed to read entry path")?
451                .into_owned();
452
453            // We're going to unpack this tarball into the global source
454            // directory, but we want to make sure that it doesn't accidentally
455            // (or maliciously) overwrite source code from other crates. Cargo
456            // itself should never generate a tarball that hits this error, and
457            // crates.io should also block uploads with these sorts of tarballs,
458            // but be extra sure by adding a check here as well.
459            if !entry_path.starts_with(prefix) {
460                failure::bail!(
461                    "invalid tarball downloaded, contains \
462                     a file at {:?} which isn't under {:?}",
463                    entry_path,
464                    prefix
465                )
466            }
467
468            // Once that's verified, unpack the entry as usual.
469            entry
470                .unpack_in(parent)
471                .chain_err(|| format!("failed to unpack entry at `{}`", entry_path.display()))?;
472        }
473        File::create(&ok)?;
474        Ok(dst)
475    }
476
477    fn do_update(&mut self) -> CargoResult<()> {
478        self.ops.update_index()?;
479        let path = self.ops.index_path();
480        self.index =
481            index::RegistryIndex::new(self.source_id, path, self.config, self.index_locked);
482        Ok(())
483    }
484
485    fn get_pkg(&mut self, package: PackageId, path: &FileLock) -> CargoResult<Package> {
486        let path = self
487            .unpack_package(package, path)
488            .chain_err(|| internal(format!("failed to unpack package `{}`", package)))?;
489        let mut src = PathSource::new(&path, self.source_id, self.config);
490        src.update()?;
491        let pkg = match src.download(package)? {
492            MaybePackage::Ready(pkg) => pkg,
493            MaybePackage::Download { .. } => unreachable!(),
494        };
495        Ok(pkg)
496    }
497}
498
499impl<'cfg> Source for RegistrySource<'cfg> {
500    fn query(&mut self, dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
501        // If this is a precise dependency, then it came from a lockfile and in
502        // theory the registry is known to contain this version. If, however, we
503        // come back with no summaries, then our registry may need to be
504        // updated, so we fall back to performing a lazy update.
505        if dep.source_id().precise().is_some() && !self.updated {
506            debug!("attempting query without update");
507            let mut called = false;
508            self.index.query_inner(dep, &mut *self.ops, &mut |s| {
509                if dep.matches(&s) {
510                    called = true;
511                    f(s);
512                }
513            })?;
514            if called {
515                return Ok(());
516            } else {
517                debug!("falling back to an update");
518                self.do_update()?;
519            }
520        }
521
522        self.index.query_inner(dep, &mut *self.ops, &mut |s| {
523            if dep.matches(&s) {
524                f(s);
525            }
526        })
527    }
528
529    fn fuzzy_query(&mut self, dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
530        self.index.query_inner(dep, &mut *self.ops, f)
531    }
532
533    fn supports_checksums(&self) -> bool {
534        true
535    }
536
537    fn requires_precise(&self) -> bool {
538        false
539    }
540
541    fn source_id(&self) -> SourceId {
542        self.source_id
543    }
544
545    fn update(&mut self) -> CargoResult<()> {
546        // If we have an imprecise version then we don't know what we're going
547        // to look for, so we always attempt to perform an update here.
548        //
549        // If we have a precise version, then we'll update lazily during the
550        // querying phase. Note that precise in this case is only
551        // `Some("locked")` as other `Some` values indicate a `cargo update
552        // --precise` request
553        if self.source_id.precise() != Some("locked") {
554            self.do_update()?;
555        } else {
556            debug!("skipping update due to locked registry");
557        }
558        Ok(())
559    }
560
561    fn download(&mut self, package: PackageId) -> CargoResult<MaybePackage> {
562        let hash = self.index.hash(package, &mut *self.ops)?;
563        match self.ops.download(package, &hash)? {
564            MaybeLock::Ready(file) => self.get_pkg(package, &file).map(MaybePackage::Ready),
565            MaybeLock::Download { url, descriptor } => {
566                Ok(MaybePackage::Download { url, descriptor })
567            }
568        }
569    }
570
571    fn finish_download(&mut self, package: PackageId, data: Vec<u8>) -> CargoResult<Package> {
572        let hash = self.index.hash(package, &mut *self.ops)?;
573        let file = self.ops.finish_download(package, &hash, &data)?;
574        self.get_pkg(package, &file)
575    }
576
577    fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
578        Ok(pkg.package_id().version().to_string())
579    }
580
581    fn describe(&self) -> String {
582        self.source_id.display_registry()
583    }
584}