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