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