regressions: Enable both tests for bug 576879 (not fixed).
[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_event_callback (g, progress_callback,
503                                 GUESTFS_EVENT_PROGRESS, 0, NULL);
504
505   /* Interactive, shell script, or command(s) on the command line? */
506   if (optind >= argc) {
507     if (isatty (0))
508       interactive ();
509     else
510       shell_script ();
511   }
512   else
513     cmdline (argv, optind, argc);
514
515   cleanup_readline ();
516
517   exit (EXIT_SUCCESS);
518 }
519
520 /* The <term.h> header file which defines this has "issues". */
521 extern int tgetent (char *, const char *);
522
523 static void
524 set_up_terminal (void)
525 {
526   /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
527   utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
528
529   char *term = getenv ("TERM");
530   if (term == NULL) {
531     //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
532     return;
533   }
534
535   int r = tgetent (NULL, term);
536   if (r == -1) {
537     fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
538     return;
539   }
540   if (r == 0) {
541     fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
542              term);
543     return;
544   }
545
546   have_terminfo = 1;
547 }
548
549 static void
550 prepare_drives (struct drv *drv)
551 {
552   if (drv) {
553     prepare_drives (drv->next);
554     if (drv->type == drv_N)
555       prepare_drive (drv->N.filename, drv->N.data, drv->device);
556   }
557 }
558
559 static int
560 launch (void)
561 {
562   if (guestfs_is_config (g)) {
563     if (guestfs_launch (g) == -1)
564       return -1;
565   }
566   return 0;
567 }
568
569 static void
570 interactive (void)
571 {
572   script (1);
573 }
574
575 static void
576 shell_script (void)
577 {
578   script (0);
579 }
580
581 #define FISH "><fs> "
582
583 static char *line_read = NULL;
584
585 static char *
586 rl_gets (int prompt)
587 {
588 #ifdef HAVE_LIBREADLINE
589
590   if (prompt) {
591     if (line_read) {
592       free (line_read);
593       line_read = NULL;
594     }
595
596     line_read = readline (prompt ? FISH : "");
597
598     if (line_read && *line_read)
599       add_history_line (line_read);
600
601     return line_read;
602   }
603
604 #endif /* HAVE_LIBREADLINE */
605
606   static char buf[8192];
607   int len;
608
609   if (prompt) printf (FISH);
610   line_read = fgets (buf, sizeof buf, stdin);
611
612   if (line_read) {
613     len = strlen (line_read);
614     if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
615   }
616
617   return line_read;
618 }
619
620 static void
621 script (int prompt)
622 {
623   char *buf;
624   int global_exit_on_error = !prompt;
625   int exit_on_error;
626   struct parsed_command pcmd;
627
628   if (prompt) {
629     printf (_("\n"
630               "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
631               "editing virtual machine filesystems.\n"
632               "\n"
633               "Type: 'help' for help on commands\n"
634               "      'man' to read the manual\n"
635               "      'quit' to quit the shell\n"
636               "\n"));
637
638     if (inspector) {
639       print_inspect_prompt ();
640       printf ("\n");
641     }
642   }
643
644   while (!quit) {
645     exit_on_error = global_exit_on_error;
646
647     buf = rl_gets (prompt);
648     if (!buf) {
649       quit = 1;
650       break;
651     }
652
653     pcmd = parse_command_line (buf, &exit_on_error);
654     if (pcmd.status == -1 && exit_on_error)
655       exit (EXIT_FAILURE);
656     if (pcmd.status == 1) {
657       if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
658         if (exit_on_error) exit (EXIT_FAILURE);
659       }
660     }
661   }
662   if (prompt) printf ("\n");
663 }
664
665 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
666  * This destructively updates 'buf'.
667  *
668  * 'exit_on_error_rtn' is used to pass in the global exit_on_error
669  * setting and to return the local setting (eg. if the command begins
670  * with '-').
671  *
672  * Returns in parsed_command.status:
673  *   1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
674  *   0 = no guestfish command, but otherwise OK
675  *  -1 = an error
676  */
677 static struct parsed_command
678 parse_command_line (char *buf, int *exit_on_error_rtn)
679 {
680   struct parsed_command pcmd;
681   char *p, *pend;
682   int len;
683   int tilde_candidate;
684   int r;
685   const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
686
687   /* Note that pcmd.pipe must be set to NULL for correct usage.  Other
688    * fields do not need to be, but this silences a gcc warning.
689    */
690   memset (&pcmd, 0, sizeof pcmd);
691
692  again:
693   /* Skip any initial whitespace before the command. */
694   while (*buf && c_isspace (*buf))
695     buf++;
696
697   if (!*buf) {
698     pcmd.status = 0;
699     return pcmd;
700   }
701
702   /* If the next character is '#' then this is a comment. */
703   if (*buf == '#') {
704     pcmd.status = 0;
705     return pcmd;
706   }
707
708   /* If the next character is '!' then pass the whole lot to system(3). */
709   if (*buf == '!') {
710     r = system (buf+1);
711     if (r == -1 ||
712         (WIFSIGNALED (r) &&
713          (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
714         WEXITSTATUS (r) != 0)
715       pcmd.status = -1;
716     else
717       pcmd.status = 0;
718     return pcmd;
719   }
720
721   /* If the next two characters are "<!" then pass the command to
722    * popen(3), read the result and execute it as guestfish commands.
723    */
724   if (buf[0] == '<' && buf[1] == '!') {
725     int r = execute_and_inline (&buf[2], *exit_on_error_rtn);
726     if (r == -1)
727       pcmd.status = -1;
728     else
729       pcmd.status = 0;
730     return pcmd;
731   }
732
733   /* If the next character is '-' allow the command to fail without
734    * exiting on error (just for this one command though).
735    */
736   if (*buf == '-') {
737     *exit_on_error_rtn = 0;
738     buf++;
739     goto again;
740   }
741
742   /* Get the command (cannot be quoted). */
743   len = strcspn (buf, " \t");
744
745   if (len == 0) {
746     pcmd.status = 0;
747     return pcmd;
748   }
749
750   pcmd.cmd = buf;
751   unsigned int i = 0;
752   if (buf[len] == '\0') {
753     pcmd.argv[0] = NULL;
754     pcmd.status = 1;
755     return pcmd;
756   }
757
758   buf[len] = '\0';
759   p = &buf[len+1];
760   p += strspn (p, " \t");
761
762   /* Get the parameters. */
763   while (*p && i < argv_len) {
764     tilde_candidate = 0;
765
766     /* Parameters which start with quotes or pipes are treated
767      * specially.  Bare parameters are delimited by whitespace.
768      */
769     if (*p == '"') {
770       p++;
771       len = strcspn (p, "\"");
772       if (p[len] == '\0') {
773         fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
774         pcmd.status = -1;
775         return pcmd;
776       }
777       if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
778         fprintf (stderr,
779                  _("%s: command arguments not separated by whitespace\n"),
780                  program_name);
781         pcmd.status = -1;
782         return pcmd;
783       }
784       p[len] = '\0';
785       pend = p[len+1] ? &p[len+2] : &p[len+1];
786     } else if (*p == '\'') {
787       p++;
788       len = strcspn (p, "'");
789       if (p[len] == '\0') {
790         fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
791         pcmd.status = -1;
792         return pcmd;
793       }
794       if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
795         fprintf (stderr,
796                  _("%s: command arguments not separated by whitespace\n"),
797                  program_name);
798         pcmd.status = -1;
799         return pcmd;
800       }
801       p[len] = '\0';
802       pend = p[len+1] ? &p[len+2] : &p[len+1];
803     } else if (*p == '|') {
804       *p = '\0';
805       pcmd.pipe = p+1;
806       continue;
807     } else if (*p != ' ' && *p != '\t') {
808       /* If the first character is a ~ then note that this parameter
809        * is a candidate for ~username expansion.  NB this does not
810        * apply to quoted parameters.
811        */
812       tilde_candidate = *p == '~';
813       len = strcspn (p, " \t");
814       if (p[len]) {
815         p[len] = '\0';
816         pend = &p[len+1];
817       } else
818         pend = &p[len];
819     } else {
820       fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
821                program_name, p);
822       abort ();
823     }
824
825     if (!tilde_candidate)
826       pcmd.argv[i] = p;
827     else
828       pcmd.argv[i] = try_tilde_expansion (p);
829     i++;
830     p = pend;
831
832     if (*p)
833       p += strspn (p, " \t");
834   }
835
836   if (i == argv_len) {
837     fprintf (stderr, _("%s: too many arguments\n"), program_name);
838     pcmd.status = -1;
839     return pcmd;
840   }
841
842   pcmd.argv[i] = NULL;
843
844   pcmd.status = 1;
845   return pcmd;
846 }
847
848 /* Used to handle "<!" (execute command and inline result). */
849 static int
850 execute_and_inline (const char *cmd, int global_exit_on_error)
851 {
852   FILE *pp;
853   char *line = NULL;
854   size_t len = 0;
855   ssize_t n;
856   int exit_on_error;
857   struct parsed_command pcmd;
858
859   pp = popen (cmd, "r");
860   if (!pp) {
861     perror ("popen");
862     return -1;
863   }
864
865   while ((n = getline (&line, &len, pp)) != -1) {
866     exit_on_error = global_exit_on_error;
867
868     /* Chomp final line ending which parse_command_line would not expect. */
869     if (n > 0 && line[n-1] == '\n')
870       line[n-1] = '\0';
871
872     pcmd = parse_command_line (line, &exit_on_error);
873     if (pcmd.status == -1 && exit_on_error)
874       exit (EXIT_FAILURE);
875     if (pcmd.status == 1) {
876       if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
877         if (exit_on_error) exit (EXIT_FAILURE);
878       }
879     }
880   }
881
882   free (line);
883
884   if (pclose (pp) == -1) {
885     perror ("pclose");
886     return -1;
887   }
888
889   return 0;
890 }
891
892 static void
893 cmdline (char *argv[], int optind, int argc)
894 {
895   const char *cmd;
896   char **params;
897   int exit_on_error;
898
899   exit_on_error = 1;
900
901   if (optind >= argc) return;
902
903   cmd = argv[optind++];
904   if (STREQ (cmd, ":")) {
905     fprintf (stderr, _("%s: empty command on command line\n"), program_name);
906     exit (EXIT_FAILURE);
907   }
908
909   /* Allow -cmd on the command line to mean (temporarily) override
910    * the normal exit on error (RHBZ#578407).
911    */
912   if (cmd[0] == '-') {
913     exit_on_error = 0;
914     cmd++;
915   }
916
917   params = &argv[optind];
918
919   /* Search for end of command list or ":" ... */
920   while (optind < argc && STRNEQ (argv[optind], ":"))
921     optind++;
922
923   if (optind == argc) {
924     if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
925         exit (EXIT_FAILURE);
926   } else {
927     argv[optind] = NULL;
928     if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
929       exit (EXIT_FAILURE);
930     cmdline (argv, optind+1, argc);
931   }
932 }
933
934 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
935  * pass to the remote server (when issuing --remote commands).  It
936  * does not cause issue_command itself to exit on error.
937  */
938 int
939 issue_command (const char *cmd, char *argv[], const char *pipecmd,
940                int rc_exit_on_error_flag)
941 {
942   int argc;
943   int stdout_saved_fd = -1;
944   int pid = 0;
945   int r;
946
947   reset_progress_bar ();
948
949   /* This counts the commands issued, starting at 1. */
950   command_num++;
951
952   /* For | ... commands.  Annoyingly we can't use popen(3) here. */
953   if (pipecmd) {
954     int fd[2];
955
956     if (fflush (stdout) == EOF) {
957       perror ("failed to flush standard output");
958       return -1;
959     }
960     if (pipe (fd) < 0) {
961       perror ("pipe failed");
962       return -1;
963     }
964     pid = fork ();
965     if (pid == -1) {
966       perror ("fork");
967       return -1;
968     }
969
970     if (pid == 0) {             /* Child process. */
971       close (fd[1]);
972       if (dup2 (fd[0], 0) < 0) {
973         perror ("dup2 of stdin failed");
974         _exit (1);
975       }
976
977       r = system (pipecmd);
978       if (r == -1) {
979         perror (pipecmd);
980         _exit (1);
981       }
982       _exit (WEXITSTATUS (r));
983     }
984
985     if ((stdout_saved_fd = dup (1)) < 0) {
986       perror ("failed to dup stdout");
987       return -1;
988     }
989     close (fd[0]);
990     if (dup2 (fd[1], 1) < 0) {
991       perror ("failed to dup stdout");
992       close (stdout_saved_fd);
993       return -1;
994     }
995     close (fd[1]);
996   }
997
998   for (argc = 0; argv[argc] != NULL; ++argc)
999     ;
1000
1001   /* If --remote was set, then send this command to a remote process. */
1002   if (remote_control)
1003     r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
1004
1005   /* Otherwise execute it locally. */
1006   else if (STRCASEEQ (cmd, "help")) {
1007     if (argc == 0) {
1008       display_help ();
1009       r = 0;
1010     } else
1011       r = display_command (argv[0]);
1012   }
1013   else if (STRCASEEQ (cmd, "quit") ||
1014            STRCASEEQ (cmd, "exit") ||
1015            STRCASEEQ (cmd, "q")) {
1016     quit = 1;
1017     r = 0;
1018   }
1019   else
1020     r = run_action (cmd, argc, argv);
1021
1022   /* Always flush stdout after every command, so that messages, results
1023    * etc appear immediately.
1024    */
1025   if (fflush (stdout) == EOF) {
1026     perror ("failed to flush standard output");
1027     return -1;
1028   }
1029
1030   if (pipecmd) {
1031     close (1);
1032     if (dup2 (stdout_saved_fd, 1) < 0) {
1033       perror ("failed to dup2 standard output");
1034       r = -1;
1035     }
1036     close (stdout_saved_fd);
1037     if (waitpid (pid, NULL, 0) < 0) {
1038       perror ("waiting for command to complete");
1039       r = -1;
1040     }
1041   }
1042
1043   return r;
1044 }
1045
1046 void
1047 list_builtin_commands (void)
1048 {
1049   /* help and quit should appear at the top */
1050   printf ("%-20s %s\n",
1051           "help", _("display a list of commands or help on a command"));
1052   printf ("%-20s %s\n",
1053           "quit", _("quit guestfish"));
1054
1055   /* actions are printed after this (see list_commands) */
1056 }
1057
1058 int
1059 display_builtin_command (const char *cmd)
1060 {
1061   /* help for actions is auto-generated, see display_command */
1062
1063   if (STRCASEEQ (cmd, "help")) {
1064     printf (_("help - display a list of commands or help on a command\n"
1065               "     help cmd\n"
1066               "     help\n"));
1067     return 0;
1068   }
1069   else if (STRCASEEQ (cmd, "quit") ||
1070            STRCASEEQ (cmd, "exit") ||
1071            STRCASEEQ (cmd, "q")) {
1072     printf (_("quit - quit guestfish\n"
1073               "     quit\n"));
1074     return 0;
1075   }
1076   else {
1077     fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1078              cmd);
1079     return -1;
1080   }
1081 }
1082
1083 /* This is printed when the user types in an unknown command for the
1084  * first command issued.  A common case is the user doing:
1085  *   guestfish disk.img
1086  * expecting guestfish to open 'disk.img' (in fact, this tried to
1087  * run a command 'disk.img').
1088  */
1089 void
1090 extended_help_message (void)
1091 {
1092   fprintf (stderr,
1093            _("Did you mean to open a disk image?  guestfish -a disk.img\n"
1094              "For a list of commands:             guestfish -h\n"
1095              "For complete documentation:         man guestfish\n"));
1096 }
1097
1098 void
1099 free_strings (char **argv)
1100 {
1101   int argc;
1102
1103   for (argc = 0; argv[argc] != NULL; ++argc)
1104     free (argv[argc]);
1105   free (argv);
1106 }
1107
1108 int
1109 count_strings (char *const *argv)
1110 {
1111   int c;
1112
1113   for (c = 0; argv[c]; ++c)
1114     ;
1115   return c;
1116 }
1117
1118 void
1119 print_strings (char *const *argv)
1120 {
1121   int argc;
1122
1123   for (argc = 0; argv[argc] != NULL; ++argc)
1124     printf ("%s\n", argv[argc]);
1125 }
1126
1127 void
1128 print_table (char *const *argv)
1129 {
1130   int i;
1131
1132   for (i = 0; argv[i] != NULL; i += 2)
1133     printf ("%s: %s\n", argv[i], argv[i+1]);
1134 }
1135
1136 int
1137 is_true (const char *str)
1138 {
1139   return
1140     STRCASENEQ (str, "0") &&
1141     STRCASENEQ (str, "f") &&
1142     STRCASENEQ (str, "false") &&
1143     STRCASENEQ (str, "n") &&
1144     STRCASENEQ (str, "no");
1145 }
1146
1147 /* Free strings from a non-NULL terminated char** */
1148 static void
1149 free_n_strings (char **str, size_t len)
1150 {
1151   size_t i;
1152
1153   for (i = 0; i < len; i++) {
1154     free (str[i]);
1155   }
1156   free (str);
1157 }
1158
1159 char **
1160 parse_string_list (const char *str)
1161 {
1162   char **argv = NULL;
1163   size_t argv_len = 0;
1164
1165   /* Current position pointer */
1166   const char *p = str;
1167
1168   /* Token might be simple:
1169    *  Token
1170    * or be quoted:
1171    *  'This is a single token'
1172    * or contain embedded single-quoted sections:
1173    *  This' is a sing'l'e to'ken
1174    *
1175    * The latter may seem over-complicated, but it's what a normal shell does.
1176    * Not doing it risks surprising somebody.
1177    *
1178    * This outer loop is over complete tokens.
1179    */
1180   while (*p) {
1181     char *tok = NULL;
1182     size_t tok_len = 0;
1183
1184     /* Skip leading whitespace */
1185     p += strspn (p, " \t");
1186
1187     char in_quote = 0;
1188
1189     /* This loop is over token 'fragments'. A token can be in multiple bits if
1190      * it contains single quotes. We also treat both sides of an escaped quote
1191      * as separate fragments because we can't just copy it: we have to remove
1192      * the \.
1193      */
1194     while (*p && (!c_isblank (*p) || in_quote)) {
1195       const char *end = p;
1196
1197       /* Check if the fragment starts with a quote */
1198       if ('\'' == *p) {
1199         /* Toggle in_quote */
1200         in_quote = !in_quote;
1201
1202         /* Skip the quote */
1203         p++; end++;
1204       }
1205
1206       /* If we're in a quote, look for an end quote */
1207       if (in_quote) {
1208         end += strcspn (end, "'");
1209       }
1210
1211       /* Otherwise, look for whitespace or a quote */
1212       else {
1213         end += strcspn (end, " \t'");
1214       }
1215
1216       /* Grow the token to accommodate the fragment */
1217       size_t tok_end = tok_len;
1218       tok_len += end - p;
1219       char *tok_new = realloc (tok, tok_len + 1);
1220       if (NULL == tok_new) {
1221         perror ("realloc");
1222         free_n_strings (argv, argv_len);
1223         free (tok);
1224         exit (EXIT_FAILURE);
1225       }
1226       tok = tok_new;
1227
1228       /* Check if we stopped on an escaped quote */
1229       if ('\'' == *end && end != p && *(end-1) == '\\') {
1230         /* Add everything before \' to the token */
1231         memcpy (&tok[tok_end], p, end - p - 1);
1232
1233         /* Add the quote */
1234         tok[tok_len-1] = '\'';
1235
1236         /* Already processed the quote */
1237         p = end + 1;
1238       }
1239
1240       else {
1241         /* Add the whole fragment */
1242         memcpy (&tok[tok_end], p, end - p);
1243
1244         p = end;
1245       }
1246     }
1247
1248     /* We've reached the end of a token. We shouldn't still be in quotes. */
1249     if (in_quote) {
1250       fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1251
1252       free_n_strings (argv, argv_len);
1253
1254       return NULL;
1255     }
1256
1257     /* Add this token if there is one. There might not be if there was
1258      * whitespace at the end of the input string */
1259     if (tok) {
1260       /* Add the NULL terminator */
1261       tok[tok_len] = '\0';
1262
1263       /* Add the argument to the argument list */
1264       argv_len++;
1265       char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1266       if (NULL == argv_new) {
1267         perror ("realloc");
1268         free_n_strings (argv, argv_len-1);
1269         free (tok);
1270         exit (EXIT_FAILURE);
1271       }
1272       argv = argv_new;
1273
1274       argv[argv_len-1] = tok;
1275     }
1276   }
1277
1278   /* NULL terminate the argument list */
1279   argv_len++;
1280   char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1281   if (NULL == argv_new) {
1282     perror ("realloc");
1283     free_n_strings (argv, argv_len-1);
1284     exit (EXIT_FAILURE);
1285   }
1286   argv = argv_new;
1287
1288   argv[argv_len-1] = NULL;
1289
1290   return argv;
1291 }
1292
1293 #ifdef HAVE_LIBREADLINE
1294 static char histfile[1024];
1295 static int nr_history_lines = 0;
1296 #endif
1297
1298 static void
1299 initialize_readline (void)
1300 {
1301 #ifdef HAVE_LIBREADLINE
1302   const char *home;
1303
1304   home = getenv ("HOME");
1305   if (home) {
1306     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1307     using_history ();
1308     (void) read_history (histfile);
1309   }
1310
1311   rl_readline_name = "guestfish";
1312   rl_attempted_completion_function = do_completion;
1313
1314   /* Note that .inputrc (or /etc/inputrc) is not read until the first
1315    * call the readline(), which happens later.  Therefore, these
1316    * provide default values which can be overridden by the user if
1317    * they wish.
1318    */
1319   (void) rl_variable_bind ("completion-ignore-case", "on");
1320 #endif
1321 }
1322
1323 static void
1324 cleanup_readline (void)
1325 {
1326 #ifdef HAVE_LIBREADLINE
1327   int fd;
1328
1329   if (histfile[0] != '\0') {
1330     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1331     if (fd == -1) {
1332       perror (histfile);
1333       return;
1334     }
1335     close (fd);
1336
1337 #ifdef HAVE_APPEND_HISTORY
1338     (void) append_history (nr_history_lines, histfile);
1339 #else
1340     (void) write_history (histfile);
1341 #endif
1342     clear_history ();
1343   }
1344 #endif
1345 }
1346
1347 #ifdef HAVE_LIBREADLINE
1348 static void
1349 add_history_line (const char *line)
1350 {
1351   add_history (line);
1352   nr_history_lines++;
1353 }
1354 #endif
1355
1356 int
1357 xwrite (int fd, const void *v_buf, size_t len)
1358 {
1359   int r;
1360   const char *buf = v_buf;
1361
1362   while (len > 0) {
1363     r = write (fd, buf, len);
1364     if (r == -1) {
1365       perror ("write");
1366       return -1;
1367     }
1368     buf += r;
1369     len -= r;
1370   }
1371
1372   return 0;
1373 }
1374
1375 /* Resolve the special "win:..." form for Windows-specific paths.
1376  * This always returns a newly allocated string which is freed by the
1377  * caller function in "cmds.c".
1378  */
1379 char *
1380 resolve_win_path (const char *path)
1381 {
1382   char *ret;
1383   size_t i;
1384
1385   if (STRCASENEQLEN (path, "win:", 4)) {
1386     ret = strdup (path);
1387     if (ret == NULL)
1388       perror ("strdup");
1389     return ret;
1390   }
1391
1392   path += 4;
1393
1394   /* Drop drive letter, if it's "C:". */
1395   if (STRCASEEQLEN (path, "c:", 2))
1396     path += 2;
1397
1398   if (!*path) {
1399     ret = strdup ("/");
1400     if (ret == NULL)
1401       perror ("strdup");
1402     return ret;
1403   }
1404
1405   ret = strdup (path);
1406   if (ret == NULL) {
1407     perror ("strdup");
1408     return NULL;
1409   }
1410
1411   /* Blindly convert any backslashes into forward slashes.  Is this good? */
1412   for (i = 0; i < strlen (ret); ++i)
1413     if (ret[i] == '\\')
1414       ret[i] = '/';
1415
1416   char *t = guestfs_case_sensitive_path (g, ret);
1417   free (ret);
1418   ret = t;
1419
1420   return ret;
1421 }
1422
1423 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1424  * The caller (cmds.c) will call free_file_in after the command has
1425  * run which should clean up resources.
1426  */
1427 static char *file_in_heredoc (const char *endmarker);
1428 static char *file_in_tmpfile = NULL;
1429
1430 char *
1431 file_in (const char *arg)
1432 {
1433   char *ret;
1434
1435   if (STREQ (arg, "-")) {
1436     ret = strdup ("/dev/stdin");
1437     if (!ret) {
1438       perror ("strdup");
1439       return NULL;
1440     }
1441   }
1442   else if (STRPREFIX (arg, "-<<")) {
1443     const char *endmarker = &arg[3];
1444     if (*endmarker == '\0') {
1445       fprintf (stderr, "%s: missing end marker in -<< expression\n",
1446                program_name);
1447       return NULL;
1448     }
1449     ret = file_in_heredoc (endmarker);
1450     if (ret == NULL)
1451       return NULL;
1452   }
1453   else {
1454     ret = strdup (arg);
1455     if (!ret) {
1456       perror ("strdup");
1457       return NULL;
1458     }
1459   }
1460
1461   return ret;
1462 }
1463
1464 static char *
1465 file_in_heredoc (const char *endmarker)
1466 {
1467   TMP_TEMPLATE_ON_STACK (template);
1468   file_in_tmpfile = strdup (template);
1469   if (file_in_tmpfile == NULL) {
1470     perror ("strdup");
1471     return NULL;
1472   }
1473
1474   int fd = mkstemp (file_in_tmpfile);
1475   if (fd == -1) {
1476     perror ("mkstemp");
1477     goto error1;
1478   }
1479
1480   size_t markerlen = strlen (endmarker);
1481
1482   char buffer[BUFSIZ];
1483   int write_error = 0;
1484   while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1485     /* Look for "END"<EOF> or "END\n" in input. */
1486     size_t blen = strlen (buffer);
1487     if (STREQLEN (buffer, endmarker, markerlen) &&
1488         (blen == markerlen ||
1489          (blen == markerlen+1 && buffer[markerlen] == '\n')))
1490       goto found_end;
1491
1492     if (xwrite (fd, buffer, blen) == -1) {
1493       if (!write_error) perror ("write");
1494       write_error = 1;
1495       /* continue reading up to the end marker */
1496     }
1497   }
1498
1499   /* Reached EOF of stdin without finding the end marker, which
1500    * is likely to be an error.
1501    */
1502   fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1503            program_name, endmarker);
1504   goto error2;
1505
1506  found_end:
1507   if (write_error) {
1508     close (fd);
1509     goto error2;
1510   }
1511
1512   if (close (fd) == -1) {
1513     perror ("close");
1514     goto error2;
1515   }
1516
1517   return file_in_tmpfile;
1518
1519  error2:
1520   unlink (file_in_tmpfile);
1521
1522  error1:
1523   free (file_in_tmpfile);
1524   file_in_tmpfile = NULL;
1525   return NULL;
1526 }
1527
1528 void
1529 free_file_in (char *s)
1530 {
1531   if (file_in_tmpfile) {
1532     if (unlink (file_in_tmpfile) == -1)
1533       perror (file_in_tmpfile);
1534     file_in_tmpfile = NULL;
1535   }
1536
1537   /* Free the device or file name which was strdup'd in file_in().
1538    * Note it's not immediately clear, but for -<< heredocs,
1539    * s == file_in_tmpfile, so this frees up that buffer.
1540    */
1541   free (s);
1542 }
1543
1544 /* Resolve the special FileOut paths ("-" or filename).
1545  * The caller (cmds.c) will call free (str) after the command has run.
1546  */
1547 char *
1548 file_out (const char *arg)
1549 {
1550   char *ret;
1551
1552   if (STREQ (arg, "-"))
1553     ret = strdup ("/dev/stdout");
1554   else
1555     ret = strdup (arg);
1556
1557   if (!ret) {
1558     perror ("strdup");
1559     return NULL;
1560   }
1561   return ret;
1562 }