Skip to main content

binary_install/
lib.rs

1//! Utilities for finding and installing binaries that we depend on.
2
3use anyhow::{anyhow, bail, Context, Result};
4use siphasher::sip::SipHasher13;
5use std::collections::HashSet;
6use std::env;
7use std::fs;
8use std::fs::File;
9use std::hash::{Hash, Hasher};
10use std::io::{self, Read};
11use std::path::{Path, PathBuf};
12
13/// Global cache for wasm-pack, currently containing binaries downloaded from
14/// urls like wasm-bindgen and such.
15#[derive(Debug)]
16pub struct Cache {
17    pub destination: PathBuf,
18}
19
20/// Representation of a downloaded tarball/zip
21#[derive(Debug, Clone)]
22pub struct Download {
23    root: PathBuf,
24}
25
26impl Cache {
27    /// Returns the global cache directory, as inferred from env vars and such.
28    ///
29    /// This function may return an error if a cache directory cannot be
30    /// determined.
31    pub fn new(name: &str) -> Result<Cache> {
32        let cache_name = format!(".{}", name);
33        let destination = dirs_next::cache_dir()
34            .map(|p| p.join(&cache_name))
35            .or_else(|| {
36                let home = dirs_next::home_dir()?;
37                Some(home.join(&cache_name))
38            })
39            .ok_or_else(|| anyhow!("couldn't find your home directory, is $HOME not set?"))?;
40        if !destination.exists() {
41            fs::create_dir_all(&destination)?;
42        }
43        Ok(Cache::at(&destination))
44    }
45
46    /// Creates a new cache specifically at a particular directory, useful in
47    /// testing and such.
48    pub fn at(path: &Path) -> Cache {
49        Cache {
50            destination: path.to_path_buf(),
51        }
52    }
53
54    /// Joins a path to the destination of this cache, returning the result
55    pub fn join(&self, path: &Path) -> PathBuf {
56        self.destination.join(path)
57    }
58
59    /// Downloads a tarball or zip file from the specified url, extracting it
60    /// to a directory with the version number and returning the directory that
61    /// the contents were extracted into.
62    ///
63    /// Note that this function requries that the contents of `url` never change
64    /// as the contents of the url are globally cached on the system and never
65    /// invalidated.
66    ///
67    /// The `name` is a human-readable name used to go into the folder name of
68    /// the destination, and `binaries` is a list of binaries expected to be at
69    /// the url. If the URL's extraction doesn't contain all the binaries this
70    /// function will return an error.
71    pub fn download_version(
72        &self,
73        install_permitted: bool,
74        name: &str,
75        binaries: &[&str],
76        url: &str,
77        version: &str,
78    ) -> Result<Option<Download>> {
79        self._download(install_permitted, name, binaries, url, Some(version))
80    }
81
82    /// Downloads a tarball or zip file from the specified url, extracting it
83    /// locally and returning the directory that the contents were extracted
84    /// into.
85    ///
86    /// Note that this function requries that the contents of `url` never change
87    /// as the contents of the url are globally cached on the system and never
88    /// invalidated.
89    ///
90    /// The `name` is a human-readable name used to go into the folder name of
91    /// the destination, and `binaries` is a list of binaries expected to be at
92    /// the url. If the URL's extraction doesn't contain all the binaries this
93    /// function will return an error.
94    pub fn download(
95        &self,
96        install_permitted: bool,
97        name: &str,
98        binaries: &[&str],
99        url: &str,
100    ) -> Result<Option<Download>> {
101        self._download(install_permitted, name, binaries, url, None)
102    }
103
104    fn _download(
105        &self,
106        install_permitted: bool,
107        name: &str,
108        binaries: &[&str],
109        url: &str,
110        version: Option<&str>,
111    ) -> Result<Option<Download>> {
112        let dirname = match version {
113            Some(version) => get_dirname(name, version),
114            None => hashed_dirname(url, name),
115        };
116
117        let destination = self.destination.join(&dirname);
118
119        let flock = File::create(self.destination.join(&format!(".{}.lock", dirname)))?;
120        flock.lock()?;
121
122        if destination.exists() {
123            return Ok(Some(Download { root: destination }));
124        }
125
126        if !install_permitted {
127            return Ok(None);
128        }
129
130        let data =
131            download_binary(&url).with_context(|| format!("failed to download from {}", url))?;
132
133        // Extract everything in a temporary directory in case we're ctrl-c'd.
134        // Don't want to leave around corrupted data!
135        let temp = self.destination.join(&format!(".{}", dirname));
136        drop(fs::remove_dir_all(&temp));
137        fs::create_dir_all(&temp)?;
138
139        if url.ends_with(".tar.gz") {
140            self.extract_tarball(&data, &temp, binaries)
141                .with_context(|| format!("failed to extract tarball from {}", url))?;
142        } else if url.ends_with(".zip") {
143            self.extract_zip(&data, &temp, binaries)
144                .with_context(|| format!("failed to extract zip from {}", url))?;
145        } else {
146            // panic instead of runtime error as it's a static violation to
147            // download a different kind of url, all urls should be encoded into
148            // the binary anyway
149            panic!("don't know how to extract {}", url)
150        }
151
152        // Now that everything is ready move this over to our destination and
153        // we're good to go.
154        fs::rename(&temp, &destination)?;
155
156        flock.unlock()?;
157        Ok(Some(Download { root: destination }))
158    }
159
160    /// Downloads a tarball from the specified url, extracting it locally and
161    /// returning the directory that the contents were extracted into.
162    ///
163    /// Similar to download; use this function for languages that doesn't emit a
164    /// binary.
165    pub fn download_artifact(&self, name: &str, url: &str) -> Result<Option<Download>> {
166        self._download_artifact(name, url, None)
167    }
168
169    /// Downloads a tarball from the specified url, extracting it locally and
170    /// returning the directory that the contents were extracted into.
171    ///
172    /// Similar to download; use this function for languages that doesn't emit a
173    /// binary.
174    pub fn download_artifact_version(
175        &self,
176        name: &str,
177        url: &str,
178        version: &str,
179    ) -> Result<Option<Download>> {
180        self._download_artifact(name, url, Some(version))
181    }
182
183    fn _download_artifact(
184        &self,
185        name: &str,
186        url: &str,
187        version: Option<&str>,
188    ) -> Result<Option<Download>> {
189        let dirname = match version {
190            Some(version) => get_dirname(name, version),
191            None => hashed_dirname(url, name),
192        };
193        let destination = self.destination.join(&dirname);
194
195        if destination.exists() {
196            return Ok(Some(Download { root: destination }));
197        }
198
199        let data =
200            download_binary(&url).with_context(|| format!("failed to download from {}", url))?;
201
202        // Extract everything in a temporary directory in case we're ctrl-c'd.
203        // Don't want to leave around corrupted data!
204        let temp = self.destination.join(&format!(".{}", &dirname));
205        drop(fs::remove_dir_all(&temp));
206        fs::create_dir_all(&temp)?;
207
208        if url.ends_with(".tar.gz") {
209            self.extract_tarball_all(&data, &temp)
210                .with_context(|| format!("failed to extract tarball from {}", url))?;
211        } else {
212            // panic instead of runtime error as it's a static violation to
213            // download a different kind of url, all urls should be encoded into
214            // the binary anyway
215            panic!("don't know how to extract {}", url)
216        }
217
218        // Now that everything is ready move this over to our destination and
219        // we're good to go.
220        fs::rename(&temp, &destination)?;
221        Ok(Some(Download { root: destination }))
222    }
223
224    /// simiar to extract_tarball, but preserves all the archive's content.
225    fn extract_tarball_all(&self, tarball: &[u8], dst: &Path) -> Result<()> {
226        let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(tarball));
227
228        for entry in archive.entries()? {
229            let mut entry = entry?;
230            let dest = match entry.path()?.file_stem() {
231                Some(_) => dst.join(entry.path()?.file_name().unwrap()),
232                _ => continue,
233            };
234            entry.unpack(dest)?;
235        }
236
237        Ok(())
238    }
239
240    fn extract_tarball(&self, tarball: &[u8], dst: &Path, binaries: &[&str]) -> Result<()> {
241        let mut binaries: HashSet<_> = binaries.iter().copied().collect();
242        let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(tarball));
243
244        for entry in archive.entries()? {
245            let mut entry = entry?;
246
247            let dest = match self.extract_binary(&entry.path()?, dst, &mut binaries) {
248                Some(dest) => dest,
249                _ => continue,
250            };
251
252            fs::create_dir_all(
253                dest.parent().ok_or_else(|| {
254                    anyhow!("could not get parent directory of {}", dest.display())
255                })?,
256            )?;
257
258            entry.unpack(dest)?;
259        }
260
261        if !binaries.is_empty() {
262            bail!(
263                "the tarball was missing expected executables: {}",
264                binaries
265                    .iter()
266                    .map(|s| s.to_string())
267                    .collect::<Vec<_>>()
268                    .join(", "),
269            )
270        }
271
272        Ok(())
273    }
274
275    fn extract_zip(&self, zip: &[u8], dst: &Path, binaries: &[&str]) -> Result<()> {
276        let mut binaries: HashSet<_> = binaries.iter().copied().collect();
277
278        let data = io::Cursor::new(zip);
279        let mut zip = zip::ZipArchive::new(data)?;
280
281        for i in 0..zip.len() {
282            let mut entry = zip.by_index(i).unwrap();
283            let entry_path = match entry.enclosed_name() {
284                Some(path) => path,
285                None => continue,
286            };
287
288            let dest = match self.extract_binary(&entry_path, dst, &mut binaries) {
289                Some(dest) => dest,
290                _ => continue,
291            };
292
293            fs::create_dir_all(
294                dest.parent().ok_or_else(|| {
295                    anyhow!("could not get parent directory of {}", dest.display())
296                })?,
297            )?;
298
299            let mut dest = bin_open_options().write(true).create_new(true).open(dest)?;
300            io::copy(&mut entry, &mut dest)?;
301        }
302
303        if !binaries.is_empty() {
304            bail!(
305                "the zip was missing expected executables: {}",
306                binaries
307                    .iter()
308                    .map(|s| s.to_string())
309                    .collect::<Vec<_>>()
310                    .join(", "),
311            )
312        }
313
314        return Ok(());
315
316        #[cfg(unix)]
317        fn bin_open_options() -> fs::OpenOptions {
318            use std::os::unix::fs::OpenOptionsExt;
319
320            let mut opts = fs::OpenOptions::new();
321            opts.mode(0o755);
322            opts
323        }
324
325        #[cfg(not(unix))]
326        fn bin_open_options() -> fs::OpenOptions {
327            fs::OpenOptions::new()
328        }
329    }
330
331    /// Works out whether or not to extract a given file from an archive.
332    ///
333    /// If a file should be extracted, this function removes its corresponding
334    /// entry from `binaries`, and returns the destination path where the file should be
335    /// extracted to.
336    fn extract_binary(
337        &self,
338        entry_path: &Path,
339        dst: &Path,
340        binaries: &mut HashSet<&str>,
341    ) -> Option<PathBuf> {
342        let file_stem = entry_path.file_stem()?;
343
344        for &binary in binaries.iter() {
345            if binary == file_stem {
346                binaries.remove(binary);
347                return Some(dst.join(entry_path.file_name()?));
348            } else if binary.contains('/') && entry_path.ends_with(binary) {
349                binaries.remove(binary);
350                return Some(dst.join(binary));
351            }
352        }
353        None
354    }
355}
356
357impl Download {
358    /// Manually constructs a download at the specified path
359    pub fn at(path: &Path) -> Download {
360        Download {
361            root: path.to_path_buf(),
362        }
363    }
364
365    /// Returns the path to the binary `name` within this download
366    pub fn binary(&self, name: &str) -> Result<PathBuf> {
367        use is_executable::IsExecutable;
368
369        let ret = self
370            .root
371            .join(name)
372            .with_extension(env::consts::EXE_EXTENSION);
373
374        if !ret.is_file() {
375            bail!("{} binary does not exist", ret.display());
376        }
377        if !ret.is_executable() || !has_executable_header(&ret) {
378            bail!("{} is not executable", ret.display());
379        }
380
381        return Ok(ret);
382
383        // is_executable only checks the extension against PATHEXT on Windows,
384        // so also check for the "MZ" magic bytes every Windows executable
385        // starts with, to catch empty or corrupted downloads.
386        #[cfg(windows)]
387        fn has_executable_header(path: &Path) -> bool {
388            let mut magic = [0; 2];
389            File::open(path)
390                .and_then(|mut file| file.read_exact(&mut magic))
391                .is_ok()
392                && &magic == b"MZ"
393        }
394
395        #[cfg(not(windows))]
396        fn has_executable_header(_path: &Path) -> bool {
397            true
398        }
399    }
400
401    /// Returns the path to the root
402    pub fn path(&self) -> PathBuf {
403        self.root.clone()
404    }
405}
406
407fn download_binary(url: &str) -> Result<Vec<u8>> {
408    let agent: ureq::Agent = ureq::Agent::config_builder()
409        .proxy(ureq::Proxy::try_from_env())
410        .http_status_as_error(false)
411        .build()
412        .into();
413    let response = agent.get(url).call()?;
414
415    let status_code = response.status();
416
417    if status_code.is_success() {
418        // note malicious server might exhaust our memory
419        let len: usize = response
420            .headers()
421            .get("Content-Length")
422            .and_then(|s| s.to_str().ok())
423            .and_then(|s| s.parse().ok())
424            .unwrap_or(0);
425        let mut bytes: Vec<u8> = Vec::with_capacity(len);
426        response.into_body().into_reader().read_to_end(&mut bytes)?;
427        Ok(bytes)
428    } else {
429        bail!(
430            "received a bad HTTP status code ({}) when requesting {}",
431            status_code.as_u16(),
432            url
433        )
434    }
435}
436
437fn get_dirname(name: &str, suffix: &str) -> String {
438    format!("{}-{}", name, suffix)
439}
440
441fn hashed_dirname(url: &str, name: &str) -> String {
442    let mut hasher = SipHasher13::new();
443    url.hash(&mut hasher);
444    let result = hasher.finish();
445    let hex = hex::encode(&[
446        (result >> 0) as u8,
447        (result >> 8) as u8,
448        (result >> 16) as u8,
449        (result >> 24) as u8,
450        (result >> 32) as u8,
451        (result >> 40) as u8,
452        (result >> 48) as u8,
453        (result >> 56) as u8,
454    ]);
455    format!("{}-{}", name, hex)
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461
462    #[test]
463    fn it_returns_same_hash_for_same_name_and_url() {
464        let name = "wasm-pack";
465        let url = "http://localhost:7878/wasm-pack-v0.6.0.tar.gz";
466
467        let first = hashed_dirname(url, name);
468        let second = hashed_dirname(url, name);
469
470        assert!(!first.is_empty());
471        assert!(!second.is_empty());
472        assert_eq!(first, second);
473    }
474
475    #[test]
476    fn it_returns_different_hashes_for_different_urls() {
477        let name = "wasm-pack";
478        let url = "http://localhost:7878/wasm-pack-v0.5.1.tar.gz";
479        let second_url = "http://localhost:7878/wasm-pack-v0.6.0.tar.gz";
480
481        let first = hashed_dirname(url, name);
482        let second = hashed_dirname(second_url, name);
483
484        assert_ne!(first, second);
485    }
486
487    #[test]
488    fn it_returns_same_dirname_for_same_name_and_version() {
489        let name = "wasm-pack";
490        let version = "0.6.0";
491
492        let first = get_dirname(name, version);
493        let second = get_dirname(name, version);
494
495        assert!(!first.is_empty());
496        assert!(!second.is_empty());
497        assert_eq!(first, second);
498    }
499
500    #[test]
501    fn it_returns_different_dirnames_for_different_versions() {
502        let name = "wasm-pack";
503        let version = "0.5.1";
504        let second_version = "0.6.0";
505
506        let first = get_dirname(name, version);
507        let second = get_dirname(name, second_version);
508
509        assert_ne!(first, second);
510    }
511
512    #[test]
513    fn it_returns_cache_dir() {
514        let name = "wasm-pack";
515        let cache = Cache::new(name);
516
517        let expected = dirs_next::cache_dir()
518            .unwrap()
519            .join(PathBuf::from(".".to_owned() + name));
520
521        assert!(cache.is_ok());
522        assert_eq!(cache.unwrap().destination, expected);
523    }
524
525    #[test]
526    fn it_returns_destination_if_binary_already_exists() {
527        use std::fs;
528
529        let binary_name = "wasm-pack";
530        let binaries = vec![binary_name];
531
532        let dir = tempfile::TempDir::new().unwrap();
533        let cache = Cache::at(dir.path());
534        let version = "0.6.0";
535        let url = &format!(
536            "{}/{}/v{}.tar.gz",
537            "http://localhost:7878", binary_name, version
538        );
539
540        let dirname = get_dirname(&binary_name, &version);
541        let full_path = dir.path().join(dirname);
542
543        // Create temporary directory and binary to simulate that
544        // a cached binary already exists.
545        fs::create_dir_all(full_path).unwrap();
546
547        let dl = cache.download_version(true, binary_name, &binaries, url, version);
548
549        assert!(dl.is_ok());
550        assert!(dl.unwrap().is_some())
551    }
552}