*** empty log message ***
[gnulib.git] / lib / makepath.c
1 /* makepath.c -- Ensure that a directory path exists.
2    Copyright (C) 1990, 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Written by David MacKenzie <djm@gnu.ai.mit.edu> and Jim Meyering.  */
19
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #if __GNUC__
25 # define alloca __builtin_alloca
26 #else
27 # if HAVE_ALLOCA_H
28 #  include <alloca.h>
29 # else
30 #  ifdef _AIX
31  #  pragma alloca
32 #  else
33 char *alloca ();
34 #  endif
35 # endif
36 #endif
37
38 #include <stdio.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #if HAVE_UNISTD_H
42 # include <unistd.h>
43 #endif
44
45 #if STAT_MACROS_BROKEN
46 # undef S_ISDIR
47 #endif
48
49 #if !defined(S_ISDIR) && defined(S_IFDIR)
50 # define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
51 #endif
52
53 #ifndef S_IRWXUGO
54 # define S_IRWXUGO (S_IRWXU | S_IRWXG | S_IRWXO)
55 #endif
56
57 #if STDC_HEADERS
58 # include <stdlib.h>
59 #endif
60
61 #if HAVE_ERRNO_H
62 # include <errno.h>
63 #endif
64
65 #ifndef errno
66 extern int errno;
67 #endif
68
69 #if HAVE_STRING_H
70 # include <string.h>
71 #else
72 # include <strings.h>
73 # ifndef strchr
74 #  define strchr index
75 # endif
76 #endif
77
78 #ifndef S_ISUID
79 # define S_ISUID 04000
80 #endif
81 #ifndef S_ISGID
82 # define S_ISGID 02000
83 #endif
84 #ifndef S_ISVTX
85 # define S_ISVTX 01000
86 #endif
87 #ifndef S_IRUSR
88 # define S_IRUSR 0200
89 #endif
90 #ifndef S_IWUSR
91 # define S_IWUSR 0200
92 #endif
93 #ifndef S_IXUSR
94 # define S_IXUSR 0100
95 #endif
96
97 #ifndef S_IRWXU
98 # define S_IRWXU (S_IRUSR | S_IWUSR | S_IXUSR)
99 #endif
100
101 #define WX_USR (S_IWUSR | S_IXUSR)
102
103 /* Include this before libintl.h so we get our definition of PARAMS. */
104 #include "makepath.h"
105
106 #if HAVE_LOCALE_H
107 # include <locale.h>
108 #endif
109
110 #if ENABLE_NLS
111 # include <libintl.h>
112 # define _(Text) gettext (Text)
113 #else
114 # define _(Text) Text
115 #endif
116
117 #include "save-cwd.h"
118 #include "error.h"
119
120 void strip_trailing_slashes ();
121
122 #define CLEANUP_CWD                                     \
123   do                                                    \
124     {                                                   \
125       /* We're done operating on basename_dir.          \
126          Restore working directory.  */                 \
127       if (do_chdir)                                     \
128         {                                               \
129           int _fail = restore_cwd (&cwd, NULL, NULL);   \
130           free_cwd (&cwd);                              \
131           if (_fail)                                    \
132             return 1;                                   \
133         }                                               \
134     }                                                   \
135   while (0)
136
137 #define CLEANUP                                         \
138   do                                                    \
139     {                                                   \
140       umask (oldmask);                                  \
141       CLEANUP_CWD;                                      \
142     }                                                   \
143   while (0)
144
145 /* Attempt to create directory DIR (aka DIRPATH) with the specified MODE.
146    If CREATED_DIR_P is non-NULL, set *CREATED_DIR_P to non-zero if this
147    function creates DIR and to zero otherwise.  Give a diagnostic and
148    return non-zero if DIR cannot be created or cannot be determined to
149    exist already.  Use DIRPATH in any diagnostic, not DIR.
150    Note that if DIR already exists, this function will return zero
151    (indicating success) and will set *CREATED_DIR_P to zero.  */
152
153 static int
154 make_dir (const char *dir, const char *dirpath, mode_t mode, int *created_dir_p)
155 {
156   int fail = 0;
157   int created_dir;
158
159   created_dir = (mkdir (dir, mode) == 0);
160
161   if (!created_dir)
162     {
163       struct stat stats;
164       int saved_errno = errno;
165
166       /* The mkdir and stat calls below may appear to be reversed.
167          They are not.  It is important to call mkdir first and then to
168          call stat (to distinguish the three cases) only if mkdir fails.
169          The alternative to this approach is to `stat' each directory,
170          then to call mkdir if it doesn't exist.  But if some other process
171          were to create the directory between the stat & mkdir, the mkdir
172          would fail with EEXIST.  */
173
174       if (stat (dir, &stats))
175         {
176           error (0, saved_errno, _("cannot create directory `%s'"), dirpath);
177           fail = 1;
178         }
179       else if (!S_ISDIR (stats.st_mode))
180         {
181           error (0, 0, _("`%s' exists but is not a directory"), dirpath);
182           fail = 1;
183         }
184       else
185         {
186           /* DIR (aka DIRPATH) already exists and is a directory. */
187         }
188     }
189
190   if (created_dir_p)
191     *created_dir_p = created_dir;
192
193   return fail;
194 }
195
196 /* Ensure that the directory ARGPATH exists.
197    Remove any trailing slashes from ARGPATH before calling this function.
198
199    Create any leading directories that don't already exist, with
200    permissions PARENT_MODE.
201    If the last element of ARGPATH does not exist, create it as
202    a new directory with permissions MODE.
203    If OWNER and GROUP are non-negative, use them to set the UID and GID of
204    any created directories.
205    If VERBOSE_FMT_STRING is nonzero, use it as a printf format
206    string for printing a message after successfully making a directory,
207    with the name of the directory that was just made as an argument.
208    If PRESERVE_EXISTING is non-zero and ARGPATH is an existing directory,
209    then do not attempt to set its permissions and ownership.
210
211    Return 0 if ARGPATH exists as a directory with the proper
212    ownership and permissions when done, otherwise 1.  */
213
214 int
215 make_path (const char *argpath,
216            int mode,
217            int parent_mode,
218            uid_t owner,
219            gid_t group,
220            int preserve_existing,
221            const char *verbose_fmt_string)
222 {
223   struct stat stats;
224   int retval = 0;
225
226   if (stat (argpath, &stats))
227     {
228       char *slash;
229       int tmp_mode;             /* Initial perms for leading dirs.  */
230       int re_protect;           /* Should leading dirs be unwritable? */
231       struct ptr_list
232       {
233         char *dirname_end;
234         struct ptr_list *next;
235       };
236       struct ptr_list *p, *leading_dirs = NULL;
237       int do_chdir;             /* Whether to chdir before each mkdir.  */
238       struct saved_cwd cwd;
239       char *basename_dir;
240       char *dirpath;
241
242       /* Temporarily relax umask in case it's overly restrictive.  */
243       mode_t oldmask = umask (0);
244
245       /* Make a copy of ARGPATH that we can scribble NULs on.  */
246       dirpath = (char *) alloca (strlen (argpath) + 1);
247       strcpy (dirpath, argpath);
248       strip_trailing_slashes (dirpath);
249
250       /* If leading directories shouldn't be writable or executable,
251          or should have set[ug]id or sticky bits set and we are setting
252          their owners, we need to fix their permissions after making them.  */
253       if (((parent_mode & WX_USR) != WX_USR)
254           || ((owner != (uid_t) -1 || group != (gid_t) -1)
255               && (parent_mode & (S_ISUID | S_ISGID | S_ISVTX)) != 0))
256         {
257           tmp_mode = S_IRWXU;
258           re_protect = 1;
259         }
260       else
261         {
262           tmp_mode = parent_mode;
263           re_protect = 0;
264         }
265
266       /* If we can record the current working directory, we may be able
267          to do the chdir optimization.  */
268       do_chdir = !save_cwd (&cwd);
269
270       /* If we've saved the cwd and DIRPATH is an absolute pathname,
271          we must chdir to `/' in order to enable the chdir optimization.
272          So if chdir ("/") fails, turn off the optimization.  */
273       if (do_chdir && *dirpath == '/' && chdir ("/") < 0)
274         do_chdir = 0;
275
276       slash = dirpath;
277
278       /* Skip over leading slashes.  */
279       while (*slash == '/')
280         slash++;
281
282       while (1)
283         {
284           int newly_created_dir;
285           int fail;
286
287           /* slash points to the leftmost unprocessed component of dirpath.  */
288           basename_dir = slash;
289
290           slash = strchr (slash, '/');
291           if (slash == NULL)
292             break;
293
294           /* If we're *not* doing chdir before each mkdir, then we have to refer
295              to the target using the full (multi-component) directory name.  */
296           if (!do_chdir)
297             basename_dir = dirpath;
298
299           *slash = '\0';
300           fail = make_dir (basename_dir, dirpath, tmp_mode, &newly_created_dir);
301           if (fail)
302             {
303               CLEANUP;
304               return 1;
305             }
306
307           if (newly_created_dir)
308             {
309               if (verbose_fmt_string)
310                 error (0, 0, verbose_fmt_string, dirpath);
311
312               if ((owner != (uid_t) -1 || group != (gid_t) -1)
313                   && chown (basename_dir, owner, group)
314 #if defined(AFS) && defined (EPERM)
315                   && errno != EPERM
316 #endif
317                   )
318                 {
319                   error (0, errno, "%s", dirpath);
320                   CLEANUP;
321                   return 1;
322                 }
323
324               if (re_protect)
325                 {
326                   struct ptr_list *new = (struct ptr_list *)
327                     alloca (sizeof (struct ptr_list));
328                   new->dirname_end = slash;
329                   new->next = leading_dirs;
330                   leading_dirs = new;
331                 }
332             }
333
334           /* If we were able to save the initial working directory,
335              then we can use chdir to change into each directory before
336              creating an entry in that directory.  This avoids making
337              stat and mkdir process O(n^2) file name components.  */
338           if (do_chdir && chdir (basename_dir) < 0)
339             {
340               error (0, errno, _("cannot chdir to directory, %s"), dirpath);
341               CLEANUP;
342               return 1;
343             }
344
345           *slash++ = '/';
346
347           /* Avoid unnecessary calls to `stat' when given
348              pathnames containing multiple adjacent slashes.  */
349           while (*slash == '/')
350             slash++;
351         }
352
353       if (!do_chdir)
354         basename_dir = dirpath;
355
356       /* We're done making leading directories.
357          Create the final component of the path.  */
358
359       if (make_dir (basename_dir, dirpath, mode, NULL))
360         {
361           CLEANUP;
362           return 1;
363         }
364
365       /* Done creating directories.  Restore original umask.  */
366       umask (oldmask);
367
368       if (verbose_fmt_string != NULL)
369         error (0, 0, verbose_fmt_string, dirpath);
370
371       if (owner != (uid_t) -1 || group != (gid_t) -1)
372         {
373           if (chown (basename_dir, owner, group)
374 #ifdef AFS
375               && errno != EPERM
376 #endif
377               )
378             {
379               error (0, errno, _("cannot chown %s"), dirpath);
380               retval = 1;
381             }
382         }
383
384       /* The above chown may have turned off some permission bits in MODE.
385          Another reason we may have to use chmod here is that mkdir(2) is
386          required to honor only the file permission bits.  In particular,
387          it need not honor the `special' bits, so if MODE includes any
388          special bits, set them here.  */
389       if ((mode & ~S_IRWXUGO)
390           && chmod (basename_dir, mode))
391         {
392           error (0, errno, _("cannot chmod %s"), dirpath);
393           retval = 1;
394         }
395
396       CLEANUP_CWD;
397
398       /* If the mode for leading directories didn't include owner "wx"
399          privileges, we have to reset their protections to the correct
400          value.  */
401       for (p = leading_dirs; p != NULL; p = p->next)
402         {
403           *(p->dirname_end) = '\0';
404           if (chmod (dirpath, parent_mode))
405             {
406               error (0, errno, "%s", dirpath);
407               retval = 1;
408             }
409         }
410     }
411   else
412     {
413       /* We get here if the entire path already exists.  */
414
415       const char *dirpath = argpath;
416
417       if (!S_ISDIR (stats.st_mode))
418         {
419           error (0, 0, _("`%s' exists but is not a directory"), dirpath);
420           return 1;
421         }
422
423       if (!preserve_existing)
424         {
425           /* chown must precede chmod because on some systems,
426              chown clears the set[ug]id bits for non-superusers,
427              resulting in incorrect permissions.
428              On System V, users can give away files with chown and then not
429              be able to chmod them.  So don't give files away.  */
430
431           if ((owner != (uid_t) -1 || group != (gid_t) -1)
432               && chown (dirpath, owner, group)
433 #ifdef AFS
434               && errno != EPERM
435 #endif
436               )
437             {
438               error (0, errno, "%s", dirpath);
439               retval = 1;
440             }
441           if (chmod (dirpath, mode))
442             {
443               error (0, errno, "%s", dirpath);
444               retval = 1;
445             }
446         }
447     }
448
449   return retval;
450 }