1 /* mkdir-p.c -- Ensure that a directory and its parents exist.
3 Copyright (C) 1990, 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005
4 Free Software Foundation, Inc.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software Foundation,
18 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
20 /* Written by David MacKenzie <djm@gnu.ai.mit.edu> and Jim Meyering. */
31 #include <sys/types.h>
42 #define _(msgid) gettext (msgid)
48 #include "stat-macros.h"
50 #define WX_USR (S_IWUSR | S_IXUSR)
55 /* We're done operating on basename_dir. \
56 Restore working directory. */ \
59 if (restore_cwd (&cwd) != 0) \
61 int _saved_errno = errno; \
63 _("failed to return to initial working directory")); \
65 errno = _saved_errno; \
81 /* Attempt to create directory DIR (aka FULLDIR) with the specified MODE.
82 If CREATED_DIR_P is non-NULL, set *CREATED_DIR_P if this
83 function creates DIR and clear it otherwise. Give a diagnostic and
84 return false if DIR cannot be created or cannot be determined to
85 exist already. Use FULLDIR in any diagnostic, not DIR.
86 Note that if DIR already exists, this function returns true
87 (indicating success) and clears *CREATED_DIR_P. */
90 make_dir (char const *dir, char const *fulldir, mode_t mode,
96 created_dir = (mkdir (dir, mode) == 0);
101 int saved_errno = errno;
103 /* The mkdir and stat calls below may appear to be reversed.
104 They are not. It is important to call mkdir first and then to
105 call stat (to distinguish the three cases) only if mkdir fails.
106 The alternative to this approach is to `stat' each directory,
107 then to call mkdir if it doesn't exist. But if some other process
108 were to create the directory between the stat & mkdir, the mkdir
109 would fail with EEXIST. */
111 if (stat (dir, &stats))
113 error (0, saved_errno, _("cannot create directory %s"),
117 else if (!S_ISDIR (stats.st_mode))
119 error (0, 0, _("%s exists but is not a directory"), quote (fulldir));
124 /* DIR (aka FULLDIR) already exists and is a directory. */
129 *created_dir_p = created_dir;
134 /* Ensure that the directory ARG exists.
136 Create any leading directories that don't already exist, with
137 permissions PARENT_MODE.
138 If the last element of ARG does not exist, create it as
139 a new directory with permissions MODE.
140 If OWNER and GROUP are non-negative, use them to set the UID and GID of
141 any created directories.
142 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
143 string for printing a message after successfully making a directory,
144 with the name of the directory that was just made as an argument.
145 If PRESERVE_EXISTING is true and ARG is an existing directory,
146 then do not attempt to set its permissions and ownership.
148 Return true iff ARG exists as a directory with the proper
149 ownership and permissions when done. */
152 make_dir_parents (char const *arg,
157 bool preserve_existing,
158 char const *verbose_fmt_string)
163 if (stat (arg, &stats) != 0)
166 mode_t tmp_mode; /* Initial perms for leading dirs. */
167 bool re_protect; /* Should leading dirs be unwritable? */
171 struct ptr_list *next;
173 struct ptr_list *p, *leading_dirs = NULL;
174 bool do_chdir; /* Whether to chdir before each mkdir. */
175 struct saved_cwd cwd;
179 /* Temporarily relax umask in case it's overly restrictive. */
180 mode_t oldmask = umask (0);
182 /* Make a copy of ARG that we can scribble NULs on. */
183 dir = (char *) alloca (strlen (arg) + 1);
185 strip_trailing_slashes (dir);
187 /* If leading directories shouldn't be writable or executable,
188 or should have set[ug]id or sticky bits set and we are setting
189 their owners, we need to fix their permissions after making them. */
190 if (((parent_mode & WX_USR) != WX_USR)
191 || ((owner != (uid_t) -1 || group != (gid_t) -1)
192 && (parent_mode & (S_ISUID | S_ISGID | S_ISVTX)) != 0))
199 tmp_mode = parent_mode;
203 /* If we can record the current working directory, we may be able
204 to do the chdir optimization. */
205 do_chdir = (save_cwd (&cwd) == 0);
207 /* If we've saved the cwd and DIR is an absolute file name,
208 we must chdir to `/' in order to enable the chdir optimization.
209 So if chdir ("/") fails, turn off the optimization. */
210 if (do_chdir && dir[0] == '/')
212 /* POSIX says "//" might be special, so chdir to "//" if the
213 file name starts with exactly two slashes. */
214 char const *root = "//" + (dir[1] != '/' || dir[2] == '/');
215 if (chdir (root) != 0)
221 /* Skip over leading slashes. */
222 while (*slash == '/')
227 bool newly_created_dir;
229 /* slash points to the leftmost unprocessed component of dir. */
230 basename_dir = slash;
232 slash = strchr (slash, '/');
236 /* If we're *not* doing chdir before each mkdir, then we have to refer
237 to the target using the full (multi-component) directory name. */
242 if (! make_dir (basename_dir, dir, tmp_mode, &newly_created_dir))
248 if (newly_created_dir)
250 if (verbose_fmt_string)
251 error (0, 0, verbose_fmt_string, quote (dir));
253 if ((owner != (uid_t) -1 || group != (gid_t) -1)
254 && chown (basename_dir, owner, group)
255 #if defined AFS && defined EPERM
260 error (0, errno, _("cannot change owner and/or group of %s"),
268 struct ptr_list *new = (struct ptr_list *)
269 alloca (sizeof (struct ptr_list));
270 new->dirname_end = slash;
271 new->next = leading_dirs;
276 /* If we were able to save the initial working directory,
277 then we can use chdir to change into each directory before
278 creating an entry in that directory. This avoids making
279 stat and mkdir process O(n^2) file name components. */
280 if (do_chdir && chdir (basename_dir) < 0)
282 error (0, errno, _("cannot chdir to directory %s"),
290 /* Avoid unnecessary calls to `stat' when given
291 file names containing multiple adjacent slashes. */
292 while (*slash == '/')
299 /* Done creating leading directories. Restore original umask. */
302 /* We're done making leading directories.
303 Create the final component of the file name. */
305 if (! make_dir (basename_dir, dir, mode, NULL))
311 if (verbose_fmt_string != NULL)
312 error (0, 0, verbose_fmt_string, quote (dir));
314 if (owner != (uid_t) -1 || group != (gid_t) -1)
316 if (chown (basename_dir, owner, group)
322 error (0, errno, _("cannot change owner and/or group of %s"),
328 /* The above chown may have turned off some permission bits in MODE.
329 Another reason we may have to use chmod here is that mkdir(2) is
330 required to honor only the file permission bits. In particular,
331 it need not honor the `special' bits, so if MODE includes any
332 special bits, set them here. */
333 if ((mode & ~S_IRWXUGO)
334 && chmod (basename_dir, mode))
336 error (0, errno, _("cannot change permissions of %s"),
343 /* If the mode for leading directories didn't include owner "wx"
344 privileges, we have to reset their protections to the correct
346 for (p = leading_dirs; p != NULL; p = p->next)
348 *(p->dirname_end) = '\0';
349 if (chmod (dir, parent_mode) != 0)
351 error (0, errno, _("cannot change permissions of %s"),
359 /* We get here if the file already exists. */
361 char const *dir = arg;
363 if (!S_ISDIR (stats.st_mode))
365 error (0, 0, _("%s exists but is not a directory"), quote (dir));
369 if (!preserve_existing)
371 /* chown must precede chmod because on some systems,
372 chown clears the set[ug]id bits for non-superusers,
373 resulting in incorrect permissions.
374 On System V, users can give away files with chown and then not
375 be able to chmod them. So don't give files away. */
377 if ((owner != (uid_t) -1 || group != (gid_t) -1)
378 && chown (dir, owner, group)
384 error (0, errno, _("cannot change owner and/or group of %s"),
388 if (chmod (dir, mode) != 0)
390 error (0, errno, _("cannot change permissions of %s"),