chiark / gitweb /
3d9822129618e28bd4ad50727536f0c1fa5a41c0
[elogind.git] / src / shared / mkdir.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
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.
12
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.
17
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/>.
20 ***/
21
22 #include <assert.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <errno.h>
26 #include <stdlib.h>
27 #include <stdio.h>
28
29 #include "mkdir.h"
30 #include "label.h"
31 #include "util.h"
32 #include "log.h"
33
34 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
35         struct stat st;
36
37         if (label_mkdir(path, mode) >= 0)
38                 if (chmod_and_chown(path, mode, uid, gid) < 0)
39                         return -errno;
40
41         if (lstat(path, &st) < 0)
42                 return -errno;
43
44         if ((st.st_mode & 0777) != mode ||
45             st.st_uid != uid ||
46             st.st_gid != gid ||
47             !S_ISDIR(st.st_mode)) {
48                 errno = EEXIST;
49                 return -errno;
50         }
51
52         return 0;
53 }
54
55 int mkdir_parents(const char *path, mode_t mode) {
56         const char *p, *e;
57
58         assert(path);
59
60         /* Creates every parent directory in the path except the last
61          * component. */
62
63         p = path + strspn(path, "/");
64         for (;;) {
65                 int r;
66                 char *t;
67
68                 e = p + strcspn(p, "/");
69                 p = e + strspn(e, "/");
70
71                 /* Is this the last component? If so, then we're
72                  * done */
73                 if (*p == 0)
74                         return 0;
75
76                 if (!(t = strndup(path, e - path)))
77                         return -ENOMEM;
78
79                 r = label_mkdir(t, mode);
80                 free(t);
81
82                 if (r < 0 && errno != EEXIST)
83                         return -errno;
84         }
85 }
86
87 int mkdir_p(const char *path, mode_t mode) {
88         int r;
89
90         /* Like mkdir -p */
91
92         if ((r = mkdir_parents(path, mode)) < 0)
93                 return r;
94
95         if (label_mkdir(path, mode) < 0 && errno != EEXIST)
96                 return -errno;
97
98         return 0;
99 }