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/>.
31 #include "path-util.h"
34 int mkdir_safe_internal(const char *path, mode_t mode, uid_t uid, gid_t gid, mkdir_func_t _mkdir) {
37 if (_mkdir(path, mode) >= 0)
38 if (chmod_and_chown(path, mode, uid, gid) < 0)
41 if (lstat(path, &st) < 0)
44 if ((st.st_mode & 0007) > (mode & 0007) ||
45 (st.st_mode & 0070) > (mode & 0070) ||
46 (st.st_mode & 0700) > (mode & 0700) ||
47 (uid != (uid_t) -1 && st.st_uid != uid) ||
48 (gid != (gid_t) -1 && st.st_gid != gid) ||
49 !S_ISDIR(st.st_mode)) {
57 int mkdir_safe(const char *path, mode_t mode, uid_t uid, gid_t gid) {
58 return mkdir_safe_internal(path, mode, uid, gid, mkdir);
61 int mkdir_parents_internal(const char *prefix, const char *path, mode_t mode, mkdir_func_t _mkdir) {
67 if (prefix && !path_startswith(path, prefix))
70 /* return immediately if directory exists */
71 e = strrchr(path, '/');
78 p = strndupa(path, e - path);
85 /* create every parent directory in the path, except the last component */
86 p = path + strspn(path, "/");
88 char t[strlen(path) + 1];
90 e = p + strcspn(p, "/");
91 p = e + strspn(e, "/");
93 /* Is this the last component? If so, then we're
98 memcpy(t, path, e - path);
101 if (prefix && path_startswith(prefix, t))
105 if (r < 0 && errno != EEXIST)
110 int mkdir_parents(const char *path, mode_t mode) {
111 return mkdir_parents_internal(NULL, path, mode, mkdir);
114 int mkdir_p_internal(const char *prefix, const char *path, mode_t mode, mkdir_func_t _mkdir) {
119 r = mkdir_parents_internal(prefix, path, mode, _mkdir);
123 r = _mkdir(path, mode);
124 if (r < 0 && (errno != EEXIST || is_dir(path, true) <= 0))
130 int mkdir_p(const char *path, mode_t mode) {
131 return mkdir_p_internal(NULL, path, mode, mkdir);