*** 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 #include "quote.h"
120
121 void strip_trailing_slashes ();
122
123 #define CLEANUP_CWD                                     \
124   do                                                    \
125     {                                                   \
126       /* We're done operating on basename_dir.          \
127          Restore working directory.  */                 \
128       if (do_chdir)                                     \
129         {                                               \
130           int _fail = restore_cwd (&cwd, NULL, NULL);   \
131           free_cwd (&cwd);                              \
132           if (_fail)                                    \
133             return 1;                                   \
134         }                                               \
135     }                                                   \
136   while (0)
137
138 #define CLEANUP                                         \
139   do                                                    \
140     {                                                   \
141       umask (oldmask);                                  \
142       CLEANUP_CWD;                                      \
143     }                                                   \
144   while (0)
145
146 /* Attempt to create directory DIR (aka DIRPATH) with the specified MODE.
147    If CREATED_DIR_P is non-NULL, set *CREATED_DIR_P to non-zero if this
148    function creates DIR and to zero otherwise.  Give a diagnostic and
149    return non-zero if DIR cannot be created or cannot be determined to
150    exist already.  Use DIRPATH in any diagnostic, not DIR.
151    Note that if DIR already exists, this function returns zero
152    (indicating success) and sets *CREATED_DIR_P to zero.  */
153
154 int
155 make_dir (const char *dir, const char *dirpath, mode_t mode, int *created_dir_p)
156 {
157   int fail = 0;
158   int created_dir;
159
160   created_dir = (mkdir (dir, mode) == 0);
161
162   if (!created_dir)
163     {
164       struct stat stats;
165       int saved_errno = errno;
166
167       /* The mkdir and stat calls below may appear to be reversed.
168          They are not.  It is important to call mkdir first and then to
169          call stat (to distinguish the three cases) only if mkdir fails.
170          The alternative to this approach is to `stat' each directory,
171          then to call mkdir if it doesn't exist.  But if some other process
172          were to create the directory between the stat & mkdir, the mkdir
173          would fail with EEXIST.  */
174
175       if (stat (dir, &stats))
176         {
177           error (0, saved_errno, _("cannot create directory %s"),
178                  quote (dirpath));
179           fail = 1;
180         }
181       else if (!S_ISDIR (stats.st_mode))
182         {
183           error (0, 0, _("%s exists but is not a directory"), quote (dirpath));
184           fail = 1;
185         }
186       else
187         {
188           /* DIR (aka DIRPATH) already exists and is a directory. */
189         }
190     }
191
192   if (created_dir_p)
193     *created_dir_p = created_dir;
194
195   return fail;
196 }
197
198 /* Ensure that the directory ARGPATH exists.
199    Remove any trailing slashes from ARGPATH before calling this function.
200
201    Create any leading directories that don't already exist, with
202    permissions PARENT_MODE.
203    If the last element of ARGPATH does not exist, create it as
204    a new directory with permissions MODE.
205    If OWNER and GROUP are non-negative, use them to set the UID and GID of
206    any created directories.
207    If VERBOSE_FMT_STRING is nonzero, use it as a printf format
208    string for printing a message after successfully making a directory,
209    with the name of the directory that was just made as an argument.
210    If PRESERVE_EXISTING is non-zero and ARGPATH is an existing directory,
211    then do not attempt to set its permissions and ownership.
212
213    Return 0 if ARGPATH exists as a directory with the proper
214    ownership and permissions when done, otherwise 1.  */
215
216 int
217 make_path (const char *argpath,
218            int mode,
219            int parent_mode,
220            uid_t owner,
221            gid_t group,
222            int preserve_existing,
223            const char *verbose_fmt_string)
224 {
225   struct stat stats;
226   int retval = 0;
227
228   if (stat (argpath, &stats))
229     {
230       char *slash;
231       int tmp_mode;             /* Initial perms for leading dirs.  */
232       int re_protect;           /* Should leading dirs be unwritable? */
233       struct ptr_list
234       {
235         char *dirname_end;
236         struct ptr_list *next;
237       };
238       struct ptr_list *p, *leading_dirs = NULL;
239       int do_chdir;             /* Whether to chdir before each mkdir.  */
240       struct saved_cwd cwd;
241       char *basename_dir;
242       char *dirpath;
243
244       /* Temporarily relax umask in case it's overly restrictive.  */
245       mode_t oldmask = umask (0);
246
247       /* Make a copy of ARGPATH that we can scribble NULs on.  */
248       dirpath = (char *) alloca (strlen (argpath) + 1);
249       strcpy (dirpath, argpath);
250       strip_trailing_slashes (dirpath);
251
252       /* If leading directories shouldn't be writable or executable,
253          or should have set[ug]id or sticky bits set and we are setting
254          their owners, we need to fix their permissions after making them.  */
255       if (((parent_mode & WX_USR) != WX_USR)
256           || ((owner != (uid_t) -1 || group != (gid_t) -1)
257               && (parent_mode & (S_ISUID | S_ISGID | S_ISVTX)) != 0))
258         {
259           tmp_mode = S_IRWXU;
260           re_protect = 1;
261         }
262       else
263         {
264           tmp_mode = parent_mode;
265           re_protect = 0;
266         }
267
268       /* If we can record the current working directory, we may be able
269          to do the chdir optimization.  */
270       do_chdir = !save_cwd (&cwd);
271
272       /* If we've saved the cwd and DIRPATH is an absolute pathname,
273          we must chdir to `/' in order to enable the chdir optimization.
274          So if chdir ("/") fails, turn off the optimization.  */
275       if (do_chdir && *dirpath == '/' && chdir ("/") < 0)
276         do_chdir = 0;
277
278       slash = dirpath;
279
280       /* Skip over leading slashes.  */
281       while (*slash == '/')
282         slash++;
283
284       while (1)
285         {
286           int newly_created_dir;
287           int fail;
288
289           /* slash points to the leftmost unprocessed component of dirpath.  */
290           basename_dir = slash;
291
292           slash = strchr (slash, '/');
293           if (slash == NULL)
294             break;
295
296           /* If we're *not* doing chdir before each mkdir, then we have to refer
297              to the target using the full (multi-component) directory name.  */
298           if (!do_chdir)
299             basename_dir = dirpath;
300
301           *slash = '\0';
302           fail = make_dir (basename_dir, dirpath, tmp_mode, &newly_created_dir);
303           if (fail)
304             {
305               CLEANUP;
306               return 1;
307             }
308
309           if (newly_created_dir)
310             {
311               if (verbose_fmt_string)
312                 error (0, 0, verbose_fmt_string, quote (dirpath));
313
314               if ((owner != (uid_t) -1 || group != (gid_t) -1)
315                   && chown (basename_dir, owner, group)
316 #if defined(AFS) && defined (EPERM)
317                   && errno != EPERM
318 #endif
319                   )
320                 {
321                   error (0, errno, _("cannot change owner and/or group of %s"),
322                          quote (dirpath));
323                   CLEANUP;
324                   return 1;
325                 }
326
327               if (re_protect)
328                 {
329                   struct ptr_list *new = (struct ptr_list *)
330                     alloca (sizeof (struct ptr_list));
331                   new->dirname_end = slash;
332                   new->next = leading_dirs;
333                   leading_dirs = new;
334                 }
335             }
336
337           /* If we were able to save the initial working directory,
338              then we can use chdir to change into each directory before
339              creating an entry in that directory.  This avoids making
340              stat and mkdir process O(n^2) file name components.  */
341           if (do_chdir && chdir (basename_dir) < 0)
342             {
343               error (0, errno, _("cannot chdir to directory, %s"),
344                      quote (dirpath));
345               CLEANUP;
346               return 1;
347             }
348
349           *slash++ = '/';
350
351           /* Avoid unnecessary calls to `stat' when given
352              pathnames containing multiple adjacent slashes.  */
353           while (*slash == '/')
354             slash++;
355         }
356
357       if (!do_chdir)
358         basename_dir = dirpath;
359
360       /* We're done making leading directories.
361          Create the final component of the path.  */
362
363       if (make_dir (basename_dir, dirpath, mode, NULL))
364         {
365           CLEANUP;
366           return 1;
367         }
368
369       /* Done creating directories.  Restore original umask.  */
370       umask (oldmask);
371
372       if (verbose_fmt_string != NULL)
373         error (0, 0, verbose_fmt_string, quote (dirpath));
374
375       if (owner != (uid_t) -1 || group != (gid_t) -1)
376         {
377           if (chown (basename_dir, owner, group)
378 #ifdef AFS
379               && errno != EPERM
380 #endif
381               )
382             {
383               error (0, errno, _("cannot change owner and/or group of %s"),
384                      quote (dirpath));
385               retval = 1;
386             }
387         }
388
389       /* The above chown may have turned off some permission bits in MODE.
390          Another reason we may have to use chmod here is that mkdir(2) is
391          required to honor only the file permission bits.  In particular,
392          it need not honor the `special' bits, so if MODE includes any
393          special bits, set them here.  */
394       if ((mode & ~S_IRWXUGO)
395           && chmod (basename_dir, mode))
396         {
397           error (0, errno, _("cannot change permissions of %s"), quote (dirpath));
398           retval = 1;
399         }
400
401       CLEANUP_CWD;
402
403       /* If the mode for leading directories didn't include owner "wx"
404          privileges, we have to reset their protections to the correct
405          value.  */
406       for (p = leading_dirs; p != NULL; p = p->next)
407         {
408           *(p->dirname_end) = '\0';
409           if (chmod (dirpath, parent_mode))
410             {
411               error (0, errno, "cannot change permissions of %s",
412                      quote (dirpath));
413               retval = 1;
414             }
415         }
416     }
417   else
418     {
419       /* We get here if the entire path already exists.  */
420
421       const char *dirpath = argpath;
422
423       if (!S_ISDIR (stats.st_mode))
424         {
425           error (0, 0, _("%s exists but is not a directory"), quote (dirpath));
426           return 1;
427         }
428
429       if (!preserve_existing)
430         {
431           /* chown must precede chmod because on some systems,
432              chown clears the set[ug]id bits for non-superusers,
433              resulting in incorrect permissions.
434              On System V, users can give away files with chown and then not
435              be able to chmod them.  So don't give files away.  */
436
437           if ((owner != (uid_t) -1 || group != (gid_t) -1)
438               && chown (dirpath, owner, group)
439 #ifdef AFS
440               && errno != EPERM
441 #endif
442               )
443             {
444               error (0, errno, _("cannot change owner and/or group of %s"),
445                      quote (dirpath));
446               retval = 1;
447             }
448           if (chmod (dirpath, mode))
449             {
450               error (0, errno, _("cannot change permissions of %s"),
451                                  quote (dirpath));
452               retval = 1;
453             }
454         }
455     }
456
457   return retval;
458 }