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