]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/findlib/makepath.c
36660a0d26d86b97709fefc828cfd42b609b42cb
[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 int
137 isAbsolute(const char *path)
138 {
139 #if defined(HAVE_WIN32)
140     return path[1] == ':' || IsPathSeparator(*path);     /* drivespec:/blah is absolute */
141 #else
142     return IsPathSeparator(*path);
143 #endif
144 }
145
146 /* Ensure that the directory ARGPATH exists.
147    Remove any trailing slashes from ARGPATH before calling this function.
148
149    Create any leading directories that don't already exist, with
150    permissions PARENT_MODE.
151
152    If the last element of ARGPATH does not exist, create it as
153    a new directory with permissions MODE.
154
155    If OWNER and GROUP are non-negative, use them to set the UID and GID of
156    any created directories.
157
158    If VERBOSE_FMT_STRING is nonzero, use it as a printf format
159    string for printing a message after successfully making a directory,
160    with the name of the directory that was just made as an argument.
161
162    If PRESERVE_EXISTING is non-zero and ARGPATH is an existing directory,
163    then do not attempt to set its permissions and ownership.
164
165    Return 0 if ARGPATH exists as a directory with the proper
166    ownership and permissions when done, otherwise 1.  */
167
168 int
169 make_path(
170            JCR *jcr,
171            const char *argpath,
172            int mode,
173            int parent_mode,
174            uid_t owner,
175            gid_t group,
176            int preserve_existing,
177            char *verbose_fmt_string)
178 {
179   struct stat stats;
180   int retval = 0;
181
182   if (stat(argpath, &stats)) {
183       char *slash;
184       int tmp_mode;              /* Initial perms for leading dirs.  */
185       int re_protect;            /* Should leading dirs be unwritable? */
186       struct ptr_list {
187         char *dirname_end;
188         struct ptr_list *next;
189       };
190       struct ptr_list *p, *leading_dirs = NULL;
191       struct saved_cwd cwd;
192       char *basename_dir;
193       char *dirpath;
194
195       /* Temporarily relax umask in case it's overly restrictive.  */
196       mode_t oldmask = umask(0);
197
198       /* Make a copy of ARGPATH that we can scribble NULs on.  */
199       dirpath = (char *)alloca(strlen(argpath) + 1);
200       strcpy (dirpath, argpath);
201       strip_trailing_slashes(dirpath);
202
203       /* If leading directories shouldn't be writable or executable,
204          or should have set[ug]id or sticky bits set and we are setting
205          their owners, we need to fix their permissions after making them.  */
206       if (((parent_mode & WX_USR) != WX_USR)
207           || ((owner != (uid_t)-1 || group != (gid_t)-1)
208               && (parent_mode & (S_ISUID | S_ISGID | S_ISVTX)) != 0)) {
209          tmp_mode = S_IRWXU;
210          re_protect = 1;
211       } else {
212          tmp_mode = parent_mode;
213          re_protect = 0;
214       }
215
216 #if defined(HAVE_WIN32)
217       /* chdir can fail if permissions are sufficiently restricted since I don't think
218          backup/restore security rights affect ChangeWorkingDirectory */
219       cwd.do_chdir = 0;
220
221       /* Validate drive letter */
222       if (dirpath[1] == ':') {
223          char drive[4] = "X:\\";
224
225          drive[0] = dirpath[0];
226
227          UINT drive_type = GetDriveType(drive);
228
229          if (drive_type == DRIVE_UNKNOWN || drive_type == DRIVE_NO_ROOT_DIR) {
230             Jmsg(jcr, M_ERROR, 0, _("%c: is not a valid drive\n"), dirpath[0]);
231             return 1;
232          }
233
234          if (dirpath[2] == '\0') {
235             return 0;
236          }
237
238          slash = &dirpath[3];
239       } else {
240          slash = dirpath;
241       }
242 #else
243       /* If we can record the current working directory, we may be able
244          to do the chdir optimization.  */
245       cwd.do_chdir = !save_cwd(&cwd);
246
247       slash = dirpath;
248 #endif
249
250       /* If we've saved the cwd and DIRPATH is an absolute pathname,
251          we must chdir to `/' in order to enable the chdir optimization.
252          So if chdir ("/") fails, turn off the optimization.  */
253       if (cwd.do_chdir && isAbsolute(dirpath) && (chdir("/") < 0)) {
254          cwd.do_chdir = 0;
255       }
256
257       /* Skip over leading slashes.  */
258       while (IsPathSeparator(*slash))
259          slash++;
260
261       for ( ; ; ) {
262           int newly_created_dir;
263           int fail;
264
265           /* slash points to the leftmost unprocessed component of dirpath.  */
266           basename_dir = slash;
267           slash = first_path_separator(slash);
268           if (slash == NULL) {
269              break;
270           }
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 (!cwd.do_chdir) {
275              basename_dir = dirpath;
276           }
277
278           *slash = '\0';
279           fail = make_dir(jcr, basename_dir, dirpath, tmp_mode, &newly_created_dir);
280           if (fail) {
281               umask(oldmask);
282               cleanup(&cwd);
283               return 1;
284           }
285
286           if (newly_created_dir) {
287               Dmsg0(300, "newly_created_dir\n");
288
289               if ((owner != (uid_t)-1 || group != (gid_t)-1)
290                   && chown(basename_dir, owner, group)
291 #if defined(AFS) && defined (EPERM)
292                   && errno != EPERM
293 #endif
294                   ) {
295                  /* Note, if we are restoring as NON-root, this may not be fatal */
296                  berrno be;
297                  Jmsg(jcr, M_ERROR, 0, _("Cannot change owner and/or group of %s: ERR=%s\n"),
298                       quote(dirpath), be.strerror());
299               }
300               Dmsg0(300, "Chown done.\n");
301
302               if (re_protect) {
303                  struct ptr_list *pnew = (struct ptr_list *)
304                     alloca(sizeof (struct ptr_list));
305                  pnew->dirname_end = slash;
306                  pnew->next = leading_dirs;
307                  leading_dirs = pnew;
308                  Dmsg0(300, "re_protect\n");
309               }
310           }
311
312           /* If we were able to save the initial working directory,
313              then we can use chdir to change into each directory before
314              creating an entry in that directory.  This avoids making
315              stat and mkdir process O(n^2) file name components.  */
316           if (cwd.do_chdir && chdir(basename_dir) < 0) {
317               berrno be;
318               Jmsg(jcr, M_ERROR, 0, _("Cannot chdir to directory, %s: ERR=%s\n"),
319                      quote(dirpath), be.strerror());
320               umask(oldmask);
321               cleanup(&cwd);
322               return 1;
323           }
324
325           *slash++ = '/';
326
327           /* Avoid unnecessary calls to `stat' when given
328              pathnames containing multiple adjacent slashes.  */
329          while (IsPathSeparator(*slash))
330             slash++;
331       } /* end while (1) */
332
333       if (!cwd.do_chdir) {
334          basename_dir = dirpath;
335       }
336
337       /* We're done making leading directories.
338          Create the final component of the path.  */
339
340       Dmsg1(300, "Create final component. mode=%o\n", mode);
341       if (make_dir(jcr, basename_dir, dirpath, mode, NULL)) {
342           umask(oldmask);
343           cleanup(&cwd);
344           return 1;
345       }
346
347       /* Done creating directories.  Restore original umask.  */
348       umask(oldmask);
349
350       if (owner != (uid_t)-1 || group != (gid_t)-1) {
351           if (chown(basename_dir, owner, group)
352 #ifdef AFS
353               && errno != EPERM
354 #endif
355               )
356             {
357               berrno be;
358               Jmsg(jcr, M_WARNING, 0, _("Cannot change owner and/or group of %s: ERR=%s\n"),
359                      quote(dirpath), be.strerror());
360             }
361       }
362
363       /* The above chown may have turned off some permission bits in MODE.
364          Another reason we may have to use chmod here is that mkdir(2) is
365          required to honor only the file permission bits.  In particular,
366          it need not honor the `special' bits, so if MODE includes any
367          special bits, set them here.  */
368       if (mode & ~S_IRWXUGO) {
369          Dmsg1(300, "Final chmod mode=%o\n", mode);
370       }
371       if ((mode & ~S_IRWXUGO) && chmod(basename_dir, mode)) {
372           berrno be;
373           Jmsg(jcr, M_WARNING, 0, _("Cannot change permissions of %s: ERR=%s\n"),
374              quote(dirpath), be.strerror());
375       }
376
377      if (cleanup(&cwd)) {
378         return 1;
379      }
380
381       /* If the mode for leading directories didn't include owner "wx"
382          privileges, we have to reset their protections to the correct
383          value.  */
384       for (p = leading_dirs; p != NULL; p = p->next) {
385           *(p->dirname_end) = '\0';
386           Dmsg2(300, "Reset parent mode=%o dir=%s\n", parent_mode, dirpath);
387           if (chmod(dirpath, parent_mode)) {
388               berrno be;
389               Jmsg(jcr, M_WARNING, 0, _("Cannot change permissions of %s: ERR=%s\n"),
390                      quote(dirpath), be.strerror());
391           }
392       }
393   } else {
394       /* We get here if the entire path already exists.  */
395
396       const char *dirpath = argpath;
397
398       if (!S_ISDIR(stats.st_mode)) {
399           Jmsg(jcr, M_ERROR, 0, _("%s exists but is not a directory\n"), quote(dirpath));
400           return 1;
401       }
402
403       if (!preserve_existing) {
404           Dmsg0(300, "Do not preserve existing.\n");
405           /* chown must precede chmod because on some systems,
406              chown clears the set[ug]id bits for non-superusers,
407              resulting in incorrect permissions.
408              On System V, users can give away files with chown and then not
409              be able to chmod them.  So don't give files away.  */
410
411           if ((owner != (uid_t)-1 || group != (gid_t)-1)
412               && chown(dirpath, owner, group)
413 #ifdef AFS
414               && errno != EPERM
415 #endif
416               ) {
417               berrno be;
418               Jmsg(jcr, M_WARNING, 0, _("Cannot change owner and/or group of %s: ERR=%s\n"),
419                      quote(dirpath), be.strerror());
420             }
421           if (chmod(dirpath, mode)) {
422               berrno be;
423               Jmsg(jcr, M_WARNING, 0, _("Cannot change permissions of %s: ERR=%s\n"),
424                                  quote(dirpath), be.strerror());
425           }
426           Dmsg2(300, "pathexists chmod mode=%o dir=%s\n", mode, dirpath);
427       }
428   }
429   return retval;
430 }