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