Version 1.8.16.
[libguestfs.git] / rescue / virt-rescue.c
1 /* virt-rescue
2  * Copyright (C) 2010 Red Hat Inc.
3  *
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.
8  *
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.
13  *
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.
17  */
18
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <inttypes.h>
24 #include <unistd.h>
25 #include <getopt.h>
26 #include <errno.h>
27 #include <locale.h>
28 #include <assert.h>
29
30 #include "progname.h"
31 #include "xvasprintf.h"
32
33 #include "guestfs.h"
34 #include "options.h"
35
36 /* Currently open libguestfs handle. */
37 guestfs_h *g;
38
39 int read_only = 0;
40 int verbose = 0;
41 int keys_from_stdin = 0;
42 int echo_keys = 0;
43 const char *libvirt_uri = NULL;
44 int inspector = 0;
45
46 static inline char *
47 bad_cast (char const *s)
48 {
49   return (char *) s;
50 }
51
52 static void __attribute__((noreturn))
53 usage (int status)
54 {
55   if (status != EXIT_SUCCESS)
56     fprintf (stderr, _("Try `%s --help' for more information.\n"),
57              program_name);
58   else {
59     fprintf (stdout,
60            _("%s: Run a rescue shell on a virtual machine\n"
61              "Copyright (C) 2009-2010 Red Hat Inc.\n"
62              "Usage:\n"
63              "  %s [--options] -d domname\n"
64              "  %s [--options] -a disk.img [-a disk.img ...]\n"
65              "Options:\n"
66              "  -a|--add image       Add image\n"
67              "  --append kernelopts  Append kernel options\n"
68              "  -c|--connect uri     Specify libvirt URI for -d option\n"
69              "  -d|--domain guest    Add disks from libvirt guest\n"
70              "  --format[=raw|..]    Force disk format for -a option\n"
71              "  --help               Display brief help\n"
72              "  -m|--memsize MB      Set memory size in megabytes\n"
73              "  --network            Enable network\n"
74              "  -r|--ro              Access read-only\n"
75              "  --selinux            Enable SELinux\n"
76              "  -v|--verbose         Verbose messages\n"
77              "  -V|--version         Display version and exit\n"
78              "  -w|--rw              Mount read-write\n"
79              "  -x                   Trace libguestfs API calls\n"
80              "For more information, see the manpage %s(1).\n"),
81              program_name, program_name, program_name,
82              program_name);
83   }
84   exit (status);
85 }
86
87 int
88 main (int argc, char *argv[])
89 {
90   /* Set global program name that is not polluted with libtool artifacts.  */
91   set_program_name (argv[0]);
92
93   setlocale (LC_ALL, "");
94   bindtextdomain (PACKAGE, LOCALEBASEDIR);
95   textdomain (PACKAGE);
96
97   enum { HELP_OPTION = CHAR_MAX + 1 };
98
99   static const char *options = "a:c:d:m:rvVx";
100   static const struct option long_options[] = {
101     { "add", 1, 0, 'a' },
102     { "append", 1, 0, 0 },
103     { "connect", 1, 0, 'c' },
104     { "domain", 1, 0, 'd' },
105     { "format", 2, 0, 0 },
106     { "help", 0, 0, HELP_OPTION },
107     { "memsize", 1, 0, 'm' },
108     { "network", 0, 0, 0 },
109     { "ro", 0, 0, 'r' },
110     { "rw", 0, 0, 'w' },
111     { "selinux", 0, 0, 0 },
112     { "verbose", 0, 0, 'v' },
113     { "version", 0, 0, 'V' },
114     { 0, 0, 0, 0 }
115   };
116   struct drv *drvs = NULL;
117   struct drv *drv;
118   const char *format = NULL;
119   int c;
120   int option_index;
121   int network = 0;
122   const char *append = NULL;
123   char *append_full;
124   int memsize = 0;
125
126   g = guestfs_create ();
127   if (g == NULL) {
128     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
129     exit (EXIT_FAILURE);
130   }
131
132   argv[0] = bad_cast (program_name);
133
134   for (;;) {
135     c = getopt_long (argc, argv, options, long_options, &option_index);
136     if (c == -1) break;
137
138     switch (c) {
139     case 0:                     /* options which are long only */
140       if (STREQ (long_options[option_index].name, "selinux")) {
141         guestfs_set_selinux (g, 1);
142       } else if (STREQ (long_options[option_index].name, "append")) {
143         append = optarg;
144       } else if (STREQ (long_options[option_index].name, "network")) {
145         network = 1;
146       } else if (STREQ (long_options[option_index].name, "format")) {
147         if (!optarg || STREQ (optarg, ""))
148           format = NULL;
149         else
150           format = optarg;
151       } else {
152         fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
153                  program_name, long_options[option_index].name, option_index);
154         exit (EXIT_FAILURE);
155       }
156       break;
157
158     case 'a':
159       OPTION_a;
160       break;
161
162     case 'c':
163       OPTION_c;
164       break;
165
166     case 'd':
167       OPTION_d;
168       break;
169
170     case 'h':
171       usage (EXIT_SUCCESS);
172
173     case 'm':
174       if (sscanf (optarg, "%u", &memsize) != 1) {
175         fprintf (stderr, _("%s: could not parse memory size '%s'\n"),
176                  program_name, optarg);
177         exit (EXIT_FAILURE);
178       }
179       break;
180
181     case 'r':
182       OPTION_r;
183       break;
184
185     case 'v':
186       OPTION_v;
187       break;
188
189     case 'V':
190       OPTION_V;
191       break;
192
193     case 'w':
194       OPTION_w;
195       break;
196
197     case 'x':
198       OPTION_x;
199       break;
200
201     case HELP_OPTION:
202       usage (EXIT_SUCCESS);
203
204     default:
205       usage (EXIT_FAILURE);
206     }
207   }
208
209   /* Old-style syntax?  There were no -a or -d options in the old
210    * virt-rescue which is how we detect this.
211    */
212   if (drvs == NULL) {
213     while (optind < argc) {
214       if (strchr (argv[optind], '/') ||
215           access (argv[optind], F_OK) == 0) { /* simulate -a option */
216         drv = malloc (sizeof (struct drv));
217         if (!drv) {
218           perror ("malloc");
219           exit (EXIT_FAILURE);
220         }
221         drv->type = drv_a;
222         drv->a.filename = argv[optind];
223         drv->a.format = NULL;
224         drv->next = drvs;
225         drvs = drv;
226       } else {                  /* simulate -d option */
227         drv = malloc (sizeof (struct drv));
228         if (!drv) {
229           perror ("malloc");
230           exit (EXIT_FAILURE);
231         }
232         drv->type = drv_d;
233         drv->d.guest = argv[optind];
234         drv->next = drvs;
235         drvs = drv;
236       }
237
238       optind++;
239     }
240   }
241
242   /* These are really constants, but they have to be variables for the
243    * options parsing code.  Assert here that they have known-good
244    * values.
245    */
246   assert (inspector == 0);
247   assert (keys_from_stdin == 0);
248   assert (echo_keys == 0);
249
250   /* Must be no extra arguments on the command line. */
251   if (optind != argc)
252     usage (EXIT_FAILURE);
253
254   /* User must have specified some drives. */
255   if (drvs == NULL)
256     usage (EXIT_FAILURE);
257
258   /* Setting "direct mode" is required for the rescue appliance. */
259   guestfs_set_direct (g, 1);
260
261   /* Set other features. */
262   if (memsize > 0)
263     guestfs_set_memsize (g, memsize);
264   if (network)
265     guestfs_set_network (g, 1);
266
267   /* Kernel command line must include guestfs_rescue=1 (see
268    * appliance/init) as well as other options.
269    */
270   append_full = xasprintf ("guestfs_rescue=1%s%s",
271                            append ? " " : "",
272                            append ? append : "");
273   guestfs_set_append (g, append_full);
274   free (append_full);
275
276   /* Add drives. */
277   add_drives (drvs, 'a');
278
279   /* Free up data structures, no longer needed after this point. */
280   free_drives (drvs);
281
282   /* Run the appliance.  This won't return until the user quits the
283    * appliance.
284    */
285   guestfs_set_error_handler (g, NULL, NULL);
286   guestfs_launch (g);
287
288   /* launch() expects guestfsd to start. However, virt-rescue doesn't
289    * run guestfsd, so this will always fail with ECHILD when the
290    * appliance exits unexpectedly.
291    */
292   if (errno != ECHILD) {
293     fprintf (stderr, "%s: %s\n", program_name, guestfs_last_error (g));
294     guestfs_close (g);
295     exit (EXIT_FAILURE);
296   }
297
298   guestfs_close (g);
299
300   exit (EXIT_SUCCESS);
301 }
302
303 /* The following was a nice idea, but in fact it doesn't work.  This is
304  * because qemu has some (broken) pty emulation itself.
305  */
306 #if 0
307   int fd_m, fd_s, r;
308   pid_t pid;
309   struct termios tsorig, tsnew;
310
311   /* Set up pty. */
312   fd_m = posix_openpt (O_RDWR);
313   if (fd_m == -1) {
314     perror ("posix_openpt");
315     exit (EXIT_FAILURE);
316   }
317   r = grantpt (fd_m);
318   if (r == -1) {
319     perror ("grantpt");
320     exit (EXIT_FAILURE);
321   }
322   r = unlockpt (fd_m);
323   if (r == -1) {
324     perror ("unlockpt");
325     exit (EXIT_FAILURE);
326   }
327   fd_s = open (ptsname (fd_m), O_RDWR);
328   if (fd_s == -1) {
329     perror ("open ptsname");
330     exit (EXIT_FAILURE);
331   }
332
333   pid = fork ();
334   if (pid == -1) {
335     perror ("fork");
336     exit (EXIT_FAILURE);
337   }
338   if (pid == 0) {
339     /* Child process. */
340
341 #if 1
342     /* Set raw mode. */
343     r = tcgetattr (fd_s, &tsorig);
344     tsnew = tsorig;
345     cfmakeraw (&tsnew);
346     tcsetattr (fd_s, TCSANOW, &tsnew);
347 #endif
348
349     /* Close the master side of pty and set slave side as
350      * stdin/stdout/stderr.
351      */
352     close (fd_m);
353
354     close (0);
355     close (1);
356     close (2);
357     if (dup (fd_s) == -1 || dup (fd_s) == -1 || dup (fd_s) == -1) {
358       perror ("dup");
359       exit (EXIT_FAILURE);
360     }
361     close (fd_s);
362
363 #if 1
364     if (setsid () == -1)
365       perror ("warning: failed to setsid");
366     if (ioctl (0, TIOCSCTTY, 0) == -1)
367       perror ("warning: failed to TIOCSCTTY");
368 #endif
369
370     /* Run the appliance.  This won't return until the user quits the
371      * appliance.
372      */
373     guestfs_set_error_handler (g, NULL, NULL);
374     r = guestfs_launch (g);
375
376     /* launch() expects guestfsd to start. However, virt-rescue doesn't
377      * run guestfsd, so this will always fail with ECHILD when the
378      * appliance exits unexpectedly.
379      */
380     if (errno != ECHILD) {
381       fprintf (stderr, "%s: %s\n", program_name, guestfs_last_error (g));
382       guestfs_close (g);
383       exit (EXIT_FAILURE);
384     }
385
386     guestfs_close (g);
387     _exit (EXIT_SUCCESS);
388   }
389
390   /* Parent process continues ... */
391
392   /* Close slave side of pty. */
393   close (fd_s);
394
395   /* Set raw mode. */
396   r = tcgetattr (fd_s, &tsorig);
397   tsnew = tsorig;
398   cfmakeraw (&tsnew);
399   tcsetattr (fd_s, TCSANOW, &tsnew);
400
401   /* Send input and output to master side of pty. */
402   r = multiplex (fd_m);
403   tcsetattr (fd_s, TCSANOW, &tsorig); /* Restore cooked mode. */
404   if (r == -1)
405     exit (EXIT_FAILURE);
406
407   if (waitpid (pid, &r, 0) == -1) {
408     perror ("waitpid");
409     exit (EXIT_FAILURE);
410   }
411   if (!WIFEXITED (r)) {
412     /* abnormal child exit */
413     fprintf (stderr, _("%s: unknown child exit status (%d)\n"),
414              program_name, r);
415     exit (EXIT_FAILURE);
416   }
417   else
418     exit (WEXITSTATUS (r)); /* normal exit, return child process's status */
419 }
420
421 /* Naive and simple multiplex function. */
422 static int
423 multiplex (int fd_m)
424 {
425   int r, eof_stdin = 0;
426   fd_set rfds, wfds;
427   char tobuf[BUFSIZ], frombuf[BUFSIZ]; /* to/from slave */
428   size_t tosize = 0, fromsize = 0;
429   ssize_t n;
430   size_t count;
431   long flags_0, flags_1, flags_fd_m;
432
433   flags_0 = fcntl (0, F_GETFL);
434   fcntl (0, F_SETFL, O_NONBLOCK | flags_0);
435   flags_1 = fcntl (0, F_GETFL);
436   fcntl (1, F_SETFL, O_NONBLOCK | flags_1);
437   flags_fd_m = fcntl (0, F_GETFL);
438   fcntl (fd_m, F_SETFL, O_NONBLOCK | flags_fd_m);
439
440   for (;;) {
441     FD_ZERO (&rfds);
442     FD_ZERO (&wfds);
443
444     /* Still space in to-buffer?  If so, we can read from the user. */
445     if (!eof_stdin && tosize < BUFSIZ)
446       FD_SET (0, &rfds);
447     /* Still space in from-buffer?  If so, we can read from the slave. */
448     if (fromsize < BUFSIZ)
449       FD_SET (fd_m, &rfds);
450     /* Content in to-buffer?  If so, we want to write to the slave. */
451     if (tosize > 0)
452       FD_SET (fd_m, &wfds);
453     /* Content in from-buffer?  If so, we want to write to the user. */
454     if (fromsize > 0)
455       FD_SET (1, &wfds);
456
457     r = select (fd_m+1, &rfds, &wfds, NULL, NULL);
458     if (r == -1) {
459       if (errno == EAGAIN || errno == EINTR)
460         continue;
461       perror ("select");
462       return -1;
463     }
464
465     /* Input from user: Put it in the to-buffer. */
466     if (FD_ISSET (0, &rfds)) {
467       count = BUFSIZ - tosize;
468       n = read (0, &tobuf[tosize], count);
469       if (n == -1) {
470         perror ("read");
471         return -1;
472       }
473       if (n == 0) { /* stdin was closed */
474         eof_stdin = 1;
475         /* This is what telnetd does ... */
476         tobuf[tosize] = '\004';
477         tosize += 1;
478       } else
479         tosize += n;
480     }
481
482     /* Input from slave: Put it in the from-buffer. */
483     if (FD_ISSET (fd_m, &rfds)) {
484       count = BUFSIZ - fromsize;
485       n = read (fd_m, &frombuf[fromsize], count);
486       if (n == -1) {
487         if (errno != EIO) /* EIO if slave process dies */
488           perror ("read");
489         break;
490       }
491       if (n == 0) /* slave closed the connection */
492         break;
493       fromsize += n;
494     }
495
496     /* Can write to user. */
497     if (FD_ISSET (1, &wfds)) {
498       n = write (1, frombuf, fromsize);
499       if (n == -1) {
500         perror ("write");
501         return -1;
502       }
503       memmove (frombuf, &frombuf[n], BUFSIZ - n);
504       fromsize -= n;
505     }
506
507     /* Can write to slave. */
508     if (FD_ISSET (fd_m, &wfds)) {
509       n = write (fd_m, tobuf, tosize);
510       if (n == -1) {
511         perror ("write");
512         return -1;
513       }
514       memmove (tobuf, &tobuf[n], BUFSIZ - n);
515       tosize -= n;
516     }
517   } /* for (;;) */
518
519   /* We end up here when slave has closed the connection. */
520   close (fd_m);
521
522   /* Restore blocking behaviour. */
523   fcntl (1, F_SETFL, flags_1);
524
525   /* Last chance to write out any remaining data in the buffers, but
526    * don't bother about errors.
527    */
528   ignore_value (write (1, frombuf, fromsize));
529
530   return 0;
531 }
532 #endif