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