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