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