]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/chown-recursive.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2017 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/>.
21 #include <sys/types.h>
25 #include "user-util.h"
28 #include "dirent-util.h"
29 #include "chown-recursive.h"
31 static int chown_one(int fd
, const char *name
, const struct stat
*st
, uid_t uid
, gid_t gid
) {
37 if ((!uid_is_valid(uid
) || st
->st_uid
== uid
) &&
38 (!gid_is_valid(gid
) || st
->st_gid
== gid
))
42 r
= fchownat(fd
, name
, uid
, gid
, AT_SYMLINK_NOFOLLOW
);
44 r
= fchown(fd
, uid
, gid
);
48 /* The linux kernel alters the mode in some cases of chown(). Let's undo this. */
50 if (!S_ISLNK(st
->st_mode
))
51 r
= fchmodat(fd
, name
, st
->st_mode
, 0);
52 else /* There's currently no AT_SYMLINK_NOFOLLOW for fchmodat() */
55 r
= fchmod(fd
, st
->st_mode
);
62 static int chown_recursive_internal(int fd
, const struct stat
*st
, uid_t uid
, gid_t gid
) {
69 if (S_ISDIR(st
->st_mode
)) {
70 _cleanup_closedir_
DIR *d
= NULL
;
80 FOREACH_DIRENT_ALL(de
, d
, r
= -errno
; goto finish
) {
83 if (dot_or_dot_dot(de
->d_name
))
86 if (fstatat(dirfd(d
), de
->d_name
, &fst
, AT_SYMLINK_NOFOLLOW
) < 0) {
91 if (S_ISDIR(fst
.st_mode
)) {
94 subdir_fd
= openat(dirfd(d
), de
->d_name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|O_NOFOLLOW
|O_NOATIME
);
100 r
= chown_recursive_internal(subdir_fd
, &fst
, uid
, gid
);
106 r
= chown_one(dirfd(d
), de
->d_name
, &fst
, uid
, gid
);
114 r
= chown_one(dirfd(d
), NULL
, st
, uid
, gid
);
116 r
= chown_one(fd
, NULL
, st
, uid
, gid
);
120 r
= r
> 0 || changed
;
127 int path_chown_recursive(const char *path
, uid_t uid
, gid_t gid
) {
128 _cleanup_close_
int fd
= -1;
132 fd
= open(path
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|O_NOFOLLOW
|O_NOATIME
);
136 if (!uid_is_valid(uid
) && !gid_is_valid(gid
))
137 return 0; /* nothing to do */
139 if (fstat(fd
, &st
) < 0)
142 /* Let's take a shortcut: if the top-level directory is properly owned, we don't descend into the whole tree,
143 * under the assumption that all is OK anyway. */
145 if ((!uid_is_valid(uid
) || st
.st_uid
== uid
) &&
146 (!gid_is_valid(gid
) || st
.st_gid
== gid
))
149 r
= chown_recursive_internal(fd
, &st
, uid
, gid
);
150 fd
= -1; /* we donated the fd to the call, regardless if it succeeded or failed */