*** empty log message ***
[gnulib.git] / lib / makepath.c
1 /* makepath.c -- Ensure that a directory path exists.
2    Copyright (C) 1990, 1997, 1998, 1999 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 #if STDC_HEADERS
54 # include <stdlib.h>
55 #endif
56
57 #if HAVE_ERRNO_H
58 # include <errno.h>
59 #endif
60
61 #ifndef errno
62 extern int errno;
63 #endif
64
65 #if HAVE_STRING_H
66 # include <string.h>
67 #else
68 # include <strings.h>
69 # ifndef strchr
70 #  define strchr index
71 # endif
72 #endif
73
74 #ifndef S_ISUID
75 # define S_ISUID 04000
76 #endif
77 #ifndef S_ISGID
78 # define S_ISGID 02000
79 #endif
80 #ifndef S_ISVTX
81 # define S_ISVTX 01000
82 #endif
83 #ifndef S_IRUSR
84 # define S_IRUSR 0200
85 #endif
86 #ifndef S_IWUSR
87 # define S_IWUSR 0200
88 #endif
89 #ifndef S_IXUSR
90 # define S_IXUSR 0100
91 #endif
92
93 #ifndef S_IRWXU
94 # define S_IRWXU (S_IRUSR | S_IWUSR | S_IXUSR)
95 #endif
96
97 #define WX_USR (S_IWUSR | S_IXUSR)
98
99 /* Include this before libintl.h so we get our definition of PARAMS. */
100 #include "makepath.h"
101
102 #if HAVE_LOCALE_H
103 # include <locale.h>
104 #endif
105
106 #if ENABLE_NLS
107 # include <libintl.h>
108 # define _(Text) gettext (Text)
109 #else
110 # define _(Text) Text
111 #endif
112
113 #ifdef __MSDOS__
114 typedef int uid_t;
115 typedef int gid_t;
116 #endif
117
118 #include "save-cwd.h"
119 #include "error.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 will return zero
152    (indicating success) and will set *CREATED_DIR_P to zero.  */
153
154 static 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'"), dirpath);
178           fail = 1;
179         }
180       else if (!S_ISDIR (stats.st_mode))
181         {
182           error (0, 0, _("`%s' exists but is not a directory"), dirpath);
183           fail = 1;
184         }
185       else
186         {
187           /* DIR (aka DIRPATH) already exists and is a directory. */
188         }
189     }
190
191   if (created_dir_p)
192     *created_dir_p = created_dir;
193
194   return fail;
195 }
196
197 /* Ensure that the directory ARGPATH exists.
198    Remove any trailing slashes from ARGPATH before calling this function.
199
200    Create any leading directories that don't already exist, with
201    permissions PARENT_MODE.
202    If the last element of ARGPATH does not exist, create it as
203    a new directory with permissions MODE.
204    If OWNER and GROUP are non-negative, use them to set the UID and GID of
205    any created directories.
206    If VERBOSE_FMT_STRING is nonzero, use it as a printf format
207    string for printing a message after successfully making a directory,
208    with the name of the directory that was just made as an argument.
209    If PRESERVE_EXISTING is non-zero and ARGPATH is an existing directory,
210    then do not attempt to set its permissions and ownership.
211
212    Return 0 if ARGPATH exists as a directory with the proper
213    ownership and permissions when done, otherwise 1.  */
214
215 int
216 make_path (const char *argpath,
217            int mode,
218            int parent_mode,
219            uid_t owner,
220            gid_t group,
221            int preserve_existing,
222            const char *verbose_fmt_string)
223 {
224   struct stat stats;
225   int retval = 0;
226
227   if (stat (argpath, &stats))
228     {
229       char *slash;
230       int tmp_mode;             /* Initial perms for leading dirs.  */
231       int re_protect;           /* Should leading dirs be unwritable? */
232       struct ptr_list
233       {
234         char *dirname_end;
235         struct ptr_list *next;
236       };
237       struct ptr_list *p, *leading_dirs = NULL;
238       int do_chdir;             /* Whether to chdir before each mkdir.  */
239       struct saved_cwd cwd;
240       char *basename_dir;
241       char *dirpath;
242
243       /* Temporarily relax umask in case it's overly restrictive.  */
244       mode_t oldmask = umask (0);
245
246       /* Make a copy of ARGPATH that we can scribble NULs on.  */
247       dirpath = (char *) alloca (strlen (argpath) + 1);
248       strcpy (dirpath, argpath);
249       strip_trailing_slashes (dirpath);
250
251       /* If leading directories shouldn't be writable or executable,
252          or should have set[ug]id or sticky bits set and we are setting
253          their owners, we need to fix their permissions after making them.  */
254       if (((parent_mode & WX_USR) != WX_USR)
255           || ((owner != (uid_t) -1 || group != (gid_t) -1)
256               && (parent_mode & (S_ISUID | S_ISGID | S_ISVTX)) != 0))
257         {
258           tmp_mode = S_IRWXU;
259           re_protect = 1;
260         }
261       else
262         {
263           tmp_mode = parent_mode;
264           re_protect = 0;
265         }
266
267       /* If we can record the current working directory, we may be able
268          to do the chdir optimization.  */
269       do_chdir = !save_cwd (&cwd);
270
271       /* If we've saved the cwd and DIRPATH is an absolute pathname,
272          we must chdir to `/' in order to enable the chdir optimization.
273          So if chdir ("/") fails, turn off the optimization.  */
274       if (do_chdir && *dirpath == '/' && chdir ("/") < 0)
275         do_chdir = 0;
276
277       slash = dirpath;
278
279       /* Skip over leading slashes.  */
280       while (*slash == '/')
281         slash++;
282
283       while (1)
284         {
285           int newly_created_dir;
286           int fail;
287
288           /* slash points to the leftmost unprocessed component of dirpath.  */
289           basename_dir = slash;
290
291           slash = strchr (slash, '/');
292           if (slash == NULL)
293             break;
294
295           /* If we're *not* doing chdir before each mkdir, then we have to refer
296              to the target using the full (multi-component) directory name.  */
297           if (!do_chdir)
298             basename_dir = dirpath;
299
300           *slash = '\0';
301           fail = make_dir (basename_dir, dirpath, tmp_mode, &newly_created_dir);
302           if (fail)
303             {
304               CLEANUP;
305               return 1;
306             }
307
308           if (newly_created_dir)
309             {
310               if (verbose_fmt_string)
311                 error (0, 0, verbose_fmt_string, dirpath);
312
313               if ((owner != (uid_t) -1 || group != (gid_t) -1)
314                   && chown (basename_dir, owner, group)
315 #if defined(AFS) && defined (EPERM)
316                   && errno != EPERM
317 #endif
318                   )
319                 {
320                   error (0, errno, "%s", dirpath);
321                   CLEANUP;
322                   return 1;
323                 }
324
325               if (re_protect)
326                 {
327                   struct ptr_list *new = (struct ptr_list *)
328                     alloca (sizeof (struct ptr_list));
329                   new->dirname_end = slash;
330                   new->next = leading_dirs;
331                   leading_dirs = new;
332                 }
333             }
334
335           /* If we were able to save the initial working directory,
336              then we can use chdir to change into each directory before
337              creating an entry in that directory.  This avoids making
338              stat and mkdir process O(n^2) file name components.  */
339           if (do_chdir && chdir (basename_dir) < 0)
340             {
341               error (0, errno, _("cannot chdir to directory, %s"), dirpath);
342               CLEANUP;
343               return 1;
344             }
345
346           *slash++ = '/';
347
348           /* Avoid unnecessary calls to `stat' when given
349              pathnames containing multiple adjacent slashes.  */
350           while (*slash == '/')
351             slash++;
352         }
353
354       if (!do_chdir)
355         basename_dir = dirpath;
356
357       /* We're done making leading directories.
358          Create the final component of the path.  */
359
360       if (make_dir (basename_dir, dirpath, mode, NULL))
361         {
362           CLEANUP;
363           return 1;
364         }
365
366       /* Done creating directories.  Restore original umask.  */
367       umask (oldmask);
368
369       if (verbose_fmt_string != NULL)
370         error (0, 0, verbose_fmt_string, dirpath);
371
372       if (owner != (uid_t) -1 || group != (gid_t) -1)
373         {
374           if (chown (basename_dir, owner, group)
375 #ifdef AFS
376               && errno != EPERM
377 #endif
378               )
379             {
380               error (0, errno, _("cannot chown %s"), dirpath);
381               retval = 1;
382             }
383           /* chown may have turned off some permission bits we wanted.  */
384           if ((mode & (S_ISUID | S_ISGID | S_ISVTX))
385               && chmod (basename_dir, mode))
386             {
387               error (0, errno, _("cannot chmod %s"), dirpath);
388               retval = 1;
389             }
390         }
391
392       CLEANUP_CWD;
393
394       /* If the mode for leading directories didn't include owner "wx"
395          privileges, we have to reset their protections to the correct
396          value.  */
397       for (p = leading_dirs; p != NULL; p = p->next)
398         {
399           *(p->dirname_end) = '\0';
400           if (chmod (dirpath, parent_mode))
401             {
402               error (0, errno, "%s", 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"), 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, "%s", dirpath);
435               retval = 1;
436             }
437           if (chmod (dirpath, mode))
438             {
439               error (0, errno, "%s", dirpath);
440               retval = 1;
441             }
442         }
443     }
444
445   return retval;
446 }