cap-tempfile-3.4.1/.cargo_vcs_info.json0000644000000001520000000000100134050ustar { "git": { "sha1": "c461c0799f831df5d8ca2e121b7f541d9e8143af" }, "path_in_vcs": "cap-tempfile" }cap-tempfile-3.4.1/COPYRIGHT000064400000000000000000000015551046102023000135000ustar 00000000000000Short version for non-lawyers: `cap-tempfile` is triple-licensed under Apache 2.0 with the LLVM Exception, Apache 2.0, and MIT terms. Longer version: Copyrights in the `cap-tempfile` project are retained by their contributors. No copyright assignment is required to contribute to the `cap-tempfile` project. Some files include code derived from Rust's `libstd`; see the comments in the code for details. Except as otherwise noted (below and/or in individual files), `cap-tempfile` is licensed under: - the Apache License, Version 2.0, with the LLVM Exception or - the Apache License, Version 2.0 or , - or the MIT license or , at your option. cap-tempfile-3.4.1/Cargo.toml0000644000000031110000000000100114010ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "cap-tempfile" version = "3.4.1" authors = [ "Dan Gohman ", "Jakub Konka ", ] build = false autobins = false autoexamples = false autotests = false autobenches = false description = "Capability-based temporary directories" readme = "README.md" keywords = [ "filesystem", "tmpfile", "tempfile", ] categories = ["filesystem"] license = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" repository = "https://github.com/bytecodealliance/cap-std" [lib] name = "cap_tempfile" path = "src/lib.rs" [dependencies.camino] version = "1.0.5" optional = true [dependencies.cap-std] version = "^3.4.1" [dependencies.uuid] version = "1.0.0" features = ["v4"] [features] arf_strings = ["cap-std/arf_strings"] default = [] fs_utf8 = [ "cap-std/fs_utf8", "camino", ] [target."cfg(not(windows))".dependencies.rustix] version = "0.38.0" features = ["procfs"] [target.'cfg(target_os = "emscripten")'.dependencies.rand] version = "0.8.1" [target."cfg(windows)".dev-dependencies.windows-sys] version = "0.52.0" features = ["Win32_Foundation"] cap-tempfile-3.4.1/Cargo.toml.orig000064400000000000000000000017131046102023000150700ustar 00000000000000[package] name = "cap-tempfile" version = "3.4.1" description = "Capability-based temporary directories" authors = [ "Dan Gohman ", "Jakub Konka ", ] license = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" keywords = ["filesystem", "tmpfile", "tempfile"] categories = ["filesystem"] repository = "https://github.com/bytecodealliance/cap-std" edition = "2021" [dependencies] cap-std = { path = "../cap-std", version = "^3.4.1" } uuid = { version = "1.0.0", features = ["v4"] } camino = { version = "1.0.5", optional = true } [target.'cfg(target_os = "emscripten")'.dependencies] rand = "0.8.1" [target.'cfg(not(windows))'.dependencies] rustix = { version = "0.38.0", features = ["procfs"] } [target.'cfg(windows)'.dev-dependencies.windows-sys] version = "0.52.0" features = [ "Win32_Foundation", ] [features] default = [] fs_utf8 = ["cap-std/fs_utf8", "camino"] arf_strings = ["cap-std/arf_strings"] cap-tempfile-3.4.1/LICENSE-APACHE000064400000000000000000000251371046102023000141330ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. cap-tempfile-3.4.1/LICENSE-Apache-2.0_WITH_LLVM-exception000064400000000000000000000277231046102023000203540ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- LLVM Exceptions to the Apache 2.0 License ---- As an exception, if, as a result of your compiling your source code, portions of this Software are embedded into an Object form of such source code, you may redistribute such embedded portions in such Object form without complying with the conditions of Sections 4(a), 4(b) and 4(d) of the License. In addition, if you combine or link compiled forms of this Software with software that is licensed under the GPLv2 ("Combined Software") and if a court of competent jurisdiction determines that the patent provision (Section 3), the indemnity provision (Section 9) or other Section of the License conflicts with the conditions of the GPLv2, you may retroactively and prospectively choose to deem waived or otherwise exclude such Section(s) of the License, but only in their entirety and only with respect to the Combined Software. cap-tempfile-3.4.1/LICENSE-MIT000064400000000000000000000017771046102023000136470ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. cap-tempfile-3.4.1/README.md000064400000000000000000000015651046102023000134650ustar 00000000000000

cap-tempfile

Capability-based temporary directories

Github Actions CI Status crates.io page docs.rs docs

The `cap-tempfile` crate provides utilities for creating temporary directories via the [`tempfile`] crate, but which provide [`Dir`]s instead of `Path`s. [`tempfile`]: https://crates.io/crates/tempfile [`Dir`]: https://docs.rs/cap-std/latest/cap_std/fs/struct.Dir.html cap-tempfile-3.4.1/src/lib.rs000064400000000000000000000203151046102023000141030ustar 00000000000000//! Capability-based temporary directories and files. #![deny(missing_docs)] #![forbid(unsafe_code)] #![doc( html_logo_url = "https://raw.githubusercontent.com/bytecodealliance/cap-std/main/media/cap-std.svg" )] #![doc( html_favicon_url = "https://raw.githubusercontent.com/bytecodealliance/cap-std/main/media/cap-std.ico" )] use cap_std::fs::Dir; use std::ops::Deref; use std::{env, fmt, fs, io, mem}; #[cfg(not(target_os = "emscripten"))] use uuid::Uuid; #[cfg(feature = "fs_utf8")] pub mod utf8; mod tempfile; pub use tempfile::*; /// Re-export because we use this in our public API. pub use cap_std; #[doc(hidden)] pub use cap_std::ambient_authority_known_at_compile_time; pub use cap_std::{ambient_authority, AmbientAuthority}; /// A directory in a filesystem that is automatically deleted when it goes out /// of scope. /// /// This corresponds to [`tempfile::TempDir`]. /// /// Unlike `tempfile::TempDir`, this API has no `TempDir::path`, /// `TempDir::into_path`, or `impl AsRef`, because absolute paths don't /// interoperate well with the capability model. /// /// [`tempfile::TempDir`]: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html pub struct TempDir { dir: Option, } impl TempDir { /// Attempts to make a temporary directory inside of `env::temp_dir()`. /// /// This corresponds to [`tempfile::TempDir::new`]. /// /// [`tempfile::TempDir::new`]: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html#method.new /// /// # Ambient Authority /// /// This function makes use of ambient authority to access temporary /// directories. pub fn new(ambient_authority: AmbientAuthority) -> io::Result { let system_tmp = env::temp_dir(); for _ in 0..Self::num_iterations() { let name = system_tmp.join(&Self::new_name()); match fs::create_dir(&name) { Ok(()) => { let dir = match Dir::open_ambient_dir(&name, ambient_authority) { Ok(dir) => dir, Err(e) => { fs::remove_dir(name).ok(); return Err(e); } }; return Ok(Self { dir: Some(dir) }); } Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, Err(e) => return Err(e), } } Err(Self::already_exists()) } /// Create a new temporary directory. /// /// This corresponds to [`tempfile::TempDir::new_in`]. /// /// [`tempfile::TempDir::new_in`]: https://docs.rs/tempfile/latest/tempfile/fn.tempdir_in.html pub fn new_in(dir: &Dir) -> io::Result { for _ in 0..Self::num_iterations() { let name = &Self::new_name(); match dir.create_dir(name) { Ok(()) => { let dir = match dir.open_dir(name) { Ok(dir) => dir, Err(e) => { dir.remove_dir(name).ok(); return Err(e); } }; return Ok(Self { dir: Some(dir) }); } Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, Err(e) => return Err(e), } } Err(Self::already_exists()) } /// Make this directory persistent. /// /// This corresponds to [`tempfile::TempDir::into_path`], but returns a [`Dir`]. /// /// [`tempfile::TempDir::into_path`]: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html#method.into_path /// [`Dir`]: https://docs.rs/cap-std/latest/cap_std/fs/struct.Dir.html pub fn into_dir(mut self) -> io::Result { Ok(self.dir.take().unwrap()) } /// Closes and removes the temporary directory, returning a `Result`. /// /// This corresponds to [`tempfile::TempDir::close`]. /// /// [`tempfile::TempDir::close`]: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html#method.close pub fn close(mut self) -> io::Result<()> { mem::take(&mut self.dir).unwrap().remove_open_dir_all() } pub(crate) fn new_name() -> String { #[cfg(not(target_os = "emscripten"))] { Uuid::new_v4().to_string() } // Uuid doesn't support Emscripten yet, but Emscripten isn't multi-user // or multi-process yet, so we can do something simple. #[cfg(target_os = "emscripten")] { use rand::RngCore; let mut r = rand::thread_rng(); format!("cap-primitives.{}", r.next_u32()) } } pub(crate) const fn num_iterations() -> i32 { i32::MAX } fn already_exists() -> io::Error { io::Error::new( io::ErrorKind::AlreadyExists, "too many temporary files exist", ) } } impl Deref for TempDir { type Target = Dir; fn deref(&self) -> &Self::Target { self.dir.as_ref().unwrap() } } impl Drop for TempDir { fn drop(&mut self) { if let Some(dir) = mem::take(&mut self.dir) { dir.remove_open_dir_all().ok(); } } } impl fmt::Debug for TempDir { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.dir.fmt(f) } } /// Create a new temporary directory. /// /// This corresponds to [`tempfile::tempdir`]. /// /// [`tempfile::tempdir`]: https://docs.rs/tempfile/latest/tempfile/fn.tempdir.html /// /// # Ambient Authority /// /// This function makes use of ambient authority to access temporary /// directories. pub fn tempdir(ambient_authority: AmbientAuthority) -> io::Result { TempDir::new(ambient_authority) } /// Create a new temporary directory. /// /// This corresponds to [`tempfile::tempdir_in`]. /// /// [`tempfile::tempdir_in`]: https://docs.rs/tempfile/latest/tempfile/fn.tempdir_in.html pub fn tempdir_in(dir: &Dir) -> io::Result { TempDir::new_in(dir) } /// Call f repeatedly, passing a randomly generated temporary name. /// An error matching the `err` will be ignored. /// This will repeat until a maximum number of attempts is reached. /// On success, the result of the function call along with the provided name is /// returned. pub(crate) fn retry_with_name_ignoring( err: std::io::ErrorKind, mut f: F, ) -> io::Result<(T, String)> where F: FnMut(&str) -> io::Result, { for _ in 0..TempDir::num_iterations() { let name = TempDir::new_name(); match f(name.as_str()) { Ok(r) => return Ok((r, name)), Err(e) if e.kind() == err => continue, Err(e) => return Err(e), } } Err(std::io::Error::new(err, "too many temporary files exist")) } #[test] fn drop_tempdir() { use crate::ambient_authority; let t = tempdir(ambient_authority()).unwrap(); drop(t) } #[test] fn close_tempdir() { use crate::ambient_authority; let t = tempdir(ambient_authority()).unwrap(); t.close().unwrap(); } #[test] fn persist_tempdir() { use crate::ambient_authority; let t = tempdir(ambient_authority()).unwrap(); let d = t.into_dir().unwrap(); assert!(d.exists(".")); } #[test] fn drop_tempdir_in() { use crate::ambient_authority; let dir = Dir::open_ambient_dir(env::temp_dir(), ambient_authority()).unwrap(); let t = tempdir_in(&dir).unwrap(); drop(t); } #[test] fn close_tempdir_in() { use crate::ambient_authority; let dir = Dir::open_ambient_dir(env::temp_dir(), ambient_authority()).unwrap(); let t = tempdir_in(&dir).unwrap(); t.close().unwrap(); } #[test] fn close_outer() { use crate::ambient_authority; let t = tempdir(ambient_authority()).unwrap(); let _s = tempdir_in(&t).unwrap(); #[cfg(windows)] assert!(matches!( t.close().unwrap_err().raw_os_error().map(|err| err as _), Some(windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION) | Some(windows_sys::Win32::Foundation::ERROR_DIR_NOT_EMPTY) )); #[cfg(not(windows))] t.close().unwrap(); } #[test] fn close_inner() { use crate::ambient_authority; let t = tempdir(ambient_authority()).unwrap(); let s = tempdir_in(&t).unwrap(); s.close().unwrap(); } cap-tempfile-3.4.1/src/tempfile.rs000064400000000000000000000260641046102023000151510ustar 00000000000000//! Temporary files. use cap_std::fs::{Dir, File}; use std::ffi::OsStr; use std::fmt::Debug; use std::io::{self, Read, Seek, Write}; /// A file in a directory that is by default deleted when it goes out /// of scope, but may also be written persistently. /// /// This corresponds most closely to [`tempfile::NamedTempFile`]; however, /// there are some important differences, so read the below carefully /// to understand how to port existing code. /// /// # Name-able, but not necessarily named /// /// By default, the file does not necessarily have an name until the file is /// written persistently. /// /// On some operating systems like Linux, it is possible to create anonymous /// temporary files that can still be written to disk persistently via /// `O_TMPFILE`. The advantage of this is that if the process (or operating /// system) crashes while the file is being written, the temporary space will /// be automatically cleaned up. For this reason, there is no API to retrieve /// the name, for either case. /// /// To more closely match the semantics of [`tempfile::tempfile`], use /// [`crate::TempFile::new_anonymous`]. /// /// # File permissions /// /// Unlike the tempfile crate, the default [`TempFile::new`] will use the same /// permissions as [`File::create_new`] in the Rust standard library. /// Concretely on Unix systems for example this can (depending on `umask`) /// result in files that are readable by all users. The rationale for this is /// to make it more ergonomic and natural to use this API to atomically create /// new files and replace existing ones. Many cases that want "private" files /// will prefer [`TempFile::new_anonymous`] to have the file not be accessible /// at all outside the current process. /// /// To fully control the permissions of the resulting file, you can use /// [`File::set_permissions`]. /// /// [`tempfile::tempfile`]: https://docs.rs/tempfile/latest/tempfile/fn.tempfile.html /// [`tempfile::NamedTempFile`]: https://docs.rs/tempfile/latest/tempfile/struct.NamedTempFile.html /// [`File::create_new`]: https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.create_new /// [`File::set_permissions`]: https://docs.rs/cap-std/latest/cap_std/fs/struct.File.html#method.set_permissions pub struct TempFile<'d> { dir: &'d Dir, fd: File, name: Option, } impl<'d> Debug for TempFile<'d> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // Manual Debug implementation to omit the file reference and name so // we don't leak the path, the same as `cap_std::fs::File`. f.debug_struct("TempFile").field("dir", &self.dir).finish() } } #[cfg(any(target_os = "android", target_os = "linux"))] fn new_tempfile_linux(d: &Dir, anonymous: bool) -> io::Result> { use rustix::fs::{Mode, OFlags}; // openat's API uses WRONLY. There may be use cases for reading too, so let's // support it. let mut oflags = OFlags::CLOEXEC | OFlags::TMPFILE | OFlags::RDWR; if anonymous { oflags |= OFlags::EXCL; } // We default to 0o666, same as main rust when creating new files; this will be // modified by umask: let mode = Mode::from_raw_mode(0o666); // Happy path - Linux with O_TMPFILE match rustix::fs::openat(d, ".", oflags, mode) { Ok(r) => Ok(Some(File::from(r))), // See Err(rustix::io::Errno::OPNOTSUPP | rustix::io::Errno::ISDIR | rustix::io::Errno::NOENT) => { Ok(None) } Err(e) => Err(e.into()), } } /// Assign a random name to a currently anonymous O_TMPFILE descriptor. #[cfg(any(target_os = "android", target_os = "linux"))] fn generate_name_in(subdir: &Dir, f: &File) -> io::Result { use rustix::fd::AsFd; use rustix::fs::AtFlags; let procself_fd = rustix::procfs::proc_self_fd()?; let fdnum = rustix::path::DecInt::from_fd(f.as_fd()); let fdnum = fdnum.as_c_str(); super::retry_with_name_ignoring(io::ErrorKind::AlreadyExists, |name| { rustix::fs::linkat(procself_fd, fdnum, subdir, name, AtFlags::SYMLINK_FOLLOW) .map_err(Into::into) }) .map(|(_, name)| name) } /// Create a new temporary file in the target directory, which may or may not /// have a (randomly generated) name at this point. If anonymous is specified, /// the file will be deleted fn new_tempfile(d: &Dir, anonymous: bool) -> io::Result<(File, Option)> { // On Linux, try O_TMPFILE #[cfg(any(target_os = "android", target_os = "linux"))] if let Some(f) = new_tempfile_linux(d, anonymous)? { return Ok((f, None)); } // Otherwise, fall back to just creating a randomly named file. let mut opts = cap_std::fs::OpenOptions::new(); opts.read(true); opts.write(true); opts.create_new(true); let (f, name) = super::retry_with_name_ignoring(io::ErrorKind::AlreadyExists, |name| { d.open_with(name, &opts) })?; if anonymous { d.remove_file(name)?; Ok((f, None)) } else { Ok((f, Some(name))) } } impl<'d> TempFile<'d> { /// Crate a new temporary file in the provided directory. pub fn new(dir: &'d Dir) -> io::Result { let (fd, name) = new_tempfile(dir, false)?; Ok(Self { dir, fd, name }) } /// Crate a new temporary file in the provided directory that will not have /// a name. This corresponds to [`tempfile::tempfile_in`]. /// /// [`tempfile::tempfile_in`]: https://docs.rs/tempfile/latest/tempfile/fn.tempfile_in.html pub fn new_anonymous(dir: &'d Dir) -> io::Result { new_tempfile(dir, true).map(|v| v.0) } /// Get a reference to the underlying file. pub fn as_file(&self) -> &File { &self.fd } /// Get a mutable reference to the underlying file. pub fn as_file_mut(&mut self) -> &mut File { &mut self.fd } fn impl_replace(mut self, destname: &OsStr) -> io::Result<()> { // At this point on Linux if O_TMPFILE is used, we need to give the file a // temporary name in order to link it into place. There are patches to // add an `AT_LINKAT_REPLACE` API. With that we could skip this and // have file-leak-proof atomic file replacement: #[cfg(any(target_os = "android", target_os = "linux"))] let tempname = self .name .take() .map(Ok) .unwrap_or_else(|| generate_name_in(self.dir, &self.fd))?; // SAFETY: We only support anonymous files on Linux, so the file must have a // name here. #[cfg(not(any(target_os = "android", target_os = "linux")))] let tempname = self.name.take().unwrap(); // And try the rename into place. self.dir.rename(&tempname, self.dir, destname).map_err(|e| { // But, if we catch an error here, then move ownership back into self, // which means the Drop invocation will clean it up. self.name = Some(tempname); e }) } /// Write the file to the target directory with the provided name. /// Any existing file will be replaced. /// /// The file permissions will default to read-only. pub fn replace(self, destname: impl AsRef) -> io::Result<()> { let destname = destname.as_ref(); self.impl_replace(destname) } } impl<'d> Read for TempFile<'d> { fn read(&mut self, buf: &mut [u8]) -> io::Result { self.as_file_mut().read(buf) } } impl<'d> Write for TempFile<'d> { fn write(&mut self, buf: &[u8]) -> io::Result { self.as_file_mut().write(buf) } #[inline] fn flush(&mut self) -> io::Result<()> { self.as_file_mut().flush() } } impl<'d> Seek for TempFile<'d> { fn seek(&mut self, pos: io::SeekFrom) -> io::Result { self.as_file_mut().seek(pos) } } impl<'d> Drop for TempFile<'d> { fn drop(&mut self) { if let Some(name) = self.name.take() { let _ = self.dir.remove_file(name); } } } #[cfg(test)] mod test { use super::*; /// On Unix, calling `umask()` actually *mutates* the process global state. /// This uses Linux `/proc` to read the current value. #[cfg(any(target_os = "android", target_os = "linux"))] fn get_process_umask() -> io::Result { use io::BufRead; let status = std::fs::File::open("/proc/self/status")?; let bufr = io::BufReader::new(status); for line in bufr.lines() { let line = line?; let l = if let Some(v) = line.split_once(':') { v } else { continue; }; let (k, v) = l; if k != "Umask" { continue; } return Ok(u32::from_str_radix(v.trim(), 8).unwrap()); } panic!("Could not determine process umask") } /// Older Windows versions don't support removing open files fn os_supports_unlinked_tmp(d: &Dir) -> bool { if cfg!(not(windows)) { return true; } let name = "testfile"; let _f = d.create(name).unwrap(); d.remove_file(name).and_then(|_| d.create(name)).is_ok() } #[test] fn test_tempfile() -> io::Result<()> { use crate::ambient_authority; let td = crate::tempdir(ambient_authority())?; // Base case, verify we clean up on drop let tf = TempFile::new(&td).unwrap(); drop(tf); assert_eq!(td.entries()?.into_iter().count(), 0); let mut tf = TempFile::new(&td)?; // Test that we created with the right permissions #[cfg(any(target_os = "android", target_os = "linux"))] { use cap_std::fs_utf8::MetadataExt; use rustix::fs::Mode; let umask = get_process_umask()?; let metadata = tf.as_file().metadata().unwrap(); let mode = metadata.mode(); let mode = Mode::from_bits_truncate(mode); assert_eq!(0o666 & !umask, mode.bits() & 0o777); } // And that we can write tf.write_all(b"hello world")?; drop(tf); assert_eq!(td.entries()?.into_iter().count(), 0); let mut tf = TempFile::new(&td)?; tf.write_all(b"hello world")?; tf.replace("testfile").unwrap(); assert_eq!(td.entries()?.into_iter().count(), 1); assert_eq!(td.read("testfile")?, b"hello world"); if os_supports_unlinked_tmp(&td) { let mut tf = TempFile::new_anonymous(&td).unwrap(); tf.write_all(b"hello world, I'm anonymous").unwrap(); tf.seek(std::io::SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); tf.read_to_string(&mut buf).unwrap(); assert_eq!(&buf, "hello world, I'm anonymous"); } else if cfg!(windows) { eprintln!("notice: Detected older Windows"); } td.close() } } cap-tempfile-3.4.1/src/utf8.rs000064400000000000000000000122051046102023000142220ustar 00000000000000//! Capability-based temporary directories, with UTF-8 paths. //! //! TODO: This whole scheme is still under development. #[cfg(test)] use camino::Utf8PathBuf; use cap_std::fs_utf8::Dir; #[cfg(test)] use std::env; use std::ops::Deref; use std::{fmt, io, mem}; #[doc(hidden)] pub use cap_std::ambient_authority_known_at_compile_time; pub use cap_std::{ambient_authority, AmbientAuthority}; /// A directory in a filesystem that is automatically deleted when it goes out /// of scope. /// /// This corresponds to [`tempfile::TempDir`]. /// /// Unlike `tempfile::TempDir`, this API has no `TempDir::path`, /// `TempDir::into_path`, or `impl AsRef`, because absolute paths /// don't interoperate well with the capability model. /// /// [`tempfile::TempDir`]: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html pub struct TempDir { dir: Option, } impl TempDir { // Consume a base/non-UTF8 tempdir instance and return a UTF8 version fn from_cap_std(mut td: super::TempDir) -> Self { // Take ownership of the underlying Dir instance let dir = td.dir.take().map(Dir::from_cap_std); Self { dir } } /// Attempts to make a temporary directory inside of `env::temp_dir()`. /// /// This corresponds to [`tempfile::TempDir::new`]. /// /// [`tempfile::TempDir::new`]: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html#method.new /// /// # Ambient Authority /// /// This function makes use of ambient authority to access temporary /// directories. pub fn new(ambient_authority: AmbientAuthority) -> io::Result { // Because a Dir instance doesn't have a name accessible to the calling // code, we just delegate to the non-UTF8 base version. In some presumably // very unusual situations the tempdir may have a non-UTF8 name, // but that's fine. super::TempDir::new(ambient_authority).map(Self::from_cap_std) } /// Create a new temporary directory. /// /// This corresponds to [`tempfile::TempDir::new_in`]. /// /// [`tempfile::TempDir::new_in`]: https://docs.rs/tempfile/latest/tempfile/fn.tempdir_in.html pub fn new_in(dir: &Dir) -> io::Result { super::TempDir::new_in(dir.as_cap_std()).map(Self::from_cap_std) } /// Closes and removes the temporary directory, returning a `Result`. /// /// This corresponds to [`tempfile::TempDir::close`]. /// /// [`tempfile::TempDir::close`]: https://docs.rs/tempfile/latest/tempfile/struct.TempDir.html#method.close pub fn close(mut self) -> io::Result<()> { mem::take(&mut self.dir).unwrap().remove_open_dir_all() } } impl Deref for TempDir { type Target = Dir; fn deref(&self) -> &Self::Target { self.dir.as_ref().unwrap() } } impl Drop for TempDir { fn drop(&mut self) { if let Some(dir) = mem::take(&mut self.dir) { dir.remove_open_dir_all().ok(); } } } impl fmt::Debug for TempDir { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.dir.fmt(f) } } /// Create a new temporary directory. /// /// This corresponds to [`tempfile::tempdir`]. /// /// [`tempfile::tempdir`]: https://docs.rs/tempfile/latest/tempfile/fn.tempdir.html /// /// # Ambient Authority /// /// This function makes use of ambient authority to access temporary /// directories. pub fn tempdir(ambient_authority: AmbientAuthority) -> io::Result { TempDir::new(ambient_authority) } /// Create a new temporary directory. /// /// This corresponds to [`tempfile::tempdir_in`]. /// /// [`tempfile::tempdir_in`]: https://docs.rs/tempfile/latest/tempfile/fn.tempdir_in.html pub fn tempdir_in(dir: &Dir) -> io::Result { TempDir::new_in(dir) } #[test] fn drop_tempdir() { use crate::ambient_authority; let t = tempdir(ambient_authority()).unwrap(); drop(t) } #[test] fn close_tempdir() { use crate::ambient_authority; let t = tempdir(ambient_authority()).unwrap(); t.close().unwrap(); } #[test] fn drop_tempdir_in() { use crate::ambient_authority; let temp_dir: Utf8PathBuf = env::temp_dir().try_into().unwrap(); let dir = Dir::open_ambient_dir(temp_dir, ambient_authority()).unwrap(); let t = tempdir_in(&dir).unwrap(); drop(t); } #[test] fn close_tempdir_in() { use crate::ambient_authority; let temp_dir: Utf8PathBuf = env::temp_dir().try_into().unwrap(); let dir = Dir::open_ambient_dir(temp_dir, ambient_authority()).unwrap(); let t = tempdir_in(&dir).unwrap(); t.close().unwrap(); } #[test] fn close_outer() { use crate::ambient_authority; let t = tempdir(ambient_authority()).unwrap(); let _s = tempdir_in(&t).unwrap(); #[cfg(windows)] assert!(matches!( t.close().unwrap_err().raw_os_error().map(|err| err as _), Some(windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION) | Some(windows_sys::Win32::Foundation::ERROR_DIR_NOT_EMPTY) )); #[cfg(not(windows))] t.close().unwrap(); } #[test] fn close_inner() { use crate::ambient_authority; let t = tempdir(ambient_authority()).unwrap(); let s = tempdir_in(&t).unwrap(); s.close().unwrap(); }