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