rescue: Rewrite virt-rescue in C.
[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   char *p, *file = NULL;
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
244   /* Must be no extra arguments on the command line. */
245   if (optind != argc)
246     usage (EXIT_FAILURE);
247
248   /* User must have specified some drives. */
249   if (drvs == NULL)
250     usage (EXIT_FAILURE);
251
252   /* Setting "direct mode" is required for the rescue appliance. */
253   guestfs_set_direct (g, 1);
254
255   /* Set other features. */
256   if (memsize > 0)
257     guestfs_set_memsize (g, memsize);
258   if (network)
259     guestfs_set_network (g, 1);
260
261   /* Kernel command line must include guestfs_rescue=1 (see
262    * appliance/init) as well as other options.
263    */
264   append_full = xasprintf ("guestfs_rescue=1%s%s",
265                            append ? " " : "",
266                            append ? append : "");
267   guestfs_set_append (g, append_full);
268   free (append_full);
269
270   /* Add drives. */
271   add_drives (drvs, 'a');
272
273   /* Free up data structures, no longer needed after this point. */
274   free_drives (drvs);
275
276   /* Run the appliance.  This won't return until the user quits the
277    * appliance.
278    */
279   guestfs_set_error_handler (g, NULL, NULL);
280   guestfs_launch (g);
281
282   /* launch() expects guestfsd to start. However, virt-rescue doesn't
283    * run guestfsd, so this will always fail with ECHILD when the
284    * appliance exits unexpectedly.
285    */
286   if (errno != ECHILD) {
287     fprintf (stderr, "%s: %s\n", program_name, guestfs_last_error (g));
288     guestfs_close (g);
289     exit (EXIT_FAILURE);
290   }
291
292   guestfs_close (g);
293
294   exit (EXIT_SUCCESS);
295 }
296
297 /* The following was a nice idea, but in fact it doesn't work.  This is
298  * because qemu has some (broken) pty emulation itself.
299  */
300 #if 0
301   int fd_m, fd_s, r;
302   pid_t pid;
303   struct termios tsorig, tsnew;
304
305   /* Set up pty. */
306   fd_m = posix_openpt (O_RDWR);
307   if (fd_m == -1) {
308     perror ("posix_openpt");
309     exit (EXIT_FAILURE);
310   }
311   r = grantpt (fd_m);
312   if (r == -1) {
313     perror ("grantpt");
314     exit (EXIT_FAILURE);
315   }
316   r = unlockpt (fd_m);
317   if (r == -1) {
318     perror ("unlockpt");
319     exit (EXIT_FAILURE);
320   }
321   fd_s = open (ptsname (fd_m), O_RDWR);
322   if (fd_s == -1) {
323     perror ("open ptsname");
324     exit (EXIT_FAILURE);
325   }
326
327   pid = fork ();
328   if (pid == -1) {
329     perror ("fork");
330     exit (EXIT_FAILURE);
331   }
332   if (pid == 0) {
333     /* Child process. */
334
335 #if 1
336     /* Set raw mode. */
337     r = tcgetattr (fd_s, &tsorig);
338     tsnew = tsorig;
339     cfmakeraw (&tsnew);
340     tcsetattr (fd_s, TCSANOW, &tsnew);
341 #endif
342
343     /* Close the master side of pty and set slave side as
344      * stdin/stdout/stderr.
345      */
346     close (fd_m);
347
348     close (0);
349     close (1);
350     close (2);
351     if (dup (fd_s) == -1 || dup (fd_s) == -1 || dup (fd_s) == -1) {
352       perror ("dup");
353       exit (EXIT_FAILURE);
354     }
355     close (fd_s);
356
357 #if 1
358     if (setsid () == -1)
359       perror ("warning: failed to setsid");
360     if (ioctl (0, TIOCSCTTY, 0) == -1)
361       perror ("warning: failed to TIOCSCTTY");
362 #endif
363
364     /* Run the appliance.  This won't return until the user quits the
365      * appliance.
366      */
367     guestfs_set_error_handler (g, NULL, NULL);
368     r = guestfs_launch (g);
369
370     /* launch() expects guestfsd to start. However, virt-rescue doesn't
371      * run guestfsd, so this will always fail with ECHILD when the
372      * appliance exits unexpectedly.
373      */
374     if (errno != ECHILD) {
375       fprintf (stderr, "%s: %s\n", program_name, guestfs_last_error (g));
376       guestfs_close (g);
377       exit (EXIT_FAILURE);
378     }
379
380     guestfs_close (g);
381     _exit (EXIT_SUCCESS);
382   }
383
384   /* Parent process continues ... */
385
386   /* Close slave side of pty. */
387   close (fd_s);
388
389   /* Set raw mode. */
390   r = tcgetattr (fd_s, &tsorig);
391   tsnew = tsorig;
392   cfmakeraw (&tsnew);
393   tcsetattr (fd_s, TCSANOW, &tsnew);
394
395   /* Send input and output to master side of pty. */
396   r = multiplex (fd_m);
397   tcsetattr (fd_s, TCSANOW, &tsorig); /* Restore cooked mode. */
398   if (r == -1)
399     exit (EXIT_FAILURE);
400
401   if (waitpid (pid, &r, 0) == -1) {
402     perror ("waitpid");
403     exit (EXIT_FAILURE);
404   }
405   if (!WIFEXITED (r)) {
406     /* abnormal child exit */
407     fprintf (stderr, _("%s: unknown child exit status (%d)\n"),
408              program_name, r);
409     exit (EXIT_FAILURE);
410   }
411   else
412     exit (WEXITSTATUS (r)); /* normal exit, return child process's status */
413 }
414
415 /* Naive and simple multiplex function. */
416 static int
417 multiplex (int fd_m)
418 {
419   int r, eof_stdin = 0;
420   fd_set rfds, wfds;
421   char tobuf[BUFSIZ], frombuf[BUFSIZ]; /* to/from slave */
422   size_t tosize = 0, fromsize = 0;
423   ssize_t n;
424   size_t count;
425   long flags_0, flags_1, flags_fd_m;
426
427   flags_0 = fcntl (0, F_GETFL);
428   fcntl (0, F_SETFL, O_NONBLOCK | flags_0);
429   flags_1 = fcntl (0, F_GETFL);
430   fcntl (1, F_SETFL, O_NONBLOCK | flags_1);
431   flags_fd_m = fcntl (0, F_GETFL);
432   fcntl (fd_m, F_SETFL, O_NONBLOCK | flags_fd_m);
433
434   for (;;) {
435     FD_ZERO (&rfds);
436     FD_ZERO (&wfds);
437
438     /* Still space in to-buffer?  If so, we can read from the user. */
439     if (!eof_stdin && tosize < BUFSIZ)
440       FD_SET (0, &rfds);
441     /* Still space in from-buffer?  If so, we can read from the slave. */
442     if (fromsize < BUFSIZ)
443       FD_SET (fd_m, &rfds);
444     /* Content in to-buffer?  If so, we want to write to the slave. */
445     if (tosize > 0)
446       FD_SET (fd_m, &wfds);
447     /* Content in from-buffer?  If so, we want to write to the user. */
448     if (fromsize > 0)
449       FD_SET (1, &wfds);
450
451     r = select (fd_m+1, &rfds, &wfds, NULL, NULL);
452     if (r == -1) {
453       if (errno == EAGAIN || errno == EINTR)
454         continue;
455       perror ("select");
456       return -1;
457     }
458
459     /* Input from user: Put it in the to-buffer. */
460     if (FD_ISSET (0, &rfds)) {
461       count = BUFSIZ - tosize;
462       n = read (0, &tobuf[tosize], count);
463       if (n == -1) {
464         perror ("read");
465         return -1;
466       }
467       if (n == 0) { /* stdin was closed */
468         eof_stdin = 1;
469         /* This is what telnetd does ... */
470         tobuf[tosize] = '\004';
471         tosize += 1;
472       } else
473         tosize += n;
474     }
475
476     /* Input from slave: Put it in the from-buffer. */
477     if (FD_ISSET (fd_m, &rfds)) {
478       count = BUFSIZ - fromsize;
479       n = read (fd_m, &frombuf[fromsize], count);
480       if (n == -1) {
481         if (errno != EIO) /* EIO if slave process dies */
482           perror ("read");
483         break;
484       }
485       if (n == 0) /* slave closed the connection */
486         break;
487       fromsize += n;
488     }
489
490     /* Can write to user. */
491     if (FD_ISSET (1, &wfds)) {
492       n = write (1, frombuf, fromsize);
493       if (n == -1) {
494         perror ("write");
495         return -1;
496       }
497       memmove (frombuf, &frombuf[n], BUFSIZ - n);
498       fromsize -= n;
499     }
500
501     /* Can write to slave. */
502     if (FD_ISSET (fd_m, &wfds)) {
503       n = write (fd_m, tobuf, tosize);
504       if (n == -1) {
505         perror ("write");
506         return -1;
507       }
508       memmove (tobuf, &tobuf[n], BUFSIZ - n);
509       tosize -= n;
510     }
511   } /* for (;;) */
512
513   /* We end up here when slave has closed the connection. */
514   close (fd_m);
515
516   /* Restore blocking behaviour. */
517   fcntl (1, F_SETFL, flags_1);
518
519   /* Last chance to write out any remaining data in the buffers, but
520    * don't bother about errors.
521    */
522   ignore_value (write (1, frombuf, fromsize));
523
524   return 0;
525 }
526 #endif