fish: Initialize pcmd structure.
[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   /* Note that pcmd.pipe must be set to NULL for correct usage.  Other
681    * fields do not need to be, but this silences a gcc warning.
682    */
683   memset (&pcmd, 0, sizeof pcmd);
684
685  again:
686   /* Skip any initial whitespace before the command. */
687   while (*buf && c_isspace (*buf))
688     buf++;
689
690   if (!*buf) {
691     pcmd.status = 0;
692     return pcmd;
693   }
694
695   /* If the next character is '#' then this is a comment. */
696   if (*buf == '#') {
697     pcmd.status = 0;
698     return pcmd;
699   }
700
701   /* If the next character is '!' then pass the whole lot to system(3). */
702   if (*buf == '!') {
703     r = system (buf+1);
704     if (r == -1 ||
705         (WIFSIGNALED (r) &&
706          (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
707         WEXITSTATUS (r) != 0)
708       pcmd.status = -1;
709     else
710       pcmd.status = 0;
711     return pcmd;
712   }
713
714   /* If the next character is '-' allow the command to fail without
715    * exiting on error (just for this one command though).
716    */
717   if (*buf == '-') {
718     *exit_on_error_rtn = 0;
719     buf++;
720     goto again;
721   }
722
723   /* Get the command (cannot be quoted). */
724   len = strcspn (buf, " \t");
725
726   if (len == 0) {
727     pcmd.status = 0;
728     return pcmd;
729   }
730
731   pcmd.cmd = buf;
732   unsigned int i = 0;
733   if (buf[len] == '\0') {
734     pcmd.argv[0] = NULL;
735     pcmd.status = 1;
736     return pcmd;
737   }
738
739   buf[len] = '\0';
740   p = &buf[len+1];
741   p += strspn (p, " \t");
742
743   /* Get the parameters. */
744   while (*p && i < argv_len) {
745     tilde_candidate = 0;
746
747     /* Parameters which start with quotes or pipes are treated
748      * specially.  Bare parameters are delimited by whitespace.
749      */
750     if (*p == '"') {
751       p++;
752       len = strcspn (p, "\"");
753       if (p[len] == '\0') {
754         fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
755         pcmd.status = -1;
756         return pcmd;
757       }
758       if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
759         fprintf (stderr,
760                  _("%s: command arguments not separated by whitespace\n"),
761                  program_name);
762         pcmd.status = -1;
763         return pcmd;
764       }
765       p[len] = '\0';
766       pend = p[len+1] ? &p[len+2] : &p[len+1];
767     } else if (*p == '\'') {
768       p++;
769       len = strcspn (p, "'");
770       if (p[len] == '\0') {
771         fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
772         pcmd.status = -1;
773         return pcmd;
774       }
775       if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
776         fprintf (stderr,
777                  _("%s: command arguments not separated by whitespace\n"),
778                  program_name);
779         pcmd.status = -1;
780         return pcmd;
781       }
782       p[len] = '\0';
783       pend = p[len+1] ? &p[len+2] : &p[len+1];
784     } else if (*p == '|') {
785       *p = '\0';
786       pcmd.pipe = p+1;
787       continue;
788     } else if (*p != ' ' && *p != '\t') {
789       /* If the first character is a ~ then note that this parameter
790        * is a candidate for ~username expansion.  NB this does not
791        * apply to quoted parameters.
792        */
793       tilde_candidate = *p == '~';
794       len = strcspn (p, " \t");
795       if (p[len]) {
796         p[len] = '\0';
797         pend = &p[len+1];
798       } else
799         pend = &p[len];
800     } else {
801       fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
802                program_name, p);
803       abort ();
804     }
805
806     if (!tilde_candidate)
807       pcmd.argv[i] = p;
808     else
809       pcmd.argv[i] = try_tilde_expansion (p);
810     i++;
811     p = pend;
812
813     if (*p)
814       p += strspn (p, " \t");
815   }
816
817   if (i == argv_len) {
818     fprintf (stderr, _("%s: too many arguments\n"), program_name);
819     pcmd.status = -1;
820     return pcmd;
821   }
822
823   pcmd.argv[i] = NULL;
824
825   pcmd.status = 1;
826   return pcmd;
827 }
828
829 static void
830 cmdline (char *argv[], int optind, int argc)
831 {
832   const char *cmd;
833   char **params;
834   int exit_on_error;
835
836   exit_on_error = 1;
837
838   if (optind >= argc) return;
839
840   cmd = argv[optind++];
841   if (STREQ (cmd, ":")) {
842     fprintf (stderr, _("%s: empty command on command line\n"), program_name);
843     exit (EXIT_FAILURE);
844   }
845
846   /* Allow -cmd on the command line to mean (temporarily) override
847    * the normal exit on error (RHBZ#578407).
848    */
849   if (cmd[0] == '-') {
850     exit_on_error = 0;
851     cmd++;
852   }
853
854   params = &argv[optind];
855
856   /* Search for end of command list or ":" ... */
857   while (optind < argc && STRNEQ (argv[optind], ":"))
858     optind++;
859
860   if (optind == argc) {
861     if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
862         exit (EXIT_FAILURE);
863   } else {
864     argv[optind] = NULL;
865     if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
866       exit (EXIT_FAILURE);
867     cmdline (argv, optind+1, argc);
868   }
869 }
870
871 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
872  * pass to the remote server (when issuing --remote commands).  It
873  * does not cause issue_command itself to exit on error.
874  */
875 int
876 issue_command (const char *cmd, char *argv[], const char *pipecmd,
877                int rc_exit_on_error_flag)
878 {
879   int argc;
880   int stdout_saved_fd = -1;
881   int pid = 0;
882   int r;
883
884   reset_progress_bar ();
885
886   /* This counts the commands issued, starting at 1. */
887   command_num++;
888
889   /* For | ... commands.  Annoyingly we can't use popen(3) here. */
890   if (pipecmd) {
891     int fd[2];
892
893     if (fflush (stdout) == EOF) {
894       perror ("failed to flush standard output");
895       return -1;
896     }
897     if (pipe (fd) < 0) {
898       perror ("pipe failed");
899       return -1;
900     }
901     pid = fork ();
902     if (pid == -1) {
903       perror ("fork");
904       return -1;
905     }
906
907     if (pid == 0) {             /* Child process. */
908       close (fd[1]);
909       if (dup2 (fd[0], 0) < 0) {
910         perror ("dup2 of stdin failed");
911         _exit (1);
912       }
913
914       r = system (pipecmd);
915       if (r == -1) {
916         perror (pipecmd);
917         _exit (1);
918       }
919       _exit (WEXITSTATUS (r));
920     }
921
922     if ((stdout_saved_fd = dup (1)) < 0) {
923       perror ("failed to dup stdout");
924       return -1;
925     }
926     close (fd[0]);
927     if (dup2 (fd[1], 1) < 0) {
928       perror ("failed to dup stdout");
929       close (stdout_saved_fd);
930       return -1;
931     }
932     close (fd[1]);
933   }
934
935   for (argc = 0; argv[argc] != NULL; ++argc)
936     ;
937
938   /* If --remote was set, then send this command to a remote process. */
939   if (remote_control)
940     r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
941
942   /* Otherwise execute it locally. */
943   else if (STRCASEEQ (cmd, "help")) {
944     if (argc == 0) {
945       display_help ();
946       r = 0;
947     } else
948       r = display_command (argv[0]);
949   }
950   else if (STRCASEEQ (cmd, "quit") ||
951            STRCASEEQ (cmd, "exit") ||
952            STRCASEEQ (cmd, "q")) {
953     quit = 1;
954     r = 0;
955   }
956   else
957     r = run_action (cmd, argc, argv);
958
959   /* Always flush stdout after every command, so that messages, results
960    * etc appear immediately.
961    */
962   if (fflush (stdout) == EOF) {
963     perror ("failed to flush standard output");
964     return -1;
965   }
966
967   if (pipecmd) {
968     close (1);
969     if (dup2 (stdout_saved_fd, 1) < 0) {
970       perror ("failed to dup2 standard output");
971       r = -1;
972     }
973     close (stdout_saved_fd);
974     if (waitpid (pid, NULL, 0) < 0) {
975       perror ("waiting for command to complete");
976       r = -1;
977     }
978   }
979
980   return r;
981 }
982
983 void
984 list_builtin_commands (void)
985 {
986   /* help and quit should appear at the top */
987   printf ("%-20s %s\n",
988           "help", _("display a list of commands or help on a command"));
989   printf ("%-20s %s\n",
990           "quit", _("quit guestfish"));
991
992   /* actions are printed after this (see list_commands) */
993 }
994
995 int
996 display_builtin_command (const char *cmd)
997 {
998   /* help for actions is auto-generated, see display_command */
999
1000   if (STRCASEEQ (cmd, "help")) {
1001     printf (_("help - display a list of commands or help on a command\n"
1002               "     help cmd\n"
1003               "     help\n"));
1004     return 0;
1005   }
1006   else if (STRCASEEQ (cmd, "quit") ||
1007            STRCASEEQ (cmd, "exit") ||
1008            STRCASEEQ (cmd, "q")) {
1009     printf (_("quit - quit guestfish\n"
1010               "     quit\n"));
1011     return 0;
1012   }
1013   else {
1014     fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1015              cmd);
1016     return -1;
1017   }
1018 }
1019
1020 /* This is printed when the user types in an unknown command for the
1021  * first command issued.  A common case is the user doing:
1022  *   guestfish disk.img
1023  * expecting guestfish to open 'disk.img' (in fact, this tried to
1024  * run a command 'disk.img').
1025  */
1026 void
1027 extended_help_message (void)
1028 {
1029   fprintf (stderr,
1030            _("Did you mean to open a disk image?  guestfish -a disk.img\n"
1031              "For a list of commands:             guestfish -h\n"
1032              "For complete documentation:         man guestfish\n"));
1033 }
1034
1035 void
1036 free_strings (char **argv)
1037 {
1038   int argc;
1039
1040   for (argc = 0; argv[argc] != NULL; ++argc)
1041     free (argv[argc]);
1042   free (argv);
1043 }
1044
1045 int
1046 count_strings (char *const *argv)
1047 {
1048   int c;
1049
1050   for (c = 0; argv[c]; ++c)
1051     ;
1052   return c;
1053 }
1054
1055 void
1056 print_strings (char *const *argv)
1057 {
1058   int argc;
1059
1060   for (argc = 0; argv[argc] != NULL; ++argc)
1061     printf ("%s\n", argv[argc]);
1062 }
1063
1064 void
1065 print_table (char *const *argv)
1066 {
1067   int i;
1068
1069   for (i = 0; argv[i] != NULL; i += 2)
1070     printf ("%s: %s\n", argv[i], argv[i+1]);
1071 }
1072
1073 int
1074 is_true (const char *str)
1075 {
1076   return
1077     STRCASENEQ (str, "0") &&
1078     STRCASENEQ (str, "f") &&
1079     STRCASENEQ (str, "false") &&
1080     STRCASENEQ (str, "n") &&
1081     STRCASENEQ (str, "no");
1082 }
1083
1084 /* Free strings from a non-NULL terminated char** */
1085 static void
1086 free_n_strings (char **str, size_t len)
1087 {
1088   size_t i;
1089
1090   for (i = 0; i < len; i++) {
1091     free (str[i]);
1092   }
1093   free (str);
1094 }
1095
1096 char **
1097 parse_string_list (const char *str)
1098 {
1099   char **argv = NULL;
1100   size_t argv_len = 0;
1101
1102   /* Current position pointer */
1103   const char *p = str;
1104
1105   /* Token might be simple:
1106    *  Token
1107    * or be quoted:
1108    *  'This is a single token'
1109    * or contain embedded single-quoted sections:
1110    *  This' is a sing'l'e to'ken
1111    *
1112    * The latter may seem over-complicated, but it's what a normal shell does.
1113    * Not doing it risks surprising somebody.
1114    *
1115    * This outer loop is over complete tokens.
1116    */
1117   while (*p) {
1118     char *tok = NULL;
1119     size_t tok_len = 0;
1120
1121     /* Skip leading whitespace */
1122     p += strspn (p, " \t");
1123
1124     char in_quote = 0;
1125
1126     /* This loop is over token 'fragments'. A token can be in multiple bits if
1127      * it contains single quotes. We also treat both sides of an escaped quote
1128      * as separate fragments because we can't just copy it: we have to remove
1129      * the \.
1130      */
1131     while (*p && (!c_isblank (*p) || in_quote)) {
1132       const char *end = p;
1133
1134       /* Check if the fragment starts with a quote */
1135       if ('\'' == *p) {
1136         /* Toggle in_quote */
1137         in_quote = !in_quote;
1138
1139         /* Skip the quote */
1140         p++; end++;
1141       }
1142
1143       /* If we're in a quote, look for an end quote */
1144       if (in_quote) {
1145         end += strcspn (end, "'");
1146       }
1147
1148       /* Otherwise, look for whitespace or a quote */
1149       else {
1150         end += strcspn (end, " \t'");
1151       }
1152
1153       /* Grow the token to accommodate the fragment */
1154       size_t tok_end = tok_len;
1155       tok_len += end - p;
1156       char *tok_new = realloc (tok, tok_len + 1);
1157       if (NULL == tok_new) {
1158         perror ("realloc");
1159         free_n_strings (argv, argv_len);
1160         free (tok);
1161         exit (EXIT_FAILURE);
1162       }
1163       tok = tok_new;
1164
1165       /* Check if we stopped on an escaped quote */
1166       if ('\'' == *end && end != p && *(end-1) == '\\') {
1167         /* Add everything before \' to the token */
1168         memcpy (&tok[tok_end], p, end - p - 1);
1169
1170         /* Add the quote */
1171         tok[tok_len-1] = '\'';
1172
1173         /* Already processed the quote */
1174         p = end + 1;
1175       }
1176
1177       else {
1178         /* Add the whole fragment */
1179         memcpy (&tok[tok_end], p, end - p);
1180
1181         p = end;
1182       }
1183     }
1184
1185     /* We've reached the end of a token. We shouldn't still be in quotes. */
1186     if (in_quote) {
1187       fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1188
1189       free_n_strings (argv, argv_len);
1190
1191       return NULL;
1192     }
1193
1194     /* Add this token if there is one. There might not be if there was
1195      * whitespace at the end of the input string */
1196     if (tok) {
1197       /* Add the NULL terminator */
1198       tok[tok_len] = '\0';
1199
1200       /* Add the argument to the argument list */
1201       argv_len++;
1202       char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1203       if (NULL == argv_new) {
1204         perror ("realloc");
1205         free_n_strings (argv, argv_len-1);
1206         free (tok);
1207         exit (EXIT_FAILURE);
1208       }
1209       argv = argv_new;
1210
1211       argv[argv_len-1] = tok;
1212     }
1213   }
1214
1215   /* NULL terminate the argument list */
1216   argv_len++;
1217   char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1218   if (NULL == argv_new) {
1219     perror ("realloc");
1220     free_n_strings (argv, argv_len-1);
1221     exit (EXIT_FAILURE);
1222   }
1223   argv = argv_new;
1224
1225   argv[argv_len-1] = NULL;
1226
1227   return argv;
1228 }
1229
1230 #ifdef HAVE_LIBREADLINE
1231 static char histfile[1024];
1232 static int nr_history_lines = 0;
1233 #endif
1234
1235 static void
1236 initialize_readline (void)
1237 {
1238 #ifdef HAVE_LIBREADLINE
1239   const char *home;
1240
1241   home = getenv ("HOME");
1242   if (home) {
1243     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1244     using_history ();
1245     (void) read_history (histfile);
1246   }
1247
1248   rl_readline_name = "guestfish";
1249   rl_attempted_completion_function = do_completion;
1250
1251   /* Note that .inputrc (or /etc/inputrc) is not read until the first
1252    * call the readline(), which happens later.  Therefore, these
1253    * provide default values which can be overridden by the user if
1254    * they wish.
1255    */
1256   (void) rl_variable_bind ("completion-ignore-case", "on");
1257 #endif
1258 }
1259
1260 static void
1261 cleanup_readline (void)
1262 {
1263 #ifdef HAVE_LIBREADLINE
1264   int fd;
1265
1266   if (histfile[0] != '\0') {
1267     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1268     if (fd == -1) {
1269       perror (histfile);
1270       return;
1271     }
1272     close (fd);
1273
1274 #ifdef HAVE_APPEND_HISTORY
1275     (void) append_history (nr_history_lines, histfile);
1276 #else
1277     (void) write_history (histfile);
1278 #endif
1279     clear_history ();
1280   }
1281 #endif
1282 }
1283
1284 #ifdef HAVE_LIBREADLINE
1285 static void
1286 add_history_line (const char *line)
1287 {
1288   add_history (line);
1289   nr_history_lines++;
1290 }
1291 #endif
1292
1293 int
1294 xwrite (int fd, const void *v_buf, size_t len)
1295 {
1296   int r;
1297   const char *buf = v_buf;
1298
1299   while (len > 0) {
1300     r = write (fd, buf, len);
1301     if (r == -1) {
1302       perror ("write");
1303       return -1;
1304     }
1305     buf += r;
1306     len -= r;
1307   }
1308
1309   return 0;
1310 }
1311
1312 /* Resolve the special "win:..." form for Windows-specific paths.
1313  * This always returns a newly allocated string which is freed by the
1314  * caller function in "cmds.c".
1315  */
1316 char *
1317 resolve_win_path (const char *path)
1318 {
1319   char *ret;
1320   size_t i;
1321
1322   if (STRCASENEQLEN (path, "win:", 4)) {
1323     ret = strdup (path);
1324     if (ret == NULL)
1325       perror ("strdup");
1326     return ret;
1327   }
1328
1329   path += 4;
1330
1331   /* Drop drive letter, if it's "C:". */
1332   if (STRCASEEQLEN (path, "c:", 2))
1333     path += 2;
1334
1335   if (!*path) {
1336     ret = strdup ("/");
1337     if (ret == NULL)
1338       perror ("strdup");
1339     return ret;
1340   }
1341
1342   ret = strdup (path);
1343   if (ret == NULL) {
1344     perror ("strdup");
1345     return NULL;
1346   }
1347
1348   /* Blindly convert any backslashes into forward slashes.  Is this good? */
1349   for (i = 0; i < strlen (ret); ++i)
1350     if (ret[i] == '\\')
1351       ret[i] = '/';
1352
1353   char *t = guestfs_case_sensitive_path (g, ret);
1354   free (ret);
1355   ret = t;
1356
1357   return ret;
1358 }
1359
1360 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1361  * The caller (cmds.c) will call free_file_in after the command has
1362  * run which should clean up resources.
1363  */
1364 static char *file_in_heredoc (const char *endmarker);
1365 static char *file_in_tmpfile = NULL;
1366
1367 char *
1368 file_in (const char *arg)
1369 {
1370   char *ret;
1371
1372   if (STREQ (arg, "-")) {
1373     ret = strdup ("/dev/stdin");
1374     if (!ret) {
1375       perror ("strdup");
1376       return NULL;
1377     }
1378   }
1379   else if (STRPREFIX (arg, "-<<")) {
1380     const char *endmarker = &arg[3];
1381     if (*endmarker == '\0') {
1382       fprintf (stderr, "%s: missing end marker in -<< expression\n",
1383                program_name);
1384       return NULL;
1385     }
1386     ret = file_in_heredoc (endmarker);
1387     if (ret == NULL)
1388       return NULL;
1389   }
1390   else {
1391     ret = strdup (arg);
1392     if (!ret) {
1393       perror ("strdup");
1394       return NULL;
1395     }
1396   }
1397
1398   return ret;
1399 }
1400
1401 static char *
1402 file_in_heredoc (const char *endmarker)
1403 {
1404   TMP_TEMPLATE_ON_STACK (template);
1405   file_in_tmpfile = strdup (template);
1406   if (file_in_tmpfile == NULL) {
1407     perror ("strdup");
1408     return NULL;
1409   }
1410
1411   int fd = mkstemp (file_in_tmpfile);
1412   if (fd == -1) {
1413     perror ("mkstemp");
1414     goto error1;
1415   }
1416
1417   size_t markerlen = strlen (endmarker);
1418
1419   char buffer[BUFSIZ];
1420   int write_error = 0;
1421   while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1422     /* Look for "END"<EOF> or "END\n" in input. */
1423     size_t blen = strlen (buffer);
1424     if (STREQLEN (buffer, endmarker, markerlen) &&
1425         (blen == markerlen ||
1426          (blen == markerlen+1 && buffer[markerlen] == '\n')))
1427       goto found_end;
1428
1429     if (xwrite (fd, buffer, blen) == -1) {
1430       if (!write_error) perror ("write");
1431       write_error = 1;
1432       /* continue reading up to the end marker */
1433     }
1434   }
1435
1436   /* Reached EOF of stdin without finding the end marker, which
1437    * is likely to be an error.
1438    */
1439   fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1440            program_name, endmarker);
1441   goto error2;
1442
1443  found_end:
1444   if (write_error) {
1445     close (fd);
1446     goto error2;
1447   }
1448
1449   if (close (fd) == -1) {
1450     perror ("close");
1451     goto error2;
1452   }
1453
1454   return file_in_tmpfile;
1455
1456  error2:
1457   unlink (file_in_tmpfile);
1458
1459  error1:
1460   free (file_in_tmpfile);
1461   file_in_tmpfile = NULL;
1462   return NULL;
1463 }
1464
1465 void
1466 free_file_in (char *s)
1467 {
1468   if (file_in_tmpfile) {
1469     if (unlink (file_in_tmpfile) == -1)
1470       perror (file_in_tmpfile);
1471     file_in_tmpfile = NULL;
1472   }
1473
1474   /* Free the device or file name which was strdup'd in file_in().
1475    * Note it's not immediately clear, but for -<< heredocs,
1476    * s == file_in_tmpfile, so this frees up that buffer.
1477    */
1478   free (s);
1479 }
1480
1481 /* Resolve the special FileOut paths ("-" or filename).
1482  * The caller (cmds.c) will call free (str) after the command has run.
1483  */
1484 char *
1485 file_out (const char *arg)
1486 {
1487   char *ret;
1488
1489   if (STREQ (arg, "-"))
1490     ret = strdup ("/dev/stdout");
1491   else
1492     ret = strdup (arg);
1493
1494   if (!ret) {
1495     perror ("strdup");
1496     return NULL;
1497   }
1498   return ret;
1499 }