2 * Copyright (C) 2010-2011 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
32 #include "ignore-value.h"
34 #include "xvasprintf.h"
39 static void do_suggestion (struct drv *drvs);
41 /* Currently open libguestfs handle. */
47 int keys_from_stdin = 0;
49 const char *libvirt_uri = NULL;
53 bad_cast (char const *s)
58 static void __attribute__((noreturn))
61 if (status != EXIT_SUCCESS)
62 fprintf (stderr, _("Try `%s --help' for more information.\n"),
66 _("%s: Run a rescue shell on a virtual machine\n"
67 "Copyright (C) 2009-2010 Red Hat Inc.\n"
69 " %s [--options] -d domname\n"
70 " %s [--options] -a disk.img [-a disk.img ...]\n"
72 " -a|--add image Add image\n"
73 " --append kernelopts Append kernel options\n"
74 " -c|--connect uri Specify libvirt URI for -d option\n"
75 " -d|--domain guest Add disks from libvirt guest\n"
76 " --format[=raw|..] Force disk format for -a option\n"
77 " --help Display brief help\n"
78 " -m|--memsize MB Set memory size in megabytes\n"
79 " --network Enable network\n"
80 " -r|--ro Access read-only\n"
81 " --selinux Enable SELinux\n"
82 " --smp N Enable SMP with N >= 2 virtual CPUs\n"
83 " --suggest Suggest mount commands for this guest\n"
84 " -v|--verbose Verbose messages\n"
85 " -V|--version Display version and exit\n"
86 " -w|--rw Mount read-write\n"
87 " -x Trace libguestfs API calls\n"
88 "For more information, see the manpage %s(1).\n"),
89 program_name, program_name, program_name,
96 main (int argc, char *argv[])
98 /* Set global program name that is not polluted with libtool artifacts. */
99 set_program_name (argv[0]);
101 setlocale (LC_ALL, "");
102 bindtextdomain (PACKAGE, LOCALEBASEDIR);
103 textdomain (PACKAGE);
107 enum { HELP_OPTION = CHAR_MAX + 1 };
109 static const char *options = "a:c:d:m:rvVx";
110 static const struct option long_options[] = {
111 { "add", 1, 0, 'a' },
112 { "append", 1, 0, 0 },
113 { "connect", 1, 0, 'c' },
114 { "domain", 1, 0, 'd' },
115 { "format", 2, 0, 0 },
116 { "help", 0, 0, HELP_OPTION },
117 { "memsize", 1, 0, 'm' },
118 { "network", 0, 0, 0 },
121 { "selinux", 0, 0, 0 },
123 { "suggest", 0, 0, 0 },
124 { "verbose", 0, 0, 'v' },
125 { "version", 0, 0, 'V' },
128 struct drv *drvs = NULL;
130 const char *format = NULL;
134 const char *append = NULL;
140 g = guestfs_create ();
142 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
146 argv[0] = bad_cast (program_name);
149 c = getopt_long (argc, argv, options, long_options, &option_index);
153 case 0: /* options which are long only */
154 if (STREQ (long_options[option_index].name, "selinux")) {
155 guestfs_set_selinux (g, 1);
156 } else if (STREQ (long_options[option_index].name, "append")) {
158 } else if (STREQ (long_options[option_index].name, "network")) {
160 } else if (STREQ (long_options[option_index].name, "format")) {
161 if (!optarg || STREQ (optarg, ""))
165 } else if (STREQ (long_options[option_index].name, "smp")) {
166 if (sscanf (optarg, "%u", &smp) != 1) {
167 fprintf (stderr, _("%s: could not parse --smp parameter '%s'\n"),
168 program_name, optarg);
172 fprintf (stderr, _("%s: --smp parameter '%s' should be >= 1\n"),
173 program_name, optarg);
176 } else if (STREQ (long_options[option_index].name, "suggest")) {
179 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
180 program_name, long_options[option_index].name, option_index);
198 usage (EXIT_SUCCESS);
201 if (sscanf (optarg, "%u", &memsize) != 1) {
202 fprintf (stderr, _("%s: could not parse memory size '%s'\n"),
203 program_name, optarg);
229 usage (EXIT_SUCCESS);
232 usage (EXIT_FAILURE);
236 /* Old-style syntax? There were no -a or -d options in the old
237 * virt-rescue which is how we detect this.
240 while (optind < argc) {
241 if (strchr (argv[optind], '/') ||
242 access (argv[optind], F_OK) == 0) { /* simulate -a option */
243 drv = malloc (sizeof (struct drv));
249 drv->a.filename = argv[optind];
250 drv->a.format = NULL;
253 } else { /* simulate -d option */
254 drv = malloc (sizeof (struct drv));
260 drv->d.guest = argv[optind];
271 do_suggestion (drvs);
275 /* These are really constants, but they have to be variables for the
276 * options parsing code. Assert here that they have known-good
279 assert (inspector == 0);
280 assert (keys_from_stdin == 0);
281 assert (echo_keys == 0);
284 /* Must be no extra arguments on the command line. */
286 usage (EXIT_FAILURE);
288 /* User must have specified some drives. */
290 usage (EXIT_FAILURE);
292 /* Setting "direct mode" is required for the rescue appliance. */
293 guestfs_set_direct (g, 1);
295 /* Set other features. */
297 guestfs_set_memsize (g, memsize);
299 guestfs_set_network (g, 1);
301 guestfs_set_smp (g, smp);
303 /* Kernel command line must include guestfs_rescue=1 (see
304 * appliance/init) as well as other options.
306 append_full = xasprintf ("guestfs_rescue=1%s%s",
308 append ? append : "");
309 guestfs_set_append (g, append_full);
313 add_drives (drvs, 'a');
315 /* Free up data structures, no longer needed after this point. */
318 /* Run the appliance. This won't return until the user quits the
321 guestfs_set_error_handler (g, NULL, NULL);
323 /* We expect launch to fail, so ignore the return value. */
324 ignore_value (guestfs_launch (g));
331 static void suggest_filesystems (void);
334 compare_keys_len (const void *p1, const void *p2)
336 const char *key1 = * (char * const *) p1;
337 const char *key2 = * (char * const *) p2;
338 return strlen (key1) - strlen (key2);
342 count_strings (char *const *argv)
346 for (i = 0; argv[i]; ++i)
351 /* virt-rescue --suggest flag does a kind of inspection on the
352 * drives and suggests mount commands that you should use.
355 do_suggestion (struct drv *drvs)
359 char *type, *distro, *product_name;
363 /* For inspection, force add_drives to add the drives read-only. */
367 add_drives (drvs, 'a');
369 /* Free up data structures, no longer needed after this point. */
372 printf (_("Inspecting the virtual machine or disk image ...\n\n"));
375 if (guestfs_launch (g) == -1)
378 /* Don't use inspect_mount, since for virt-rescue we should allow
379 * arbitrary disks and disks with more than one OS on them. Let's
380 * do this using the basic API instead.
382 roots = guestfs_inspect_os (g);
386 if (roots[0] == NULL) {
387 suggest_filesystems ();
391 printf (_("This disk contains one or more operating systems. You can use these mount\n"
392 "commands in virt-rescue (at the ><rescue> prompt) to mount the filesystems.\n\n"));
394 for (i = 0; roots[i] != NULL; ++i) {
395 type = guestfs_inspect_get_type (g, roots[i]);
396 distro = guestfs_inspect_get_distro (g, roots[i]);
397 product_name = guestfs_inspect_get_product_name (g, roots[i]);
398 major = guestfs_inspect_get_major_version (g, roots[i]);
399 minor = guestfs_inspect_get_minor_version (g, roots[i]);
401 printf (_("# %s is the root of a %s operating system\n"
402 "# type: %s, distro: %s, version: %d.%d\n"
404 roots[i], type ? : "unknown",
405 type ? : "unknown", distro ? : "unknown", major, minor,
406 product_name ? : "");
408 mps = guestfs_inspect_get_mountpoints (g, roots[i]);
412 /* Sort by key length, shortest key first, so that we end up
413 * mounting the filesystems in the correct order.
415 qsort (mps, count_strings (mps) / 2, 2 * sizeof (char *),
418 for (j = 0; mps[j] != NULL; j += 2) {
419 printf ("mount %s /sysroot%s\n", mps[j+1], mps[j]);
424 /* If it's Linux, print the bind-mounts. */
425 if (type && STREQ (type, "linux")) {
426 printf ("mount --bind /dev /sysroot/dev\n");
427 printf ("mount --bind /dev/pts /sysroot/dev/pts\n");
428 printf ("mount --bind /proc /sysroot/proc\n");
429 printf ("mount --bind /sys /sysroot/sys\n");
443 /* Inspection failed, so it doesn't contain any OS that we recognise.
444 * However there might still be filesystems so print some suggestions
448 suggest_filesystems (void)
453 fses = guestfs_list_filesystems (g);
457 if (fses[0] == NULL) {
458 printf (_("This disk contains no filesystems that we recognize.\n\n"
459 "However you can still use virt-rescue on the disk image, to try to mount\n"
460 "filesystems that are not recognized by libguestfs, or to create partitions,\n"
461 "logical volumes and filesystems on a blank disk.\n"));
465 printf (_("This disk contains one or more filesystems, but we don't recognize any\n"
466 "operating system. You can use these mount commands in virt-rescue (at the\n"
467 "><rescue> prompt) to mount these filesystems.\n\n"));
469 for (i = 0; fses[i] != NULL; i += 2) {
470 printf (_("# %s has type '%s'\n"), fses[i], fses[i+1]);
472 if (STRNEQ (fses[i+1], "swap") && STRNEQ (fses[i+1], "unknown"))
473 printf ("mount %s /sysroot\n", fses[i]);
484 /* The following was a nice idea, but in fact it doesn't work. This is
485 * because qemu has some (broken) pty emulation itself.
490 struct termios tsorig, tsnew;
493 fd_m = posix_openpt (O_RDWR);
495 perror ("posix_openpt");
508 fd_s = open (ptsname (fd_m), O_RDWR);
510 perror ("open ptsname");
524 r = tcgetattr (fd_s, &tsorig);
527 tcsetattr (fd_s, TCSANOW, &tsnew);
530 /* Close the master side of pty and set slave side as
531 * stdin/stdout/stderr.
538 if (dup (fd_s) == -1 || dup (fd_s) == -1 || dup (fd_s) == -1) {
546 perror ("warning: failed to setsid");
547 if (ioctl (0, TIOCSCTTY, 0) == -1)
548 perror ("warning: failed to TIOCSCTTY");
551 /* Run the appliance. This won't return until the user quits the
554 guestfs_set_error_handler (g, NULL, NULL);
555 r = guestfs_launch (g);
557 /* launch() expects guestfsd to start. However, virt-rescue doesn't
558 * run guestfsd, so this will always fail with ECHILD when the
559 * appliance exits unexpectedly.
561 if (errno != ECHILD) {
562 fprintf (stderr, "%s: %s\n", program_name, guestfs_last_error (g));
568 _exit (EXIT_SUCCESS);
571 /* Parent process continues ... */
573 /* Close slave side of pty. */
577 r = tcgetattr (fd_s, &tsorig);
580 tcsetattr (fd_s, TCSANOW, &tsnew);
582 /* Send input and output to master side of pty. */
583 r = multiplex (fd_m);
584 tcsetattr (fd_s, TCSANOW, &tsorig); /* Restore cooked mode. */
588 if (waitpid (pid, &r, 0) == -1) {
592 if (!WIFEXITED (r)) {
593 /* abnormal child exit */
594 fprintf (stderr, _("%s: unknown child exit status (%d)\n"),
599 exit (WEXITSTATUS (r)); /* normal exit, return child process's status */
602 /* Naive and simple multiplex function. */
606 int r, eof_stdin = 0;
608 char tobuf[BUFSIZ], frombuf[BUFSIZ]; /* to/from slave */
609 size_t tosize = 0, fromsize = 0;
612 long flags_0, flags_1, flags_fd_m;
614 flags_0 = fcntl (0, F_GETFL);
615 fcntl (0, F_SETFL, O_NONBLOCK | flags_0);
616 flags_1 = fcntl (0, F_GETFL);
617 fcntl (1, F_SETFL, O_NONBLOCK | flags_1);
618 flags_fd_m = fcntl (0, F_GETFL);
619 fcntl (fd_m, F_SETFL, O_NONBLOCK | flags_fd_m);
625 /* Still space in to-buffer? If so, we can read from the user. */
626 if (!eof_stdin && tosize < BUFSIZ)
628 /* Still space in from-buffer? If so, we can read from the slave. */
629 if (fromsize < BUFSIZ)
630 FD_SET (fd_m, &rfds);
631 /* Content in to-buffer? If so, we want to write to the slave. */
633 FD_SET (fd_m, &wfds);
634 /* Content in from-buffer? If so, we want to write to the user. */
638 r = select (fd_m+1, &rfds, &wfds, NULL, NULL);
640 if (errno == EAGAIN || errno == EINTR)
646 /* Input from user: Put it in the to-buffer. */
647 if (FD_ISSET (0, &rfds)) {
648 count = BUFSIZ - tosize;
649 n = read (0, &tobuf[tosize], count);
654 if (n == 0) { /* stdin was closed */
656 /* This is what telnetd does ... */
657 tobuf[tosize] = '\004';
663 /* Input from slave: Put it in the from-buffer. */
664 if (FD_ISSET (fd_m, &rfds)) {
665 count = BUFSIZ - fromsize;
666 n = read (fd_m, &frombuf[fromsize], count);
668 if (errno != EIO) /* EIO if slave process dies */
672 if (n == 0) /* slave closed the connection */
677 /* Can write to user. */
678 if (FD_ISSET (1, &wfds)) {
679 n = write (1, frombuf, fromsize);
684 memmove (frombuf, &frombuf[n], BUFSIZ - n);
688 /* Can write to slave. */
689 if (FD_ISSET (fd_m, &wfds)) {
690 n = write (fd_m, tobuf, tosize);
695 memmove (tobuf, &tobuf[n], BUFSIZ - n);
700 /* We end up here when slave has closed the connection. */
703 /* Restore blocking behaviour. */
704 fcntl (1, F_SETFL, flags_1);
706 /* Last chance to write out any remaining data in the buffers, but
707 * don't bother about errors.
709 ignore_value (write (1, frombuf, fromsize));