2 * Copyright (C) 2010 Red Hat Inc.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library 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 GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
31 #include <sys/select.h>
35 #ifdef HAVE_SYS_TYPES_H
36 #include <sys/types.h>
40 #include "guestfs-internal.h"
41 #include "guestfs-internal-actions.h"
42 #include "guestfs_protocol.h"
44 static const char *kernel_name = "vmlinuz." host_cpu;
45 static const char *initrd_name = "initramfs." host_cpu ".img";
47 static int find_path (guestfs_h *g, int (*pred) (guestfs_h *g, const char *pelem, void *data), void *data, char **pelem);
48 static int dir_contains_file (const char *dir, const char *file);
49 static int dir_contains_files (const char *dir, ...);
50 static int contains_ordinary_appliance (guestfs_h *g, const char *path, void *data);
52 static int contains_supermin_appliance (guestfs_h *g, const char *path, void *data);
53 static char *calculate_supermin_checksum (guestfs_h *g, const char *supermin_path);
54 static int check_for_cached_appliance (guestfs_h *g, const char *supermin_path, const char *checksum, char **kernel, char **initrd, char **appliance);
55 static int build_supermin_appliance (guestfs_h *g, const char *supermin_path, const char *checksum, char **kernel, char **initrd, char **appliance);
56 static int run_supermin_helper (guestfs_h *g, const char *supermin_path, const char *cachedir, size_t cdlen);
59 /* Locate or build the appliance.
61 * This function locates or builds the appliance as necessary,
62 * handling the supermin appliance, caching of supermin-built
63 * appliances, or using an ordinary appliance.
65 * The return value is 0 = good, -1 = error. Returned in '*kernel'
66 * will be the name of the kernel to use, '*initrd' the name of the
67 * initrd, '*appliance' the name of the ext2 root filesystem.
68 * '*appliance' can be NULL, meaning that we are using an ordinary
69 * (non-ext2) appliance. All three strings must be freed by the
70 * caller. However the referenced files themselves must not be
73 * The process is as follows:
75 * (1) Look for the first element of g->path which contains a
76 * supermin appliance skeleton. If no element has this, skip
77 * straight to step (5).
78 * (2) Calculate the checksum of this supermin appliance.
79 * (3) Check whether $TMPDIR/$checksum/ directory exists, contains
80 * a cached appliance, and passes basic security checks. If so,
81 * return this appliance.
82 * (4) Try to build the supermin appliance into $TMPDIR/$checksum/.
83 * If this is successful, return it.
84 * (5) Check each element of g->path, looking for an ordinary appliance.
85 * If one is found, return it.
88 guestfs___build_appliance (guestfs_h *g,
89 char **kernel, char **initrd, char **appliance)
96 r = find_path (g, contains_supermin_appliance, NULL, &supermin_path);
101 /* Step (2): calculate checksum. */
102 char *checksum = calculate_supermin_checksum (g, supermin_path);
104 /* Step (3): cached appliance exists? */
105 r = check_for_cached_appliance (g, supermin_path, checksum,
106 kernel, initrd, appliance);
108 free (supermin_path);
110 return r == 1 ? 0 : -1;
113 /* Step (4): build supermin appliance. */
114 r = build_supermin_appliance (g, supermin_path, checksum,
115 kernel, initrd, appliance);
116 free (supermin_path);
120 free (supermin_path);
126 r = find_path (g, contains_ordinary_appliance, NULL, &path);
131 size_t len = strlen (path);
132 *kernel = safe_malloc (g, len + strlen (kernel_name) + 2);
133 *initrd = safe_malloc (g, len + strlen (initrd_name) + 2);
134 sprintf (*kernel, "%s/%s", path, kernel_name);
135 sprintf (*initrd, "%s/%s", path, initrd_name);
142 error (g, _("cannot find any suitable libguestfs supermin or ordinary appliance on LIBGUESTFS_PATH (search path: %s)"),
148 contains_ordinary_appliance (guestfs_h *g, const char *path, void *data)
150 return dir_contains_files (path, kernel_name, initrd_name, NULL);
155 contains_supermin_appliance (guestfs_h *g, const char *path, void *data)
157 return dir_contains_files (path, "supermin.d", "kmod.whitelist", NULL);
160 /* supermin_path is a path which is known to contain a supermin
161 * appliance. Using febootstrap-supermin-helper -f checksum calculate
162 * the checksum so we can see if it is cached.
165 calculate_supermin_checksum (guestfs_h *g, const char *supermin_path)
167 size_t len = 2 * strlen (supermin_path) + 256;
169 int pass_u_g_args = getuid () != geteuid () || getgid () != getegid ();
173 "febootstrap-supermin-helper%s "
177 g->verbose ? " --verbose" : "",
181 "febootstrap-supermin-helper%s "
187 g->verbose ? " --verbose" : "",
188 geteuid (), getegid (),
192 guestfs___print_timestamped_message (g, "%s", cmd);
194 /* Errors here are non-fatal, so we don't need to call error(). */
195 FILE *pp = popen (cmd, "r");
200 if (fgets (checksum, sizeof checksum, pp) == NULL) {
205 if (pclose (pp) == -1) {
210 len = strlen (checksum);
212 if (len < 16) { /* sanity check */
213 fprintf (stderr, "libguestfs: internal error: febootstrap-supermin-helper -f checksum returned a short string\n");
217 if (len > 0 && checksum[len-1] == '\n')
218 checksum[--len] = '\0';
220 return safe_strndup (g, checksum, len);
223 /* Check for cached appliance in $TMPDIR/$checksum. Check it exists
224 * and passes some basic security checks.
227 * 1 = exists, and passes
229 * -1 = error which should abort the whole launch process
232 security_check_cache_file (guestfs_h *g, const char *filename,
233 const struct stat *statbuf)
235 uid_t uid = geteuid ();
237 if (statbuf->st_uid != uid) {
238 error (g, ("libguestfs cached appliance %s is not owned by UID %d\n"),
243 if ((statbuf->st_mode & 0022) != 0) {
244 error (g, ("libguestfs cached appliance %s is writable by group or other (mode %o)\n"),
245 filename, statbuf->st_mode);
253 check_for_cached_appliance (guestfs_h *g,
254 const char *supermin_path, const char *checksum,
255 char **kernel, char **initrd, char **appliance)
257 const char *tmpdir = guestfs_tmpdir ();
259 size_t len = strlen (tmpdir) + strlen (checksum) + 10;
261 snprintf (cachedir, len, "%s/guestfs.%s", tmpdir, checksum);
263 /* Touch the directory to prevent it being deleting in a rare race
264 * between us doing the checks and a tmp cleaner running. Note this
265 * doesn't create the directory, and we ignore any error.
267 (void) utime (cachedir, NULL);
269 /* See if the cache directory exists and passes some simple checks
270 * to make sure it has not been tampered with. Note that geteuid()
271 * forms a part of the checksum.
274 if (lstat (cachedir, &statbuf) == -1)
277 if (security_check_cache_file (g, cachedir, &statbuf) == -1)
282 *kernel = safe_malloc (g, len + 8 /* / + "kernel" + \0 */);
283 *initrd = safe_malloc (g, len + 8 /* / + "initrd" + \0 */);
284 *appliance = safe_malloc (g, len + 6 /* / + "root" + \0 */);
285 sprintf (*kernel, "%s/kernel", cachedir);
286 sprintf (*initrd, "%s/initrd", cachedir);
287 sprintf (*appliance, "%s/root", cachedir);
289 /* Touch the files to prevent them being deleted, and to bring the
290 * cache up to date. Note this doesn't create the files.
292 (void) utime (*kernel, NULL);
294 /* NB. *kernel is a symlink, so we want to check the kernel, not the
295 * link (stat, not lstat). We don't do a security check on the
296 * kernel since it's always under /boot.
298 if (stat (*kernel, &statbuf) == -1) {
303 (void) utime (*initrd, NULL);
305 if (lstat (*initrd, &statbuf) == -1) {
310 if (security_check_cache_file (g, *initrd, &statbuf) == -1) {
315 (void) utime (*appliance, NULL);
317 if (lstat (*appliance, &statbuf) == -1) {
322 if (security_check_cache_file (g, *appliance, &statbuf) == -1) {
337 /* Build supermin appliance from supermin_path to $TMPDIR/$checksum.
341 * -1 = error (aborts launch)
344 build_supermin_appliance (guestfs_h *g,
345 const char *supermin_path, const char *checksum,
346 char **kernel, char **initrd, char **appliance)
349 guestfs___print_timestamped_message (g, "begin building supermin appliance");
351 const char *tmpdir = guestfs_tmpdir ();
353 size_t tmpcdlen = strlen (tmpdir) + 16;
354 char tmpcd[tmpcdlen];
355 snprintf (tmpcd, tmpcdlen, "%s/guestfs.XXXXXX", tmpdir);
357 if (NULL == mkdtemp (tmpcd)) {
358 error (g, _("failed to create temporary cache directory: %m"));
363 guestfs___print_timestamped_message (g, "run febootstrap-supermin-helper");
365 int r = run_supermin_helper (g, supermin_path, tmpcd, tmpcdlen);
370 guestfs___print_timestamped_message (g, "finished building supermin appliance");
372 size_t cdlen = strlen (tmpdir) + strlen (checksum) + 10;
373 char cachedir[cdlen];
374 snprintf (cachedir, cdlen, "%s/guestfs.%s", tmpdir, checksum);
376 /* Make the temporary directory world readable */
377 if (chmod (tmpcd, 0755) == -1) {
378 error (g, "chmod %s: %m", tmpcd);
381 /* Try to rename the temporary directory to its non-temporary name */
382 if (rename (tmpcd, cachedir) == -1) {
383 /* If the cache directory now exists, we may have been racing with another
384 * libguestfs process. Check the new directory and use it if it's valid. */
385 if (errno == ENOTEMPTY || errno == EEXIST) {
386 /* Appliance cache consists of 2 files and a symlink in the cache
387 * directory. Delete them first. */
388 DIR *dir = opendir (tmpcd);
390 error (g, "opendir %s: %m", tmpcd);
394 int fd = dirfd (dir);
396 error (g, "dirfd: %m");
401 struct dirent *dirent;
404 dirent = readdir (dir);
406 if (dirent == NULL) {
410 /* Check that dirent is a file so we don't try to delete . and .. */
412 if (fstatat (fd, dirent->d_name, &st, AT_SYMLINK_NOFOLLOW) == -1) {
413 error (g, "fstatat %s: %m", dirent->d_name);
417 if (!S_ISDIR(st.st_mode)) {
418 if (unlinkat (fd, dirent->d_name, 0) == -1) {
419 error (g, "unlinkat %s: %m", dirent->d_name);
427 error (g, "readdir %s: %m", tmpcd);
434 /* Delete the temporary cache directory itself. */
435 if (rmdir (tmpcd) == -1) {
436 error (g, "rmdir %s: %m", tmpcd);
440 /* Check the new cache directory, and return it if valid */
441 return check_for_cached_appliance (g, supermin_path, checksum,
442 kernel, initrd, appliance);
446 error (g, _("error renaming temporary cache directory: %m"));
451 *kernel = safe_malloc (g, cdlen + 8 /* / + "kernel" + \0 */);
452 *initrd = safe_malloc (g, cdlen + 8 /* / + "initrd" + \0 */);
453 *appliance = safe_malloc (g, cdlen + 6 /* / + "root" + \0 */);
454 sprintf (*kernel, "%s/kernel", cachedir);
455 sprintf (*initrd, "%s/initrd", cachedir);
456 sprintf (*appliance, "%s/root", cachedir);
461 /* Run febootstrap-supermin-helper and tell it to generate the
465 run_supermin_helper (guestfs_h *g, const char *supermin_path,
466 const char *cachedir, size_t cdlen)
468 size_t pathlen = strlen (supermin_path);
470 const char *argv[30];
474 snprintf (uid, sizeof uid, "%i", geteuid ());
476 snprintf (gid, sizeof gid, "%i", getegid ());
477 char supermin_d[pathlen + 32];
478 snprintf (supermin_d, pathlen + 32, "%s/supermin.d", supermin_path);
479 char kernel[cdlen + 32];
480 snprintf (kernel, cdlen + 32, "%s/kernel", cachedir);
481 char initrd[cdlen + 32];
482 snprintf (initrd, cdlen + 32, "%s/initrd", cachedir);
483 char root[cdlen + 32];
484 snprintf (root, cdlen + 32, "%s/root", cachedir);
486 int pass_u_g_args = getuid () != geteuid () || getgid () != getegid ();
488 argv[i++] = "febootstrap-supermin-helper";
490 argv[i++] = "--verbose";
499 argv[i++] = supermin_d;
500 argv[i++] = host_cpu;
512 if (pid > 0) { /* Parent. */
514 guestfs___print_timestamped_argv (g, argv);
517 if (waitpid (pid, &status, 0) == -1) {
518 perrorf (g, "waitpid");
521 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0) {
522 error (g, _("external command failed, see earlier error messages"));
530 /* Set a sensible umask in the subprocess, so kernel and initrd
531 * output files are world-readable (RHBZ#610880).
535 execvp ("febootstrap-supermin-helper", (char * const *) argv);
537 _exit (EXIT_FAILURE);
541 /* Search elements of g->path, returning the first path element which
542 * matches the predicate function 'pred'.
544 * Function 'pred' must return a true or false value. If it returns
545 * -1 then the entire search is aborted.
548 * 1 = a path element matched, it is returned in *pelem_ret and must be
549 * freed by the caller,
550 * 0 = no path element matched, *pelem_ret is set to NULL, or
551 * -1 = error which aborts the launch process
554 find_path (guestfs_h *g,
555 int (*pred) (guestfs_h *g, const char *pelem, void *data),
561 const char *pelem = g->path;
563 /* Note that if g->path is an empty string, we want to check the
564 * current directory (for backwards compatibility with
565 * libguestfs < 1.5.4).
568 len = strcspn (pelem, ":");
570 /* Empty element or "." means current directory. */
572 *pelem_ret = safe_strdup (g, ".");
574 *pelem_ret = safe_strndup (g, pelem, len);
576 r = pred (g, *pelem_ret, data);
582 if (r != 0) /* predicate matched */
587 if (pelem[len] == ':')
593 /* Predicate didn't match on any path element. */
598 /* Returns true iff file is contained in dir. */
600 dir_contains_file (const char *dir, const char *file)
602 size_t dirlen = strlen (dir);
603 size_t filelen = strlen (file);
604 size_t len = dirlen + filelen + 2;
607 snprintf (path, len, "%s/%s", dir, file);
608 return access (path, F_OK) == 0;
611 /* Returns true iff every listed file is contained in 'dir'. */
613 dir_contains_files (const char *dir, ...)
618 va_start (args, dir);
619 while ((file = va_arg (args, const char *)) != NULL) {
620 if (!dir_contains_file (dir, file)) {