]> git.proxmox.com Git - cargo.git/blob - src/cargo/sources/registry/mod.rs
Auto merge of #8277 - tverghis:default-readme, r=alexcrichton
[cargo.git] / src / 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/compressible.
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
161 use std::borrow::Cow;
162 use std::collections::BTreeMap;
163 use std::collections::HashSet;
164 use std::fs::{File, OpenOptions};
165 use std::io::Write;
166 use std::path::{Path, PathBuf};
167
168 use flate2::read::GzDecoder;
169 use log::debug;
170 use semver::{Version, VersionReq};
171 use serde::Deserialize;
172 use tar::Archive;
173
174 use crate::core::dependency::{DepKind, Dependency};
175 use crate::core::source::MaybePackage;
176 use crate::core::{InternedString, Package, PackageId, Source, SourceId, Summary};
177 use crate::sources::PathSource;
178 use crate::util::errors::CargoResultExt;
179 use crate::util::hex;
180 use crate::util::into_url::IntoUrl;
181 use crate::util::{restricted_names, CargoResult, Config, Filesystem};
182
183 const PACKAGE_SOURCE_LOCK: &str = ".cargo-ok";
184 pub const CRATES_IO_INDEX: &str = "https://github.com/rust-lang/crates.io-index";
185 pub const CRATES_IO_REGISTRY: &str = "crates-io";
186 const CRATE_TEMPLATE: &str = "{crate}";
187 const VERSION_TEMPLATE: &str = "{version}";
188 const PREFIX_TEMPLATE: &str = "{prefix}";
189 const LOWER_PREFIX_TEMPLATE: &str = "{lowerprefix}";
190
191 pub struct RegistrySource<'cfg> {
192 source_id: SourceId,
193 src_path: Filesystem,
194 config: &'cfg Config,
195 updated: bool,
196 ops: Box<dyn RegistryData + 'cfg>,
197 index: index::RegistryIndex<'cfg>,
198 yanked_whitelist: HashSet<PackageId>,
199 }
200
201 #[derive(Deserialize)]
202 pub struct RegistryConfig {
203 /// Download endpoint for all crates.
204 ///
205 /// The string is a template which will generate the download URL for the
206 /// tarball of a specific version of a crate. The substrings `{crate}` and
207 /// `{version}` will be replaced with the crate's name and version
208 /// respectively. The substring `{prefix}` will be replaced with the
209 /// crate's prefix directory name, and the substring `{lowerprefix}` will
210 /// be replaced with the crate's prefix directory name converted to
211 /// lowercase.
212 ///
213 /// For backwards compatibility, if the string does not contain any
214 /// markers (`{crate}`, `{version}`, `{prefix}`, or ``{lowerprefix}`), it
215 /// will be extended with `/{crate}/{version}/download` to
216 /// support registries like crates.io which were created before the
217 /// templating setup was created.
218 pub dl: String,
219
220 /// API endpoint for the registry. This is what's actually hit to perform
221 /// operations like yanks, owner modifications, publish new crates, etc.
222 /// If this is None, the registry does not support API commands.
223 pub api: Option<String>,
224 }
225
226 /// A single line in the index representing a single version of a package.
227 #[derive(Deserialize)]
228 pub struct RegistryPackage<'a> {
229 name: InternedString,
230 vers: Version,
231 #[serde(borrow)]
232 deps: Vec<RegistryDependency<'a>>,
233 features: BTreeMap<InternedString, Vec<InternedString>>,
234 cksum: String,
235 /// If `true`, Cargo will skip this version when resolving.
236 ///
237 /// This was added in 2014. Everything in the crates.io index has this set
238 /// now, so this probably doesn't need to be an option anymore.
239 yanked: Option<bool>,
240 /// Native library name this package links to.
241 ///
242 /// Added early 2018 (see https://github.com/rust-lang/cargo/pull/4978),
243 /// can be `None` if published before then.
244 links: Option<InternedString>,
245 }
246
247 #[test]
248 fn escaped_char_in_json() {
249 let _: RegistryPackage<'_> = serde_json::from_str(
250 r#"{"name":"a","vers":"0.0.1","deps":[],"cksum":"bae3","features":{}}"#,
251 )
252 .unwrap();
253 let _: RegistryPackage<'_> = serde_json::from_str(
254 r#"{"name":"a","vers":"0.0.1","deps":[],"cksum":"bae3","features":{"test":["k","q"]},"links":"a-sys"}"#
255 ).unwrap();
256
257 // Now we add escaped cher all the places they can go
258 // these are not valid, but it should error later than json parsing
259 let _: RegistryPackage<'_> = serde_json::from_str(
260 r#"{
261 "name":"This name has a escaped cher in it \n\t\" ",
262 "vers":"0.0.1",
263 "deps":[{
264 "name": " \n\t\" ",
265 "req": " \n\t\" ",
266 "features": [" \n\t\" "],
267 "optional": true,
268 "default_features": true,
269 "target": " \n\t\" ",
270 "kind": " \n\t\" ",
271 "registry": " \n\t\" "
272 }],
273 "cksum":"bae3",
274 "features":{"test \n\t\" ":["k \n\t\" ","q \n\t\" "]},
275 "links":" \n\t\" "}"#,
276 )
277 .unwrap();
278 }
279
280 #[derive(Deserialize)]
281 #[serde(field_identifier, rename_all = "lowercase")]
282 enum Field {
283 Name,
284 Vers,
285 Deps,
286 Features,
287 Cksum,
288 Yanked,
289 Links,
290 }
291
292 #[derive(Deserialize)]
293 struct RegistryDependency<'a> {
294 name: InternedString,
295 #[serde(borrow)]
296 req: Cow<'a, str>,
297 features: Vec<InternedString>,
298 optional: bool,
299 default_features: bool,
300 target: Option<Cow<'a, str>>,
301 kind: Option<Cow<'a, str>>,
302 registry: Option<Cow<'a, str>>,
303 package: Option<InternedString>,
304 public: Option<bool>,
305 }
306
307 impl<'a> RegistryDependency<'a> {
308 /// Converts an encoded dependency in the registry to a cargo dependency
309 pub fn into_dep(self, default: SourceId) -> CargoResult<Dependency> {
310 let RegistryDependency {
311 name,
312 req,
313 mut features,
314 optional,
315 default_features,
316 target,
317 kind,
318 registry,
319 package,
320 public,
321 } = self;
322
323 let id = if let Some(registry) = &registry {
324 SourceId::for_registry(&registry.into_url()?)?
325 } else {
326 default
327 };
328
329 let mut dep = Dependency::parse_no_deprecated(package.unwrap_or(name), Some(&req), id)?;
330 if package.is_some() {
331 dep.set_explicit_name_in_toml(name);
332 }
333 let kind = match kind.as_deref().unwrap_or("") {
334 "dev" => DepKind::Development,
335 "build" => DepKind::Build,
336 _ => DepKind::Normal,
337 };
338
339 let platform = match target {
340 Some(target) => Some(target.parse()?),
341 None => None,
342 };
343
344 // All dependencies are private by default
345 let public = public.unwrap_or(false);
346
347 // Unfortunately older versions of cargo and/or the registry ended up
348 // publishing lots of entries where the features array contained the
349 // empty feature, "", inside. This confuses the resolution process much
350 // later on and these features aren't actually valid, so filter them all
351 // out here.
352 features.retain(|s| !s.is_empty());
353
354 // In index, "registry" is null if it is from the same index.
355 // In Cargo.toml, "registry" is None if it is from the default
356 if !id.is_default_registry() {
357 dep.set_registry_id(id);
358 }
359
360 dep.set_optional(optional)
361 .set_default_features(default_features)
362 .set_features(features)
363 .set_platform(platform)
364 .set_kind(kind)
365 .set_public(public);
366
367 Ok(dep)
368 }
369 }
370
371 pub trait RegistryData {
372 fn prepare(&self) -> CargoResult<()>;
373 fn index_path(&self) -> &Filesystem;
374 fn load(
375 &self,
376 root: &Path,
377 path: &Path,
378 data: &mut dyn FnMut(&[u8]) -> CargoResult<()>,
379 ) -> CargoResult<()>;
380 fn config(&mut self) -> CargoResult<Option<RegistryConfig>>;
381 fn update_index(&mut self) -> CargoResult<()>;
382 fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock>;
383 fn finish_download(&mut self, pkg: PackageId, checksum: &str, data: &[u8])
384 -> CargoResult<File>;
385
386 fn is_crate_downloaded(&self, _pkg: PackageId) -> bool {
387 true
388 }
389 fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path;
390 fn current_version(&self) -> Option<InternedString>;
391 }
392
393 pub enum MaybeLock {
394 Ready(File),
395 Download { url: String, descriptor: String },
396 }
397
398 mod index;
399 mod local;
400 mod remote;
401
402 fn short_name(id: SourceId) -> String {
403 let hash = hex::short_hash(&id);
404 let ident = id.url().host_str().unwrap_or("").to_string();
405 format!("{}-{}", ident, hash)
406 }
407
408 impl<'cfg> RegistrySource<'cfg> {
409 pub fn remote(
410 source_id: SourceId,
411 yanked_whitelist: &HashSet<PackageId>,
412 config: &'cfg Config,
413 ) -> RegistrySource<'cfg> {
414 let name = short_name(source_id);
415 let ops = remote::RemoteRegistry::new(source_id, config, &name);
416 RegistrySource::new(source_id, config, &name, Box::new(ops), yanked_whitelist)
417 }
418
419 pub fn local(
420 source_id: SourceId,
421 path: &Path,
422 yanked_whitelist: &HashSet<PackageId>,
423 config: &'cfg Config,
424 ) -> RegistrySource<'cfg> {
425 let name = short_name(source_id);
426 let ops = local::LocalRegistry::new(path, config, &name);
427 RegistrySource::new(source_id, config, &name, Box::new(ops), yanked_whitelist)
428 }
429
430 fn new(
431 source_id: SourceId,
432 config: &'cfg Config,
433 name: &str,
434 ops: Box<dyn RegistryData + 'cfg>,
435 yanked_whitelist: &HashSet<PackageId>,
436 ) -> RegistrySource<'cfg> {
437 RegistrySource {
438 src_path: config.registry_source_path().join(name),
439 config,
440 source_id,
441 updated: false,
442 index: index::RegistryIndex::new(source_id, ops.index_path(), config),
443 yanked_whitelist: yanked_whitelist.clone(),
444 ops,
445 }
446 }
447
448 /// Decode the configuration stored within the registry.
449 ///
450 /// This requires that the index has been at least checked out.
451 pub fn config(&mut self) -> CargoResult<Option<RegistryConfig>> {
452 self.ops.config()
453 }
454
455 /// Unpacks a downloaded package into a location where it's ready to be
456 /// compiled.
457 ///
458 /// No action is taken if the source looks like it's already unpacked.
459 fn unpack_package(&self, pkg: PackageId, tarball: &File) -> CargoResult<PathBuf> {
460 // The `.cargo-ok` file is used to track if the source is already
461 // unpacked.
462 let package_dir = format!("{}-{}", pkg.name(), pkg.version());
463 let dst = self.src_path.join(&package_dir);
464 dst.create_dir()?;
465 let path = dst.join(PACKAGE_SOURCE_LOCK);
466 let path = self.config.assert_package_cache_locked(&path);
467 let unpack_dir = path.parent().unwrap();
468 if let Ok(meta) = path.metadata() {
469 if meta.len() > 0 {
470 return Ok(unpack_dir.to_path_buf());
471 }
472 }
473 let mut ok = OpenOptions::new()
474 .create(true)
475 .read(true)
476 .write(true)
477 .open(&path)
478 .chain_err(|| format!("failed to open `{}`", path.display()))?;
479
480 let gz = GzDecoder::new(tarball);
481 let mut tar = Archive::new(gz);
482 let prefix = unpack_dir.file_name().unwrap();
483 let parent = unpack_dir.parent().unwrap();
484 for entry in tar.entries()? {
485 let mut entry = entry.chain_err(|| "failed to iterate over archive")?;
486 let entry_path = entry
487 .path()
488 .chain_err(|| "failed to read entry path")?
489 .into_owned();
490
491 // We're going to unpack this tarball into the global source
492 // directory, but we want to make sure that it doesn't accidentally
493 // (or maliciously) overwrite source code from other crates. Cargo
494 // itself should never generate a tarball that hits this error, and
495 // crates.io should also block uploads with these sorts of tarballs,
496 // but be extra sure by adding a check here as well.
497 if !entry_path.starts_with(prefix) {
498 anyhow::bail!(
499 "invalid tarball downloaded, contains \
500 a file at {:?} which isn't under {:?}",
501 entry_path,
502 prefix
503 )
504 }
505 // Unpacking failed
506 let mut result = entry.unpack_in(parent).map_err(anyhow::Error::from);
507 if cfg!(windows) && restricted_names::is_windows_reserved_path(&entry_path) {
508 result = result.chain_err(|| {
509 format!(
510 "`{}` appears to contain a reserved Windows path, \
511 it cannot be extracted on Windows",
512 entry_path.display()
513 )
514 });
515 }
516 result.chain_err(|| format!("failed to unpack entry at `{}`", entry_path.display()))?;
517 }
518
519 // Write to the lock file to indicate that unpacking was successful.
520 write!(ok, "ok")?;
521
522 Ok(unpack_dir.to_path_buf())
523 }
524
525 fn do_update(&mut self) -> CargoResult<()> {
526 self.ops.update_index()?;
527 let path = self.ops.index_path();
528 self.index = index::RegistryIndex::new(self.source_id, path, self.config);
529 self.updated = true;
530 Ok(())
531 }
532
533 fn get_pkg(&mut self, package: PackageId, path: &File) -> CargoResult<Package> {
534 let path = self
535 .unpack_package(package, path)
536 .chain_err(|| format!("failed to unpack package `{}`", package))?;
537 let mut src = PathSource::new(&path, self.source_id, self.config);
538 src.update()?;
539 let mut pkg = match src.download(package)? {
540 MaybePackage::Ready(pkg) => pkg,
541 MaybePackage::Download { .. } => unreachable!(),
542 };
543
544 // After we've loaded the package configure its summary's `checksum`
545 // field with the checksum we know for this `PackageId`.
546 let req = VersionReq::exact(package.version());
547 let summary_with_cksum = self
548 .index
549 .summaries(package.name(), &req, &mut *self.ops)?
550 .map(|s| s.summary.clone())
551 .next()
552 .expect("summary not found");
553 if let Some(cksum) = summary_with_cksum.checksum() {
554 pkg.manifest_mut()
555 .summary_mut()
556 .set_checksum(cksum.to_string());
557 }
558
559 Ok(pkg)
560 }
561 }
562
563 impl<'cfg> Source for RegistrySource<'cfg> {
564 fn query(&mut self, dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
565 // If this is a precise dependency, then it came from a lock file and in
566 // theory the registry is known to contain this version. If, however, we
567 // come back with no summaries, then our registry may need to be
568 // updated, so we fall back to performing a lazy update.
569 if dep.source_id().precise().is_some() && !self.updated {
570 debug!("attempting query without update");
571 let mut called = false;
572 self.index
573 .query_inner(dep, &mut *self.ops, &self.yanked_whitelist, &mut |s| {
574 if dep.matches(&s) {
575 called = true;
576 f(s);
577 }
578 })?;
579 if called {
580 return Ok(());
581 } else {
582 debug!("falling back to an update");
583 self.do_update()?;
584 }
585 }
586
587 self.index
588 .query_inner(dep, &mut *self.ops, &self.yanked_whitelist, &mut |s| {
589 if dep.matches(&s) {
590 f(s);
591 }
592 })
593 }
594
595 fn fuzzy_query(&mut self, dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
596 self.index
597 .query_inner(dep, &mut *self.ops, &self.yanked_whitelist, f)
598 }
599
600 fn supports_checksums(&self) -> bool {
601 true
602 }
603
604 fn requires_precise(&self) -> bool {
605 false
606 }
607
608 fn source_id(&self) -> SourceId {
609 self.source_id
610 }
611
612 fn update(&mut self) -> CargoResult<()> {
613 // If we have an imprecise version then we don't know what we're going
614 // to look for, so we always attempt to perform an update here.
615 //
616 // If we have a precise version, then we'll update lazily during the
617 // querying phase. Note that precise in this case is only
618 // `Some("locked")` as other `Some` values indicate a `cargo update
619 // --precise` request
620 if self.source_id.precise() != Some("locked") {
621 self.do_update()?;
622 } else {
623 debug!("skipping update due to locked registry");
624 }
625 Ok(())
626 }
627
628 fn download(&mut self, package: PackageId) -> CargoResult<MaybePackage> {
629 let hash = self.index.hash(package, &mut *self.ops)?;
630 match self.ops.download(package, hash)? {
631 MaybeLock::Ready(file) => self.get_pkg(package, &file).map(MaybePackage::Ready),
632 MaybeLock::Download { url, descriptor } => {
633 Ok(MaybePackage::Download { url, descriptor })
634 }
635 }
636 }
637
638 fn finish_download(&mut self, package: PackageId, data: Vec<u8>) -> CargoResult<Package> {
639 let hash = self.index.hash(package, &mut *self.ops)?;
640 let file = self.ops.finish_download(package, hash, &data)?;
641 self.get_pkg(package, &file)
642 }
643
644 fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
645 Ok(pkg.package_id().version().to_string())
646 }
647
648 fn describe(&self) -> String {
649 self.source_id.display_index()
650 }
651
652 fn add_to_yanked_whitelist(&mut self, pkgs: &[PackageId]) {
653 self.yanked_whitelist.extend(pkgs);
654 }
655
656 fn is_yanked(&mut self, pkg: PackageId) -> CargoResult<bool> {
657 if !self.updated {
658 self.do_update()?;
659 }
660 self.index.is_yanked(pkg, &mut *self.ops)
661 }
662 }