]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/mkdir.c
2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
28 #include "path-util.h"
29 #include "stat-util.h"
30 #include "user-util.h"
32 int mkdir_safe_internal(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
, mkdir_func_t _mkdir
) {
36 if (_mkdir(path
, mode
) >= 0) {
37 r
= chmod_and_chown(path
, mode
, uid
, gid
);
42 if (lstat(path
, &st
) < 0)
45 if ((st
.st_mode
& 0007) > (mode
& 0007) ||
46 (st
.st_mode
& 0070) > (mode
& 0070) ||
47 (st
.st_mode
& 0700) > (mode
& 0700) ||
48 (uid
!= UID_INVALID
&& st
.st_uid
!= uid
) ||
49 (gid
!= GID_INVALID
&& st
.st_gid
!= gid
) ||
56 int mkdir_safe(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
57 return mkdir_safe_internal(path
, mode
, uid
, gid
, mkdir
);
60 int mkdir_parents_internal(const char *prefix
, const char *path
, mode_t mode
, mkdir_func_t _mkdir
) {
66 if (prefix
&& !path_startswith(path
, prefix
))
69 /* return immediately if directory exists */
70 e
= strrchr(path
, '/');
77 p
= strndupa(path
, e
- path
);
84 /* create every parent directory in the path, except the last component */
85 p
= path
+ strspn(path
, "/");
87 char t
[strlen(path
) + 1];
89 e
= p
+ strcspn(p
, "/");
90 p
= e
+ strspn(e
, "/");
92 /* Is this the last component? If so, then we're
97 memcpy(t
, path
, e
- path
);
100 if (prefix
&& path_startswith(prefix
, t
))
104 if (r
< 0 && errno
!= EEXIST
)
109 int mkdir_parents(const char *path
, mode_t mode
) {
110 return mkdir_parents_internal(NULL
, path
, mode
, mkdir
);
113 int mkdir_p_internal(const char *prefix
, const char *path
, mode_t mode
, mkdir_func_t _mkdir
) {
118 r
= mkdir_parents_internal(prefix
, path
, mode
, _mkdir
);
122 r
= _mkdir(path
, mode
);
123 if (r
< 0 && (errno
!= EEXIST
|| is_dir(path
, true) <= 0))
129 int mkdir_p(const char *path
, mode_t mode
) {
130 return mkdir_p_internal(NULL
, path
, mode
, mkdir
);