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