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