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