Repository navigation
Expand file tree
/
Copy pathupdater.rs
More file actions
1865 lines (1658 loc) · 64.3 KB
/
Copy pathupdater.rs
File metadata and controls
1865 lines (1658 loc) · 64.3 KB
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::{
collections::HashMap,
ffi::OsString,
io::Cursor,
path::{Path, PathBuf},
str::FromStr,
sync::Arc,
time::Duration,
};
#[cfg(not(target_os = "macos"))]
use std::ffi::OsStr;
use base64::Engine;
use futures_util::StreamExt;
use http::{header::ACCEPT, HeaderName};
use minisign_verify::{PublicKey, Signature};
use percent_encoding::{AsciiSet, CONTROLS};
use reqwest::{
header::{HeaderMap, HeaderValue},
ClientBuilder, StatusCode,
};
use semver::Version;
use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize};
use tauri::{
utils::{
config::BundleType,
platform::{bundle_type, current_exe},
},
AppHandle, Resource, Runtime,
};
use time::OffsetDateTime;
use url::Url;
use crate::{
error::{Error, Result},
Config,
};
const UPDATER_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
#[derive(Copy, Clone)]
pub enum Installer {
AppImage,
Deb,
Rpm,
App,
Msi,
Nsis,
}
impl Installer {
fn name(self) -> &'static str {
match self {
Self::AppImage => "appimage",
Self::Deb => "deb",
Self::Rpm => "rpm",
Self::App => "app",
Self::Msi => "msi",
Self::Nsis => "nsis",
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ReleaseManifestPlatform {
/// Download URL for the platform
pub url: Url,
/// Signature for the platform
pub signature: String,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum RemoteReleaseInner {
Dynamic(ReleaseManifestPlatform),
Static {
platforms: HashMap<String, ReleaseManifestPlatform>,
},
}
/// Information about a release returned by the remote update server.
///
/// This type can have one of two shapes: Server Format (Dynamic Format) and Static Format.
#[derive(Debug, Clone)]
pub struct RemoteRelease {
/// Version to install.
pub version: Version,
/// Release notes.
pub notes: Option<String>,
/// Release date.
pub pub_date: Option<OffsetDateTime>,
/// Release data.
pub data: RemoteReleaseInner,
}
impl RemoteRelease {
/// The release's download URL for the given target.
pub fn download_url(&self, target: &str) -> Result<&Url> {
match self.data {
RemoteReleaseInner::Dynamic(ref platform) => Ok(&platform.url),
RemoteReleaseInner::Static { ref platforms } => platforms
.get(target)
.map_or(Err(Error::TargetNotFound(target.to_string())), |p| {
Ok(&p.url)
}),
}
}
/// The release's signature for the given target.
pub fn signature(&self, target: &str) -> Result<&String> {
match self.data {
RemoteReleaseInner::Dynamic(ref platform) => Ok(&platform.signature),
RemoteReleaseInner::Static { ref platforms } => platforms
.get(target)
.map_or(Err(Error::TargetNotFound(target.to_string())), |platform| {
Ok(&platform.signature)
}),
}
}
}
pub type OnBeforeExit = Arc<dyn Fn() + Send + Sync + 'static>;
pub type OnBeforeRequest = Arc<dyn Fn(ClientBuilder) -> ClientBuilder + Send + Sync + 'static>;
pub type VersionComparator = Arc<dyn Fn(Version, RemoteRelease) -> bool + Send + Sync>;
#[cfg(target_os = "macos")]
type MainThreadClosure = Box<dyn FnOnce() + Send + Sync + 'static>;
#[cfg(target_os = "macos")]
type RunOnMainThread = Arc<dyn Fn(MainThreadClosure) -> tauri::Result<()> + Send + Sync + 'static>;
// TODO: Move more fields to this in v3 if we can mark those fields non `pub`
/// Updater context shared between [`UpdaterBuilder`], [`Updater`] and [`Update`]
#[derive(Clone)]
struct UpdaterContext {
config: Config,
configure_client: Option<OnBeforeRequest>,
#[cfg(target_os = "macos")]
run_on_main_thread: RunOnMainThread,
/// App name, used for creating named tempfiles
#[cfg(windows)]
app_name: String,
#[cfg(windows)]
installer_args: Vec<OsString>,
#[cfg(windows)]
current_exe_args: Vec<OsString>,
#[cfg(windows)]
on_before_exit: Option<OnBeforeExit>,
#[cfg(windows)]
restart_after_install: bool,
}
pub struct UpdaterBuilder {
current_version: Version,
pub(crate) version_comparator: Option<VersionComparator>,
executable_path: Option<PathBuf>,
target: Option<String>,
endpoints: Option<Vec<Url>>,
headers: HeaderMap,
timeout: Option<Duration>,
proxy: Option<Url>,
no_proxy: bool,
context: UpdaterContext,
}
impl UpdaterBuilder {
pub(crate) fn new<R: Runtime>(app: &AppHandle<R>, config: crate::Config) -> Self {
#[cfg(target_os = "macos")]
let run_on_main_thread = {
let app_ = app.clone();
Arc::new(move |f| app_.run_on_main_thread(f))
};
Self {
context: UpdaterContext {
#[cfg(windows)]
installer_args: config
.windows
.as_ref()
.map(|w| w.installer_args.clone())
.unwrap_or_default(),
config,
configure_client: None,
#[cfg(target_os = "macos")]
run_on_main_thread,
#[cfg(windows)]
app_name: app.package_info().name.clone(),
#[cfg(windows)]
current_exe_args: Vec::new(),
#[cfg(windows)]
on_before_exit: None,
#[cfg(windows)]
restart_after_install: true,
},
current_version: app.package_info().version.clone(),
version_comparator: None,
executable_path: None,
target: None,
endpoints: None,
headers: Default::default(),
timeout: None,
proxy: None,
no_proxy: false,
}
}
pub fn version_comparator<F: Fn(Version, RemoteRelease) -> bool + Send + Sync + 'static>(
mut self,
f: F,
) -> Self {
self.version_comparator = Some(Arc::new(f));
self
}
pub fn target(mut self, target: impl Into<String>) -> Self {
self.target.replace(target.into());
self
}
pub fn endpoints(mut self, endpoints: Vec<Url>) -> Result<Self> {
crate::config::validate_endpoints(
&endpoints,
self.context.config.dangerous_insecure_transport_protocol,
)?;
self.endpoints.replace(endpoints);
Ok(self)
}
pub fn executable_path<P: AsRef<Path>>(mut self, p: P) -> Self {
self.executable_path.replace(p.as_ref().into());
self
}
pub fn header<K, V>(mut self, key: K, value: V) -> Result<Self>
where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<http::Error>,
HeaderValue: TryFrom<V>,
<HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
{
let key: std::result::Result<HeaderName, http::Error> = key.try_into().map_err(Into::into);
let value: std::result::Result<HeaderValue, http::Error> =
value.try_into().map_err(Into::into);
self.headers.insert(key?, value?);
Ok(self)
}
pub fn headers(mut self, headers: HeaderMap) -> Self {
self.headers = headers;
self
}
pub fn clear_headers(mut self) -> Self {
self.headers.clear();
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn proxy(mut self, proxy: Url) -> Self {
self.proxy.replace(proxy);
self
}
/// Clear all proxies. See [`reqwest::ClientBuilder::no_proxy`](https://docs.rs/reqwest/latest/reqwest/struct.ClientBuilder.html#method.no_proxy).
pub fn no_proxy(mut self) -> Self {
self.no_proxy = true;
self
}
pub fn pubkey<S: Into<String>>(mut self, pubkey: S) -> Self {
self.context.config.pubkey = pubkey.into();
self
}
/// Adds an argument to pass to the Windows installer.
///
/// Note: this applies to both WiX and NSIS installers
#[cfg_attr(not(windows), allow(unused))]
pub fn installer_arg<S>(mut self, arg: S) -> Self
where
S: Into<OsString>,
{
#[cfg(windows)]
{
self.context.installer_args.push(arg.into());
}
self
}
/// Adds multiple arguments to pass to the Windows installer.
///
/// Note: this applies to both WiX and NSIS installers
#[cfg_attr(not(windows), allow(unused))]
pub fn installer_args<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<OsString>,
{
#[cfg(windows)]
{
self.context
.installer_args
.extend(args.into_iter().map(Into::into));
}
self
}
/// Removes all the additional arguments to pass to the Windows installer.
///
/// Note: this only removes the additional arguments added through
/// [`Self::installer_arg`], [`crate::Builder::installer_arg`]
/// and the `plugins > updater > windows > installerArgs` config,
/// not the ones managed by us (e.g. `/UPDATER` flag passed to the NSIS installer)
#[cfg_attr(not(windows), allow(unused))]
pub fn clear_installer_args(mut self) -> Self {
#[cfg(windows)]
{
self.context.installer_args.clear();
}
self
}
/// Function to run before we run the installer and exit the app through `std::process::exit(0)` on Windows
#[cfg_attr(not(windows), allow(unused))]
pub fn on_before_exit<F: Fn() + Send + Sync + 'static>(mut self, f: F) -> Self {
#[cfg(windows)]
{
self.context.on_before_exit.replace(Arc::new(f));
}
self
}
/// If the Windows installer should restart the app after installed, default is `true`
#[cfg_attr(not(windows), allow(unused))]
pub fn restart_after_install(mut self, restart_after_install: bool) -> Self {
#[cfg(windows)]
{
self.context.restart_after_install = restart_after_install;
}
self
}
/// Allows you to modify the `reqwest` client builder before the HTTP request is sent.
///
/// Note that `reqwest` crate may be updated in minor releases of tauri-plugin-updater.
/// Therefore it's recommended to pin the plugin to at least a minor version when you're using `configure_client`.
pub fn configure_client<F: Fn(ClientBuilder) -> ClientBuilder + Send + Sync + 'static>(
mut self,
f: F,
) -> Self {
self.context.configure_client.replace(Arc::new(f));
self
}
pub fn build(self) -> Result<Updater> {
let endpoints = self
.endpoints
.unwrap_or_else(|| self.context.config.endpoints.clone());
if endpoints.is_empty() {
return Err(Error::EmptyEndpoints);
};
let arch = updater_arch().ok_or(Error::UnsupportedArch)?;
let executable_path = self.executable_path.clone().unwrap_or(current_exe()?);
// Get the extract_path from the provided executable_path
let extract_path = if cfg!(target_os = "linux") {
executable_path
} else {
extract_path_from_executable(&executable_path)?
};
Ok(Updater {
current_version: self.current_version,
version_comparator: self.version_comparator,
timeout: self.timeout,
proxy: self.proxy,
no_proxy: self.no_proxy,
endpoints,
arch,
target: self.target,
headers: self.headers,
extract_path,
context: self.context.clone(),
})
}
}
#[cfg(windows)]
impl UpdaterBuilder {
pub(crate) fn current_exe_args<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<OsString>,
{
self.context
.current_exe_args
.extend(args.into_iter().map(Into::into));
self
}
}
pub struct Updater {
current_version: Version,
version_comparator: Option<VersionComparator>,
timeout: Option<Duration>,
proxy: Option<Url>,
no_proxy: bool,
endpoints: Vec<Url>,
arch: &'static str,
// The `{{target}}` variable we replace in the endpoint and serach for in the JSON,
// this is either the user provided target or the current operating system by default
target: Option<String>,
headers: HeaderMap,
extract_path: PathBuf,
context: UpdaterContext,
}
impl Updater {
pub async fn check(&self) -> Result<Option<Update>> {
// we want JSON only
let mut headers = self.headers.clone();
if !headers.contains_key(ACCEPT) {
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
}
// Set SSL certs for linux if they aren't available.
#[cfg(target_os = "linux")]
{
if std::env::var_os("SSL_CERT_FILE").is_none() {
std::env::set_var("SSL_CERT_FILE", "/etc/ssl/certs/ca-certificates.crt");
}
if std::env::var_os("SSL_CERT_DIR").is_none() {
std::env::set_var("SSL_CERT_DIR", "/etc/ssl/certs");
}
}
let target = if let Some(target) = &self.target {
target
} else {
updater_os().ok_or(Error::UnsupportedOs)?
};
let mut remote_release: Option<RemoteRelease> = None;
let mut raw_json: Option<serde_json::Value> = None;
let mut last_error: Option<Error> = None;
for url in &self.endpoints {
// replace {{current_version}}, {{target}}, {{arch}} and {{bundle_type}} in the provided URL
// this is useful if we need to query example
// https://releases.myapp.com/update/{{target}}/{{arch}}/{{current_version}}
// will be translated into ->
// https://releases.myapp.com/update/darwin/aarch64/1.0.0
// The main objective is if the update URL is defined via the Cargo.toml
// the URL will be generated dynamically
let version = self.current_version.to_string();
let version = version.as_bytes();
const CONTROLS_ADD: &AsciiSet = &CONTROLS.add(b'+');
let encoded_version = percent_encoding::percent_encode(version, CONTROLS_ADD);
let encoded_version = encoded_version.to_string();
let installer = installer_for_bundle_type(bundle_type())
.map(|i| i.name())
.unwrap_or("unknown");
let url: Url = url
.to_string()
// url::Url automatically url-encodes the path components
.replace("%7B%7Bcurrent_version%7D%7D", &encoded_version)
.replace("%7B%7Btarget%7D%7D", target)
.replace("%7B%7Barch%7D%7D", self.arch)
.replace("%7B%7Bbundle_type%7D%7D", installer)
// but not query parameters
.replace("{{current_version}}", &encoded_version)
.replace("{{target}}", target)
.replace("{{arch}}", self.arch)
.replace("{{bundle_type}}", installer)
.parse()?;
log::debug!("checking for updates {url}");
#[cfg(feature = "rustls-tls")]
if rustls::crypto::CryptoProvider::get_default().is_none() {
// This can only fail if there is already a default provider which we checked for already.
let _ = rustls::crypto::ring::default_provider().install_default();
}
let mut request = ClientBuilder::new().user_agent(UPDATER_USER_AGENT);
if self.context.config.dangerous_accept_invalid_certs {
request = request.danger_accept_invalid_certs(true);
}
if self.context.config.dangerous_accept_invalid_hostnames {
request = request.danger_accept_invalid_hostnames(true);
}
if let Some(timeout) = self.timeout {
request = request.timeout(timeout);
}
if self.no_proxy {
log::debug!("disabling proxy");
request = request.no_proxy();
} else if let Some(ref proxy) = self.proxy {
log::debug!("using proxy {proxy}");
let proxy = reqwest::Proxy::all(proxy.as_str())?;
request = request.proxy(proxy);
}
if let Some(ref configure_client) = self.context.configure_client {
request = configure_client(request);
}
let response = request
.build()?
.get(url)
.headers(headers.clone())
.send()
.await;
match response {
Ok(res) => {
if res.status().is_success() {
// no updates found!
if StatusCode::NO_CONTENT == res.status() {
log::debug!("update endpoint returned 204 No Content");
return Ok(None);
};
let update_response: serde_json::Value = res.json().await?;
log::debug!("update response: {update_response:?}");
raw_json = Some(update_response.clone());
match serde_json::from_value::<RemoteRelease>(update_response)
.map_err(Into::into)
{
Ok(release) => {
log::debug!("parsed release response {release:?}");
last_error = None;
remote_release = Some(release);
// we found a release, break the loop
break;
}
Err(err) => {
log::error!("failed to deserialize update response: {err}");
last_error = Some(err)
}
}
} else {
log::error!(
"update endpoint did not respond with a successful status code"
);
}
}
Err(err) => {
log::error!("failed to check for updates: {err}");
last_error = Some(err.into())
}
}
}
// Last error is cleaned on success.
// Shouldn't be triggered if we had a successfull call
if let Some(error) = last_error {
return Err(error);
}
// Extracted remote metadata
let release = remote_release.ok_or(Error::ReleaseNotFound)?;
let should_update = match self.version_comparator.as_ref() {
Some(comparator) => comparator(self.current_version.clone(), release.clone()),
None => release.version > self.current_version,
};
let installer = installer_for_bundle_type(bundle_type());
let (download_url, signature) = self.get_urls(&release, &installer)?;
let update = if should_update {
Some(Update {
current_version: self.current_version.to_string(),
target: target.to_owned(),
extract_path: self.extract_path.clone(),
version: release.version.to_string(),
date: release.pub_date,
download_url: download_url.clone(),
signature: signature.to_owned(),
body: release.notes,
raw_json: raw_json.unwrap(),
timeout: None,
proxy: self.proxy.clone(),
no_proxy: self.no_proxy,
headers: self.headers.clone(),
context: self.context.clone(),
})
} else {
None
};
Ok(update)
}
fn get_urls<'a>(
&self,
release: &'a RemoteRelease,
installer: &Option<Installer>,
) -> Result<(&'a Url, &'a String)> {
// Use the user provided target
if let Some(target) = &self.target {
return Ok((release.download_url(target)?, release.signature(target)?));
}
// Or else we search for [`{os}-{arch}-{installer}`, `{os}-{arch}`] in order
let os = updater_os().ok_or(Error::UnsupportedOs)?;
let arch = self.arch;
let mut targets = Vec::new();
if let Some(installer) = installer {
let installer = installer.name();
targets.push(format!("{os}-{arch}-{installer}"));
}
targets.push(format!("{os}-{arch}"));
for target in &targets {
log::debug!("Searching for updater target '{target}' in release data");
if let (Ok(download_url), Ok(signature)) =
(release.download_url(target), release.signature(target))
{
return Ok((download_url, signature));
};
}
Err(Error::TargetsNotFound(targets))
}
}
#[derive(Clone)]
pub struct Update {
/// Update description
pub body: Option<String>,
/// Version used to check for update
pub current_version: String,
/// Version announced
pub version: String,
/// Update publish date
pub date: Option<OffsetDateTime>,
/// The `{{target}}` variable we replace in the endpoint and search for in the JSON,
/// this is either the user provided target or the current operating system by default
pub target: String,
/// Download URL announced
pub download_url: Url,
/// Signature announced
pub signature: String,
/// The raw version of server's JSON response. Useful if the response contains additional fields that the updater doesn't handle.
pub raw_json: serde_json::Value,
/// Request timeout
pub timeout: Option<Duration>,
/// Request proxy
pub proxy: Option<Url>,
/// Disable system proxy
pub no_proxy: bool,
/// Request headers
pub headers: HeaderMap,
/// Extract path
#[allow(unused)]
extract_path: PathBuf,
context: UpdaterContext,
}
impl Resource for Update {}
impl Update {
/// Downloads the updater package, verifies it then return it as bytes.
///
/// Use [`Update::install`] to install it
pub async fn download<C: FnMut(usize, Option<u64>), D: FnOnce()>(
&self,
mut on_chunk: C,
on_download_finish: D,
) -> Result<Vec<u8>> {
// set our headers
let mut headers = self.headers.clone();
if !headers.contains_key(ACCEPT) {
headers.insert(ACCEPT, HeaderValue::from_static("application/octet-stream"));
}
let mut request = ClientBuilder::new().user_agent(UPDATER_USER_AGENT);
if self.context.config.dangerous_accept_invalid_certs {
request = request.danger_accept_invalid_certs(true);
}
if self.context.config.dangerous_accept_invalid_hostnames {
request = request.danger_accept_invalid_hostnames(true);
}
if let Some(timeout) = self.timeout {
request = request.timeout(timeout);
}
if self.no_proxy {
request = request.no_proxy();
} else if let Some(ref proxy) = self.proxy {
let proxy = reqwest::Proxy::all(proxy.as_str())?;
request = request.proxy(proxy);
}
if let Some(ref configure_client) = self.context.configure_client {
request = configure_client(request);
}
let response = request
.build()?
.get(self.download_url.clone())
.headers(headers)
.send()
.await?;
if !response.status().is_success() {
return Err(Error::Network(format!(
"Download request failed with status: {}",
response.status()
)));
}
let content_length: Option<u64> = response
.headers()
.get("Content-Length")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse().ok());
let mut buffer = Vec::new();
let mut stream = response.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
on_chunk(chunk.len(), content_length);
buffer.extend(chunk);
}
on_download_finish();
verify_signature(
&buffer,
&self.signature,
&self.context.config.pubkey,
&self.version,
self.context.config.require_signed_version,
)?;
Ok(buffer)
}
/// Installs the updater package downloaded by [`Update::download`]
///
/// ## Platform-specific:
///
/// - **Windows:** This function exits the app after launching the updater installer successfully
/// - **macOS / Linux:** You need to relaunch the app to run the newly install version
pub fn install(&self, bytes: impl AsRef<[u8]>) -> Result<()> {
self.install_inner(bytes.as_ref())
}
/// Downloads and installs the updater package
///
/// ## Platform-specific:
///
/// - **Windows:** This function exits the app after launching the updater installer successfully
/// - **macOS / Linux:** You need to relaunch the app to run the newly install version
pub async fn download_and_install<C: FnMut(usize, Option<u64>), D: FnOnce()>(
&self,
on_chunk: C,
on_download_finish: D,
) -> Result<()> {
let bytes = self.download(on_chunk, on_download_finish).await?;
self.install(bytes)
}
#[cfg(mobile)]
fn install_inner(&self, _bytes: &[u8]) -> Result<()> {
Ok(())
}
/// Whether the Windows installer should restart the app after installed, default is `true`
#[cfg_attr(not(windows), allow(unused))]
pub fn restart_after_install(mut self, restart_after_install: bool) -> Self {
#[cfg(windows)]
{
self.context.restart_after_install = restart_after_install;
}
self
}
}
#[cfg(windows)]
enum WindowsUpdaterType {
Nsis {
path: PathBuf,
#[allow(unused)]
temp: Option<tempfile::TempPath>,
},
Msi {
path: PathBuf,
#[allow(unused)]
temp: Option<tempfile::TempPath>,
},
}
#[cfg(windows)]
impl WindowsUpdaterType {
fn nsis(path: PathBuf, temp: Option<tempfile::TempPath>) -> Self {
Self::Nsis { path, temp }
}
fn msi(path: PathBuf, temp: Option<tempfile::TempPath>) -> Self {
Self::Msi {
path: path.wrap_in_quotes(),
temp,
}
}
}
#[cfg(windows)]
impl Config {
fn install_mode(&self) -> crate::config::WindowsUpdateInstallMode {
self.windows
.as_ref()
.map(|w| w.install_mode.clone())
.unwrap_or_default()
}
}
/// Windows
#[cfg(windows)]
impl Update {
/// ### Expected structure:
/// ├── [AppName]_[version]_x64.msi # Application MSI
/// ├── [AppName]_[version]_x64-setup.exe # NSIS installer
/// ├── [AppName]_[version]_x64.msi.zip # ZIP generated by tauri-bundler
/// │ └──[AppName]_[version]_x64.msi # Application MSI
/// ├── [AppName]_[version]_x64-setup.exe.zip # ZIP generated by tauri-bundler
/// │ └──[AppName]_[version]_x64-setup.exe # NSIS installer
/// └── ...
fn install_inner(&self, bytes: &[u8]) -> Result<()> {
use windows_sys::{
w,
Win32::UI::{Shell::ShellExecuteW, WindowsAndMessaging::SW_SHOW},
};
let updater_type = self.extract(bytes)?;
if let Some(on_before_exit) = self.context.on_before_exit.as_ref() {
log::debug!("running on_before_exit hook");
on_before_exit();
}
let file = match &updater_type {
WindowsUpdaterType::Nsis { path, .. } => path.as_os_str().to_os_string(),
WindowsUpdaterType::Msi { .. } => std::env::var("SYSTEMROOT").as_ref().map_or_else(
|_| OsString::from("msiexec.exe"),
|p| OsString::from(format!("{p}\\System32\\msiexec.exe")),
),
};
let parameters = self.updater_parameters(&updater_type);
log::debug!("Executing updater {file:?} with parameters: {parameters:?}");
let file = encode_wide(file);
let parameters = encode_wide(parameters);
let result = unsafe {
ShellExecuteW(
std::ptr::null_mut(),
w!("open"),
file.as_ptr(),
parameters.as_ptr(),
std::ptr::null(),
SW_SHOW,
)
};
if result as isize <= 32 {
return Err(crate::Error::Io(std::io::Error::last_os_error()));
}
std::process::exit(0);
}
fn updater_parameters(&self, updater_type: &WindowsUpdaterType) -> OsString {
let install_mode = self.context.config.install_mode();
let current_args = &self.context.current_exe_args[1..];
match updater_type {
WindowsUpdaterType::Nsis { .. } => {
let mut installer_args: Vec<&OsStr> = Vec::new();
installer_args.extend(install_mode.nsis_args().iter().map(OsStr::new));
installer_args.push(OsStr::new("/UPDATE"));
let nsis_current_exe_arg;
if self.context.restart_after_install {
nsis_current_exe_arg = current_args
.iter()
.map(escape_nsis_current_exe_arg)
.collect::<Vec<_>>();
installer_args.extend(
install_mode
.nsis_restart_after_install_args()
.iter()
.map(OsStr::new),
);
installer_args.push(OsStr::new("/ARGS"));
installer_args.extend(nsis_current_exe_arg.iter().map(OsStr::new));
}
installer_args.extend(self.installer_args());
installer_args.join(OsStr::new(" "))
}
WindowsUpdaterType::Msi { path, .. } => {
let mut installer_args: Vec<&OsStr> = vec![OsStr::new("/i"), path.as_os_str()];
installer_args.extend(install_mode.msiexec_args().iter().map(OsStr::new));
installer_args.push(OsStr::new("/promptrestart"));
installer_args.extend(self.installer_args());
let msi_current_exe_arg;
if self.context.restart_after_install {
msi_current_exe_arg = format!(
"LAUNCHAPPARGS=\"{}\"",
current_args
.iter()
.map(escape_msi_property_arg)
.collect::<Vec<_>>()
.join(" ")
);
installer_args.extend(
install_mode
.msi_restart_after_install_args()
.iter()
.map(OsStr::new),
);
installer_args.push(OsStr::new(&msi_current_exe_arg));
}
installer_args.join(OsStr::new(" "))
}
}
}
fn installer_args(
&self,
) -> std::iter::Map<std::slice::Iter<'_, OsString>, fn(&OsString) -> &OsStr> {
self.context.installer_args.iter().map(OsStr::new)
}
fn extract(&self, bytes: &[u8]) -> Result<WindowsUpdaterType> {
#[cfg(feature = "zip")]
if infer::archive::is_zip(bytes) {
return self.extract_zip(bytes);
}
self.extract_exe(bytes)
}
fn make_temp_dir(&self) -> Result<PathBuf> {
Ok(tempfile::Builder::new()
.prefix(&format!(
"{}-{}-updater-",
self.context.app_name, self.version
))
.tempdir()?
.keep())
}
#[cfg(feature = "zip")]
fn extract_zip(&self, bytes: &[u8]) -> Result<WindowsUpdaterType> {
let temp_dir = self.make_temp_dir()?;
let archive = Cursor::new(bytes);
let mut extractor = zip::ZipArchive::new(archive)?;
extractor.extract(&temp_dir)?;
let paths = std::fs::read_dir(&temp_dir)?;
for path in paths {
let path = path?.path();
let ext = path.extension();
if ext == Some(OsStr::new("exe")) {
return Ok(WindowsUpdaterType::nsis(path, None));
} else if ext == Some(OsStr::new("msi")) {
return Ok(WindowsUpdaterType::msi(path, None));
}
}
Err(crate::Error::BinaryNotFoundInArchive)
}
fn extract_exe(&self, bytes: &[u8]) -> Result<WindowsUpdaterType> {
if infer::app::is_exe(bytes) {
let (path, temp) = self.write_to_temp(bytes, ".exe")?;
Ok(WindowsUpdaterType::nsis(path, temp))
} else if infer::archive::is_msi(bytes) {
let (path, temp) = self.write_to_temp(bytes, ".msi")?;
Ok(WindowsUpdaterType::msi(path, temp))