Skip to main content

cargo/core/
package.rs

1use std::cell::{Cell, Ref, RefCell};
2use std::cmp::Ordering;
3use std::collections::{HashMap, HashSet};
4use std::fmt;
5use std::hash;
6use std::mem;
7use std::path::{Path, PathBuf};
8use std::time::{Duration, Instant};
9
10use bytesize::ByteSize;
11use curl::easy::{Easy, HttpVersion};
12use curl::multi::{EasyHandle, Multi};
13use failure::ResultExt;
14use lazycell::LazyCell;
15use log::{debug, warn};
16use semver::Version;
17use serde::ser;
18use serde::Serialize;
19
20use crate::core::interning::InternedString;
21use crate::core::source::MaybePackage;
22use crate::core::{Dependency, Manifest, PackageId, SourceId, Target};
23use crate::core::{FeatureMap, SourceMap, Summary};
24use crate::ops;
25use crate::util::errors::{CargoResult, CargoResultExt, HttpNot200};
26use crate::util::network::Retry;
27use crate::util::{self, internal, lev_distance, Config, Progress, ProgressStyle};
28
29/// Information about a package that is available somewhere in the file system.
30///
31/// A package is a `Cargo.toml` file plus all the files that are part of it.
32// TODO: Is manifest_path a relic?
33#[derive(Clone)]
34pub struct Package {
35    /// The package's manifest
36    manifest: Manifest,
37    /// The root of the package
38    manifest_path: PathBuf,
39}
40
41impl Ord for Package {
42    fn cmp(&self, other: &Package) -> Ordering {
43        self.package_id().cmp(&other.package_id())
44    }
45}
46
47impl PartialOrd for Package {
48    fn partial_cmp(&self, other: &Package) -> Option<Ordering> {
49        Some(self.cmp(other))
50    }
51}
52
53/// A Package in a form where `Serialize` can be derived.
54#[derive(Serialize)]
55struct SerializedPackage<'a> {
56    name: &'a str,
57    version: &'a Version,
58    id: PackageId,
59    license: Option<&'a str>,
60    license_file: Option<&'a str>,
61    description: Option<&'a str>,
62    source: SourceId,
63    dependencies: &'a [Dependency],
64    targets: Vec<&'a Target>,
65    features: &'a FeatureMap,
66    manifest_path: &'a Path,
67    metadata: Option<&'a toml::Value>,
68    authors: &'a [String],
69    categories: &'a [String],
70    keywords: &'a [String],
71    readme: Option<&'a str>,
72    repository: Option<&'a str>,
73    edition: &'a str,
74    links: Option<&'a str>,
75    #[serde(skip_serializing_if = "Option::is_none")]
76    metabuild: Option<&'a Vec<String>>,
77}
78
79impl ser::Serialize for Package {
80    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
81    where
82        S: ser::Serializer,
83    {
84        let summary = self.manifest.summary();
85        let package_id = summary.package_id();
86        let manmeta = self.manifest.metadata();
87        let license = manmeta.license.as_ref().map(String::as_ref);
88        let license_file = manmeta.license_file.as_ref().map(String::as_ref);
89        let description = manmeta.description.as_ref().map(String::as_ref);
90        let authors = manmeta.authors.as_ref();
91        let categories = manmeta.categories.as_ref();
92        let keywords = manmeta.keywords.as_ref();
93        let readme = manmeta.readme.as_ref().map(String::as_ref);
94        let repository = manmeta.repository.as_ref().map(String::as_ref);
95        // Filter out metabuild targets. They are an internal implementation
96        // detail that is probably not relevant externally. There's also not a
97        // real path to show in `src_path`, and this avoids changing the format.
98        let targets: Vec<&Target> = self
99            .manifest
100            .targets()
101            .iter()
102            .filter(|t| t.src_path().is_path())
103            .collect();
104
105        SerializedPackage {
106            name: &*package_id.name(),
107            version: &package_id.version(),
108            id: package_id,
109            license,
110            license_file,
111            description,
112            source: summary.source_id(),
113            dependencies: summary.dependencies(),
114            targets,
115            features: summary.features(),
116            manifest_path: &self.manifest_path,
117            metadata: self.manifest.custom_metadata(),
118            authors,
119            categories,
120            keywords,
121            readme,
122            repository,
123            edition: &self.manifest.edition().to_string(),
124            links: self.manifest.links(),
125            metabuild: self.manifest.metabuild(),
126        }
127        .serialize(s)
128    }
129}
130
131impl Package {
132    /// Create a package from a manifest and its location
133    pub fn new(manifest: Manifest, manifest_path: &Path) -> Package {
134        Package {
135            manifest,
136            manifest_path: manifest_path.to_path_buf(),
137        }
138    }
139
140    /// Get the manifest dependencies
141    pub fn dependencies(&self) -> &[Dependency] {
142        self.manifest.dependencies()
143    }
144    /// Get the manifest
145    pub fn manifest(&self) -> &Manifest {
146        &self.manifest
147    }
148    /// Get the path to the manifest
149    pub fn manifest_path(&self) -> &Path {
150        &self.manifest_path
151    }
152    /// Get the name of the package
153    pub fn name(&self) -> InternedString {
154        self.package_id().name()
155    }
156    /// Get the PackageId object for the package (fully defines a package)
157    pub fn package_id(&self) -> PackageId {
158        self.manifest.package_id()
159    }
160    /// Get the root folder of the package
161    pub fn root(&self) -> &Path {
162        self.manifest_path.parent().unwrap()
163    }
164    /// Get the summary for the package
165    pub fn summary(&self) -> &Summary {
166        self.manifest.summary()
167    }
168    /// Get the targets specified in the manifest
169    pub fn targets(&self) -> &[Target] {
170        self.manifest.targets()
171    }
172    /// Get the current package version
173    pub fn version(&self) -> &Version {
174        self.package_id().version()
175    }
176    /// Get the package authors
177    pub fn authors(&self) -> &Vec<String> {
178        &self.manifest.metadata().authors
179    }
180    /// Whether the package is set to publish
181    pub fn publish(&self) -> &Option<Vec<String>> {
182        self.manifest.publish()
183    }
184
185    /// Whether the package uses a custom build script for any target
186    pub fn has_custom_build(&self) -> bool {
187        self.targets().iter().any(|t| t.is_custom_build())
188    }
189
190    pub fn find_closest_target(
191        &self,
192        target: &str,
193        is_expected_kind: fn(&Target) -> bool,
194    ) -> Option<&Target> {
195        let targets = self.targets();
196
197        let matches = targets
198            .iter()
199            .filter(|t| is_expected_kind(t))
200            .map(|t| (lev_distance(target, t.name()), t))
201            .filter(|&(d, _)| d < 4);
202        matches.min_by_key(|t| t.0).map(|t| t.1)
203    }
204
205    pub fn map_source(self, to_replace: SourceId, replace_with: SourceId) -> Package {
206        Package {
207            manifest: self.manifest.map_source(to_replace, replace_with),
208            manifest_path: self.manifest_path,
209        }
210    }
211
212    pub fn to_registry_toml(&self, config: &Config) -> CargoResult<String> {
213        let manifest = self.manifest().original().prepare_for_publish(config)?;
214        let toml = toml::to_string(&manifest)?;
215        Ok(format!(
216            "\
217             # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO\n\
218             #\n\
219             # When uploading crates to the registry Cargo will automatically\n\
220             # \"normalize\" Cargo.toml files for maximal compatibility\n\
221             # with all versions of Cargo and also rewrite `path` dependencies\n\
222             # to registry (e.g. crates.io) dependencies\n\
223             #\n\
224             # If you believe there's an error in this file please file an\n\
225             # issue against the rust-lang/cargo repository. If you're\n\
226             # editing this file be aware that the upstream Cargo.toml\n\
227             # will likely look very different (and much more reasonable)\n\
228             \n\
229             {}\
230             ",
231            toml
232        ))
233    }
234}
235
236impl fmt::Display for Package {
237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238        write!(f, "{}", self.summary().package_id())
239    }
240}
241
242impl fmt::Debug for Package {
243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244        f.debug_struct("Package")
245            .field("id", &self.summary().package_id())
246            .field("..", &"..")
247            .finish()
248    }
249}
250
251impl PartialEq for Package {
252    fn eq(&self, other: &Package) -> bool {
253        self.package_id() == other.package_id()
254    }
255}
256
257impl Eq for Package {}
258
259impl hash::Hash for Package {
260    fn hash<H: hash::Hasher>(&self, into: &mut H) {
261        self.package_id().hash(into)
262    }
263}
264
265pub struct PackageSet<'cfg> {
266    packages: HashMap<PackageId, LazyCell<Package>>,
267    sources: RefCell<SourceMap<'cfg>>,
268    config: &'cfg Config,
269    multi: Multi,
270    downloading: Cell<bool>,
271    multiplexing: bool,
272}
273
274pub struct Downloads<'a, 'cfg: 'a> {
275    set: &'a PackageSet<'cfg>,
276    pending: HashMap<usize, (Download<'cfg>, EasyHandle)>,
277    pending_ids: HashSet<PackageId>,
278    results: Vec<(usize, Result<(), curl::Error>)>,
279    next: usize,
280    progress: RefCell<Option<Progress<'cfg>>>,
281    downloads_finished: usize,
282    downloaded_bytes: u64,
283    largest: (u64, String),
284    start: Instant,
285    success: bool,
286
287    /// Timeout management, both of timeout thresholds as well as whether or not
288    /// our connection has timed out (and accompanying message if it has).
289    ///
290    /// Note that timeout management is done manually here instead of in libcurl
291    /// because we want to apply timeouts to an entire batch of operations, not
292    /// any one particular single operatino
293    timeout: ops::HttpTimeout, // timeout configuration
294    updated_at: Cell<Instant>,       // last time we received bytes
295    next_speed_check: Cell<Instant>, // if threshold isn't 0 by this time, error
296    next_speed_check_bytes_threshold: Cell<u64>, // decremented when we receive bytes
297}
298
299struct Download<'cfg> {
300    /// Token for this download, used as the key of the `Downloads::pending` map
301    /// and stored in `EasyHandle` as well.
302    token: usize,
303
304    /// Package that we're downloading
305    id: PackageId,
306
307    /// Actual downloaded data, updated throughout the lifetime of this download
308    data: RefCell<Vec<u8>>,
309
310    /// The URL that we're downloading from, cached here for error messages and
311    /// reenqueuing.
312    url: String,
313
314    /// A descriptive string to print when we've finished downloading this crate
315    descriptor: String,
316
317    /// Statistics updated from the progress callback in libcurl
318    total: Cell<u64>,
319    current: Cell<u64>,
320
321    /// The moment we started this transfer at
322    start: Instant,
323    timed_out: Cell<Option<String>>,
324
325    /// Logic used to track retrying this download if it's a spurious failure.
326    retry: Retry<'cfg>,
327}
328
329impl<'cfg> PackageSet<'cfg> {
330    pub fn new(
331        package_ids: &[PackageId],
332        sources: SourceMap<'cfg>,
333        config: &'cfg Config,
334    ) -> CargoResult<PackageSet<'cfg>> {
335        // We've enabled the `http2` feature of `curl` in Cargo, so treat
336        // failures here as fatal as it would indicate a build-time problem.
337        //
338        // Note that the multiplexing support is pretty new so we're having it
339        // off-by-default temporarily.
340        //
341        // Also note that pipelining is disabled as curl authors have indicated
342        // that it's buggy, and we've empirically seen that it's buggy with HTTP
343        // proxies.
344        let mut multi = Multi::new();
345        let multiplexing = config
346            .get::<Option<bool>>("http.multiplexing")?
347            .unwrap_or(true);
348        multi
349            .pipelining(false, multiplexing)
350            .chain_err(|| "failed to enable multiplexing/pipelining in curl")?;
351
352        // let's not flood crates.io with connections
353        multi.set_max_host_connections(2)?;
354
355        Ok(PackageSet {
356            packages: package_ids
357                .iter()
358                .map(|&id| (id, LazyCell::new()))
359                .collect(),
360            sources: RefCell::new(sources),
361            config,
362            multi,
363            downloading: Cell::new(false),
364            multiplexing,
365        })
366    }
367
368    pub fn package_ids<'a>(&'a self) -> impl Iterator<Item = PackageId> + 'a {
369        self.packages.keys().cloned()
370    }
371
372    pub fn enable_download<'a>(&'a self) -> CargoResult<Downloads<'a, 'cfg>> {
373        assert!(!self.downloading.replace(true));
374        let timeout = ops::HttpTimeout::new(self.config)?;
375        Ok(Downloads {
376            start: Instant::now(),
377            set: self,
378            next: 0,
379            pending: HashMap::new(),
380            pending_ids: HashSet::new(),
381            results: Vec::new(),
382            progress: RefCell::new(Some(Progress::with_style(
383                "Downloading",
384                ProgressStyle::Ratio,
385                self.config,
386            ))),
387            downloads_finished: 0,
388            downloaded_bytes: 0,
389            largest: (0, String::new()),
390            success: false,
391            updated_at: Cell::new(Instant::now()),
392            timeout,
393            next_speed_check: Cell::new(Instant::now()),
394            next_speed_check_bytes_threshold: Cell::new(0),
395        })
396    }
397
398    pub fn get_one(&self, id: PackageId) -> CargoResult<&Package> {
399        Ok(self.get_many(Some(id))?.remove(0))
400    }
401
402    pub fn get_many(&self, ids: impl IntoIterator<Item = PackageId>) -> CargoResult<Vec<&Package>> {
403        let mut pkgs = Vec::new();
404        let mut downloads = self.enable_download()?;
405        for id in ids {
406            pkgs.extend(downloads.start(id)?);
407        }
408        while downloads.remaining() > 0 {
409            pkgs.push(downloads.wait()?);
410        }
411        downloads.success = true;
412        Ok(pkgs)
413    }
414
415    pub fn sources(&self) -> Ref<'_, SourceMap<'cfg>> {
416        self.sources.borrow()
417    }
418}
419
420// When dynamically linked against libcurl, we want to ignore some failures
421// when using old versions that don't support certain features.
422macro_rules! try_old_curl {
423    ($e:expr, $msg:expr) => {
424        let result = $e;
425        if cfg!(target_os = "macos") {
426            if let Err(e) = result {
427                warn!("ignoring libcurl {} error: {}", $msg, e);
428            }
429        } else {
430            result.with_context(|_| {
431                failure::format_err!("failed to enable {}, is curl not built right?", $msg)
432            })?;
433        }
434    };
435}
436
437impl<'a, 'cfg> Downloads<'a, 'cfg> {
438    /// Starts to download the package for the `id` specified.
439    ///
440    /// Returns `None` if the package is queued up for download and will
441    /// eventually be returned from `wait_for_download`. Returns `Some(pkg)` if
442    /// the package is ready and doesn't need to be downloaded.
443    pub fn start(&mut self, id: PackageId) -> CargoResult<Option<&'a Package>> {
444        // First up see if we've already cached this package, in which case
445        // there's nothing to do.
446        let slot = self
447            .set
448            .packages
449            .get(&id)
450            .ok_or_else(|| internal(format!("couldn't find `{}` in package set", id)))?;
451        if let Some(pkg) = slot.borrow() {
452            return Ok(Some(pkg));
453        }
454
455        // Ask the original source fo this `PackageId` for the corresponding
456        // package. That may immediately come back and tell us that the package
457        // is ready, or it could tell us that it needs to be downloaded.
458        let mut sources = self.set.sources.borrow_mut();
459        let source = sources
460            .get_mut(id.source_id())
461            .ok_or_else(|| internal(format!("couldn't find source for `{}`", id)))?;
462        let pkg = source
463            .download(id)
464            .chain_err(|| failure::format_err!("unable to get packages from source"))?;
465        let (url, descriptor) = match pkg {
466            MaybePackage::Ready(pkg) => {
467                debug!("{} doesn't need a download", id);
468                assert!(slot.fill(pkg).is_ok());
469                return Ok(Some(slot.borrow().unwrap()));
470            }
471            MaybePackage::Download { url, descriptor } => (url, descriptor),
472        };
473
474        // Ok we're going to download this crate, so let's set up all our
475        // internal state and hand off an `Easy` handle to our libcurl `Multi`
476        // handle. This won't actually start the transfer, but later it'll
477        // hapen during `wait_for_download`
478        let token = self.next;
479        self.next += 1;
480        debug!("downloading {} as {}", id, token);
481        assert!(self.pending_ids.insert(id));
482
483        let (mut handle, _timeout) = ops::http_handle_and_timeout(self.set.config)?;
484        handle.get(true)?;
485        handle.url(&url)?;
486        handle.follow_location(true)?; // follow redirects
487
488        // Enable HTTP/2 to be used as it'll allow true multiplexing which makes
489        // downloads much faster.
490        //
491        // Currently Cargo requests the `http2` feature of the `curl` crate
492        // which means it should always be built in. On OSX, however, we ship
493        // cargo still linked against the system libcurl. Building curl with
494        // ALPN support for HTTP/2 requires newer versions of OSX (the
495        // SecureTransport API) than we want to ship Cargo for. By linking Cargo
496        // against the system libcurl then older curl installations won't use
497        // HTTP/2 but newer ones will. All that to basically say we ignore
498        // errors here on OSX, but consider this a fatal error to not activate
499        // HTTP/2 on all other platforms.
500        if self.set.multiplexing {
501            try_old_curl!(handle.http_version(HttpVersion::V2), "HTTP2");
502        } else {
503            handle.http_version(HttpVersion::V11)?;
504        }
505
506        // This is an option to `libcurl` which indicates that if there's a
507        // bunch of parallel requests to the same host they all wait until the
508        // pipelining status of the host is known. This means that we won't
509        // initiate dozens of connections to crates.io, but rather only one.
510        // Once the main one is opened we realized that pipelining is possible
511        // and multiplexing is possible with static.crates.io. All in all this
512        // reduces the number of connections done to a more manageable state.
513        try_old_curl!(handle.pipewait(true), "pipewait");
514
515        handle.write_function(move |buf| {
516            debug!("{} - {} bytes of data", token, buf.len());
517            tls::with(|downloads| {
518                if let Some(downloads) = downloads {
519                    downloads.pending[&token]
520                        .0
521                        .data
522                        .borrow_mut()
523                        .extend_from_slice(buf);
524                }
525            });
526            Ok(buf.len())
527        })?;
528
529        handle.progress(true)?;
530        handle.progress_function(move |dl_total, dl_cur, _, _| {
531            tls::with(|downloads| match downloads {
532                Some(d) => d.progress(token, dl_total as u64, dl_cur as u64),
533                None => false,
534            })
535        })?;
536
537        // If the progress bar isn't enabled then it may be awhile before the
538        // first crate finishes downloading so we inform immediately that we're
539        // downloading crates here.
540        if self.downloads_finished == 0
541            && self.pending.is_empty()
542            && !self.progress.borrow().as_ref().unwrap().is_enabled()
543        {
544            self.set
545                .config
546                .shell()
547                .status("Downloading", "crates ...")?;
548        }
549
550        let dl = Download {
551            token,
552            data: RefCell::new(Vec::new()),
553            id,
554            url,
555            descriptor,
556            total: Cell::new(0),
557            current: Cell::new(0),
558            start: Instant::now(),
559            timed_out: Cell::new(None),
560            retry: Retry::new(self.set.config)?,
561        };
562        self.enqueue(dl, handle)?;
563        self.tick(WhyTick::DownloadStarted)?;
564
565        Ok(None)
566    }
567
568    /// Returns the number of crates that are still downloading
569    pub fn remaining(&self) -> usize {
570        self.pending.len()
571    }
572
573    /// Blocks the current thread waiting for a package to finish downloading.
574    ///
575    /// This method will wait for a previously enqueued package to finish
576    /// downloading and return a reference to it after it's done downloading.
577    ///
578    /// # Panics
579    ///
580    /// This function will panic if there are no remaining downloads.
581    pub fn wait(&mut self) -> CargoResult<&'a Package> {
582        let (dl, data) = loop {
583            assert_eq!(self.pending.len(), self.pending_ids.len());
584            let (token, result) = self.wait_for_curl()?;
585            debug!("{} finished with {:?}", token, result);
586
587            let (mut dl, handle) = self
588                .pending
589                .remove(&token)
590                .expect("got a token for a non-in-progress transfer");
591            let data = mem::replace(&mut *dl.data.borrow_mut(), Vec::new());
592            let mut handle = self.set.multi.remove(handle)?;
593            self.pending_ids.remove(&dl.id);
594
595            // Check if this was a spurious error. If it was a spurious error
596            // then we want to re-enqueue our request for another attempt and
597            // then we wait for another request to finish.
598            let ret = {
599                let timed_out = &dl.timed_out;
600                let url = &dl.url;
601                dl.retry
602                    .r#try(|| {
603                        if let Err(e) = result {
604                            // If this error is "aborted by callback" then that's
605                            // probably because our progress callback aborted due to
606                            // a timeout. We'll find out by looking at the
607                            // `timed_out` field, looking for a descriptive message.
608                            // If one is found we switch the error code (to ensure
609                            // it's flagged as spurious) and then attach our extra
610                            // information to the error.
611                            if !e.is_aborted_by_callback() {
612                                return Err(e.into());
613                            }
614
615                            return Err(match timed_out.replace(None) {
616                                Some(msg) => {
617                                    let code = curl_sys::CURLE_OPERATION_TIMEDOUT;
618                                    let mut err = curl::Error::new(code);
619                                    err.set_extra(msg);
620                                    err
621                                }
622                                None => e,
623                            }
624                            .into());
625                        }
626
627                        let code = handle.response_code()?;
628                        if code != 200 && code != 0 {
629                            let url = handle.effective_url()?.unwrap_or(url);
630                            return Err(HttpNot200 {
631                                code,
632                                url: url.to_string(),
633                            }
634                            .into());
635                        }
636                        Ok(())
637                    })
638                    .chain_err(|| format!("failed to download from `{}`", dl.url))?
639            };
640            match ret {
641                Some(()) => break (dl, data),
642                None => {
643                    self.pending_ids.insert(dl.id);
644                    self.enqueue(dl, handle)?
645                }
646            }
647        };
648
649        // If the progress bar isn't enabled then we still want to provide some
650        // semblance of progress of how we're downloading crates, and if the
651        // progress bar is enabled this provides a good log of what's happening.
652        self.progress.borrow_mut().as_mut().unwrap().clear();
653        self.set
654            .config
655            .shell()
656            .status("Downloaded", &dl.descriptor)?;
657
658        self.downloads_finished += 1;
659        self.downloaded_bytes += dl.total.get();
660        if dl.total.get() > self.largest.0 {
661            self.largest = (dl.total.get(), dl.id.name().to_string());
662        }
663
664        // We're about to synchronously extract the crate below. While we're
665        // doing that our download progress won't actually be updated, nor do we
666        // have a great view into the progress of the extraction. Let's prepare
667        // the user for this CPU-heavy step if it looks like it'll take some
668        // time to do so.
669        if dl.total.get() < ByteSize::kb(400).0 {
670            self.tick(WhyTick::DownloadFinished)?;
671        } else {
672            self.tick(WhyTick::Extracting(&dl.id.name()))?;
673        }
674
675        // Inform the original source that the download is finished which
676        // should allow us to actually get the package and fill it in now.
677        let mut sources = self.set.sources.borrow_mut();
678        let source = sources
679            .get_mut(dl.id.source_id())
680            .ok_or_else(|| internal(format!("couldn't find source for `{}`", dl.id)))?;
681        let start = Instant::now();
682        let pkg = source.finish_download(dl.id, data)?;
683
684        // Assume that no time has passed while we were calling
685        // `finish_download`, update all speed checks and timeout limits of all
686        // active downloads to make sure they don't fire because of a slowly
687        // extracted tarball.
688        let finish_dur = start.elapsed();
689        self.updated_at.set(self.updated_at.get() + finish_dur);
690        self.next_speed_check
691            .set(self.next_speed_check.get() + finish_dur);
692
693        let slot = &self.set.packages[&dl.id];
694        assert!(slot.fill(pkg).is_ok());
695        Ok(slot.borrow().unwrap())
696    }
697
698    fn enqueue(&mut self, dl: Download<'cfg>, handle: Easy) -> CargoResult<()> {
699        let mut handle = self.set.multi.add(handle)?;
700        let now = Instant::now();
701        handle.set_token(dl.token)?;
702        self.updated_at.set(now);
703        self.next_speed_check.set(now + self.timeout.dur);
704        self.next_speed_check_bytes_threshold
705            .set(u64::from(self.timeout.low_speed_limit));
706        dl.timed_out.set(None);
707        dl.current.set(0);
708        dl.total.set(0);
709        self.pending.insert(dl.token, (dl, handle));
710        Ok(())
711    }
712
713    fn wait_for_curl(&mut self) -> CargoResult<(usize, Result<(), curl::Error>)> {
714        // This is the main workhorse loop. We use libcurl's portable `wait`
715        // method to actually perform blocking. This isn't necessarily too
716        // efficient in terms of fd management, but we should only be juggling
717        // a few anyway.
718        //
719        // Here we start off by asking the `multi` handle to do some work via
720        // the `perform` method. This will actually do I/O work (nonblocking)
721        // and attempt to make progress. Afterwards we ask about the `messages`
722        // contained in the handle which will inform us if anything has finished
723        // transferring.
724        //
725        // If we've got a finished transfer after all that work we break out
726        // and process the finished transfer at the end. Otherwise we need to
727        // actually block waiting for I/O to happen, which we achieve with the
728        // `wait` method on `multi`.
729        loop {
730            let n = tls::set(self, || {
731                self.set
732                    .multi
733                    .perform()
734                    .chain_err(|| "failed to perform http requests")
735            })?;
736            debug!("handles remaining: {}", n);
737            let results = &mut self.results;
738            let pending = &self.pending;
739            self.set.multi.messages(|msg| {
740                let token = msg.token().expect("failed to read token");
741                let handle = &pending[&token].1;
742                if let Some(result) = msg.result_for(&handle) {
743                    results.push((token, result));
744                } else {
745                    debug!("message without a result (?)");
746                }
747            });
748
749            if let Some(pair) = results.pop() {
750                break Ok(pair);
751            }
752            assert!(!self.pending.is_empty());
753            let timeout = self
754                .set
755                .multi
756                .get_timeout()?
757                .unwrap_or_else(|| Duration::new(5, 0));
758            self.set
759                .multi
760                .wait(&mut [], timeout)
761                .chain_err(|| "failed to wait on curl `Multi`")?;
762        }
763    }
764
765    fn progress(&self, token: usize, total: u64, cur: u64) -> bool {
766        let dl = &self.pending[&token].0;
767        dl.total.set(total);
768        let now = Instant::now();
769        if cur != dl.current.get() {
770            let delta = cur - dl.current.get();
771            let threshold = self.next_speed_check_bytes_threshold.get();
772
773            dl.current.set(cur);
774            self.updated_at.set(now);
775
776            if delta >= threshold {
777                self.next_speed_check.set(now + self.timeout.dur);
778                self.next_speed_check_bytes_threshold
779                    .set(u64::from(self.timeout.low_speed_limit));
780            } else {
781                self.next_speed_check_bytes_threshold.set(threshold - delta);
782            }
783        }
784        if self.tick(WhyTick::DownloadUpdate).is_err() {
785            return false;
786        }
787
788        // If we've spent too long not actually receiving any data we time out.
789        if now - self.updated_at.get() > self.timeout.dur {
790            self.updated_at.set(now);
791            let msg = format!(
792                "failed to download any data for `{}` within {}s",
793                dl.id,
794                self.timeout.dur.as_secs()
795            );
796            dl.timed_out.set(Some(msg));
797            return false;
798        }
799
800        // If we reached the point in time that we need to check our speed
801        // limit, see if we've transferred enough data during this threshold. If
802        // it fails this check then we fail because the download is going too
803        // slowly.
804        if now >= self.next_speed_check.get() {
805            self.next_speed_check.set(now + self.timeout.dur);
806            assert!(self.next_speed_check_bytes_threshold.get() > 0);
807            let msg = format!(
808                "download of `{}` failed to transfer more \
809                 than {} bytes in {}s",
810                dl.id,
811                self.timeout.low_speed_limit,
812                self.timeout.dur.as_secs()
813            );
814            dl.timed_out.set(Some(msg));
815            return false;
816        }
817
818        true
819    }
820
821    fn tick(&self, why: WhyTick<'_>) -> CargoResult<()> {
822        let mut progress = self.progress.borrow_mut();
823        let progress = progress.as_mut().unwrap();
824
825        if let WhyTick::DownloadUpdate = why {
826            if !progress.update_allowed() {
827                return Ok(());
828            }
829        }
830        let pending = self.pending.len();
831        let mut msg = if pending == 1 {
832            format!("{} crate", pending)
833        } else {
834            format!("{} crates", pending)
835        };
836        match why {
837            WhyTick::Extracting(krate) => {
838                msg.push_str(&format!(", extracting {} ...", krate));
839            }
840            _ => {
841                let mut dur = Duration::new(0, 0);
842                let mut remaining = 0;
843                for (dl, _) in self.pending.values() {
844                    dur += dl.start.elapsed();
845                    // If the total/current look weird just throw out the data
846                    // point, sounds like curl has more to learn before we have
847                    // the true information.
848                    if dl.total.get() >= dl.current.get() {
849                        remaining += dl.total.get() - dl.current.get();
850                    }
851                }
852                if remaining > 0 && dur > Duration::from_millis(500) {
853                    msg.push_str(&format!(", remaining bytes: {}", ByteSize(remaining)));
854                }
855            }
856        }
857        progress.print_now(&msg)
858    }
859}
860
861#[derive(Copy, Clone)]
862enum WhyTick<'a> {
863    DownloadStarted,
864    DownloadUpdate,
865    DownloadFinished,
866    Extracting(&'a str),
867}
868
869impl<'a, 'cfg> Drop for Downloads<'a, 'cfg> {
870    fn drop(&mut self) {
871        self.set.downloading.set(false);
872        let progress = self.progress.get_mut().take().unwrap();
873        // Don't print a download summary if we're not using a progress bar,
874        // we've already printed lots of `Downloading...` items.
875        if !progress.is_enabled() {
876            return;
877        }
878        // If we didn't download anything, no need for a summary
879        if self.downloads_finished == 0 {
880            return;
881        }
882        // If an error happened, let's not clutter up the output
883        if !self.success {
884            return;
885        }
886        let mut status = format!(
887            "{} crates ({}) in {}",
888            self.downloads_finished,
889            ByteSize(self.downloaded_bytes),
890            util::elapsed(self.start.elapsed())
891        );
892        if self.largest.0 > ByteSize::mb(1).0 {
893            status.push_str(&format!(
894                " (largest was `{}` at {})",
895                self.largest.1,
896                ByteSize(self.largest.0),
897            ));
898        }
899        // Clear progress before displaying final summary.
900        drop(progress);
901        drop(self.set.config.shell().status("Downloaded", status));
902    }
903}
904
905mod tls {
906    use std::cell::Cell;
907
908    use super::Downloads;
909
910    thread_local!(static PTR: Cell<usize> = Cell::new(0));
911
912    pub(crate) fn with<R>(f: impl FnOnce(Option<&Downloads<'_, '_>>) -> R) -> R {
913        let ptr = PTR.with(|p| p.get());
914        if ptr == 0 {
915            f(None)
916        } else {
917            unsafe { f(Some(&*(ptr as *const Downloads<'_, '_>))) }
918        }
919    }
920
921    pub(crate) fn set<R>(dl: &Downloads<'_, '_>, f: impl FnOnce() -> R) -> R {
922        struct Reset<'a, T: Copy>(&'a Cell<T>, T);
923
924        impl<'a, T: Copy> Drop for Reset<'a, T> {
925            fn drop(&mut self) {
926                self.0.set(self.1);
927            }
928        }
929
930        PTR.with(|p| {
931            let _reset = Reset(p, p.get());
932            p.set(dl as *const Downloads<'_, '_> as usize);
933            f()
934        })
935    }
936}