Skip to main content

cargo/context/
mod.rs

1//! Cargo's config system.
2//!
3//! The [`GlobalContext`] object contains general information about the environment,
4//! and provides access to Cargo's configuration files.
5//!
6//! ## Config value API
7//!
8//! The primary API for fetching user-defined config values is the
9//! [`GlobalContext::get`] method. It uses `serde` to translate config values to a
10//! target type.
11//!
12//! There are a variety of helper types for deserializing some common formats:
13//!
14//! - [`Value`]: This type provides access to the location where the
15//!   config value was defined.
16//! - [`ConfigRootRelativePath`]: For a path that is relative to where it is
17//!   defined.
18//! - [`ConfigRootRelativeProgramPath`]: For a path that is relative to where it is
19//!   defined unless it is a bin name to look up in `PATH`
20//! - [`ConfigRootRelativePathTemplate`]: For a templated path that is relative to where it is
21//!   defined.
22//! - [`PathAndArgs`]: Similar to [`ConfigRootRelativePath`],
23//!   but also supports a list of arguments, useful for programs to execute.
24//! - [`StringList`]: Get a value that is either a list or a whitespace split
25//!   string.
26//!
27//! # Config schemas
28//!
29//! Configuration schemas are defined in the [`crate::config::schema`] module.
30//!
31//! ## Config deserialization
32//!
33//! Cargo uses a two-layer deserialization approach:
34//!
35//! 1. **External sources → `ConfigValue`** ---
36//!    Configuration files, environment variables, and CLI `--config` arguments
37//!    are parsed into [`ConfigValue`] instances via [`ConfigValue::from_toml`].
38//!    These parsed results are stored in [`GlobalContext`].
39//!
40//! 2. **`ConfigValue` → Target types** ---
41//!    The [`GlobalContext::get`] method uses a custom Serde deserializer
42//!    to convert [`ConfigValue`] instances to the caller's desired type.
43//!    Precedence between [`ConfigValue`] sources is resolved during retrieval
44//!    based on [`Definition`] priority.
45//!    See [`ConfigReader::get`] for the typed lookup API.
46//!
47//! ## Map key recommendations
48//!
49//! Handling tables that have arbitrary keys can be tricky, particularly if it
50//! should support environment variables. In general, if possible, the caller
51//! should pass the full key path into the `get()` method so that the config
52//! deserializer can properly handle environment variables (which need to be
53//! uppercased, and dashes converted to underscores).
54//!
55//! A good example is the `[target]` table. The code will request
56//! `target.$TUPLE` and the config system can then appropriately fetch
57//! environment variables like `CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER`.
58//! Conversely, it is not possible do the same thing for the `cfg()` target
59//! tables (because Cargo must fetch all of them), so those do not support
60//! environment variables.
61//!
62//! Try to avoid keys that are a prefix of another with a dash/underscore. For
63//! example `build.target` and `build.target-dir`. This is OK if these are not
64//! structs/maps, but if it is a struct or map, then it will not be able to
65//! read the environment variable due to ambiguity. (See `ConfigMapAccess` for
66//! more details.)
67
68use cargo_util::collections::{HashMap, HashSet};
69use std::env;
70use std::ffi::{OsStr, OsString};
71use std::fs::File;
72use std::io::SeekFrom;
73use std::io::prelude::*;
74use std::path::{Path, PathBuf};
75use std::sync::{Arc, LazyLock, Mutex, MutexGuard, OnceLock};
76use std::time::Instant;
77
78use self::ConfigValue as CV;
79use crate::ops::RegistryCredentialConfig;
80use crate::sources::CRATES_IO_INDEX;
81use crate::sources::CRATES_IO_REGISTRY;
82use crate::util::OnceExt as _;
83use crate::util::VersionReqMatchMode;
84use crate::util::cache_lock::{CacheLock, CacheLockMode, CacheLocker};
85use crate::util::errors::CargoResult;
86use crate::util::network::http::{HandleConfiguration, configure_http_handle, http_handle};
87use crate::util::network::http_async;
88use crate::util::{CanonicalUrl, closest_msg, internal};
89use crate::util::{Filesystem, IntoUrl, IntoUrlWithBase, Rustc};
90use crate::workspace::global_cache_tracker::{DeferredGlobalLastUse, GlobalCacheTracker};
91use crate::workspace::{CliUnstable, SourceId, Workspace, WorkspaceRootConfig, features};
92
93use anyhow::{Context as _, anyhow, bail, format_err};
94use cargo_credential::Secret;
95use cargo_util::paths;
96use cargo_util_schemas::manifest::RegistryName;
97use cargo_util_terminal::{Shell, Verbosity};
98use curl::easy::Easy;
99use itertools::Itertools;
100use jiff::Timestamp;
101use url::Url;
102
103use crate::config::ConfigLoader;
104use crate::config::ConfigReader;
105use crate::config::Env;
106pub use crate::config::{
107    ConfigError, ConfigKey, ConfigStore, ConfigValue, Definition, OptValue, Scope, Value,
108};
109
110mod target;
111pub use target::{TargetCfgConfig, TargetConfig};
112
113pub use crate::config::schema::*;
114
115pub const TOP_LEVEL_CONFIG_KEYS: &[&str] = &[
116    "paths",
117    "alias",
118    "build",
119    "credential-alias",
120    "doc",
121    "env",
122    "future-incompat-report",
123    "cache",
124    "cargo-new",
125    "http",
126    "install",
127    "net",
128    "patch",
129    "profile",
130    "resolver",
131    "registries",
132    "registry",
133    "source",
134    "target",
135    "term",
136];
137
138/// A previously generated authentication token and the data needed to determine if it can be reused.
139#[derive(Debug)]
140pub struct CredentialCacheValue {
141    pub token_value: Secret<String>,
142    pub expiration: Option<Timestamp>,
143    pub operation_independent: bool,
144}
145
146/// Configuration information for cargo. This is not specific to a build, it is information
147/// relating to cargo itself.
148#[derive(Debug)]
149pub struct GlobalContext {
150    /// The location of the user's Cargo home directory. OS-dependent.
151    cargo_home: Filesystem,
152    /// Information about how to write messages to the shell
153    shell: Mutex<Shell>,
154    /// A collection of configuration options
155    config: OnceLock<ConfigStore>,
156    /// A collection of configuration options from the credentials file
157    credentials_config: OnceLock<ConfigStore>,
158    /// CLI config values, passed in via `configure`.
159    cli_config: Option<Vec<String>>,
160    /// The current working directory of cargo
161    cwd: PathBuf,
162    /// Directory where config file searching should stop (inclusive).
163    search_stop_path: Option<PathBuf>,
164    /// The location of the cargo executable (path to current process)
165    cargo_exe: OnceLock<PathBuf>,
166    /// The location of the rustdoc executable
167    rustdoc: OnceLock<PathBuf>,
168    /// Whether we are printing extra verbose messages
169    extra_verbose: bool,
170    /// `frozen` is the same as `locked`, but additionally will not access the
171    /// network to determine if the lock file is out-of-date.
172    frozen: bool,
173    /// `locked` is set if we should not update lock files. If the lock file
174    /// is missing, or needs to be updated, an error is produced.
175    locked: bool,
176    /// `offline` is set if we should never access the network, but otherwise
177    /// continue operating if possible.
178    offline: bool,
179    /// A global static IPC control mechanism (used for managing parallel builds)
180    jobserver: Option<&'static jobserver::Client>,
181    /// Cli flags of the form "-Z something" merged with config file values
182    unstable_flags: CliUnstable,
183    /// Cli flags of the form "-Z something"
184    unstable_flags_cli: Option<Vec<String>>,
185    /// A handle on curl easy mode for http calls
186    easy: OnceLock<Mutex<Easy>>,
187    /// Cache of the `SourceId` for crates.io
188    crates_io_source_id: OnceLock<SourceId>,
189    /// If false, don't cache `rustc --version --verbose` invocations
190    cache_rustc_info: bool,
191    /// Monotonic start of this cargo invocation for reporting time elapsed.
192    invocation_instant: Instant,
193    /// Wall-clock time of this cargo invocation.
194    ///
195    /// Currently used as the reference time for `min-publish-age` and `-Zbuild-analysis`.
196    invocation_time: jiff::Timestamp,
197    /// Target Directory via resolved Cli parameter
198    target_dir: Option<Filesystem>,
199    /// Environment variable snapshot.
200    env: Env,
201    /// Tracks which sources have been updated to avoid multiple updates.
202    updated_sources: Mutex<HashSet<SourceId>>,
203    /// Cache of credentials from configuration or credential providers.
204    /// Maps from url to credential value.
205    credential_cache: Mutex<HashMap<CanonicalUrl, CredentialCacheValue>>,
206    /// Cache of registry config from the `[registries]` table.
207    registry_config: Mutex<HashMap<SourceId, Option<RegistryConfig>>>,
208    /// Locks on the package and index caches.
209    package_cache_lock: CacheLocker,
210    /// Cached configuration parsed by Cargo
211    http_config: OnceLock<CargoHttpConfig>,
212    http_async: OnceLock<http_async::Client>,
213    future_incompat_config: OnceLock<CargoFutureIncompatConfig>,
214    net_config: OnceLock<CargoNetConfig>,
215    build_config: OnceLock<CargoBuildConfig>,
216    target_cfgs: OnceLock<Vec<(String, TargetCfgConfig)>>,
217    doc_extern_map: OnceLock<RustdocExternMap>,
218    progress_config: ProgressConfig,
219    env_config: OnceLock<Arc<HashMap<String, OsString>>>,
220    /// This should be false if:
221    /// - this is an artifact of the rustc distribution process for "stable" or for "beta"
222    /// - this is an `#[test]` that does not opt in with `enable_nightly_features`
223    /// - this is an integration test that uses `ProcessBuilder`
224    ///      that does not opt in with `masquerade_as_nightly_cargo`
225    /// This should be true if:
226    /// - this is an artifact of the rustc distribution process for "nightly"
227    /// - this is being used in the rustc distribution process internally
228    /// - this is a cargo executable that was built from source
229    /// - this is an `#[test]` that called `enable_nightly_features`
230    /// - this is an integration test that uses `ProcessBuilder`
231    ///       that called `masquerade_as_nightly_cargo`
232    /// It's public to allow tests use nightly features.
233    /// NOTE: this should be set before `configure()`. If calling this from an integration test,
234    /// consider using `ConfigBuilder::enable_nightly_features` instead.
235    pub nightly_features_allowed: bool,
236    /// `WorkspaceRootConfigs` that have been found
237    ws_roots: Mutex<HashMap<PathBuf, WorkspaceRootConfig>>,
238    /// The global cache tracker is a database used to track disk cache usage.
239    global_cache_tracker: OnceLock<Mutex<GlobalCacheTracker>>,
240    /// A cache of modifications to make to [`GlobalContext::global_cache_tracker`],
241    /// saved to disk in a batch to improve performance.
242    deferred_global_last_use: OnceLock<Mutex<DeferredGlobalLastUse>>,
243}
244
245impl GlobalContext {
246    /// Creates a new config instance.
247    ///
248    /// This is typically used for tests or other special cases. `default` is
249    /// preferred otherwise.
250    ///
251    /// This does only minimal initialization. In particular, it does not load
252    /// any config files from disk. Those will be loaded lazily as-needed.
253    pub fn new(mut shell: Shell, cwd: PathBuf, cargo_home: PathBuf) -> GlobalContext {
254        static GLOBAL_JOBSERVER: LazyLock<CargoResult<Option<jobserver::Client>>> = LazyLock::new(
255            || {
256                use jobserver::FromEnvErrorKind;
257                // Note that this is unsafe because it may misinterpret file descriptors
258                // on Unix as jobserver file descriptors. We hopefully execute this near
259                // the beginning of the process though to ensure we don't get false
260                // positives, or in other words we try to execute this before we open
261                // any file descriptors ourselves.
262                let jobserver::FromEnv { client, var } =
263                    unsafe { jobserver::Client::from_env_ext(true) };
264
265                match client {
266                    Ok(client) => return Ok(Some(client)),
267                    Err(e)
268                        if matches!(
269                            e.kind(),
270                            FromEnvErrorKind::NoEnvVar
271                                | FromEnvErrorKind::NoJobserver
272                                | FromEnvErrorKind::NegativeFd
273                                | FromEnvErrorKind::Unsupported
274                        ) =>
275                    {
276                        Ok(None)
277                    }
278                    Err(e) => {
279                        let (name, value) = var.unwrap();
280                        Err(anyhow::anyhow!(
281                            "failed to connect to jobserver from environment variable `{name}={value:?}`: {e}"
282                        ))
283                    }
284                }
285            },
286        );
287        let jobserver = match &*GLOBAL_JOBSERVER {
288            Ok(jobserver) => jobserver.as_ref(),
289            Err(e) => {
290                let _ = shell.warn(e);
291                None
292            }
293        };
294
295        let env = Env::from_env();
296
297        let cache_key = "CARGO_CACHE_RUSTC_INFO";
298        let cache_rustc_info = match env.get_env_os(cache_key) {
299            Some(cache) => cache != "0",
300            _ => true,
301        };
302
303        #[expect(
304            clippy::disallowed_methods,
305            reason = "testing only, no reason for config support"
306        )]
307        let invocation_time = match env::var("__CARGO_TEST_INVOCATION_TIME") {
308            Ok(now) => now.parse().unwrap(),
309            Err(_) => jiff::Timestamp::now(),
310        };
311
312        GlobalContext {
313            cargo_home: Filesystem::new(cargo_home),
314            shell: Mutex::new(shell),
315            cwd,
316            search_stop_path: None,
317            config: Default::default(),
318            credentials_config: Default::default(),
319            cli_config: None,
320            cargo_exe: Default::default(),
321            rustdoc: Default::default(),
322            extra_verbose: false,
323            frozen: false,
324            locked: false,
325            offline: false,
326            jobserver,
327            unstable_flags: CliUnstable::default(),
328            unstable_flags_cli: None,
329            easy: Default::default(),
330            crates_io_source_id: Default::default(),
331            cache_rustc_info,
332            invocation_instant: Instant::now(),
333            invocation_time,
334            target_dir: None,
335            env,
336            updated_sources: Default::default(),
337            credential_cache: Default::default(),
338            registry_config: Default::default(),
339            package_cache_lock: CacheLocker::new(),
340            http_config: Default::default(),
341            http_async: Default::default(),
342            future_incompat_config: Default::default(),
343            net_config: Default::default(),
344            build_config: Default::default(),
345            target_cfgs: Default::default(),
346            doc_extern_map: Default::default(),
347            progress_config: ProgressConfig::default(),
348            env_config: Default::default(),
349            nightly_features_allowed: matches!(&*features::channel(), "nightly" | "dev"),
350            ws_roots: Default::default(),
351            global_cache_tracker: Default::default(),
352            deferred_global_last_use: Default::default(),
353        }
354    }
355
356    /// Creates a new instance, with all default settings.
357    ///
358    /// This does only minimal initialization. In particular, it does not load
359    /// any config files from disk. Those will be loaded lazily as-needed.
360    pub fn default() -> CargoResult<GlobalContext> {
361        let shell = Shell::new();
362        let cwd =
363            env::current_dir().context("couldn't get the current directory of the process")?;
364        let cargo_home = cargo_home(&cwd)?;
365        Ok(GlobalContext::new(shell, cwd, cargo_home))
366    }
367
368    /// Gets the user's Cargo home directory (OS-dependent).
369    pub fn cargo_home(&self) -> &Filesystem {
370        &self.cargo_home
371    }
372
373    /// Returns a path to display to the user with the location of their home
374    /// config file (to only be used for displaying a diagnostics suggestion,
375    /// such as recommending where to add a config value).
376    pub fn diagnostic_home_config(&self) -> String {
377        let cargo_home = self.cargo_home.as_path_unlocked();
378        let path = match self
379            .config_loader()
380            .get_file_path(cargo_home, "config", false)
381        {
382            Ok(Some(existing_path)) => existing_path,
383            _ => cargo_home.join("config.toml"),
384        };
385        path.to_string_lossy().to_string()
386    }
387
388    /// Gets the Cargo Git directory (`<cargo_home>/git`).
389    pub fn git_path(&self) -> Filesystem {
390        self.cargo_home.join("git")
391    }
392
393    /// Gets the directory of code sources Cargo checkouts from Git bare repos
394    /// (`<cargo_home>/git/checkouts`).
395    pub fn git_checkouts_path(&self) -> Filesystem {
396        self.git_path().join("checkouts")
397    }
398
399    /// Gets the directory for all Git bare repos Cargo clones
400    /// (`<cargo_home>/git/db`).
401    pub fn git_db_path(&self) -> Filesystem {
402        self.git_path().join("db")
403    }
404
405    /// Gets the Cargo base directory for all registry information (`<cargo_home>/registry`).
406    pub fn registry_base_path(&self) -> Filesystem {
407        self.cargo_home.join("registry")
408    }
409
410    /// Gets the Cargo registry index directory (`<cargo_home>/registry/index`).
411    pub fn registry_index_path(&self) -> Filesystem {
412        self.registry_base_path().join("index")
413    }
414
415    /// Gets the Cargo registry cache directory (`<cargo_home>/registry/cache`).
416    pub fn registry_cache_path(&self) -> Filesystem {
417        self.registry_base_path().join("cache")
418    }
419
420    /// Gets the Cargo registry source directory (`<cargo_home>/registry/src`).
421    pub fn registry_source_path(&self) -> Filesystem {
422        self.registry_base_path().join("src")
423    }
424
425    /// Gets the default Cargo registry.
426    pub fn default_registry(&self) -> CargoResult<Option<String>> {
427        Ok(self
428            .get_string(["registry", "default"])?
429            .map(|registry| registry.val))
430    }
431
432    /// Gets a reference to the shell, e.g., for writing error messages.
433    pub fn shell(&self) -> MutexGuard<'_, Shell> {
434        self.shell.lock().unwrap()
435    }
436
437    /// Assert [`Self::shell`] is not in use
438    ///
439    /// Testing might not identify bugs with two accesses to `shell` at once
440    /// due to conditional logic,
441    /// so place this outside of the conditions to catch these bugs in more situations.
442    pub fn debug_assert_shell_not_borrowed(&self) {
443        if cfg!(debug_assertions) {
444            match self.shell.try_lock() {
445                Ok(_) | Err(std::sync::TryLockError::Poisoned(_)) => (),
446                Err(std::sync::TryLockError::WouldBlock) => panic!("shell is borrowed!"),
447            }
448        }
449    }
450
451    /// Gets the path to the `rustdoc` executable.
452    pub fn rustdoc(&self) -> CargoResult<&Path> {
453        self.rustdoc
454            .try_borrow_with(|| Ok(self.get_tool(Tool::Rustdoc, &self.build_config()?.rustdoc)))
455            .map(AsRef::as_ref)
456    }
457
458    /// Gets the path to the `rustc` executable.
459    pub fn load_global_rustc(&self, ws: Option<&Workspace<'_>>) -> CargoResult<Rustc> {
460        let cache_location =
461            ws.map(|ws| ws.build_dir().join(".rustc_info.json").into_path_unlocked());
462        let wrapper = self.maybe_get_tool("rustc_wrapper", &self.build_config()?.rustc_wrapper);
463        let rustc_workspace_wrapper = self.maybe_get_tool(
464            "rustc_workspace_wrapper",
465            &self.build_config()?.rustc_workspace_wrapper,
466        );
467
468        Rustc::new(
469            self.get_tool(Tool::Rustc, &self.build_config()?.rustc),
470            wrapper,
471            rustc_workspace_wrapper,
472            &self
473                .cargo_home()
474                .join("bin")
475                .join("rustc")
476                .into_path_unlocked()
477                .with_extension(env::consts::EXE_EXTENSION),
478            if self.cache_rustc_info {
479                cache_location
480            } else {
481                None
482            },
483            self,
484        )
485    }
486
487    /// Gets the path to the `cargo` executable.
488    pub fn cargo_exe(&self) -> CargoResult<&Path> {
489        self.cargo_exe
490            .try_borrow_with(|| {
491                let from_env = || -> CargoResult<PathBuf> {
492                    // Try re-using the `cargo` set in the environment already. This allows
493                    // commands that use Cargo as a library to inherit (via `cargo <subcommand>`)
494                    // or set (by setting `$CARGO`) a correct path to `cargo` when the current exe
495                    // is not actually cargo (e.g., `cargo-*` binaries, Valgrind, `ld.so`, etc.).
496                    let exe = self
497                        .get_env_os(crate::CARGO_ENV)
498                        .map(PathBuf::from)
499                        .ok_or_else(|| anyhow!("$CARGO not set"))?;
500                    Ok(exe)
501                };
502
503                fn from_current_exe() -> CargoResult<PathBuf> {
504                    // Try fetching the path to `cargo` using `env::current_exe()`.
505                    // The method varies per operating system and might fail; in particular,
506                    // it depends on `/proc` being mounted on Linux, and some environments
507                    // (like containers or chroots) may not have that available.
508                    let exe = env::current_exe()?;
509                    Ok(exe)
510                }
511
512                fn from_argv() -> CargoResult<PathBuf> {
513                    // Grab `argv[0]` and attempt to resolve it to an absolute path.
514                    // If `argv[0]` has one component, it must have come from a `PATH` lookup,
515                    // so probe `PATH` in that case.
516                    // Otherwise, it has multiple components and is either:
517                    // - a relative path (e.g., `./cargo`, `target/debug/cargo`), or
518                    // - an absolute path (e.g., `/usr/local/bin/cargo`).
519                    let argv0 = env::args_os()
520                        .map(PathBuf::from)
521                        .next()
522                        .ok_or_else(|| anyhow!("no argv[0]"))?;
523                    paths::resolve_executable(&argv0)
524                }
525
526                // Determines whether `path` is a cargo binary.
527                // See: https://github.com/rust-lang/cargo/issues/15099#issuecomment-2666737150
528                fn is_cargo(path: &Path) -> bool {
529                    path.file_stem() == Some(OsStr::new("cargo"))
530                }
531
532                let from_current_exe = from_current_exe();
533                if from_current_exe.as_deref().is_ok_and(is_cargo) {
534                    return from_current_exe;
535                }
536
537                let from_argv = from_argv();
538                if from_argv.as_deref().is_ok_and(is_cargo) {
539                    return from_argv;
540                }
541
542                let exe = from_env()
543                    .or(from_current_exe)
544                    .or(from_argv)
545                    .context("couldn't get the path to cargo executable")?;
546                Ok(exe)
547            })
548            .map(AsRef::as_ref)
549    }
550
551    /// Which package sources have been updated, used to ensure it is only done once.
552    pub fn updated_sources(&self) -> MutexGuard<'_, HashSet<SourceId>> {
553        self.updated_sources.lock().unwrap()
554    }
555
556    /// Cached credentials from credential providers or configuration.
557    pub fn credential_cache(&self) -> MutexGuard<'_, HashMap<CanonicalUrl, CredentialCacheValue>> {
558        self.credential_cache.lock().unwrap()
559    }
560
561    /// Gets the configuration for a remote registry.
562    ///
563    /// The registry name is resolved from its index URL. This may emit a note if
564    /// the resolved name differs from the source's configured name. Returns
565    /// `None` if no configuration is found.
566    ///
567    /// **Note:** this does not load tokens from `credentials.toml`, see instead
568    /// [`Self::registry_credentials`].
569    pub fn registry_config(&self, sid: &SourceId) -> CargoResult<Option<RegistryConfig>> {
570        let mut cache = self.registry_config.lock().unwrap();
571        if let Some(cfg) = cache.get(sid) {
572            return Ok(cfg.clone());
573        }
574        let cfg = registry_config_uncached(self, sid)?;
575        cache.insert(*sid, cfg.clone());
576        Ok(cfg)
577    }
578
579    /// Gets the credentials configured for a remote registry.
580    ///
581    /// This loads credentials if needed and resolves the registry name in the
582    /// same way as [`GlobalContext::registry_config`].
583    pub fn registry_credentials(&self, sid: &SourceId) -> CargoResult<Option<RegistryCredential>> {
584        let credentials = self.credentials_config()?;
585        let mut key = if sid.is_crates_io() {
586            ConfigKey::from_parts(["registry"])
587        } else if let Some(name) = registry_name(self, sid)? {
588            ConfigKey::from_parts(["registries", &name])
589        } else {
590            return Ok(None);
591        };
592        let has_credentials = credentials.get_cv(&key)?.is_some();
593        key.push("token");
594        let credentials_token = match credentials.get_cv(&key)? {
595            Some(CV::String(val, definition)) => Some(Value {
596                val: Secret::from(val),
597                definition,
598            }),
599            Some(cv) => return Err(ConfigError::expected(&key, "a string", &cv).into()),
600            None => None,
601        };
602
603        let config = self.registry_config(sid)?;
604        let has_config = config.is_some();
605        let config_token = config.and_then(|config| {
606            #[expect(deprecated)]
607            config.token
608        });
609
610        let token = match (config_token, credentials_token) {
611            (Some(config_token), Some(credentials_token))
612                if config_token
613                    .definition
614                    .is_higher_priority(&credentials_token.definition) =>
615            {
616                Some(config_token)
617            }
618            (_, Some(credentials_token)) => Some(credentials_token),
619            (config_token, None) => config_token,
620        };
621
622        Ok((has_config || has_credentials).then_some(RegistryCredential { token }))
623    }
624
625    /// Gets all config values from disk.
626    ///
627    /// This will lazy-load the values as necessary. Callers are responsible
628    /// for checking environment variables. Callers outside of the `config`
629    /// module should avoid using this.
630    pub fn config(&self) -> CargoResult<&ConfigStore> {
631        self.config.try_borrow_with(|| self.load_config())
632    }
633
634    /// Gets a mutable copy of the on-disk config values.
635    ///
636    /// This requires the config values to already have been loaded. This
637    /// currently only exists for `cargo vendor` to remove the `source`
638    /// entries. This doesn't respect environment variables. You should avoid
639    /// using this if possible.
640    pub fn config_mut(&mut self) -> CargoResult<&mut ConfigStore> {
641        let _ = self.config()?;
642        Ok(self.config.get_mut().expect("already loaded config values"))
643    }
644
645    /// Sets the path where ancestor config file searching will stop. The
646    /// given path is included, but its ancestors are not.
647    pub fn set_search_stop_path<P: Into<PathBuf>>(&mut self, path: P) {
648        let path = path.into();
649        debug_assert!(self.cwd.starts_with(&path));
650        self.search_stop_path = Some(path);
651    }
652
653    /// Switches the working directory to [`std::env::current_dir`]
654    ///
655    /// There is not a need to also call [`Self::reload_rooted_at`].
656    pub fn reload_cwd(&mut self) -> CargoResult<()> {
657        let cwd =
658            env::current_dir().context("couldn't get the current directory of the process")?;
659        let cargo_home = cargo_home(&cwd)?;
660
661        self.cwd = cwd;
662        self.cargo_home = Filesystem::new(cargo_home);
663        self.reload_rooted_at(self.cwd.clone())?;
664        Ok(())
665    }
666
667    /// Reloads on-disk configuration values, starting at the given path and
668    /// walking up its ancestors.
669    pub fn reload_rooted_at<P: AsRef<Path>>(&mut self, path: P) -> CargoResult<()> {
670        let mut layers = self.config_loader().load_layers(path.as_ref())?;
671        layers.push(self.cli_args_to_config()?);
672        let config =
673            ConfigStore::from_layers(layers).context("could not load Cargo configuration")?;
674        self.config.replace(config);
675        self.load_unstable_flags_from_config()?;
676        Ok(())
677    }
678
679    /// The current working directory.
680    pub fn cwd(&self) -> &Path {
681        &self.cwd
682    }
683
684    /// The `target` output directory to use.
685    ///
686    /// Returns `None` if the user has not chosen an explicit directory.
687    ///
688    /// Callers should prefer [`Workspace::target_dir`] instead.
689    pub fn target_dir(&self) -> CargoResult<Option<Filesystem>> {
690        if let Some(dir) = &self.target_dir {
691            Ok(Some(dir.clone()))
692        } else if let Some(dir) = self.get_env_os("CARGO_TARGET_DIR") {
693            // Check if the CARGO_TARGET_DIR environment variable is set to an empty string.
694            if dir.is_empty() {
695                bail!(
696                    "the target directory is set to an empty string in the \
697                     `CARGO_TARGET_DIR` environment variable"
698                )
699            }
700
701            Ok(Some(Filesystem::new(self.cwd.join(dir))))
702        } else if let Some(val) = &self.build_config()?.target_dir {
703            let path = val.resolve(self.cwd());
704
705            // Check if the target directory is set to an empty string in the config.toml file.
706            if val.is_empty() {
707                bail!(
708                    "the target directory is set to an empty string in {}",
709                    val.definition()
710                )
711            }
712
713            Ok(Some(Filesystem::new(path)))
714        } else {
715            Ok(None)
716        }
717    }
718
719    /// The directory to use for intermediate build artifacts.
720    ///
721    /// Callers should prefer [`Workspace::build_dir`] instead.
722    pub fn build_dir(&self, workspace_manifest_path: &Path) -> CargoResult<Option<Filesystem>> {
723        let Some(val) = &self.build_config()?.build_dir else {
724            return Ok(None);
725        };
726        self.custom_build_dir(val, workspace_manifest_path)
727            .map(Some)
728    }
729
730    /// The directory to use for intermediate build artifacts.
731    ///
732    /// Callers should prefer [`Workspace::build_dir`] instead.
733    pub fn custom_build_dir(
734        &self,
735        val: &ConfigRootRelativePathTemplate,
736        workspace_manifest_path: &Path,
737    ) -> CargoResult<Filesystem> {
738        let replacements = [
739            (
740                "{workspace-root}",
741                workspace_manifest_path
742                    .parent()
743                    .unwrap()
744                    .to_str()
745                    .context("workspace root was not valid utf-8")?
746                    .to_string(),
747            ),
748            (
749                "{cargo-cache-home}",
750                self.cargo_home()
751                    .as_path_unlocked()
752                    .to_str()
753                    .context("cargo home was not valid utf-8")?
754                    .to_string(),
755            ),
756            ("{workspace-path-hash}", {
757                let real_path = std::fs::canonicalize(workspace_manifest_path)
758                    .unwrap_or_else(|_err| workspace_manifest_path.to_owned());
759                let hash = crate::util::hex::short_hash(&real_path);
760                format!("{}{}{}", &hash[0..2], std::path::MAIN_SEPARATOR, &hash[2..])
761            }),
762        ];
763
764        let template_variables = replacements
765            .iter()
766            .map(|(key, _)| key[1..key.len() - 1].to_string())
767            .collect_vec();
768
769        let path = val
770            .resolve(self.cwd(), replacements)
771            .map_err(|e| match e {
772                ResolveTemplateError::UnexpectedVariable {
773                    variable,
774                    raw_template,
775                } => {
776                    let mut suggestion = closest_msg(&variable, template_variables.iter(), |key| key, "template variable");
777                    if suggestion == "" {
778                        let variables = template_variables.iter().map(|v| format!("`{{{v}}}`")).join(", ");
779                        suggestion = format!("\n\nhelp: available template variables are {variables}");
780                    }
781                    anyhow!(
782                            "unexpected variable `{variable}` in build.build-dir path `{raw_template}`{suggestion}"
783                        )
784                }
785                ResolveTemplateError::UnexpectedBracket { bracket_type, raw_template } => {
786                    let (btype, literal) = match bracket_type {
787                        BracketType::Opening => ("opening", "{"),
788                        BracketType::Closing => ("closing", "}"),
789                    };
790
791                    anyhow!(
792                            "unexpected {btype} bracket `{literal}` in build.build-dir path `{raw_template}`"
793                        )
794                }
795            })?;
796
797        // Check if the target directory is set to an empty string in the config.toml file.
798        if val.is_empty() {
799            bail!(
800                "the build directory is set to an empty string in {}",
801                val.definition()
802            )
803        }
804
805        Ok(Filesystem::new(path))
806    }
807
808    fn config_reader(&self) -> CargoResult<ConfigReader<'_>> {
809        Ok(ConfigReader::new(&self.shell)
810            .config(self.config()?)
811            .env(&self.env)
812            .unstable_advanced_env(self.cli_unstable().advanced_env))
813    }
814
815    pub(crate) fn get_cv_with_env(&self, key: &ConfigKey) -> CargoResult<Option<CV>> {
816        self.config_reader()?.get_cv_with_env(key)
817    }
818
819    /// Helper primarily for testing.
820    pub fn set_env(&mut self, env: HashMap<String, String>) {
821        self.env = Env::from_map(env);
822    }
823
824    /// Returns all environment variables as an iterator,
825    /// keeping only entries where both the key and value are valid UTF-8.
826    pub(crate) fn env(&self) -> impl Iterator<Item = (&str, &str)> {
827        self.env.iter_str()
828    }
829
830    /// Get the value of environment variable `key` through the snapshot in
831    /// [`GlobalContext`].
832    ///
833    /// This can be used similarly to [`std::env::var`].
834    pub fn get_env(&self, key: impl AsRef<OsStr>) -> CargoResult<&str> {
835        self.env.get_env(key)
836    }
837
838    /// Get the value of environment variable `key` through the snapshot in
839    /// [`GlobalContext`].
840    ///
841    /// This can be used similarly to [`std::env::var_os`].
842    pub fn get_env_os(&self, key: impl AsRef<OsStr>) -> Option<&OsStr> {
843        self.env.get_env_os(key)
844    }
845
846    /// Get a string config value.
847    ///
848    /// See `get` for more details.
849    pub fn get_string(
850        &self,
851        key: impl IntoIterator<Item = impl AsRef<str>>,
852    ) -> CargoResult<OptValue<String>> {
853        self.get::<OptValue<String>>(key)
854    }
855
856    /// Update the instance based on settings typically passed in on
857    /// the command-line.
858    ///
859    /// This may also load the config from disk if it hasn't already been
860    /// loaded.
861    pub fn configure(
862        &mut self,
863        verbose: u32,
864        quiet: bool,
865        color: Option<&str>,
866        frozen: bool,
867        locked: bool,
868        offline: bool,
869        target_dir: &Option<PathBuf>,
870        unstable_flags: &[String],
871        cli_config: &[String],
872    ) -> CargoResult<()> {
873        for warning in self
874            .unstable_flags
875            .parse(unstable_flags, self.nightly_features_allowed)?
876        {
877            self.shell().warn(warning)?;
878        }
879        if !unstable_flags.is_empty() {
880            // store a copy of the cli flags separately for `load_unstable_flags_from_config`
881            // (we might also need it again for `reload_rooted_at`)
882            self.unstable_flags_cli = Some(unstable_flags.to_vec());
883        }
884        if !cli_config.is_empty() {
885            self.cli_config = Some(cli_config.iter().map(|s| s.to_string()).collect());
886            let cli_config = self.cli_args_to_config()?;
887            // Config files may already be loaded and merged, for example to expand aliases.
888            let files = std::mem::take(self.config_mut()?);
889            let config = ConfigStore::from_layers([files, cli_config])?;
890            self.config.replace(config);
891        }
892
893        self.load_unstable_flags_from_config()?;
894
895        // Ignore errors in the configuration files. We don't want basic
896        // commands like `cargo version` to error out due to config file
897        // problems.
898        let term = self.get::<TermConfig>(["term"]).unwrap_or_default();
899
900        // The command line takes precedence over configuration.
901        let extra_verbose = verbose >= 2;
902        let verbose = verbose != 0;
903        let verbosity = match (verbose, quiet) {
904            (true, true) => bail!("cannot set both --verbose and --quiet"),
905            (true, false) => Verbosity::Verbose,
906            (false, true) => Verbosity::Quiet,
907            (false, false) => match (term.verbose, term.quiet) {
908                (Some(true), Some(true)) => {
909                    bail!("cannot set both `term.verbose` and `term.quiet`")
910                }
911                (Some(true), _) => Verbosity::Verbose,
912                (_, Some(true)) => Verbosity::Quiet,
913                _ => Verbosity::Normal,
914            },
915        };
916        self.shell().set_verbosity(verbosity);
917        self.extra_verbose = extra_verbose;
918
919        let color = color.or_else(|| term.color.as_deref());
920        self.shell().set_color_choice(color)?;
921        if let Some(hyperlinks) = term.hyperlinks {
922            self.shell().set_hyperlinks(hyperlinks)?;
923        }
924        if let Some(unicode) = term.unicode {
925            self.shell().set_unicode(unicode)?;
926        }
927
928        self.progress_config = term.progress.unwrap_or_default();
929
930        self.frozen = frozen;
931        self.locked = locked;
932        self.offline = offline
933            || self
934                .net_config()
935                .ok()
936                .and_then(|n| n.offline)
937                .unwrap_or(false);
938        let cli_target_dir = target_dir.as_ref().map(|dir| Filesystem::new(dir.clone()));
939        self.target_dir = cli_target_dir;
940
941        self.shell()
942            .set_unstable_flags_rustc_unicode(self.unstable_flags.rustc_unicode)?;
943
944        // Without this a user could set `NO_GRAPHICS=1` and be able to use an
945        // unstable feature without it being enabled
946        if !self.unstable_flags.term_graphics {
947            self.shell().set_graphics(true)?;
948        }
949
950        if let Some(graphics) = term.graphics {
951            if self.unstable_flags.term_graphics {
952                self.shell().set_graphics(graphics)?;
953            } else {
954                self.shell()
955                    .warn("ignoring `term.graphics` without `-Zterm-graphics`")?;
956            }
957        }
958
959        Ok(())
960    }
961
962    fn load_unstable_flags_from_config(&mut self) -> CargoResult<()> {
963        // If nightly features are enabled, allow setting Z-flags from config
964        // using the `unstable` table. Ignore that block otherwise.
965        if self.nightly_features_allowed {
966            self.unstable_flags = self
967                .get::<Option<CliUnstable>>(["unstable"])?
968                .unwrap_or_default();
969            if let Some(unstable_flags_cli) = &self.unstable_flags_cli {
970                // NB. It's not ideal to parse these twice, but doing it again here
971                //     allows the CLI to override config files for both enabling
972                //     and disabling, and doing it up top allows CLI Zflags to
973                //     control config parsing behavior.
974                self.unstable_flags.parse(unstable_flags_cli, true)?;
975            }
976        }
977
978        Ok(())
979    }
980
981    pub fn cli_unstable(&self) -> &CliUnstable {
982        &self.unstable_flags
983    }
984
985    pub fn extra_verbose(&self) -> bool {
986        self.extra_verbose
987    }
988
989    pub fn network_allowed(&self) -> bool {
990        !self.offline_flag().is_some()
991    }
992
993    pub fn offline_flag(&self) -> Option<&'static str> {
994        if self.frozen {
995            Some("--frozen")
996        } else if self.offline {
997            Some("--offline")
998        } else {
999            None
1000        }
1001    }
1002
1003    pub fn set_locked(&mut self, locked: bool) {
1004        self.locked = locked;
1005    }
1006
1007    pub fn lock_update_allowed(&self) -> bool {
1008        !self.locked_flag().is_some()
1009    }
1010
1011    pub fn locked_flag(&self) -> Option<&'static str> {
1012        if self.frozen {
1013            Some("--frozen")
1014        } else if self.locked {
1015            Some("--locked")
1016        } else {
1017            None
1018        }
1019    }
1020
1021    /// Loads configuration from the filesystem.
1022    pub fn load_config(&self) -> CargoResult<ConfigStore> {
1023        let layers = self.config_loader().load_layers(&self.cwd)?;
1024        ConfigStore::from_layers(layers).context("could not load Cargo configuration")
1025    }
1026
1027    /// Parses the CLI config args and returns them as a table.
1028    pub(crate) fn cli_args_to_config(&self) -> CargoResult<ConfigStore> {
1029        let cli_args = self.cli_config.as_deref().unwrap_or_default();
1030        self.config_loader().load_cli_args_layer(cli_args)
1031    }
1032
1033    pub(crate) fn config_loader(&self) -> ConfigLoader<'_> {
1034        ConfigLoader::new(&self.shell, &self.cwd, self.cargo_home.as_path_unlocked())
1035            .search_stop_path(self.search_stop_path.as_deref())
1036    }
1037
1038    /// Gets the index for a registry.
1039    pub fn get_registry_index(&self, registry: &str) -> CargoResult<Url> {
1040        RegistryName::new(registry)?;
1041        if let Some(index) = self.get_string(["registries", registry, "index"])? {
1042            self.resolve_registry_index(&index).with_context(|| {
1043                format!(
1044                    "invalid index URL for registry `{}` defined in {}",
1045                    registry, index.definition
1046                )
1047            })
1048        } else {
1049            bail!(
1050                "registry index was not found in any configuration: `{}`",
1051                registry
1052            );
1053        }
1054    }
1055
1056    /// Returns an error if `registry.index` is set.
1057    pub fn check_registry_index_not_set(&self) -> CargoResult<()> {
1058        if self.get_string(["registry", "index"])?.is_some() {
1059            bail!(
1060                "the `registry.index` config value is no longer supported\n\
1061                Use `[source]` replacement to alter the default index for crates.io."
1062            );
1063        }
1064        Ok(())
1065    }
1066
1067    fn resolve_registry_index(&self, index: &Value<String>) -> CargoResult<Url> {
1068        // This handles relative file: URLs, relative to the config definition.
1069        let base = index
1070            .definition
1071            .root(self.cwd())
1072            .join("truncated-by-url_with_base");
1073        // Parse val to check it is a URL, not a relative path without a protocol.
1074        let _parsed = index.val.into_url()?;
1075        let url = index.val.into_url_with_base(Some(&*base))?;
1076        if url.password().is_some() {
1077            bail!("registry URLs may not contain passwords");
1078        }
1079        Ok(url)
1080    }
1081
1082    /// Gets configuration values from the credentials file, loading them on first use.
1083    fn credentials_config(&self) -> CargoResult<&ConfigStore> {
1084        self.credentials_config
1085            .try_borrow_with(|| self.config_loader().load_credentials())
1086    }
1087
1088    /// Looks for a path for `tool` in an environment variable or the given config, and returns
1089    /// `None` if it's not present.
1090    fn maybe_get_tool(
1091        &self,
1092        tool: &str,
1093        from_config: &Option<ConfigRootRelativeProgramPath>,
1094    ) -> Option<PathBuf> {
1095        let var = tool.to_uppercase();
1096
1097        match self.get_env_os(&var).as_ref().and_then(|s| s.to_str()) {
1098            Some(tool_path) => {
1099                let maybe_relative = tool_path.contains('/') || tool_path.contains('\\');
1100                let path = if maybe_relative {
1101                    self.cwd.join(tool_path)
1102                } else {
1103                    PathBuf::from(tool_path)
1104                };
1105                Some(path)
1106            }
1107
1108            None => from_config.as_ref().map(|p| p.resolve(self.cwd())),
1109        }
1110    }
1111
1112    /// Returns the path for the given tool.
1113    ///
1114    /// This will look for the tool in the following order:
1115    ///
1116    /// 1. From an environment variable matching the tool name (such as `RUSTC`).
1117    /// 2. From the given config value (which is usually something like `build.rustc`).
1118    /// 3. Finds the tool in the PATH environment variable.
1119    ///
1120    /// This is intended for tools that are rustup proxies. If you need to get
1121    /// a tool that is not a rustup proxy, use `maybe_get_tool` instead.
1122    fn get_tool(&self, tool: Tool, from_config: &Option<ConfigRootRelativeProgramPath>) -> PathBuf {
1123        let tool_str = tool.as_str();
1124        self.maybe_get_tool(tool_str, from_config)
1125            .or_else(|| {
1126                // This is an optimization to circumvent the rustup proxies
1127                // which can have a significant performance hit. The goal here
1128                // is to determine if calling `rustc` from PATH would end up
1129                // calling the proxies.
1130                //
1131                // This is somewhat cautious trying to determine if it is safe
1132                // to circumvent rustup, because there are some situations
1133                // where users may do things like modify PATH, call cargo
1134                // directly, use a custom rustup toolchain link without a
1135                // cargo executable, etc. However, there is still some risk
1136                // this may make the wrong decision in unusual circumstances.
1137                //
1138                // First, we must be running under rustup in the first place.
1139                let toolchain = self.get_env_os("RUSTUP_TOOLCHAIN")?;
1140                // Rustup supports named toolchains and absolute path toolchains,
1141                // but not relative path toolchains. This also enforces UTF-8.
1142                let toolchain = toolchain.to_str()?;
1143                let toolchain_path = Path::new(toolchain);
1144                let toolchain_dir = if toolchain_path.is_absolute() {
1145                    toolchain_path.to_path_buf()
1146                } else if !toolchain.contains(&['/', '\\']) {
1147                    home::rustup_home().ok()?.join("toolchains").join(toolchain)
1148                } else {
1149                    return None;
1150                };
1151                // If the tool on PATH is the same as `rustup` on path, then
1152                // there is pretty good evidence that it will be a proxy.
1153                let tool_resolved = paths::resolve_executable(Path::new(tool_str)).ok()?;
1154                let rustup_resolved = paths::resolve_executable(Path::new("rustup")).ok()?;
1155                let tool_meta = tool_resolved.metadata().ok()?;
1156                let rustup_meta = rustup_resolved.metadata().ok()?;
1157                // This works on the assumption that rustup and its proxies
1158                // use hard links to a single binary. If rustup ever changes
1159                // that setup, then I think the worst consequence is that this
1160                // optimization will not work, and it will take the slow path.
1161                if tool_meta.len() != rustup_meta.len() {
1162                    return None;
1163                }
1164                // Try to find the tool in rustup's toolchain directory.
1165                let tool_exe = Path::new(tool_str).with_extension(env::consts::EXE_EXTENSION);
1166                let toolchain_exe = toolchain_dir.join("bin").join(&tool_exe);
1167                toolchain_exe.exists().then_some(toolchain_exe)
1168            })
1169            .unwrap_or_else(|| PathBuf::from(tool_str))
1170    }
1171
1172    /// Get the `paths` overrides config value.
1173    pub fn paths_overrides(&self) -> CargoResult<OptValue<Vec<(String, Definition)>>> {
1174        let key = ConfigKey::from_parts(["paths"]);
1175        // paths overrides cannot be set via env config, so use get_cv here.
1176        match self.config()?.get_cv(&key)? {
1177            Some(CV::List(val, definition)) => {
1178                let val = val
1179                    .into_iter()
1180                    .map(|cv| match cv {
1181                        CV::String(s, def) => Ok((s, def)),
1182                        other => crate::config::expected("string", &key, &other),
1183                    })
1184                    .collect::<CargoResult<Vec<_>>>()?;
1185                Ok(Some(Value { val, definition }))
1186            }
1187            Some(val) => crate::config::expected("list", &key, &val),
1188            None => Ok(None),
1189        }
1190    }
1191
1192    pub fn jobserver_from_env(&self) -> Option<&jobserver::Client> {
1193        self.jobserver
1194    }
1195
1196    pub fn http(&self) -> CargoResult<&Mutex<Easy>> {
1197        let http = self
1198            .easy
1199            .try_borrow_with(|| http_handle(self).map(Into::into))?;
1200        {
1201            let mut http = http.lock().unwrap();
1202            http.reset();
1203            let timeout = configure_http_handle(self, &mut http)?;
1204            timeout.configure(&mut http)?;
1205        }
1206        Ok(http)
1207    }
1208
1209    pub fn http_async(&self) -> CargoResult<&http_async::Client> {
1210        self.http_async.try_borrow_with(|| {
1211            let handle_config = HandleConfiguration::new(&self)?;
1212            Ok(http_async::Client::new(handle_config))
1213        })
1214    }
1215
1216    pub fn http_config(&self) -> CargoResult<&CargoHttpConfig> {
1217        self.http_config.try_borrow_with(|| {
1218            let mut http = self.get::<CargoHttpConfig>(["http"])?;
1219            let curl_v = curl::Version::get();
1220            disables_multiplexing_for_bad_curl(curl_v.version(), &mut http, self);
1221            Ok(http)
1222        })
1223    }
1224
1225    pub fn future_incompat_config(&self) -> CargoResult<&CargoFutureIncompatConfig> {
1226        self.future_incompat_config
1227            .try_borrow_with(|| self.get::<CargoFutureIncompatConfig>(["future-incompat-report"]))
1228    }
1229
1230    pub fn net_config(&self) -> CargoResult<&CargoNetConfig> {
1231        self.net_config
1232            .try_borrow_with(|| self.get::<CargoNetConfig>(["net"]))
1233    }
1234
1235    pub fn build_config(&self) -> CargoResult<&CargoBuildConfig> {
1236        self.build_config
1237            .try_borrow_with(|| self.get::<CargoBuildConfig>(["build"]))
1238    }
1239
1240    pub fn progress_config(&self) -> &ProgressConfig {
1241        &self.progress_config
1242    }
1243
1244    /// Get the env vars from the config `[env]` table which
1245    /// are `force = true` or don't exist in the env snapshot [`GlobalContext::get_env`].
1246    pub fn env_config(&self) -> CargoResult<&Arc<HashMap<String, OsString>>> {
1247        let env_config = self.env_config.try_borrow_with(|| {
1248            CargoResult::Ok(Arc::new({
1249                let env_config = self.get::<EnvConfig>(["env"])?;
1250                // Reasons for disallowing these values:
1251                //
1252                // - CARGO_HOME: The initial call to cargo does not honor this value
1253                //   from the [env] table. Recursive calls to cargo would use the new
1254                //   value, possibly behaving differently from the outer cargo.
1255                //
1256                // - RUSTUP_HOME and RUSTUP_TOOLCHAIN: Under normal usage with rustup,
1257                //   this will have no effect because the rustup proxy sets
1258                //   RUSTUP_HOME and RUSTUP_TOOLCHAIN, and that would override the
1259                //   [env] table. If the outer cargo is executed directly
1260                //   circumventing the rustup proxy, then this would affect calls to
1261                //   rustc (assuming that is a proxy), which could potentially cause
1262                //   problems with cargo and rustc being from different toolchains. We
1263                //   consider this to be not a use case we would like to support,
1264                //   since it will likely cause problems or lead to confusion.
1265                for disallowed in &["CARGO_HOME", "RUSTUP_HOME", "RUSTUP_TOOLCHAIN"] {
1266                    if env_config.contains_key(*disallowed) {
1267                        bail!(
1268                            "setting the `{disallowed}` environment variable is not supported \
1269                            in the `[env]` configuration table"
1270                        );
1271                    }
1272                }
1273                env_config
1274                    .into_iter()
1275                    .filter_map(|(k, v)| {
1276                        if v.is_force() || self.get_env_os(&k).is_none() {
1277                            Some((k, v.resolve(self.cwd()).to_os_string()))
1278                        } else {
1279                            None
1280                        }
1281                    })
1282                    .collect()
1283            }))
1284        })?;
1285
1286        Ok(env_config)
1287    }
1288
1289    /// This is used to validate the `term` table has valid syntax.
1290    ///
1291    /// This is necessary because loading the term settings happens very
1292    /// early, and in some situations (like `cargo version`) we don't want to
1293    /// fail if there are problems with the config file.
1294    pub fn validate_term_config(&self) -> CargoResult<()> {
1295        drop(self.get::<TermConfig>(["term"])?);
1296        Ok(())
1297    }
1298
1299    /// Returns a list of `target.'cfg()'` tables.
1300    ///
1301    /// The list is sorted by the table name.
1302    pub fn target_cfgs(&self) -> CargoResult<&Vec<(String, TargetCfgConfig)>> {
1303        self.target_cfgs
1304            .try_borrow_with(|| target::load_target_cfgs(self))
1305    }
1306
1307    pub fn doc_extern_map(&self) -> CargoResult<&RustdocExternMap> {
1308        // Note: This does not support environment variables. The `Unit`
1309        // fundamentally does not have access to the registry name, so there is
1310        // nothing to query. Plumbing the name into SourceId is quite challenging.
1311        self.doc_extern_map
1312            .try_borrow_with(|| self.get::<RustdocExternMap>(["doc", "extern-map"]))
1313    }
1314
1315    /// Returns true if the `[target]` table should be applied to host targets.
1316    pub fn target_applies_to_host(&self) -> CargoResult<bool> {
1317        target::get_target_applies_to_host(self)
1318    }
1319
1320    /// Returns the `[host]` table definition for the given target tuple.
1321    pub fn host_cfg_tuple(&self, target: &str) -> CargoResult<TargetConfig> {
1322        target::load_host_tuple(self, target)
1323    }
1324
1325    /// Returns the `[target]` table definition for the given target tuple.
1326    pub fn target_cfg_tuple(&self, target: &str) -> CargoResult<TargetConfig> {
1327        target::load_target_tuple(self, target)
1328    }
1329
1330    /// Returns the cached [`SourceId`] corresponding to the main repository.
1331    ///
1332    /// This is the main cargo registry by default, but it can be overridden in
1333    /// a `.cargo/config.toml`.
1334    pub fn crates_io_source_id(&self) -> CargoResult<SourceId> {
1335        let source_id = self.crates_io_source_id.try_borrow_with(|| {
1336            self.check_registry_index_not_set()?;
1337            let url = CRATES_IO_INDEX.into_url().unwrap();
1338            SourceId::for_alt_registry(&url, CRATES_IO_REGISTRY)
1339        })?;
1340        Ok(*source_id)
1341    }
1342
1343    pub fn invocation_instant(&self) -> Instant {
1344        self.invocation_instant
1345    }
1346
1347    /// Returns the wall-clock time of this cargo invocation.
1348    ///
1349    /// See the [`invocation_time`] field doc for details.
1350    ///
1351    /// [`invocation_time`]: GlobalContext::invocation_time
1352    pub fn invocation_time(&self) -> jiff::Timestamp {
1353        self.invocation_time
1354    }
1355
1356    /// Retrieves a config variable.
1357    ///
1358    /// This supports most serde `Deserialize` types. Examples:
1359    ///
1360    /// ```rust,ignore
1361    /// let v: Option<u32> = config.get(["some", "nested", "key"])?;
1362    /// let v: Option<MyStruct> = config.get(["some", "key"])?;
1363    /// let v: Option<HashMap<String, MyStruct>> = config.get(["foo"])?;
1364    /// ```
1365    ///
1366    /// The key may be a dotted key, but this does NOT support TOML key
1367    /// quoting. Avoid key components that may have dots. For example,
1368    /// `foo.'a.b'.bar" does not work if you try to fetch `foo.'a.b'". You can
1369    /// fetch `foo` if it is a map, though.
1370    pub fn get<'de, T: serde::de::Deserialize<'de>>(
1371        &self,
1372
1373        key: impl IntoIterator<Item = impl AsRef<str>>,
1374    ) -> CargoResult<T> {
1375        self.config_reader()?.get(ConfigKey::from_parts(key))
1376    }
1377
1378    /// Obtain a [`Path`] from a [`Filesystem`], verifying that the
1379    /// appropriate lock is already currently held.
1380    ///
1381    /// Locks are usually acquired via [`GlobalContext::acquire_package_cache_lock`]
1382    /// or [`GlobalContext::try_acquire_package_cache_lock`].
1383    #[track_caller]
1384    #[tracing::instrument(skip_all)]
1385    pub fn assert_package_cache_locked<'a>(
1386        &self,
1387        mode: CacheLockMode,
1388        f: &'a Filesystem,
1389    ) -> &'a Path {
1390        let ret = f.as_path_unlocked();
1391        assert!(
1392            self.package_cache_lock.is_locked(mode),
1393            "package cache lock is not currently held, Cargo forgot to call \
1394             `acquire_package_cache_lock` before we got to this stack frame",
1395        );
1396        assert!(ret.starts_with(self.cargo_home.as_path_unlocked()));
1397        ret
1398    }
1399
1400    /// Acquires a lock on the global "package cache", blocking if another
1401    /// cargo holds the lock.
1402    ///
1403    /// See [`crate::util::cache_lock`] for an in-depth discussion of locking
1404    /// and lock modes.
1405    #[tracing::instrument(skip_all)]
1406    pub fn acquire_package_cache_lock(&self, mode: CacheLockMode) -> CargoResult<CacheLock<'_>> {
1407        self.package_cache_lock.lock(self, mode)
1408    }
1409
1410    /// Acquires a lock on the global "package cache", returning `None` if
1411    /// another cargo holds the lock.
1412    ///
1413    /// See [`crate::util::cache_lock`] for an in-depth discussion of locking
1414    /// and lock modes.
1415    #[tracing::instrument(skip_all)]
1416    pub fn try_acquire_package_cache_lock(
1417        &self,
1418        mode: CacheLockMode,
1419    ) -> CargoResult<Option<CacheLock<'_>>> {
1420        self.package_cache_lock.try_lock(self, mode)
1421    }
1422
1423    /// Returns a reference to the shared [`GlobalCacheTracker`].
1424    ///
1425    /// The package cache lock must be held to call this function (and to use
1426    /// it in general).
1427    pub fn global_cache_tracker(&self) -> CargoResult<MutexGuard<'_, GlobalCacheTracker>> {
1428        let tracker = self.global_cache_tracker.try_borrow_with(|| {
1429            Ok::<_, anyhow::Error>(Mutex::new(GlobalCacheTracker::new(self)?))
1430        })?;
1431        Ok(tracker.lock().unwrap())
1432    }
1433
1434    /// Returns a reference to the shared [`DeferredGlobalLastUse`].
1435    pub fn deferred_global_last_use(&self) -> CargoResult<MutexGuard<'_, DeferredGlobalLastUse>> {
1436        let deferred = self
1437            .deferred_global_last_use
1438            .try_borrow_with(|| Ok::<_, anyhow::Error>(Mutex::new(DeferredGlobalLastUse::new())))?;
1439        Ok(deferred.lock().unwrap())
1440    }
1441
1442    /// Get the global [`WarningHandling`] configuration.
1443    pub fn warning_handling(&self) -> CargoResult<WarningHandling> {
1444        Ok(self.build_config()?.warnings.unwrap_or_default())
1445    }
1446
1447    pub fn ws_roots(&self) -> MutexGuard<'_, HashMap<PathBuf, WorkspaceRootConfig>> {
1448        self.ws_roots.lock().unwrap()
1449    }
1450
1451    /// Mode for matching version requirements
1452    /// against versions already selected / locked.
1453    ///
1454    /// Once stabilized,
1455    /// this always returns [`VersionReqMatchMode::Prerelease`] (or remove and inline).
1456    pub fn version_req_match_mode(&self) -> VersionReqMatchMode {
1457        if self.cli_unstable().prerelease {
1458            VersionReqMatchMode::Prerelease
1459        } else {
1460            VersionReqMatchMode::Default
1461        }
1462    }
1463}
1464
1465fn registry_config_uncached(
1466    gctx: &GlobalContext,
1467    sid: &SourceId,
1468) -> CargoResult<Option<RegistryConfig>> {
1469    tracing::trace!("loading registry config for {}", sid);
1470    if !sid.is_remote_registry() {
1471        bail!(
1472            "{} does not support API commands.\n\
1473             Check for a source-replacement in .cargo/config.",
1474            sid
1475        );
1476    }
1477
1478    // Handle crates.io specially, since it uses different configuration keys.
1479    if sid.is_crates_io() {
1480        gctx.check_registry_index_not_set()?;
1481        return Ok(gctx
1482            .get::<Option<GlobalRegistryConfig>>(["registry"])?
1483            .map(|c| c.to_registry_config()));
1484    }
1485
1486    let name = registry_name(gctx, sid)?;
1487
1488    // It's possible to have a registry configured in a Cargo config file,
1489    // then override it with configuration from environment variables.
1490    // If the name doesn't match, leave a note to help the user understand
1491    // the potentially confusing situation.
1492    if let Some(name) = name.as_deref() {
1493        if Some(name) != sid.alt_registry_key() {
1494            gctx.shell().note(format!(
1495                "name of alternative registry `{}` set to `{name}`",
1496                sid.url()
1497            ))?
1498        }
1499    }
1500
1501    if let Some(name) = &name {
1502        tracing::debug!("found alternative registry name `{name}` for {sid}");
1503        gctx.get::<Option<RegistryConfig>>(["registries", name.as_str()])
1504    } else {
1505        tracing::debug!("no registry name found for {sid}");
1506        Ok(None)
1507    }
1508}
1509
1510fn registry_name(gctx: &GlobalContext, sid: &SourceId) -> CargoResult<Option<String>> {
1511    // Find the SourceId's name by its index URL. If environment variables
1512    // are available they will be preferred over configuration values.
1513    //
1514    // The fundamental problem is that we only know the index url of the registry
1515    // for certain. For example, an unnamed registry source can come from the `--index`
1516    // command line argument, or from a Cargo.lock file. For this reason, we always
1517    // attempt to discover the name by looking it up by the index URL.
1518    //
1519    // This also allows the authorization token for a registry to be set
1520    // without knowing the registry name by using the _INDEX and _TOKEN
1521    // environment variables.
1522
1523    let name = {
1524        // Discover names from environment variables.
1525        let index = sid.canonical_url();
1526        let mut names: Vec<_> = gctx
1527            .env()
1528            .filter_map(|(k, v)| {
1529                Some((
1530                    k.strip_prefix("CARGO_REGISTRIES_")?
1531                        .strip_suffix("_INDEX")?,
1532                    v,
1533                ))
1534            })
1535            .filter_map(|(k, v)| Some((k, CanonicalUrl::new(&v.into_url().ok()?).ok()?)))
1536            .filter(|(_, v)| v == index)
1537            .map(|(k, _)| k.to_lowercase())
1538            .collect();
1539
1540        // Discover names from the configuration only if none were found in the environment.
1541        if names.len() == 0 {
1542            if let Some(registries) = gctx.config()?.values().get("registries") {
1543                let (registries, _) = registries.table("registries")?;
1544                for (name, value) in registries {
1545                    if let Some(v) = value.table(&format!("registries.{name}"))?.0.get("index") {
1546                        let (v, _) = v.string(&format!("registries.{name}.index"))?;
1547                        if index == &CanonicalUrl::new(&v.into_url()?)? {
1548                            names.push(name.clone());
1549                        }
1550                    }
1551                }
1552            }
1553        }
1554        names.sort();
1555        match names.len() {
1556            0 => None,
1557            1 => Some(std::mem::take(&mut names[0])),
1558            _ => anyhow::bail!(
1559                "multiple registries are configured with the same index url '{}': {}",
1560                &sid.as_url(),
1561                names.join(", ")
1562            ),
1563        }
1564    };
1565
1566    Ok(name)
1567}
1568
1569pub fn cargo_home(cwd: &Path) -> CargoResult<PathBuf> {
1570    let cargo_home = ::home::cargo_home_with_cwd(cwd).map_err(|_| {
1571        anyhow!(
1572            "Cargo couldn't find your home directory. \
1573             This probably means that $HOME was not set."
1574        )
1575    })?;
1576    // https://github.com/rust-lang/cargo/issues/15981
1577    // This is so everything shares one spelling and
1578    // isn't incorrectly seen as distinct.
1579    Ok(paths::normalize_path(&cargo_home))
1580}
1581
1582pub fn save_credentials(
1583    gctx: &GlobalContext,
1584    token: Option<RegistryCredentialConfig>,
1585    registry: &SourceId,
1586) -> CargoResult<()> {
1587    let registry = if registry.is_crates_io() {
1588        None
1589    } else {
1590        let name = registry
1591            .alt_registry_key()
1592            .ok_or_else(|| internal("can't save credentials for anonymous registry"))?;
1593        Some(name)
1594    };
1595
1596    // If 'credentials' exists, write to that for backward compatibility reasons.
1597    // Otherwise write to 'credentials.toml'. There's no need to print the
1598    // warning here, because it would already be printed at load time.
1599    let cargo_home = gctx.cargo_home.clone().into_path_unlocked();
1600    let filename = match gctx
1601        .config_loader()
1602        .get_file_path(&cargo_home, "credentials", false)?
1603    {
1604        Some(path) => match path.file_name() {
1605            Some(filename) => Path::new(filename).to_owned(),
1606            None => Path::new("credentials.toml").to_owned(),
1607        },
1608        None => Path::new("credentials.toml").to_owned(),
1609    };
1610
1611    let mut file = {
1612        gctx.cargo_home.create_dir()?;
1613        gctx.cargo_home
1614            .open_rw_exclusive_create(filename, gctx, "credentials' config file")?
1615    };
1616
1617    let mut contents = String::new();
1618    file.read_to_string(&mut contents).with_context(|| {
1619        format!(
1620            "failed to read configuration file `{}`",
1621            file.path().display()
1622        )
1623    })?;
1624
1625    let mut toml = contents.parse::<toml::Table>()?;
1626
1627    // Move the old token location to the new one.
1628    if let Some(token) = toml.remove("token") {
1629        #[expect(
1630            clippy::disallowed_types,
1631            reason = "need stdlib's HashMap because of TOML compatibility"
1632        )]
1633        let map = std::collections::HashMap::from([("token".to_string(), token)]);
1634        toml.insert("registry".into(), map.into());
1635    }
1636
1637    if let Some(token) = token {
1638        // login
1639
1640        let path_def = Definition::path(file.path().to_path_buf());
1641        let (key, mut value) = match token {
1642            RegistryCredentialConfig::Token(token) => {
1643                // login with token
1644
1645                let key = "token".to_string();
1646                let value = ConfigValue::String(token.expose(), path_def.clone());
1647                let map = HashMap::from_iter([(key, value)]);
1648                let table = CV::Table(map, path_def.clone());
1649
1650                if let Some(registry) = registry {
1651                    let map = HashMap::from_iter([(registry.to_string(), table)]);
1652                    ("registries".into(), CV::Table(map, path_def.clone()))
1653                } else {
1654                    ("registry".into(), table)
1655                }
1656            }
1657            _ => unreachable!(),
1658        };
1659
1660        if registry.is_some() {
1661            if let Some(table) = toml.remove("registries") {
1662                let v = CV::from_toml(path_def, table)?;
1663                value.merge(v)?;
1664            }
1665        }
1666        toml.insert(key, value.into_toml());
1667    } else {
1668        // logout
1669        if let Some(registry) = registry {
1670            if let Some(registries) = toml.get_mut("registries") {
1671                if let Some(reg) = registries.get_mut(registry) {
1672                    let rtable = reg.as_table_mut().ok_or_else(|| {
1673                        format_err!("expected `[registries.{}]` to be a table", registry)
1674                    })?;
1675                    rtable.remove("token");
1676                }
1677            }
1678        } else if let Some(registry) = toml.get_mut("registry") {
1679            let reg_table = registry
1680                .as_table_mut()
1681                .ok_or_else(|| format_err!("expected `[registry]` to be a table"))?;
1682            reg_table.remove("token");
1683        }
1684    }
1685
1686    let contents = toml.to_string();
1687    file.seek(SeekFrom::Start(0))?;
1688    file.write_all(contents.as_bytes())
1689        .with_context(|| format!("failed to write to `{}`", file.path().display()))?;
1690    file.file().set_len(contents.len() as u64)?;
1691    set_permissions(file.file(), 0o600)
1692        .with_context(|| format!("failed to set permissions of `{}`", file.path().display()))?;
1693
1694    return Ok(());
1695
1696    #[cfg(unix)]
1697    fn set_permissions(file: &File, mode: u32) -> CargoResult<()> {
1698        use std::os::unix::fs::PermissionsExt;
1699
1700        let mut perms = file.metadata()?.permissions();
1701        perms.set_mode(mode);
1702        file.set_permissions(perms)?;
1703        Ok(())
1704    }
1705
1706    #[cfg(not(unix))]
1707    fn set_permissions(_file: &File, _mode: u32) -> CargoResult<()> {
1708        Ok(())
1709    }
1710}
1711
1712#[macro_export]
1713macro_rules! __shell_print {
1714    ($config:expr, $which:ident, $newline:literal, $($arg:tt)*) => ({
1715        let mut shell = $config.shell();
1716        let out = shell.$which();
1717        drop(out.write_fmt(format_args!($($arg)*)));
1718        if $newline {
1719            drop(out.write_all(b"\n"));
1720        }
1721    });
1722}
1723
1724#[macro_export]
1725macro_rules! drop_println {
1726    ($config:expr) => ( $crate::drop_print!($config, "\n") );
1727    ($config:expr, $($arg:tt)*) => (
1728        $crate::__shell_print!($config, out, true, $($arg)*)
1729    );
1730}
1731
1732#[macro_export]
1733macro_rules! drop_eprintln {
1734    ($config:expr) => ( $crate::drop_eprint!($config, "\n") );
1735    ($config:expr, $($arg:tt)*) => (
1736        $crate::__shell_print!($config, err, true, $($arg)*)
1737    );
1738}
1739
1740#[macro_export]
1741macro_rules! drop_print {
1742    ($config:expr, $($arg:tt)*) => (
1743        $crate::__shell_print!($config, out, false, $($arg)*)
1744    );
1745}
1746
1747#[macro_export]
1748macro_rules! drop_eprint {
1749    ($config:expr, $($arg:tt)*) => (
1750        $crate::__shell_print!($config, err, false, $($arg)*)
1751    );
1752}
1753
1754enum Tool {
1755    Rustc,
1756    Rustdoc,
1757}
1758
1759impl Tool {
1760    fn as_str(&self) -> &str {
1761        match self {
1762            Tool::Rustc => "rustc",
1763            Tool::Rustdoc => "rustdoc",
1764        }
1765    }
1766}
1767
1768/// Disable HTTP/2 multiplexing for some broken versions of libcurl.
1769///
1770/// In certain versions of libcurl when proxy is in use with HTTP/2
1771/// multiplexing, connections will continue stacking up. This was
1772/// fixed in libcurl 8.0.0 in curl/curl@821f6e2a89de8aec1c7da3c0f381b92b2b801efc
1773///
1774/// However, Cargo can still link against old system libcurl if it is from a
1775/// custom built one or on macOS. For those cases, multiplexing needs to be
1776/// disabled when those versions are detected.
1777fn disables_multiplexing_for_bad_curl(
1778    curl_version: &str,
1779    http: &mut CargoHttpConfig,
1780    gctx: &GlobalContext,
1781) {
1782    use crate::util::network;
1783
1784    if network::proxy::http_proxy_exists(http, gctx) && http.multiplexing.is_none() {
1785        let bad_curl_versions = ["7.87.0", "7.88.0", "7.88.1"];
1786        if bad_curl_versions
1787            .iter()
1788            .any(|v| curl_version.starts_with(v))
1789        {
1790            tracing::info!("disabling multiplexing with proxy, curl version is {curl_version}");
1791            http.multiplexing = Some(false);
1792        }
1793    }
1794}
1795
1796#[cfg(test)]
1797mod tests {
1798    use super::CargoHttpConfig;
1799    use super::GlobalContext;
1800    use super::Shell;
1801    use super::disables_multiplexing_for_bad_curl;
1802
1803    #[test]
1804    fn disables_multiplexing() {
1805        let mut gctx = GlobalContext::new(Shell::new(), "".into(), "".into());
1806        gctx.set_search_stop_path(std::path::PathBuf::new());
1807        gctx.set_env(Default::default());
1808
1809        let mut http = CargoHttpConfig::default();
1810        http.proxy = Some("127.0.0.1:3128".into());
1811        disables_multiplexing_for_bad_curl("7.88.1", &mut http, &gctx);
1812        assert_eq!(http.multiplexing, Some(false));
1813
1814        let cases = [
1815            (None, None, "7.87.0", None),
1816            (None, None, "7.88.0", None),
1817            (None, None, "7.88.1", None),
1818            (None, None, "8.0.0", None),
1819            (Some("".into()), None, "7.87.0", Some(false)),
1820            (Some("".into()), None, "7.88.0", Some(false)),
1821            (Some("".into()), None, "7.88.1", Some(false)),
1822            (Some("".into()), None, "8.0.0", None),
1823            (Some("".into()), Some(false), "7.87.0", Some(false)),
1824            (Some("".into()), Some(false), "7.88.0", Some(false)),
1825            (Some("".into()), Some(false), "7.88.1", Some(false)),
1826            (Some("".into()), Some(false), "8.0.0", Some(false)),
1827        ];
1828
1829        for (proxy, multiplexing, curl_v, result) in cases {
1830            let mut http = CargoHttpConfig {
1831                multiplexing,
1832                proxy,
1833                ..Default::default()
1834            };
1835            disables_multiplexing_for_bad_curl(curl_v, &mut http, &gctx);
1836            assert_eq!(http.multiplexing, result);
1837        }
1838    }
1839
1840    #[test]
1841    fn sync_context() {
1842        fn assert_sync<S: Sync>() {}
1843        assert_sync::<GlobalContext>();
1844    }
1845}