]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
tmpfile-util: Add fopen_temporary_at()
authorDaan De Meyer <daan.j.demeyer@gmail.com>
Mon, 26 Sep 2022 09:59:21 +0000 (11:59 +0200)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Wed, 9 Nov 2022 10:14:10 +0000 (11:14 +0100)
src/basic/tmpfile-util.c
src/basic/tmpfile-util.h

index f3f9062121e29d1e50fffe6ddc875fc08bcbd78e..e0e58472d37314b0e763ee51f6357c9f68b23e10 100644 (file)
 #include "tmpfile-util.h"
 #include "umask-util.h"
 
-int fopen_temporary(const char *path, FILE **ret_f, char **ret_temp_path) {
+int fopen_temporary_at(int dir_fd, const char *path, FILE **ret_file, char **ret_temp_path) {
         _cleanup_fclose_ FILE *f = NULL;
         _cleanup_free_ char *t = NULL;
         _cleanup_close_ int fd = -1;
         int r;
 
         if (path) {
-                r = tempfn_xxxxxx(path, NULL, &t);
+                r = tempfn_random(path, NULL, &t);
                 if (r < 0)
                         return r;
         } else {
@@ -36,12 +36,12 @@ int fopen_temporary(const char *path, FILE **ret_f, char **ret_temp_path) {
                 if (r < 0)
                         return r;
 
-                t = path_join(d, "XXXXXX");
-                if (!t)
-                        return -ENOMEM;
+                r = tempfn_random_child(d, NULL, &t);
+                if (r < 0)
+                        return r;
         }
 
-        fd = mkostemp_safe(t);
+        fd = openat(dir_fd, t, O_CLOEXEC|O_NOCTTY|O_RDWR|O_CREAT|O_EXCL, 0600);
         if (fd < 0)
                 return -errno;
 
@@ -50,12 +50,12 @@ int fopen_temporary(const char *path, FILE **ret_f, char **ret_temp_path) {
 
         r = take_fdopen_unlocked(&fd, "w", &f);
         if (r < 0) {
-                (void) unlink(t);
+                (void) unlinkat(dir_fd, t, 0);
                 return r;
         }
 
-        if (ret_f)
-                *ret_f = TAKE_PTR(f);
+        if (ret_file)
+                *ret_file = TAKE_PTR(f);
 
         if (ret_temp_path)
                 *ret_temp_path = TAKE_PTR(t);
index 96e37cc5783b407faea3d309444c72de1fd47e61..4af28b9da34be3dd92690b95d4a925e79dbaf5bd 100644 (file)
@@ -1,9 +1,13 @@
 /* SPDX-License-Identifier: LGPL-2.1-or-later */
 #pragma once
 
+#include <fcntl.h>
 #include <stdio.h>
 
-int fopen_temporary(const char *path, FILE **_f, char **_temp_path);
+int fopen_temporary_at(int dir_fd, const char *path, FILE **ret_file, char **ret_path);
+static inline int fopen_temporary(const char *path, FILE **ret_file, char **ret_path) {
+        return fopen_temporary_at(AT_FDCWD, path, ret_file, ret_path);
+}
 int mkostemp_safe(char *pattern);
 int fmkostemp_safe(char *pattern, const char *mode, FILE**_f);