file_system.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. // Copyright 2019-2022 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. #![allow(unused_imports)]
  5. use crate::{
  6. api::{
  7. dir,
  8. file::{self, SafePathBuf},
  9. path::BaseDirectory,
  10. },
  11. scope::Scopes,
  12. Config, Env, Manager, PackageInfo, Runtime, Window,
  13. };
  14. use super::InvokeContext;
  15. #[allow(unused_imports)]
  16. use anyhow::Context;
  17. use serde::{
  18. de::{Deserializer, Error as DeError},
  19. Deserialize, Serialize,
  20. };
  21. use tauri_macros::{command_enum, module_command_handler, CommandModule};
  22. use std::fmt::{Debug, Formatter};
  23. use std::{
  24. fs,
  25. fs::File,
  26. io::Write,
  27. path::{Component, Path},
  28. sync::Arc,
  29. };
  30. /// The options for the directory functions on the file system API.
  31. #[derive(Debug, Clone, Deserialize)]
  32. pub struct DirOperationOptions {
  33. /// Whether the API should recursively perform the operation on the directory.
  34. #[serde(default)]
  35. pub recursive: bool,
  36. /// The base directory of the operation.
  37. /// The directory path of the BaseDirectory will be the prefix of the defined directory path.
  38. pub dir: Option<BaseDirectory>,
  39. }
  40. /// The options for the file functions on the file system API.
  41. #[derive(Debug, Clone, Deserialize)]
  42. pub struct FileOperationOptions {
  43. /// The base directory of the operation.
  44. /// The directory path of the BaseDirectory will be the prefix of the defined file path.
  45. pub dir: Option<BaseDirectory>,
  46. }
  47. /// The API descriptor.
  48. #[command_enum]
  49. #[derive(Deserialize, CommandModule)]
  50. #[serde(tag = "cmd", rename_all = "camelCase")]
  51. pub(crate) enum Cmd {
  52. /// The read binary file API.
  53. #[cmd(fs_read_file, "fs > readFile")]
  54. ReadFile {
  55. path: SafePathBuf,
  56. options: Option<FileOperationOptions>,
  57. },
  58. /// The read binary file API.
  59. #[cmd(fs_read_file, "fs > readFile")]
  60. ReadTextFile {
  61. path: SafePathBuf,
  62. options: Option<FileOperationOptions>,
  63. },
  64. /// The write file API.
  65. #[cmd(fs_write_file, "fs > writeFile")]
  66. WriteFile {
  67. path: SafePathBuf,
  68. contents: Vec<u8>,
  69. options: Option<FileOperationOptions>,
  70. },
  71. /// The read dir API.
  72. #[cmd(fs_read_dir, "fs > readDir")]
  73. ReadDir {
  74. path: SafePathBuf,
  75. options: Option<DirOperationOptions>,
  76. },
  77. /// The copy file API.
  78. #[cmd(fs_copy_file, "fs > copyFile")]
  79. CopyFile {
  80. source: SafePathBuf,
  81. destination: SafePathBuf,
  82. options: Option<FileOperationOptions>,
  83. },
  84. /// The create dir API.
  85. #[cmd(fs_create_dir, "fs > createDir")]
  86. CreateDir {
  87. path: SafePathBuf,
  88. options: Option<DirOperationOptions>,
  89. },
  90. /// The remove dir API.
  91. #[cmd(fs_remove_dir, "fs > removeDir")]
  92. RemoveDir {
  93. path: SafePathBuf,
  94. options: Option<DirOperationOptions>,
  95. },
  96. /// The remove file API.
  97. #[cmd(fs_remove_file, "fs > removeFile")]
  98. RemoveFile {
  99. path: SafePathBuf,
  100. options: Option<FileOperationOptions>,
  101. },
  102. /// The rename file API.
  103. #[cmd(fs_rename_file, "fs > renameFile")]
  104. #[serde(rename_all = "camelCase")]
  105. RenameFile {
  106. old_path: SafePathBuf,
  107. new_path: SafePathBuf,
  108. options: Option<FileOperationOptions>,
  109. },
  110. /// The exists API.
  111. #[cmd(fs_exists, "fs > exists")]
  112. Exists {
  113. path: SafePathBuf,
  114. options: Option<FileOperationOptions>,
  115. },
  116. }
  117. impl Cmd {
  118. #[module_command_handler(fs_read_file)]
  119. fn read_file<R: Runtime>(
  120. context: InvokeContext<R>,
  121. path: SafePathBuf,
  122. options: Option<FileOperationOptions>,
  123. ) -> super::Result<Vec<u8>> {
  124. let resolved_path = resolve_path(
  125. &context.config,
  126. &context.package_info,
  127. &context.window,
  128. path,
  129. options.and_then(|o| o.dir),
  130. )?;
  131. file::read_binary(&resolved_path)
  132. .with_context(|| format!("path: {}", resolved_path.display()))
  133. .map_err(Into::into)
  134. }
  135. #[module_command_handler(fs_read_file)]
  136. fn read_text_file<R: Runtime>(
  137. context: InvokeContext<R>,
  138. path: SafePathBuf,
  139. options: Option<FileOperationOptions>,
  140. ) -> super::Result<String> {
  141. let resolved_path = resolve_path(
  142. &context.config,
  143. &context.package_info,
  144. &context.window,
  145. path,
  146. options.and_then(|o| o.dir),
  147. )?;
  148. file::read_string(&resolved_path)
  149. .with_context(|| format!("path: {}", resolved_path.display()))
  150. .map_err(Into::into)
  151. }
  152. #[module_command_handler(fs_write_file)]
  153. fn write_file<R: Runtime>(
  154. context: InvokeContext<R>,
  155. path: SafePathBuf,
  156. contents: Vec<u8>,
  157. options: Option<FileOperationOptions>,
  158. ) -> super::Result<()> {
  159. let resolved_path = resolve_path(
  160. &context.config,
  161. &context.package_info,
  162. &context.window,
  163. path,
  164. options.and_then(|o| o.dir),
  165. )?;
  166. File::create(&resolved_path)
  167. .with_context(|| format!("path: {}", resolved_path.display()))
  168. .map_err(Into::into)
  169. .and_then(|mut f| f.write_all(&contents).map_err(|err| err.into()))
  170. }
  171. #[module_command_handler(fs_read_dir)]
  172. fn read_dir<R: Runtime>(
  173. context: InvokeContext<R>,
  174. path: SafePathBuf,
  175. options: Option<DirOperationOptions>,
  176. ) -> super::Result<Vec<dir::DiskEntry>> {
  177. let (recursive, dir) = if let Some(options_value) = options {
  178. (options_value.recursive, options_value.dir)
  179. } else {
  180. (false, None)
  181. };
  182. let resolved_path = resolve_path(
  183. &context.config,
  184. &context.package_info,
  185. &context.window,
  186. path,
  187. dir,
  188. )?;
  189. dir::read_dir_with_options(
  190. &resolved_path,
  191. recursive,
  192. dir::ReadDirOptions {
  193. scope: Some(&context.window.state::<Scopes>().fs),
  194. },
  195. )
  196. .with_context(|| format!("path: {}", resolved_path.display()))
  197. .map_err(Into::into)
  198. }
  199. #[module_command_handler(fs_copy_file)]
  200. fn copy_file<R: Runtime>(
  201. context: InvokeContext<R>,
  202. source: SafePathBuf,
  203. destination: SafePathBuf,
  204. options: Option<FileOperationOptions>,
  205. ) -> super::Result<()> {
  206. let (src, dest) = match options.and_then(|o| o.dir) {
  207. Some(dir) => (
  208. resolve_path(
  209. &context.config,
  210. &context.package_info,
  211. &context.window,
  212. source,
  213. Some(dir),
  214. )?,
  215. resolve_path(
  216. &context.config,
  217. &context.package_info,
  218. &context.window,
  219. destination,
  220. Some(dir),
  221. )?,
  222. ),
  223. None => (source, destination),
  224. };
  225. fs::copy(src.clone(), dest.clone())
  226. .with_context(|| format!("source: {}, dest: {}", src.display(), dest.display()))?;
  227. Ok(())
  228. }
  229. #[module_command_handler(fs_create_dir)]
  230. fn create_dir<R: Runtime>(
  231. context: InvokeContext<R>,
  232. path: SafePathBuf,
  233. options: Option<DirOperationOptions>,
  234. ) -> super::Result<()> {
  235. let (recursive, dir) = if let Some(options_value) = options {
  236. (options_value.recursive, options_value.dir)
  237. } else {
  238. (false, None)
  239. };
  240. let resolved_path = resolve_path(
  241. &context.config,
  242. &context.package_info,
  243. &context.window,
  244. path,
  245. dir,
  246. )?;
  247. if recursive {
  248. fs::create_dir_all(&resolved_path)
  249. .with_context(|| format!("path: {}", resolved_path.display()))?;
  250. } else {
  251. fs::create_dir(&resolved_path)
  252. .with_context(|| format!("path: {} (non recursive)", resolved_path.display()))?;
  253. }
  254. Ok(())
  255. }
  256. #[module_command_handler(fs_remove_dir)]
  257. fn remove_dir<R: Runtime>(
  258. context: InvokeContext<R>,
  259. path: SafePathBuf,
  260. options: Option<DirOperationOptions>,
  261. ) -> super::Result<()> {
  262. let (recursive, dir) = if let Some(options_value) = options {
  263. (options_value.recursive, options_value.dir)
  264. } else {
  265. (false, None)
  266. };
  267. let resolved_path = resolve_path(
  268. &context.config,
  269. &context.package_info,
  270. &context.window,
  271. path,
  272. dir,
  273. )?;
  274. if recursive {
  275. fs::remove_dir_all(&resolved_path)
  276. .with_context(|| format!("path: {}", resolved_path.display()))?;
  277. } else {
  278. fs::remove_dir(&resolved_path)
  279. .with_context(|| format!("path: {} (non recursive)", resolved_path.display()))?;
  280. }
  281. Ok(())
  282. }
  283. #[module_command_handler(fs_remove_file)]
  284. fn remove_file<R: Runtime>(
  285. context: InvokeContext<R>,
  286. path: SafePathBuf,
  287. options: Option<FileOperationOptions>,
  288. ) -> super::Result<()> {
  289. let resolved_path = resolve_path(
  290. &context.config,
  291. &context.package_info,
  292. &context.window,
  293. path,
  294. options.and_then(|o| o.dir),
  295. )?;
  296. fs::remove_file(&resolved_path)
  297. .with_context(|| format!("path: {}", resolved_path.display()))?;
  298. Ok(())
  299. }
  300. #[module_command_handler(fs_rename_file)]
  301. fn rename_file<R: Runtime>(
  302. context: InvokeContext<R>,
  303. old_path: SafePathBuf,
  304. new_path: SafePathBuf,
  305. options: Option<FileOperationOptions>,
  306. ) -> super::Result<()> {
  307. let (old, new) = match options.and_then(|o| o.dir) {
  308. Some(dir) => (
  309. resolve_path(
  310. &context.config,
  311. &context.package_info,
  312. &context.window,
  313. old_path,
  314. Some(dir),
  315. )?,
  316. resolve_path(
  317. &context.config,
  318. &context.package_info,
  319. &context.window,
  320. new_path,
  321. Some(dir),
  322. )?,
  323. ),
  324. None => (old_path, new_path),
  325. };
  326. fs::rename(&old, &new)
  327. .with_context(|| format!("old: {}, new: {}", old.display(), new.display()))
  328. .map_err(Into::into)
  329. }
  330. #[module_command_handler(fs_exists)]
  331. fn exists<R: Runtime>(
  332. context: InvokeContext<R>,
  333. path: SafePathBuf,
  334. options: Option<FileOperationOptions>,
  335. ) -> super::Result<bool> {
  336. let resolved_path = resolve_path(
  337. &context.config,
  338. &context.package_info,
  339. &context.window,
  340. path,
  341. options.and_then(|o| o.dir),
  342. )?;
  343. Ok(resolved_path.as_ref().exists())
  344. }
  345. }
  346. #[allow(dead_code)]
  347. fn resolve_path<R: Runtime>(
  348. config: &Config,
  349. package_info: &PackageInfo,
  350. window: &Window<R>,
  351. path: SafePathBuf,
  352. dir: Option<BaseDirectory>,
  353. ) -> super::Result<SafePathBuf> {
  354. let env = window.state::<Env>().inner();
  355. match crate::api::path::resolve_path(config, package_info, env, &path, dir) {
  356. Ok(path) => {
  357. if window.state::<Scopes>().fs.is_allowed(&path) {
  358. Ok(
  359. // safety: the path is resolved by Tauri so it is safe
  360. unsafe { SafePathBuf::new_unchecked(path) },
  361. )
  362. } else {
  363. Err(anyhow::anyhow!(
  364. crate::Error::PathNotAllowed(path).to_string()
  365. ))
  366. }
  367. }
  368. Err(e) => super::Result::<SafePathBuf>::Err(e.into())
  369. .with_context(|| format!("path: {}, base dir: {:?}", path.display(), dir)),
  370. }
  371. }
  372. #[cfg(test)]
  373. mod tests {
  374. use super::{BaseDirectory, DirOperationOptions, FileOperationOptions, SafePathBuf};
  375. use quickcheck::{Arbitrary, Gen};
  376. impl Arbitrary for BaseDirectory {
  377. fn arbitrary(g: &mut Gen) -> Self {
  378. if bool::arbitrary(g) {
  379. BaseDirectory::AppData
  380. } else {
  381. BaseDirectory::Resource
  382. }
  383. }
  384. }
  385. impl Arbitrary for FileOperationOptions {
  386. fn arbitrary(g: &mut Gen) -> Self {
  387. Self {
  388. dir: Option::arbitrary(g),
  389. }
  390. }
  391. }
  392. impl Arbitrary for DirOperationOptions {
  393. fn arbitrary(g: &mut Gen) -> Self {
  394. Self {
  395. recursive: bool::arbitrary(g),
  396. dir: Option::arbitrary(g),
  397. }
  398. }
  399. }
  400. #[tauri_macros::module_command_test(fs_read_file, "fs > readFile")]
  401. #[quickcheck_macros::quickcheck]
  402. fn read_file(path: SafePathBuf, options: Option<FileOperationOptions>) {
  403. let res = super::Cmd::read_file(crate::test::mock_invoke_context(), path, options);
  404. crate::test_utils::assert_not_allowlist_error(res);
  405. }
  406. #[tauri_macros::module_command_test(fs_write_file, "fs > writeFile")]
  407. #[quickcheck_macros::quickcheck]
  408. fn write_file(path: SafePathBuf, contents: Vec<u8>, options: Option<FileOperationOptions>) {
  409. let res = super::Cmd::write_file(crate::test::mock_invoke_context(), path, contents, options);
  410. crate::test_utils::assert_not_allowlist_error(res);
  411. }
  412. #[tauri_macros::module_command_test(fs_read_dir, "fs > readDir")]
  413. #[quickcheck_macros::quickcheck]
  414. fn read_dir(path: SafePathBuf, options: Option<DirOperationOptions>) {
  415. let res = super::Cmd::read_dir(crate::test::mock_invoke_context(), path, options);
  416. crate::test_utils::assert_not_allowlist_error(res);
  417. }
  418. #[tauri_macros::module_command_test(fs_copy_file, "fs > copyFile")]
  419. #[quickcheck_macros::quickcheck]
  420. fn copy_file(
  421. source: SafePathBuf,
  422. destination: SafePathBuf,
  423. options: Option<FileOperationOptions>,
  424. ) {
  425. let res = super::Cmd::copy_file(
  426. crate::test::mock_invoke_context(),
  427. source,
  428. destination,
  429. options,
  430. );
  431. crate::test_utils::assert_not_allowlist_error(res);
  432. }
  433. #[tauri_macros::module_command_test(fs_create_dir, "fs > createDir")]
  434. #[quickcheck_macros::quickcheck]
  435. fn create_dir(path: SafePathBuf, options: Option<DirOperationOptions>) {
  436. let res = super::Cmd::create_dir(crate::test::mock_invoke_context(), path, options);
  437. crate::test_utils::assert_not_allowlist_error(res);
  438. }
  439. #[tauri_macros::module_command_test(fs_remove_dir, "fs > removeDir")]
  440. #[quickcheck_macros::quickcheck]
  441. fn remove_dir(path: SafePathBuf, options: Option<DirOperationOptions>) {
  442. let res = super::Cmd::remove_dir(crate::test::mock_invoke_context(), path, options);
  443. crate::test_utils::assert_not_allowlist_error(res);
  444. }
  445. #[tauri_macros::module_command_test(fs_remove_file, "fs > removeFile")]
  446. #[quickcheck_macros::quickcheck]
  447. fn remove_file(path: SafePathBuf, options: Option<FileOperationOptions>) {
  448. let res = super::Cmd::remove_file(crate::test::mock_invoke_context(), path, options);
  449. crate::test_utils::assert_not_allowlist_error(res);
  450. }
  451. #[tauri_macros::module_command_test(fs_rename_file, "fs > renameFile")]
  452. #[quickcheck_macros::quickcheck]
  453. fn rename_file(
  454. old_path: SafePathBuf,
  455. new_path: SafePathBuf,
  456. options: Option<FileOperationOptions>,
  457. ) {
  458. let res = super::Cmd::rename_file(
  459. crate::test::mock_invoke_context(),
  460. old_path,
  461. new_path,
  462. options,
  463. );
  464. crate::test_utils::assert_not_allowlist_error(res);
  465. }
  466. #[tauri_macros::module_command_test(fs_exists, "fs > exists")]
  467. #[quickcheck_macros::quickcheck]
  468. fn exists(path: SafePathBuf, options: Option<FileOperationOptions>) {
  469. let res = super::Cmd::exists(crate::test::mock_invoke_context(), path, options);
  470. crate::test_utils::assert_not_allowlist_error(res);
  471. }
  472. }