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