fish: Add --rw option (does nothing yet).
[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?Vwx";
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     { "rw", 0, 0, 'w' },
176     { "selinux", 0, 0, 0 },
177     { "verbose", 0, 0, 'v' },
178     { "version", 0, 0, 'V' },
179     { 0, 0, 0, 0 }
180   };
181   struct drv *drvs = NULL;
182   struct drv *drv;
183   struct mp *mps = NULL;
184   struct mp *mp;
185   char *p, *file = NULL;
186   const char *format = NULL;
187   int c;
188   int option_index;
189   struct sigaction sa;
190   int next_prepared_drive = 1;
191
192   initialize_readline ();
193
194   memset (&sa, 0, sizeof sa);
195   sa.sa_handler = SIG_IGN;
196   sa.sa_flags = SA_RESTART;
197   sigaction (SIGPIPE, &sa, NULL);
198
199   /* guestfs_create is meant to be a lightweight operation, so
200    * it's OK to do it early here.
201    */
202   g = guestfs_create ();
203   if (g == NULL) {
204     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
205     exit (EXIT_FAILURE);
206   }
207
208   /* If developing, add ./appliance to the path.  Note that libtools
209    * interferes with this because uninstalled guestfish is a shell
210    * script that runs the real program with an absolute path.  Detect
211    * that too.
212    *
213    * BUT if LIBGUESTFS_PATH environment variable is already set by
214    * the user, then don't override it.
215    */
216   if (getenv ("LIBGUESTFS_PATH") == NULL &&
217       argv[0] &&
218       (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
219     guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
220
221   /* CAUTION: we are careful to modify argv[0] here, only after
222    * using it just above.
223    *
224    * getopt_long uses argv[0], so give it the sanitized name.  Save a copy
225    * of the original, in case it's needed below.
226    */
227   char *real_argv0 = argv[0];
228   argv[0] = bad_cast (program_name);
229
230   for (;;) {
231     c = getopt_long (argc, argv, options, long_options, &option_index);
232     if (c == -1) break;
233
234     switch (c) {
235     case 0:                     /* options which are long only */
236       if (STREQ (long_options[option_index].name, "listen"))
237         remote_control_listen = 1;
238       else if (STREQ (long_options[option_index].name, "remote")) {
239         if (optarg) {
240           if (sscanf (optarg, "%d", &remote_control) != 1) {
241             fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
242                      program_name, optarg);
243             exit (EXIT_FAILURE);
244           }
245         } else {
246           p = getenv ("GUESTFISH_PID");
247           if (!p || sscanf (p, "%d", &remote_control) != 1) {
248             fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
249                                " to the PID of the remote process\n"),
250                      program_name);
251             exit (EXIT_FAILURE);
252           }
253         }
254       } else if (STREQ (long_options[option_index].name, "selinux")) {
255         guestfs_set_selinux (g, 1);
256       } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
257         keys_from_stdin = 1;
258       } else if (STREQ (long_options[option_index].name, "progress-bars")) {
259         override_progress_bars = 1;
260       } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
261         override_progress_bars = 0;
262       } else if (STREQ (long_options[option_index].name, "echo-keys")) {
263         echo_keys = 1;
264       } else if (STREQ (long_options[option_index].name, "format")) {
265         if (!optarg || STREQ (optarg, ""))
266           format = NULL;
267         else
268           format = optarg;
269       } else if (STREQ (long_options[option_index].name, "csh")) {
270         remote_control_csh = 1;
271       } else {
272         fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
273                  program_name, long_options[option_index].name, option_index);
274         exit (EXIT_FAILURE);
275       }
276       break;
277
278     case 'a':
279       OPTION_a;
280       break;
281
282     case 'c':
283       OPTION_c;
284       break;
285
286     case 'd':
287       OPTION_d;
288       break;
289
290     case 'D':
291       complete_dest_paths = 0;
292       break;
293
294     case 'f':
295       if (file) {
296         fprintf (stderr, _("%s: only one -f parameter can be given\n"),
297                  program_name);
298         exit (EXIT_FAILURE);
299       }
300       file = optarg;
301       break;
302
303     case 'h': {
304       int r = 0;
305
306       if (optarg)
307         r = display_command (optarg);
308       else if (argv[optind] && argv[optind][0] != '-')
309         r = display_command (argv[optind++]);
310       else
311         list_commands ();
312
313       exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
314     }
315
316     case 'i':
317       OPTION_i;
318       break;
319
320     case 'm':
321       OPTION_m;
322       break;
323
324     case 'n':
325       OPTION_n;
326       break;
327
328     case 'N':
329       if (STRCASEEQ (optarg, "list") ||
330           STRCASEEQ (optarg, "help") ||
331           STRCASEEQ (optarg, "h") ||
332           STRCASEEQ (optarg, "?")) {
333         list_prepared_drives ();
334         exit (EXIT_SUCCESS);
335       }
336       drv = malloc (sizeof (struct drv));
337       if (!drv) {
338         perror ("malloc");
339         exit (EXIT_FAILURE);
340       }
341       drv->type = drv_N;
342       if (asprintf (&drv->N.filename, "test%d.img",
343                     next_prepared_drive++) == -1) {
344         perror ("asprintf");
345         exit (EXIT_FAILURE);
346       }
347       drv->N.data = create_prepared_file (optarg, drv->N.filename);
348       drv->N.data_free = free_prep_data;
349       drv->N.device = NULL;     /* filled in by add_drives */
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 void
534 pod2text (const char *name, const char *shortdesc, const char *str)
535 {
536   FILE *fp;
537
538   fp = popen ("pod2text", "w");
539   if (fp == NULL) {
540     /* pod2text failed, maybe not found, so let's just print the
541      * source instead, since that's better than doing nothing.
542      */
543     printf ("%s - %s\n\n%s\n", name, shortdesc, str);
544     return;
545   }
546   fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
547   fputs (str, fp);
548   pclose (fp);
549 }
550
551 static void
552 prepare_drives (struct drv *drv)
553 {
554   if (drv) {
555     prepare_drives (drv->next);
556     if (drv->type == drv_N)
557       prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
558   }
559 }
560
561 static int
562 launch (void)
563 {
564   if (guestfs_is_config (g)) {
565     if (guestfs_launch (g) == -1)
566       return -1;
567   }
568   return 0;
569 }
570
571 static void
572 interactive (void)
573 {
574   script (1);
575 }
576
577 static void
578 shell_script (void)
579 {
580   script (0);
581 }
582
583 #define FISH "><fs> "
584
585 static char *line_read = NULL;
586
587 static char *
588 rl_gets (int prompt)
589 {
590 #ifdef HAVE_LIBREADLINE
591
592   if (prompt) {
593     if (line_read) {
594       free (line_read);
595       line_read = NULL;
596     }
597
598     line_read = readline (prompt ? FISH : "");
599
600     if (line_read && *line_read)
601       add_history_line (line_read);
602
603     return line_read;
604   }
605
606 #endif /* HAVE_LIBREADLINE */
607
608   static char buf[8192];
609   int len;
610
611   if (prompt) printf (FISH);
612   line_read = fgets (buf, sizeof buf, stdin);
613
614   if (line_read) {
615     len = strlen (line_read);
616     if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
617   }
618
619   return line_read;
620 }
621
622 static void
623 script (int prompt)
624 {
625   char *buf;
626   char *cmd;
627   char *p, *pend;
628   char *argv[64];
629   int len;
630   int global_exit_on_error = !prompt;
631   int tilde_candidate;
632
633   if (prompt) {
634     printf (_("\n"
635               "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
636               "editing virtual machine filesystems.\n"
637               "\n"
638               "Type: 'help' for help on commands\n"
639               "      'man' to read the manual\n"
640               "      'quit' to quit the shell\n"
641               "\n"));
642
643     if (inspector) {
644       print_inspect_prompt ();
645       printf ("\n");
646     }
647   }
648
649   while (!quit) {
650     char *pipe = NULL;
651
652     exit_on_error = global_exit_on_error;
653
654     buf = rl_gets (prompt);
655     if (!buf) {
656       quit = 1;
657       break;
658     }
659
660     /* Skip any initial whitespace before the command. */
661   again:
662     while (*buf && c_isspace (*buf))
663       buf++;
664
665     if (!*buf) continue;
666
667     /* If the next character is '#' then this is a comment. */
668     if (*buf == '#') continue;
669
670     /* If the next character is '!' then pass the whole lot to system(3). */
671     if (*buf == '!') {
672       int r;
673
674       r = system (buf+1);
675       if (exit_on_error) {
676         if (r == -1 ||
677             (WIFSIGNALED (r) &&
678              (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
679             WEXITSTATUS (r) != 0)
680           exit (EXIT_FAILURE);
681       }
682       continue;
683     }
684
685     /* If the next character is '-' allow the command to fail without
686      * exiting on error (just for this one command though).
687      */
688     if (*buf == '-') {
689       exit_on_error = 0;
690       buf++;
691       goto again;
692     }
693
694     /* Get the command (cannot be quoted). */
695     len = strcspn (buf, " \t");
696
697     if (len == 0) continue;
698
699     cmd = buf;
700     unsigned int i = 0;
701     if (buf[len] == '\0') {
702       argv[0] = NULL;
703       goto got_command;
704     }
705
706     buf[len] = '\0';
707     p = &buf[len+1];
708     p += strspn (p, " \t");
709
710     /* Get the parameters. */
711     while (*p && i < sizeof argv / sizeof argv[0]) {
712       tilde_candidate = 0;
713
714       /* Parameters which start with quotes or pipes are treated
715        * specially.  Bare parameters are delimited by whitespace.
716        */
717       if (*p == '"') {
718         p++;
719         len = strcspn (p, "\"");
720         if (p[len] == '\0') {
721           fprintf (stderr, _("%s: unterminated double 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++;
736         len = strcspn (p, "'");
737         if (p[len] == '\0') {
738           fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
739           if (exit_on_error) exit (EXIT_FAILURE);
740           goto next_command;
741         }
742         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
743           fprintf (stderr,
744                    _("%s: command arguments not separated by whitespace\n"),
745                    program_name);
746           if (exit_on_error) exit (EXIT_FAILURE);
747           goto next_command;
748         }
749         p[len] = '\0';
750         pend = p[len+1] ? &p[len+2] : &p[len+1];
751       } else if (*p == '|') {
752         *p = '\0';
753         pipe = p+1;
754         continue;
755         /*
756       } else if (*p == '[') {
757         int c = 1;
758         p++;
759         pend = p;
760         while (*pend && c != 0) {
761           if (*pend == '[') c++;
762           else if (*pend == ']') c--;
763           pend++;
764         }
765         if (c != 0) {
766           fprintf (stderr,
767                    _("%s: unterminated \"[...]\" sequence\n"), program_name);
768           if (exit_on_error) exit (EXIT_FAILURE);
769           goto next_command;
770         }
771         if (*pend && (*pend != ' ' && *pend != '\t')) {
772           fprintf (stderr,
773                    _("%s: command arguments not separated by whitespace\n"),
774                    program_name);
775           if (exit_on_error) exit (EXIT_FAILURE);
776           goto next_command;
777         }
778         *(pend-1) = '\0';
779         */
780       } else if (*p != ' ' && *p != '\t') {
781         /* If the first character is a ~ then note that this parameter
782          * is a candidate for ~username expansion.  NB this does not
783          * apply to quoted parameters.
784          */
785         tilde_candidate = *p == '~';
786         len = strcspn (p, " \t");
787         if (p[len]) {
788           p[len] = '\0';
789           pend = &p[len+1];
790         } else
791           pend = &p[len];
792       } else {
793         fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
794                  program_name, p);
795         abort ();
796       }
797
798       if (!tilde_candidate)
799         argv[i] = p;
800       else
801         argv[i] = try_tilde_expansion (p);
802       i++;
803       p = pend;
804
805       if (*p)
806         p += strspn (p, " \t");
807     }
808
809     if (i == sizeof argv / sizeof argv[0]) {
810       fprintf (stderr, _("%s: too many arguments\n"), program_name);
811       if (exit_on_error) exit (EXIT_FAILURE);
812       goto next_command;
813     }
814
815     argv[i] = NULL;
816
817   got_command:
818     if (issue_command (cmd, argv, pipe) == -1) {
819       if (exit_on_error) exit (EXIT_FAILURE);
820     }
821
822   next_command:;
823   }
824   if (prompt) printf ("\n");
825 }
826
827 static void
828 cmdline (char *argv[], int optind, int argc)
829 {
830   const char *cmd;
831   char **params;
832
833   exit_on_error = 1;
834
835   if (optind >= argc) return;
836
837   cmd = argv[optind++];
838   if (STREQ (cmd, ":")) {
839     fprintf (stderr, _("%s: empty command on command line\n"), program_name);
840     exit (EXIT_FAILURE);
841   }
842
843   /* Allow -cmd on the command line to mean (temporarily) override
844    * the normal exit on error (RHBZ#578407).
845    */
846   if (cmd[0] == '-') {
847     exit_on_error = 0;
848     cmd++;
849   }
850
851   params = &argv[optind];
852
853   /* Search for end of command list or ":" ... */
854   while (optind < argc && STRNEQ (argv[optind], ":"))
855     optind++;
856
857   if (optind == argc) {
858     if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
859         exit (EXIT_FAILURE);
860   } else {
861     argv[optind] = NULL;
862     if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
863       exit (EXIT_FAILURE);
864     cmdline (argv, optind+1, argc);
865   }
866 }
867
868 int
869 issue_command (const char *cmd, char *argv[], const char *pipecmd)
870 {
871   int argc;
872   int stdout_saved_fd = -1;
873   int pid = 0;
874   int i, r;
875
876   reset_progress_bar ();
877
878   /* This counts the commands issued, starting at 1. */
879   command_num++;
880
881   /* For | ... commands.  Annoyingly we can't use popen(3) here. */
882   if (pipecmd) {
883     int fd[2];
884
885     if (fflush (stdout) == EOF) {
886       perror ("failed to flush standard output");
887       return -1;
888     }
889     if (pipe (fd) < 0) {
890       perror ("pipe failed");
891       return -1;
892     }
893     pid = fork ();
894     if (pid == -1) {
895       perror ("fork");
896       return -1;
897     }
898
899     if (pid == 0) {             /* Child process. */
900       close (fd[1]);
901       if (dup2 (fd[0], 0) < 0) {
902         perror ("dup2 of stdin failed");
903         _exit (1);
904       }
905
906       r = system (pipecmd);
907       if (r == -1) {
908         perror (pipecmd);
909         _exit (1);
910       }
911       _exit (WEXITSTATUS (r));
912     }
913
914     if ((stdout_saved_fd = dup (1)) < 0) {
915       perror ("failed to dup stdout");
916       return -1;
917     }
918     close (fd[0]);
919     if (dup2 (fd[1], 1) < 0) {
920       perror ("failed to dup stdout");
921       close (stdout_saved_fd);
922       return -1;
923     }
924     close (fd[1]);
925   }
926
927   for (argc = 0; argv[argc] != NULL; ++argc)
928     ;
929
930   /* If --remote was set, then send this command to a remote process. */
931   if (remote_control)
932     r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
933
934   /* Otherwise execute it locally. */
935   else if (STRCASEEQ (cmd, "help")) {
936     if (argc == 0) {
937       display_help ();
938       r = 0;
939     } else
940       r = display_command (argv[0]);
941   }
942   else if (STRCASEEQ (cmd, "quit") ||
943            STRCASEEQ (cmd, "exit") ||
944            STRCASEEQ (cmd, "q")) {
945     quit = 1;
946     r = 0;
947   }
948   else
949     r = run_action (cmd, argc, argv);
950
951   /* Always flush stdout after every command, so that messages, results
952    * etc appear immediately.
953    */
954   if (fflush (stdout) == EOF) {
955     perror ("failed to flush standard output");
956     return -1;
957   }
958
959   if (pipecmd) {
960     close (1);
961     if (dup2 (stdout_saved_fd, 1) < 0) {
962       perror ("failed to dup2 standard output");
963       r = -1;
964     }
965     close (stdout_saved_fd);
966     if (waitpid (pid, NULL, 0) < 0) {
967       perror ("waiting for command to complete");
968       r = -1;
969     }
970   }
971
972   return r;
973 }
974
975 void
976 list_builtin_commands (void)
977 {
978   /* help and quit should appear at the top */
979   printf ("%-20s %s\n",
980           "help", _("display a list of commands or help on a command"));
981   printf ("%-20s %s\n",
982           "quit", _("quit guestfish"));
983
984   /* actions are printed after this (see list_commands) */
985 }
986
987 int
988 display_builtin_command (const char *cmd)
989 {
990   /* help for actions is auto-generated, see display_command */
991
992   if (STRCASEEQ (cmd, "help")) {
993     printf (_("help - display a list of commands or help on a command\n"
994               "     help cmd\n"
995               "     help\n"));
996     return 0;
997   }
998   else if (STRCASEEQ (cmd, "quit") ||
999            STRCASEEQ (cmd, "exit") ||
1000            STRCASEEQ (cmd, "q")) {
1001     printf (_("quit - quit guestfish\n"
1002               "     quit\n"));
1003     return 0;
1004   }
1005   else {
1006     fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1007              cmd);
1008     return -1;
1009   }
1010 }
1011
1012 /* This is printed when the user types in an unknown command for the
1013  * first command issued.  A common case is the user doing:
1014  *   guestfish disk.img
1015  * expecting guestfish to open 'disk.img' (in fact, this tried to
1016  * run a command 'disk.img').
1017  */
1018 void
1019 extended_help_message (void)
1020 {
1021   fprintf (stderr,
1022            _("Did you mean to open a disk image?  guestfish -a disk.img\n"
1023              "For a list of commands:             guestfish -h\n"
1024              "For complete documentation:         man guestfish\n"));
1025 }
1026
1027 void
1028 free_strings (char **argv)
1029 {
1030   int argc;
1031
1032   for (argc = 0; argv[argc] != NULL; ++argc)
1033     free (argv[argc]);
1034   free (argv);
1035 }
1036
1037 int
1038 count_strings (char *const *argv)
1039 {
1040   int c;
1041
1042   for (c = 0; argv[c]; ++c)
1043     ;
1044   return c;
1045 }
1046
1047 void
1048 print_strings (char *const *argv)
1049 {
1050   int argc;
1051
1052   for (argc = 0; argv[argc] != NULL; ++argc)
1053     printf ("%s\n", argv[argc]);
1054 }
1055
1056 void
1057 print_table (char *const *argv)
1058 {
1059   int i;
1060
1061   for (i = 0; argv[i] != NULL; i += 2)
1062     printf ("%s: %s\n", argv[i], argv[i+1]);
1063 }
1064
1065 int
1066 is_true (const char *str)
1067 {
1068   return
1069     STRCASENEQ (str, "0") &&
1070     STRCASENEQ (str, "f") &&
1071     STRCASENEQ (str, "false") &&
1072     STRCASENEQ (str, "n") &&
1073     STRCASENEQ (str, "no");
1074 }
1075
1076 /* Free strings from a non-NULL terminated char** */
1077 static void
1078 free_n_strings (char **str, size_t len)
1079 {
1080   size_t i;
1081
1082   for (i = 0; i < len; i++) {
1083     free (str[i]);
1084   }
1085   free (str);
1086 }
1087
1088 char **
1089 parse_string_list (const char *str)
1090 {
1091   char **argv = NULL;
1092   size_t argv_len = 0;
1093
1094   /* Current position pointer */
1095   const char *p = str;
1096
1097   /* Token might be simple:
1098    *  Token
1099    * or be quoted:
1100    *  'This is a single token'
1101    * or contain embedded single-quoted sections:
1102    *  This' is a sing'l'e to'ken
1103    *
1104    * The latter may seem over-complicated, but it's what a normal shell does.
1105    * Not doing it risks surprising somebody.
1106    *
1107    * This outer loop is over complete tokens.
1108    */
1109   while (*p) {
1110     char *tok = NULL;
1111     size_t tok_len = 0;
1112
1113     /* Skip leading whitespace */
1114     p += strspn (p, " \t");
1115
1116     char in_quote = 0;
1117
1118     /* This loop is over token 'fragments'. A token can be in multiple bits if
1119      * it contains single quotes. We also treat both sides of an escaped quote
1120      * as separate fragments because we can't just copy it: we have to remove
1121      * the \.
1122      */
1123     while (*p && (!c_isblank (*p) || in_quote)) {
1124       const char *end = p;
1125
1126       /* Check if the fragment starts with a quote */
1127       if ('\'' == *p) {
1128         /* Toggle in_quote */
1129         in_quote = !in_quote;
1130
1131         /* Skip the quote */
1132         p++; end++;
1133       }
1134
1135       /* If we're in a quote, look for an end quote */
1136       if (in_quote) {
1137         end += strcspn (end, "'");
1138       }
1139
1140       /* Otherwise, look for whitespace or a quote */
1141       else {
1142         end += strcspn (end, " \t'");
1143       }
1144
1145       /* Grow the token to accommodate the fragment */
1146       size_t tok_end = tok_len;
1147       tok_len += end - p;
1148       char *tok_new = realloc (tok, tok_len + 1);
1149       if (NULL == tok_new) {
1150         perror ("realloc");
1151         free_n_strings (argv, argv_len);
1152         free (tok);
1153         exit (EXIT_FAILURE);
1154       }
1155       tok = tok_new;
1156
1157       /* Check if we stopped on an escaped quote */
1158       if ('\'' == *end && end != p && *(end-1) == '\\') {
1159         /* Add everything before \' to the token */
1160         memcpy (&tok[tok_end], p, end - p - 1);
1161
1162         /* Add the quote */
1163         tok[tok_len-1] = '\'';
1164
1165         /* Already processed the quote */
1166         p = end + 1;
1167       }
1168
1169       else {
1170         /* Add the whole fragment */
1171         memcpy (&tok[tok_end], p, end - p);
1172
1173         p = end;
1174       }
1175     }
1176
1177     /* We've reached the end of a token. We shouldn't still be in quotes. */
1178     if (in_quote) {
1179       fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1180
1181       free_n_strings (argv, argv_len);
1182
1183       return NULL;
1184     }
1185
1186     /* Add this token if there is one. There might not be if there was
1187      * whitespace at the end of the input string */
1188     if (tok) {
1189       /* Add the NULL terminator */
1190       tok[tok_len] = '\0';
1191
1192       /* Add the argument to the argument list */
1193       argv_len++;
1194       char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1195       if (NULL == argv_new) {
1196         perror ("realloc");
1197         free_n_strings (argv, argv_len-1);
1198         free (tok);
1199         exit (EXIT_FAILURE);
1200       }
1201       argv = argv_new;
1202
1203       argv[argv_len-1] = tok;
1204     }
1205   }
1206
1207   /* NULL terminate the argument list */
1208   argv_len++;
1209   char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1210   if (NULL == argv_new) {
1211     perror ("realloc");
1212     free_n_strings (argv, argv_len-1);
1213     exit (EXIT_FAILURE);
1214   }
1215   argv = argv_new;
1216
1217   argv[argv_len-1] = NULL;
1218
1219   return argv;
1220 }
1221
1222 #ifdef HAVE_LIBREADLINE
1223 static char histfile[1024];
1224 static int nr_history_lines = 0;
1225 #endif
1226
1227 static void
1228 initialize_readline (void)
1229 {
1230 #ifdef HAVE_LIBREADLINE
1231   const char *home;
1232
1233   home = getenv ("HOME");
1234   if (home) {
1235     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1236     using_history ();
1237     (void) read_history (histfile);
1238   }
1239
1240   rl_readline_name = "guestfish";
1241   rl_attempted_completion_function = do_completion;
1242
1243   /* Note that .inputrc (or /etc/inputrc) is not read until the first
1244    * call the readline(), which happens later.  Therefore, these
1245    * provide default values which can be overridden by the user if
1246    * they wish.
1247    */
1248   (void) rl_variable_bind ("completion-ignore-case", "on");
1249 #endif
1250 }
1251
1252 static void
1253 cleanup_readline (void)
1254 {
1255 #ifdef HAVE_LIBREADLINE
1256   int fd;
1257
1258   if (histfile[0] != '\0') {
1259     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1260     if (fd == -1) {
1261       perror (histfile);
1262       return;
1263     }
1264     close (fd);
1265
1266 #ifdef HAVE_APPEND_HISTORY
1267     (void) append_history (nr_history_lines, histfile);
1268 #else
1269     (void) write_history (histfile);
1270 #endif
1271     clear_history ();
1272   }
1273 #endif
1274 }
1275
1276 #ifdef HAVE_LIBREADLINE
1277 static void
1278 add_history_line (const char *line)
1279 {
1280   add_history (line);
1281   nr_history_lines++;
1282 }
1283 #endif
1284
1285 int
1286 xwrite (int fd, const void *v_buf, size_t len)
1287 {
1288   int r;
1289   const char *buf = v_buf;
1290
1291   while (len > 0) {
1292     r = write (fd, buf, len);
1293     if (r == -1) {
1294       perror ("write");
1295       return -1;
1296     }
1297     buf += r;
1298     len -= r;
1299   }
1300
1301   return 0;
1302 }
1303
1304 /* Resolve the special "win:..." form for Windows-specific paths.
1305  * This always returns a newly allocated string which is freed by the
1306  * caller function in "cmds.c".
1307  */
1308 char *
1309 resolve_win_path (const char *path)
1310 {
1311   char *ret;
1312   size_t i;
1313
1314   if (STRCASENEQLEN (path, "win:", 4)) {
1315     ret = strdup (path);
1316     if (ret == NULL)
1317       perror ("strdup");
1318     return ret;
1319   }
1320
1321   path += 4;
1322
1323   /* Drop drive letter, if it's "C:". */
1324   if (STRCASEEQLEN (path, "c:", 2))
1325     path += 2;
1326
1327   if (!*path) {
1328     ret = strdup ("/");
1329     if (ret == NULL)
1330       perror ("strdup");
1331     return ret;
1332   }
1333
1334   ret = strdup (path);
1335   if (ret == NULL) {
1336     perror ("strdup");
1337     return NULL;
1338   }
1339
1340   /* Blindly convert any backslashes into forward slashes.  Is this good? */
1341   for (i = 0; i < strlen (ret); ++i)
1342     if (ret[i] == '\\')
1343       ret[i] = '/';
1344
1345   char *t = guestfs_case_sensitive_path (g, ret);
1346   free (ret);
1347   ret = t;
1348
1349   return ret;
1350 }
1351
1352 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1353  * The caller (cmds.c) will call free_file_in after the command has
1354  * run which should clean up resources.
1355  */
1356 static char *file_in_heredoc (const char *endmarker);
1357 static char *file_in_tmpfile = NULL;
1358
1359 char *
1360 file_in (const char *arg)
1361 {
1362   char *ret;
1363
1364   if (STREQ (arg, "-")) {
1365     ret = strdup ("/dev/stdin");
1366     if (!ret) {
1367       perror ("strdup");
1368       return NULL;
1369     }
1370   }
1371   else if (STRPREFIX (arg, "-<<")) {
1372     const char *endmarker = &arg[3];
1373     if (*endmarker == '\0') {
1374       fprintf (stderr, "%s: missing end marker in -<< expression\n",
1375                program_name);
1376       return NULL;
1377     }
1378     ret = file_in_heredoc (endmarker);
1379     if (ret == NULL)
1380       return NULL;
1381   }
1382   else {
1383     ret = strdup (arg);
1384     if (!ret) {
1385       perror ("strdup");
1386       return NULL;
1387     }
1388   }
1389
1390   return ret;
1391 }
1392
1393 static char *
1394 file_in_heredoc (const char *endmarker)
1395 {
1396   TMP_TEMPLATE_ON_STACK (template);
1397   file_in_tmpfile = strdup (template);
1398   if (file_in_tmpfile == NULL) {
1399     perror ("strdup");
1400     return NULL;
1401   }
1402
1403   int fd = mkstemp (file_in_tmpfile);
1404   if (fd == -1) {
1405     perror ("mkstemp");
1406     goto error1;
1407   }
1408
1409   size_t markerlen = strlen (endmarker);
1410
1411   char buffer[BUFSIZ];
1412   int write_error = 0;
1413   while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1414     /* Look for "END"<EOF> or "END\n" in input. */
1415     size_t blen = strlen (buffer);
1416     if (STREQLEN (buffer, endmarker, markerlen) &&
1417         (blen == markerlen ||
1418          (blen == markerlen+1 && buffer[markerlen] == '\n')))
1419       goto found_end;
1420
1421     if (xwrite (fd, buffer, blen) == -1) {
1422       if (!write_error) perror ("write");
1423       write_error = 1;
1424       /* continue reading up to the end marker */
1425     }
1426   }
1427
1428   /* Reached EOF of stdin without finding the end marker, which
1429    * is likely to be an error.
1430    */
1431   fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1432            program_name, endmarker);
1433   goto error2;
1434
1435  found_end:
1436   if (write_error) {
1437     close (fd);
1438     goto error2;
1439   }
1440
1441   if (close (fd) == -1) {
1442     perror ("close");
1443     goto error2;
1444   }
1445
1446   return file_in_tmpfile;
1447
1448  error2:
1449   unlink (file_in_tmpfile);
1450
1451  error1:
1452   free (file_in_tmpfile);
1453   file_in_tmpfile = NULL;
1454   return NULL;
1455 }
1456
1457 void
1458 free_file_in (char *s)
1459 {
1460   if (file_in_tmpfile) {
1461     if (unlink (file_in_tmpfile) == -1)
1462       perror (file_in_tmpfile);
1463     file_in_tmpfile = NULL;
1464   }
1465
1466   /* Free the device or file name which was strdup'd in file_in().
1467    * Note it's not immediately clear, but for -<< heredocs,
1468    * s == file_in_tmpfile, so this frees up that buffer.
1469    */
1470   free (s);
1471 }
1472
1473 /* Resolve the special FileOut paths ("-" or filename).
1474  * The caller (cmds.c) will call free (str) after the command has run.
1475  */
1476 char *
1477 file_out (const char *arg)
1478 {
1479   char *ret;
1480
1481   if (STREQ (arg, "-"))
1482     ret = strdup ("/dev/stdout");
1483   else
1484     ret = strdup (arg);
1485
1486   if (!ret) {
1487     perror ("strdup");
1488     return NULL;
1489   }
1490   return ret;
1491 }