Skip to main content

cargo/sources/git/
utils.rs

1use std::env;
2use std::fmt;
3use std::fs::{self, File};
4use std::mem;
5use std::path::{Path, PathBuf};
6use std::process::Command;
7
8use curl::easy::{Easy, List};
9use git2::{self, ObjectType};
10use log::{debug, info};
11use serde::ser;
12use serde::Serialize;
13use url::Url;
14
15use crate::core::GitReference;
16use crate::util::errors::{CargoResult, CargoResultExt};
17use crate::util::paths;
18use crate::util::process_builder::process;
19use crate::util::{internal, network, Config, Progress, ToUrl};
20
21#[derive(PartialEq, Clone, Debug)]
22pub struct GitRevision(git2::Oid);
23
24impl ser::Serialize for GitRevision {
25    fn serialize<S: ser::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
26        serialize_str(self, s)
27    }
28}
29
30fn serialize_str<T, S>(t: &T, s: S) -> Result<S::Ok, S::Error>
31where
32    T: fmt::Display,
33    S: ser::Serializer,
34{
35    s.collect_str(t)
36}
37
38impl fmt::Display for GitRevision {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        fmt::Display::fmt(&self.0, f)
41    }
42}
43
44pub struct GitShortID(git2::Buf);
45
46impl GitShortID {
47    pub fn as_str(&self) -> &str {
48        self.0.as_str().unwrap()
49    }
50}
51
52/// `GitRemote` represents a remote repository. It gets cloned into a local
53/// `GitDatabase`.
54#[derive(PartialEq, Clone, Debug, Serialize)]
55pub struct GitRemote {
56    #[serde(serialize_with = "serialize_str")]
57    url: Url,
58}
59
60/// `GitDatabase` is a local clone of a remote repository's database. Multiple
61/// `GitCheckouts` can be cloned from this `GitDatabase`.
62#[derive(Serialize)]
63pub struct GitDatabase {
64    remote: GitRemote,
65    path: PathBuf,
66    #[serde(skip_serializing)]
67    repo: git2::Repository,
68}
69
70/// `GitCheckout` is a local checkout of a particular revision. Calling
71/// `clone_into` with a reference will resolve the reference into a revision,
72/// and return a `failure::Error` if no revision for that reference was found.
73#[derive(Serialize)]
74pub struct GitCheckout<'a> {
75    database: &'a GitDatabase,
76    location: PathBuf,
77    revision: GitRevision,
78    #[serde(skip_serializing)]
79    repo: git2::Repository,
80}
81
82// Implementations
83
84impl GitRemote {
85    pub fn new(url: &Url) -> GitRemote {
86        GitRemote { url: url.clone() }
87    }
88
89    pub fn url(&self) -> &Url {
90        &self.url
91    }
92
93    pub fn rev_for(&self, path: &Path, reference: &GitReference) -> CargoResult<GitRevision> {
94        reference.resolve(&self.db_at(path)?.repo)
95    }
96
97    pub fn checkout(
98        &self,
99        into: &Path,
100        reference: &GitReference,
101        cargo_config: &Config,
102    ) -> CargoResult<(GitDatabase, GitRevision)> {
103        let mut repo_and_rev = None;
104        if let Ok(mut repo) = git2::Repository::open(into) {
105            self.fetch_into(&mut repo, cargo_config)
106                .chain_err(|| format!("failed to fetch into {}", into.display()))?;
107            if let Ok(rev) = reference.resolve(&repo) {
108                repo_and_rev = Some((repo, rev));
109            }
110        }
111        let (repo, rev) = match repo_and_rev {
112            Some(pair) => pair,
113            None => {
114                let repo = self
115                    .clone_into(into, cargo_config)
116                    .chain_err(|| format!("failed to clone into: {}", into.display()))?;
117                let rev = reference.resolve(&repo)?;
118                (repo, rev)
119            }
120        };
121
122        Ok((
123            GitDatabase {
124                remote: self.clone(),
125                path: into.to_path_buf(),
126                repo,
127            },
128            rev,
129        ))
130    }
131
132    pub fn db_at(&self, db_path: &Path) -> CargoResult<GitDatabase> {
133        let repo = git2::Repository::open(db_path)?;
134        Ok(GitDatabase {
135            remote: self.clone(),
136            path: db_path.to_path_buf(),
137            repo,
138        })
139    }
140
141    fn fetch_into(&self, dst: &mut git2::Repository, cargo_config: &Config) -> CargoResult<()> {
142        // Create a local anonymous remote in the repository to fetch the url
143        let refspec = "refs/heads/*:refs/heads/*";
144        fetch(dst, &self.url, refspec, cargo_config)
145    }
146
147    fn clone_into(&self, dst: &Path, cargo_config: &Config) -> CargoResult<git2::Repository> {
148        if fs::metadata(&dst).is_ok() {
149            paths::remove_dir_all(dst)?;
150        }
151        fs::create_dir_all(dst)?;
152        let mut repo = init(dst, true)?;
153        fetch(
154            &mut repo,
155            &self.url,
156            "refs/heads/*:refs/heads/*",
157            cargo_config,
158        )?;
159        Ok(repo)
160    }
161}
162
163impl GitDatabase {
164    pub fn copy_to(
165        &self,
166        rev: GitRevision,
167        dest: &Path,
168        cargo_config: &Config,
169    ) -> CargoResult<GitCheckout<'_>> {
170        let mut checkout = None;
171        if let Ok(repo) = git2::Repository::open(dest) {
172            let mut co = GitCheckout::new(dest, self, rev.clone(), repo);
173            if !co.is_fresh() {
174                // After a successful fetch operation do a sanity check to
175                // ensure we've got the object in our database to reset to. This
176                // can fail sometimes for corrupt repositories where the fetch
177                // operation succeeds but the object isn't actually there.
178                co.fetch(cargo_config)?;
179                if co.has_object() {
180                    co.reset(cargo_config)?;
181                    assert!(co.is_fresh());
182                    checkout = Some(co);
183                }
184            } else {
185                checkout = Some(co);
186            }
187        };
188        let checkout = match checkout {
189            Some(c) => c,
190            None => GitCheckout::clone_into(dest, self, rev, cargo_config)?,
191        };
192        checkout.update_submodules(cargo_config)?;
193        Ok(checkout)
194    }
195
196    pub fn to_short_id(&self, revision: &GitRevision) -> CargoResult<GitShortID> {
197        let obj = self.repo.find_object(revision.0, None)?;
198        Ok(GitShortID(obj.short_id()?))
199    }
200
201    pub fn has_ref(&self, reference: &str) -> CargoResult<()> {
202        self.repo.revparse_single(reference)?;
203        Ok(())
204    }
205}
206
207impl GitReference {
208    fn resolve(&self, repo: &git2::Repository) -> CargoResult<GitRevision> {
209        let id = match *self {
210            GitReference::Tag(ref s) => (|| -> CargoResult<git2::Oid> {
211                let refname = format!("refs/tags/{}", s);
212                let id = repo.refname_to_id(&refname)?;
213                let obj = repo.find_object(id, None)?;
214                let obj = obj.peel(ObjectType::Commit)?;
215                Ok(obj.id())
216            })()
217            .chain_err(|| format!("failed to find tag `{}`", s))?,
218            GitReference::Branch(ref s) => {
219                let b = repo
220                    .find_branch(s, git2::BranchType::Local)
221                    .chain_err(|| format!("failed to find branch `{}`", s))?;
222                b.get()
223                    .target()
224                    .ok_or_else(|| failure::format_err!("branch `{}` did not have a target", s))?
225            }
226            GitReference::Rev(ref s) => {
227                let obj = repo.revparse_single(s)?;
228                match obj.as_tag() {
229                    Some(tag) => tag.target_id(),
230                    None => obj.id(),
231                }
232            }
233        };
234        Ok(GitRevision(id))
235    }
236}
237
238impl<'a> GitCheckout<'a> {
239    fn new(
240        path: &Path,
241        database: &'a GitDatabase,
242        revision: GitRevision,
243        repo: git2::Repository,
244    ) -> GitCheckout<'a> {
245        GitCheckout {
246            location: path.to_path_buf(),
247            database,
248            revision,
249            repo,
250        }
251    }
252
253    fn clone_into(
254        into: &Path,
255        database: &'a GitDatabase,
256        revision: GitRevision,
257        config: &Config,
258    ) -> CargoResult<GitCheckout<'a>> {
259        let dirname = into.parent().unwrap();
260        fs::create_dir_all(&dirname)
261            .chain_err(|| format!("Couldn't mkdir {}", dirname.display()))?;
262        if into.exists() {
263            paths::remove_dir_all(into)?;
264        }
265
266        // we're doing a local filesystem-to-filesystem clone so there should
267        // be no need to respect global configuration options, so pass in
268        // an empty instance of `git2::Config` below.
269        let git_config = git2::Config::new()?;
270
271        // Clone the repository, but make sure we use the "local" option in
272        // libgit2 which will attempt to use hardlinks to set up the database.
273        // This should speed up the clone operation quite a bit if it works.
274        //
275        // Note that we still use the same fetch options because while we don't
276        // need authentication information we may want progress bars and such.
277        let url = database.path.to_url()?;
278        let mut repo = None;
279        with_fetch_options(&git_config, &url, config, &mut |fopts| {
280            let mut checkout = git2::build::CheckoutBuilder::new();
281            checkout.dry_run(); // we'll do this below during a `reset`
282
283            let r = git2::build::RepoBuilder::new()
284                // use hard links and/or copy the database, we're doing a
285                // filesystem clone so this'll speed things up quite a bit.
286                .clone_local(git2::build::CloneLocal::Local)
287                .with_checkout(checkout)
288                .fetch_options(fopts)
289                // .remote_create(|repo, _name, url| repo.remote_anonymous(url))
290                .clone(url.as_str(), into)?;
291            repo = Some(r);
292            Ok(())
293        })?;
294        let repo = repo.unwrap();
295
296        let checkout = GitCheckout::new(into, database, revision, repo);
297        checkout.reset(config)?;
298        Ok(checkout)
299    }
300
301    fn is_fresh(&self) -> bool {
302        match self.repo.revparse_single("HEAD") {
303            Ok(ref head) if head.id() == self.revision.0 => {
304                // See comments in reset() for why we check this
305                self.location.join(".cargo-ok").exists()
306            }
307            _ => false,
308        }
309    }
310
311    fn fetch(&mut self, cargo_config: &Config) -> CargoResult<()> {
312        info!("fetch {}", self.repo.path().display());
313        let url = self.database.path.to_url()?;
314        let refspec = "refs/heads/*:refs/heads/*";
315        fetch(&mut self.repo, &url, refspec, cargo_config)?;
316        Ok(())
317    }
318
319    fn has_object(&self) -> bool {
320        self.repo.find_object(self.revision.0, None).is_ok()
321    }
322
323    fn reset(&self, config: &Config) -> CargoResult<()> {
324        // If we're interrupted while performing this reset (e.g. we die because
325        // of a signal) Cargo needs to be sure to try to check out this repo
326        // again on the next go-round.
327        //
328        // To enable this we have a dummy file in our checkout, .cargo-ok, which
329        // if present means that the repo has been successfully reset and is
330        // ready to go. Hence if we start to do a reset, we make sure this file
331        // *doesn't* exist, and then once we're done we create the file.
332        let ok_file = self.location.join(".cargo-ok");
333        let _ = paths::remove_file(&ok_file);
334        info!("reset {} to {}", self.repo.path().display(), self.revision);
335        let object = self.repo.find_object(self.revision.0, None)?;
336        reset(&self.repo, &object, config)?;
337        File::create(ok_file)?;
338        Ok(())
339    }
340
341    fn update_submodules(&self, cargo_config: &Config) -> CargoResult<()> {
342        return update_submodules(&self.repo, cargo_config);
343
344        fn update_submodules(repo: &git2::Repository, cargo_config: &Config) -> CargoResult<()> {
345            info!("update submodules for: {:?}", repo.workdir().unwrap());
346
347            for mut child in repo.submodules()? {
348                update_submodule(repo, &mut child, cargo_config).chain_err(|| {
349                    format!(
350                        "failed to update submodule `{}`",
351                        child.name().unwrap_or("")
352                    )
353                })?;
354            }
355            Ok(())
356        }
357
358        fn update_submodule(
359            parent: &git2::Repository,
360            child: &mut git2::Submodule<'_>,
361            cargo_config: &Config,
362        ) -> CargoResult<()> {
363            child.init(false)?;
364            let url = child
365                .url()
366                .ok_or_else(|| internal("non-utf8 url for submodule"))?;
367
368            // A submodule which is listed in .gitmodules but not actually
369            // checked out will not have a head id, so we should ignore it.
370            let head = match child.head_id() {
371                Some(head) => head,
372                None => return Ok(()),
373            };
374
375            // If the submodule hasn't been checked out yet, we need to
376            // clone it. If it has been checked out and the head is the same
377            // as the submodule's head, then we can skip an update and keep
378            // recursing.
379            let head_and_repo = child.open().and_then(|repo| {
380                let target = repo.head()?.target();
381                Ok((target, repo))
382            });
383            let mut repo = match head_and_repo {
384                Ok((head, repo)) => {
385                    if child.head_id() == head {
386                        return update_submodules(&repo, cargo_config);
387                    }
388                    repo
389                }
390                Err(..) => {
391                    let path = parent.workdir().unwrap().join(child.path());
392                    let _ = paths::remove_dir_all(&path);
393                    init(&path, false)?
394                }
395            };
396
397            // Fetch data from origin and reset to the head commit
398            let refspec = "refs/heads/*:refs/heads/*";
399            let url = url.to_url()?;
400            fetch(&mut repo, &url, refspec, cargo_config).chain_err(|| {
401                internal(format!(
402                    "failed to fetch submodule `{}` from {}",
403                    child.name().unwrap_or(""),
404                    url
405                ))
406            })?;
407
408            let obj = repo.find_object(head, None)?;
409            reset(&repo, &obj, cargo_config)?;
410            update_submodules(&repo, cargo_config)
411        }
412    }
413}
414
415/// Prepare the authentication callbacks for cloning a git repository.
416///
417/// The main purpose of this function is to construct the "authentication
418/// callback" which is used to clone a repository. This callback will attempt to
419/// find the right authentication on the system (without user input) and will
420/// guide libgit2 in doing so.
421///
422/// The callback is provided `allowed` types of credentials, and we try to do as
423/// much as possible based on that:
424///
425/// * Prioritize SSH keys from the local ssh agent as they're likely the most
426///   reliable. The username here is prioritized from the credential
427///   callback, then from whatever is configured in git itself, and finally
428///   we fall back to the generic user of `git`.
429///
430/// * If a username/password is allowed, then we fallback to git2-rs's
431///   implementation of the credential helper. This is what is configured
432///   with `credential.helper` in git, and is the interface for the OSX
433///   keychain, for example.
434///
435/// * After the above two have failed, we just kinda grapple attempting to
436///   return *something*.
437///
438/// If any form of authentication fails, libgit2 will repeatedly ask us for
439/// credentials until we give it a reason to not do so. To ensure we don't
440/// just sit here looping forever we keep track of authentications we've
441/// attempted and we don't try the same ones again.
442fn with_authentication<T, F>(url: &str, cfg: &git2::Config, mut f: F) -> CargoResult<T>
443where
444    F: FnMut(&mut git2::Credentials<'_>) -> CargoResult<T>,
445{
446    let mut cred_helper = git2::CredentialHelper::new(url);
447    cred_helper.config(cfg);
448
449    let mut ssh_username_requested = false;
450    let mut cred_helper_bad = None;
451    let mut ssh_agent_attempts = Vec::new();
452    let mut any_attempts = false;
453    let mut tried_sshkey = false;
454
455    let mut res = f(&mut |url, username, allowed| {
456        any_attempts = true;
457        // libgit2's "USERNAME" authentication actually means that it's just
458        // asking us for a username to keep going. This is currently only really
459        // used for SSH authentication and isn't really an authentication type.
460        // The logic currently looks like:
461        //
462        //      let user = ...;
463        //      if (user.is_null())
464        //          user = callback(USERNAME, null, ...);
465        //
466        //      callback(SSH_KEY, user, ...)
467        //
468        // So if we're being called here then we know that (a) we're using ssh
469        // authentication and (b) no username was specified in the URL that
470        // we're trying to clone. We need to guess an appropriate username here,
471        // but that may involve a few attempts. Unfortunately we can't switch
472        // usernames during one authentication session with libgit2, so to
473        // handle this we bail out of this authentication session after setting
474        // the flag `ssh_username_requested`, and then we handle this below.
475        if allowed.contains(git2::CredentialType::USERNAME) {
476            debug_assert!(username.is_none());
477            ssh_username_requested = true;
478            return Err(git2::Error::from_str("gonna try usernames later"));
479        }
480
481        // An "SSH_KEY" authentication indicates that we need some sort of SSH
482        // authentication. This can currently either come from the ssh-agent
483        // process or from a raw in-memory SSH key. Cargo only supports using
484        // ssh-agent currently.
485        //
486        // If we get called with this then the only way that should be possible
487        // is if a username is specified in the URL itself (e.g. `username` is
488        // Some), hence the unwrap() here. We try custom usernames down below.
489        if allowed.contains(git2::CredentialType::SSH_KEY) && !tried_sshkey {
490            // If ssh-agent authentication fails, libgit2 will keep
491            // calling this callback asking for other authentication
492            // methods to try. Make sure we only try ssh-agent once,
493            // to avoid looping forever.
494            tried_sshkey = true;
495            let username = username.unwrap();
496            debug_assert!(!ssh_username_requested);
497            ssh_agent_attempts.push(username.to_string());
498            return git2::Cred::ssh_key_from_agent(username);
499        }
500
501        // Sometimes libgit2 will ask for a username/password in plaintext. This
502        // is where Cargo would have an interactive prompt if we supported it,
503        // but we currently don't! Right now the only way we support fetching a
504        // plaintext password is through the `credential.helper` support, so
505        // fetch that here.
506        if allowed.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
507            let r = git2::Cred::credential_helper(cfg, url, username);
508            cred_helper_bad = Some(r.is_err());
509            return r;
510        }
511
512        // I'm... not sure what the DEFAULT kind of authentication is, but seems
513        // easy to support?
514        if allowed.contains(git2::CredentialType::DEFAULT) {
515            return git2::Cred::default();
516        }
517
518        // Whelp, we tried our best
519        Err(git2::Error::from_str("no authentication available"))
520    });
521
522    // Ok, so if it looks like we're going to be doing ssh authentication, we
523    // want to try a few different usernames as one wasn't specified in the URL
524    // for us to use. In order, we'll try:
525    //
526    // * A credential helper's username for this URL, if available.
527    // * This account's username.
528    // * "git"
529    //
530    // We have to restart the authentication session each time (due to
531    // constraints in libssh2 I guess? maybe this is inherent to ssh?), so we
532    // call our callback, `f`, in a loop here.
533    if ssh_username_requested {
534        debug_assert!(res.is_err());
535        let mut attempts = Vec::new();
536        attempts.push("git".to_string());
537        if let Ok(s) = env::var("USER").or_else(|_| env::var("USERNAME")) {
538            attempts.push(s);
539        }
540        if let Some(ref s) = cred_helper.username {
541            attempts.push(s.clone());
542        }
543
544        while let Some(s) = attempts.pop() {
545            // We should get `USERNAME` first, where we just return our attempt,
546            // and then after that we should get `SSH_KEY`. If the first attempt
547            // fails we'll get called again, but we don't have another option so
548            // we bail out.
549            let mut attempts = 0;
550            res = f(&mut |_url, username, allowed| {
551                if allowed.contains(git2::CredentialType::USERNAME) {
552                    return git2::Cred::username(&s);
553                }
554                if allowed.contains(git2::CredentialType::SSH_KEY) {
555                    debug_assert_eq!(Some(&s[..]), username);
556                    attempts += 1;
557                    if attempts == 1 {
558                        ssh_agent_attempts.push(s.to_string());
559                        return git2::Cred::ssh_key_from_agent(&s);
560                    }
561                }
562                Err(git2::Error::from_str("no authentication available"))
563            });
564
565            // If we made two attempts then that means:
566            //
567            // 1. A username was requested, we returned `s`.
568            // 2. An ssh key was requested, we returned to look up `s` in the
569            //    ssh agent.
570            // 3. For whatever reason that lookup failed, so we were asked again
571            //    for another mode of authentication.
572            //
573            // Essentially, if `attempts == 2` then in theory the only error was
574            // that this username failed to authenticate (e.g. no other network
575            // errors happened). Otherwise something else is funny so we bail
576            // out.
577            if attempts != 2 {
578                break;
579            }
580        }
581    }
582
583    if res.is_ok() || !any_attempts {
584        return res.map_err(From::from);
585    }
586
587    // In the case of an authentication failure (where we tried something) then
588    // we try to give a more helpful error message about precisely what we
589    // tried.
590    let res = res.map_err(failure::Error::from).chain_err(|| {
591        let mut msg = "failed to authenticate when downloading \
592                       repository"
593            .to_string();
594        if !ssh_agent_attempts.is_empty() {
595            let names = ssh_agent_attempts
596                .iter()
597                .map(|s| format!("`{}`", s))
598                .collect::<Vec<_>>()
599                .join(", ");
600            msg.push_str(&format!(
601                "\nattempted ssh-agent authentication, but \
602                 none of the usernames {} succeeded",
603                names
604            ));
605        }
606        if let Some(failed_cred_helper) = cred_helper_bad {
607            if failed_cred_helper {
608                msg.push_str(
609                    "\nattempted to find username/password via \
610                     git's `credential.helper` support, but failed",
611                );
612            } else {
613                msg.push_str(
614                    "\nattempted to find username/password via \
615                     `credential.helper`, but maybe the found \
616                     credentials were incorrect",
617                );
618            }
619        }
620        msg
621    })?;
622    Ok(res)
623}
624
625fn reset(repo: &git2::Repository, obj: &git2::Object<'_>, config: &Config) -> CargoResult<()> {
626    let mut pb = Progress::new("Checkout", config);
627    let mut opts = git2::build::CheckoutBuilder::new();
628    opts.progress(|_, cur, max| {
629        drop(pb.tick(cur, max));
630    });
631    repo.reset(obj, git2::ResetType::Hard, Some(&mut opts))?;
632    Ok(())
633}
634
635pub fn with_fetch_options(
636    git_config: &git2::Config,
637    url: &Url,
638    config: &Config,
639    cb: &mut dyn FnMut(git2::FetchOptions<'_>) -> CargoResult<()>,
640) -> CargoResult<()> {
641    let mut progress = Progress::new("Fetch", config);
642    network::with_retry(config, || {
643        with_authentication(url.as_str(), git_config, |f| {
644            let mut rcb = git2::RemoteCallbacks::new();
645            rcb.credentials(f);
646
647            rcb.transfer_progress(|stats| {
648                progress
649                    .tick(stats.indexed_objects(), stats.total_objects())
650                    .is_ok()
651            });
652
653            // Create a local anonymous remote in the repository to fetch the
654            // url
655            let mut opts = git2::FetchOptions::new();
656            opts.remote_callbacks(rcb)
657                .download_tags(git2::AutotagOption::All);
658            cb(opts)
659        })?;
660        Ok(())
661    })
662}
663
664pub fn fetch(
665    repo: &mut git2::Repository,
666    url: &Url,
667    refspec: &str,
668    config: &Config,
669) -> CargoResult<()> {
670    if config.frozen() {
671        failure::bail!(
672            "attempting to update a git repository, but --frozen \
673             was specified"
674        )
675    }
676    if !config.network_allowed() {
677        failure::bail!("can't update a git repository in the offline mode")
678    }
679
680    // If we're fetching from GitHub, attempt GitHub's special fast path for
681    // testing if we've already got an up-to-date copy of the repository
682    if url.host_str() == Some("github.com") {
683        if let Ok(oid) = repo.refname_to_id("refs/remotes/origin/master") {
684            let mut handle = config.http()?.borrow_mut();
685            debug!("attempting GitHub fast path for {}", url);
686            if github_up_to_date(&mut handle, url, &oid) {
687                return Ok(());
688            } else {
689                debug!("fast path failed, falling back to a git fetch");
690            }
691        }
692    }
693
694    // We reuse repositories quite a lot, so before we go through and update the
695    // repo check to see if it's a little too old and could benefit from a gc.
696    // In theory this shouldn't be too too expensive compared to the network
697    // request we're about to issue.
698    maybe_gc_repo(repo)?;
699
700    // Unfortuantely `libgit2` is notably lacking in the realm of authentication
701    // when compared to the `git` command line. As a result, allow an escape
702    // hatch for users that would prefer to use `git`-the-CLI for fetching
703    // repositories instead of `libgit2`-the-library. This should make more
704    // flavors of authentication possible while also still giving us all the
705    // speed and portability of using `libgit2`.
706    if let Some(val) = config.get_bool("net.git-fetch-with-cli")? {
707        if val.val {
708            return fetch_with_cli(repo, url, refspec, config);
709        }
710    }
711
712    debug!("doing a fetch for {}", url);
713    let git_config = git2::Config::open_default()?;
714    with_fetch_options(&git_config, url, config, &mut |mut opts| {
715        // The `fetch` operation here may fail spuriously due to a corrupt
716        // repository. It could also fail, however, for a whole slew of other
717        // reasons (aka network related reasons). We want Cargo to automatically
718        // recover from corrupt repositories, but we don't want Cargo to stomp
719        // over other legitimate errors.o
720        //
721        // Consequently we save off the error of the `fetch` operation and if it
722        // looks like a "corrupt repo" error then we blow away the repo and try
723        // again. If it looks like any other kind of error, or if we've already
724        // blown away the repository, then we want to return the error as-is.
725        let mut repo_reinitialized = false;
726        loop {
727            debug!("initiating fetch of {} from {}", refspec, url);
728            let res = repo
729                .remote_anonymous(url.as_str())?
730                .fetch(&[refspec], Some(&mut opts), None);
731            let err = match res {
732                Ok(()) => break,
733                Err(e) => e,
734            };
735            debug!("fetch failed: {}", err);
736
737            if !repo_reinitialized && err.class() == git2::ErrorClass::Reference {
738                repo_reinitialized = true;
739                debug!(
740                    "looks like this is a corrupt repository, reinitializing \
741                     and trying again"
742                );
743                if reinitialize(repo).is_ok() {
744                    continue;
745                }
746            }
747
748            return Err(err.into());
749        }
750        Ok(())
751    })
752}
753
754fn fetch_with_cli(
755    repo: &mut git2::Repository,
756    url: &Url,
757    refspec: &str,
758    config: &Config,
759) -> CargoResult<()> {
760    let mut cmd = process("git");
761    cmd.arg("fetch")
762        .arg("--tags") // fetch all tags
763        .arg("--quiet")
764        .arg("--update-head-ok") // see discussion in #2078
765        .arg(url.to_string())
766        .arg(refspec)
767        .cwd(repo.path());
768    config
769        .shell()
770        .verbose(|s| s.status("Running", &cmd.to_string()))?;
771    cmd.exec()?;
772    Ok(())
773}
774
775/// Cargo has a bunch of long-lived git repositories in its global cache and
776/// some, like the index, are updated very frequently. Right now each update
777/// creates a new "pack file" inside the git database, and over time this can
778/// cause bad performance and bad current behavior in libgit2.
779///
780/// One pathological use case today is where libgit2 opens hundreds of file
781/// descriptors, getting us dangerously close to blowing out the OS limits of
782/// how many fds we can have open. This is detailed in #4403.
783///
784/// To try to combat this problem we attempt a `git gc` here. Note, though, that
785/// we may not even have `git` installed on the system! As a result we
786/// opportunistically try a `git gc` when the pack directory looks too big, and
787/// failing that we just blow away the repository and start over.
788fn maybe_gc_repo(repo: &mut git2::Repository) -> CargoResult<()> {
789    // Here we arbitrarily declare that if you have more than 100 files in your
790    // `pack` folder that we need to do a gc.
791    let entries = match repo.path().join("objects/pack").read_dir() {
792        Ok(e) => e.count(),
793        Err(_) => {
794            debug!("skipping gc as pack dir appears gone");
795            return Ok(());
796        }
797    };
798    let max = env::var("__CARGO_PACKFILE_LIMIT")
799        .ok()
800        .and_then(|s| s.parse::<usize>().ok())
801        .unwrap_or(100);
802    if entries < max {
803        debug!("skipping gc as there's only {} pack files", entries);
804        return Ok(());
805    }
806
807    // First up, try a literal `git gc` by shelling out to git. This is pretty
808    // likely to fail though as we may not have `git` installed. Note that
809    // libgit2 doesn't currently implement the gc operation, so there's no
810    // equivalent there.
811    match Command::new("git")
812        .arg("gc")
813        .current_dir(repo.path())
814        .output()
815    {
816        Ok(out) => {
817            debug!(
818                "git-gc status: {}\n\nstdout ---\n{}\nstderr ---\n{}",
819                out.status,
820                String::from_utf8_lossy(&out.stdout),
821                String::from_utf8_lossy(&out.stderr)
822            );
823            if out.status.success() {
824                let new = git2::Repository::open(repo.path())?;
825                mem::replace(repo, new);
826                return Ok(());
827            }
828        }
829        Err(e) => debug!("git-gc failed to spawn: {}", e),
830    }
831
832    // Alright all else failed, let's start over.
833    reinitialize(repo)
834}
835
836fn reinitialize(repo: &mut git2::Repository) -> CargoResult<()> {
837    // Here we want to drop the current repository object pointed to by `repo`,
838    // so we initialize temporary repository in a sub-folder, blow away the
839    // existing git folder, and then recreate the git repo. Finally we blow away
840    // the `tmp` folder we allocated.
841    let path = repo.path().to_path_buf();
842    debug!("reinitializing git repo at {:?}", path);
843    let tmp = path.join("tmp");
844    let bare = !repo.path().ends_with(".git");
845    *repo = init(&tmp, false)?;
846    for entry in path.read_dir()? {
847        let entry = entry?;
848        if entry.file_name().to_str() == Some("tmp") {
849            continue;
850        }
851        let path = entry.path();
852        drop(paths::remove_file(&path).or_else(|_| paths::remove_dir_all(&path)));
853    }
854    *repo = init(&path, bare)?;
855    paths::remove_dir_all(&tmp)?;
856    Ok(())
857}
858
859fn init(path: &Path, bare: bool) -> CargoResult<git2::Repository> {
860    let mut opts = git2::RepositoryInitOptions::new();
861    // Skip anyting related to templates, they just call all sorts of issues as
862    // we really don't want to use them yet they insist on being used. See #6240
863    // for an example issue that comes up.
864    opts.external_template(false);
865    opts.bare(bare);
866    Ok(git2::Repository::init_opts(&path, &opts)?)
867}
868
869/// Updating the index is done pretty regularly so we want it to be as fast as
870/// possible. For registries hosted on GitHub (like the crates.io index) there's
871/// a fast path available to use [1] to tell us that there's no updates to be
872/// made.
873///
874/// This function will attempt to hit that fast path and verify that the `oid`
875/// is actually the current `master` branch of the repository. If `true` is
876/// returned then no update needs to be performed, but if `false` is returned
877/// then the standard update logic still needs to happen.
878///
879/// [1]: https://developer.github.com/v3/repos/commits/#get-the-sha-1-of-a-commit-reference
880///
881/// Note that this function should never cause an actual failure because it's
882/// just a fast path. As a result all errors are ignored in this function and we
883/// just return a `bool`. Any real errors will be reported through the normal
884/// update path above.
885fn github_up_to_date(handle: &mut Easy, url: &Url, oid: &git2::Oid) -> bool {
886    macro_rules! r#try {
887        ($e:expr) => {
888            match $e {
889                Some(e) => e,
890                None => return false,
891            }
892        };
893    }
894
895    // This expects GitHub urls in the form `github.com/user/repo` and nothing
896    // else
897    let mut pieces = r#try!(url.path_segments());
898    let username = r#try!(pieces.next());
899    let repo = r#try!(pieces.next());
900    if pieces.next().is_some() {
901        return false;
902    }
903
904    let url = format!(
905        "https://api.github.com/repos/{}/{}/commits/master",
906        username, repo
907    );
908    r#try!(handle.get(true).ok());
909    r#try!(handle.url(&url).ok());
910    r#try!(handle.useragent("cargo").ok());
911    let mut headers = List::new();
912    r#try!(headers.append("Accept: application/vnd.github.3.sha").ok());
913    r#try!(headers.append(&format!("If-None-Match: \"{}\"", oid)).ok());
914    r#try!(handle.http_headers(headers).ok());
915    r#try!(handle.perform().ok());
916
917    r#try!(handle.response_code().ok()) == 304
918}