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