all lists on lists.proxmox.com
 help / color / mirror / Atom feed
* [pbs-devel] [PATCH v3 proxmox] Add tempfile() helper function
@ 2020-08-13 14:56 Mira Limbeck
  2020-08-13 14:56 ` [pbs-devel] [PATCH v3 proxmox-backup] Replace all occurences of open() with O_TMPFILE Mira Limbeck
  0 siblings, 1 reply; 2+ messages in thread
From: Mira Limbeck @ 2020-08-13 14:56 UTC (permalink / raw)
  To: pbs-devel

The tempfile() helper function tries to create a temporary file in /tmp
with the O_TMPFILE option. If that fails it falls back to using
mkstemp().

As O_TMPFILE was introduced in kernel 3.11 this fallback can help with
CentOS 7 and its 3.10 kernel as well as with WSL (Windows Subsystem for
Linux).

Signed-off-by: Mira Limbeck <m.limbeck@proxmox.com>
---
v3:
    - O_TMPFILE support is tested on first run of tempfile()
    - EISDIR is handled specifically to test for O_TMPFILE support
    - AtomicBool is used as it provides a safe interface, but 'static mut'
        could also be used
    - mkstemp() now creates the tempfile in a subdirectory called
      proxmox-backup-<UID>

 proxmox/src/tools/fs.rs | 62 +++++++++++++++++++++++++++++++++++++++--
 1 file changed, 60 insertions(+), 2 deletions(-)

diff --git a/proxmox/src/tools/fs.rs b/proxmox/src/tools/fs.rs
index b1a95b5..0a12254 100644
--- a/proxmox/src/tools/fs.rs
+++ b/proxmox/src/tools/fs.rs
@@ -1,17 +1,20 @@
 //! File related utilities such as `replace_file`.
 
 use std::ffi::CStr;
-use std::fs::{File, OpenOptions};
+use std::fs::{DirBuilder, File, OpenOptions};
 use std::io::{self, BufRead, BufReader, Write};
+use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
 use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
 use std::path::Path;
+use std::sync::atomic::{AtomicBool, Ordering};
 use std::time::Duration;
 
 use anyhow::{bail, format_err, Error};
+use lazy_static::lazy_static;
 use nix::errno::Errno;
 use nix::fcntl::OFlag;
 use nix::sys::stat;
-use nix::unistd::{self, Gid, Uid};
+use nix::unistd::{self, mkstemp, unlink, Gid, Uid};
 use serde_json::Value;
 
 use crate::sys::error::SysResult;
@@ -518,3 +521,58 @@ pub fn open_file_locked<P: AsRef<Path>>(path: P, timeout: Duration) -> Result<Fi
         Err(err) => bail!("Unable to acquire lock {:?} - {}", path, err),
     }
 }
+
+static O_TMPFILE_SUPPORT: AtomicBool = AtomicBool::new(true);
+lazy_static! {
+    static ref MKSTEMP_PATH: String = {
+        use nix::unistd::geteuid;
+        let uid = geteuid();
+        format!("/tmp/proxmox-backup-{}", uid)
+    };
+    static ref MKSTEMP_FILE: String = {
+        format!("{}/tmpfile_XXXXXX", MKSTEMP_PATH.as_str())
+    };
+}
+
+/// Create a new tempfile by using O_TMPFILE with a fallback to mkstemp() if it fails (e.g. not supported).
+pub fn tempfile() -> Result<File, Error> {
+    if O_TMPFILE_SUPPORT.load(Ordering::Relaxed) {
+        match std::fs::OpenOptions::new()
+            .write(true)
+            .read(true)
+            .custom_flags(libc::O_TMPFILE)
+            .open("/tmp")
+            {
+                Ok(file) => return Ok(file),
+                Err(err) => {
+                    let raw_os_error = match err.raw_os_error() {
+                        Some(v) => v,
+                        None => -1,
+                    };
+                    if raw_os_error == 21 {
+                        O_TMPFILE_SUPPORT.store(false, Ordering::Relaxed);
+                        eprintln!(
+                            "Error creating tempfile: 'EISDIR', falling back to mkstemp() instead",
+                        );
+                    } else {
+                        bail!("Error creating tempfile: '{}'", err);
+                    }
+                }
+            }
+    }
+
+
+    match DirBuilder::new().recursive(true).mode(0o700).create(MKSTEMP_PATH.as_str()) {
+        Err(err) => {
+            if err.kind() != std::io::ErrorKind::AlreadyExists {
+                bail!("Error creating directory: '{}'", MKSTEMP_PATH.as_str());
+            }
+            // ignore EEXISTS
+        },
+        _ => {},
+    }
+    let (fd, path) = mkstemp(MKSTEMP_FILE.as_str())?;
+    unlink(path.as_path())?;
+    let file = unsafe { File::from_raw_fd(fd) };
+    Ok(file)
+}
-- 
2.20.1





^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2020-08-13 14:56 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2020-08-13 14:56 [pbs-devel] [PATCH v3 proxmox] Add tempfile() helper function Mira Limbeck
2020-08-13 14:56 ` [pbs-devel] [PATCH v3 proxmox-backup] Replace all occurences of open() with O_TMPFILE Mira Limbeck

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal