Skip to main content

cargo/sources/git/
libgit2.rs

1//! Git operations through libgit2.
2
3use crate::sources::git::utils::note_github_pull_request;
4use crate::sources::git::utils::reinitialize;
5use crate::util::GlobalContext;
6use crate::util::HumanBytes;
7use crate::util::MetricsCounter;
8use crate::util::Progress;
9use crate::util::errors::CargoResult;
10use crate::util::network;
11use crate::util::network::http::http_handle;
12use crate::util::network::http::needs_custom_http_transport;
13
14use git2::ErrorClass;
15use tracing::debug;
16use url::Url;
17
18use std::sync::Once;
19use std::time::{Duration, Instant};
20
21/// Prepare the authentication callbacks for cloning a git repository.
22///
23/// The main purpose of this function is to construct the "authentication
24/// callback" which is used to clone a repository. This callback will attempt to
25/// find the right authentication on the system (without user input) and will
26/// guide libgit2 in doing so.
27///
28/// The callback is provided `allowed` types of credentials, and we try to do as
29/// much as possible based on that:
30///
31/// * Prioritize SSH keys from the local ssh agent as they're likely the most
32///   reliable. The username here is prioritized from the credential
33///   callback, then from whatever is configured in git itself, and finally
34///   we fall back to the generic user of `git`.
35///
36/// * If a username/password is allowed, then we fallback to git2-rs's
37///   implementation of the credential helper. This is what is configured
38///   with `credential.helper` in git, and is the interface for the macOS
39///   keychain, for example.
40///
41/// * After the above two have failed, we just kinda grapple attempting to
42///   return *something*.
43///
44/// If any form of authentication fails, libgit2 will repeatedly ask us for
45/// credentials until we give it a reason to not do so. To ensure we don't
46/// just sit here looping forever we keep track of authentications we've
47/// attempted and we don't try the same ones again.
48fn with_authentication<T, F>(
49    gctx: &GlobalContext,
50    url: &str,
51    cfg: &git2::Config,
52    mut f: F,
53) -> CargoResult<T>
54where
55    F: FnMut(&mut git2::Credentials<'_>) -> CargoResult<T>,
56{
57    let mut cred_helper = git2::CredentialHelper::new(url);
58    cred_helper.config(cfg);
59
60    let mut ssh_username_requested = false;
61    let mut cred_helper_bad = None;
62    let mut ssh_agent_attempts = Vec::new();
63    let mut any_attempts = false;
64    let mut tried_sshkey = false;
65    let mut url_attempt = None;
66
67    let orig_url = url;
68    let mut res = f(&mut |url, username, allowed| {
69        any_attempts = true;
70        if url != orig_url {
71            url_attempt = Some(url.to_string());
72        }
73        // libgit2's "USERNAME" authentication actually means that it's just
74        // asking us for a username to keep going. This is currently only really
75        // used for SSH authentication and isn't really an authentication type.
76        // The logic currently looks like:
77        //
78        //      let user = ...;
79        //      if (user.is_null())
80        //          user = callback(USERNAME, null, ...);
81        //
82        //      callback(SSH_KEY, user, ...)
83        //
84        // So if we're being called here then we know that (a) we're using ssh
85        // authentication and (b) no username was specified in the URL that
86        // we're trying to clone. We need to guess an appropriate username here,
87        // but that may involve a few attempts. Unfortunately we can't switch
88        // usernames during one authentication session with libgit2, so to
89        // handle this we bail out of this authentication session after setting
90        // the flag `ssh_username_requested`, and then we handle this below.
91        if allowed.contains(git2::CredentialType::USERNAME) {
92            debug_assert!(username.is_none());
93            ssh_username_requested = true;
94            return Err(git2::Error::from_str("gonna try usernames later"));
95        }
96
97        // An "SSH_KEY" authentication indicates that we need some sort of SSH
98        // authentication. This can currently either come from the ssh-agent
99        // process or from a raw in-memory SSH key. Cargo only supports using
100        // ssh-agent currently.
101        //
102        // If we get called with this then the only way that should be possible
103        // is if a username is specified in the URL itself (e.g., `username` is
104        // Some), hence the unwrap() here. We try custom usernames down below.
105        if allowed.contains(git2::CredentialType::SSH_KEY) && !tried_sshkey {
106            // If ssh-agent authentication fails, libgit2 will keep
107            // calling this callback asking for other authentication
108            // methods to try. Make sure we only try ssh-agent once,
109            // to avoid looping forever.
110            tried_sshkey = true;
111            let username = username.unwrap();
112            debug_assert!(!ssh_username_requested);
113            ssh_agent_attempts.push(username.to_string());
114            return git2::Cred::ssh_key_from_agent(username);
115        }
116
117        // Sometimes libgit2 will ask for a username/password in plaintext. This
118        // is where Cargo would have an interactive prompt if we supported it,
119        // but we currently don't! Right now the only way we support fetching a
120        // plaintext password is through the `credential.helper` support, so
121        // fetch that here.
122        //
123        // If ssh-agent authentication fails, libgit2 will keep calling this
124        // callback asking for other authentication methods to try. Check
125        // cred_helper_bad to make sure we only try the git credential helper
126        // once, to avoid looping forever.
127        if allowed.contains(git2::CredentialType::USER_PASS_PLAINTEXT) && cred_helper_bad.is_none()
128        {
129            let r = git2::Cred::credential_helper(cfg, url, username);
130            cred_helper_bad = Some(r.is_err());
131            return r;
132        }
133
134        // I'm... not sure what the DEFAULT kind of authentication is, but seems
135        // easy to support?
136        if allowed.contains(git2::CredentialType::DEFAULT) {
137            return git2::Cred::default();
138        }
139
140        // Whelp, we tried our best
141        Err(git2::Error::from_str("no authentication methods succeeded"))
142    });
143
144    // Ok, so if it looks like we're going to be doing ssh authentication, we
145    // want to try a few different usernames as one wasn't specified in the URL
146    // for us to use. In order, we'll try:
147    //
148    // * A credential helper's username for this URL, if available.
149    // * This account's username.
150    // * "git"
151    //
152    // We have to restart the authentication session each time (due to
153    // constraints in libssh2 I guess? maybe this is inherent to ssh?), so we
154    // call our callback, `f`, in a loop here.
155    if ssh_username_requested {
156        debug_assert!(res.is_err());
157        let mut attempts = vec![String::from("git")];
158        if let Ok(s) = gctx.get_env("USER").or_else(|_| gctx.get_env("USERNAME")) {
159            attempts.push(s.to_string());
160        }
161        if let Some(ref s) = cred_helper.username {
162            attempts.push(s.clone());
163        }
164
165        while let Some(s) = attempts.pop() {
166            // We should get `USERNAME` first, where we just return our attempt,
167            // and then after that we should get `SSH_KEY`. If the first attempt
168            // fails we'll get called again, but we don't have another option so
169            // we bail out.
170            let mut attempts = 0;
171            res = f(&mut |_url, username, allowed| {
172                if allowed.contains(git2::CredentialType::USERNAME) {
173                    return git2::Cred::username(&s);
174                }
175                if allowed.contains(git2::CredentialType::SSH_KEY) {
176                    debug_assert_eq!(Some(&s[..]), username);
177                    attempts += 1;
178                    if attempts == 1 {
179                        ssh_agent_attempts.push(s.to_string());
180                        return git2::Cred::ssh_key_from_agent(&s);
181                    }
182                }
183                Err(git2::Error::from_str("no authentication methods succeeded"))
184            });
185
186            // If we made two attempts then that means:
187            //
188            // 1. A username was requested, we returned `s`.
189            // 2. An ssh key was requested, we returned to look up `s` in the
190            //    ssh agent.
191            // 3. For whatever reason that lookup failed, so we were asked again
192            //    for another mode of authentication.
193            //
194            // Essentially, if `attempts == 2` then in theory the only error was
195            // that this username failed to authenticate (e.g., no other network
196            // errors happened). Otherwise something else is funny so we bail
197            // out.
198            if attempts != 2 {
199                break;
200            }
201        }
202    }
203    let mut err = match res {
204        Ok(e) => return Ok(e),
205        Err(e) => e,
206    };
207
208    // In the case of an authentication failure (where we tried something) then
209    // we try to give a more helpful error message about precisely what we
210    // tried.
211    if any_attempts {
212        let mut msg = "failed to authenticate when downloading \
213                       repository"
214            .to_string();
215
216        if let Some(attempt) = &url_attempt {
217            if url != attempt {
218                msg.push_str(": ");
219                msg.push_str(attempt);
220            }
221        }
222        msg.push('\n');
223        if !ssh_agent_attempts.is_empty() {
224            let names = ssh_agent_attempts
225                .iter()
226                .map(|s| format!("`{}`", s))
227                .collect::<Vec<_>>()
228                .join(", ");
229            msg.push_str(&format!(
230                "\n* attempted ssh-agent authentication, but \
231                 no usernames succeeded: {}",
232                names
233            ));
234        }
235        if let Some(failed_cred_helper) = cred_helper_bad {
236            if failed_cred_helper {
237                msg.push_str(
238                    "\n* attempted to find username/password via \
239                     git's `credential.helper` support, but failed",
240                );
241            } else {
242                msg.push_str(
243                    "\n* attempted to find username/password via \
244                     `credential.helper`, but maybe the found \
245                     credentials were incorrect",
246                );
247            }
248        }
249        msg.push_str("\n\n");
250        msg.push_str("if the git CLI succeeds then `net.git-fetch-with-cli` may help here\n");
251        msg.push_str("https://doc.rust-lang.org/cargo/reference/config.html#netgit-fetch-with-cli");
252        err = err.context(msg);
253
254        // Otherwise if we didn't even get to the authentication phase them we may
255        // have failed to set up a connection, in these cases hint on the
256        // `net.git-fetch-with-cli` configuration option.
257    } else if let Some(e) = err.downcast_ref::<git2::Error>() {
258        match e.class() {
259            ErrorClass::Net
260            | ErrorClass::Ssl
261            | ErrorClass::Submodule
262            | ErrorClass::FetchHead
263            | ErrorClass::Ssh
264            | ErrorClass::Http => {
265                let msg = format!(
266                    concat!(
267                        "network failure seems to have happened\n",
268                        "if a proxy or similar is necessary `net.git-fetch-with-cli` may help here\n",
269                        "https://doc.rust-lang.org/cargo/reference/config.html#netgit-fetch-with-cli",
270                        "{}"
271                    ),
272                    note_github_pull_request(url).unwrap_or_default()
273                );
274                err = err.context(msg);
275            }
276            ErrorClass::Callback => {
277                // This unwraps the git2 error. We're using the callback error
278                // specifically to convey errors from Rust land through the C
279                // callback interface. We don't need the `; class=Callback
280                // (26)` that gets tacked on to the git2 error message.
281                err = anyhow::format_err!("{}", e.message());
282            }
283            _ => {}
284        }
285    }
286
287    Err(err)
288}
289
290/// Prepares the callbacks for fetching a git repository.
291///
292/// The main purpose of this function is to construct everything before a fetch.
293/// This will attempt to setup a progress bar, the authentication for git,
294/// ssh known hosts check, and the network retry mechanism.
295///
296/// The callback is provided a fetch options, which can be used by the actual
297/// git fetch.
298pub(super) fn with_fetch_options(
299    git_config: &git2::Config,
300    url: &str,
301    gctx: &GlobalContext,
302    cb: &mut dyn FnMut(git2::FetchOptions<'_>) -> CargoResult<()>,
303) -> CargoResult<()> {
304    let mut progress = Progress::new("Fetch", gctx);
305    let ssh_config = gctx.net_config()?.ssh.as_ref();
306    let config_known_hosts = ssh_config.and_then(|ssh| ssh.known_hosts.as_ref());
307    let diagnostic_home_config = gctx.diagnostic_home_config();
308    network::retry::with_retry(gctx, || {
309        // Hack: libgit2 disallows overriding the error from check_cb since v1.8.0,
310        // so we store the error additionally and unwrap it later
311        let mut check_cb_result = Ok(());
312        let auth_result = with_authentication(gctx, url, git_config, |f| {
313            let port = Url::parse(url).ok().and_then(|url| url.port());
314            let mut last_update = Instant::now();
315            let mut rcb = git2::RemoteCallbacks::new();
316            // We choose `N=10` here to make a `300ms * 10slots ~= 3000ms`
317            // sliding window for tracking the data transfer rate (in bytes/s).
318            let mut counter = MetricsCounter::<10>::new(0, last_update);
319            rcb.credentials(f);
320            rcb.certificate_check(|cert, host| {
321                match super::known_hosts::certificate_check(
322                    gctx,
323                    cert,
324                    host,
325                    port,
326                    config_known_hosts,
327                    &diagnostic_home_config,
328                ) {
329                    Ok(status) => Ok(status),
330                    Err(e) => {
331                        check_cb_result = Err(e);
332                        // This is not really used because it'll be overridden by libgit2
333                        // See https://github.com/libgit2/libgit2/commit/9a9f220119d9647a352867b24b0556195cb26548
334                        Err(git2::Error::from_str(
335                            "invalid or unknown remote ssh hostkey",
336                        ))
337                    }
338                }
339            });
340            rcb.transfer_progress(|stats| {
341                let indexed_deltas = stats.indexed_deltas();
342                let msg = if indexed_deltas > 0 {
343                    // Resolving deltas.
344                    format!(
345                        ", ({}/{}) resolving deltas",
346                        indexed_deltas,
347                        stats.total_deltas()
348                    )
349                } else {
350                    // Receiving objects.
351                    //
352                    // # Caveat
353                    //
354                    // Progress bar relies on git2 calling `transfer_progress`
355                    // to update its transfer rate, but we cannot guarantee a
356                    // periodic call of that callback. Thus if we don't receive
357                    // any data for, say, 10 seconds, the rate will get stuck
358                    // and never go down to 0B/s.
359                    // In the future, we need to find away to update the rate
360                    // even when the callback is not called.
361                    let now = Instant::now();
362                    // Scrape a `received_bytes` to the counter every 300ms.
363                    if now - last_update > Duration::from_millis(300) {
364                        counter.add(stats.received_bytes(), now);
365                        last_update = now;
366                    }
367                    let rate = HumanBytes(counter.rate() as u64);
368                    format!(", {rate:.2}/s")
369                };
370                progress
371                    .tick(stats.indexed_objects(), stats.total_objects(), &msg)
372                    .is_ok()
373            });
374
375            // Create a local anonymous remote in the repository to fetch the
376            // url
377            let mut opts = git2::FetchOptions::new();
378            opts.remote_callbacks(rcb);
379            cb(opts)
380        });
381        if auth_result.is_err() {
382            check_cb_result?;
383        }
384        auth_result?;
385        Ok(())
386    })
387}
388
389#[tracing::instrument(skip(repo, gctx))]
390pub(super) fn fetch_with_libgit2(
391    repo: &mut git2::Repository,
392    remote_url: &str,
393    refspecs: Vec<String>,
394    tags: bool,
395    shallow: gix::remote::fetch::Shallow,
396    gctx: &GlobalContext,
397) -> CargoResult<()> {
398    debug!(target: "git-fetch", backend = "libgit2");
399
400    static INIT: Once = Once::new();
401    INIT.call_once(|| {
402        // SAFETY:
403        //
404        // The unsafety of the registration function derives from two aspects:
405        //
406        // 1. This call must be synchronized with all other registration calls as
407        //    well as construction of new transports.
408        // 2. The argument is leaked.
409        //
410        // We're clear on point (1) because this is the only `register` call we make in the
411        // cargo-binary and cargo-library is not officially supported and it is under a lock.
412        // Technically, `git2_curl` also has a lock but that isn't part of their API guarantees.
413        //
414        // We're mostly clear on point (2) because we'd only free it after everything is done anyway
415        unsafe { init_git_transports(gctx) };
416    });
417
418    let git_config = git2::Config::open_default()?;
419    with_fetch_options(&git_config, remote_url, gctx, &mut |mut opts| {
420        if tags {
421            opts.download_tags(git2::AutotagOption::All);
422        }
423        if let gix::remote::fetch::Shallow::DepthAtRemote(depth) = shallow {
424            opts.depth(0i32.saturating_add_unsigned(depth.get()));
425        }
426        // The `fetch` operation here may fail spuriously due to a corrupt
427        // repository. It could also fail, however, for a whole slew of other
428        // reasons (aka network related reasons). We want Cargo to automatically
429        // recover from corrupt repositories, but we don't want Cargo to stomp
430        // over other legitimate errors.
431        //
432        // Consequently we save off the error of the `fetch` operation and if it
433        // looks like a "corrupt repo" error then we blow away the repo and try
434        // again. If it looks like any other kind of error, or if we've already
435        // blown away the repository, then we want to return the error as-is.
436        let mut repo_reinitialized = false;
437        loop {
438            debug!("initiating fetch of {refspecs:?} from {remote_url}");
439            let res = repo
440                .remote_anonymous(remote_url)?
441                .fetch(&refspecs, Some(&mut opts), None);
442            let err = match res {
443                Ok(()) => break,
444                Err(e) => e,
445            };
446            debug!("fetch failed: {}", err);
447
448            if !repo_reinitialized && matches!(err.class(), ErrorClass::Reference | ErrorClass::Odb)
449            {
450                repo_reinitialized = true;
451                debug!(
452                    "looks like this is a corrupt repository, reinitializing \
453                     and trying again"
454                );
455                if reinitialize(repo).is_ok() {
456                    continue;
457                }
458            }
459
460            return Err(err.into());
461        }
462        Ok(())
463    })
464}
465
466/// Configure libgit2 to use libcurl if necessary.
467///
468/// If the user has a non-default network configuration, then libgit2 will be
469/// configured to use libcurl instead of the built-in networking support so
470/// that those configuration settings can be used.
471///
472/// # Safety
473///
474/// See [git2_curl::register]
475#[tracing::instrument(skip_all)]
476unsafe fn init_git_transports(gctx: &GlobalContext) {
477    match needs_custom_http_transport(gctx) {
478        Ok(true) => {}
479        _ => return,
480    }
481
482    let handle = match http_handle(gctx) {
483        Ok(handle) => handle,
484        Err(..) => return,
485    };
486
487    unsafe {
488        git2_curl::register(handle);
489    }
490}