1 /* libguestfs - the guestfsd daemon
2 * Copyright (C) 2009 Red Hat Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 #include <sys/types.h>
28 #include "../src/guestfs_protocol.h"
33 do_rmdir (const char *path)
42 reply_with_perror ("rmdir: %s", path);
49 /* This implementation is quick and dirty, and allows people to try
50 * to remove parts of the initramfs (eg. "rm -r /..") but if people
51 * do stupid stuff, who are we to try to stop them?
54 do_rm_rf (const char *path)
59 if (STREQ (path, "/")) {
60 reply_with_error ("rm -rf: cannot remove root directory");
64 buf = sysroot_path (path);
66 reply_with_perror ("malloc");
70 r = command (NULL, &err, "rm", "-rf", buf, NULL);
73 /* rm -rf is never supposed to fail. I/O errors perhaps? */
75 reply_with_error ("rm -rf: %s: %s", path, err);
86 do_mkdir (const char *path)
91 r = mkdir (path, 0777);
95 reply_with_perror ("mkdir: %s", path);
103 do_mkdir_mode (const char *path, int mode)
108 r = mkdir (path, mode);
112 reply_with_perror ("mkdir_mode: %s", path);
120 recursive_mkdir (const char *path)
128 r = mkdir (path, 0777);
130 if (errno == EEXIST) { /* Something exists here, might not be a dir. */
131 r = lstat (path, &buf);
132 if (r == -1) return -1;
133 if (!S_ISDIR (buf.st_mode)) {
137 return 0; /* OK - directory exists here already. */
140 if (!loop && errno == ENOENT) {
141 loop = 1; /* Stops it looping forever. */
143 /* If we're at the root, and we failed, just give up. */
144 if (path[0] == '/' && path[1] == '\0') return -1;
146 /* Try to make the parent directory first. */
147 ppath = strdup (path);
148 if (ppath == NULL) return -1;
150 p = strrchr (ppath, '/');
153 r = recursive_mkdir (ppath);
156 if (r == -1) return -1;
159 } else /* Failed for some other reason, so return error. */
166 do_mkdir_p (const char *path)
171 r = recursive_mkdir (path);
175 reply_with_perror ("mkdir -p: %s", path);
183 do_is_dir (const char *path)
189 r = lstat (path, &buf);
193 if (errno != ENOENT && errno != ENOTDIR) {
194 reply_with_perror ("stat: %s", path);
198 return 0; /* Not a directory. */
201 return S_ISDIR (buf.st_mode);
205 do_mkdtemp (const char *template)
207 char *writable = strdup (template);
208 if (writable == NULL) {
209 reply_with_perror ("strdup");
214 char *r = mkdtemp (writable);
218 reply_with_perror ("mkdtemp: %s", template);