1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
7 #include <linux/falloc.h>
8 #include <linux/magic.h>
11 #include "alloc-util.h"
13 #include "dirent-util.h"
17 #include "hostname-util.h"
19 #include "lock-util.h"
22 #include "missing_fcntl.h"
23 #include "missing_fs.h"
24 #include "missing_syscall.h"
26 #include "parse-util.h"
27 #include "path-util.h"
28 #include "process-util.h"
29 #include "random-util.h"
30 #include "ratelimit.h"
31 #include "stat-util.h"
32 #include "stdio-util.h"
33 #include "string-util.h"
35 #include "time-util.h"
36 #include "tmpfile-util.h"
37 #include "umask-util.h"
38 #include "user-util.h"
40 int rmdir_parents(const char *path
, const char *stop
) {
47 if (!path_is_safe(path
))
50 if (!path_is_safe(stop
))
53 p
= strdupa_safe(path
);
58 /* skip the last component. */
59 r
= path_find_last_component(p
, /* accept_dot_dot= */ false, (const char **) &slash
, NULL
);
65 assert(*slash
== '/');
68 if (path_startswith_full(stop
, p
, /* accept_dot_dot= */ false))
71 if (rmdir(p
) < 0 && errno
!= ENOENT
)
76 int rename_noreplace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
79 /* Try the ideal approach first */
80 if (renameat2(olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
) >= 0)
83 /* renameat2() exists since Linux 3.15, btrfs and FAT added support for it later. If it is not implemented,
84 * fall back to a different method. */
85 if (!ERRNO_IS_NOT_SUPPORTED(errno
) && errno
!= EINVAL
)
88 /* Let's try to use linkat()+unlinkat() as fallback. This doesn't work on directories and on some file systems
89 * that do not support hard links (such as FAT, most prominently), but for files it's pretty close to what we
90 * want — though not atomic (i.e. for a short period both the new and the old filename will exist). */
91 if (linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0) >= 0) {
93 r
= RET_NERRNO(unlinkat(olddirfd
, oldpath
, 0));
95 (void) unlinkat(newdirfd
, newpath
, 0);
102 if (!ERRNO_IS_NOT_SUPPORTED(errno
) && !IN_SET(errno
, EINVAL
, EPERM
)) /* FAT returns EPERM on link()… */
105 /* OK, neither RENAME_NOREPLACE nor linkat()+unlinkat() worked. Let's then fall back to the racy TOCTOU
106 * vulnerable accessat(F_OK) check followed by classic, replacing renameat(), we have nothing better. */
108 if (faccessat(newdirfd
, newpath
, F_OK
, AT_SYMLINK_NOFOLLOW
) >= 0)
113 return RET_NERRNO(renameat(olddirfd
, oldpath
, newdirfd
, newpath
));
116 int readlinkat_malloc(int fd
, const char *p
, char **ret
) {
119 assert(fd
>= 0 || fd
== AT_FDCWD
);
121 if (fd
< 0 && isempty(p
))
122 return -EISDIR
; /* In this case, the fd points to the current working directory, and is
123 * definitely not a symlink. Let's return earlier. */
126 _cleanup_free_
char *c
= NULL
;
133 n
= readlinkat(fd
, strempty(p
), c
, l
);
137 if ((size_t) n
< l
) {
146 if (l
> (SSIZE_MAX
-1)/2) /* readlinkat() returns an ssize_t, and we want an extra byte for a
147 * trailing NUL, hence do an overflow check relative to SSIZE_MAX-1
155 int readlink_malloc(const char *p
, char **ret
) {
156 return readlinkat_malloc(AT_FDCWD
, p
, ret
);
159 int readlink_value(const char *p
, char **ret
) {
160 _cleanup_free_
char *link
= NULL
, *name
= NULL
;
166 r
= readlink_malloc(p
, &link
);
170 r
= path_extract_filename(link
, &name
);
173 if (r
== O_DIRECTORY
)
176 *ret
= TAKE_PTR(name
);
180 int readlink_and_make_absolute(const char *p
, char **ret
) {
181 _cleanup_free_
char *target
= NULL
;
187 r
= readlink_malloc(p
, &target
);
191 return file_in_same_dir(p
, target
, ret
);
194 int chmod_and_chown_at(int dir_fd
, const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
195 _cleanup_close_
int fd
= -EBADF
;
197 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
200 /* Let's acquire an O_PATH fd, as precaution to change mode/owner on the same file */
201 fd
= openat(dir_fd
, path
, O_PATH
|O_CLOEXEC
|O_NOFOLLOW
);
206 } else if (dir_fd
== AT_FDCWD
) {
207 /* Let's acquire an O_PATH fd of the current directory */
208 fd
= openat(dir_fd
, ".", O_PATH
|O_CLOEXEC
|O_NOFOLLOW
|O_DIRECTORY
);
214 return fchmod_and_chown(dir_fd
, mode
, uid
, gid
);
217 int fchmod_and_chown_with_fallback(int fd
, const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
218 bool do_chown
, do_chmod
;
222 /* Change ownership and access mode of the specified fd. Tries to do so safely, ensuring that at no
223 * point in time the access mode is above the old access mode under the old ownership or the new
224 * access mode under the new ownership. Note: this call tries hard to leave the access mode
225 * unaffected if the uid/gid is changed, i.e. it undoes implicit suid/sgid dropping the kernel does
228 * This call is happy with O_PATH fds.
230 * If path is given, allow a fallback path which does not use /proc/self/fd/. On any normal system
231 * /proc will be mounted, but in certain improperly assembled environments it might not be. This is
232 * less secure (potential TOCTOU), so should only be used after consideration. */
234 if (fstat(fd
, &st
) < 0)
238 (uid
!= UID_INVALID
&& st
.st_uid
!= uid
) ||
239 (gid
!= GID_INVALID
&& st
.st_gid
!= gid
);
242 !S_ISLNK(st
.st_mode
) && /* chmod is not defined on symlinks */
243 ((mode
!= MODE_INVALID
&& ((st
.st_mode
^ mode
) & 07777) != 0) ||
244 do_chown
); /* If we change ownership, make sure we reset the mode afterwards, since chown()
245 * modifies the access mode too */
247 if (mode
== MODE_INVALID
)
248 mode
= st
.st_mode
; /* If we only shall do a chown(), save original mode, since chown() might break it. */
249 else if ((mode
& S_IFMT
) != 0 && ((mode
^ st
.st_mode
) & S_IFMT
) != 0)
250 return -EINVAL
; /* insist on the right file type if it was specified */
252 if (do_chown
&& do_chmod
) {
253 mode_t minimal
= st
.st_mode
& mode
; /* the subset of the old and the new mask */
255 if (((minimal
^ st
.st_mode
) & 07777) != 0) {
256 r
= fchmod_opath(fd
, minimal
& 07777);
258 if (!path
|| r
!= -ENOSYS
)
261 /* Fallback path which doesn't use /proc/self/fd/. */
262 if (chmod(path
, minimal
& 07777) < 0)
269 if (fchownat(fd
, "", uid
, gid
, AT_EMPTY_PATH
) < 0)
273 r
= fchmod_opath(fd
, mode
& 07777);
275 if (!path
|| r
!= -ENOSYS
)
278 /* Fallback path which doesn't use /proc/self/fd/. */
279 if (chmod(path
, mode
& 07777) < 0)
284 return do_chown
|| do_chmod
;
287 int fchmod_umask(int fd
, mode_t m
) {
288 _cleanup_umask_ mode_t u
= umask(0777);
290 return RET_NERRNO(fchmod(fd
, m
& (~u
)));
293 int fchmod_opath(int fd
, mode_t m
) {
294 /* This function operates also on fd that might have been opened with
295 * O_PATH. The tool set we have is non-intuitive:
296 * - fchmod(2) only operates on open files (i. e., fds with an open file description);
297 * - fchmodat(2) does not have a flag arg like fchownat(2) does, so no way to pass AT_EMPTY_PATH;
298 * + it should not be confused with the libc fchmodat(3) interface, which adds 4th flag argument,
299 * but does not support AT_EMPTY_PATH (only supports AT_SYMLINK_NOFOLLOW);
300 * - fchmodat2(2) supports all the AT_* flags, but is still very recent.
302 * We try to use fchmodat2(), and, if it is not supported, resort
303 * to the /proc/self/fd dance. */
307 if (fchmodat2(fd
, "", m
, AT_EMPTY_PATH
) >= 0)
309 if (!IN_SET(errno
, ENOSYS
, EPERM
)) /* Some container managers block unknown syscalls with EPERM */
312 if (chmod(FORMAT_PROC_FD_PATH(fd
), m
) < 0) {
316 if (proc_mounted() == 0)
317 return -ENOSYS
; /* if we have no /proc/, the concept is not implementable */
325 int futimens_opath(int fd
, const struct timespec ts
[2]) {
326 /* Similar to fchmod_opath() but for futimens() */
328 if (utimensat(AT_FDCWD
, FORMAT_PROC_FD_PATH(fd
), ts
, 0) < 0) {
332 if (proc_mounted() == 0)
333 return -ENOSYS
; /* if we have no /proc/, the concept is not implementable */
341 int stat_warn_permissions(const char *path
, const struct stat
*st
) {
345 /* Don't complain if we are reading something that is not a file, for example /dev/null */
346 if (!S_ISREG(st
->st_mode
))
349 if (st
->st_mode
& 0111)
350 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path
);
352 if (st
->st_mode
& 0002)
353 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path
);
355 if (getpid_cached() == 1 && (st
->st_mode
& 0044) != 0044)
356 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
);
361 int fd_warn_permissions(const char *path
, int fd
) {
367 if (fstat(fd
, &st
) < 0)
370 return stat_warn_permissions(path
, &st
);
373 int touch_file(const char *path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
374 _cleanup_close_
int fd
= -EBADF
;
379 /* Note that touch_file() does not follow symlinks: if invoked on an existing symlink, then it is the symlink
380 * itself which is updated, not its target
382 * Returns the first error we encounter, but tries to apply as much as possible. */
385 (void) mkdir_parents(path
, 0755);
387 /* Initially, we try to open the node with O_PATH, so that we get a reference to the node. This is useful in
388 * case the path refers to an existing device or socket node, as we can open it successfully in all cases, and
389 * won't trigger any driver magic or so. */
390 fd
= open(path
, O_PATH
|O_CLOEXEC
|O_NOFOLLOW
);
395 /* if the node doesn't exist yet, we create it, but with O_EXCL, so that we only create a regular file
396 * here, and nothing else */
397 fd
= open(path
, O_WRONLY
|O_CREAT
|O_EXCL
|O_CLOEXEC
, IN_SET(mode
, 0, MODE_INVALID
) ? 0644 : mode
);
402 /* Let's make a path from the fd, and operate on that. With this logic, we can adjust the access mode,
403 * ownership and time of the file node in all cases, even if the fd refers to an O_PATH object — which is
404 * something fchown(), fchmod(), futimensat() don't allow. */
405 ret
= fchmod_and_chown(fd
, mode
, uid
, gid
);
407 if (stamp
!= USEC_INFINITY
) {
408 struct timespec ts
[2];
410 timespec_store(&ts
[0], stamp
);
412 r
= futimens_opath(fd
, ts
);
414 r
= futimens_opath(fd
, NULL
);
415 if (r
< 0 && ret
>= 0)
421 int symlink_idempotent(const char *from
, const char *to
, bool make_relative
) {
422 _cleanup_free_
char *relpath
= NULL
;
429 r
= path_make_relative_parent(to
, from
, &relpath
);
436 if (symlink(from
, to
) < 0) {
437 _cleanup_free_
char *p
= NULL
;
442 r
= readlink_malloc(to
, &p
);
443 if (r
== -EINVAL
) /* Not a symlink? In that case return the original error we encountered: -EEXIST */
445 if (r
< 0) /* Any other error? In that case propagate it as is */
448 if (!streq(p
, from
)) /* Not the symlink we want it to be? In that case, propagate the original -EEXIST */
455 int symlinkat_atomic_full(const char *from
, int atfd
, const char *to
, bool make_relative
) {
456 _cleanup_free_
char *relpath
= NULL
, *t
= NULL
;
463 r
= path_make_relative_parent(to
, from
, &relpath
);
470 r
= tempfn_random(to
, NULL
, &t
);
474 if (symlinkat(from
, atfd
, t
) < 0)
477 r
= RET_NERRNO(renameat(atfd
, t
, atfd
, to
));
479 (void) unlinkat(atfd
, t
, 0);
486 int mknodat_atomic(int atfd
, const char *path
, mode_t mode
, dev_t dev
) {
487 _cleanup_free_
char *t
= NULL
;
492 r
= tempfn_random(path
, NULL
, &t
);
496 if (mknodat(atfd
, t
, mode
, dev
) < 0)
499 r
= RET_NERRNO(renameat(atfd
, t
, atfd
, path
));
501 (void) unlinkat(atfd
, t
, 0);
508 int mkfifoat_atomic(int atfd
, const char *path
, mode_t mode
) {
509 _cleanup_free_
char *t
= NULL
;
514 /* We're only interested in the (random) filename. */
515 r
= tempfn_random(path
, NULL
, &t
);
519 if (mkfifoat(atfd
, t
, mode
) < 0)
522 r
= RET_NERRNO(renameat(atfd
, t
, atfd
, path
));
524 (void) unlinkat(atfd
, t
, 0);
531 int get_files_in_directory(const char *path
, char ***list
) {
532 _cleanup_strv_free_
char **l
= NULL
;
533 _cleanup_closedir_
DIR *d
= NULL
;
538 /* Returns all files in a directory in *list, and the number
539 * of files as return value. If list is NULL returns only the
546 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
547 if (!dirent_is_file(de
))
551 /* one extra slot is needed for the terminating NULL */
552 if (!GREEDY_REALLOC(l
, n
+ 2))
555 l
[n
] = strdup(de
->d_name
);
570 static int getenv_tmp_dir(const char **ret_path
) {
575 /* We use the same order of environment variables python uses in tempfile.gettempdir():
576 * https://docs.python.org/3/library/tempfile.html#tempfile.gettempdir */
577 FOREACH_STRING(n
, "TMPDIR", "TEMP", "TMP") {
580 e
= secure_getenv(n
);
583 if (!path_is_absolute(e
)) {
587 if (!path_is_normalized(e
)) {
604 /* Remember first error, to make this more debuggable */
616 static int tmp_dir_internal(const char *def
, const char **ret
) {
623 r
= getenv_tmp_dir(&e
);
629 k
= is_dir(def
, true);
633 return r
< 0 ? r
: k
;
639 int var_tmp_dir(const char **ret
) {
641 /* Returns the location for "larger" temporary files, that is backed by physical storage if available, and thus
642 * even might survive a boot: /var/tmp. If $TMPDIR (or related environment variables) are set, its value is
643 * returned preferably however. Note that both this function and tmp_dir() below are affected by $TMPDIR,
644 * making it a variable that overrides all temporary file storage locations. */
646 return tmp_dir_internal("/var/tmp", ret
);
649 int tmp_dir(const char **ret
) {
651 /* Similar to var_tmp_dir() above, but returns the location for "smaller" temporary files, which is usually
652 * backed by an in-memory file system: /tmp. */
654 return tmp_dir_internal("/tmp", ret
);
657 int unlink_or_warn(const char *filename
) {
658 if (unlink(filename
) < 0 && errno
!= ENOENT
)
659 /* If the file doesn't exist and the fs simply was read-only (in which
660 * case unlink() returns EROFS even if the file doesn't exist), don't
662 if (errno
!= EROFS
|| access(filename
, F_OK
) >= 0)
663 return log_error_errno(errno
, "Failed to remove \"%s\": %m", filename
);
668 int access_fd(int fd
, int mode
) {
669 /* Like access() but operates on an already open fd */
671 if (access(FORMAT_PROC_FD_PATH(fd
), mode
) < 0) {
675 /* ENOENT can mean two things: that the fd does not exist or that /proc is not mounted. Let's
676 * make things debuggable and distinguish the two. */
678 if (proc_mounted() == 0)
679 return -ENOSYS
; /* /proc is not available or not set up properly, we're most likely in some chroot
682 return -EBADF
; /* The directory exists, hence it's the fd that doesn't. */
688 void unlink_tempfilep(char (*p
)[]) {
689 /* If the file is created with mkstemp(), it will (almost always)
690 * change the suffix. Treat this as a sign that the file was
691 * successfully created. We ignore both the rare case where the
692 * original suffix is used and unlink failures. */
693 if (!endswith(*p
, ".XXXXXX"))
697 int unlinkat_deallocate(int fd
, const char *name
, UnlinkDeallocateFlags flags
) {
698 _cleanup_close_
int truncate_fd
= -EBADF
;
702 assert((flags
& ~(UNLINK_REMOVEDIR
|UNLINK_ERASE
)) == 0);
704 /* Operates like unlinkat() but also deallocates the file contents if it is a regular file and there's no other
705 * link to it. This is useful to ensure that other processes that might have the file open for reading won't be
706 * able to keep the data pinned on disk forever. This call is particular useful whenever we execute clean-up
707 * jobs ("vacuuming"), where we want to make sure the data is really gone and the disk space released and
708 * returned to the free pool.
710 * Deallocation is preferably done by FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE (👊) if supported, which means
711 * the file won't change size. That's a good thing since we shouldn't needlessly trigger SIGBUS in other
712 * programs that have mmap()ed the file. (The assumption here is that changing file contents to all zeroes
713 * underneath those programs is the better choice than simply triggering SIGBUS in them which truncation does.)
714 * However if hole punching is not implemented in the kernel or file system we'll fall back to normal file
715 * truncation (🔪), as our goal of deallocating the data space trumps our goal of being nice to readers (💐).
717 * Note that we attempt deallocation, but failure to succeed with that is not considered fatal, as long as the
718 * primary job – to delete the file – is accomplished. */
720 if (!FLAGS_SET(flags
, UNLINK_REMOVEDIR
)) {
721 truncate_fd
= openat(fd
, name
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
|O_NONBLOCK
);
722 if (truncate_fd
< 0) {
724 /* If this failed because the file doesn't exist propagate the error right-away. Also,
725 * AT_REMOVEDIR wasn't set, and we tried to open the file for writing, which means EISDIR is
726 * returned when this is a directory but we are not supposed to delete those, hence propagate
727 * the error right-away too. */
728 if (IN_SET(errno
, ENOENT
, EISDIR
))
731 if (errno
!= ELOOP
) /* don't complain if this is a symlink */
732 log_debug_errno(errno
, "Failed to open file '%s' for deallocation, ignoring: %m", name
);
736 if (unlinkat(fd
, name
, FLAGS_SET(flags
, UNLINK_REMOVEDIR
) ? AT_REMOVEDIR
: 0) < 0)
739 if (truncate_fd
< 0) /* Don't have a file handle, can't do more ☹️ */
742 if (fstat(truncate_fd
, &st
) < 0) {
743 log_debug_errno(errno
, "Failed to stat file '%s' for deallocation, ignoring: %m", name
);
747 if (!S_ISREG(st
.st_mode
))
750 if (FLAGS_SET(flags
, UNLINK_ERASE
) && st
.st_size
> 0 && st
.st_nlink
== 0) {
751 uint64_t left
= st
.st_size
;
752 char buffer
[64 * 1024];
754 /* If erasing is requested, let's overwrite the file with random data once before deleting
755 * it. This isn't going to give you shred(1) semantics, but hopefully should be good enough
756 * for stuff backed by tmpfs at least.
758 * Note that we only erase like this if the link count of the file is zero. If it is higher it
759 * is still linked by someone else and we'll leave it to them to remove it securely
762 random_bytes(buffer
, sizeof(buffer
));
767 n
= write(truncate_fd
, buffer
, MIN(sizeof(buffer
), left
));
769 log_debug_errno(errno
, "Failed to erase data in file '%s', ignoring.", name
);
773 assert(left
>= (size_t) n
);
777 /* Let's refresh metadata */
778 if (fstat(truncate_fd
, &st
) < 0) {
779 log_debug_errno(errno
, "Failed to stat file '%s' for deallocation, ignoring: %m", name
);
784 /* Don't dallocate if there's nothing to deallocate or if the file is linked elsewhere */
785 if (st
.st_blocks
== 0 || st
.st_nlink
> 0)
788 /* If this is a regular file, it actually took up space on disk and there are no other links it's time to
789 * punch-hole/truncate this to release the disk space. */
791 bs
= MAX(st
.st_blksize
, 512);
792 l
= ROUND_UP(st
.st_size
, bs
); /* Round up to next block size */
794 if (fallocate(truncate_fd
, FALLOC_FL_PUNCH_HOLE
|FALLOC_FL_KEEP_SIZE
, 0, l
) >= 0)
795 return 0; /* Successfully punched a hole! 😊 */
797 /* Fall back to truncation */
798 if (ftruncate(truncate_fd
, 0) < 0) {
799 log_debug_errno(errno
, "Failed to truncate file to 0, ignoring: %m");
806 int open_parent_at(int dir_fd
, const char *path
, int flags
, mode_t mode
) {
807 _cleanup_free_
char *parent
= NULL
;
810 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
813 r
= path_extract_directory(path
, &parent
);
814 if (r
== -EDESTADDRREQ
) {
815 parent
= strdup(".");
818 } else if (r
== -EADDRNOTAVAIL
) {
819 parent
= strdup(path
);
825 /* Let's insist on O_DIRECTORY since the parent of a file or directory is a directory. Except if we open an
826 * O_TMPFILE file, because in that case we are actually create a regular file below the parent directory. */
828 if (FLAGS_SET(flags
, O_PATH
))
829 flags
|= O_DIRECTORY
;
830 else if (!FLAGS_SET(flags
, O_TMPFILE
))
831 flags
|= O_DIRECTORY
|O_RDONLY
;
833 return RET_NERRNO(openat(dir_fd
, parent
, flags
, mode
));
836 int conservative_renameat(
837 int olddirfd
, const char *oldpath
,
838 int newdirfd
, const char *newpath
) {
840 _cleanup_close_
int old_fd
= -EBADF
, new_fd
= -EBADF
;
841 struct stat old_stat
, new_stat
;
843 /* Renames the old path to the new path, much like renameat() — except if both are regular files and
844 * have the exact same contents and basic file attributes already. In that case remove the new file
845 * instead. This call is useful for reducing inotify wakeups on files that are updated but don't
846 * actually change. This function is written in a style that we rather rename too often than suppress
847 * too much. I.e. whenever we are in doubt, we rather rename than fail. After all reducing inotify
848 * events is an optimization only, not more. */
850 old_fd
= openat(olddirfd
, oldpath
, O_CLOEXEC
|O_RDONLY
|O_NOCTTY
|O_NOFOLLOW
);
854 new_fd
= openat(newdirfd
, newpath
, O_CLOEXEC
|O_RDONLY
|O_NOCTTY
|O_NOFOLLOW
);
858 if (fstat(old_fd
, &old_stat
) < 0)
861 if (!S_ISREG(old_stat
.st_mode
))
864 if (fstat(new_fd
, &new_stat
) < 0)
867 if (stat_inode_same(&new_stat
, &old_stat
))
870 if (old_stat
.st_mode
!= new_stat
.st_mode
||
871 old_stat
.st_size
!= new_stat
.st_size
||
872 old_stat
.st_uid
!= new_stat
.st_uid
||
873 old_stat
.st_gid
!= new_stat
.st_gid
)
877 uint8_t buf1
[16*1024];
878 uint8_t buf2
[sizeof(buf1
)];
881 l1
= read(old_fd
, buf1
, sizeof(buf1
));
885 if (l1
== sizeof(buf1
))
886 /* Read the full block, hence read a full block in the other file too */
888 l2
= read(new_fd
, buf2
, l1
);
890 assert((size_t) l1
< sizeof(buf1
));
892 /* Short read. This hence was the last block in the first file, and then came
893 * EOF. Read one byte more in the second file, so that we can verify we hit EOF there
896 assert((size_t) (l1
+ 1) <= sizeof(buf2
));
897 l2
= read(new_fd
, buf2
, l1
+ 1);
902 if (memcmp(buf1
, buf2
, l1
) != 0)
905 if ((size_t) l1
< sizeof(buf1
)) /* We hit EOF on the first file, and the second file too, hence exit
911 /* Everything matches? Then don't rename, instead remove the source file, and leave the existing
912 * destination in place */
914 if (unlinkat(olddirfd
, oldpath
, 0) < 0)
920 if (renameat(olddirfd
, oldpath
, newdirfd
, newpath
) < 0)
926 int posix_fallocate_loop(int fd
, uint64_t offset
, uint64_t size
) {
930 r
= posix_fallocate(fd
, offset
, size
); /* returns positive errnos on error */
932 return -r
; /* Let's return negative errnos, like common in our codebase */
934 /* On EINTR try a couple of times more, but protect against busy looping
935 * (not more than 16 times per 10s) */
936 rl
= (const RateLimit
) { 10 * USEC_PER_SEC
, 16 };
937 while (ratelimit_below(&rl
)) {
938 r
= posix_fallocate(fd
, offset
, size
);
946 int parse_cifs_service(
952 _cleanup_free_
char *h
= NULL
, *ss
= NULL
, *x
= NULL
;
953 const char *p
, *e
, *d
;
956 /* Parses a CIFS service in form of //host/service/path… and splitting it in three parts. The last
957 * part is optional, in which case NULL is returned there. To maximize compatibility syntax with
958 * backslashes instead of slashes is accepted too. */
963 p
= startswith(s
, "//");
965 p
= startswith(s
, "\\\\");
971 e
= strchr(p
, delimiter
);
975 h
= strndup(p
, e
- p
);
979 if (!hostname_is_valid(h
, 0))
984 d
= strchrnul(e
, delimiter
);
986 ss
= strndup(e
, d
- e
);
990 if (!filename_is_valid(ss
))
994 x
= strdup(skip_leading_chars(d
, CHAR_TO_STR(delimiter
)));
998 /* Make sure to convert Windows-style "\" → Unix-style / */
999 for (char *i
= x
; *i
; i
++)
1000 if (*i
== delimiter
)
1003 if (!path_is_valid(x
))
1007 if (!path_is_normalized(x
))
1012 *ret_host
= TAKE_PTR(h
);
1014 *ret_service
= TAKE_PTR(ss
);
1016 *ret_path
= TAKE_PTR(x
);
1021 int open_mkdir_at(int dirfd
, const char *path
, int flags
, mode_t mode
) {
1022 _cleanup_close_
int fd
= -EBADF
, parent_fd
= -EBADF
;
1023 _cleanup_free_
char *fname
= NULL
, *parent
= NULL
;
1026 /* Creates a directory with mkdirat() and then opens it, in the "most atomic" fashion we can
1027 * do. Guarantees that the returned fd refers to a directory. If O_EXCL is specified will fail if the
1028 * dir already exists. Otherwise will open an existing dir, but only if it is one. */
1030 if (flags
& ~(O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_EXCL
|O_NOATIME
|O_NOFOLLOW
|O_PATH
))
1032 if ((flags
& O_ACCMODE
) != O_RDONLY
)
1035 /* Note that O_DIRECTORY|O_NOFOLLOW is implied, but we allow specifying it anyway. The following
1036 * flags actually make sense to specify: O_CLOEXEC, O_EXCL, O_NOATIME, O_PATH */
1038 /* If this is not a valid filename, it's a path. Let's open the parent directory then, so
1039 * that we can pin it, and operate below it. */
1040 r
= path_extract_directory(path
, &parent
);
1042 if (!IN_SET(r
, -EDESTADDRREQ
, -EADDRNOTAVAIL
))
1045 r
= path_extract_filename(path
, &fname
);
1049 parent_fd
= openat(dirfd
, parent
, O_PATH
|O_DIRECTORY
|O_CLOEXEC
);
1057 fd
= xopenat_full(dirfd
, path
, flags
|O_CREAT
|O_DIRECTORY
|O_NOFOLLOW
, /* xopen_flags = */ 0, mode
);
1058 if (IN_SET(fd
, -ELOOP
, -ENOTDIR
))
1066 int openat_report_new(int dirfd
, const char *pathname
, int flags
, mode_t mode
, bool *ret_newly_created
) {
1067 unsigned attempts
= 7;
1070 /* Just like openat(), but adds one thing: optionally returns whether we created the file anew or if
1071 * it already existed before. This is only relevant if O_CREAT is set without O_EXCL, and thus will
1072 * shortcut to openat() otherwise */
1074 if (!ret_newly_created
)
1075 return RET_NERRNO(openat(dirfd
, pathname
, flags
, mode
));
1077 if (!FLAGS_SET(flags
, O_CREAT
) || FLAGS_SET(flags
, O_EXCL
)) {
1078 fd
= openat(dirfd
, pathname
, flags
, mode
);
1082 *ret_newly_created
= FLAGS_SET(flags
, O_CREAT
);
1087 /* First, attempt to open without O_CREAT/O_EXCL, i.e. open existing file */
1088 fd
= openat(dirfd
, pathname
, flags
& ~(O_CREAT
| O_EXCL
), mode
);
1090 *ret_newly_created
= false;
1093 if (errno
!= ENOENT
)
1096 /* So the file didn't exist yet, hence create it with O_CREAT/O_EXCL. */
1097 fd
= openat(dirfd
, pathname
, flags
| O_CREAT
| O_EXCL
, mode
);
1099 *ret_newly_created
= true;
1102 if (errno
!= EEXIST
)
1105 /* Hmm, so now we got EEXIST? So it apparently exists now? If so, let's try to open again
1106 * without the two flags. But let's not spin forever, hence put a limit on things */
1108 if (--attempts
== 0) /* Give up eventually, somebody is playing with us */
1113 int xopenat_full(int dir_fd
, const char *path
, int open_flags
, XOpenFlags xopen_flags
, mode_t mode
) {
1114 _cleanup_close_
int fd
= -EBADF
;
1118 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
1120 /* This is like openat(), but has a few tricks up its sleeves, extending behaviour:
1122 * • O_DIRECTORY|O_CREAT is supported, which causes a directory to be created, and immediately
1123 * opened. When used with the XO_SUBVOLUME flag this will even create a btrfs subvolume.
1125 * • If O_CREAT is used with XO_LABEL, any created file will be immediately relabelled.
1127 * • If the path is specified NULL or empty, behaves like fd_reopen().
1130 if (isempty(path
)) {
1131 assert(!FLAGS_SET(open_flags
, O_CREAT
|O_EXCL
));
1132 return fd_reopen(dir_fd
, open_flags
& ~O_NOFOLLOW
);
1135 if (FLAGS_SET(open_flags
, O_CREAT
) && FLAGS_SET(xopen_flags
, XO_LABEL
)) {
1136 r
= label_ops_pre(dir_fd
, path
, FLAGS_SET(open_flags
, O_DIRECTORY
) ? S_IFDIR
: S_IFREG
);
1141 if (FLAGS_SET(open_flags
, O_DIRECTORY
|O_CREAT
)) {
1142 if (FLAGS_SET(xopen_flags
, XO_SUBVOLUME
))
1143 r
= btrfs_subvol_make_fallback(dir_fd
, path
, mode
);
1145 r
= RET_NERRNO(mkdirat(dir_fd
, path
, mode
));
1147 if (FLAGS_SET(open_flags
, O_EXCL
))
1156 if (FLAGS_SET(xopen_flags
, XO_LABEL
)) {
1157 r
= label_ops_post(dir_fd
, path
);
1162 open_flags
&= ~(O_EXCL
|O_CREAT
);
1163 xopen_flags
&= ~XO_LABEL
;
1166 fd
= RET_NERRNO(openat(dir_fd
, path
, open_flags
, mode
));
1169 /* We got ENOENT? then someone else immediately removed it after we
1170 * created it. In that case let's return immediately without unlinking
1171 * anything, because there simply isn't anything to unlink anymore. */
1173 /* is a symlink? exists already → created by someone else, don't unlink */
1175 /* not a directory? exists already → created by someone else, don't unlink */
1180 (void) unlinkat(dir_fd
, path
, AT_REMOVEDIR
);
1185 if (FLAGS_SET(open_flags
, O_CREAT
) && FLAGS_SET(xopen_flags
, XO_LABEL
)) {
1186 r
= label_ops_post(dir_fd
, path
);
1194 int xopenat_lock_full(
1198 XOpenFlags xopen_flags
,
1203 _cleanup_close_
int fd
= -EBADF
;
1206 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
1207 assert(IN_SET(operation
& ~LOCK_NB
, LOCK_EX
, LOCK_SH
));
1209 /* POSIX/UNPOSIX locks don't work on directories (errno is set to -EBADF so let's return early with
1210 * the same error here). */
1211 if (FLAGS_SET(open_flags
, O_DIRECTORY
) && !IN_SET(locktype
, LOCK_BSD
, LOCK_NONE
))
1217 fd
= xopenat_full(dir_fd
, path
, open_flags
, xopen_flags
, mode
);
1221 r
= lock_generic(fd
, locktype
, operation
);
1225 /* If we acquired the lock, let's check if the file/directory still exists in the file
1226 * system. If not, then the previous exclusive owner removed it and then closed it. In such a
1227 * case our acquired lock is worthless, hence try again. */
1229 if (fstat(fd
, &st
) < 0)
1231 if (st
.st_nlink
> 0)
1234 fd
= safe_close(fd
);
1240 int link_fd(int fd
, int newdirfd
, const char *newpath
) {
1244 assert(newdirfd
>= 0 || newdirfd
== AT_FDCWD
);
1247 /* Try linking via /proc/self/fd/ first. */
1248 r
= RET_NERRNO(linkat(AT_FDCWD
, FORMAT_PROC_FD_PATH(fd
), newdirfd
, newpath
, AT_SYMLINK_FOLLOW
));
1252 /* Fall back to symlinking via AT_EMPTY_PATH as fallback (this requires CAP_DAC_READ_SEARCH and a
1253 * more recent kernel, but does not require /proc/ mounted) */
1254 if (proc_mounted() != 0)
1257 return RET_NERRNO(linkat(fd
, "", newdirfd
, newpath
, AT_EMPTY_PATH
));
1260 int linkat_replace(int olddirfd
, const char *oldpath
, int newdirfd
, const char *newpath
) {
1261 _cleanup_close_
int old_fd
= -EBADF
;
1264 assert(olddirfd
>= 0 || olddirfd
== AT_FDCWD
);
1265 assert(newdirfd
>= 0 || newdirfd
== AT_FDCWD
);
1266 assert(!isempty(newpath
)); /* source path is optional, but the target path is not */
1268 /* Like linkat() but replaces the target if needed. Is a NOP if source and target already share the
1271 if (olddirfd
== AT_FDCWD
&& isempty(oldpath
)) /* Refuse operating on the cwd (which is a dir, and dirs can't be hardlinked) */
1274 if (path_implies_directory(oldpath
)) /* Refuse these definite directories early */
1277 if (path_implies_directory(newpath
))
1280 /* First, try to link this directly */
1282 r
= RET_NERRNO(linkat(olddirfd
, oldpath
, newdirfd
, newpath
, 0));
1284 r
= link_fd(olddirfd
, newdirfd
, newpath
);
1290 old_fd
= xopenat(olddirfd
, oldpath
, O_PATH
|O_CLOEXEC
);
1295 if (fstat(old_fd
, &old_st
) < 0)
1298 if (S_ISDIR(old_st
.st_mode
)) /* Don't bother if we are operating on a directory */
1302 if (fstatat(newdirfd
, newpath
, &new_st
, AT_SYMLINK_NOFOLLOW
) < 0)
1305 if (S_ISDIR(new_st
.st_mode
)) /* Refuse replacing directories */
1308 if (stat_inode_same(&old_st
, &new_st
)) /* Already the same inode? Then shortcut this */
1311 _cleanup_free_
char *tmp_path
= NULL
;
1312 r
= tempfn_random(newpath
, /* extra= */ NULL
, &tmp_path
);
1316 r
= link_fd(old_fd
, newdirfd
, tmp_path
);
1318 if (!ERRNO_IS_PRIVILEGE(r
))
1321 /* If that didn't work due to permissions then go via the path of the dentry */
1322 r
= RET_NERRNO(linkat(olddirfd
, oldpath
, newdirfd
, tmp_path
, 0));
1327 r
= RET_NERRNO(renameat(newdirfd
, tmp_path
, newdirfd
, newpath
));
1329 (void) unlinkat(newdirfd
, tmp_path
, /* flags= */ 0);