    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366

    use crate::core::{GitReference, PackageId, SourceId};
    use crate::sources::git;
    use crate::sources::registry::download;
    use crate::sources::registry::MaybeLock;
    use crate::sources::registry::{LoadResponse, RegistryConfig, RegistryData};
    use crate::util::errors::CargoResult;
    use crate::util::interning::InternedString;
    use crate::util::{Config, Filesystem};
    use anyhow::Context as _;
    use cargo_util::paths;
    use lazycell::LazyCell;
    use log::{debug, trace};
    use std::cell::{Cell, Ref, RefCell};
    use std::fs::File;
    use std::mem;
    use std::path::Path;
    use std::str;
    use std::task::{ready, Poll};

    /// A remote registry is a registry that lives at a remote URL (such as
    /// crates.io). The git index is cloned locally, and `.crate` files are
    /// downloaded as needed and cached locally.
    pub struct RemoteRegistry<'cfg> {
        index_path: Filesystem,
        /// Path to the cache of `.crate` files (`$CARGO_HOME/registry/path/$REG-HASH`).
        cache_path: Filesystem,
        source_id: SourceId,
        index_git_ref: GitReference,
        config: &'cfg Config,
        tree: RefCell<Option<git2::Tree<'static>>>,
        repo: LazyCell<git2::Repository>,
        head: Cell<Option<git2::Oid>>,
        current_sha: Cell<Option<InternedString>>,
        needs_update: bool, // Does this registry need to be updated?
        quiet: bool,
    }

    impl<'cfg> RemoteRegistry<'cfg> {
        pub fn new(source_id: SourceId, config: &'cfg Config, name: &str) -> RemoteRegistry<'cfg> {
            RemoteRegistry {
                index_path: config.registry_index_path().join(name),
                cache_path: config.registry_cache_path().join(name),
                source_id,
                config,
                // TODO: we should probably make this configurable
                index_git_ref: GitReference::DefaultBranch,
                tree: RefCell::new(None),
                repo: LazyCell::new(),
                head: Cell::new(None),
                current_sha: Cell::new(None),
                needs_update: false,
                quiet: false,
            }
        }

        fn repo(&self) -> CargoResult<&git2::Repository> {
            self.repo.try_borrow_with(|| {
                let path = self.config.assert_package_cache_locked(&self.index_path);

                // Fast path without a lock
                if let Ok(repo) = git2::Repository::open(&path) {
                    trace!("opened a repo without a lock");
                    return Ok(repo);
                }

                // Ok, now we need to lock and try the whole thing over again.
                trace!("acquiring registry index lock");
                match git2::Repository::open(&path) {
                    Ok(repo) => Ok(repo),
                    Err(_) => {
                        drop(paths::remove_dir_all(&path));
                        paths::create_dir_all(&path)?;

                        // Note that we'd actually prefer to use a bare repository
                        // here as we're not actually going to check anything out.
                        // All versions of Cargo, though, share the same CARGO_HOME,
                        // so for compatibility with older Cargo which *does* do
                        // checkouts we make sure to initialize a new full
                        // repository (not a bare one).
                        //
                        // We should change this to `init_bare` whenever we feel
                        // like enough time has passed or if we change the directory
                        // that the folder is located in, such as by changing the
                        // hash at the end of the directory.
                        //
                        // Note that in the meantime we also skip `init.templatedir`
                        // as it can be misconfigured sometimes or otherwise add
                        // things that we don't want.
                        let mut opts = git2::RepositoryInitOptions::new();
                        opts.external_template(false);
                        Ok(git2::Repository::init_opts(&path, &opts).with_context(|| {
                            format!("failed to initialize index git repository (in {:?})", path)
                        })?)
                    }
                }
            })
        }

        fn head(&self) -> CargoResult<git2::Oid> {
            if self.head.get().is_none() {
                let repo = self.repo()?;
                let oid = self.index_git_ref.resolve(repo)?;
                self.head.set(Some(oid));
            }
            Ok(self.head.get().unwrap())
        }

        fn tree(&self) -> CargoResult<Ref<'_, git2::Tree<'_>>> {
            {
                let tree = self.tree.borrow();
                if tree.is_some() {
                    return Ok(Ref::map(tree, |s| s.as_ref().unwrap()));
                }
            }
            let repo = self.repo()?;
            let commit = repo.find_commit(self.head()?)?;
            let tree = commit.tree()?;

            // Unfortunately in libgit2 the tree objects look like they've got a
            // reference to the repository object which means that a tree cannot
            // outlive the repository that it came from. Here we want to cache this
            // tree, though, so to accomplish this we transmute it to a static
            // lifetime.
            //
            // Note that we don't actually hand out the static lifetime, instead we
            // only return a scoped one from this function. Additionally the repo
            // we loaded from (above) lives as long as this object
            // (`RemoteRegistry`) so we then just need to ensure that the tree is
            // destroyed first in the destructor, hence the destructor on
            // `RemoteRegistry` below.
            let tree = unsafe { mem::transmute::<git2::Tree<'_>, git2::Tree<'static>>(tree) };
            *self.tree.borrow_mut() = Some(tree);
            Ok(Ref::map(self.tree.borrow(), |s| s.as_ref().unwrap()))
        }

        fn current_version(&self) -> Option<InternedString> {
            if let Some(sha) = self.current_sha.get() {
                return Some(sha);
            }
            let sha = InternedString::new(&self.head().ok()?.to_string());
            self.current_sha.set(Some(sha));
            Some(sha)
        }

        fn is_updated(&self) -> bool {
            self.config.updated_sources().contains(&self.source_id)
        }

        fn mark_updated(&self) {
            self.config.updated_sources().insert(self.source_id);
        }
    }

    const LAST_UPDATED_FILE: &str = ".last-updated";

    impl<'cfg> RegistryData for RemoteRegistry<'cfg> {
        fn prepare(&self) -> CargoResult<()> {
            self.repo()?; // create intermediate dirs and initialize the repo
            Ok(())
        }

        fn index_path(&self) -> &Filesystem {
            &self.index_path
        }

        fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path {
            self.config.assert_package_cache_locked(path)
        }

        // `index_version` Is a string representing the version of the file used to construct the cached copy.
        // Older versions of Cargo used the single value of the hash of the HEAD commit as a `index_version`.
        // This is technically correct but a little too conservative. If a new commit is fetched all cached
        // files need to be regenerated even if a particular file was not changed.
        // However if an old cargo has written such a file we still know how to read it, as long as we check for that hash value.
        //
        // Cargo now uses a hash of the file's contents as provided by git.
        fn load(
            &mut self,
            _root: &Path,
            path: &Path,
            index_version: Option<&str>,
        ) -> Poll<CargoResult<LoadResponse>> {
            if self.needs_update {
                return Poll::Pending;
            }
            // Check if the cache is valid.
            let git_commit_hash = self.current_version();
            if index_version.is_some() && index_version == git_commit_hash.as_deref() {
                // This file was written by an old version of cargo, but it is still up-to-date.
                return Poll::Ready(Ok(LoadResponse::CacheValid));
            }
            // Note that the index calls this method and the filesystem is locked
            // in the index, so we don't need to worry about an `update_index`
            // happening in a different process.
            fn load_helper(
                registry: &RemoteRegistry<'_>,
                path: &Path,
                index_version: Option<&str>,
            ) -> CargoResult<LoadResponse> {
                let repo = registry.repo()?;
                let tree = registry.tree()?;
                let entry = tree.get_path(path);
                let entry = entry?;
                let git_file_hash = Some(entry.id().to_string());

                // Check if the cache is valid.
                if index_version.is_some() && index_version == git_file_hash.as_deref() {
                    return Ok(LoadResponse::CacheValid);
                }

                let object = entry.to_object(repo)?;
                let blob = match object.as_blob() {
                    Some(blob) => blob,
                    None => anyhow::bail!("path `{}` is not a blob in the git repo", path.display()),
                };

                Ok(LoadResponse::Data {
                    raw_data: blob.content().to_vec(),
                    index_version: git_file_hash,
                })
            }

            match load_helper(&self, path, index_version) {
                Ok(result) => Poll::Ready(Ok(result)),
                Err(_) if !self.is_updated() => {
                    // If git returns an error and we haven't updated the repo, return
                    // pending to allow an update to try again.
                    self.needs_update = true;
                    Poll::Pending
                }
                Err(e)
                    if e.downcast_ref::<git2::Error>()
                        .map(|e| e.code() == git2::ErrorCode::NotFound)
                        .unwrap_or_default() =>
                {
                    // The repo has been updated and the file does not exist.
                    Poll::Ready(Ok(LoadResponse::NotFound))
                }
                Err(e) => Poll::Ready(Err(e)),
            }
        }

        fn config(&mut self) -> Poll<CargoResult<Option<RegistryConfig>>> {
            debug!("loading config");
            self.prepare()?;
            self.config.assert_package_cache_locked(&self.index_path);
            match ready!(self.load(Path::new(""), Path::new("config.json"), None)?) {
                LoadResponse::Data { raw_data, .. } => {
                    trace!("config loaded");
                    let mut cfg: RegistryConfig = serde_json::from_slice(&raw_data)?;
                    if !self.config.cli_unstable().registry_auth {
                        cfg.auth_required = false;
                    }
                    Poll::Ready(Ok(Some(cfg)))
                }
                _ => Poll::Ready(Ok(None)),
            }
        }

        fn block_until_ready(&mut self) -> CargoResult<()> {
            if !self.needs_update {
                return Ok(());
            }

            self.needs_update = false;

            // Make sure the index is only updated once per session since it is an
            // expensive operation. This generally only happens when the resolver
            // is run multiple times, such as during `cargo publish`.
            if self.is_updated() {
                return Ok(());
            }
            self.mark_updated();

            if self.config.offline() {
                return Ok(());
            }
            if self.config.cli_unstable().no_index_update {
                return Ok(());
            }

            debug!("updating the index");

            // Ensure that we'll actually be able to acquire an HTTP handle later on
            // once we start trying to download crates. This will weed out any
            // problems with `.cargo/config` configuration related to HTTP.
            //
            // This way if there's a problem the error gets printed before we even
            // hit the index, which may not actually read this configuration.
            self.config.http()?;

            self.prepare()?;
            self.head.set(None);
            *self.tree.borrow_mut() = None;
            self.current_sha.set(None);
            let path = self.config.assert_package_cache_locked(&self.index_path);
            if !self.quiet {
                self.config
                    .shell()
                    .status("Updating", self.source_id.display_index())?;
            }

            // Fetch the latest version of our `index_git_ref` into the index
            // checkout.
            let url = self.source_id.url();
            let repo = self.repo.borrow_mut().unwrap();
            git::fetch(repo, url.as_str(), &self.index_git_ref, self.config)
                .with_context(|| format!("failed to fetch `{}`", url))?;

            // Create a dummy file to record the mtime for when we updated the
            // index.
            paths::create(&path.join(LAST_UPDATED_FILE))?;

            Ok(())
        }

        fn invalidate_cache(&mut self) {
            // To fully invalidate, undo `mark_updated`s work
            self.needs_update = true;
        }

        fn set_quiet(&mut self, quiet: bool) {
            self.quiet = quiet;
        }

        fn is_updated(&self) -> bool {
            self.is_updated()
        }

        fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock> {
            let registry_config = loop {
                match self.config()? {
                    Poll::Pending => self.block_until_ready()?,
                    Poll::Ready(cfg) => break cfg.unwrap(),
                }
            };

            download::download(
                &self.cache_path,
                &self.config,
                pkg,
                checksum,
                registry_config,
            )
        }

        fn finish_download(
            &mut self,
            pkg: PackageId,
            checksum: &str,
            data: &[u8],
        ) -> CargoResult<File> {
            download::finish_download(&self.cache_path, &self.config, pkg, checksum, data)
        }

        fn is_crate_downloaded(&self, pkg: PackageId) -> bool {
            download::is_crate_downloaded(&self.cache_path, &self.config, pkg)
        }
    }

    impl<'cfg> Drop for RemoteRegistry<'cfg> {
        fn drop(&mut self) {
            // Just be sure to drop this before our other fields
            self.tree.borrow_mut().take();
        }
    }