Skip to main content

tauri_utils/
platform.rs

1// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! Platform helper functions.
6
7use std::{fmt::Display, path::PathBuf};
8
9use serde::{Deserialize, Serialize};
10
11use crate::{Env, PackageInfo, config::BundleType};
12
13mod starting_binary;
14
15/// URI prefix of a Tauri asset.
16///
17/// This is referenced in the Tauri Android library,
18/// which resolves these assets to a file descriptor.
19#[cfg(target_os = "android")]
20pub const ANDROID_ASSET_PROTOCOL_URI_PREFIX: &str = "asset://localhost/";
21
22/// Resource id of the application icon that `tauri-build` embeds into Windows executables
23/// and that `tauri::image::Image::from_app_icon_resource` reads back.
24///
25/// `32512` has no special meaning here: it was picked because we misunderstood
26/// `IDI_APPLICATION` (`MAKEINTRESOURCE(32512)`) to be the id an application icon must use,
27/// which is not the case. See <https://devblogs.microsoft.com/oldnewthing/20250423-00/?p=111106>.
28pub const WINDOWS_APP_ICON_RESOURCE_ID: u16 = 32512;
29
30/// Platform target.
31#[derive(PartialEq, Eq, Copy, Debug, Clone, Serialize, Deserialize)]
32#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
33#[serde(rename_all = "camelCase")]
34#[non_exhaustive]
35pub enum Target {
36  /// MacOS.
37  #[serde(rename = "macOS")]
38  MacOS,
39  /// Windows.
40  Windows,
41  /// Linux.
42  Linux,
43  /// Android.
44  Android,
45  /// iOS.
46  #[serde(rename = "iOS")]
47  Ios,
48}
49
50impl Display for Target {
51  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52    write!(
53      f,
54      "{}",
55      match self {
56        Self::MacOS => "macOS",
57        Self::Windows => "windows",
58        Self::Linux => "linux",
59        Self::Android => "android",
60        Self::Ios => "iOS",
61      }
62    )
63  }
64}
65
66impl Target {
67  /// Parses the target from the given target triple.
68  pub fn from_triple(target: &str) -> Self {
69    if target.contains("darwin") {
70      Self::MacOS
71    } else if target.contains("windows") {
72      Self::Windows
73    } else if target.contains("android") {
74      Self::Android
75    } else if target.contains("ios") {
76      Self::Ios
77    } else {
78      Self::Linux
79    }
80  }
81
82  /// Gets the current build target.
83  pub fn current() -> Self {
84    if cfg!(target_os = "macos") {
85      Self::MacOS
86    } else if cfg!(target_os = "windows") {
87      Self::Windows
88    } else if cfg!(target_os = "ios") {
89      Self::Ios
90    } else if cfg!(target_os = "android") {
91      Self::Android
92    } else {
93      Self::Linux
94    }
95  }
96
97  /// Whether the target is mobile or not.
98  pub fn is_mobile(&self) -> bool {
99    matches!(self, Target::Android | Target::Ios)
100  }
101
102  /// Whether the target is desktop or not.
103  pub fn is_desktop(&self) -> bool {
104    !self.is_mobile()
105  }
106}
107
108/// Retrieves the currently running binary's path, taking into account security considerations.
109///
110/// The path is cached as soon as possible (before even `main` runs) and that value is returned
111/// repeatedly instead of fetching the path every time. It is possible for the path to not be found,
112/// or explicitly disabled (see following macOS specific behavior).
113///
114/// # Platform-specific behavior
115///
116/// On `macOS`, this function will return an error if the original path contained any symlinks
117/// due to less protection on macOS regarding symlinks. This behavior can be disabled by setting the
118/// `process-relaunch-dangerous-allow-symlink-macos` feature, although it is *highly discouraged*.
119///
120/// # Security
121///
122/// If the above platform-specific behavior does **not** take place, this function uses the
123/// following resolution.
124///
125/// We canonicalize the path we received from [`std::env::current_exe`] to resolve any soft links.
126/// This avoids the usual issue of needing the file to exist at the passed path because a valid
127/// current executable result for our purpose should always exist. Notably,
128/// [`std::env::current_exe`] also has a security section that goes over a theoretical attack using
129/// hard links. Let's cover some specific topics that relate to different ways an attacker might
130/// try to trick this function into returning the wrong binary path.
131///
132/// ## Symlinks ("Soft Links")
133///
134/// [`std::path::Path::canonicalize`] is used to resolve symbolic links to the original path,
135/// including nested symbolic links (`link2 -> link1 -> bin`). On macOS, any results that include
136/// a symlink are rejected by default due to lesser symlink protections. This can be disabled,
137/// **although discouraged**, with the `process-relaunch-dangerous-allow-symlink-macos` feature.
138///
139/// ## Hard Links
140///
141/// A [Hard Link] is a named entry that points to a file in the file system.
142/// On most systems, this is what you would think of as a "file". The term is
143/// used on filesystems that allow multiple entries to point to the same file.
144/// The linked [Hard Link] Wikipedia page provides a decent overview.
145///
146/// In short, unless the attacker was able to create the link with elevated
147/// permissions, it should generally not be possible for them to hard link
148/// to a file they do not have permissions to - with exception to possible
149/// operating system exploits.
150///
151/// There are also some platform-specific information about this below.
152///
153/// ### Windows
154///
155/// Windows requires a permission to be set for the user to create a symlink
156/// or a hard link, regardless of ownership status of the target. Elevated
157/// permissions users have the ability to create them.
158///
159/// ### macOS
160///
161/// macOS allows for the creation of symlinks and hard links to any file.
162/// Accessing through those links will fail if the user who owns the links
163/// does not have the proper permissions on the original file.
164///
165/// ### Linux
166///
167/// Linux allows for the creation of symlinks to any file. Accessing the
168/// symlink will fail if the user who owns the symlink does not have the
169/// proper permissions on the original file.
170///
171/// Linux additionally provides a kernel hardening feature since version
172/// 3.6 (30 September 2012). Most distributions since then have enabled
173/// the protection (setting `fs.protected_hardlinks = 1`) by default, which
174/// means that a vast majority of desktop Linux users should have it enabled.
175/// **The feature prevents the creation of hardlinks that the user does not own
176/// or have read/write access to.** [See the patch that enabled this].
177///
178/// [Hard Link]: https://en.wikipedia.org/wiki/Hard_link
179/// [See the patch that enabled this]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=800179c9b8a1e796e441674776d11cd4c05d61d7
180pub fn current_exe() -> std::io::Result<PathBuf> {
181  self::starting_binary::STARTING_BINARY.cloned()
182}
183
184/// Try to determine the current target triple.
185///
186/// Returns a target triple (e.g. `x86_64-unknown-linux-gnu` or `i686-pc-windows-msvc`) or an
187/// `Error::Config` if the current config cannot be determined or is not some combination of the
188/// following values:
189/// `linux, mac, windows` -- `i686, x86, armv7` -- `gnu, musl, msvc`
190///
191/// * Errors:
192///     * Unexpected system config
193pub fn target_triple() -> crate::Result<String> {
194  let arch = if cfg!(target_arch = "x86") {
195    "i686"
196  } else if cfg!(target_arch = "x86_64") {
197    "x86_64"
198  } else if cfg!(target_arch = "arm") {
199    "armv7"
200  } else if cfg!(target_arch = "aarch64") {
201    "aarch64"
202  } else if cfg!(target_arch = "riscv64") {
203    "riscv64"
204  } else {
205    return Err(crate::Error::Architecture);
206  };
207
208  let os = if cfg!(target_os = "linux") {
209    "unknown-linux"
210  } else if cfg!(target_os = "macos") {
211    "apple-darwin"
212  } else if cfg!(target_os = "windows") {
213    "pc-windows"
214  } else if cfg!(target_os = "freebsd") {
215    "unknown-freebsd"
216  } else {
217    return Err(crate::Error::Os);
218  };
219
220  let os = if cfg!(target_os = "macos") || cfg!(target_os = "freebsd") {
221    String::from(os)
222  } else {
223    let env = if cfg!(target_env = "gnu") {
224      "gnu"
225    } else if cfg!(target_env = "musl") {
226      "musl"
227    } else if cfg!(target_env = "msvc") {
228      "msvc"
229    } else {
230      return Err(crate::Error::Environment);
231    };
232
233    format!("{os}-{env}")
234  };
235
236  Ok(format!("{arch}-{os}"))
237}
238
239#[cfg(all(not(test), not(target_os = "android")))]
240fn is_cargo_output_directory(path: &std::path::Path) -> bool {
241  path.join(".cargo-lock").exists()
242}
243
244#[cfg(test)]
245const CARGO_OUTPUT_DIRECTORIES: &[&str] = &["debug", "release", "custom-profile"];
246
247#[cfg(test)]
248fn is_cargo_output_directory(path: &std::path::Path) -> bool {
249  let Some(last_component) = path.components().next_back() else {
250    return false;
251  };
252  CARGO_OUTPUT_DIRECTORIES
253    .iter()
254    .any(|dirname| &last_component.as_os_str() == dirname)
255}
256
257/// Computes the resource directory of the current environment.
258///
259/// ## Platform-specific
260///
261/// - **Windows:** Resolves to the directory that contains the main executable.
262/// - **Linux:** When running from a Cargo output directory, resolves to the directory containing the
263///   executable. Otherwise, resolves to `${exe_dir}/../lib/${package_info.name}` when that directory
264///   exists, `${APPDIR}/usr/lib/${package_info.name}` inside an AppImage, or
265///   `/usr/lib/${package_info.name}` for an installed package.
266/// - **macOS:** Resolves to `${exe_dir}/../Resources` (inside .app).
267/// - **iOS:** Resolves to `${exe_dir}/assets`.
268/// - **Android:** Currently the resources are stored in the APK as assets so it's not a normal file system path,
269///   we return a special URI prefix `asset://localhost/` here that can be used with the [file system plugin](https://tauri.app/plugin/file-system/),
270///   with that, you can read the files through [`FsExt::fs`](https://docs.rs/tauri-plugin-fs/latest/tauri_plugin_fs/trait.FsExt.html#tymethod.fs)
271///   like this: `app.fs().read_to_string(app.path().resource_dir().unwrap().join("resource"));`
272///
273/// For applications packaged with `tauri-bundler`, `package_info.name` must match
274/// [`tauri_bundler::bundle::PackageSettings::product_name`](https://docs.rs/tauri-bundler/latest/tauri_bundler/bundle/struct.PackageSettings.html#structfield.product_name).
275///
276/// ## Example
277///
278/// ```no_run
279/// use tauri_utils::{platform::resource_dir, Env, PackageInfo};
280///
281/// let package_info = PackageInfo {
282///   name: "Your Awesome App".into(),
283///   version: "1.0.0".parse().unwrap(),
284///   authors: "",
285///   description: "",
286///   crate_name: "your-awesome-app",
287/// };
288///
289/// let _index_html = resource_dir(&package_info, &Env::default())?.join("assets/index.html");
290/// # Ok::<(), tauri_utils::Error>(())
291/// ```
292pub fn resource_dir(package_info: &PackageInfo, env: &Env) -> crate::Result<PathBuf> {
293  #[cfg(target_os = "android")]
294  return resource_dir_android(package_info, env);
295  #[cfg(not(target_os = "android"))]
296  {
297    let exe = current_exe()?;
298    resource_dir_from(exe, package_info, env)
299  }
300}
301
302#[cfg(target_os = "android")]
303fn resource_dir_android(_package_info: &PackageInfo, _env: &Env) -> crate::Result<PathBuf> {
304  Ok(PathBuf::from(ANDROID_ASSET_PROTOCOL_URI_PREFIX))
305}
306
307#[cfg(not(target_os = "android"))]
308#[allow(unused_variables)]
309fn resource_dir_from<P: AsRef<std::path::Path>>(
310  exe: P,
311  package_info: &PackageInfo,
312  env: &Env,
313) -> crate::Result<PathBuf> {
314  let exe_dir = exe.as_ref().parent().expect("failed to get exe directory");
315  let curr_dir = exe_dir.display().to_string();
316
317  let parts: Vec<&str> = curr_dir.split(std::path::MAIN_SEPARATOR).collect();
318  let len = parts.len();
319
320  // Check if running from the Cargo output directory, which means it's an executable in a development machine
321  // We check if the binary is inside a `target` folder which can be either `target/$profile` or `target/$triple/$profile`
322  // and see if there's a .cargo-lock file along the executable
323  // This ensures the check is safer so it doesn't affect apps in production
324  // Windows also includes the resources in the executable folder so we check that too
325  if cfg!(target_os = "windows")
326    || ((len >= 2 && parts[len - 2] == "target") || (len >= 3 && parts[len - 3] == "target"))
327      && is_cargo_output_directory(exe_dir)
328  {
329    return Ok(exe_dir.to_path_buf());
330  }
331
332  #[allow(unused_mut, unused_assignments)]
333  let mut res = Err(crate::Error::UnsupportedPlatform);
334
335  #[cfg(target_os = "linux")]
336  {
337    // (canonicalize checks for existence, so there's no need for an extra check)
338    res = if let Ok(bundle_dir) = exe_dir
339      .join(format!("../lib/{}", package_info.name))
340      .canonicalize()
341    {
342      Ok(bundle_dir)
343    } else if let Some(appdir) = &env.appdir {
344      let appdir: &std::path::Path = appdir.as_ref();
345      Ok(PathBuf::from(format!(
346        "{}/usr/lib/{}",
347        appdir.display(),
348        package_info.name
349      )))
350    } else {
351      // running bundle
352      Ok(PathBuf::from(format!("/usr/lib/{}", package_info.name)))
353    };
354  }
355
356  #[cfg(target_os = "macos")]
357  {
358    res = exe_dir
359      .join("../Resources")
360      .canonicalize()
361      .map_err(Into::into);
362  }
363
364  #[cfg(target_os = "ios")]
365  {
366    res = exe_dir.join("assets").canonicalize().map_err(Into::into);
367  }
368
369  res
370}
371
372// Variable holding the type of bundle the executable is stored in. This is modified by binary
373// patching during build
374#[used]
375// Marked as `mut` because it could get optimized away without it,
376// see https://github.com/tauri-apps/tauri/pull/13812
377static mut __TAURI_BUNDLE_TYPE: &str = "__TAURI_BUNDLE_TYPE_VAR_UNK";
378
379/// Get the type of the bundle current binary is packaged in.
380/// If the bundle type is unknown, it returns [`Option::None`].
381pub fn bundle_type() -> Option<BundleType> {
382  unsafe {
383    match __TAURI_BUNDLE_TYPE {
384      "__TAURI_BUNDLE_TYPE_VAR_DEB" => Some(BundleType::Deb),
385      "__TAURI_BUNDLE_TYPE_VAR_RPM" => Some(BundleType::Rpm),
386      "__TAURI_BUNDLE_TYPE_VAR_APP" => Some(BundleType::AppImage),
387      "__TAURI_BUNDLE_TYPE_VAR_MSI" => Some(BundleType::Msi),
388      "__TAURI_BUNDLE_TYPE_VAR_NSS" => Some(BundleType::Nsis),
389      _ => {
390        if cfg!(target_os = "macos") {
391          Some(BundleType::App)
392        } else {
393          None
394        }
395      }
396    }
397  }
398}
399
400#[cfg(any(feature = "build", feature = "build-2"))]
401mod build {
402  use proc_macro2::TokenStream;
403  use quote::{ToTokens, TokenStreamExt, quote};
404
405  use super::*;
406
407  impl ToTokens for Target {
408    fn to_tokens(&self, tokens: &mut TokenStream) {
409      let prefix = quote! { ::tauri::utils::platform::Target };
410
411      tokens.append_all(match self {
412        Self::MacOS => quote! { #prefix::MacOS },
413        Self::Linux => quote! { #prefix::Linux },
414        Self::Windows => quote! { #prefix::Windows },
415        Self::Android => quote! { #prefix::Android },
416        Self::Ios => quote! { #prefix::Ios },
417      });
418    }
419  }
420}
421
422#[cfg(test)]
423mod tests {
424  use std::path::PathBuf;
425
426  use crate::{Env, PackageInfo};
427
428  #[test]
429  #[cfg(not(target_os = "android"))]
430  fn resolve_resource_dir() {
431    let package_info = PackageInfo {
432      name: "MyApp".into(),
433      version: "1.0.0".parse().unwrap(),
434      authors: "",
435      description: "",
436      crate_name: "my-app",
437    };
438    let env = Env::default();
439
440    let path = PathBuf::from("/path/to/target/aarch64-apple-darwin/debug/app");
441    let resource_dir = super::resource_dir_from(&path, &package_info, &env).unwrap();
442    assert_eq!(resource_dir, path.parent().unwrap());
443
444    let path = PathBuf::from("/path/to/target/custom-profile/app");
445    let resource_dir = super::resource_dir_from(&path, &package_info, &env).unwrap();
446    assert_eq!(resource_dir, path.parent().unwrap());
447
448    let path = PathBuf::from("/path/to/target/release/app");
449    let resource_dir = super::resource_dir_from(&path, &package_info, &env).unwrap();
450    assert_eq!(resource_dir, path.parent().unwrap());
451
452    let path = PathBuf::from("/path/to/target/unknown-profile/app");
453    #[allow(clippy::needless_borrows_for_generic_args)]
454    let resource_dir = super::resource_dir_from(&path, &package_info, &env);
455    #[cfg(target_os = "macos")]
456    assert!(resource_dir.is_err());
457    #[cfg(target_os = "linux")]
458    assert_eq!(resource_dir.unwrap(), PathBuf::from("/usr/lib/MyApp"));
459    #[cfg(windows)]
460    assert_eq!(resource_dir.unwrap(), path.parent().unwrap());
461  }
462}