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