Sync from coreutils.
[gnulib.git] / lib / mkdir-p.c
1 /* mkdir-p.c -- Ensure that a directory and its parents exist.
2
3    Copyright (C) 1990, 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005
4    Free Software Foundation, Inc.
5
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)
9    any later version.
10
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.
15
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.  */
19
20 /* Written by David MacKenzie <djm@gnu.ai.mit.edu> and Jim Meyering.  */
21
22 #if HAVE_CONFIG_H
23 # include <config.h>
24 #endif
25
26 #include "mkdir-p.h"
27
28 #include <alloca.h>
29
30 #include <stdio.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #if HAVE_UNISTD_H
34 # include <unistd.h>
35 #endif
36
37 #include <stdlib.h>
38 #include <errno.h>
39 #include <string.h>
40
41 #include "gettext.h"
42 #define _(msgid) gettext (msgid)
43
44 #include "save-cwd.h"
45 #include "dirname.h"
46 #include "error.h"
47 #include "quote.h"
48 #include "stat-macros.h"
49
50 #define WX_USR (S_IWUSR | S_IXUSR)
51
52 #define CLEANUP_CWD                                     \
53   do                                                    \
54     {                                                   \
55       /* We're done operating on basename_dir.          \
56          Restore working directory.  */                 \
57       if (do_chdir)                                     \
58         {                                               \
59           if (restore_cwd (&cwd) != 0)                  \
60             {                                           \
61               int _saved_errno = errno;                 \
62               error (0, errno,                          \
63                 _("failed to return to initial working directory")); \
64               free_cwd (&cwd);                          \
65               errno = _saved_errno;                     \
66               return 1;                                 \
67             }                                           \
68           free_cwd (&cwd);                              \
69         }                                               \
70     }                                                   \
71   while (0)
72
73 #define CLEANUP                                         \
74   do                                                    \
75     {                                                   \
76       umask (oldmask);                                  \
77       CLEANUP_CWD;                                      \
78     }                                                   \
79   while (0)
80
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.  */
88
89 bool
90 make_dir (char const *dir, char const *fulldir, mode_t mode,
91           bool *created_dir_p)
92 {
93   bool ok = true;
94   bool created_dir;
95
96   created_dir = (mkdir (dir, mode) == 0);
97
98   if (!created_dir)
99     {
100       struct stat stats;
101       int saved_errno = errno;
102
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.  */
110
111       if (stat (dir, &stats))
112         {
113           error (0, saved_errno, _("cannot create directory %s"),
114                  quote (fulldir));
115           ok = false;
116         }
117       else if (!S_ISDIR (stats.st_mode))
118         {
119           error (0, 0, _("%s exists but is not a directory"), quote (fulldir));
120           ok = false;
121         }
122       else
123         {
124           /* DIR (aka FULLDIR) already exists and is a directory. */
125         }
126     }
127
128   if (created_dir_p)
129     *created_dir_p = created_dir;
130
131   return ok;
132 }
133
134 /* Ensure that the directory ARG exists.
135
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.
147
148    Return true iff ARG exists as a directory with the proper
149    ownership and permissions when done.  */
150
151 bool
152 make_dir_parents (char const *arg,
153                   mode_t mode,
154                   mode_t parent_mode,
155                   uid_t owner,
156                   gid_t group,
157                   bool preserve_existing,
158                   char const *verbose_fmt_string)
159 {
160   struct stat stats;
161   bool retval = true;
162
163   if (stat (arg, &stats) != 0)
164     {
165       char *slash;
166       mode_t tmp_mode;          /* Initial perms for leading dirs.  */
167       bool re_protect;          /* Should leading dirs be unwritable? */
168       struct ptr_list
169       {
170         char *dirname_end;
171         struct ptr_list *next;
172       };
173       struct ptr_list *p, *leading_dirs = NULL;
174       bool do_chdir;            /* Whether to chdir before each mkdir.  */
175       struct saved_cwd cwd;
176       char *basename_dir;
177       char *dir;
178
179       /* Temporarily relax umask in case it's overly restrictive.  */
180       mode_t oldmask = umask (0);
181
182       /* Make a copy of ARG that we can scribble NULs on.  */
183       dir = (char *) alloca (strlen (arg) + 1);
184       strcpy (dir, arg);
185       strip_trailing_slashes (dir);
186
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))
193         {
194           tmp_mode = S_IRWXU;
195           re_protect = true;
196         }
197       else
198         {
199           tmp_mode = parent_mode;
200           re_protect = false;
201         }
202
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);
206
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] == '/')
211         {
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)
216             do_chdir = false;
217         }
218
219       slash = dir;
220
221       /* Skip over leading slashes.  */
222       while (*slash == '/')
223         slash++;
224
225       while (1)
226         {
227           bool newly_created_dir;
228
229           /* slash points to the leftmost unprocessed component of dir.  */
230           basename_dir = slash;
231
232           slash = strchr (slash, '/');
233           if (slash == NULL)
234             break;
235
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.  */
238           if (!do_chdir)
239             basename_dir = dir;
240
241           *slash = '\0';
242           if (! make_dir (basename_dir, dir, tmp_mode, &newly_created_dir))
243             {
244               CLEANUP;
245               return false;
246             }
247
248           if (newly_created_dir)
249             {
250               if (verbose_fmt_string)
251                 error (0, 0, verbose_fmt_string, quote (dir));
252
253               if ((owner != (uid_t) -1 || group != (gid_t) -1)
254                   && chown (basename_dir, owner, group)
255 #if defined AFS && defined EPERM
256                   && errno != EPERM
257 #endif
258                   )
259                 {
260                   error (0, errno, _("cannot change owner and/or group of %s"),
261                          quote (dir));
262                   CLEANUP;
263                   return false;
264                 }
265
266               if (re_protect)
267                 {
268                   struct ptr_list *new = (struct ptr_list *)
269                     alloca (sizeof (struct ptr_list));
270                   new->dirname_end = slash;
271                   new->next = leading_dirs;
272                   leading_dirs = new;
273                 }
274             }
275
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)
281             {
282               error (0, errno, _("cannot chdir to directory %s"),
283                      quote (dir));
284               CLEANUP;
285               return false;
286             }
287
288           *slash++ = '/';
289
290           /* Avoid unnecessary calls to `stat' when given
291              file names containing multiple adjacent slashes.  */
292           while (*slash == '/')
293             slash++;
294         }
295
296       if (!do_chdir)
297         basename_dir = dir;
298
299       /* Done creating leading directories.  Restore original umask.  */
300       umask (oldmask);
301
302       /* We're done making leading directories.
303          Create the final component of the file name.  */
304
305       if (! make_dir (basename_dir, dir, mode, NULL))
306         {
307           CLEANUP;
308           return false;
309         }
310
311       if (verbose_fmt_string != NULL)
312         error (0, 0, verbose_fmt_string, quote (dir));
313
314       if (owner != (uid_t) -1 || group != (gid_t) -1)
315         {
316           if (chown (basename_dir, owner, group)
317 #ifdef AFS
318               && errno != EPERM
319 #endif
320               )
321             {
322               error (0, errno, _("cannot change owner and/or group of %s"),
323                      quote (dir));
324               retval = false;
325             }
326         }
327
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))
335         {
336           error (0, errno, _("cannot change permissions of %s"),
337                  quote (dir));
338           retval = false;
339         }
340
341       CLEANUP_CWD;
342
343       /* If the mode for leading directories didn't include owner "wx"
344          privileges, we have to reset their protections to the correct
345          value.  */
346       for (p = leading_dirs; p != NULL; p = p->next)
347         {
348           *(p->dirname_end) = '\0';
349           if (chmod (dir, parent_mode) != 0)
350             {
351               error (0, errno, _("cannot change permissions of %s"),
352                      quote (dir));
353               retval = false;
354             }
355         }
356     }
357   else
358     {
359       /* We get here if the file already exists.  */
360
361       char const *dir = arg;
362
363       if (!S_ISDIR (stats.st_mode))
364         {
365           error (0, 0, _("%s exists but is not a directory"), quote (dir));
366           return false;
367         }
368
369       if (!preserve_existing)
370         {
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.  */
376
377           if ((owner != (uid_t) -1 || group != (gid_t) -1)
378               && chown (dir, owner, group)
379 #ifdef AFS
380               && errno != EPERM
381 #endif
382               )
383             {
384               error (0, errno, _("cannot change owner and/or group of %s"),
385                      quote (dir));
386               retval = false;
387             }
388           if (chmod (dir, mode) != 0)
389             {
390               error (0, errno, _("cannot change permissions of %s"),
391                                  quote (dir));
392               retval = false;
393             }
394         }
395     }
396
397   return retval;
398 }