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; \
66 *different_working_dir = true; \
82 /* Attempt to create directory DIR (aka FULLDIR) with the specified MODE.
83 If CREATED_DIR_P is non-NULL, set *CREATED_DIR_P if this
84 function creates DIR and clear it otherwise. Give a diagnostic and
85 return false if DIR cannot be created or cannot be determined to
86 exist already. Use FULLDIR in any diagnostic, not DIR.
87 Note that if DIR already exists, this function returns true
88 (indicating success) and clears *CREATED_DIR_P. */
91 make_dir (char const *dir, char const *fulldir, mode_t mode,
97 created_dir = (mkdir (dir, mode) == 0);
102 int saved_errno = errno;
104 /* The mkdir and stat calls below may appear to be reversed.
105 They are not. It is important to call mkdir first and then to
106 call stat (to distinguish the three cases) only if mkdir fails.
107 The alternative to this approach is to `stat' each directory,
108 then to call mkdir if it doesn't exist. But if some other process
109 were to create the directory between the stat & mkdir, the mkdir
110 would fail with EEXIST. */
112 if (stat (dir, &stats))
114 error (0, saved_errno, _("cannot create directory %s"),
118 else if (!S_ISDIR (stats.st_mode))
120 error (0, 0, _("%s exists but is not a directory"), quote (fulldir));
125 /* DIR (aka FULLDIR) already exists and is a directory. */
130 *created_dir_p = created_dir;
135 /* Ensure that the directory ARG exists.
137 Create any leading directories that don't already exist, with
138 permissions PARENT_MODE.
139 If the last element of ARG does not exist, create it as
140 a new directory with permissions MODE.
141 If OWNER and GROUP are non-negative, use them to set the UID and GID of
142 any created directories.
143 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
144 string for printing a message after successfully making a directory,
145 with the name of the directory that was just made as an argument.
146 If PRESERVE_EXISTING is true and ARG is an existing directory,
147 then do not attempt to set its permissions and ownership.
148 Upon return, set *DIFFERENT_WORKING_DIR to true if this function
149 has changed the current working directory and is unable to restore
150 it to its initial state.
152 Return true iff ARG exists as a directory with the proper
153 ownership and permissions when done. */
156 make_dir_parents (char const *arg,
161 bool preserve_existing,
162 char const *verbose_fmt_string,
163 bool *different_working_dir)
167 *different_working_dir = false;
169 if (stat (arg, &stats) != 0)
172 mode_t tmp_mode; /* Initial perms for leading dirs. */
173 bool re_protect; /* Should leading dirs be unwritable? */
177 struct ptr_list *next;
179 struct ptr_list *p, *leading_dirs = NULL;
180 bool do_chdir; /* Whether to chdir before each mkdir. */
181 struct saved_cwd cwd;
185 /* Temporarily relax umask in case it's overly restrictive. */
186 mode_t oldmask = umask (0);
188 /* Make a copy of ARG that we can scribble NULs on. */
189 dir = (char *) alloca (strlen (arg) + 1);
191 strip_trailing_slashes (dir);
193 /* If leading directories shouldn't be writable or executable,
194 or should have set[ug]id or sticky bits set and we are setting
195 their owners, we need to fix their permissions after making them. */
196 if (((parent_mode & WX_USR) != WX_USR)
197 || ((owner != (uid_t) -1 || group != (gid_t) -1)
198 && (parent_mode & (S_ISUID | S_ISGID | S_ISVTX)) != 0))
205 tmp_mode = parent_mode;
209 /* If we can record the current working directory, we may be able
210 to do the chdir optimization. */
211 do_chdir = (save_cwd (&cwd) == 0);
213 /* If we've saved the cwd and DIR is an absolute file name,
214 we must chdir to `/' in order to enable the chdir optimization.
215 So if chdir ("/") fails, turn off the optimization. */
216 if (do_chdir && dir[0] == '/')
218 /* POSIX says "//" might be special, so chdir to "//" if the
219 file name starts with exactly two slashes. */
220 char const *root = "//" + (dir[1] != '/' || dir[2] == '/');
221 if (chdir (root) != 0)
227 /* Skip over leading slashes. */
228 while (*slash == '/')
233 bool newly_created_dir;
235 /* slash points to the leftmost unprocessed component of dir. */
236 basename_dir = slash;
238 slash = strchr (slash, '/');
242 /* If we're *not* doing chdir before each mkdir, then we have to refer
243 to the target using the full (multi-component) directory name. */
248 if (! make_dir (basename_dir, dir, tmp_mode, &newly_created_dir))
254 if (newly_created_dir)
256 if (verbose_fmt_string)
257 error (0, 0, verbose_fmt_string, quote (dir));
259 if ((owner != (uid_t) -1 || group != (gid_t) -1)
260 && chown (basename_dir, owner, group)
261 #if defined AFS && defined EPERM
266 error (0, errno, _("cannot change owner and/or group of %s"),
274 struct ptr_list *new = (struct ptr_list *)
275 alloca (sizeof (struct ptr_list));
276 new->dirname_end = slash;
277 new->next = leading_dirs;
282 /* If we were able to save the initial working directory,
283 then we can use chdir to change into each directory before
284 creating an entry in that directory. This avoids making
285 stat and mkdir process O(n^2) file name components. */
286 if (do_chdir && chdir (basename_dir) < 0)
288 error (0, errno, _("cannot chdir to directory %s"),
296 /* Avoid unnecessary calls to `stat' when given
297 file names containing multiple adjacent slashes. */
298 while (*slash == '/')
305 /* Done creating leading directories. Restore original umask. */
308 /* We're done making leading directories.
309 Create the final component of the file name. */
311 if (! make_dir (basename_dir, dir, mode, NULL))
317 if (verbose_fmt_string != NULL)
318 error (0, 0, verbose_fmt_string, quote (dir));
320 if (owner != (uid_t) -1 || group != (gid_t) -1)
322 if (chown (basename_dir, owner, group)
328 error (0, errno, _("cannot change owner and/or group of %s"),
334 /* The above chown may have turned off some permission bits in MODE.
335 Another reason we may have to use chmod here is that mkdir(2) is
336 required to honor only the file permission bits. In particular,
337 it need not honor the `special' bits, so if MODE includes any
338 special bits, set them here. */
339 if ((mode & ~S_IRWXUGO)
340 && chmod (basename_dir, mode))
342 error (0, errno, _("cannot change permissions of %s"),
349 /* If the mode for leading directories didn't include owner "wx"
350 privileges, we have to reset their protections to the correct
352 for (p = leading_dirs; p != NULL; p = p->next)
354 *(p->dirname_end) = '\0';
355 if (chmod (dir, parent_mode) != 0)
357 error (0, errno, _("cannot change permissions of %s"),
365 /* We get here if the file already exists. */
367 char const *dir = arg;
369 if (!S_ISDIR (stats.st_mode))
371 error (0, 0, _("%s exists but is not a directory"), quote (dir));
375 if (!preserve_existing)
377 /* chown must precede chmod because on some systems,
378 chown clears the set[ug]id bits for non-superusers,
379 resulting in incorrect permissions.
380 On System V, users can give away files with chown and then not
381 be able to chmod them. So don't give files away. */
383 if ((owner != (uid_t) -1 || group != (gid_t) -1)
384 && chown (dir, owner, group)
390 error (0, errno, _("cannot change owner and/or group of %s"),
394 if (chmod (dir, mode) != 0)
396 error (0, errno, _("cannot change permissions of %s"),