]>
git.proxmox.com Git - systemd.git/blob - src/shared/mkdir.c
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
& 0777) != mode
||
47 !S_ISDIR(st
.st_mode
)) {
55 int mkdir_safe(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
56 return mkdir_safe_internal(path
, mode
, uid
, gid
, false);
59 static int is_dir(const char* path
) {
62 if (stat(path
, &st
) < 0)
65 return S_ISDIR(st
.st_mode
);
68 int mkdir_parents_internal(const char *prefix
, const char *path
, mode_t mode
, mkdir_func_t _mkdir
) {
74 if (prefix
&& !path_startswith(path
, prefix
))
77 /* return immediately if directory exists */
78 e
= strrchr(path
, '/');
85 p
= strndupa(path
, e
- path
);
92 /* create every parent directory in the path, except the last component */
93 p
= path
+ strspn(path
, "/");
95 char t
[strlen(path
) + 1];
97 e
= p
+ strcspn(p
, "/");
98 p
= e
+ strspn(e
, "/");
100 /* Is this the last component? If so, then we're
105 memcpy(t
, path
, e
- path
);
108 if (prefix
&& path_startswith(prefix
, t
))
112 if (r
< 0 && errno
!= EEXIST
)
117 int mkdir_parents(const char *path
, mode_t mode
) {
118 return mkdir_parents_internal(NULL
, path
, mode
, mkdir
);
121 int mkdir_p_internal(const char *prefix
, const char *path
, mode_t mode
, mkdir_func_t _mkdir
) {
126 r
= mkdir_parents_internal(prefix
, path
, mode
, _mkdir
);
130 r
= _mkdir(path
, mode
);
131 if (r
< 0 && (errno
!= EEXIST
|| is_dir(path
) <= 0))
137 int mkdir_p(const char *path
, mode_t mode
) {
138 return mkdir_p_internal(NULL
, path
, mode
, mkdir
);
141 int mkdir_p_prefix(const char *prefix
, const char *path
, mode_t mode
) {
142 return mkdir_p_internal(prefix
, path
, mode
, mkdir
);