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