1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
33 int mkdir_label(const char *path, mode_t mode) {
34 return label_mkdir(path, mode, true);
37 static int makedir_safe(const char *path, mode_t mode, uid_t uid, gid_t gid, bool apply) {
40 if (label_mkdir(path, mode, apply) >= 0)
41 if (chmod_and_chown(path, mode, uid, gid) < 0)
44 if (lstat(path, &st) < 0)
47 if ((st.st_mode & 0777) != mode ||
50 !S_ISDIR(st.st_mode)) {
58 int mkdir_safe(const char *path, mode_t mode, uid_t uid, gid_t gid) {
59 return makedir_safe(path, mode, uid, gid, false);
62 int mkdir_safe_label(const char *path, mode_t mode, uid_t uid, gid_t gid) {
63 return makedir_safe(path, mode, uid, gid, true);
66 static int makedir_parents(const char *path, mode_t mode, bool apply) {
72 /* return immediately if directory exists */
73 e = strrchr(path, '/');
76 p = strndupa(path, e - path);
77 if (stat(p, &st) >= 0) {
78 if ((st.st_mode & S_IFMT) == S_IFDIR)
84 /* create every parent directory in the path, except the last component */
85 p = path + strspn(path, "/");
90 e = p + strcspn(p, "/");
91 p = e + strspn(e, "/");
93 /* Is this the last component? If so, then we're
98 t = strndup(path, e - path);
102 r = label_mkdir(t, mode, apply);
105 if (r < 0 && errno != EEXIST)
110 int mkdir_parents(const char *path, mode_t mode) {
111 return makedir_parents(path, mode, false);
114 int mkdir_parents_label(const char *path, mode_t mode) {
115 return makedir_parents(path, mode, true);
118 static int makedir_p(const char *path, mode_t mode, bool apply) {
123 r = makedir_parents(path, mode, apply);
127 if (label_mkdir(path, mode, apply) < 0 && errno != EEXIST)
133 int mkdir_p(const char *path, mode_t mode) {
134 return makedir_p(path, mode, false);
137 int mkdir_p_label(const char *path, mode_t mode) {
138 return makedir_p(path, mode, true);