]> git.proxmox.com Git - cargo.git/blob - src/cargo/sources/registry/mod.rs
Auto merge of #9112 - alexcrichton:split-debuginfo, r=ehuss
[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 /// A "source" for a [local](local::LocalRegistry) or
193 /// [remote](remote::RemoteRegistry) registry.
194 ///
195 /// This contains common functionality that is shared between the two registry
196 /// kinds, with the registry-specific logic implemented as part of the
197 /// [`RegistryData`] trait referenced via the `ops` field.
198 pub struct RegistrySource<'cfg> {
199 source_id: SourceId,
200 /// The path where crate files are extracted (`$CARGO_HOME/registry/src/$REG-HASH`).
201 src_path: Filesystem,
202 /// Local reference to [`Config`] for convenience.
203 config: &'cfg Config,
204 /// Whether or not the index has been updated.
205 ///
206 /// This is used as an optimization to avoid updating if not needed, such
207 /// as `Cargo.lock` already exists and the index already contains the
208 /// locked entries. Or, to avoid updating multiple times.
209 ///
210 /// Only remote registries really need to update. Local registries only
211 /// check that the index exists.
212 updated: bool,
213 /// Abstraction for interfacing to the different registry kinds.
214 ops: Box<dyn RegistryData + 'cfg>,
215 /// Interface for managing the on-disk index.
216 index: index::RegistryIndex<'cfg>,
217 /// A set of packages that should be allowed to be used, even if they are
218 /// yanked.
219 ///
220 /// This is populated from the entries in `Cargo.lock` to ensure that
221 /// `cargo update -p somepkg` won't unlock yanked entries in `Cargo.lock`.
222 /// Otherwise, the resolver would think that those entries no longer
223 /// exist, and it would trigger updates to unrelated packages.
224 yanked_whitelist: HashSet<PackageId>,
225 }
226
227 /// The `config.json` file stored in the index.
228 #[derive(Deserialize)]
229 pub struct RegistryConfig {
230 /// Download endpoint for all crates.
231 ///
232 /// The string is a template which will generate the download URL for the
233 /// tarball of a specific version of a crate. The substrings `{crate}` and
234 /// `{version}` will be replaced with the crate's name and version
235 /// respectively. The substring `{prefix}` will be replaced with the
236 /// crate's prefix directory name, and the substring `{lowerprefix}` will
237 /// be replaced with the crate's prefix directory name converted to
238 /// lowercase.
239 ///
240 /// For backwards compatibility, if the string does not contain any
241 /// markers (`{crate}`, `{version}`, `{prefix}`, or ``{lowerprefix}`), it
242 /// will be extended with `/{crate}/{version}/download` to
243 /// support registries like crates.io which were created before the
244 /// templating setup was created.
245 pub dl: String,
246
247 /// API endpoint for the registry. This is what's actually hit to perform
248 /// operations like yanks, owner modifications, publish new crates, etc.
249 /// If this is None, the registry does not support API commands.
250 pub api: Option<String>,
251 }
252
253 /// A single line in the index representing a single version of a package.
254 #[derive(Deserialize)]
255 pub struct RegistryPackage<'a> {
256 name: InternedString,
257 vers: Version,
258 #[serde(borrow)]
259 deps: Vec<RegistryDependency<'a>>,
260 features: BTreeMap<InternedString, Vec<InternedString>>,
261 cksum: String,
262 /// If `true`, Cargo will skip this version when resolving.
263 ///
264 /// This was added in 2014. Everything in the crates.io index has this set
265 /// now, so this probably doesn't need to be an option anymore.
266 yanked: Option<bool>,
267 /// Native library name this package links to.
268 ///
269 /// Added early 2018 (see <https://github.com/rust-lang/cargo/pull/4978>),
270 /// can be `None` if published before then.
271 links: Option<InternedString>,
272 }
273
274 #[test]
275 fn escaped_char_in_json() {
276 let _: RegistryPackage<'_> = serde_json::from_str(
277 r#"{"name":"a","vers":"0.0.1","deps":[],"cksum":"bae3","features":{}}"#,
278 )
279 .unwrap();
280 let _: RegistryPackage<'_> = serde_json::from_str(
281 r#"{"name":"a","vers":"0.0.1","deps":[],"cksum":"bae3","features":{"test":["k","q"]},"links":"a-sys"}"#
282 ).unwrap();
283
284 // Now we add escaped cher all the places they can go
285 // these are not valid, but it should error later than json parsing
286 let _: RegistryPackage<'_> = serde_json::from_str(
287 r#"{
288 "name":"This name has a escaped cher in it \n\t\" ",
289 "vers":"0.0.1",
290 "deps":[{
291 "name": " \n\t\" ",
292 "req": " \n\t\" ",
293 "features": [" \n\t\" "],
294 "optional": true,
295 "default_features": true,
296 "target": " \n\t\" ",
297 "kind": " \n\t\" ",
298 "registry": " \n\t\" "
299 }],
300 "cksum":"bae3",
301 "features":{"test \n\t\" ":["k \n\t\" ","q \n\t\" "]},
302 "links":" \n\t\" "}"#,
303 )
304 .unwrap();
305 }
306
307 /// A dependency as encoded in the index JSON.
308 #[derive(Deserialize)]
309 struct RegistryDependency<'a> {
310 name: InternedString,
311 #[serde(borrow)]
312 req: Cow<'a, str>,
313 features: Vec<InternedString>,
314 optional: bool,
315 default_features: bool,
316 target: Option<Cow<'a, str>>,
317 kind: Option<Cow<'a, str>>,
318 registry: Option<Cow<'a, str>>,
319 package: Option<InternedString>,
320 public: Option<bool>,
321 }
322
323 impl<'a> RegistryDependency<'a> {
324 /// Converts an encoded dependency in the registry to a cargo dependency
325 pub fn into_dep(self, default: SourceId) -> CargoResult<Dependency> {
326 let RegistryDependency {
327 name,
328 req,
329 mut features,
330 optional,
331 default_features,
332 target,
333 kind,
334 registry,
335 package,
336 public,
337 } = self;
338
339 let id = if let Some(registry) = &registry {
340 SourceId::for_registry(&registry.into_url()?)?
341 } else {
342 default
343 };
344
345 let mut dep = Dependency::parse_no_deprecated(package.unwrap_or(name), Some(&req), id)?;
346 if package.is_some() {
347 dep.set_explicit_name_in_toml(name);
348 }
349 let kind = match kind.as_deref().unwrap_or("") {
350 "dev" => DepKind::Development,
351 "build" => DepKind::Build,
352 _ => DepKind::Normal,
353 };
354
355 let platform = match target {
356 Some(target) => Some(target.parse()?),
357 None => None,
358 };
359
360 // All dependencies are private by default
361 let public = public.unwrap_or(false);
362
363 // Unfortunately older versions of cargo and/or the registry ended up
364 // publishing lots of entries where the features array contained the
365 // empty feature, "", inside. This confuses the resolution process much
366 // later on and these features aren't actually valid, so filter them all
367 // out here.
368 features.retain(|s| !s.is_empty());
369
370 // In index, "registry" is null if it is from the same index.
371 // In Cargo.toml, "registry" is None if it is from the default
372 if !id.is_default_registry() {
373 dep.set_registry_id(id);
374 }
375
376 dep.set_optional(optional)
377 .set_default_features(default_features)
378 .set_features(features)
379 .set_platform(platform)
380 .set_kind(kind)
381 .set_public(public);
382
383 Ok(dep)
384 }
385 }
386
387 /// An abstract interface to handle both a [local](local::LocalRegistry) and
388 /// [remote](remote::RemoteRegistry) registry.
389 ///
390 /// This allows [`RegistrySource`] to abstractly handle both registry kinds.
391 pub trait RegistryData {
392 /// Performs initialization for the registry.
393 ///
394 /// This should be safe to call multiple times, the implementation is
395 /// expected to not do any work if it is already prepared.
396 fn prepare(&self) -> CargoResult<()>;
397
398 /// Returns the path to the index.
399 ///
400 /// Note that different registries store the index in different formats
401 /// (remote=git, local=files).
402 fn index_path(&self) -> &Filesystem;
403
404 /// Loads the JSON for a specific named package from the index.
405 ///
406 /// * `root` is the root path to the index.
407 /// * `path` is the relative path to the package to load (like `ca/rg/cargo`).
408 /// * `data` is a callback that will receive the raw bytes of the index JSON file.
409 fn load(
410 &self,
411 root: &Path,
412 path: &Path,
413 data: &mut dyn FnMut(&[u8]) -> CargoResult<()>,
414 ) -> CargoResult<()>;
415
416 /// Loads the `config.json` file and returns it.
417 ///
418 /// Local registries don't have a config, and return `None`.
419 fn config(&mut self) -> CargoResult<Option<RegistryConfig>>;
420
421 /// Updates the index.
422 ///
423 /// For a remote registry, this updates the index over the network. Local
424 /// registries only check that the index exists.
425 fn update_index(&mut self) -> CargoResult<()>;
426
427 /// Prepare to start downloading a `.crate` file.
428 ///
429 /// Despite the name, this doesn't actually download anything. If the
430 /// `.crate` is already downloaded, then it returns [`MaybeLock::Ready`].
431 /// If it hasn't been downloaded, then it returns [`MaybeLock::Download`]
432 /// which contains the URL to download. The [`crate::core::package::Download`]
433 /// system handles the actual download process. After downloading, it
434 /// calls [`finish_download`] to save the downloaded file.
435 ///
436 /// `checksum` is currently only used by local registries to verify the
437 /// file contents (because local registries never actually download
438 /// anything). Remote registries will validate the checksum in
439 /// `finish_download`. For already downloaded `.crate` files, it does not
440 /// validate the checksum, assuming the filesystem does not suffer from
441 /// corruption or manipulation.
442 fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock>;
443
444 /// Finish a download by saving a `.crate` file to disk.
445 ///
446 /// After [`crate::core::package::Download`] has finished a download,
447 /// it will call this to save the `.crate` file. This is only relevant
448 /// for remote registries. This should validate the checksum and save
449 /// the given data to the on-disk cache.
450 ///
451 /// Returns a [`File`] handle to the `.crate` file, positioned at the start.
452 fn finish_download(&mut self, pkg: PackageId, checksum: &str, data: &[u8])
453 -> CargoResult<File>;
454
455 /// Returns whether or not the `.crate` file is already downloaded.
456 fn is_crate_downloaded(&self, _pkg: PackageId) -> bool {
457 true
458 }
459
460 /// Validates that the global package cache lock is held.
461 ///
462 /// Given the [`Filesystem`], this will make sure that the package cache
463 /// lock is held. If not, it will panic. See
464 /// [`Config::acquire_package_cache_lock`] for acquiring the global lock.
465 ///
466 /// Returns the [`Path`] to the [`Filesystem`].
467 fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path;
468
469 /// Returns the current "version" of the index.
470 ///
471 /// For local registries, this returns `None` because there is no
472 /// versioning. For remote registries, this returns the SHA hash of the
473 /// git index on disk (or None if the index hasn't been downloaded yet).
474 ///
475 /// This is used by index caching to check if the cache is out of date.
476 fn current_version(&self) -> Option<InternedString>;
477 }
478
479 /// The status of [`RegistryData::download`] which indicates if a `.crate`
480 /// file has already been downloaded, or if not then the URL to download.
481 pub enum MaybeLock {
482 /// The `.crate` file is already downloaded. [`File`] is a handle to the
483 /// opened `.crate` file on the filesystem.
484 Ready(File),
485 /// The `.crate` file is not downloaded, here's the URL to download it from.
486 ///
487 /// `descriptor` is just a text string to display to the user of what is
488 /// being downloaded.
489 Download { url: String, descriptor: String },
490 }
491
492 mod index;
493 mod local;
494 mod remote;
495
496 fn short_name(id: SourceId) -> String {
497 let hash = hex::short_hash(&id);
498 let ident = id.url().host_str().unwrap_or("").to_string();
499 format!("{}-{}", ident, hash)
500 }
501
502 impl<'cfg> RegistrySource<'cfg> {
503 pub fn remote(
504 source_id: SourceId,
505 yanked_whitelist: &HashSet<PackageId>,
506 config: &'cfg Config,
507 ) -> RegistrySource<'cfg> {
508 let name = short_name(source_id);
509 let ops = remote::RemoteRegistry::new(source_id, config, &name);
510 RegistrySource::new(source_id, config, &name, Box::new(ops), yanked_whitelist)
511 }
512
513 pub fn local(
514 source_id: SourceId,
515 path: &Path,
516 yanked_whitelist: &HashSet<PackageId>,
517 config: &'cfg Config,
518 ) -> RegistrySource<'cfg> {
519 let name = short_name(source_id);
520 let ops = local::LocalRegistry::new(path, config, &name);
521 RegistrySource::new(source_id, config, &name, Box::new(ops), yanked_whitelist)
522 }
523
524 fn new(
525 source_id: SourceId,
526 config: &'cfg Config,
527 name: &str,
528 ops: Box<dyn RegistryData + 'cfg>,
529 yanked_whitelist: &HashSet<PackageId>,
530 ) -> RegistrySource<'cfg> {
531 RegistrySource {
532 src_path: config.registry_source_path().join(name),
533 config,
534 source_id,
535 updated: false,
536 index: index::RegistryIndex::new(source_id, ops.index_path(), config),
537 yanked_whitelist: yanked_whitelist.clone(),
538 ops,
539 }
540 }
541
542 /// Decode the configuration stored within the registry.
543 ///
544 /// This requires that the index has been at least checked out.
545 pub fn config(&mut self) -> CargoResult<Option<RegistryConfig>> {
546 self.ops.config()
547 }
548
549 /// Unpacks a downloaded package into a location where it's ready to be
550 /// compiled.
551 ///
552 /// No action is taken if the source looks like it's already unpacked.
553 fn unpack_package(&self, pkg: PackageId, tarball: &File) -> CargoResult<PathBuf> {
554 // The `.cargo-ok` file is used to track if the source is already
555 // unpacked.
556 let package_dir = format!("{}-{}", pkg.name(), pkg.version());
557 let dst = self.src_path.join(&package_dir);
558 dst.create_dir()?;
559 let path = dst.join(PACKAGE_SOURCE_LOCK);
560 let path = self.config.assert_package_cache_locked(&path);
561 let unpack_dir = path.parent().unwrap();
562 if let Ok(meta) = path.metadata() {
563 if meta.len() > 0 {
564 return Ok(unpack_dir.to_path_buf());
565 }
566 }
567 let gz = GzDecoder::new(tarball);
568 let mut tar = Archive::new(gz);
569 let prefix = unpack_dir.file_name().unwrap();
570 let parent = unpack_dir.parent().unwrap();
571 for entry in tar.entries()? {
572 let mut entry = entry.chain_err(|| "failed to iterate over archive")?;
573 let entry_path = entry
574 .path()
575 .chain_err(|| "failed to read entry path")?
576 .into_owned();
577
578 // We're going to unpack this tarball into the global source
579 // directory, but we want to make sure that it doesn't accidentally
580 // (or maliciously) overwrite source code from other crates. Cargo
581 // itself should never generate a tarball that hits this error, and
582 // crates.io should also block uploads with these sorts of tarballs,
583 // but be extra sure by adding a check here as well.
584 if !entry_path.starts_with(prefix) {
585 anyhow::bail!(
586 "invalid tarball downloaded, contains \
587 a file at {:?} which isn't under {:?}",
588 entry_path,
589 prefix
590 )
591 }
592 // Unpacking failed
593 let mut result = entry.unpack_in(parent).map_err(anyhow::Error::from);
594 if cfg!(windows) && restricted_names::is_windows_reserved_path(&entry_path) {
595 result = result.chain_err(|| {
596 format!(
597 "`{}` appears to contain a reserved Windows path, \
598 it cannot be extracted on Windows",
599 entry_path.display()
600 )
601 });
602 }
603 result.chain_err(|| format!("failed to unpack entry at `{}`", entry_path.display()))?;
604 }
605
606 // The lock file is created after unpacking so we overwrite a lock file
607 // which may have been extracted from the package.
608 let mut ok = OpenOptions::new()
609 .create(true)
610 .read(true)
611 .write(true)
612 .open(&path)
613 .chain_err(|| format!("failed to open `{}`", path.display()))?;
614
615 // Write to the lock file to indicate that unpacking was successful.
616 write!(ok, "ok")?;
617
618 Ok(unpack_dir.to_path_buf())
619 }
620
621 fn do_update(&mut self) -> CargoResult<()> {
622 self.ops.update_index()?;
623 let path = self.ops.index_path();
624 self.index = index::RegistryIndex::new(self.source_id, path, self.config);
625 self.updated = true;
626 Ok(())
627 }
628
629 fn get_pkg(&mut self, package: PackageId, path: &File) -> CargoResult<Package> {
630 let path = self
631 .unpack_package(package, path)
632 .chain_err(|| format!("failed to unpack package `{}`", package))?;
633 let mut src = PathSource::new(&path, self.source_id, self.config);
634 src.update()?;
635 let mut pkg = match src.download(package)? {
636 MaybePackage::Ready(pkg) => pkg,
637 MaybePackage::Download { .. } => unreachable!(),
638 };
639
640 // After we've loaded the package configure its summary's `checksum`
641 // field with the checksum we know for this `PackageId`.
642 let req = VersionReq::exact(package.version());
643 let summary_with_cksum = self
644 .index
645 .summaries(package.name(), &req, &mut *self.ops)?
646 .map(|s| s.summary.clone())
647 .next()
648 .expect("summary not found");
649 if let Some(cksum) = summary_with_cksum.checksum() {
650 pkg.manifest_mut()
651 .summary_mut()
652 .set_checksum(cksum.to_string());
653 }
654
655 Ok(pkg)
656 }
657 }
658
659 impl<'cfg> Source for RegistrySource<'cfg> {
660 fn query(&mut self, dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
661 // If this is a precise dependency, then it came from a lock file and in
662 // theory the registry is known to contain this version. If, however, we
663 // come back with no summaries, then our registry may need to be
664 // updated, so we fall back to performing a lazy update.
665 if dep.source_id().precise().is_some() && !self.updated {
666 debug!("attempting query without update");
667 let mut called = false;
668 self.index
669 .query_inner(dep, &mut *self.ops, &self.yanked_whitelist, &mut |s| {
670 if dep.matches(&s) {
671 called = true;
672 f(s);
673 }
674 })?;
675 if called {
676 return Ok(());
677 } else {
678 debug!("falling back to an update");
679 self.do_update()?;
680 }
681 }
682
683 self.index
684 .query_inner(dep, &mut *self.ops, &self.yanked_whitelist, &mut |s| {
685 if dep.matches(&s) {
686 f(s);
687 }
688 })
689 }
690
691 fn fuzzy_query(&mut self, dep: &Dependency, f: &mut dyn FnMut(Summary)) -> CargoResult<()> {
692 self.index
693 .query_inner(dep, &mut *self.ops, &self.yanked_whitelist, f)
694 }
695
696 fn supports_checksums(&self) -> bool {
697 true
698 }
699
700 fn requires_precise(&self) -> bool {
701 false
702 }
703
704 fn source_id(&self) -> SourceId {
705 self.source_id
706 }
707
708 fn update(&mut self) -> CargoResult<()> {
709 // If we have an imprecise version then we don't know what we're going
710 // to look for, so we always attempt to perform an update here.
711 //
712 // If we have a precise version, then we'll update lazily during the
713 // querying phase. Note that precise in this case is only
714 // `Some("locked")` as other `Some` values indicate a `cargo update
715 // --precise` request
716 if self.source_id.precise() != Some("locked") {
717 self.do_update()?;
718 } else {
719 debug!("skipping update due to locked registry");
720 }
721 Ok(())
722 }
723
724 fn download(&mut self, package: PackageId) -> CargoResult<MaybePackage> {
725 let hash = self.index.hash(package, &mut *self.ops)?;
726 match self.ops.download(package, hash)? {
727 MaybeLock::Ready(file) => self.get_pkg(package, &file).map(MaybePackage::Ready),
728 MaybeLock::Download { url, descriptor } => {
729 Ok(MaybePackage::Download { url, descriptor })
730 }
731 }
732 }
733
734 fn finish_download(&mut self, package: PackageId, data: Vec<u8>) -> CargoResult<Package> {
735 let hash = self.index.hash(package, &mut *self.ops)?;
736 let file = self.ops.finish_download(package, hash, &data)?;
737 self.get_pkg(package, &file)
738 }
739
740 fn fingerprint(&self, pkg: &Package) -> CargoResult<String> {
741 Ok(pkg.package_id().version().to_string())
742 }
743
744 fn describe(&self) -> String {
745 self.source_id.display_index()
746 }
747
748 fn add_to_yanked_whitelist(&mut self, pkgs: &[PackageId]) {
749 self.yanked_whitelist.extend(pkgs);
750 }
751
752 fn is_yanked(&mut self, pkg: PackageId) -> CargoResult<bool> {
753 if !self.updated {
754 self.do_update()?;
755 }
756 self.index.is_yanked(pkg, &mut *self.ops)
757 }
758 }