fish: Add guestfish --live, guestmount --live options.
[libguestfs.git] / fish / fish.c
1 /* guestfish - the filesystem interactive shell
2  * Copyright (C) 2009-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 <inttypes.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <getopt.h>
28 #include <signal.h>
29 #include <sys/types.h>
30 #include <sys/wait.h>
31 #include <locale.h>
32 #include <langinfo.h>
33
34 #ifdef HAVE_LIBREADLINE
35 #include <readline/readline.h>
36 #include <readline/history.h>
37 #endif
38
39 #include <guestfs.h>
40
41 #include "fish.h"
42 #include "options.h"
43
44 #include "c-ctype.h"
45 #include "closeout.h"
46 #include "progname.h"
47
48 /* Return from parse_command_line.  See description below. */
49 struct parsed_command {
50   int status;
51   char *pipe;
52   char *cmd;
53   char *argv[64];
54 };
55
56 static void set_up_terminal (void);
57 static void prepare_drives (struct drv *drv);
58 static int launch (void);
59 static void interactive (void);
60 static void shell_script (void);
61 static void script (int prompt);
62 static void cmdline (char *argv[], int optind, int argc);
63 static struct parsed_command parse_command_line (char *buf, int *exit_on_error_rtn);
64 static int execute_and_inline (const char *cmd, int exit_on_error);
65 static void initialize_readline (void);
66 static void cleanup_readline (void);
67 #ifdef HAVE_LIBREADLINE
68 static void add_history_line (const char *);
69 #endif
70
71 static int override_progress_bars = -1;
72
73 /* Currently open libguestfs handle. */
74 guestfs_h *g;
75
76 int read_only = 0;
77 int live = 0;
78 int quit = 0;
79 int verbose = 0;
80 int remote_control_listen = 0;
81 int remote_control_csh = 0;
82 int remote_control = 0;
83 int command_num = 0;
84 int keys_from_stdin = 0;
85 int echo_keys = 0;
86 const char *libvirt_uri = NULL;
87 int inspector = 0;
88 int utf8_mode = 0;
89 int have_terminfo = 0;
90 int progress_bars = 0;
91
92 static void __attribute__((noreturn))
93 usage (int status)
94 {
95   if (status != EXIT_SUCCESS)
96     fprintf (stderr, _("Try `%s --help' for more information.\n"),
97              program_name);
98   else {
99     fprintf (stdout,
100            _("%s: guest filesystem shell\n"
101              "%s lets you edit virtual machine filesystems\n"
102              "Copyright (C) 2009-2010 Red Hat Inc.\n"
103              "Usage:\n"
104              "  %s [--options] cmd [: cmd : cmd ...]\n"
105              "  %s [--ro] -i -a disk-image\n"
106              "  %s [--ro] -i -d libvirt-domain\n"
107              "or for interactive use:\n"
108              "  %s\n"
109              "or from a shell script:\n"
110              "  %s <<EOF\n"
111              "  cmd\n"
112              "  ...\n"
113              "  EOF\n"
114              "Options:\n"
115              "  -h|--cmd-help        List available commands\n"
116              "  -h|--cmd-help cmd    Display detailed help on 'cmd'\n"
117              "  -a|--add image       Add image\n"
118              "  -c|--connect uri     Specify libvirt URI for -d option\n"
119              "  --csh                Make --listen csh-compatible\n"
120              "  -d|--domain guest    Add disks from libvirt guest\n"
121              "  -D|--no-dest-paths   Don't tab-complete paths from guest fs\n"
122              "  --echo-keys          Don't turn off echo for passphrases\n"
123              "  -f|--file file       Read commands from file\n"
124              "  --format[=raw|..]    Force disk format for -a option\n"
125              "  -i|--inspector       Automatically mount filesystems\n"
126              "  --keys-from-stdin    Read passphrases from stdin\n"
127              "  --listen             Listen for remote commands\n"
128              "  --live               Connect to a live virtual machine\n"
129              "  -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
130              "  -n|--no-sync         Don't autosync\n"
131              "  -N|--new type        Create prepared disk (test1.img, ...)\n"
132              "  --progress-bars      Enable progress bars even when not interactive\n"
133              "  --no-progress-bars   Disable progress bars\n"
134              "  --remote[=pid]       Send commands to remote %s\n"
135              "  -r|--ro              Mount read-only\n"
136              "  --selinux            Enable SELinux support\n"
137              "  -v|--verbose         Verbose messages\n"
138              "  -V|--version         Display version and exit\n"
139              "  -x                   Echo each command before executing it\n"
140              "For more information, see the manpage %s(1).\n"),
141              program_name, program_name, program_name,
142              program_name, program_name, program_name,
143              program_name, program_name, program_name);
144   }
145   exit (status);
146 }
147
148 int
149 main (int argc, char *argv[])
150 {
151   /* Set global program name that is not polluted with libtool artifacts.  */
152   set_program_name (argv[0]);
153
154   atexit (close_stdout);
155
156   setlocale (LC_ALL, "");
157   bindtextdomain (PACKAGE, LOCALEBASEDIR);
158   textdomain (PACKAGE);
159
160   set_up_terminal ();
161
162   enum { HELP_OPTION = CHAR_MAX + 1 };
163
164   static const char *options = "a:c:d:Df:h::im:nN:rv?Vwx";
165   static const struct option long_options[] = {
166     { "add", 1, 0, 'a' },
167     { "cmd-help", 2, 0, 'h' },
168     { "connect", 1, 0, 'c' },
169     { "csh", 0, 0, 0 },
170     { "domain", 1, 0, 'd' },
171     { "echo-keys", 0, 0, 0 },
172     { "file", 1, 0, 'f' },
173     { "format", 2, 0, 0 },
174     { "help", 0, 0, HELP_OPTION },
175     { "inspector", 0, 0, 'i' },
176     { "keys-from-stdin", 0, 0, 0 },
177     { "listen", 0, 0, 0 },
178     { "live", 0, 0, 0 },
179     { "mount", 1, 0, 'm' },
180     { "new", 1, 0, 'N' },
181     { "no-dest-paths", 0, 0, 'D' },
182     { "no-sync", 0, 0, 'n' },
183     { "progress-bars", 0, 0, 0 },
184     { "no-progress-bars", 0, 0, 0 },
185     { "remote", 2, 0, 0 },
186     { "ro", 0, 0, 'r' },
187     { "rw", 0, 0, 'w' },
188     { "selinux", 0, 0, 0 },
189     { "verbose", 0, 0, 'v' },
190     { "version", 0, 0, 'V' },
191     { 0, 0, 0, 0 }
192   };
193   struct drv *drvs = NULL;
194   struct drv *drv;
195   struct mp *mps = NULL;
196   struct mp *mp;
197   char *p, *file = NULL;
198   const char *format = NULL;
199   int c;
200   int option_index;
201   struct sigaction sa;
202   int next_prepared_drive = 1;
203
204   initialize_readline ();
205
206   memset (&sa, 0, sizeof sa);
207   sa.sa_handler = SIG_IGN;
208   sa.sa_flags = SA_RESTART;
209   sigaction (SIGPIPE, &sa, NULL);
210
211   /* guestfs_create is meant to be a lightweight operation, so
212    * it's OK to do it early here.
213    */
214   g = guestfs_create ();
215   if (g == NULL) {
216     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
217     exit (EXIT_FAILURE);
218   }
219
220   /* If developing, add ./appliance to the path.  Note that libtools
221    * interferes with this because uninstalled guestfish is a shell
222    * script that runs the real program with an absolute path.  Detect
223    * that too.
224    *
225    * BUT if LIBGUESTFS_PATH environment variable is already set by
226    * the user, then don't override it.
227    */
228   if (getenv ("LIBGUESTFS_PATH") == NULL &&
229       argv[0] &&
230       (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
231     guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
232
233   /* CAUTION: we are careful to modify argv[0] here, only after
234    * using it just above.
235    *
236    * getopt_long uses argv[0], so give it the sanitized name.  Save a copy
237    * of the original, in case it's needed below.
238    */
239   //char *real_argv0 = argv[0];
240   argv[0] = bad_cast (program_name);
241
242   for (;;) {
243     c = getopt_long (argc, argv, options, long_options, &option_index);
244     if (c == -1) break;
245
246     switch (c) {
247     case 0:                     /* options which are long only */
248       if (STREQ (long_options[option_index].name, "listen"))
249         remote_control_listen = 1;
250       else if (STREQ (long_options[option_index].name, "remote")) {
251         if (optarg) {
252           if (sscanf (optarg, "%d", &remote_control) != 1) {
253             fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
254                      program_name, optarg);
255             exit (EXIT_FAILURE);
256           }
257         } else {
258           p = getenv ("GUESTFISH_PID");
259           if (!p || sscanf (p, "%d", &remote_control) != 1) {
260             fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
261                                " to the PID of the remote process\n"),
262                      program_name);
263             exit (EXIT_FAILURE);
264           }
265         }
266       } else if (STREQ (long_options[option_index].name, "selinux")) {
267         guestfs_set_selinux (g, 1);
268       } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
269         keys_from_stdin = 1;
270       } else if (STREQ (long_options[option_index].name, "progress-bars")) {
271         override_progress_bars = 1;
272       } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
273         override_progress_bars = 0;
274       } else if (STREQ (long_options[option_index].name, "echo-keys")) {
275         echo_keys = 1;
276       } else if (STREQ (long_options[option_index].name, "format")) {
277         if (!optarg || STREQ (optarg, ""))
278           format = NULL;
279         else
280           format = optarg;
281       } else if (STREQ (long_options[option_index].name, "csh")) {
282         remote_control_csh = 1;
283       } else if (STREQ (long_options[option_index].name, "live")) {
284         live = 1;
285       } else {
286         fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
287                  program_name, long_options[option_index].name, option_index);
288         exit (EXIT_FAILURE);
289       }
290       break;
291
292     case 'a':
293       OPTION_a;
294       break;
295
296     case 'c':
297       OPTION_c;
298       break;
299
300     case 'd':
301       OPTION_d;
302       break;
303
304     case 'D':
305       complete_dest_paths = 0;
306       break;
307
308     case 'f':
309       if (file) {
310         fprintf (stderr, _("%s: only one -f parameter can be given\n"),
311                  program_name);
312         exit (EXIT_FAILURE);
313       }
314       file = optarg;
315       break;
316
317     case 'h': {
318       int r = 0;
319
320       if (optarg)
321         r = display_command (optarg);
322       else if (argv[optind] && argv[optind][0] != '-')
323         r = display_command (argv[optind++]);
324       else
325         list_commands ();
326
327       exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
328     }
329
330     case 'i':
331       OPTION_i;
332       break;
333
334     case 'm':
335       OPTION_m;
336       break;
337
338     case 'n':
339       OPTION_n;
340       break;
341
342     case 'N':
343       if (STRCASEEQ (optarg, "list") ||
344           STRCASEEQ (optarg, "help") ||
345           STRCASEEQ (optarg, "h") ||
346           STRCASEEQ (optarg, "?")) {
347         list_prepared_drives ();
348         exit (EXIT_SUCCESS);
349       }
350       drv = malloc (sizeof (struct drv));
351       if (!drv) {
352         perror ("malloc");
353         exit (EXIT_FAILURE);
354       }
355       drv->type = drv_N;
356       drv->device = NULL;
357       drv->nr_drives = -1;
358       if (asprintf (&drv->N.filename, "test%d.img",
359                     next_prepared_drive++) == -1) {
360         perror ("asprintf");
361         exit (EXIT_FAILURE);
362       }
363       drv->N.data = create_prepared_file (optarg, drv->N.filename);
364       drv->N.data_free = free_prep_data;
365       drv->next = drvs;
366       drvs = drv;
367       break;
368
369     case 'r':
370       OPTION_r;
371       break;
372
373     case 'v':
374       OPTION_v;
375       break;
376
377     case 'V':
378       OPTION_V;
379       break;
380
381     case 'w':
382       OPTION_w;
383       break;
384
385     case 'x':
386       OPTION_x;
387       break;
388
389     case HELP_OPTION:
390       usage (EXIT_SUCCESS);
391
392     default:
393       usage (EXIT_FAILURE);
394     }
395   }
396
397   /* Old-style -i syntax?  Since -a/-d/-N and -i was disallowed
398    * previously, if we have -i without any drives but with something
399    * on the command line, it must be old-style syntax.
400    */
401   if (inspector && drvs == NULL && optind < argc) {
402     while (optind < argc) {
403       if (strchr (argv[optind], '/') ||
404           access (argv[optind], F_OK) == 0) { /* simulate -a option */
405         drv = malloc (sizeof (struct drv));
406         if (!drv) {
407           perror ("malloc");
408           exit (EXIT_FAILURE);
409         }
410         drv->type = drv_a;
411         drv->a.filename = argv[optind];
412         drv->a.format = NULL;
413         drv->next = drvs;
414         drvs = drv;
415       } else {                  /* simulate -d option */
416         drv = malloc (sizeof (struct drv));
417         if (!drv) {
418           perror ("malloc");
419           exit (EXIT_FAILURE);
420         }
421         drv->type = drv_d;
422         drv->d.guest = argv[optind];
423         drv->next = drvs;
424         drvs = drv;
425       }
426
427       optind++;
428     }
429   }
430
431   /* If we've got drives to add, add them now. */
432   add_drives (drvs, 'a');
433
434   /* If we've got mountpoints or prepared drives or -i option, we must
435    * launch the guest and mount them.
436    */
437   if (next_prepared_drive > 1 || mps != NULL || inspector) {
438     /* RHBZ#612178: If --listen flag is given, then we will fork into
439      * the background in rc_listen().  However you can't do this while
440      * holding a libguestfs handle open because the recovery process
441      * will think the main program has died and kill qemu.  Therefore
442      * don't use the recovery process for this case.  (A better
443      * solution would be to call launch () etc after the fork, but
444      * that greatly complicates the code here).
445      */
446     if (remote_control_listen)
447       guestfs_set_recovery_proc (g, 0);
448
449     if (launch () == -1) exit (EXIT_FAILURE);
450
451     if (inspector)
452       inspect_mount ();
453
454     prepare_drives (drvs);
455     mount_mps (mps);
456   }
457
458   /* Free up data structures, no longer needed after this point. */
459   free_drives (drvs);
460   free_mps (mps);
461
462   /* Remote control? */
463   if (remote_control_listen && remote_control) {
464     fprintf (stderr,
465              _("%s: cannot use --listen and --remote options at the same time\n"),
466              program_name);
467     exit (EXIT_FAILURE);
468   }
469
470   if (remote_control_listen) {
471     if (optind < argc) {
472       fprintf (stderr,
473                _("%s: extra parameters on the command line with --listen flag\n"),
474                program_name);
475       exit (EXIT_FAILURE);
476     }
477     if (file) {
478       fprintf (stderr,
479                _("%s: cannot use --listen and --file options at the same time\n"),
480                program_name);
481       exit (EXIT_FAILURE);
482     }
483     rc_listen ();
484   }
485
486   /* -f (file) parameter? */
487   if (file) {
488     close (0);
489     if (open (file, O_RDONLY) == -1) {
490       perror (file);
491       exit (EXIT_FAILURE);
492     }
493   }
494
495   /* Decide if we display progress bars. */
496   progress_bars =
497     override_progress_bars >= 0
498     ? override_progress_bars
499     : (optind >= argc && isatty (0));
500
501   if (progress_bars)
502     guestfs_set_progress_callback (g, progress_callback, NULL);
503
504   /* Interactive, shell script, or command(s) on the command line? */
505   if (optind >= argc) {
506     if (isatty (0))
507       interactive ();
508     else
509       shell_script ();
510   }
511   else
512     cmdline (argv, optind, argc);
513
514   cleanup_readline ();
515
516   exit (EXIT_SUCCESS);
517 }
518
519 /* The <term.h> header file which defines this has "issues". */
520 extern int tgetent (char *, const char *);
521
522 static void
523 set_up_terminal (void)
524 {
525   /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
526   utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
527
528   char *term = getenv ("TERM");
529   if (term == NULL) {
530     //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
531     return;
532   }
533
534   int r = tgetent (NULL, term);
535   if (r == -1) {
536     fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
537     return;
538   }
539   if (r == 0) {
540     fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
541              term);
542     return;
543   }
544
545   have_terminfo = 1;
546 }
547
548 static void
549 prepare_drives (struct drv *drv)
550 {
551   if (drv) {
552     prepare_drives (drv->next);
553     if (drv->type == drv_N)
554       prepare_drive (drv->N.filename, drv->N.data, drv->device);
555   }
556 }
557
558 static int
559 launch (void)
560 {
561   if (guestfs_is_config (g)) {
562     if (guestfs_launch (g) == -1)
563       return -1;
564   }
565   return 0;
566 }
567
568 static void
569 interactive (void)
570 {
571   script (1);
572 }
573
574 static void
575 shell_script (void)
576 {
577   script (0);
578 }
579
580 #define FISH "><fs> "
581
582 static char *line_read = NULL;
583
584 static char *
585 rl_gets (int prompt)
586 {
587 #ifdef HAVE_LIBREADLINE
588
589   if (prompt) {
590     if (line_read) {
591       free (line_read);
592       line_read = NULL;
593     }
594
595     line_read = readline (prompt ? FISH : "");
596
597     if (line_read && *line_read)
598       add_history_line (line_read);
599
600     return line_read;
601   }
602
603 #endif /* HAVE_LIBREADLINE */
604
605   static char buf[8192];
606   int len;
607
608   if (prompt) printf (FISH);
609   line_read = fgets (buf, sizeof buf, stdin);
610
611   if (line_read) {
612     len = strlen (line_read);
613     if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
614   }
615
616   return line_read;
617 }
618
619 static void
620 script (int prompt)
621 {
622   char *buf;
623   int global_exit_on_error = !prompt;
624   int exit_on_error;
625   struct parsed_command pcmd;
626
627   if (prompt) {
628     printf (_("\n"
629               "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
630               "editing virtual machine filesystems.\n"
631               "\n"
632               "Type: 'help' for help on commands\n"
633               "      'man' to read the manual\n"
634               "      'quit' to quit the shell\n"
635               "\n"));
636
637     if (inspector) {
638       print_inspect_prompt ();
639       printf ("\n");
640     }
641   }
642
643   while (!quit) {
644     exit_on_error = global_exit_on_error;
645
646     buf = rl_gets (prompt);
647     if (!buf) {
648       quit = 1;
649       break;
650     }
651
652     pcmd = parse_command_line (buf, &exit_on_error);
653     if (pcmd.status == -1 && exit_on_error)
654       exit (EXIT_FAILURE);
655     if (pcmd.status == 1) {
656       if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
657         if (exit_on_error) exit (EXIT_FAILURE);
658       }
659     }
660   }
661   if (prompt) printf ("\n");
662 }
663
664 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
665  * This destructively updates 'buf'.
666  *
667  * 'exit_on_error_rtn' is used to pass in the global exit_on_error
668  * setting and to return the local setting (eg. if the command begins
669  * with '-').
670  *
671  * Returns in parsed_command.status:
672  *   1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
673  *   0 = no guestfish command, but otherwise OK
674  *  -1 = an error
675  */
676 static struct parsed_command
677 parse_command_line (char *buf, int *exit_on_error_rtn)
678 {
679   struct parsed_command pcmd;
680   char *p, *pend;
681   int len;
682   int tilde_candidate;
683   int r;
684   const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
685
686   /* Note that pcmd.pipe must be set to NULL for correct usage.  Other
687    * fields do not need to be, but this silences a gcc warning.
688    */
689   memset (&pcmd, 0, sizeof pcmd);
690
691  again:
692   /* Skip any initial whitespace before the command. */
693   while (*buf && c_isspace (*buf))
694     buf++;
695
696   if (!*buf) {
697     pcmd.status = 0;
698     return pcmd;
699   }
700
701   /* If the next character is '#' then this is a comment. */
702   if (*buf == '#') {
703     pcmd.status = 0;
704     return pcmd;
705   }
706
707   /* If the next character is '!' then pass the whole lot to system(3). */
708   if (*buf == '!') {
709     r = system (buf+1);
710     if (r == -1 ||
711         (WIFSIGNALED (r) &&
712          (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
713         WEXITSTATUS (r) != 0)
714       pcmd.status = -1;
715     else
716       pcmd.status = 0;
717     return pcmd;
718   }
719
720   /* If the next two characters are "<!" then pass the command to
721    * popen(3), read the result and execute it as guestfish commands.
722    */
723   if (buf[0] == '<' && buf[1] == '!') {
724     int r = execute_and_inline (&buf[2], *exit_on_error_rtn);
725     if (r == -1)
726       pcmd.status = -1;
727     else
728       pcmd.status = 0;
729     return pcmd;
730   }
731
732   /* If the next character is '-' allow the command to fail without
733    * exiting on error (just for this one command though).
734    */
735   if (*buf == '-') {
736     *exit_on_error_rtn = 0;
737     buf++;
738     goto again;
739   }
740
741   /* Get the command (cannot be quoted). */
742   len = strcspn (buf, " \t");
743
744   if (len == 0) {
745     pcmd.status = 0;
746     return pcmd;
747   }
748
749   pcmd.cmd = buf;
750   unsigned int i = 0;
751   if (buf[len] == '\0') {
752     pcmd.argv[0] = NULL;
753     pcmd.status = 1;
754     return pcmd;
755   }
756
757   buf[len] = '\0';
758   p = &buf[len+1];
759   p += strspn (p, " \t");
760
761   /* Get the parameters. */
762   while (*p && i < argv_len) {
763     tilde_candidate = 0;
764
765     /* Parameters which start with quotes or pipes are treated
766      * specially.  Bare parameters are delimited by whitespace.
767      */
768     if (*p == '"') {
769       p++;
770       len = strcspn (p, "\"");
771       if (p[len] == '\0') {
772         fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
773         pcmd.status = -1;
774         return pcmd;
775       }
776       if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
777         fprintf (stderr,
778                  _("%s: command arguments not separated by whitespace\n"),
779                  program_name);
780         pcmd.status = -1;
781         return pcmd;
782       }
783       p[len] = '\0';
784       pend = p[len+1] ? &p[len+2] : &p[len+1];
785     } else if (*p == '\'') {
786       p++;
787       len = strcspn (p, "'");
788       if (p[len] == '\0') {
789         fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
790         pcmd.status = -1;
791         return pcmd;
792       }
793       if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
794         fprintf (stderr,
795                  _("%s: command arguments not separated by whitespace\n"),
796                  program_name);
797         pcmd.status = -1;
798         return pcmd;
799       }
800       p[len] = '\0';
801       pend = p[len+1] ? &p[len+2] : &p[len+1];
802     } else if (*p == '|') {
803       *p = '\0';
804       pcmd.pipe = p+1;
805       continue;
806     } else if (*p != ' ' && *p != '\t') {
807       /* If the first character is a ~ then note that this parameter
808        * is a candidate for ~username expansion.  NB this does not
809        * apply to quoted parameters.
810        */
811       tilde_candidate = *p == '~';
812       len = strcspn (p, " \t");
813       if (p[len]) {
814         p[len] = '\0';
815         pend = &p[len+1];
816       } else
817         pend = &p[len];
818     } else {
819       fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
820                program_name, p);
821       abort ();
822     }
823
824     if (!tilde_candidate)
825       pcmd.argv[i] = p;
826     else
827       pcmd.argv[i] = try_tilde_expansion (p);
828     i++;
829     p = pend;
830
831     if (*p)
832       p += strspn (p, " \t");
833   }
834
835   if (i == argv_len) {
836     fprintf (stderr, _("%s: too many arguments\n"), program_name);
837     pcmd.status = -1;
838     return pcmd;
839   }
840
841   pcmd.argv[i] = NULL;
842
843   pcmd.status = 1;
844   return pcmd;
845 }
846
847 /* Used to handle "<!" (execute command and inline result). */
848 static int
849 execute_and_inline (const char *cmd, int global_exit_on_error)
850 {
851   FILE *pp;
852   char *line = NULL;
853   size_t len = 0;
854   ssize_t n;
855   int exit_on_error;
856   struct parsed_command pcmd;
857
858   pp = popen (cmd, "r");
859   if (!pp) {
860     perror ("popen");
861     return -1;
862   }
863
864   while ((n = getline (&line, &len, pp)) != -1) {
865     exit_on_error = global_exit_on_error;
866
867     /* Chomp final line ending which parse_command_line would not expect. */
868     if (n > 0 && line[n-1] == '\n')
869       line[n-1] = '\0';
870
871     pcmd = parse_command_line (line, &exit_on_error);
872     if (pcmd.status == -1 && exit_on_error)
873       exit (EXIT_FAILURE);
874     if (pcmd.status == 1) {
875       if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
876         if (exit_on_error) exit (EXIT_FAILURE);
877       }
878     }
879   }
880
881   free (line);
882
883   if (pclose (pp) == -1) {
884     perror ("pclose");
885     return -1;
886   }
887
888   return 0;
889 }
890
891 static void
892 cmdline (char *argv[], int optind, int argc)
893 {
894   const char *cmd;
895   char **params;
896   int exit_on_error;
897
898   exit_on_error = 1;
899
900   if (optind >= argc) return;
901
902   cmd = argv[optind++];
903   if (STREQ (cmd, ":")) {
904     fprintf (stderr, _("%s: empty command on command line\n"), program_name);
905     exit (EXIT_FAILURE);
906   }
907
908   /* Allow -cmd on the command line to mean (temporarily) override
909    * the normal exit on error (RHBZ#578407).
910    */
911   if (cmd[0] == '-') {
912     exit_on_error = 0;
913     cmd++;
914   }
915
916   params = &argv[optind];
917
918   /* Search for end of command list or ":" ... */
919   while (optind < argc && STRNEQ (argv[optind], ":"))
920     optind++;
921
922   if (optind == argc) {
923     if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
924         exit (EXIT_FAILURE);
925   } else {
926     argv[optind] = NULL;
927     if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
928       exit (EXIT_FAILURE);
929     cmdline (argv, optind+1, argc);
930   }
931 }
932
933 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
934  * pass to the remote server (when issuing --remote commands).  It
935  * does not cause issue_command itself to exit on error.
936  */
937 int
938 issue_command (const char *cmd, char *argv[], const char *pipecmd,
939                int rc_exit_on_error_flag)
940 {
941   int argc;
942   int stdout_saved_fd = -1;
943   int pid = 0;
944   int r;
945
946   reset_progress_bar ();
947
948   /* This counts the commands issued, starting at 1. */
949   command_num++;
950
951   /* For | ... commands.  Annoyingly we can't use popen(3) here. */
952   if (pipecmd) {
953     int fd[2];
954
955     if (fflush (stdout) == EOF) {
956       perror ("failed to flush standard output");
957       return -1;
958     }
959     if (pipe (fd) < 0) {
960       perror ("pipe failed");
961       return -1;
962     }
963     pid = fork ();
964     if (pid == -1) {
965       perror ("fork");
966       return -1;
967     }
968
969     if (pid == 0) {             /* Child process. */
970       close (fd[1]);
971       if (dup2 (fd[0], 0) < 0) {
972         perror ("dup2 of stdin failed");
973         _exit (1);
974       }
975
976       r = system (pipecmd);
977       if (r == -1) {
978         perror (pipecmd);
979         _exit (1);
980       }
981       _exit (WEXITSTATUS (r));
982     }
983
984     if ((stdout_saved_fd = dup (1)) < 0) {
985       perror ("failed to dup stdout");
986       return -1;
987     }
988     close (fd[0]);
989     if (dup2 (fd[1], 1) < 0) {
990       perror ("failed to dup stdout");
991       close (stdout_saved_fd);
992       return -1;
993     }
994     close (fd[1]);
995   }
996
997   for (argc = 0; argv[argc] != NULL; ++argc)
998     ;
999
1000   /* If --remote was set, then send this command to a remote process. */
1001   if (remote_control)
1002     r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
1003
1004   /* Otherwise execute it locally. */
1005   else if (STRCASEEQ (cmd, "help")) {
1006     if (argc == 0) {
1007       display_help ();
1008       r = 0;
1009     } else
1010       r = display_command (argv[0]);
1011   }
1012   else if (STRCASEEQ (cmd, "quit") ||
1013            STRCASEEQ (cmd, "exit") ||
1014            STRCASEEQ (cmd, "q")) {
1015     quit = 1;
1016     r = 0;
1017   }
1018   else
1019     r = run_action (cmd, argc, argv);
1020
1021   /* Always flush stdout after every command, so that messages, results
1022    * etc appear immediately.
1023    */
1024   if (fflush (stdout) == EOF) {
1025     perror ("failed to flush standard output");
1026     return -1;
1027   }
1028
1029   if (pipecmd) {
1030     close (1);
1031     if (dup2 (stdout_saved_fd, 1) < 0) {
1032       perror ("failed to dup2 standard output");
1033       r = -1;
1034     }
1035     close (stdout_saved_fd);
1036     if (waitpid (pid, NULL, 0) < 0) {
1037       perror ("waiting for command to complete");
1038       r = -1;
1039     }
1040   }
1041
1042   return r;
1043 }
1044
1045 void
1046 list_builtin_commands (void)
1047 {
1048   /* help and quit should appear at the top */
1049   printf ("%-20s %s\n",
1050           "help", _("display a list of commands or help on a command"));
1051   printf ("%-20s %s\n",
1052           "quit", _("quit guestfish"));
1053
1054   /* actions are printed after this (see list_commands) */
1055 }
1056
1057 int
1058 display_builtin_command (const char *cmd)
1059 {
1060   /* help for actions is auto-generated, see display_command */
1061
1062   if (STRCASEEQ (cmd, "help")) {
1063     printf (_("help - display a list of commands or help on a command\n"
1064               "     help cmd\n"
1065               "     help\n"));
1066     return 0;
1067   }
1068   else if (STRCASEEQ (cmd, "quit") ||
1069            STRCASEEQ (cmd, "exit") ||
1070            STRCASEEQ (cmd, "q")) {
1071     printf (_("quit - quit guestfish\n"
1072               "     quit\n"));
1073     return 0;
1074   }
1075   else {
1076     fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1077              cmd);
1078     return -1;
1079   }
1080 }
1081
1082 /* This is printed when the user types in an unknown command for the
1083  * first command issued.  A common case is the user doing:
1084  *   guestfish disk.img
1085  * expecting guestfish to open 'disk.img' (in fact, this tried to
1086  * run a command 'disk.img').
1087  */
1088 void
1089 extended_help_message (void)
1090 {
1091   fprintf (stderr,
1092            _("Did you mean to open a disk image?  guestfish -a disk.img\n"
1093              "For a list of commands:             guestfish -h\n"
1094              "For complete documentation:         man guestfish\n"));
1095 }
1096
1097 void
1098 free_strings (char **argv)
1099 {
1100   int argc;
1101
1102   for (argc = 0; argv[argc] != NULL; ++argc)
1103     free (argv[argc]);
1104   free (argv);
1105 }
1106
1107 int
1108 count_strings (char *const *argv)
1109 {
1110   int c;
1111
1112   for (c = 0; argv[c]; ++c)
1113     ;
1114   return c;
1115 }
1116
1117 void
1118 print_strings (char *const *argv)
1119 {
1120   int argc;
1121
1122   for (argc = 0; argv[argc] != NULL; ++argc)
1123     printf ("%s\n", argv[argc]);
1124 }
1125
1126 void
1127 print_table (char *const *argv)
1128 {
1129   int i;
1130
1131   for (i = 0; argv[i] != NULL; i += 2)
1132     printf ("%s: %s\n", argv[i], argv[i+1]);
1133 }
1134
1135 int
1136 is_true (const char *str)
1137 {
1138   return
1139     STRCASENEQ (str, "0") &&
1140     STRCASENEQ (str, "f") &&
1141     STRCASENEQ (str, "false") &&
1142     STRCASENEQ (str, "n") &&
1143     STRCASENEQ (str, "no");
1144 }
1145
1146 /* Free strings from a non-NULL terminated char** */
1147 static void
1148 free_n_strings (char **str, size_t len)
1149 {
1150   size_t i;
1151
1152   for (i = 0; i < len; i++) {
1153     free (str[i]);
1154   }
1155   free (str);
1156 }
1157
1158 char **
1159 parse_string_list (const char *str)
1160 {
1161   char **argv = NULL;
1162   size_t argv_len = 0;
1163
1164   /* Current position pointer */
1165   const char *p = str;
1166
1167   /* Token might be simple:
1168    *  Token
1169    * or be quoted:
1170    *  'This is a single token'
1171    * or contain embedded single-quoted sections:
1172    *  This' is a sing'l'e to'ken
1173    *
1174    * The latter may seem over-complicated, but it's what a normal shell does.
1175    * Not doing it risks surprising somebody.
1176    *
1177    * This outer loop is over complete tokens.
1178    */
1179   while (*p) {
1180     char *tok = NULL;
1181     size_t tok_len = 0;
1182
1183     /* Skip leading whitespace */
1184     p += strspn (p, " \t");
1185
1186     char in_quote = 0;
1187
1188     /* This loop is over token 'fragments'. A token can be in multiple bits if
1189      * it contains single quotes. We also treat both sides of an escaped quote
1190      * as separate fragments because we can't just copy it: we have to remove
1191      * the \.
1192      */
1193     while (*p && (!c_isblank (*p) || in_quote)) {
1194       const char *end = p;
1195
1196       /* Check if the fragment starts with a quote */
1197       if ('\'' == *p) {
1198         /* Toggle in_quote */
1199         in_quote = !in_quote;
1200
1201         /* Skip the quote */
1202         p++; end++;
1203       }
1204
1205       /* If we're in a quote, look for an end quote */
1206       if (in_quote) {
1207         end += strcspn (end, "'");
1208       }
1209
1210       /* Otherwise, look for whitespace or a quote */
1211       else {
1212         end += strcspn (end, " \t'");
1213       }
1214
1215       /* Grow the token to accommodate the fragment */
1216       size_t tok_end = tok_len;
1217       tok_len += end - p;
1218       char *tok_new = realloc (tok, tok_len + 1);
1219       if (NULL == tok_new) {
1220         perror ("realloc");
1221         free_n_strings (argv, argv_len);
1222         free (tok);
1223         exit (EXIT_FAILURE);
1224       }
1225       tok = tok_new;
1226
1227       /* Check if we stopped on an escaped quote */
1228       if ('\'' == *end && end != p && *(end-1) == '\\') {
1229         /* Add everything before \' to the token */
1230         memcpy (&tok[tok_end], p, end - p - 1);
1231
1232         /* Add the quote */
1233         tok[tok_len-1] = '\'';
1234
1235         /* Already processed the quote */
1236         p = end + 1;
1237       }
1238
1239       else {
1240         /* Add the whole fragment */
1241         memcpy (&tok[tok_end], p, end - p);
1242
1243         p = end;
1244       }
1245     }
1246
1247     /* We've reached the end of a token. We shouldn't still be in quotes. */
1248     if (in_quote) {
1249       fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1250
1251       free_n_strings (argv, argv_len);
1252
1253       return NULL;
1254     }
1255
1256     /* Add this token if there is one. There might not be if there was
1257      * whitespace at the end of the input string */
1258     if (tok) {
1259       /* Add the NULL terminator */
1260       tok[tok_len] = '\0';
1261
1262       /* Add the argument to the argument list */
1263       argv_len++;
1264       char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1265       if (NULL == argv_new) {
1266         perror ("realloc");
1267         free_n_strings (argv, argv_len-1);
1268         free (tok);
1269         exit (EXIT_FAILURE);
1270       }
1271       argv = argv_new;
1272
1273       argv[argv_len-1] = tok;
1274     }
1275   }
1276
1277   /* NULL terminate the argument list */
1278   argv_len++;
1279   char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1280   if (NULL == argv_new) {
1281     perror ("realloc");
1282     free_n_strings (argv, argv_len-1);
1283     exit (EXIT_FAILURE);
1284   }
1285   argv = argv_new;
1286
1287   argv[argv_len-1] = NULL;
1288
1289   return argv;
1290 }
1291
1292 #ifdef HAVE_LIBREADLINE
1293 static char histfile[1024];
1294 static int nr_history_lines = 0;
1295 #endif
1296
1297 static void
1298 initialize_readline (void)
1299 {
1300 #ifdef HAVE_LIBREADLINE
1301   const char *home;
1302
1303   home = getenv ("HOME");
1304   if (home) {
1305     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1306     using_history ();
1307     (void) read_history (histfile);
1308   }
1309
1310   rl_readline_name = "guestfish";
1311   rl_attempted_completion_function = do_completion;
1312
1313   /* Note that .inputrc (or /etc/inputrc) is not read until the first
1314    * call the readline(), which happens later.  Therefore, these
1315    * provide default values which can be overridden by the user if
1316    * they wish.
1317    */
1318   (void) rl_variable_bind ("completion-ignore-case", "on");
1319 #endif
1320 }
1321
1322 static void
1323 cleanup_readline (void)
1324 {
1325 #ifdef HAVE_LIBREADLINE
1326   int fd;
1327
1328   if (histfile[0] != '\0') {
1329     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1330     if (fd == -1) {
1331       perror (histfile);
1332       return;
1333     }
1334     close (fd);
1335
1336 #ifdef HAVE_APPEND_HISTORY
1337     (void) append_history (nr_history_lines, histfile);
1338 #else
1339     (void) write_history (histfile);
1340 #endif
1341     clear_history ();
1342   }
1343 #endif
1344 }
1345
1346 #ifdef HAVE_LIBREADLINE
1347 static void
1348 add_history_line (const char *line)
1349 {
1350   add_history (line);
1351   nr_history_lines++;
1352 }
1353 #endif
1354
1355 int
1356 xwrite (int fd, const void *v_buf, size_t len)
1357 {
1358   int r;
1359   const char *buf = v_buf;
1360
1361   while (len > 0) {
1362     r = write (fd, buf, len);
1363     if (r == -1) {
1364       perror ("write");
1365       return -1;
1366     }
1367     buf += r;
1368     len -= r;
1369   }
1370
1371   return 0;
1372 }
1373
1374 /* Resolve the special "win:..." form for Windows-specific paths.
1375  * This always returns a newly allocated string which is freed by the
1376  * caller function in "cmds.c".
1377  */
1378 char *
1379 resolve_win_path (const char *path)
1380 {
1381   char *ret;
1382   size_t i;
1383
1384   if (STRCASENEQLEN (path, "win:", 4)) {
1385     ret = strdup (path);
1386     if (ret == NULL)
1387       perror ("strdup");
1388     return ret;
1389   }
1390
1391   path += 4;
1392
1393   /* Drop drive letter, if it's "C:". */
1394   if (STRCASEEQLEN (path, "c:", 2))
1395     path += 2;
1396
1397   if (!*path) {
1398     ret = strdup ("/");
1399     if (ret == NULL)
1400       perror ("strdup");
1401     return ret;
1402   }
1403
1404   ret = strdup (path);
1405   if (ret == NULL) {
1406     perror ("strdup");
1407     return NULL;
1408   }
1409
1410   /* Blindly convert any backslashes into forward slashes.  Is this good? */
1411   for (i = 0; i < strlen (ret); ++i)
1412     if (ret[i] == '\\')
1413       ret[i] = '/';
1414
1415   char *t = guestfs_case_sensitive_path (g, ret);
1416   free (ret);
1417   ret = t;
1418
1419   return ret;
1420 }
1421
1422 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1423  * The caller (cmds.c) will call free_file_in after the command has
1424  * run which should clean up resources.
1425  */
1426 static char *file_in_heredoc (const char *endmarker);
1427 static char *file_in_tmpfile = NULL;
1428
1429 char *
1430 file_in (const char *arg)
1431 {
1432   char *ret;
1433
1434   if (STREQ (arg, "-")) {
1435     ret = strdup ("/dev/stdin");
1436     if (!ret) {
1437       perror ("strdup");
1438       return NULL;
1439     }
1440   }
1441   else if (STRPREFIX (arg, "-<<")) {
1442     const char *endmarker = &arg[3];
1443     if (*endmarker == '\0') {
1444       fprintf (stderr, "%s: missing end marker in -<< expression\n",
1445                program_name);
1446       return NULL;
1447     }
1448     ret = file_in_heredoc (endmarker);
1449     if (ret == NULL)
1450       return NULL;
1451   }
1452   else {
1453     ret = strdup (arg);
1454     if (!ret) {
1455       perror ("strdup");
1456       return NULL;
1457     }
1458   }
1459
1460   return ret;
1461 }
1462
1463 static char *
1464 file_in_heredoc (const char *endmarker)
1465 {
1466   TMP_TEMPLATE_ON_STACK (template);
1467   file_in_tmpfile = strdup (template);
1468   if (file_in_tmpfile == NULL) {
1469     perror ("strdup");
1470     return NULL;
1471   }
1472
1473   int fd = mkstemp (file_in_tmpfile);
1474   if (fd == -1) {
1475     perror ("mkstemp");
1476     goto error1;
1477   }
1478
1479   size_t markerlen = strlen (endmarker);
1480
1481   char buffer[BUFSIZ];
1482   int write_error = 0;
1483   while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1484     /* Look for "END"<EOF> or "END\n" in input. */
1485     size_t blen = strlen (buffer);
1486     if (STREQLEN (buffer, endmarker, markerlen) &&
1487         (blen == markerlen ||
1488          (blen == markerlen+1 && buffer[markerlen] == '\n')))
1489       goto found_end;
1490
1491     if (xwrite (fd, buffer, blen) == -1) {
1492       if (!write_error) perror ("write");
1493       write_error = 1;
1494       /* continue reading up to the end marker */
1495     }
1496   }
1497
1498   /* Reached EOF of stdin without finding the end marker, which
1499    * is likely to be an error.
1500    */
1501   fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1502            program_name, endmarker);
1503   goto error2;
1504
1505  found_end:
1506   if (write_error) {
1507     close (fd);
1508     goto error2;
1509   }
1510
1511   if (close (fd) == -1) {
1512     perror ("close");
1513     goto error2;
1514   }
1515
1516   return file_in_tmpfile;
1517
1518  error2:
1519   unlink (file_in_tmpfile);
1520
1521  error1:
1522   free (file_in_tmpfile);
1523   file_in_tmpfile = NULL;
1524   return NULL;
1525 }
1526
1527 void
1528 free_file_in (char *s)
1529 {
1530   if (file_in_tmpfile) {
1531     if (unlink (file_in_tmpfile) == -1)
1532       perror (file_in_tmpfile);
1533     file_in_tmpfile = NULL;
1534   }
1535
1536   /* Free the device or file name which was strdup'd in file_in().
1537    * Note it's not immediately clear, but for -<< heredocs,
1538    * s == file_in_tmpfile, so this frees up that buffer.
1539    */
1540   free (s);
1541 }
1542
1543 /* Resolve the special FileOut paths ("-" or filename).
1544  * The caller (cmds.c) will call free (str) after the command has run.
1545  */
1546 char *
1547 file_out (const char *arg)
1548 {
1549   char *ret;
1550
1551   if (STREQ (arg, "-"))
1552     ret = strdup ("/dev/stdout");
1553   else
1554     ret = strdup (arg);
1555
1556   if (!ret) {
1557     perror ("strdup");
1558     return NULL;
1559   }
1560   return ret;
1561 }