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