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