]> git.proxmox.com Git - cargo.git/blob - src/bin/cargo/main.rs
0ec0cc1f6ad79fb719a8b15ac7cf191b71822909
[cargo.git] / src / bin / cargo / main.rs
1 #![warn(rust_2018_idioms)] // while we're getting used to 2018
2 #![allow(clippy::all)]
3
4 use cargo::util::toml::StringOrVec;
5 use cargo::util::CliError;
6 use cargo::util::{self, closest_msg, command_prelude, CargoResult, CliResult, Config};
7 use cargo_util::{ProcessBuilder, ProcessError};
8 use std::collections::BTreeMap;
9 use std::env;
10 use std::fs;
11 use std::path::{Path, PathBuf};
12
13 mod cli;
14 mod commands;
15
16 use crate::command_prelude::*;
17
18 fn main() {
19 #[cfg(feature = "pretty-env-logger")]
20 pretty_env_logger::init_custom_env("CARGO_LOG");
21 #[cfg(not(feature = "pretty-env-logger"))]
22 env_logger::init_from_env("CARGO_LOG");
23
24 let mut config = cli::LazyConfig::new();
25
26 let result = if let Some(lock_addr) = cargo::ops::fix_get_proxy_lock_addr() {
27 cargo::ops::fix_exec_rustc(config.get(), &lock_addr).map_err(|e| CliError::from(e))
28 } else {
29 let _token = cargo::util::job::setup();
30 cli::main(&mut config)
31 };
32
33 match result {
34 Err(e) => cargo::exit_with_error(e, &mut config.get_mut().shell()),
35 Ok(()) => {}
36 }
37 }
38
39 /// Table for defining the aliases which come builtin in `Cargo`.
40 /// The contents are structured as: `(alias, aliased_command, description)`.
41 const BUILTIN_ALIASES: [(&str, &str, &str); 5] = [
42 ("b", "build", "alias: build"),
43 ("c", "check", "alias: check"),
44 ("d", "doc", "alias: doc"),
45 ("r", "run", "alias: run"),
46 ("t", "test", "alias: test"),
47 ];
48
49 /// Function which contains the list of all of the builtin aliases and it's
50 /// corresponding execs represented as &str.
51 fn builtin_aliases_execs(cmd: &str) -> Option<&(&str, &str, &str)> {
52 BUILTIN_ALIASES.iter().find(|alias| alias.0 == cmd)
53 }
54
55 fn aliased_command(config: &Config, command: &str) -> CargoResult<Option<Vec<String>>> {
56 let alias_name = format!("alias.{}", command);
57 let user_alias = match config.get_string(&alias_name) {
58 Ok(Some(record)) => Some(
59 record
60 .val
61 .split_whitespace()
62 .map(|s| s.to_string())
63 .collect(),
64 ),
65 Ok(None) => None,
66 Err(_) => config.get::<Option<Vec<String>>>(&alias_name)?,
67 };
68
69 let result = user_alias.or_else(|| {
70 builtin_aliases_execs(command).map(|command_str| vec![command_str.1.to_string()])
71 });
72 Ok(result)
73 }
74
75 /// List all runnable commands
76 fn list_commands(config: &Config) -> BTreeMap<String, CommandInfo> {
77 let prefix = "cargo-";
78 let suffix = env::consts::EXE_SUFFIX;
79 let mut commands = BTreeMap::new();
80 for dir in search_directories(config) {
81 let entries = match fs::read_dir(dir) {
82 Ok(entries) => entries,
83 _ => continue,
84 };
85 for entry in entries.filter_map(|e| e.ok()) {
86 let path = entry.path();
87 let filename = match path.file_name().and_then(|s| s.to_str()) {
88 Some(filename) => filename,
89 _ => continue,
90 };
91 if !filename.starts_with(prefix) || !filename.ends_with(suffix) {
92 continue;
93 }
94 if is_executable(entry.path()) {
95 let end = filename.len() - suffix.len();
96 commands.insert(
97 filename[prefix.len()..end].to_string(),
98 CommandInfo::External { path: path.clone() },
99 );
100 }
101 }
102 }
103
104 for cmd in commands::builtin() {
105 commands.insert(
106 cmd.get_name().to_string(),
107 CommandInfo::BuiltIn {
108 about: cmd.get_about().map(|s| s.to_string()),
109 },
110 );
111 }
112
113 // Add the builtin_aliases and them descriptions to the
114 // `commands` `BTreeMap`.
115 for command in &BUILTIN_ALIASES {
116 commands.insert(
117 command.0.to_string(),
118 CommandInfo::BuiltIn {
119 about: Some(command.2.to_string()),
120 },
121 );
122 }
123
124 // Add the user-defined aliases
125 if let Ok(aliases) = config.get::<BTreeMap<String, StringOrVec>>("alias") {
126 for (name, target) in aliases.iter() {
127 commands.insert(
128 name.to_string(),
129 CommandInfo::Alias {
130 target: target.clone(),
131 },
132 );
133 }
134 }
135
136 // `help` is special, so it needs to be inserted separately.
137 commands.insert(
138 "help".to_string(),
139 CommandInfo::BuiltIn {
140 about: Some("Displays help for a cargo subcommand".to_string()),
141 },
142 );
143
144 commands
145 }
146
147 fn find_external_subcommand(config: &Config, cmd: &str) -> Option<PathBuf> {
148 let command_exe = format!("cargo-{}{}", cmd, env::consts::EXE_SUFFIX);
149 search_directories(config)
150 .iter()
151 .map(|dir| dir.join(&command_exe))
152 .find(|file| is_executable(file))
153 }
154
155 fn execute_external_subcommand(config: &Config, cmd: &str, args: &[&str]) -> CliResult {
156 let path = find_external_subcommand(config, cmd);
157 let command = match path {
158 Some(command) => command,
159 None => {
160 let err = if cmd.starts_with('+') {
161 anyhow::format_err!(
162 "no such subcommand: `{}`\n\n\t\
163 Cargo does not handle `+toolchain` directives.\n\t\
164 Did you mean to invoke `cargo` through `rustup` instead?",
165 cmd
166 )
167 } else {
168 let suggestions = list_commands(config);
169 let did_you_mean = closest_msg(cmd, suggestions.keys(), |c| c);
170
171 anyhow::format_err!(
172 "no such subcommand: `{}`{}\n\n\t\
173 View all installed commands with `cargo --list`",
174 cmd,
175 did_you_mean
176 )
177 };
178
179 return Err(CliError::new(err, 101));
180 }
181 };
182
183 let cargo_exe = config.cargo_exe()?;
184 let mut cmd = ProcessBuilder::new(&command);
185 cmd.env(cargo::CARGO_ENV, cargo_exe).args(args);
186 if let Some(client) = config.jobserver_from_env() {
187 cmd.inherit_jobserver(client);
188 }
189 let err = match cmd.exec_replace() {
190 Ok(()) => return Ok(()),
191 Err(e) => e,
192 };
193
194 if let Some(perr) = err.downcast_ref::<ProcessError>() {
195 if let Some(code) = perr.code {
196 return Err(CliError::code(code));
197 }
198 }
199 Err(CliError::new(err, 101))
200 }
201
202 #[cfg(unix)]
203 fn is_executable<P: AsRef<Path>>(path: P) -> bool {
204 use std::os::unix::prelude::*;
205 fs::metadata(path)
206 .map(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
207 .unwrap_or(false)
208 }
209 #[cfg(windows)]
210 fn is_executable<P: AsRef<Path>>(path: P) -> bool {
211 path.as_ref().is_file()
212 }
213
214 fn search_directories(config: &Config) -> Vec<PathBuf> {
215 let mut dirs = vec![config.home().clone().into_path_unlocked().join("bin")];
216 if let Some(val) = env::var_os("PATH") {
217 dirs.extend(env::split_paths(&val));
218 }
219 dirs
220 }
221
222 fn init_git_transports(config: &Config) {
223 // Only use a custom transport if any HTTP options are specified,
224 // such as proxies or custom certificate authorities. The custom
225 // transport, however, is not as well battle-tested.
226
227 match cargo::ops::needs_custom_http_transport(config) {
228 Ok(true) => {}
229 _ => return,
230 }
231
232 let handle = match cargo::ops::http_handle(config) {
233 Ok(handle) => handle,
234 Err(..) => return,
235 };
236
237 // The unsafety of the registration function derives from two aspects:
238 //
239 // 1. This call must be synchronized with all other registration calls as
240 // well as construction of new transports.
241 // 2. The argument is leaked.
242 //
243 // We're clear on point (1) because this is only called at the start of this
244 // binary (we know what the state of the world looks like) and we're mostly
245 // clear on point (2) because we'd only free it after everything is done
246 // anyway
247 unsafe {
248 git2_curl::register(handle);
249 }
250
251 // Disabling the owner validation in git can, in theory, lead to code execution
252 // vulnerabilities. However, libgit2 does not launch executables, which is the foundation of
253 // the original security issue. Meanwhile, issues with refusing to load git repos in
254 // `CARGO_HOME` for example will likely be very frustrating for users. So, we disable the
255 // validation.
256 //
257 // For further discussion of Cargo's current interactions with git, see
258 //
259 // https://github.com/rust-lang/rfcs/pull/3279
260 //
261 // and in particular the subsection on "Git support".
262 //
263 // Note that we only disable this when Cargo is run as a binary. If Cargo is used as a library,
264 // this code won't be invoked. Instead, developers will need to explicitly disable the
265 // validation in their code. This is inconvenient, but won't accidentally open consuming
266 // applications up to security issues if they use git2 to open repositories elsewhere in their
267 // code.
268 unsafe {
269 if git2::opts::set_verify_owner_validation(false).is_err() {
270 return;
271 }
272 }
273 }