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#[derive(PartialEq, Clone, Debug, Serialize)]
55pub struct GitRemote {
56 #[serde(serialize_with = "serialize_str")]
57 url: Url,
58}
59
60#[derive(Serialize)]
63pub struct GitDatabase {
64 remote: GitRemote,
65 path: PathBuf,
66 #[serde(skip_serializing)]
67 repo: git2::Repository,
68}
69
70#[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
82impl 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 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 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 let git_config = git2::Config::new()?;
270
271 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(); let r = git2::build::RepoBuilder::new()
284 .clone_local(git2::build::CloneLocal::Local)
287 .with_checkout(checkout)
288 .fetch_options(fopts)
289 .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 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 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 let head = match child.head_id() {
371 Some(head) => head,
372 None => return Ok(()),
373 };
374
375 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 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
415fn 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 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 if allowed.contains(git2::CredentialType::SSH_KEY) && !tried_sshkey {
490 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 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 if allowed.contains(git2::CredentialType::DEFAULT) {
515 return git2::Cred::default();
516 }
517
518 Err(git2::Error::from_str("no authentication available"))
520 });
521
522 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 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 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 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 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 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 maybe_gc_repo(repo)?;
699
700 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 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") .arg("--quiet")
764 .arg("--update-head-ok") .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
775fn maybe_gc_repo(repo: &mut git2::Repository) -> CargoResult<()> {
789 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 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 reinitialize(repo)
834}
835
836fn reinitialize(repo: &mut git2::Repository) -> CargoResult<()> {
837 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 opts.external_template(false);
865 opts.bare(bare);
866 Ok(git2::Repository::init_opts(&path, &opts)?)
867}
868
869fn 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 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}