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