1 //! Management of the index of a registry source
2 //!
3 //! This module contains management of the index and various operations, such as
4 //! actually parsing the index, looking for crates, etc. This is intended to be
5 //! abstract over remote indices (downloaded via git) and local registry indices
6 //! (which are all just present on the filesystem).
7 //!
8 //! ## Index Performance
9 //!
10 //! One important aspect of the index is that we want to optimize the "happy
11 //! path" as much as possible. Whenever you type `cargo build` Cargo will
12 //! *always* reparse the registry and learn about dependency information. This
13 //! is done because Cargo needs to learn about the upstream crates.io crates
14 //! that you're using and ensure that the preexisting `Cargo.lock` still matches
15 //! the current state of the world.
16 //!
17 //! Consequently, Cargo "null builds" (the index that Cargo adds to each build
18 //! itself) need to be fast when accessing the index. The primary performance
19 //! optimization here is to avoid parsing JSON blobs from the registry if we
20 //! don't need them. Most secondary optimizations are centered around removing
21 //! allocations and such, but avoiding parsing JSON is the #1 optimization.
22 //!
23 //! When we get queries from the resolver we're given a `Dependency`. This
24 //! dependency in turn has a version requirement, and with lock files that
25 //! already exist these version requirements are exact version requirements
26 //! `=a.b.c`. This means that we in theory only need to parse one line of JSON
27 //! per query in the registry, the one that matches version `a.b.c`.
28 //!
29 //! The crates.io index, however, is not amenable to this form of query. Instead
30 //! the crates.io index simply is a file where each line is a JSON blob. To
31 //! learn about the versions in each JSON blob we would need to parse the JSON,
32 //! defeating the purpose of trying to parse as little as possible.
33 //!
34 //! > Note that as a small aside even *loading* the JSON from the registry is
35 //! > actually pretty slow. For crates.io and remote registries we don't
36 //! > actually check out the git index on disk because that takes quite some
37 //! > time and is quite large. Instead we use `libgit2` to read the JSON from
38 //! > the raw git objects. This in turn can be slow (aka show up high in
39 //! > profiles) because libgit2 has to do deflate decompression and such.
40 //!
41 //! To solve all these issues a strategy is employed here where Cargo basically
42 //! creates an index into the index. The first time a package is queried about
43 //! (first time being for an entire computer) Cargo will load the contents
44 //! (slowly via libgit2) from the registry. It will then (slowly) parse every
45 //! single line to learn about its versions. Afterwards, however, Cargo will
46 //! emit a new file (a cache) which is amenable for speedily parsing in future
47 //! invocations.
48 //!
49 //! This cache file is currently organized by basically having the semver
50 //! version extracted from each JSON blob. That way Cargo can quickly and easily
51 //! parse all versions contained and which JSON blob they're associated with.
52 //! The JSON blob then doesn't actually need to get parsed unless the version is
53 //! parsed.
54 //!
55 //! Altogether the initial measurements of this shows a massive improvement for
56 //! Cargo null build performance. It's expected that the improvements earned
57 //! here will continue to grow over time in the sense that the previous
58 //! implementation (parse all lines each time) actually continues to slow down
59 //! over time as new versions of a crate are published. In any case when first
60 //! implemented a null build of Cargo itself would parse 3700 JSON blobs from
61 //! the registry and load 150 blobs from git. Afterwards it parses 150 JSON
62 //! blobs and loads 0 files git. Removing 200ms or more from Cargo's startup
63 //! time is certainly nothing to sneeze at!
64 //!
65 //! Note that this is just a high-level overview, there's of course lots of
66 //! details like invalidating caches and whatnot which are handled below, but
67 //! hopefully those are more obvious inline in the code itself.
68 
69 use crate::core::dependency::Dependency;
70 use crate::core::{PackageId, SourceId, Summary};
71 use crate::sources::registry::{RegistryData, RegistryPackage, INDEX_V_MAX};
72 use crate::util::interning::InternedString;
73 use crate::util::{internal, CargoResult, Config, Filesystem, OptVersionReq, ToSemver};
74 use anyhow::bail;
75 use cargo_util::{paths, registry::make_dep_path};
76 use log::{debug, info};
77 use semver::Version;
78 use std::collections::{HashMap, HashSet};
79 use std::convert::TryInto;
80 use std::fs;
81 use std::path::Path;
82 use std::str;
83 
84 /// Crates.io treats hyphen and underscores as interchangeable, but the index and old Cargo do not.
85 /// Therefore, the index must store uncanonicalized version of the name so old Cargo's can find it.
86 /// This loop tries all possible combinations of switching hyphen and underscores to find the
87 /// uncanonicalized one. As all stored inputs have the correct spelling, we start with the spelling
88 /// as-provided.
89 struct UncanonicalizedIter<'s> {
90     input: &'s str,
91     num_hyphen_underscore: u32,
92     hyphen_combination_num: u16,
93 }
94 
95 impl<'s> UncanonicalizedIter<'s> {
new(input: &'s str) -> Self96     fn new(input: &'s str) -> Self {
97         let num_hyphen_underscore = input.chars().filter(|&c| c == '_' || c == '-').count() as u32;
98         UncanonicalizedIter {
99             input,
100             num_hyphen_underscore,
101             hyphen_combination_num: 0,
102         }
103     }
104 }
105 
106 impl<'s> Iterator for UncanonicalizedIter<'s> {
107     type Item = String;
108 
next(&mut self) -> Option<Self::Item>109     fn next(&mut self) -> Option<Self::Item> {
110         if self.hyphen_combination_num > 0
111             && self.hyphen_combination_num.trailing_zeros() >= self.num_hyphen_underscore
112         {
113             return None;
114         }
115 
116         let ret = Some(
117             self.input
118                 .chars()
119                 .scan(0u16, |s, c| {
120                     // the check against 15 here's to prevent
121                     // shift overflow on inputs with more than 15 hyphens
122                     if (c == '_' || c == '-') && *s <= 15 {
123                         let switch = (self.hyphen_combination_num & (1u16 << *s)) > 0;
124                         let out = if (c == '_') ^ switch { '_' } else { '-' };
125                         *s += 1;
126                         Some(out)
127                     } else {
128                         Some(c)
129                     }
130                 })
131                 .collect(),
132         );
133         self.hyphen_combination_num += 1;
134         ret
135     }
136 }
137 
138 #[test]
no_hyphen()139 fn no_hyphen() {
140     assert_eq!(
141         UncanonicalizedIter::new("test").collect::<Vec<_>>(),
142         vec!["test".to_string()]
143     )
144 }
145 
146 #[test]
two_hyphen()147 fn two_hyphen() {
148     assert_eq!(
149         UncanonicalizedIter::new("te-_st").collect::<Vec<_>>(),
150         vec![
151             "te-_st".to_string(),
152             "te__st".to_string(),
153             "te--st".to_string(),
154             "te_-st".to_string()
155         ]
156     )
157 }
158 
159 #[test]
overflow_hyphen()160 fn overflow_hyphen() {
161     assert_eq!(
162         UncanonicalizedIter::new("te-_-_-_-_-_-_-_-_-st")
163             .take(100)
164             .count(),
165         100
166     )
167 }
168 
169 /// Manager for handling the on-disk index.
170 ///
171 /// Note that local and remote registries store the index differently. Local
172 /// is a simple on-disk tree of files of the raw index. Remote registries are
173 /// stored as a raw git repository. The different means of access are handled
174 /// via the [`RegistryData`] trait abstraction.
175 ///
176 /// This transparently handles caching of the index in a more efficient format.
177 pub struct RegistryIndex<'cfg> {
178     source_id: SourceId,
179     /// Root directory of the index for the registry.
180     path: Filesystem,
181     /// Cache of summary data.
182     ///
183     /// This is keyed off the package name. The [`Summaries`] value handles
184     /// loading the summary data. It keeps an optimized on-disk representation
185     /// of the JSON files, which is created in an as-needed fashion. If it
186     /// hasn't been cached already, it uses [`RegistryData::load`] to access
187     /// to JSON files from the index, and the creates the optimized on-disk
188     /// summary cache.
189     summaries_cache: HashMap<InternedString, Summaries>,
190     /// [`Config`] reference for convenience.
191     config: &'cfg Config,
192 }
193 
194 /// An internal cache of summaries for a particular package.
195 ///
196 /// A list of summaries are loaded from disk via one of two methods:
197 ///
198 /// 1. Primarily Cargo will parse the corresponding file for a crate in the
199 ///    upstream crates.io registry. That's just a JSON blob per line which we
200 ///    can parse, extract the version, and then store here.
201 ///
202 /// 2. Alternatively, if Cargo has previously run, we'll have a cached index of
203 ///    dependencies for the upstream index. This is a file that Cargo maintains
204 ///    lazily on the local filesystem and is much faster to parse since it
205 ///    doesn't involve parsing all of the JSON.
206 ///
207 /// The outward-facing interface of this doesn't matter too much where it's
208 /// loaded from, but it's important when reading the implementation to note that
209 /// we try to parse as little as possible!
210 #[derive(Default)]
211 struct Summaries {
212     /// A raw vector of uninterpreted bytes. This is what `Unparsed` start/end
213     /// fields are indexes into. If a `Summaries` is loaded from the crates.io
214     /// index then this field will be empty since nothing is `Unparsed`.
215     raw_data: Vec<u8>,
216 
217     /// All known versions of a crate, keyed from their `Version` to the
218     /// possibly parsed or unparsed version of the full summary.
219     versions: HashMap<Version, MaybeIndexSummary>,
220 }
221 
222 /// A lazily parsed `IndexSummary`.
223 enum MaybeIndexSummary {
224     /// A summary which has not been parsed, The `start` and `end` are pointers
225     /// into `Summaries::raw_data` which this is an entry of.
226     Unparsed { start: usize, end: usize },
227 
228     /// An actually parsed summary.
229     Parsed(IndexSummary),
230 }
231 
232 /// A parsed representation of a summary from the index.
233 ///
234 /// In addition to a full `Summary` we have information on whether it is `yanked`.
235 pub struct IndexSummary {
236     pub summary: Summary,
237     pub yanked: bool,
238     /// Schema version, see [`RegistryPackage`].
239     v: u32,
240 }
241 
242 /// A representation of the cache on disk that Cargo maintains of summaries.
243 /// Cargo will initially parse all summaries in the registry and will then
244 /// serialize that into this form and place it in a new location on disk,
245 /// ensuring that access in the future is much speedier.
246 #[derive(Default)]
247 struct SummariesCache<'a> {
248     versions: Vec<(Version, &'a [u8])>,
249 }
250 
251 impl<'cfg> RegistryIndex<'cfg> {
new( source_id: SourceId, path: &Filesystem, config: &'cfg Config, ) -> RegistryIndex<'cfg>252     pub fn new(
253         source_id: SourceId,
254         path: &Filesystem,
255         config: &'cfg Config,
256     ) -> RegistryIndex<'cfg> {
257         RegistryIndex {
258             source_id,
259             path: path.clone(),
260             summaries_cache: HashMap::new(),
261             config,
262         }
263     }
264 
265     /// Returns the hash listed for a specified `PackageId`.
hash(&mut self, pkg: PackageId, load: &mut dyn RegistryData) -> CargoResult<&str>266     pub fn hash(&mut self, pkg: PackageId, load: &mut dyn RegistryData) -> CargoResult<&str> {
267         let req = OptVersionReq::exact(pkg.version());
268         let summary = self
269             .summaries(pkg.name(), &req, load)?
270             .next()
271             .ok_or_else(|| internal(format!("no hash listed for {}", pkg)))?;
272         summary
273             .summary
274             .checksum()
275             .ok_or_else(|| internal(format!("no hash listed for {}", pkg)))
276     }
277 
278     /// Load a list of summaries for `name` package in this registry which
279     /// match `req`
280     ///
281     /// This function will semantically parse the on-disk index, match all
282     /// versions, and then return an iterator over all summaries which matched.
283     /// Internally there's quite a few layer of caching to amortize this cost
284     /// though since this method is called quite a lot on null builds in Cargo.
summaries<'a, 'b>( &'a mut self, name: InternedString, req: &'b OptVersionReq, load: &mut dyn RegistryData, ) -> CargoResult<impl Iterator<Item = &'a IndexSummary> + 'b> where 'a: 'b,285     pub fn summaries<'a, 'b>(
286         &'a mut self,
287         name: InternedString,
288         req: &'b OptVersionReq,
289         load: &mut dyn RegistryData,
290     ) -> CargoResult<impl Iterator<Item = &'a IndexSummary> + 'b>
291     where
292         'a: 'b,
293     {
294         let source_id = self.source_id;
295         let config = self.config;
296         let namespaced_features = self.config.cli_unstable().namespaced_features;
297         let weak_dep_features = self.config.cli_unstable().weak_dep_features;
298 
299         // First up actually parse what summaries we have available. If Cargo
300         // has run previously this will parse a Cargo-specific cache file rather
301         // than the registry itself. In effect this is intended to be a quite
302         // cheap operation.
303         let summaries = self.load_summaries(name, load)?;
304 
305         // Iterate over our summaries, extract all relevant ones which match our
306         // version requirement, and then parse all corresponding rows in the
307         // registry. As a reminder this `summaries` method is called for each
308         // entry in a lock file on every build, so we want to absolutely
309         // minimize the amount of work being done here and parse as little as
310         // necessary.
311         let raw_data = &summaries.raw_data;
312         let max_version = if namespaced_features || weak_dep_features {
313             INDEX_V_MAX
314         } else {
315             1
316         };
317         Ok(summaries
318             .versions
319             .iter_mut()
320             .filter_map(move |(k, v)| if req.matches(k) { Some(v) } else { None })
321             .filter_map(
322                 move |maybe| match maybe.parse(config, raw_data, source_id) {
323                     Ok(summary) => Some(summary),
324                     Err(e) => {
325                         info!("failed to parse `{}` registry package: {}", name, e);
326                         None
327                     }
328                 },
329             )
330             .filter(move |is| {
331                 if is.v > max_version {
332                     debug!(
333                         "unsupported schema version {} ({} {})",
334                         is.v,
335                         is.summary.name(),
336                         is.summary.version()
337                     );
338                     false
339                 } else {
340                     true
341                 }
342             })
343             .filter(move |is| {
344                 is.summary
345                     .unstable_gate(namespaced_features, weak_dep_features)
346                     .is_ok()
347             }))
348     }
349 
load_summaries( &mut self, name: InternedString, load: &mut dyn RegistryData, ) -> CargoResult<&mut Summaries>350     fn load_summaries(
351         &mut self,
352         name: InternedString,
353         load: &mut dyn RegistryData,
354     ) -> CargoResult<&mut Summaries> {
355         // If we've previously loaded what versions are present for `name`, just
356         // return that since our cache should still be valid.
357         if self.summaries_cache.contains_key(&name) {
358             return Ok(self.summaries_cache.get_mut(&name).unwrap());
359         }
360 
361         // Prepare the `RegistryData` which will lazily initialize internal data
362         // structures.
363         load.prepare()?;
364 
365         // let root = self.config.assert_package_cache_locked(&self.path);
366         let root = load.assert_index_locked(&self.path);
367         let cache_root = root.join(".cache");
368         let index_version = load.current_version();
369 
370         // See module comment in `registry/mod.rs` for why this is structured
371         // the way it is.
372         let fs_name = name
373             .chars()
374             .flat_map(|c| c.to_lowercase())
375             .collect::<String>();
376         let raw_path = make_dep_path(&fs_name, false);
377 
378         // Attempt to handle misspellings by searching for a chain of related
379         // names to the original `raw_path` name. Only return summaries
380         // associated with the first hit, however. The resolver will later
381         // reject any candidates that have the wrong name, and with this it'll
382         // along the way produce helpful "did you mean?" suggestions.
383         for path in UncanonicalizedIter::new(&raw_path).take(1024) {
384             let summaries = Summaries::parse(
385                 index_version.as_deref(),
386                 root,
387                 &cache_root,
388                 path.as_ref(),
389                 self.source_id,
390                 load,
391                 self.config,
392             )?;
393             if let Some(summaries) = summaries {
394                 self.summaries_cache.insert(name, summaries);
395                 return Ok(self.summaries_cache.get_mut(&name).unwrap());
396             }
397         }
398 
399         // If nothing was found then this crate doesn't exists, so just use an
400         // empty `Summaries` list.
401         self.summaries_cache.insert(name, Summaries::default());
402         Ok(self.summaries_cache.get_mut(&name).unwrap())
403     }
404 
query_inner( &mut self, dep: &Dependency, load: &mut dyn RegistryData, yanked_whitelist: &HashSet<PackageId>, f: &mut dyn FnMut(Summary), ) -> CargoResult<()>405     pub fn query_inner(
406         &mut self,
407         dep: &Dependency,
408         load: &mut dyn RegistryData,
409         yanked_whitelist: &HashSet<PackageId>,
410         f: &mut dyn FnMut(Summary),
411     ) -> CargoResult<()> {
412         if self.config.offline()
413             && self.query_inner_with_online(dep, load, yanked_whitelist, f, false)? != 0
414         {
415             return Ok(());
416             // If offline, and there are no matches, try again with online.
417             // This is necessary for dependencies that are not used (such as
418             // target-cfg or optional), but are not downloaded. Normally the
419             // build should succeed if they are not downloaded and not used,
420             // but they still need to resolve. If they are actually needed
421             // then cargo will fail to download and an error message
422             // indicating that the required dependency is unavailable while
423             // offline will be displayed.
424         }
425         self.query_inner_with_online(dep, load, yanked_whitelist, f, true)?;
426         Ok(())
427     }
428 
query_inner_with_online( &mut self, dep: &Dependency, load: &mut dyn RegistryData, yanked_whitelist: &HashSet<PackageId>, f: &mut dyn FnMut(Summary), online: bool, ) -> CargoResult<usize>429     fn query_inner_with_online(
430         &mut self,
431         dep: &Dependency,
432         load: &mut dyn RegistryData,
433         yanked_whitelist: &HashSet<PackageId>,
434         f: &mut dyn FnMut(Summary),
435         online: bool,
436     ) -> CargoResult<usize> {
437         let source_id = self.source_id;
438         let summaries = self
439             .summaries(dep.package_name(), dep.version_req(), load)?
440             // First filter summaries for `--offline`. If we're online then
441             // everything is a candidate, otherwise if we're offline we're only
442             // going to consider candidates which are actually present on disk.
443             //
444             // Note: This particular logic can cause problems with
445             // optional dependencies when offline. If at least 1 version
446             // of an optional dependency is downloaded, but that version
447             // does not satisfy the requirements, then resolution will
448             // fail. Unfortunately, whether or not something is optional
449             // is not known here.
450             .filter(|s| (online || load.is_crate_downloaded(s.summary.package_id())))
451             // Next filter out all yanked packages. Some yanked packages may
452             // leak throguh if they're in a whitelist (aka if they were
453             // previously in `Cargo.lock`
454             .filter(|s| !s.yanked || yanked_whitelist.contains(&s.summary.package_id()))
455             .map(|s| s.summary.clone());
456 
457         // Handle `cargo update --precise` here. If specified, our own source
458         // will have a precise version listed of the form
459         // `<pkg>=<p_req>o-><f_req>` where `<pkg>` is the name of a crate on
460         // this source, `<p_req>` is the version installed and `<f_req> is the
461         // version requested (argument to `--precise`).
462         let name = dep.package_name().as_str();
463         let summaries = summaries.filter(|s| match source_id.precise() {
464             Some(p) if p.starts_with(name) && p[name.len()..].starts_with('=') => {
465                 let mut vers = p[name.len() + 1..].splitn(2, "->");
466                 if dep
467                     .version_req()
468                     .matches(&vers.next().unwrap().to_semver().unwrap())
469                 {
470                     vers.next().unwrap() == s.version().to_string()
471                 } else {
472                     true
473                 }
474             }
475             _ => true,
476         });
477 
478         let mut count = 0;
479         for summary in summaries {
480             f(summary);
481             count += 1;
482         }
483         Ok(count)
484     }
485 
is_yanked(&mut self, pkg: PackageId, load: &mut dyn RegistryData) -> CargoResult<bool>486     pub fn is_yanked(&mut self, pkg: PackageId, load: &mut dyn RegistryData) -> CargoResult<bool> {
487         let req = OptVersionReq::exact(pkg.version());
488         let found = self
489             .summaries(pkg.name(), &req, load)?
490             .any(|summary| summary.yanked);
491         Ok(found)
492     }
493 }
494 
495 impl Summaries {
496     /// Parse out a `Summaries` instances from on-disk state.
497     ///
498     /// This will attempt to prefer parsing a previous cache file that already
499     /// exists from a previous invocation of Cargo (aka you're typing `cargo
500     /// build` again after typing it previously). If parsing fails or the cache
501     /// isn't found, then we take a slower path which loads the full descriptor
502     /// for `relative` from the underlying index (aka typically libgit2 with
503     /// crates.io) and then parse everything in there.
504     ///
505     /// * `index_version` - a version string to describe the current state of
506     ///   the index which for remote registries is the current git sha and
507     ///   for local registries is not available.
508     /// * `root` - this is the root argument passed to `load`
509     /// * `cache_root` - this is the root on the filesystem itself of where to
510     ///   store cache files.
511     /// * `relative` - this is the file we're loading from cache or the index
512     ///   data
513     /// * `source_id` - the registry's SourceId used when parsing JSON blobs to
514     ///   create summaries.
515     /// * `load` - the actual index implementation which may be very slow to
516     ///   call. We avoid this if we can.
parse( index_version: Option<&str>, root: &Path, cache_root: &Path, relative: &Path, source_id: SourceId, load: &mut dyn RegistryData, config: &Config, ) -> CargoResult<Option<Summaries>>517     pub fn parse(
518         index_version: Option<&str>,
519         root: &Path,
520         cache_root: &Path,
521         relative: &Path,
522         source_id: SourceId,
523         load: &mut dyn RegistryData,
524         config: &Config,
525     ) -> CargoResult<Option<Summaries>> {
526         // First up, attempt to load the cache. This could fail for all manner
527         // of reasons, but consider all of them non-fatal and just log their
528         // occurrence in case anyone is debugging anything.
529         let cache_path = cache_root.join(relative);
530         let mut cache_contents = None;
531         if let Some(index_version) = index_version {
532             match fs::read(&cache_path) {
533                 Ok(contents) => match Summaries::parse_cache(contents, index_version) {
534                     Ok(s) => {
535                         log::debug!("fast path for registry cache of {:?}", relative);
536                         if cfg!(debug_assertions) {
537                             cache_contents = Some(s.raw_data);
538                         } else {
539                             return Ok(Some(s));
540                         }
541                     }
542                     Err(e) => {
543                         log::debug!("failed to parse {:?} cache: {}", relative, e);
544                     }
545                 },
546                 Err(e) => log::debug!("cache missing for {:?} error: {}", relative, e),
547             }
548         }
549 
550         // This is the fallback path where we actually talk to libgit2 to load
551         // information. Here we parse every single line in the index (as we need
552         // to find the versions)
553         log::debug!("slow path for {:?}", relative);
554         let mut ret = Summaries::default();
555         let mut hit_closure = false;
556         let mut cache_bytes = None;
557         let err = load.load(root, relative, &mut |contents| {
558             ret.raw_data = contents.to_vec();
559             let mut cache = SummariesCache::default();
560             hit_closure = true;
561             for line in split(contents, b'\n') {
562                 // Attempt forwards-compatibility on the index by ignoring
563                 // everything that we ourselves don't understand, that should
564                 // allow future cargo implementations to break the
565                 // interpretation of each line here and older cargo will simply
566                 // ignore the new lines.
567                 let summary = match IndexSummary::parse(config, line, source_id) {
568                     Ok(summary) => summary,
569                     Err(e) => {
570                         // This should only happen when there is an index
571                         // entry from a future version of cargo that this
572                         // version doesn't understand. Hopefully, those future
573                         // versions of cargo correctly set INDEX_V_MAX and
574                         // CURRENT_CACHE_VERSION, otherwise this will skip
575                         // entries in the cache preventing those newer
576                         // versions from reading them (that is, until the
577                         // cache is rebuilt).
578                         log::info!("failed to parse {:?} registry package: {}", relative, e);
579                         continue;
580                     }
581                 };
582                 let version = summary.summary.package_id().version().clone();
583                 cache.versions.push((version.clone(), line));
584                 ret.versions.insert(version, summary.into());
585             }
586             if let Some(index_version) = index_version {
587                 cache_bytes = Some(cache.serialize(index_version));
588             }
589             Ok(())
590         });
591 
592         // We ignore lookup failures as those are just crates which don't exist
593         // or we haven't updated the registry yet. If we actually ran the
594         // closure though then we care about those errors.
595         if !hit_closure {
596             debug_assert!(cache_contents.is_none());
597             return Ok(None);
598         }
599         err?;
600 
601         // If we've got debug assertions enabled and the cache was previously
602         // present and considered fresh this is where the debug assertions
603         // actually happens to verify that our cache is indeed fresh and
604         // computes exactly the same value as before.
605         if cfg!(debug_assertions) && cache_contents.is_some() {
606             if cache_bytes != cache_contents {
607                 panic!(
608                     "original cache contents:\n{:?}\n\
609                      does not equal new cache contents:\n{:?}\n",
610                     cache_contents.as_ref().map(|s| String::from_utf8_lossy(s)),
611                     cache_bytes.as_ref().map(|s| String::from_utf8_lossy(s)),
612                 );
613             }
614         }
615 
616         // Once we have our `cache_bytes` which represents the `Summaries` we're
617         // about to return, write that back out to disk so future Cargo
618         // invocations can use it.
619         //
620         // This is opportunistic so we ignore failure here but are sure to log
621         // something in case of error.
622         if let Some(cache_bytes) = cache_bytes {
623             if paths::create_dir_all(cache_path.parent().unwrap()).is_ok() {
624                 let path = Filesystem::new(cache_path.clone());
625                 config.assert_package_cache_locked(&path);
626                 if let Err(e) = fs::write(cache_path, cache_bytes) {
627                     log::info!("failed to write cache: {}", e);
628                 }
629             }
630         }
631 
632         Ok(Some(ret))
633     }
634 
635     /// Parses an open `File` which represents information previously cached by
636     /// Cargo.
parse_cache(contents: Vec<u8>, last_index_update: &str) -> CargoResult<Summaries>637     pub fn parse_cache(contents: Vec<u8>, last_index_update: &str) -> CargoResult<Summaries> {
638         let cache = SummariesCache::parse(&contents, last_index_update)?;
639         let mut ret = Summaries::default();
640         for (version, summary) in cache.versions {
641             let (start, end) = subslice_bounds(&contents, summary);
642             ret.versions
643                 .insert(version, MaybeIndexSummary::Unparsed { start, end });
644         }
645         ret.raw_data = contents;
646         return Ok(ret);
647 
648         // Returns the start/end offsets of `inner` with `outer`. Asserts that
649         // `inner` is a subslice of `outer`.
650         fn subslice_bounds(outer: &[u8], inner: &[u8]) -> (usize, usize) {
651             let outer_start = outer.as_ptr() as usize;
652             let outer_end = outer_start + outer.len();
653             let inner_start = inner.as_ptr() as usize;
654             let inner_end = inner_start + inner.len();
655             assert!(inner_start >= outer_start);
656             assert!(inner_end <= outer_end);
657             (inner_start - outer_start, inner_end - outer_start)
658         }
659     }
660 }
661 
662 // Implementation of serializing/deserializing the cache of summaries on disk.
663 // Currently the format looks like:
664 //
665 // +--------------------+----------------------+-------------+---+
666 // | cache version byte | index format version | git sha rev | 0 |
667 // +--------------------+----------------------+-------------+---+
668 //
669 // followed by...
670 //
671 // +----------------+---+------------+---+
672 // | semver version | 0 |  JSON blob | 0 | ...
673 // +----------------+---+------------+---+
674 //
675 // The idea is that this is a very easy file for Cargo to parse in future
676 // invocations. The read from disk should be quite fast and then afterwards all
677 // we need to know is what versions correspond to which JSON blob.
678 //
679 // The leading version byte is intended to ensure that there's some level of
680 // future compatibility against changes to this cache format so if different
681 // versions of Cargo share the same cache they don't get too confused. The git
682 // sha lets us know when the file needs to be regenerated (it needs regeneration
683 // whenever the index itself updates).
684 //
685 // Cache versions:
686 // * `1`: The original version.
687 // * `2`: Added the "index format version" field so that if the index format
688 //   changes, different versions of cargo won't get confused reading each
689 //   other's caches.
690 // * `3`: Bumped the version to work around a issue where multiple versions of
691 //   a package were published that differ only by semver metadata. For
692 //   example, openssl-src 110.0.0 and 110.0.0+1.1.0f. Previously, the cache
693 //   would be incorrectly populated with two entries, both 110.0.0. After
694 //   this, the metadata will be correctly included. This isn't really a format
695 //   change, just a version bump to clear the incorrect cache entries. Note:
696 //   the index shouldn't allow these, but unfortunately crates.io doesn't
697 //   check it.
698 
699 const CURRENT_CACHE_VERSION: u8 = 3;
700 
701 impl<'a> SummariesCache<'a> {
parse(data: &'a [u8], last_index_update: &str) -> CargoResult<SummariesCache<'a>>702     fn parse(data: &'a [u8], last_index_update: &str) -> CargoResult<SummariesCache<'a>> {
703         // NB: keep this method in sync with `serialize` below
704         let (first_byte, rest) = data
705             .split_first()
706             .ok_or_else(|| anyhow::format_err!("malformed cache"))?;
707         if *first_byte != CURRENT_CACHE_VERSION {
708             bail!("looks like a different Cargo's cache, bailing out");
709         }
710         let index_v_bytes = rest
711             .get(..4)
712             .ok_or_else(|| anyhow::anyhow!("cache expected 4 bytes for index version"))?;
713         let index_v = u32::from_le_bytes(index_v_bytes.try_into().unwrap());
714         if index_v != INDEX_V_MAX {
715             bail!(
716                 "index format version {} doesn't match the version I know ({})",
717                 index_v,
718                 INDEX_V_MAX
719             );
720         }
721         let rest = &rest[4..];
722 
723         let mut iter = split(rest, 0);
724         if let Some(update) = iter.next() {
725             if update != last_index_update.as_bytes() {
726                 bail!(
727                     "cache out of date: current index ({}) != cache ({})",
728                     last_index_update,
729                     str::from_utf8(update)?,
730                 )
731             }
732         } else {
733             bail!("malformed file");
734         }
735         let mut ret = SummariesCache::default();
736         while let Some(version) = iter.next() {
737             let version = str::from_utf8(version)?;
738             let version = Version::parse(version)?;
739             let summary = iter.next().unwrap();
740             ret.versions.push((version, summary));
741         }
742         Ok(ret)
743     }
744 
serialize(&self, index_version: &str) -> Vec<u8>745     fn serialize(&self, index_version: &str) -> Vec<u8> {
746         // NB: keep this method in sync with `parse` above
747         let size = self
748             .versions
749             .iter()
750             .map(|(_version, data)| (10 + data.len()))
751             .sum();
752         let mut contents = Vec::with_capacity(size);
753         contents.push(CURRENT_CACHE_VERSION);
754         contents.extend(&u32::to_le_bytes(INDEX_V_MAX));
755         contents.extend_from_slice(index_version.as_bytes());
756         contents.push(0);
757         for (version, data) in self.versions.iter() {
758             contents.extend_from_slice(version.to_string().as_bytes());
759             contents.push(0);
760             contents.extend_from_slice(data);
761             contents.push(0);
762         }
763         contents
764     }
765 }
766 
767 impl MaybeIndexSummary {
768     /// Parses this "maybe a summary" into a `Parsed` for sure variant.
769     ///
770     /// Does nothing if this is already `Parsed`, and otherwise the `raw_data`
771     /// passed in is sliced with the bounds in `Unparsed` and then actually
772     /// parsed.
parse( &mut self, config: &Config, raw_data: &[u8], source_id: SourceId, ) -> CargoResult<&IndexSummary>773     fn parse(
774         &mut self,
775         config: &Config,
776         raw_data: &[u8],
777         source_id: SourceId,
778     ) -> CargoResult<&IndexSummary> {
779         let (start, end) = match self {
780             MaybeIndexSummary::Unparsed { start, end } => (*start, *end),
781             MaybeIndexSummary::Parsed(summary) => return Ok(summary),
782         };
783         let summary = IndexSummary::parse(config, &raw_data[start..end], source_id)?;
784         *self = MaybeIndexSummary::Parsed(summary);
785         match self {
786             MaybeIndexSummary::Unparsed { .. } => unreachable!(),
787             MaybeIndexSummary::Parsed(summary) => Ok(summary),
788         }
789     }
790 }
791 
792 impl From<IndexSummary> for MaybeIndexSummary {
from(summary: IndexSummary) -> MaybeIndexSummary793     fn from(summary: IndexSummary) -> MaybeIndexSummary {
794         MaybeIndexSummary::Parsed(summary)
795     }
796 }
797 
798 impl IndexSummary {
799     /// Parses a line from the registry's index file into an `IndexSummary` for
800     /// a package.
801     ///
802     /// The `line` provided is expected to be valid JSON.
parse(config: &Config, line: &[u8], source_id: SourceId) -> CargoResult<IndexSummary>803     fn parse(config: &Config, line: &[u8], source_id: SourceId) -> CargoResult<IndexSummary> {
804         // ****CAUTION**** Please be extremely careful with returning errors
805         // from this function. Entries that error are not included in the
806         // index cache, and can cause cargo to get confused when switching
807         // between different versions that understand the index differently.
808         // Make sure to consider the INDEX_V_MAX and CURRENT_CACHE_VERSION
809         // values carefully when making changes here.
810         let RegistryPackage {
811             name,
812             vers,
813             cksum,
814             deps,
815             mut features,
816             features2,
817             yanked,
818             links,
819             v,
820         } = serde_json::from_slice(line)?;
821         let v = v.unwrap_or(1);
822         log::trace!("json parsed registry {}/{}", name, vers);
823         let pkgid = PackageId::new(name, &vers, source_id)?;
824         let deps = deps
825             .into_iter()
826             .map(|dep| dep.into_dep(source_id))
827             .collect::<CargoResult<Vec<_>>>()?;
828         if let Some(features2) = features2 {
829             for (name, values) in features2 {
830                 features.entry(name).or_default().extend(values);
831             }
832         }
833         let mut summary = Summary::new(config, pkgid, deps, &features, links)?;
834         summary.set_checksum(cksum);
835         Ok(IndexSummary {
836             summary,
837             yanked: yanked.unwrap_or(false),
838             v,
839         })
840     }
841 }
842 
split(haystack: &[u8], needle: u8) -> impl Iterator<Item = &[u8]>843 fn split(haystack: &[u8], needle: u8) -> impl Iterator<Item = &[u8]> {
844     struct Split<'a> {
845         haystack: &'a [u8],
846         needle: u8,
847     }
848 
849     impl<'a> Iterator for Split<'a> {
850         type Item = &'a [u8];
851 
852         fn next(&mut self) -> Option<&'a [u8]> {
853             if self.haystack.is_empty() {
854                 return None;
855             }
856             let (ret, remaining) = match memchr::memchr(self.needle, self.haystack) {
857                 Some(pos) => (&self.haystack[..pos], &self.haystack[pos + 1..]),
858                 None => (self.haystack, &[][..]),
859             };
860             self.haystack = remaining;
861             Some(ret)
862         }
863     }
864 
865     Split { haystack, needle }
866 }
867