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