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