]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/fs-util.c
16f97893c951cd1f5024e56033a30111348453c5
1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
27 #include <linux/magic.h>
31 #include "alloc-util.h"
32 #include "dirent-util.h"
40 #include "parse-util.h"
41 #include "path-util.h"
42 #include "stat-util.h"
43 #include "stdio-util.h"
44 #include "string-util.h"
46 #include "time-util.h"
47 #include "user-util.h"
50 int unlink_noerrno ( const char * path
) {
61 int rmdir_parents ( const char * path
, const char * stop
) {
70 /* Skip trailing slashes */
71 while ( l
> 0 && path
[ l
- 1 ] == '/' )
77 /* Skip last component */
78 while ( l
> 0 && path
[ l
- 1 ] != '/' )
81 /* Skip trailing slashes */
82 while ( l
> 0 && path
[ l
- 1 ] == '/' )
92 if ( path_startswith ( stop
, t
)) {
108 int rename_noreplace ( int olddirfd
, const char * oldpath
, int newdirfd
, const char * newpath
) {
112 ret
= renameat2 ( olddirfd
, oldpath
, newdirfd
, newpath
, RENAME_NOREPLACE
);
116 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
117 * If it is not implemented, fallback to another method. */
118 if (! IN_SET ( errno
, EINVAL
, ENOSYS
))
121 /* The link()/unlink() fallback does not work on directories. But
122 * renameat() without RENAME_NOREPLACE gives the same semantics on
123 * directories, except when newpath is an *empty* directory. This is
125 ret
= fstatat ( olddirfd
, oldpath
, & buf
, AT_SYMLINK_NOFOLLOW
);
126 if ( ret
>= 0 && S_ISDIR ( buf
. st_mode
)) {
127 ret
= renameat ( olddirfd
, oldpath
, newdirfd
, newpath
);
128 return ret
>= 0 ? 0 : - errno
;
131 /* If it is not a directory, use the link()/unlink() fallback. */
132 ret
= linkat ( olddirfd
, oldpath
, newdirfd
, newpath
, 0 );
136 ret
= unlinkat ( olddirfd
, oldpath
, 0 );
138 /* backup errno before the following unlinkat() alters it */
140 ( void ) unlinkat ( newdirfd
, newpath
, 0 );
148 int readlinkat_malloc ( int fd
, const char * p
, char ** ret
) {
163 n
= readlinkat ( fd
, p
, c
, l
- 1 );
170 if (( size_t ) n
< l
- 1 ) {
181 int readlink_malloc ( const char * p
, char ** ret
) {
182 return readlinkat_malloc ( AT_FDCWD
, p
, ret
);
185 int readlink_value ( const char * p
, char ** ret
) {
186 _cleanup_free_
char * link
= NULL
;
190 r
= readlink_malloc ( p
, & link
);
194 value
= basename ( link
);
198 value
= strdup ( value
);
207 int readlink_and_make_absolute ( const char * p
, char ** r
) {
208 _cleanup_free_
char * target
= NULL
;
215 j
= readlink_malloc ( p
, & target
);
219 k
= file_in_same_dir ( p
, target
);
227 int readlink_and_canonicalize ( const char * p
, const char * root
, char ** ret
) {
234 r
= readlink_and_make_absolute ( p
, & t
);
238 r
= chase_symlinks ( t
, root
, 0 , & s
);
240 /* If we can't follow up, then let's return the original string, slightly cleaned up. */
241 * ret
= path_kill_slashes ( t
);
250 int readlink_and_make_absolute_root ( const char * root
, const char * path
, char ** ret
) {
251 _cleanup_free_
char * target
= NULL
, * t
= NULL
;
255 full
= prefix_roota ( root
, path
);
256 r
= readlink_malloc ( full
, & target
);
260 t
= file_in_same_dir ( path
, target
);
270 int chmod_and_chown ( const char * path
, mode_t mode
, uid_t uid
, gid_t gid
) {
273 /* Under the assumption that we are running privileged we
274 * first change the access mode and only then hand out
275 * ownership to avoid a window where access is too open. */
277 if ( mode
!= MODE_INVALID
)
278 if ( chmod ( path
, mode
) < 0 )
281 if ( uid
!= UID_INVALID
|| gid
!= GID_INVALID
)
282 if ( chown ( path
, uid
, gid
) < 0 )
288 int fchmod_umask ( int fd
, mode_t m
) {
293 r
= fchmod ( fd
, m
& (~ u
)) < 0 ? - errno
: 0 ;
299 int fd_warn_permissions ( const char * path
, int fd
) {
302 if ( fstat ( fd
, & st
) < 0 )
305 if ( st
. st_mode
& 0111 )
306 log_warning ( "Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway." , path
);
308 if ( st
. st_mode
& 0002 )
309 log_warning ( "Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway." , path
);
311 if ( getpid_cached () == 1 && ( st
. st_mode
& 0044 ) != 0044 )
312 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
);
317 int touch_file ( const char * path
, bool parents
, usec_t stamp
, uid_t uid
, gid_t gid
, mode_t mode
) {
318 char fdpath
[ STRLEN ( "/proc/self/fd/" ) + DECIMAL_STR_MAX ( int )];
319 _cleanup_close_
int fd
= - 1 ;
324 /* Note that touch_file() does not follow symlinks: if invoked on an existing symlink, then it is the symlink
325 * itself which is updated, not its target
327 * Returns the first error we encounter, but tries to apply as much as possible. */
330 ( void ) mkdir_parents ( path
, 0755 );
332 /* Initially, we try to open the node with O_PATH, so that we get a reference to the node. This is useful in
333 * case the path refers to an existing device or socket node, as we can open it successfully in all cases, and
334 * won't trigger any driver magic or so. */
335 fd
= open ( path
, O_PATH
| O_CLOEXEC
| O_NOFOLLOW
);
340 /* if the node doesn't exist yet, we create it, but with O_EXCL, so that we only create a regular file
341 * here, and nothing else */
342 fd
= open ( path
, O_WRONLY
| O_CREAT
| O_EXCL
| O_CLOEXEC
, IN_SET ( mode
, 0 , MODE_INVALID
) ? 0644 : mode
);
347 /* Let's make a path from the fd, and operate on that. With this logic, we can adjust the access mode,
348 * ownership and time of the file node in all cases, even if the fd refers to an O_PATH object — which is
349 * something fchown(), fchmod(), futimensat() don't allow. */
350 xsprintf ( fdpath
, "/proc/self/fd/%i" , fd
);
352 if ( mode
!= MODE_INVALID
)
353 if ( chmod ( fdpath
, mode
) < 0 )
356 if ( uid_is_valid ( uid
) || gid_is_valid ( gid
))
357 if ( chown ( fdpath
, uid
, gid
) < 0 && ret
>= 0 )
360 if ( stamp
!= USEC_INFINITY
) {
361 struct timespec ts
[ 2 ];
363 timespec_store (& ts
[ 0 ], stamp
);
365 r
= utimensat ( AT_FDCWD
, fdpath
, ts
, 0 );
367 r
= utimensat ( AT_FDCWD
, fdpath
, NULL
, 0 );
368 if ( r
< 0 && ret
>= 0 )
374 int touch ( const char * path
) {
375 return touch_file ( path
, false , USEC_INFINITY
, UID_INVALID
, GID_INVALID
, MODE_INVALID
);
378 int symlink_idempotent ( const char * from
, const char * to
) {
384 if ( symlink ( from
, to
) < 0 ) {
385 _cleanup_free_
char * p
= NULL
;
390 r
= readlink_malloc ( to
, & p
);
391 if ( r
== - EINVAL
) /* Not a symlink? In that case return the original error we encountered: -EEXIST */
393 if ( r
< 0 ) /* Any other error? In that case propagate it as is */
396 if (! streq ( p
, from
)) /* Not the symlink we want it to be? In that case, propagate the original -EEXIST */
403 int symlink_atomic ( const char * from
, const char * to
) {
404 _cleanup_free_
char * t
= NULL
;
410 r
= tempfn_random ( to
, NULL
, & t
);
414 if ( symlink ( from
, t
) < 0 )
417 if ( rename ( t
, to
) < 0 ) {
425 int mknod_atomic ( const char * path
, mode_t mode
, dev_t dev
) {
426 _cleanup_free_
char * t
= NULL
;
431 r
= tempfn_random ( path
, NULL
, & t
);
435 if ( mknod ( t
, mode
, dev
) < 0 )
438 if ( rename ( t
, path
) < 0 ) {
446 int mkfifo_atomic ( const char * path
, mode_t mode
) {
447 _cleanup_free_
char * t
= NULL
;
452 r
= tempfn_random ( path
, NULL
, & t
);
456 if ( mkfifo ( t
, mode
) < 0 )
459 if ( rename ( t
, path
) < 0 ) {
467 int get_files_in_directory ( const char * path
, char *** list
) {
468 _cleanup_closedir_
DIR * d
= NULL
;
470 size_t bufsize
= 0 , n
= 0 ;
471 _cleanup_strv_free_
char ** l
= NULL
;
475 /* Returns all files in a directory in *list, and the number
476 * of files as return value. If list is NULL returns only the
483 FOREACH_DIRENT_ALL ( de
, d
, return - errno
) {
484 dirent_ensure_type ( d
, de
);
486 if (! dirent_is_file ( de
))
490 /* one extra slot is needed for the terminating NULL */
491 if (! GREEDY_REALLOC ( l
, bufsize
, n
+ 2 ))
494 l
[ n
] = strdup ( de
-> d_name
);
505 l
= NULL
; /* avoid freeing */
511 static int getenv_tmp_dir ( const char ** ret_path
) {
517 /* We use the same order of environment variables python uses in tempfile.gettempdir():
518 * https://docs.python.org/3/library/tempfile.html#tempfile.gettempdir */
519 FOREACH_STRING ( n
, "TMPDIR" , "TEMP" , "TMP" ) {
522 e
= secure_getenv ( n
);
525 if (! path_is_absolute ( e
)) {
529 if (! path_is_normalized ( e
)) {
546 /* Remember first error, to make this more debuggable */
558 static int tmp_dir_internal ( const char * def
, const char ** ret
) {
565 r
= getenv_tmp_dir (& e
);
571 k
= is_dir ( def
, true );
575 return r
< 0 ? r
: k
;
581 int var_tmp_dir ( const char ** ret
) {
583 /* Returns the location for "larger" temporary files, that is backed by physical storage if available, and thus
584 * even might survive a boot: /var/tmp. If $TMPDIR (or related environment variables) are set, its value is
585 * returned preferably however. Note that both this function and tmp_dir() below are affected by $TMPDIR,
586 * making it a variable that overrides all temporary file storage locations. */
588 return tmp_dir_internal ( "/var/tmp" , ret
);
591 int tmp_dir ( const char ** ret
) {
593 /* Similar to var_tmp_dir() above, but returns the location for "smaller" temporary files, which is usually
594 * backed by an in-memory file system: /tmp. */
596 return tmp_dir_internal ( "/tmp" , ret
);
599 int inotify_add_watch_fd ( int fd
, int what
, uint32_t mask
) {
600 char path
[ STRLEN ( "/proc/self/fd/" ) + DECIMAL_STR_MAX ( int ) + 1 ];
603 /* This is like inotify_add_watch(), except that the file to watch is not referenced by a path, but by an fd */
604 xsprintf ( path
, "/proc/self/fd/%i" , what
);
606 r
= inotify_add_watch ( fd
, path
, mask
);
613 int chase_symlinks ( const char * path
, const char * original_root
, unsigned flags
, char ** ret
) {
614 _cleanup_free_
char * buffer
= NULL
, * done
= NULL
, * root
= NULL
;
615 _cleanup_close_
int fd
= - 1 ;
616 unsigned max_follow
= 32 ; /* how many symlinks to follow before giving up and returning ELOOP */
623 /* This is a lot like canonicalize_file_name(), but takes an additional "root" parameter, that allows following
624 * symlinks relative to a root directory, instead of the root of the host.
626 * Note that "root" primarily matters if we encounter an absolute symlink. It is also used when following
627 * relative symlinks to ensure they cannot be used to "escape" the root directory. The path parameter passed is
628 * assumed to be already prefixed by it, except if the CHASE_PREFIX_ROOT flag is set, in which case it is first
629 * prefixed accordingly.
631 * Algorithmically this operates on two path buffers: "done" are the components of the path we already
632 * processed and resolved symlinks, "." and ".." of. "todo" are the components of the path we still need to
633 * process. On each iteration, we move one component from "todo" to "done", processing it's special meaning
634 * each time. The "todo" path always starts with at least one slash, the "done" path always ends in no
635 * slash. We always keep an O_PATH fd to the component we are currently processing, thus keeping lookup races
638 * Suggested usage: whenever you want to canonicalize a path, use this function. Pass the absolute path you got
639 * as-is: fully qualified and relative to your host's root. Optionally, specify the root parameter to tell this
640 * function what to do when encountering a symlink with an absolute path as directory: prefix it by the
644 r
= path_make_absolute_cwd ( original_root
, & root
);
648 if ( flags
& CHASE_PREFIX_ROOT
)
649 path
= prefix_roota ( root
, path
);
652 r
= path_make_absolute_cwd ( path
, & buffer
);
656 fd
= open ( "/" , O_CLOEXEC
| O_NOFOLLOW
| O_PATH
);
662 _cleanup_free_
char * first
= NULL
;
663 _cleanup_close_
int child
= - 1 ;
667 /* Determine length of first component in the path */
668 n
= strspn ( todo
, "/" ); /* The slashes */
669 m
= n
+ strcspn ( todo
+ n
, "/" ); /* The entire length of the component */
671 /* Extract the first component. */
672 first
= strndup ( todo
, m
);
678 /* Empty? Then we reached the end. */
682 /* Just a single slash? Then we reached the end. */
683 if ( path_equal ( first
, "/" )) {
684 /* Preserve the trailing slash */
685 if (! strextend (& done
, "/" , NULL
))
691 /* Just a dot? Then let's eat this up. */
692 if ( path_equal ( first
, "/." ))
695 /* Two dots? Then chop off the last bit of what we already found out. */
696 if ( path_equal ( first
, "/.." )) {
697 _cleanup_free_
char * parent
= NULL
;
700 /* If we already are at the top, then going up will not change anything. This is in-line with
701 * how the kernel handles this. */
702 if ( isempty ( done
) || path_equal ( done
, "/" ))
705 parent
= dirname_malloc ( done
);
709 /* Don't allow this to leave the root dir. */
711 path_startswith ( done
, root
) &&
712 ! path_startswith ( parent
, root
))
715 free_and_replace ( done
, parent
);
717 fd_parent
= openat ( fd
, ".." , O_CLOEXEC
| O_NOFOLLOW
| O_PATH
);
727 /* Otherwise let's see what this is. */
728 child
= openat ( fd
, first
+ n
, O_CLOEXEC
| O_NOFOLLOW
| O_PATH
);
731 if ( errno
== ENOENT
&&
732 ( flags
& CHASE_NONEXISTENT
) &&
733 ( isempty ( todo
) || path_is_normalized ( todo
))) {
735 /* If CHASE_NONEXISTENT is set, and the path does not exist, then that's OK, return
736 * what we got so far. But don't allow this if the remaining path contains "../ or "./"
737 * or something else weird. */
739 /* If done is "/", as first also contains slash at the head, then remove this redundant slash. */
740 if ( streq_ptr ( done
, "/" ))
743 if (! strextend (& done
, first
, todo
, NULL
))
753 if ( fstat ( child
, & st
) < 0 )
755 if (( flags
& CHASE_NO_AUTOFS
) &&
756 fd_is_fs_type ( child
, AUTOFS_SUPER_MAGIC
) > 0 )
759 if ( S_ISLNK ( st
. st_mode
)) {
762 _cleanup_free_
char * destination
= NULL
;
764 /* This is a symlink, in this case read the destination. But let's make sure we don't follow
765 * symlinks without bounds. */
766 if (-- max_follow
<= 0 )
769 r
= readlinkat_malloc ( fd
, first
+ n
, & destination
);
772 if ( isempty ( destination
))
775 if ( path_is_absolute ( destination
)) {
777 /* An absolute destination. Start the loop from the beginning, but use the root
778 * directory as base. */
781 fd
= open ( root
?: "/" , O_CLOEXEC
| O_NOFOLLOW
| O_PATH
);
787 /* Note that we do not revalidate the root, we take it as is. */
796 /* Prefix what's left to do with what we just read, and start the loop again, but
797 * remain in the current directory. */
798 joined
= strjoin ( destination
, todo
);
800 joined
= strjoin ( "/" , destination
, todo
);
805 todo
= buffer
= joined
;
810 /* If this is not a symlink, then let's just add the name we read to what we already verified. */
815 /* If done is "/", as first also contains slash at the head, then remove this redundant slash. */
816 if ( streq ( done
, "/" ))
819 if (! strextend (& done
, first
, NULL
))
823 /* And iterate again, but go one directory further down. */
830 /* Special case, turn the empty string into "/", to indicate the root directory. */
844 int access_fd ( int fd
, int mode
) {
845 char p
[ STRLEN ( "/proc/self/fd/" ) + DECIMAL_STR_MAX ( fd
) + 1 ];
848 /* Like access() but operates on an already open fd */
850 xsprintf ( p
, "/proc/self/fd/%i" , fd
);