1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
7 #include <linux/falloc.h>
8 #include <linux/magic.h>
11 #include "alloc-util.h"
12 #include "dirent-util.h"
16 #include "hostname-util.h"
17 #include "lock-util.h"
20 #include "missing_fcntl.h"
21 #include "missing_fs.h"
22 #include "missing_syscall.h"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "process-util.h"
27 #include "random-util.h"
28 #include "ratelimit.h"
29 #include "stat-util.h"
30 #include "stdio-util.h"
31 #include "string-util.h"
33 #include "time-util.h"
34 #include "tmpfile-util.h"
35 #include "umask-util.h"
36 #include "user-util.h"
38 int rmdir_parents(const char *path
, const char *stop
) {
45 if (!path_is_safe(path
))
48 if (!path_is_safe(stop
))
51 p
= strdupa_safe(path
);
56 /* skip the last component. */
57 r
= path_find_last_component(p
, /* accept_dot_dot= */ false, (const char **) &slash
, NULL
);
63 assert(*slash
== '/');
66 if (path_startswith_full(stop
, p
, /* accept_dot_dot= */ false))
69 if (rmdir(p
) < 0 && errno
!= ENOENT
)
74 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
77 /* Try the ideal approach first */
78 if (renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
) >= 0)
81 /* renameat2() exists since Linux 3.15, btrfs and FAT added support for it later. If it is not implemented,
82 * fall back to a different method. */
83 if (!ERRNO_IS_NOT_SUPPORTED(errno
) && errno
!= EINVAL
)
86 /* Let's try to use linkat()+unlinkat() as fallback. This doesn't work on directories and on some file systems
87 * that do not support hard links (such as FAT, most prominently), but for files it's pretty close to what we
88 * want — though not atomic (i.e. for a short period both the new and the old filename will exist). */
89 if (linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0) >= 0) {
91 r
= RET_NERRNO(unlinkat(olddirfd
, oldpath
, 0));
93 (void) unlinkat(newdirfd
, newpath
, 0);
100 if (!ERRNO_IS_NOT_SUPPORTED(errno
) && !IN_SET(errno
, EINVAL
, EPERM
)) /* FAT returns EPERM on link()… */
103 /* OK, neither RENAME_NOREPLACE nor linkat()+unlinkat() worked. Let's then fall back to the racy TOCTOU
104 * vulnerable accessat(F_OK) check followed by classic, replacing renameat(), we have nothing better. */
106 if (faccessat(newdirfd
, newpath
, F_OK
, AT_SYMLINK_NOFOLLOW
) >= 0)
111 return RET_NERRNO(renameat(olddirfd
, oldpath
, newdirfd
, newpath
));
114 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
120 _cleanup_free_
char *c
= NULL
;
127 n
= readlinkat(fd
, p
, c
, l
);
131 if ((size_t) n
< l
) {
140 if (l
> (SSIZE_MAX
-1)/2) /* readlinkat() returns an ssize_t, and we want an extra byte for a
141 * trailing NUL, hence do an overflow check relative to SSIZE_MAX-1
149 int readlink_malloc(const char *p
, char **ret
) {
150 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
153 int readlink_value(const char *p
, char **ret
) {
154 _cleanup_free_
char *link
= NULL
, *name
= NULL
;
160 r
= readlink_malloc(p
, &link
);
164 r
= path_extract_filename(link
, &name
);
167 if (r
== O_DIRECTORY
)
170 *ret
= TAKE_PTR(name
);
174 int readlink_and_make_absolute(const char *p
, char **ret
) {
175 _cleanup_free_
char *target
= NULL
;
181 r
= readlink_malloc(p
, &target
);
185 return file_in_same_dir(p
, target
, ret
);
188 int chmod_and_chown_at(int dir_fd
, const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
189 _cleanup_close_
int fd
= -EBADF
;
191 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
194 /* Let's acquire an O_PATH fd, as precaution to change mode/owner on the same file */
195 fd
= openat(dir_fd
, path
, O_PATH
|O_CLOEXEC
|O_NOFOLLOW
);
200 } else if (dir_fd
== AT_FDCWD
) {
201 /* Let's acquire an O_PATH fd of the current directory */
202 fd
= openat(dir_fd
, ".", O_PATH
|O_CLOEXEC
|O_NOFOLLOW
|O_DIRECTORY
);
208 return fchmod_and_chown(dir_fd
, mode
, uid
, gid
);
211 int fchmod_and_chown_with_fallback(int fd
, const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
212 bool do_chown
, do_chmod
;
216 /* Change ownership and access mode of the specified fd. Tries to do so safely, ensuring that at no
217 * point in time the access mode is above the old access mode under the old ownership or the new
218 * access mode under the new ownership. Note: this call tries hard to leave the access mode
219 * unaffected if the uid/gid is changed, i.e. it undoes implicit suid/sgid dropping the kernel does
222 * This call is happy with O_PATH fds.
224 * If path is given, allow a fallback path which does not use /proc/self/fd/. On any normal system
225 * /proc will be mounted, but in certain improperly assembled environments it might not be. This is
226 * less secure (potential TOCTOU), so should only be used after consideration. */
228 if (fstat(fd
, &st
) < 0)
232 (uid
!= UID_INVALID
&& st
.st_uid
!= uid
) ||
233 (gid
!= GID_INVALID
&& st
.st_gid
!= gid
);
236 !S_ISLNK(st
.st_mode
) && /* chmod is not defined on symlinks */
237 ((mode
!= MODE_INVALID
&& ((st
.st_mode
^ mode
) & 07777) != 0) ||
238 do_chown
); /* If we change ownership, make sure we reset the mode afterwards, since chown()
239 * modifies the access mode too */
241 if (mode
== MODE_INVALID
)
242 mode
= st
.st_mode
; /* If we only shall do a chown(), save original mode, since chown() might break it. */
243 else if ((mode
& S_IFMT
) != 0 && ((mode
^ st
.st_mode
) & S_IFMT
) != 0)
244 return -EINVAL
; /* insist on the right file type if it was specified */
246 if (do_chown
&& do_chmod
) {
247 mode_t minimal
= st
.st_mode
& mode
; /* the subset of the old and the new mask */
249 if (((minimal
^ st
.st_mode
) & 07777) != 0) {
250 r
= fchmod_opath(fd
, minimal
& 07777);
252 if (!path
|| r
!= -ENOSYS
)
255 /* Fallback path which doesn't use /proc/self/fd/. */
256 if (chmod(path
, minimal
& 07777) < 0)
263 if (fchownat(fd
, "", uid
, gid
, AT_EMPTY_PATH
) < 0)
267 r
= fchmod_opath(fd
, mode
& 07777);
269 if (!path
|| r
!= -ENOSYS
)
272 /* Fallback path which doesn't use /proc/self/fd/. */
273 if (chmod(path
, mode
& 07777) < 0)
278 return do_chown
|| do_chmod
;
281 int fchmod_umask(int fd
, mode_t m
) {
282 _cleanup_umask_ mode_t u
= umask(0777);
284 return RET_NERRNO(fchmod(fd
, m
& (~u
)));
287 int fchmod_opath(int fd
, mode_t m
) {
288 /* This function operates also on fd that might have been opened with
289 * O_PATH. Indeed fchmodat() doesn't have the AT_EMPTY_PATH flag like
290 * fchownat() does. */
292 if (chmod(FORMAT_PROC_FD_PATH(fd
), m
) < 0) {
296 if (proc_mounted() == 0)
297 return -ENOSYS
; /* if we have no /proc/, the concept is not implementable */
305 int futimens_opath(int fd
, const struct timespec ts
[2]) {
306 /* Similar to fchmod_path() but for futimens() */
308 if (utimensat(AT_FDCWD
, FORMAT_PROC_FD_PATH(fd
), ts
, 0) < 0) {
312 if (proc_mounted() == 0)
313 return -ENOSYS
; /* if we have no /proc/, the concept is not implementable */
321 int stat_warn_permissions(const char *path
, const struct stat
*st
) {
325 /* Don't complain if we are reading something that is not a file, for example /dev/null */
326 if (!S_ISREG(st
->st_mode
))
329 if (st
->st_mode
& 0111)
330 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
332 if (st
->st_mode
& 0002)
333 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
335 if (getpid_cached() == 1 && (st
->st_mode
& 0044) != 0044)
336 log_warning("Configuration file %s is marked world-inaccessible. This has no effect as configuration data is accessible via APIs without restrictions. Proceeding anyway.", path
);
341 int fd_warn_permissions(const char *path
, int fd
) {
347 if (fstat(fd
, &st
) < 0)
350 return stat_warn_permissions(path
, &st
);
353 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
354 _cleanup_close_
int fd
= -EBADF
;
359 /* Note that touch_file() does not follow symlinks: if invoked on an existing symlink, then it is the symlink
360 * itself which is updated, not its target
362 * Returns the first error we encounter, but tries to apply as much as possible. */
365 (void) mkdir_parents(path
, 0755);
367 /* Initially, we try to open the node with O_PATH, so that we get a reference to the node. This is useful in
368 * case the path refers to an existing device or socket node, as we can open it successfully in all cases, and
369 * won't trigger any driver magic or so. */
370 fd
= open(path
, O_PATH
|O_CLOEXEC
|O_NOFOLLOW
);
375 /* if the node doesn't exist yet, we create it, but with O_EXCL, so that we only create a regular file
376 * here, and nothing else */
377 fd
= open(path
, O_WRONLY
|O_CREAT
|O_EXCL
|O_CLOEXEC
, IN_SET(mode
, 0, MODE_INVALID
) ? 0644 : mode
);
382 /* Let's make a path from the fd, and operate on that. With this logic, we can adjust the access mode,
383 * ownership and time of the file node in all cases, even if the fd refers to an O_PATH object — which is
384 * something fchown(), fchmod(), futimensat() don't allow. */
385 ret
= fchmod_and_chown(fd
, mode
, uid
, gid
);
387 if (stamp
!= USEC_INFINITY
) {
388 struct timespec ts
[2];
390 timespec_store(&ts
[0], stamp
);
392 r
= futimens_opath(fd
, ts
);
394 r
= futimens_opath(fd
, NULL
);
395 if (r
< 0 && ret
>= 0)
401 int symlink_idempotent(const char *from
, const char *to
, bool make_relative
) {
402 _cleanup_free_
char *relpath
= NULL
;
409 r
= path_make_relative_parent(to
, from
, &relpath
);
416 if (symlink(from
, to
) < 0) {
417 _cleanup_free_
char *p
= NULL
;
422 r
= readlink_malloc(to
, &p
);
423 if (r
== -EINVAL
) /* Not a symlink? In that case return the original error we encountered: -EEXIST */
425 if (r
< 0) /* Any other error? In that case propagate it as is */
428 if (!streq(p
, from
)) /* Not the symlink we want it to be? In that case, propagate the original -EEXIST */
435 int symlinkat_atomic_full(const char *from
, int atfd
, const char *to
, bool make_relative
) {
436 _cleanup_free_
char *relpath
= NULL
, *t
= NULL
;
443 r
= path_make_relative_parent(to
, from
, &relpath
);
450 r
= tempfn_random(to
, NULL
, &t
);
454 if (symlinkat(from
, atfd
, t
) < 0)
457 r
= RET_NERRNO(renameat(atfd
, t
, atfd
, to
));
459 (void) unlinkat(atfd
, t
, 0);
466 int mknodat_atomic(int atfd
, const char *path
, mode_t mode
, dev_t dev
) {
467 _cleanup_free_
char *t
= NULL
;
472 r
= tempfn_random(path
, NULL
, &t
);
476 if (mknodat(atfd
, t
, mode
, dev
) < 0)
479 r
= RET_NERRNO(renameat(atfd
, t
, atfd
, path
));
481 (void) unlinkat(atfd
, t
, 0);
488 int mkfifoat_atomic(int atfd
, const char *path
, mode_t mode
) {
489 _cleanup_free_
char *t
= NULL
;
494 /* We're only interested in the (random) filename. */
495 r
= tempfn_random(path
, NULL
, &t
);
499 if (mkfifoat(atfd
, t
, mode
) < 0)
502 r
= RET_NERRNO(renameat(atfd
, t
, atfd
, path
));
504 (void) unlinkat(atfd
, t
, 0);
511 int get_files_in_directory(const char *path
, char ***list
) {
512 _cleanup_strv_free_
char **l
= NULL
;
513 _cleanup_closedir_
DIR *d
= NULL
;
518 /* Returns all files in a directory in *list, and the number
519 * of files as return value. If list is NULL returns only the
526 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
527 if (!dirent_is_file(de
))
531 /* one extra slot is needed for the terminating NULL */
532 if (!GREEDY_REALLOC(l
, n
+ 2))
535 l
[n
] = strdup(de
->d_name
);
550 static int getenv_tmp_dir(const char **ret_path
) {
555 /* We use the same order of environment variables python uses in tempfile.gettempdir():
556 * https://docs.python.org/3/library/tempfile.html#tempfile.gettempdir */
557 FOREACH_STRING(n
, "TMPDIR", "TEMP", "TMP") {
560 e
= secure_getenv(n
);
563 if (!path_is_absolute(e
)) {
567 if (!path_is_normalized(e
)) {
584 /* Remember first error, to make this more debuggable */
596 static int tmp_dir_internal(const char *def
, const char **ret
) {
603 r
= getenv_tmp_dir(&e
);
609 k
= is_dir(def
, true);
613 return r
< 0 ? r
: k
;
619 int var_tmp_dir(const char **ret
) {
621 /* Returns the location for "larger" temporary files, that is backed by physical storage if available, and thus
622 * even might survive a boot: /var/tmp. If $TMPDIR (or related environment variables) are set, its value is
623 * returned preferably however. Note that both this function and tmp_dir() below are affected by $TMPDIR,
624 * making it a variable that overrides all temporary file storage locations. */
626 return tmp_dir_internal("/var/tmp", ret
);
629 int tmp_dir(const char **ret
) {
631 /* Similar to var_tmp_dir() above, but returns the location for "smaller" temporary files, which is usually
632 * backed by an in-memory file system: /tmp. */
634 return tmp_dir_internal("/tmp", ret
);
637 int unlink_or_warn(const char *filename
) {
638 if (unlink(filename
) < 0 && errno
!= ENOENT
)
639 /* If the file doesn't exist and the fs simply was read-only (in which
640 * case unlink() returns EROFS even if the file doesn't exist), don't
642 if (errno
!= EROFS
|| access(filename
, F_OK
) >= 0)
643 return log_error_errno(errno
, "Failed to remove \"%s\": %m", filename
);
648 int access_fd(int fd
, int mode
) {
649 /* Like access() but operates on an already open fd */
651 if (access(FORMAT_PROC_FD_PATH(fd
), mode
) < 0) {
655 /* ENOENT can mean two things: that the fd does not exist or that /proc is not mounted. Let's
656 * make things debuggable and distinguish the two. */
658 if (proc_mounted() == 0)
659 return -ENOSYS
; /* /proc is not available or not set up properly, we're most likely in some chroot
662 return -EBADF
; /* The directory exists, hence it's the fd that doesn't. */
668 void unlink_tempfilep(char (*p
)[]) {
669 /* If the file is created with mkstemp(), it will (almost always)
670 * change the suffix. Treat this as a sign that the file was
671 * successfully created. We ignore both the rare case where the
672 * original suffix is used and unlink failures. */
673 if (!endswith(*p
, ".XXXXXX"))
677 int unlinkat_deallocate(int fd
, const char *name
, UnlinkDeallocateFlags flags
) {
678 _cleanup_close_
int truncate_fd
= -EBADF
;
682 assert((flags
& ~(UNLINK_REMOVEDIR
|UNLINK_ERASE
)) == 0);
684 /* Operates like unlinkat() but also deallocates the file contents if it is a regular file and there's no other
685 * link to it. This is useful to ensure that other processes that might have the file open for reading won't be
686 * able to keep the data pinned on disk forever. This call is particular useful whenever we execute clean-up
687 * jobs ("vacuuming"), where we want to make sure the data is really gone and the disk space released and
688 * returned to the free pool.
690 * Deallocation is preferably done by FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE (👊) if supported, which means
691 * the file won't change size. That's a good thing since we shouldn't needlessly trigger SIGBUS in other
692 * programs that have mmap()ed the file. (The assumption here is that changing file contents to all zeroes
693 * underneath those programs is the better choice than simply triggering SIGBUS in them which truncation does.)
694 * However if hole punching is not implemented in the kernel or file system we'll fall back to normal file
695 * truncation (🔪), as our goal of deallocating the data space trumps our goal of being nice to readers (💐).
697 * Note that we attempt deallocation, but failure to succeed with that is not considered fatal, as long as the
698 * primary job – to delete the file – is accomplished. */
700 if (!FLAGS_SET(flags
, UNLINK_REMOVEDIR
)) {
701 truncate_fd
= openat(fd
, name
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
|O_NONBLOCK
);
702 if (truncate_fd
< 0) {
704 /* If this failed because the file doesn't exist propagate the error right-away. Also,
705 * AT_REMOVEDIR wasn't set, and we tried to open the file for writing, which means EISDIR is
706 * returned when this is a directory but we are not supposed to delete those, hence propagate
707 * the error right-away too. */
708 if (IN_SET(errno
, ENOENT
, EISDIR
))
711 if (errno
!= ELOOP
) /* don't complain if this is a symlink */
712 log_debug_errno(errno
, "Failed to open file '%s' for deallocation, ignoring: %m", name
);
716 if (unlinkat(fd
, name
, FLAGS_SET(flags
, UNLINK_REMOVEDIR
) ? AT_REMOVEDIR
: 0) < 0)
719 if (truncate_fd
< 0) /* Don't have a file handle, can't do more ☹️ */
722 if (fstat(truncate_fd
, &st
) < 0) {
723 log_debug_errno(errno
, "Failed to stat file '%s' for deallocation, ignoring: %m", name
);
727 if (!S_ISREG(st
.st_mode
))
730 if (FLAGS_SET(flags
, UNLINK_ERASE
) && st
.st_size
> 0 && st
.st_nlink
== 0) {
731 uint64_t left
= st
.st_size
;
732 char buffer
[64 * 1024];
734 /* If erasing is requested, let's overwrite the file with random data once before deleting
735 * it. This isn't going to give you shred(1) semantics, but hopefully should be good enough
736 * for stuff backed by tmpfs at least.
738 * Note that we only erase like this if the link count of the file is zero. If it is higher it
739 * is still linked by someone else and we'll leave it to them to remove it securely
742 random_bytes(buffer
, sizeof(buffer
));
747 n
= write(truncate_fd
, buffer
, MIN(sizeof(buffer
), left
));
749 log_debug_errno(errno
, "Failed to erase data in file '%s', ignoring.", name
);
753 assert(left
>= (size_t) n
);
757 /* Let's refresh metadata */
758 if (fstat(truncate_fd
, &st
) < 0) {
759 log_debug_errno(errno
, "Failed to stat file '%s' for deallocation, ignoring: %m", name
);
764 /* Don't dallocate if there's nothing to deallocate or if the file is linked elsewhere */
765 if (st
.st_blocks
== 0 || st
.st_nlink
> 0)
768 /* If this is a regular file, it actually took up space on disk and there are no other links it's time to
769 * punch-hole/truncate this to release the disk space. */
771 bs
= MAX(st
.st_blksize
, 512);
772 l
= DIV_ROUND_UP(st
.st_size
, bs
) * bs
; /* Round up to next block size */
774 if (fallocate(truncate_fd
, FALLOC_FL_PUNCH_HOLE
|FALLOC_FL_KEEP_SIZE
, 0, l
) >= 0)
775 return 0; /* Successfully punched a hole! 😊 */
777 /* Fall back to truncation */
778 if (ftruncate(truncate_fd
, 0) < 0) {
779 log_debug_errno(errno
, "Failed to truncate file to 0, ignoring: %m");
786 int open_parent_at(int dir_fd
, const char *path
, int flags
, mode_t mode
) {
787 _cleanup_free_
char *parent
= NULL
;
790 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
793 r
= path_extract_directory(path
, &parent
);
794 if (r
== -EDESTADDRREQ
) {
795 parent
= strdup(".");
798 } else if (r
== -EADDRNOTAVAIL
) {
799 parent
= strdup(path
);
805 /* Let's insist on O_DIRECTORY since the parent of a file or directory is a directory. Except if we open an
806 * O_TMPFILE file, because in that case we are actually create a regular file below the parent directory. */
808 if (FLAGS_SET(flags
, O_PATH
))
809 flags
|= O_DIRECTORY
;
810 else if (!FLAGS_SET(flags
, O_TMPFILE
))
811 flags
|= O_DIRECTORY
|O_RDONLY
;
813 return RET_NERRNO(openat(dir_fd
, parent
, flags
, mode
));
816 int conservative_renameat(
817 int olddirfd
, const char *oldpath
,
818 int newdirfd
, const char *newpath
) {
820 _cleanup_close_
int old_fd
= -EBADF
, new_fd
= -EBADF
;
821 struct stat old_stat
, new_stat
;
823 /* Renames the old path to thew new path, much like renameat() — except if both are regular files and
824 * have the exact same contents and basic file attributes already. In that case remove the new file
825 * instead. This call is useful for reducing inotify wakeups on files that are updated but don't
826 * actually change. This function is written in a style that we rather rename too often than suppress
827 * too much. i.e. whenever we are in doubt we rather rename than fail. After all reducing inotify
828 * events is an optimization only, not more. */
830 old_fd
= openat(olddirfd
, oldpath
, O_CLOEXEC
|O_RDONLY
|O_NOCTTY
|O_NOFOLLOW
);
834 new_fd
= openat(newdirfd
, newpath
, O_CLOEXEC
|O_RDONLY
|O_NOCTTY
|O_NOFOLLOW
);
838 if (fstat(old_fd
, &old_stat
) < 0)
841 if (!S_ISREG(old_stat
.st_mode
))
844 if (fstat(new_fd
, &new_stat
) < 0)
847 if (stat_inode_same(&new_stat
, &old_stat
))
850 if (old_stat
.st_mode
!= new_stat
.st_mode
||
851 old_stat
.st_size
!= new_stat
.st_size
||
852 old_stat
.st_uid
!= new_stat
.st_uid
||
853 old_stat
.st_gid
!= new_stat
.st_gid
)
857 uint8_t buf1
[16*1024];
858 uint8_t buf2
[sizeof(buf1
)];
861 l1
= read(old_fd
, buf1
, sizeof(buf1
));
865 if (l1
== sizeof(buf1
))
866 /* Read the full block, hence read a full block in the other file too */
868 l2
= read(new_fd
, buf2
, l1
);
870 assert((size_t) l1
< sizeof(buf1
));
872 /* Short read. This hence was the last block in the first file, and then came
873 * EOF. Read one byte more in the second file, so that we can verify we hit EOF there
876 assert((size_t) (l1
+ 1) <= sizeof(buf2
));
877 l2
= read(new_fd
, buf2
, l1
+ 1);
882 if (memcmp(buf1
, buf2
, l1
) != 0)
885 if ((size_t) l1
< sizeof(buf1
)) /* We hit EOF on the first file, and the second file too, hence exit
891 /* Everything matches? Then don't rename, instead remove the source file, and leave the existing
892 * destination in place */
894 if (unlinkat(olddirfd
, oldpath
, 0) < 0)
900 if (renameat(olddirfd
, oldpath
, newdirfd
, newpath
) < 0)
906 int posix_fallocate_loop(int fd
, uint64_t offset
, uint64_t size
) {
910 r
= posix_fallocate(fd
, offset
, size
); /* returns positive errnos on error */
912 return -r
; /* Let's return negative errnos, like common in our codebase */
914 /* On EINTR try a couple of times more, but protect against busy looping
915 * (not more than 16 times per 10s) */
916 rl
= (const RateLimit
) { 10 * USEC_PER_SEC
, 16 };
917 while (ratelimit_below(&rl
)) {
918 r
= posix_fallocate(fd
, offset
, size
);
926 int parse_cifs_service(
932 _cleanup_free_
char *h
= NULL
, *ss
= NULL
, *x
= NULL
;
933 const char *p
, *e
, *d
;
936 /* Parses a CIFS service in form of //host/service/path… and splitting it in three parts. The last
937 * part is optional, in which case NULL is returned there. To maximize compatibility syntax with
938 * backslashes instead of slashes is accepted too. */
943 p
= startswith(s
, "//");
945 p
= startswith(s
, "\\\\");
951 e
= strchr(p
, delimiter
);
955 h
= strndup(p
, e
- p
);
959 if (!hostname_is_valid(h
, 0))
964 d
= strchrnul(e
, delimiter
);
966 ss
= strndup(e
, d
- e
);
970 if (!filename_is_valid(ss
))
974 x
= strdup(skip_leading_chars(d
, CHAR_TO_STR(delimiter
)));
978 /* Make sure to convert Windows-style "\" → Unix-style / */
979 for (char *i
= x
; *i
; i
++)
983 if (!path_is_valid(x
))
987 if (!path_is_normalized(x
))
992 *ret_host
= TAKE_PTR(h
);
994 *ret_service
= TAKE_PTR(ss
);
996 *ret_path
= TAKE_PTR(x
);
1001 int open_mkdir_at(int dirfd
, const char *path
, int flags
, mode_t mode
) {
1002 _cleanup_close_
int fd
= -EBADF
, parent_fd
= -EBADF
;
1003 _cleanup_free_
char *fname
= NULL
;
1006 /* Creates a directory with mkdirat() and then opens it, in the "most atomic" fashion we can
1007 * do. Guarantees that the returned fd refers to a directory. If O_EXCL is specified will fail if the
1008 * dir already exists. Otherwise will open an existing dir, but only if it is one. */
1010 if (flags
& ~(O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_EXCL
|O_NOATIME
|O_NOFOLLOW
|O_PATH
))
1012 if ((flags
& O_ACCMODE
) != O_RDONLY
)
1015 /* Note that O_DIRECTORY|O_NOFOLLOW is implied, but we allow specifying it anyway. The following
1016 * flags actually make sense to specify: O_CLOEXEC, O_EXCL, O_NOATIME, O_PATH */
1021 if (!filename_is_valid(path
)) {
1022 _cleanup_free_
char *parent
= NULL
;
1024 /* If this is not a valid filename, it's a path. Let's open the parent directory then, so
1025 * that we can pin it, and operate below it. */
1027 r
= path_extract_directory(path
, &parent
);
1031 r
= path_extract_filename(path
, &fname
);
1035 parent_fd
= openat(dirfd
, parent
, O_PATH
|O_DIRECTORY
|O_CLOEXEC
);
1043 fd
= xopenat(dirfd
, path
, flags
|O_CREAT
|O_DIRECTORY
|O_NOFOLLOW
, mode
);
1044 if (IN_SET(fd
, -ELOOP
, -ENOTDIR
))
1052 int openat_report_new(int dirfd
, const char *pathname
, int flags
, mode_t mode
, bool *ret_newly_created
) {
1053 unsigned attempts
= 7;
1056 /* Just like openat(), but adds one thing: optionally returns whether we created the file anew or if
1057 * it already existed before. This is only relevant if O_CREAT is set without O_EXCL, and thus will
1058 * shortcut to openat() otherwise */
1060 if (!ret_newly_created
)
1061 return RET_NERRNO(openat(dirfd
, pathname
, flags
, mode
));
1063 if (!FLAGS_SET(flags
, O_CREAT
) || FLAGS_SET(flags
, O_EXCL
)) {
1064 fd
= openat(dirfd
, pathname
, flags
, mode
);
1068 *ret_newly_created
= FLAGS_SET(flags
, O_CREAT
);
1073 /* First, attempt to open without O_CREAT/O_EXCL, i.e. open existing file */
1074 fd
= openat(dirfd
, pathname
, flags
& ~(O_CREAT
| O_EXCL
), mode
);
1076 *ret_newly_created
= false;
1079 if (errno
!= ENOENT
)
1082 /* So the file didn't exist yet, hence create it with O_CREAT/O_EXCL. */
1083 fd
= openat(dirfd
, pathname
, flags
| O_CREAT
| O_EXCL
, mode
);
1085 *ret_newly_created
= true;
1088 if (errno
!= EEXIST
)
1091 /* Hmm, so now we got EEXIST? So it apparently exists now? If so, let's try to open again
1092 * without the two flags. But let's not spin forever, hence put a limit on things */
1094 if (--attempts
== 0) /* Give up eventually, somebody is playing with us */
1099 int xopenat(int dir_fd
, const char *path
, int flags
, mode_t mode
) {
1100 _cleanup_close_
int fd
= -EBADF
;
1104 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
1107 if (isempty(path
)) {
1108 assert(!FLAGS_SET(flags
, O_CREAT
|O_EXCL
));
1109 return fd_reopen(dir_fd
, flags
& ~O_NOFOLLOW
);
1112 if (FLAGS_SET(flags
, O_DIRECTORY
|O_CREAT
)) {
1113 r
= RET_NERRNO(mkdirat(dir_fd
, path
, mode
));
1115 if (FLAGS_SET(flags
, O_EXCL
))
1124 flags
&= ~(O_EXCL
|O_CREAT
);
1127 fd
= RET_NERRNO(openat(dir_fd
, path
, flags
, mode
));
1130 /* We got ENOENT? then someone else immediately removed it after we
1131 * created it. In that case let's return immediately without unlinking
1132 * anything, because there simply isn't anything to unlink anymore. */
1134 /* is a symlink? exists already → created by someone else, don't unlink */
1136 /* not a directory? exists already → created by someone else, don't unlink */
1141 (void) unlinkat(dir_fd
, path
, AT_REMOVEDIR
);
1149 int xopenat_lock(int dir_fd
, const char *path
, int flags
, mode_t mode
, LockType locktype
, int operation
) {
1150 _cleanup_close_
int fd
= -EBADF
;
1153 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
1155 assert(IN_SET(operation
& ~LOCK_NB
, LOCK_EX
, LOCK_SH
));
1157 /* POSIX/UNPOSIX locks don't work on directories (errno is set to -EBADF so let's return early with
1158 * the same error here). */
1159 if (FLAGS_SET(flags
, O_DIRECTORY
) && locktype
!= LOCK_BSD
)
1165 fd
= xopenat(dir_fd
, path
, flags
, mode
);
1169 r
= lock_generic(fd
, locktype
, operation
);
1173 /* If we acquired the lock, let's check if the file/directory still exists in the file
1174 * system. If not, then the previous exclusive owner removed it and then closed it. In such a
1175 * case our acquired lock is worthless, hence try again. */
1177 if (fstat(fd
, &st
) < 0)
1179 if (st
.st_nlink
> 0)
1182 fd
= safe_close(fd
);