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"
45 reply_with_perror ("rmdir: %s", path);
52 /* This implementation is quick and dirty, and allows people to try
53 * to remove parts of the initramfs (eg. "rm -r /..") but if people
54 * do stupid stuff, who are we to try to stop them?
65 if (strcmp (path, "/") == 0) {
66 reply_with_error ("rm -rf: cannot remove root directory");
70 buf = sysroot_path (path);
72 reply_with_perror ("malloc");
76 r = command (NULL, &err, "rm", "-rf", buf, NULL);
79 /* rm -rf is never supposed to fail. I/O errors perhaps? */
81 reply_with_error ("rm -rf: %s: %s", path, err);
100 r = mkdir (path, 0777);
104 reply_with_perror ("mkdir: %s", path);
112 recursive_mkdir (const char *path)
120 r = mkdir (path, 0777);
122 if (errno == EEXIST) { /* Something exists here, might not be a dir. */
123 r = lstat (path, &buf);
124 if (r == -1) return -1;
125 if (!S_ISDIR (buf.st_mode)) {
129 return 0; /* OK - directory exists here already. */
132 if (!loop && errno == ENOENT) {
133 loop = 1; /* Stops it looping forever. */
135 /* If we're at the root, and we failed, just give up. */
136 if (path[0] == '/' && path[1] == '\0') return -1;
138 /* Try to make the parent directory first. */
139 ppath = strdup (path);
140 if (ppath == NULL) return -1;
142 p = strrchr (ppath, '/');
145 r = recursive_mkdir (ppath);
148 if (r == -1) return -1;
151 } else /* Failed for some other reason, so return error. */
158 do_mkdir_p (char *path)
166 r = recursive_mkdir (path);
170 reply_with_perror ("mkdir -p: %s", path);
178 do_is_dir (char *path)
187 r = lstat (path, &buf);
191 if (errno != ENOENT && errno != ENOTDIR) {
192 reply_with_perror ("stat: %s", path);
196 return 0; /* Not a directory. */
199 return S_ISDIR (buf.st_mode);
203 do_mkdtemp (char *template)
208 ABS_PATH (template, NULL);
211 r = mkdtemp (template);
215 reply_with_perror ("mkdtemp: %s", template);
219 /* The caller will free template AND try to free the return value,
220 * so we must make a copy here.
223 r = strdup (template);
225 reply_with_perror ("strdup");