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