1use crate::util::HumanBytes;
5use crate::util::network::http::HttpTimeout;
6use crate::util::{MetricsCounter, Progress, network};
7use crate::{CargoResult, GlobalContext};
8use cargo_util::paths;
9use gix::bstr::{BString, ByteSlice};
10use std::cell::RefCell;
11use std::path::Path;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::sync::{Arc, Weak};
14use std::time::{Duration, Instant};
15use tracing::debug;
16
17pub fn with_retry_and_progress(
20 repo_path: &std::path::Path,
21 gctx: &GlobalContext,
22 repo_remote_url: &str,
23 cb: &(
24 dyn Fn(
25 &std::path::Path,
26 &AtomicBool,
27 &mut gix::progress::tree::Item,
28 &mut dyn FnMut(&gix::bstr::BStr),
29 ) -> Result<(), crate::sources::git::fetch::Error>
30 + Send
31 + Sync
32 ),
33) -> CargoResult<()> {
34 std::thread::scope(|s| {
35 let mut progress_bar = Progress::new("Fetch", gctx);
36 let is_shallow = gctx.cli_unstable().git.map_or(false, |features| {
37 features.shallow_deps || features.shallow_index
38 });
39 network::retry::with_retry(gctx, || {
40 let progress_root: Arc<gix::progress::tree::Root> =
41 gix::progress::tree::root::Options {
42 initial_capacity: 10,
43 message_buffer_capacity: 10,
44 }
45 .into();
46 let root = Arc::downgrade(&progress_root);
47 let thread = s.spawn(move || {
48 let mut progress = progress_root.add_child("operation");
49 let mut urls = RefCell::new(Default::default());
50 let res = cb(
51 &repo_path,
52 &AtomicBool::default(),
53 &mut progress,
54 &mut |url| {
55 *urls.borrow_mut() = Some(url.to_owned());
56 },
57 );
58 amend_authentication_hints(res, repo_remote_url, urls.get_mut().take())
59 });
60 translate_progress_to_bar(&mut progress_bar, root, is_shallow)?;
61 thread.join().expect("no panic in scoped thread")
62 })
63 })
64}
65
66fn translate_progress_to_bar(
67 progress_bar: &mut Progress<'_>,
68 root: Weak<gix::progress::tree::Root>,
69 is_shallow: bool,
70) -> CargoResult<()> {
71 let remote_progress: gix::progress::Id = gix::remote::fetch::ProgressId::RemoteProgress.into();
72 let read_pack_bytes: gix::progress::Id =
73 gix::odb::pack::bundle::write::ProgressId::ReadPackBytes.into();
74 let delta_index_objects: gix::progress::Id =
75 gix::odb::pack::index::write::ProgressId::IndexObjects.into();
76 let resolve_objects: gix::progress::Id =
77 gix::odb::pack::index::write::ProgressId::ResolveObjects.into();
78
79 let mut last_percentage_update = Instant::now();
82 let mut last_fast_update = Instant::now();
83 let mut counter = MetricsCounter::<10>::new(0, last_percentage_update);
84
85 let mut tasks = Vec::with_capacity(10);
86 let slow_check_interval = std::time::Duration::from_millis(300);
87 let fast_check_interval = Duration::from_millis(50);
88 let sleep_interval = Duration::from_millis(10);
89 debug_assert_eq!(
90 slow_check_interval.as_millis() % fast_check_interval.as_millis(),
91 0,
92 "progress should be smoother by keeping these as multiples of each other"
93 );
94 debug_assert_eq!(
95 fast_check_interval.as_millis() % sleep_interval.as_millis(),
96 0,
97 "progress should be smoother by keeping these as multiples of each other"
98 );
99
100 let num_phases = if is_shallow { 3 } else { 2 }; while let Some(root) = root.upgrade() {
102 std::thread::sleep(sleep_interval);
103 let needs_update = last_fast_update.elapsed() >= fast_check_interval;
104 if !needs_update {
105 continue;
106 }
107 let now = Instant::now();
108 last_fast_update = now;
109
110 root.sorted_snapshot(&mut tasks);
111
112 fn progress_by_id(
113 id: gix::progress::Id,
114 task: &gix::progress::Task,
115 ) -> Option<(&str, &gix::progress::Value)> {
116 (task.id == id)
117 .then(|| task.progress.as_ref())
118 .flatten()
119 .map(|value| (task.name.as_str(), value))
120 }
121 fn find_in<K>(
122 tasks: &[(K, gix::progress::Task)],
123 cb: impl Fn(&gix::progress::Task) -> Option<(&str, &gix::progress::Value)>,
124 ) -> Option<(&str, &gix::progress::Value)> {
125 tasks.iter().find_map(|(_, t)| cb(t))
126 }
127
128 if let Some((_, objs)) = find_in(&tasks, |t| progress_by_id(resolve_objects, t)) {
129 let objects = objs.step.load(Ordering::Relaxed);
131 let total_objects = objs.done_at.expect("known amount of objects");
132 let msg = format!(", ({objects}/{total_objects}) resolving deltas");
133
134 progress_bar.tick(
135 (total_objects * (num_phases - 1)) + objects,
136 total_objects * num_phases,
137 &msg,
138 )?;
139 } else if let Some((objs, read_pack)) =
140 find_in(&tasks, |t| progress_by_id(read_pack_bytes, t)).and_then(|read| {
141 find_in(&tasks, |t| progress_by_id(delta_index_objects, t))
142 .map(|delta| (delta.1, read.1))
143 })
144 {
145 let objects = objs.step.load(Ordering::Relaxed);
147 let total_objects = objs.done_at.expect("known amount of objects");
148 let received_bytes = read_pack.step.load(Ordering::Relaxed);
149
150 let needs_percentage_update = last_percentage_update.elapsed() >= slow_check_interval;
151 if needs_percentage_update {
152 counter.add(received_bytes, now);
153 last_percentage_update = now;
154 }
155 let rate = HumanBytes(counter.rate() as u64);
156 let msg = format!(", {rate:.2}/s");
157
158 progress_bar.tick(
159 (total_objects * (num_phases - 2)) + objects,
160 total_objects * num_phases,
161 &msg,
162 )?;
163 } else if let Some((action, remote)) =
164 find_in(&tasks, |t| progress_by_id(remote_progress, t))
165 {
166 if !is_shallow {
167 continue;
168 }
169 let objects = remote.step.load(Ordering::Relaxed);
173 if let Some(total_objects) = remote.done_at {
174 let msg = format!(", ({objects}/{total_objects}) {action}");
175 progress_bar.tick(objects, total_objects * num_phases, &msg)?;
176 }
177 }
178 }
179 Ok(())
180}
181
182#[derive(Debug, thiserror::Error)]
183#[error("{0}")]
184pub(super) struct CredentialError(#[source] pub gix::Error);
185
186fn amend_authentication_hints(
187 res: Result<(), crate::sources::git::fetch::Error>,
188 remote_url: &str,
189 last_url_for_authentication: Option<gix::bstr::BString>,
190) -> CargoResult<()> {
191 let Err(err) = res else { return Ok(()) };
192 let auth_message = if err.downcast_any_ref::<CredentialError>().is_some()
193 || err.is_unauthenticated()
194 {
195 if err
196 .downcast_any_ref::<gix::protocol::transport::client::AuthenticationRequired>()
197 .is_none()
198 {
199 "\n* attempted to find username/password via \
200 git's `credential.helper` support, but failed"
201 .into()
202 } else {
203 "\n* attempted to find username/password via \
204 `credential.helper`, but maybe the found \
205 credentials were incorrect"
206 .into()
207 }
208 } else {
209 if err
210 .downcast_any_ref::<gix::protocol::transport::client::Error>()
211 .is_some()
212 {
213 let msg = format!(
214 concat!(
215 "network failure seems to have happened\n",
216 "if a proxy or similar is necessary `net.git-fetch-with-cli` may help here\n",
217 "https://doc.rust-lang.org/cargo/reference/config.html#netgit-fetch-with-cli",
218 "{}"
219 ),
220 super::utils::note_github_pull_request(remote_url).unwrap_or_default()
221 );
222 return Err(anyhow::Error::from(err).context(msg));
223 }
224 None
225 };
226 if let Some(auth_message) = auth_message {
227 let mut msg = "failed to authenticate when downloading \
228 repository"
229 .to_string();
230 if let Some(url) = last_url_for_authentication {
231 msg.push_str(": ");
232 msg.push_str(url.to_str_lossy().as_ref());
233 }
234 msg.push('\n');
235 msg.push_str(auth_message);
236 msg.push_str("\n\n");
237 msg.push_str("if the git CLI succeeds then `net.git-fetch-with-cli` may help here\n");
238 msg.push_str("https://doc.rust-lang.org/cargo/reference/config.html#netgit-fetch-with-cli");
239 return Err(anyhow::Error::from(err).context(msg));
240 }
241 Err(err.into())
242}
243
244pub enum OpenMode {
248 ForFetch,
253}
254
255impl OpenMode {
256 pub fn needs_git_binary_config(&self) -> bool {
259 match self {
260 OpenMode::ForFetch => true,
261 }
262 }
263}
264
265pub fn open_repo(
269 repo_path: &std::path::Path,
270 config_overrides: Vec<BString>,
271 purpose: OpenMode,
272) -> gix::Result<gix::Repository> {
273 gix::open_opts(repo_path, {
274 let mut opts = gix::open::Options::default();
275 opts.permissions.config = gix::open::permissions::Config::all();
276 opts.permissions.config.git_binary = purpose.needs_git_binary_config();
277 opts.with(gix::sec::Trust::Full)
278 .config_overrides(config_overrides)
279 })
280}
281
282pub fn cargo_config_to_gitoxide_overrides(gctx: &GlobalContext) -> CargoResult<Vec<BString>> {
285 use gix::config::tree::{Core, Http, Key, gitoxide};
286 let timeout = HttpTimeout::new(gctx)?;
287 let http = gctx.http_config()?;
288
289 let mut values = vec![
290 gitoxide::Http::CONNECT_TIMEOUT.validated_assignment_fmt(&timeout.dur.as_millis())?,
291 Http::LOW_SPEED_LIMIT.validated_assignment_fmt(&timeout.low_speed_limit)?,
292 Http::LOW_SPEED_TIME.validated_assignment_fmt(&timeout.dur.as_secs())?,
293 Core::LOG_ALL_REF_UPDATES.validated_assignment_fmt(&false)?,
295 ];
296 if let Some(proxy) = &http.proxy {
297 values.push(Http::PROXY.validated_assignment_fmt(proxy)?);
298 }
299 if let Some(check_revoke) = http.check_revoke {
300 values.push(Http::SCHANNEL_CHECK_REVOKE.validated_assignment_fmt(&check_revoke)?);
301 }
302 if let Some(cainfo) = &http.cainfo {
303 values.push(
304 Http::SSL_CA_INFO.validated_assignment_fmt(&cainfo.resolve(gctx.cwd()).display())?,
305 );
306 }
307
308 values.push(if let Some(user_agent) = &http.user_agent {
309 Http::USER_AGENT.validated_assignment_fmt(user_agent)
310 } else {
311 Http::USER_AGENT.validated_assignment_fmt(&format!("cargo {}", crate::version()))
312 }?);
313 if let Some(ssl_version) = &http.ssl_version {
314 use crate::context::SslVersionConfig;
315 match ssl_version {
316 SslVersionConfig::Single(version) => {
317 values.push(Http::SSL_VERSION.validated_assignment_fmt(&version)?);
318 }
319 SslVersionConfig::Range(range) => {
320 values.push(
321 gitoxide::Http::SSL_VERSION_MIN
322 .validated_assignment_fmt(&range.min.as_deref().unwrap_or("default"))?,
323 );
324 values.push(
325 gitoxide::Http::SSL_VERSION_MAX
326 .validated_assignment_fmt(&range.max.as_deref().unwrap_or("default"))?,
327 );
328 }
329 }
330 } else if cfg!(windows) {
331 values.push(gitoxide::Http::SSL_VERSION_MIN.validated_assignment_fmt(&"default")?);
349 values.push(gitoxide::Http::SSL_VERSION_MAX.validated_assignment_fmt(&"tlsv1.2")?);
350 }
351 if let Some(debug) = http.debug {
352 values.push(gitoxide::Http::VERBOSE.validated_assignment_fmt(&debug)?);
353 }
354 if let Some(multiplexing) = http.multiplexing {
355 let http_version = multiplexing.then(|| "HTTP/2").unwrap_or("HTTP/1.1");
356 values.push(Http::VERSION.validated_assignment_fmt(&http_version)?);
360 }
361
362 Ok(values)
363}
364
365pub fn reinitialize(git_dir: &Path) -> CargoResult<()> {
368 fn init(path: &Path, bare: bool) -> CargoResult<()> {
369 let mut opts = git2::RepositoryInitOptions::new();
370 opts.external_template(false);
374 opts.bare(bare);
375 git2::Repository::init_opts(&path, &opts)?;
376 Ok(())
377 }
378 debug!("reinitializing git repo at {:?}", git_dir);
383 let tmp = git_dir.join("tmp");
384 let bare = !git_dir.ends_with(".git");
385 init(&tmp, false)?;
386 for entry in git_dir.read_dir()? {
387 let entry = entry?;
388 if entry.file_name().to_str() == Some("tmp") {
389 continue;
390 }
391 let path = entry.path();
392 drop(paths::remove_file(&path).or_else(|_| paths::remove_dir_all(&path)));
393 }
394 init(git_dir, bare)?;
395 paths::remove_dir_all(&tmp)?;
396 Ok(())
397}
398
399fn has_shallow_lock_file(err: &crate::sources::git::fetch::Error, repo_path: &Path) -> bool {
404 err.downcast_any_ref::<std::io::Error>()
405 .is_some_and(|err| err.kind() == std::io::ErrorKind::AlreadyExists)
406 && repo_path.join("shallow.lock").is_file()
407}
408
409#[tracing::instrument(skip(repo, gctx))]
410pub(super) fn fetch_with_gitoxide(
411 repo: &mut git2::Repository,
412 remote_url: &str,
413 refspecs: Vec<String>,
414 tags: bool,
415 shallow: gix::remote::fetch::Shallow,
416 gctx: &GlobalContext,
417) -> CargoResult<()> {
418 debug!(target: "git-fetch", backend = "gitoxide");
419
420 let git2_repo = repo;
421 let config_overrides = cargo_config_to_gitoxide_overrides(gctx)?;
422 let repo_reinitialized = AtomicBool::default();
423 let res = with_retry_and_progress(
424 git2_repo.path(),
425 gctx,
426 remote_url,
427 &|repo_path,
428 should_interrupt,
429 mut progress,
430 url_for_authentication: &mut dyn FnMut(&gix::bstr::BStr)| {
431 loop {
442 let res = open_repo(repo_path, config_overrides.clone(), OpenMode::ForFetch)
443 .and_then(|repo| {
444 debug!("initiating fetch of {refspecs:?} from {remote_url}");
445 let url_for_authentication = &mut *url_for_authentication;
446 let remote = repo
447 .remote_at(remote_url)?
448 .with_fetch_tags(if tags {
449 gix::remote::fetch::Tags::All
450 } else {
451 gix::remote::fetch::Tags::Included
452 })
453 .with_refspecs(
454 refspecs.iter().map(|s| s.as_str()),
455 gix::remote::Direction::Fetch,
456 )?;
457 let url = remote
458 .url(gix::remote::Direction::Fetch)
459 .expect("set at init")
460 .to_owned();
461 let connection = remote.connect(gix::remote::Direction::Fetch)?;
462 let mut authenticate = connection.configured_credentials(url)?;
463 let connection = connection.with_credentials(
464 move |action: gix::protocol::credentials::helper::Action| {
465 if let Some(url) = action.context().and_then(|gctx| {
466 gctx.url.as_ref().filter(|url| *url != remote_url)
467 }) {
468 url_for_authentication(url.as_ref());
469 }
470 authenticate(action)
471 .map_err(|err| gix::Error::from_error(CredentialError(err)))
472 },
473 );
474 let outcome = connection
475 .prepare_fetch(&mut progress, gix::remote::ref_map::Options::default())?
476 .with_shallow(shallow.clone())
477 .receive(&mut progress, should_interrupt)?;
478 Ok(outcome)
479 });
480 let err = match res {
481 Ok(_) => break,
482 Err(e) => e,
483 };
484 debug!("fetch failed: {}", err);
485
486 if !repo_reinitialized.load(Ordering::Relaxed)
487 && err.is_corrupted()
492 || has_shallow_lock_file(&err, repo_path)
493 {
494 repo_reinitialized.store(true, Ordering::Relaxed);
495 debug!(
496 "looks like this is a corrupt repository, reinitializing \
497 and trying again"
498 );
499 if reinitialize(repo_path).is_ok() {
500 continue;
501 }
502 }
503
504 return Err(err.into());
505 }
506 Ok(())
507 },
508 );
509 if repo_reinitialized.load(Ordering::Relaxed) {
510 *git2_repo = git2::Repository::open(git2_repo.path())?;
511 }
512 res
513}
514
515#[cfg(test)]
516mod tests {
517 use super::{CredentialError, amend_authentication_hints, has_shallow_lock_file};
518 use gix::error::ErrorExt;
519 use gix::protocol::transport::client::{AuthenticationRequired, Error};
520
521 #[test]
522 fn authentication_hints_preserve_causes_and_distinguish_network_errors() {
523 let missing = gix::error::unauthenticated("missing identity").raise();
524 let helper =
525 CredentialError(gix::error::message("Terminal prompts are disabled").raise()).raise();
526 let rejected = std::io::Error::new(
527 std::io::ErrorKind::PermissionDenied,
528 AuthenticationRequired::default(),
529 )
530 .raise();
531 let network = Error::Io(std::io::Error::from(std::io::ErrorKind::ConnectionReset)).raise();
532 for (err, hint) in [
533 (missing, "git's `credential.helper` support, but failed"),
534 (helper, "git's `credential.helper` support, but failed"),
535 (rejected, "credentials were incorrect"),
536 (network, "network failure seems to have happened"),
537 ] {
538 let err = amend_authentication_hints(
539 Err(err),
540 "https://example.com/repo",
541 Some("https://example.com/auth".into()),
542 )
543 .unwrap_err();
544 assert!(err.to_string().contains(hint));
545 assert!(err.downcast_ref::<gix::Error>().is_some());
546 }
547 let cancelled = CredentialError(
548 std::io::Error::from(std::io::ErrorKind::ConnectionReset)
549 .and_raise(gix::error::cancelled("cancelled")),
550 )
551 .raise();
552 assert!(cancelled.is_cancelled());
553 assert!(!cancelled.can_retry_lenient());
554 }
555
556 #[test]
557 fn shallow_lock_recovery_requires_existing_lock_and_matching_io_error() {
558 use gix::error::ErrorExt;
559
560 let dir = tempfile::TempDir::new().unwrap();
561 let locked = std::io::Error::from(std::io::ErrorKind::AlreadyExists).raise();
562 assert!(!has_shallow_lock_file(&locked, dir.path()));
563 std::fs::write(dir.path().join("shallow.lock"), []).unwrap();
564 assert!(has_shallow_lock_file(&locked, dir.path()));
565 let denied = std::io::Error::from(std::io::ErrorKind::PermissionDenied).raise();
566 assert!(!has_shallow_lock_file(&denied, dir.path()));
567 }
568}