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