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