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