summaryrefslogtreecommitdiffhomepage
path: root/mullvad-update/src/client/app.rs
blob: 6b894dd2013af149c4bd3709db4d42476dc8cf31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#![cfg(any(target_os = "macos", target_os = "windows"))]

//! This module implements the flow of downloading and verifying the app.

use std::{ffi::OsString, path::PathBuf, time::Duration};

use tokio::{process::Command, time::timeout};

use crate::{
    fetch::{self, ProgressUpdater},
    verify::{AppVerifier, Sha256Verifier},
};

#[derive(Debug, thiserror::Error)]
pub enum DownloadError {
    #[error("Failed to download app")]
    FetchApp(#[source] anyhow::Error),
    #[error("Failed to verify app")]
    Verification(#[source] anyhow::Error),
    #[error("Failed to launch app")]
    Launch(#[source] std::io::Error),
    #[error("Installer exited with error: {0}")]
    InstallExited(std::process::ExitStatus),
    #[error("Installer failed on child.wait(): {0}")]
    InstallFailed(std::io::Error),
}

/// Parameters required to construct an [AppDownloader].
#[derive(Clone)]
pub struct AppDownloaderParameters<AppProgress> {
    pub app_version: mullvad_version::Version,
    pub app_url: String,
    pub app_size: usize,
    pub app_progress: AppProgress,
    pub app_sha256: [u8; 32],
    /// Directory to store the installer in.
    /// Ensure that this has proper permissions set.
    pub cache_dir: PathBuf,
}

/// See the [module-level documentation](self).
#[async_trait::async_trait]
pub trait AppDownloader: Send {
    /// Download the app binary.
    async fn download_executable(&mut self) -> Result<(), DownloadError>;

    /// Verify the app signature.
    async fn verify(&mut self) -> Result<(), DownloadError>;

    /// Execute installer.
    async fn install(&mut self) -> Result<(), DownloadError>;
}

/// How long to wait for the installer to exit before returning
const INSTALLER_STARTUP_TIMEOUT: Duration = Duration::from_millis(500);

/// Download the app and signature, and verify the app's signature
pub async fn install_and_upgrade(mut downloader: impl AppDownloader) -> Result<(), DownloadError> {
    downloader.download_executable().await?;
    downloader.verify().await?;
    downloader.install().await
}

#[derive(Clone)]
pub struct HttpAppDownloader<AppProgress> {
    params: AppDownloaderParameters<AppProgress>,
}

impl<AppProgress> HttpAppDownloader<AppProgress> {
    pub fn new(params: AppDownloaderParameters<AppProgress>) -> Self {
        Self { params }
    }
}

impl<AppProgress: ProgressUpdater> From<AppDownloaderParameters<AppProgress>>
    for HttpAppDownloader<AppProgress>
{
    fn from(parameters: AppDownloaderParameters<AppProgress>) -> Self {
        HttpAppDownloader::new(parameters)
    }
}

#[async_trait::async_trait]
impl<AppProgress: ProgressUpdater> AppDownloader for HttpAppDownloader<AppProgress> {
    async fn download_executable(&mut self) -> Result<(), DownloadError> {
        let bin_path = self.bin_path();
        fetch::get_to_file(
            bin_path,
            &self.params.app_url,
            &mut self.params.app_progress,
            fetch::SizeHint::Exact(self.params.app_size),
        )
        .await
        .map_err(DownloadError::FetchApp)
    }

    async fn verify(&mut self) -> Result<(), DownloadError> {
        let bin_path = self.bin_path();
        let hash = self.hash_sha256();

        match Sha256Verifier::verify(&bin_path, *hash)
            .await
            .map_err(DownloadError::Verification)
        {
            // Verification succeeded
            Ok(()) => Ok(()),
            // Verification failed
            Err(err) => {
                // Attempt to clean up
                let _ = tokio::fs::remove_file(bin_path).await;
                Err(err)
            }
        }
    }

    async fn install(&mut self) -> Result<(), DownloadError> {
        let launch_path = self.launch_path();

        // Launch process
        let mut cmd = Command::new(launch_path);
        cmd.args(self.launch_args());
        let mut child = cmd.spawn().map_err(DownloadError::Launch)?;

        // Wait to see if the installer fails
        match timeout(INSTALLER_STARTUP_TIMEOUT, child.wait()).await {
            // Timeout: Quit and let the installer take over
            Err(_timeout) => Ok(()),
            // No timeout: Incredibly quick but successful (or wrong exit code, probably)
            Ok(Ok(status)) if status.success() => Ok(()),
            // Installer exited with error code
            Ok(Ok(status)) => Err(DownloadError::InstallExited(status)),
            // `child.wait()` returned an error
            Ok(Err(err)) => Err(DownloadError::InstallFailed(err)),
        }
    }
}

impl<AppProgress> HttpAppDownloader<AppProgress> {
    fn bin_path(&self) -> PathBuf {
        #[cfg(windows)]
        let bin_filename = format!("mullvad-{}.exe", self.params.app_version);

        #[cfg(target_os = "macos")]
        let bin_filename = format!("mullvad-{}.pkg", self.params.app_version);

        self.params.cache_dir.join(bin_filename)
    }

    fn launch_path(&self) -> PathBuf {
        #[cfg(target_os = "windows")]
        {
            self.bin_path()
        }

        #[cfg(target_os = "macos")]
        {
            use std::path::Path;

            Path::new("/usr/bin/open").to_owned()
        }
    }

    fn launch_args(&self) -> Vec<OsString> {
        #[cfg(target_os = "windows")]
        {
            vec![]
        }

        #[cfg(target_os = "macos")]
        {
            vec![self.bin_path().into()]
        }
    }

    fn hash_sha256(&self) -> &[u8; 32] {
        &self.params.app_sha256
    }
}