maint: use EXIT_SUCCESS and EXIT_FAILURE, not 0 and 1 in "usage", too
[libguestfs.git] / fish / fish.c
1 /* guestfish - the filesystem interactive shell
2  * Copyright (C) 2009 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 <string.h>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <getopt.h>
27 #include <signal.h>
28 #include <assert.h>
29 #include <sys/types.h>
30 #include <sys/wait.h>
31
32 #ifdef HAVE_LIBREADLINE
33 #include <readline/readline.h>
34 #include <readline/history.h>
35 #endif
36
37 #include <guestfs.h>
38
39 #include "fish.h"
40 #include "c-ctype.h"
41 #include "closeout.h"
42 #include "progname.h"
43
44 struct mp {
45   struct mp *next;
46   char *device;
47   char *mountpoint;
48 };
49
50 struct drv {
51   struct drv *next;
52   char *filename;
53 };
54
55 static void add_drives (struct drv *drv);
56 static void mount_mps (struct mp *mp);
57 static void interactive (void);
58 static void shell_script (void);
59 static void script (int prompt);
60 static void cmdline (char *argv[], int optind, int argc);
61 static void initialize_readline (void);
62 static void cleanup_readline (void);
63 static void add_history_line (const char *);
64
65 /* Currently open libguestfs handle. */
66 guestfs_h *g;
67
68 int read_only = 0;
69 int quit = 0;
70 int verbose = 0;
71 int echo_commands = 0;
72 int remote_control_listen = 0;
73 int remote_control = 0;
74 int exit_on_error = 1;
75
76 int
77 launch (guestfs_h *_g)
78 {
79   assert (_g == g);
80
81   if (guestfs_is_config (g)) {
82     if (guestfs_launch (g) == -1)
83       return -1;
84   }
85   return 0;
86 }
87
88 static void __attribute__((noreturn))
89 usage (int status)
90 {
91   if (status != EXIT_SUCCESS)
92     fprintf (stderr, _("Try `%s --help' for more information.\n"),
93              program_name);
94   else {
95     fprintf (stdout,
96            _("%s: guest filesystem shell\n"
97              "%s lets you edit virtual machine filesystems\n"
98              "Copyright (C) 2009 Red Hat Inc.\n"
99              "Usage:\n"
100              "  %s [--options] cmd [: cmd : cmd ...]\n"
101              "  %s -i libvirt-domain\n"
102              "  %s -i disk-image(s)\n"
103              "or for interactive use:\n"
104              "  %s\n"
105              "or from a shell script:\n"
106              "  %s <<EOF\n"
107              "  cmd\n"
108              "  ...\n"
109              "  EOF\n"
110              "Options:\n"
111              "  -h|--cmd-help        List available commands\n"
112              "  -h|--cmd-help cmd    Display detailed help on 'cmd'\n"
113              "  -a|--add image       Add image\n"
114              "  -D|--no-dest-paths   Don't tab-complete paths from guest fs\n"
115              "  -f|--file file       Read commands from file\n"
116              "  -i|--inspector       Run virt-inspector to get disk mountpoints\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              "  --remote[=pid]       Send commands to remote %s\n"
121              "  -r|--ro              Mount read-only\n"
122              "  --selinux            Enable SELinux support\n"
123              "  -v|--verbose         Verbose messages\n"
124              "  -x                   Echo each command before executing it\n"
125              "  -V|--version         Display version and exit\n"
126              "For more information,  see the manpage %s(1).\n"),
127              program_name, program_name, program_name,
128              program_name, program_name, program_name,
129              program_name, program_name, program_name);
130   }
131   exit (status);
132 }
133
134 int
135 main (int argc, char *argv[])
136 {
137   /* Set global program name that is not polluted with libtool artifacts.  */
138   set_program_name (argv[0]);
139
140   atexit (close_stdout);
141
142   enum { HELP_OPTION = CHAR_MAX + 1 };
143
144   static const char *options = "a:Df:h::im:nrv?Vx";
145   static const struct option long_options[] = {
146     { "add", 1, 0, 'a' },
147     { "cmd-help", 2, 0, 'h' },
148     { "file", 1, 0, 'f' },
149     { "help", 0, 0, HELP_OPTION },
150     { "inspector", 0, 0, 'i' },
151     { "listen", 0, 0, 0 },
152     { "mount", 1, 0, 'm' },
153     { "no-dest-paths", 0, 0, 'D' },
154     { "no-sync", 0, 0, 'n' },
155     { "remote", 2, 0, 0 },
156     { "ro", 0, 0, 'r' },
157     { "selinux", 0, 0, 0 },
158     { "verbose", 0, 0, 'v' },
159     { "version", 0, 0, 'V' },
160     { 0, 0, 0, 0 }
161   };
162   struct drv *drvs = NULL;
163   struct drv *drv;
164   struct mp *mps = NULL;
165   struct mp *mp;
166   char *p, *file = NULL;
167   int c;
168   int inspector = 0;
169   int option_index;
170   struct sigaction sa;
171
172   initialize_readline ();
173
174   memset (&sa, 0, sizeof sa);
175   sa.sa_handler = SIG_IGN;
176   sa.sa_flags = SA_RESTART;
177   sigaction (SIGPIPE, &sa, NULL);
178
179   /* guestfs_create is meant to be a lightweight operation, so
180    * it's OK to do it early here.
181    */
182   g = guestfs_create ();
183   if (g == NULL) {
184     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
185     exit (EXIT_FAILURE);
186   }
187
188   guestfs_set_autosync (g, 1);
189
190   /* If developing, add ./appliance to the path.  Note that libtools
191    * interferes with this because uninstalled guestfish is a shell
192    * script that runs the real program with an absolute path.  Detect
193    * that too.
194    *
195    * BUT if LIBGUESTFS_PATH environment variable is already set by
196    * the user, then don't override it.
197    */
198   if (getenv ("LIBGUESTFS_PATH") == NULL &&
199       argv[0] &&
200       (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
201     guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
202
203   /* CAUTION: we are careful to modify argv[0] here, only after
204    * using it just above.
205    *
206    * getopt_long uses argv[0], so give it the sanitized name.  Save a copy
207    * of the original, in case it's needed in virt-inspector mode, below.
208    */
209   char *real_argv0 = argv[0];
210   argv[0] = bad_cast (program_name);
211
212   for (;;) {
213     c = getopt_long (argc, argv, options, long_options, &option_index);
214     if (c == -1) break;
215
216     switch (c) {
217     case 0:                     /* options which are long only */
218       if (STREQ (long_options[option_index].name, "listen"))
219         remote_control_listen = 1;
220       else if (STREQ (long_options[option_index].name, "remote")) {
221         if (optarg) {
222           if (sscanf (optarg, "%d", &remote_control) != 1) {
223             fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
224                      program_name, optarg);
225             exit (EXIT_FAILURE);
226           }
227         } else {
228           p = getenv ("GUESTFISH_PID");
229           if (!p || sscanf (p, "%d", &remote_control) != 1) {
230             fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
231                                " to the PID of the remote process\n"),
232                      program_name);
233             exit (EXIT_FAILURE);
234           }
235         }
236       } else if (STREQ (long_options[option_index].name, "selinux")) {
237         guestfs_set_selinux (g, 1);
238       } else {
239         fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
240                  program_name, long_options[option_index].name, option_index);
241         exit (EXIT_FAILURE);
242       }
243       break;
244
245     case 'a':
246       if (access (optarg, R_OK) != 0) {
247         perror (optarg);
248         exit (EXIT_FAILURE);
249       }
250       drv = malloc (sizeof (struct drv));
251       if (!drv) {
252         perror ("malloc");
253         exit (EXIT_FAILURE);
254       }
255       drv->filename = optarg;
256       drv->next = drvs;
257       drvs = drv;
258       break;
259
260     case 'D':
261       complete_dest_paths = 0;
262       break;
263
264     case 'f':
265       if (file) {
266         fprintf (stderr, _("%s: only one -f parameter can be given\n"),
267                  program_name);
268         exit (EXIT_FAILURE);
269       }
270       file = optarg;
271       break;
272
273     case 'h':
274       if (optarg)
275         display_command (optarg);
276       else if (argv[optind] && argv[optind][0] != '-')
277         display_command (argv[optind++]);
278       else
279         list_commands ();
280       exit (EXIT_SUCCESS);
281
282     case 'i':
283       inspector = 1;
284       break;
285
286     case 'm':
287       mp = malloc (sizeof (struct mp));
288       if (!mp) {
289         perror ("malloc");
290         exit (EXIT_FAILURE);
291       }
292       p = strchr (optarg, ':');
293       if (p) {
294         *p = '\0';
295         mp->mountpoint = p+1;
296       } else
297         mp->mountpoint = bad_cast ("/");
298       mp->device = optarg;
299       mp->next = mps;
300       mps = mp;
301       break;
302
303     case 'n':
304       guestfs_set_autosync (g, 0);
305       break;
306
307     case 'r':
308       read_only = 1;
309       break;
310
311     case 'v':
312       verbose++;
313       guestfs_set_verbose (g, verbose);
314       break;
315
316     case 'V':
317       printf ("%s %s\n", program_name, PACKAGE_VERSION);
318       exit (EXIT_SUCCESS);
319
320     case 'x':
321       echo_commands = 1;
322       break;
323
324     case HELP_OPTION:
325       usage (EXIT_SUCCESS);
326
327     default:
328       usage (EXIT_FAILURE);
329     }
330   }
331
332   /* Inspector mode invalidates most of the other arguments. */
333   if (inspector) {
334     char cmd[1024];
335     int r;
336
337     if (drvs || mps || remote_control_listen || remote_control ||
338         guestfs_get_selinux (g)) {
339       fprintf (stderr, _("%s: cannot use -i option with -a, -m,"
340                          " --listen, --remote or --selinux\n"),
341                program_name);
342       exit (EXIT_FAILURE);
343     }
344     if (optind >= argc) {
345       fprintf (stderr,
346            _("%s: -i requires a libvirt domain or path(s) to disk image(s)\n"),
347                program_name);
348       exit (EXIT_FAILURE);
349     }
350
351     strcpy (cmd, "a=`virt-inspector");
352     while (optind < argc) {
353       if (strlen (cmd) + strlen (argv[optind]) + strlen (real_argv0) + 60
354           >= sizeof cmd) {
355         fprintf (stderr,
356                  _("%s: virt-inspector command too long for fixed-size buffer\n"),
357                  program_name);
358         exit (EXIT_FAILURE);
359       }
360       strcat (cmd, " '");
361       strcat (cmd, argv[optind]);
362       strcat (cmd, "'");
363       optind++;
364     }
365
366     if (read_only)
367       strcat (cmd, " --ro-fish");
368     else
369       strcat (cmd, " --fish");
370
371     sprintf (&cmd[strlen(cmd)], "` && %s $a", real_argv0);
372
373     if (guestfs_get_verbose (g))
374       strcat (cmd, " -v");
375     if (!guestfs_get_autosync (g))
376       strcat (cmd, " -n");
377
378     if (verbose)
379       fprintf (stderr,
380                "%s -i: running virt-inspector command:\n%s\n", program_name, cmd);
381
382     r = system (cmd);
383     if (r == -1) {
384       perror ("system");
385       exit (EXIT_FAILURE);
386     }
387     exit (WEXITSTATUS (r));
388   }
389
390   /* If we've got drives to add, add them now. */
391   add_drives (drvs);
392
393   /* If we've got mountpoints, we must launch the guest and mount them. */
394   if (mps != NULL) {
395     if (launch (g) == -1) exit (EXIT_FAILURE);
396     mount_mps (mps);
397   }
398
399   /* Remote control? */
400   if (remote_control_listen && remote_control) {
401     fprintf (stderr,
402              _("%s: cannot use --listen and --remote options at the same time\n"),
403              program_name);
404     exit (EXIT_FAILURE);
405   }
406
407   if (remote_control_listen) {
408     if (optind < argc) {
409       fprintf (stderr,
410                _("%s: extra parameters on the command line with --listen flag\n"),
411                program_name);
412       exit (EXIT_FAILURE);
413     }
414     if (file) {
415       fprintf (stderr,
416                _("%s: cannot use --listen and --file options at the same time\n"),
417                program_name);
418       exit (EXIT_FAILURE);
419     }
420     rc_listen ();
421   }
422
423   /* -f (file) parameter? */
424   if (file) {
425     close (0);
426     if (open (file, O_RDONLY) == -1) {
427       perror (file);
428       exit (EXIT_FAILURE);
429     }
430   }
431
432   /* Interactive, shell script, or command(s) on the command line? */
433   if (optind >= argc) {
434     if (isatty (0))
435       interactive ();
436     else
437       shell_script ();
438   }
439   else
440     cmdline (argv, optind, argc);
441
442   cleanup_readline ();
443
444   exit (EXIT_SUCCESS);
445 }
446
447 void
448 pod2text (const char *name, const char *shortdesc, const char *str)
449 {
450   FILE *fp;
451
452   fp = popen ("pod2text", "w");
453   if (fp == NULL) {
454     /* pod2text failed, maybe not found, so let's just print the
455      * source instead, since that's better than doing nothing.
456      */
457     printf ("%s - %s\n\n%s\n", name, shortdesc, str);
458     return;
459   }
460   fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
461   fputs (str, fp);
462   pclose (fp);
463 }
464
465 /* List is built in reverse order, so mount them in reverse order. */
466 static void
467 mount_mps (struct mp *mp)
468 {
469   int r;
470
471   if (mp) {
472     mount_mps (mp->next);
473     if (!read_only)
474       r = guestfs_mount (g, mp->device, mp->mountpoint);
475     else
476       r = guestfs_mount_ro (g, mp->device, mp->mountpoint);
477     if (r == -1)
478       exit (EXIT_FAILURE);
479   }
480 }
481
482 static void
483 add_drives (struct drv *drv)
484 {
485   int r;
486
487   if (drv) {
488     add_drives (drv->next);
489     if (!read_only)
490       r = guestfs_add_drive (g, drv->filename);
491     else
492       r = guestfs_add_drive_ro (g, drv->filename);
493     if (r == -1)
494       exit (EXIT_FAILURE);
495   }
496 }
497
498 static void
499 interactive (void)
500 {
501   script (1);
502 }
503
504 static void
505 shell_script (void)
506 {
507   script (0);
508 }
509
510 #define FISH "><fs> "
511
512 static char *line_read = NULL;
513
514 static char *
515 rl_gets (int prompt)
516 {
517 #ifdef HAVE_LIBREADLINE
518
519   if (prompt) {
520     if (line_read) {
521       free (line_read);
522       line_read = NULL;
523     }
524
525     line_read = readline (prompt ? FISH : "");
526
527     if (line_read && *line_read)
528       add_history_line (line_read);
529
530     return line_read;
531   }
532
533 #endif /* HAVE_LIBREADLINE */
534
535   static char buf[8192];
536   int len;
537
538   if (prompt) printf (FISH);
539   line_read = fgets (buf, sizeof buf, stdin);
540
541   if (line_read) {
542     len = strlen (line_read);
543     if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
544   }
545
546   return line_read;
547 }
548
549 static void
550 script (int prompt)
551 {
552   char *buf;
553   char *cmd;
554   char *p, *pend;
555   char *argv[64];
556   int len;
557   int global_exit_on_error = !prompt;
558   int tilde_candidate;
559
560   if (prompt)
561     printf (_("\n"
562               "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
563               "editing virtual machine filesystems.\n"
564               "\n"
565               "Type: 'help' for help with commands\n"
566               "      'quit' to quit the shell\n"
567               "\n"));
568
569   while (!quit) {
570     char *pipe = NULL;
571
572     exit_on_error = global_exit_on_error;
573
574     buf = rl_gets (prompt);
575     if (!buf) {
576       quit = 1;
577       break;
578     }
579
580     /* Skip any initial whitespace before the command. */
581   again:
582     while (*buf && c_isspace (*buf))
583       buf++;
584
585     if (!*buf) continue;
586
587     /* If the next character is '#' then this is a comment. */
588     if (*buf == '#') continue;
589
590     /* If the next character is '!' then pass the whole lot to system(3). */
591     if (*buf == '!') {
592       int r;
593
594       r = system (buf+1);
595       if (exit_on_error) {
596         if (r == -1 ||
597             (WIFSIGNALED (r) &&
598              (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
599             WEXITSTATUS (r) != 0)
600           exit (EXIT_FAILURE);
601       }
602       continue;
603     }
604
605     /* If the next character is '-' allow the command to fail without
606      * exiting on error (just for this one command though).
607      */
608     if (*buf == '-') {
609       exit_on_error = 0;
610       buf++;
611       goto again;
612     }
613
614     /* Get the command (cannot be quoted). */
615     len = strcspn (buf, " \t");
616
617     if (len == 0) continue;
618
619     cmd = buf;
620     unsigned int i = 0;
621     if (buf[len] == '\0') {
622       argv[0] = NULL;
623       goto got_command;
624     }
625
626     buf[len] = '\0';
627     p = &buf[len+1];
628     p += strspn (p, " \t");
629
630     /* Get the parameters. */
631     while (*p && i < sizeof argv / sizeof argv[0]) {
632       tilde_candidate = 0;
633
634       /* Parameters which start with quotes or pipes are treated
635        * specially.  Bare parameters are delimited by whitespace.
636        */
637       if (*p == '"') {
638         p++;
639         len = strcspn (p, "\"");
640         if (p[len] == '\0') {
641           fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
642           if (exit_on_error) exit (EXIT_FAILURE);
643           goto next_command;
644         }
645         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
646           fprintf (stderr,
647                    _("%s: command arguments not separated by whitespace\n"),
648                    program_name);
649           if (exit_on_error) exit (EXIT_FAILURE);
650           goto next_command;
651         }
652         p[len] = '\0';
653         pend = p[len+1] ? &p[len+2] : &p[len+1];
654       } else if (*p == '\'') {
655         p++;
656         len = strcspn (p, "'");
657         if (p[len] == '\0') {
658           fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
659           if (exit_on_error) exit (EXIT_FAILURE);
660           goto next_command;
661         }
662         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
663           fprintf (stderr,
664                    _("%s: command arguments not separated by whitespace\n"),
665                    program_name);
666           if (exit_on_error) exit (EXIT_FAILURE);
667           goto next_command;
668         }
669         p[len] = '\0';
670         pend = p[len+1] ? &p[len+2] : &p[len+1];
671       } else if (*p == '|') {
672         *p = '\0';
673         pipe = p+1;
674         continue;
675         /*
676       } else if (*p == '[') {
677         int c = 1;
678         p++;
679         pend = p;
680         while (*pend && c != 0) {
681           if (*pend == '[') c++;
682           else if (*pend == ']') c--;
683           pend++;
684         }
685         if (c != 0) {
686           fprintf (stderr,
687                    _("%s: unterminated \"[...]\" sequence\n"), program_name);
688           if (exit_on_error) exit (EXIT_FAILURE);
689           goto next_command;
690         }
691         if (*pend && (*pend != ' ' && *pend != '\t')) {
692           fprintf (stderr,
693                    _("%s: command arguments not separated by whitespace\n"),
694                    program_name);
695           if (exit_on_error) exit (EXIT_FAILURE);
696           goto next_command;
697         }
698         *(pend-1) = '\0';
699         */
700       } else if (*p != ' ' && *p != '\t') {
701         /* If the first character is a ~ then note that this parameter
702          * is a candidate for ~username expansion.  NB this does not
703          * apply to quoted parameters.
704          */
705         tilde_candidate = *p == '~';
706         len = strcspn (p, " \t");
707         if (p[len]) {
708           p[len] = '\0';
709           pend = &p[len+1];
710         } else
711           pend = &p[len];
712       } else {
713         fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
714                  program_name, p);
715         abort ();
716       }
717
718       if (!tilde_candidate)
719         argv[i] = p;
720       else
721         argv[i] = try_tilde_expansion (p);
722       i++;
723       p = pend;
724
725       if (*p)
726         p += strspn (p, " \t");
727     }
728
729     if (i == sizeof argv / sizeof argv[0]) {
730       fprintf (stderr, _("%s: too many arguments\n"), program_name);
731       if (exit_on_error) exit (EXIT_FAILURE);
732       goto next_command;
733     }
734
735     argv[i] = NULL;
736
737   got_command:
738     if (issue_command (cmd, argv, pipe) == -1) {
739       if (exit_on_error) exit (EXIT_FAILURE);
740     }
741
742   next_command:;
743   }
744   if (prompt) printf ("\n");
745 }
746
747 static void
748 cmdline (char *argv[], int optind, int argc)
749 {
750   const char *cmd;
751   char **params;
752
753   exit_on_error = 1;
754
755   if (optind >= argc) return;
756
757   cmd = argv[optind++];
758   if (STREQ (cmd, ":")) {
759     fprintf (stderr, _("%s: empty command on command line\n"), program_name);
760     exit (EXIT_FAILURE);
761   }
762   params = &argv[optind];
763
764   /* Search for end of command list or ":" ... */
765   while (optind < argc && STRNEQ (argv[optind], ":"))
766     optind++;
767
768   if (optind == argc) {
769     if (issue_command (cmd, params, NULL) == -1) exit (EXIT_FAILURE);
770   } else {
771     argv[optind] = NULL;
772     if (issue_command (cmd, params, NULL) == -1) exit (EXIT_FAILURE);
773     cmdline (argv, optind+1, argc);
774   }
775 }
776
777 int
778 issue_command (const char *cmd, char *argv[], const char *pipecmd)
779 {
780   int argc;
781   int stdout_saved_fd = -1;
782   int pid = 0;
783   int i, r;
784
785   if (echo_commands) {
786     printf ("%s", cmd);
787     for (i = 0; argv[i] != NULL; ++i)
788       printf (" %s", argv[i]);
789     printf ("\n");
790   }
791
792   /* For | ... commands.  Annoyingly we can't use popen(3) here. */
793   if (pipecmd) {
794     int fd[2];
795
796     if (fflush (stdout) == EOF) {
797       perror ("failed to flush standard output");
798       return -1;
799     }
800     if (pipe (fd) < 0) {
801       perror ("pipe failed");
802       return -1;
803     }
804     pid = fork ();
805     if (pid == -1) {
806       perror ("fork");
807       return -1;
808     }
809
810     if (pid == 0) {             /* Child process. */
811       close (fd[1]);
812       if (dup2 (fd[0], 0) < 0) {
813         perror ("dup2 of stdin failed");
814         _exit (1);
815       }
816
817       r = system (pipecmd);
818       if (r == -1) {
819         perror (pipecmd);
820         _exit (1);
821       }
822       _exit (WEXITSTATUS (r));
823     }
824
825     if ((stdout_saved_fd = dup (1)) < 0) {
826       perror ("failed to dup stdout");
827       return -1;
828     }
829     close (fd[0]);
830     if (dup2 (fd[1], 1) < 0) {
831       perror ("failed to dup stdout");
832       close (stdout_saved_fd);
833       return -1;
834     }
835     close (fd[1]);
836   }
837
838   for (argc = 0; argv[argc] != NULL; ++argc)
839     ;
840
841   /* If --remote was set, then send this command to a remote process. */
842   if (remote_control)
843     r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
844
845   /* Otherwise execute it locally. */
846   else if (STRCASEEQ (cmd, "help")) {
847     if (argc == 0)
848       list_commands ();
849     else
850       display_command (argv[0]);
851     r = 0;
852   }
853   else if (STRCASEEQ (cmd, "quit") ||
854            STRCASEEQ (cmd, "exit") ||
855            STRCASEEQ (cmd, "q")) {
856     quit = 1;
857     r = 0;
858   }
859   else if (STRCASEEQ (cmd, "alloc") ||
860            STRCASEEQ (cmd, "allocate"))
861     r = do_alloc (cmd, argc, argv);
862   else if (STRCASEEQ (cmd, "echo"))
863     r = do_echo (cmd, argc, argv);
864   else if (STRCASEEQ (cmd, "edit") ||
865            STRCASEEQ (cmd, "vi") ||
866            STRCASEEQ (cmd, "emacs"))
867     r = do_edit (cmd, argc, argv);
868   else if (STRCASEEQ (cmd, "lcd"))
869     r = do_lcd (cmd, argc, argv);
870   else if (STRCASEEQ (cmd, "glob"))
871     r = do_glob (cmd, argc, argv);
872   else if (STRCASEEQ (cmd, "more") ||
873            STRCASEEQ (cmd, "less"))
874     r = do_more (cmd, argc, argv);
875   else if (STRCASEEQ (cmd, "reopen"))
876     r = do_reopen (cmd, argc, argv);
877   else if (STRCASEEQ (cmd, "sparse"))
878     r = do_sparse (cmd, argc, argv);
879   else if (STRCASEEQ (cmd, "time"))
880     r = do_time (cmd, argc, argv);
881   else
882     r = run_action (cmd, argc, argv);
883
884   /* Always flush stdout after every command, so that messages, results
885    * etc appear immediately.
886    */
887   if (fflush (stdout) == EOF) {
888     perror ("failed to flush standard output");
889     return -1;
890   }
891
892   if (pipecmd) {
893     close (1);
894     if (dup2 (stdout_saved_fd, 1) < 0) {
895       perror ("failed to dup2 standard output");
896       r = -1;
897     }
898     close (stdout_saved_fd);
899     if (waitpid (pid, NULL, 0) < 0) {
900       perror ("waiting for command to complete");
901       r = -1;
902     }
903   }
904
905   return r;
906 }
907
908 void
909 list_builtin_commands (void)
910 {
911   /* help and quit should appear at the top */
912   printf ("%-20s %s\n",
913           "help", _("display a list of commands or help on a command"));
914   printf ("%-20s %s\n",
915           "quit", _("quit guestfish"));
916
917   printf ("%-20s %s\n",
918           "alloc", _("allocate an image"));
919   printf ("%-20s %s\n",
920           "echo", _("display a line of text"));
921   printf ("%-20s %s\n",
922           "edit", _("edit a file in the image"));
923   printf ("%-20s %s\n",
924           "lcd", _("local change directory"));
925   printf ("%-20s %s\n",
926           "glob", _("expand wildcards in command"));
927   printf ("%-20s %s\n",
928           "more", _("view a file in the pager"));
929   printf ("%-20s %s\n",
930           "reopen", _("close and reopen libguestfs handle"));
931   printf ("%-20s %s\n",
932           "sparse", _("allocate a sparse image file"));
933   printf ("%-20s %s\n",
934           "time", _("measure time taken to run command"));
935
936   /* actions are printed after this (see list_commands) */
937 }
938
939 void
940 display_builtin_command (const char *cmd)
941 {
942   /* help for actions is auto-generated, see display_command */
943
944   if (STRCASEEQ (cmd, "alloc") ||
945       STRCASEEQ (cmd, "allocate"))
946     printf (_("alloc - allocate an image\n"
947               "     alloc <filename> <size>\n"
948               "\n"
949               "    This creates an empty (zeroed) file of the given size,\n"
950               "    and then adds so it can be further examined.\n"
951               "\n"
952               "    For more advanced image creation, see qemu-img utility.\n"
953               "\n"
954               "    Size can be specified (where <nn> means a number):\n"
955               "    <nn>             number of kilobytes\n"
956               "      eg: 1440       standard 3.5\" floppy\n"
957               "    <nn>K or <nn>KB  number of kilobytes\n"
958               "    <nn>M or <nn>MB  number of megabytes\n"
959               "    <nn>G or <nn>GB  number of gigabytes\n"
960               "    <nn>T or <nn>TB  number of terabytes\n"
961               "    <nn>P or <nn>PB  number of petabytes\n"
962               "    <nn>E or <nn>EB  number of exabytes\n"
963               "    <nn>sects        number of 512 byte sectors\n"));
964   else if (STRCASEEQ (cmd, "echo"))
965     printf (_("echo - display a line of text\n"
966               "     echo [<params> ...]\n"
967               "\n"
968               "    This echos the parameters to the terminal.\n"));
969   else if (STRCASEEQ (cmd, "edit") ||
970            STRCASEEQ (cmd, "vi") ||
971            STRCASEEQ (cmd, "emacs"))
972     printf (_("edit - edit a file in the image\n"
973               "     edit <filename>\n"
974               "\n"
975               "    This is used to edit a file.\n"
976               "\n"
977               "    It is the equivalent of (and is implemented by)\n"
978               "    running \"cat\", editing locally, and then \"write-file\".\n"
979               "\n"
980               "    Normally it uses $EDITOR, but if you use the aliases\n"
981               "    \"vi\" or \"emacs\" you will get those editors.\n"
982               "\n"
983               "    NOTE: This will not work reliably for large files\n"
984               "    (> 2 MB) or binary files containing \\0 bytes.\n"));
985   else if (STRCASEEQ (cmd, "lcd"))
986     printf (_("lcd - local change directory\n"
987               "    lcd <directory>\n"
988               "\n"
989               "    Change guestfish's current directory. This command is\n"
990               "    useful if you want to download files to a particular\n"
991               "    place.\n"));
992   else if (STRCASEEQ (cmd, "glob"))
993     printf (_("glob - expand wildcards in command\n"
994               "    glob <command> [<args> ...]\n"
995               "\n"
996               "    Glob runs <command> with wildcards expanded in any\n"
997               "    command args.  Note that the command is run repeatedly\n"
998               "    once for each expanded argument.\n"));
999   else if (STRCASEEQ (cmd, "help"))
1000     printf (_("help - display a list of commands or help on a command\n"
1001               "     help cmd\n"
1002               "     help\n"));
1003   else if (STRCASEEQ (cmd, "more") ||
1004            STRCASEEQ (cmd, "less"))
1005     printf (_("more - view a file in the pager\n"
1006               "     more <filename>\n"
1007               "\n"
1008               "    This is used to view a file in the pager.\n"
1009               "\n"
1010               "    It is the equivalent of (and is implemented by)\n"
1011               "    running \"cat\" and using the pager.\n"
1012               "\n"
1013               "    Normally it uses $PAGER, but if you use the alias\n"
1014               "    \"less\" then it always uses \"less\".\n"
1015               "\n"
1016               "    NOTE: This will not work reliably for large files\n"
1017               "    (> 2 MB) or binary files containing \\0 bytes.\n"));
1018   else if (STRCASEEQ (cmd, "quit") ||
1019            STRCASEEQ (cmd, "exit") ||
1020            STRCASEEQ (cmd, "q"))
1021     printf (_("quit - quit guestfish\n"
1022               "     quit\n"));
1023   else if (STRCASEEQ (cmd, "reopen"))
1024     printf (_("reopen - close and reopen the libguestfs handle\n"
1025               "     reopen\n"
1026               "\n"
1027               "Close and reopen the libguestfs handle.  It is not necessary to use\n"
1028               "this normally, because the handle is closed properly when guestfish\n"
1029               "exits.  However this is occasionally useful for testing.\n"));
1030   else if (STRCASEEQ (cmd, "sparse"))
1031     printf (_("sparse - allocate a sparse image file\n"
1032               "     sparse <filename> <size>\n"
1033               "\n"
1034               "    This creates an empty sparse file of the given size,\n"
1035               "    and then adds so it can be further examined.\n"
1036               "\n"
1037               "    In all respects it works the same as the 'alloc'\n"
1038               "    command, except that the image file is allocated\n"
1039               "    sparsely, which means that disk blocks are not assigned\n"
1040               "    to the file until they are needed.  Sparse disk files\n"
1041               "    only use space when written to, but they are slower\n"
1042               "    and there is a danger you could run out of real disk\n"
1043               "    space during a write operation.\n"
1044               "\n"
1045               "    For more advanced image creation, see qemu-img utility.\n"
1046               "\n"
1047               "    Size can be specified (where <nn> means a number):\n"
1048               "    <nn>             number of kilobytes\n"
1049               "      eg: 1440       standard 3.5\" floppy\n"
1050               "    <nn>K or <nn>KB  number of kilobytes\n"
1051               "    <nn>M or <nn>MB  number of megabytes\n"
1052               "    <nn>G or <nn>GB  number of gigabytes\n"
1053               "    <nn>T or <nn>TB  number of terabytes\n"
1054               "    <nn>P or <nn>PB  number of petabytes\n"
1055               "    <nn>E or <nn>EB  number of exabytes\n"
1056               "    <nn>sects        number of 512 byte sectors\n"));
1057   else if (STRCASEEQ (cmd, "time"))
1058     printf (_("time - measure time taken to run command\n"
1059               "    time <command> [<args> ...]\n"
1060               "\n"
1061               "    This runs <command> as usual, and prints the elapsed\n"
1062               "    time afterwards.\n"));
1063   else
1064     fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1065              cmd);
1066 }
1067
1068 void
1069 free_strings (char **argv)
1070 {
1071   int argc;
1072
1073   for (argc = 0; argv[argc] != NULL; ++argc)
1074     free (argv[argc]);
1075   free (argv);
1076 }
1077
1078 int
1079 count_strings (char *const *argv)
1080 {
1081   int c;
1082
1083   for (c = 0; argv[c]; ++c)
1084     ;
1085   return c;
1086 }
1087
1088 void
1089 print_strings (char *const *argv)
1090 {
1091   int argc;
1092
1093   for (argc = 0; argv[argc] != NULL; ++argc)
1094     printf ("%s\n", argv[argc]);
1095 }
1096
1097 void
1098 print_table (char *const *argv)
1099 {
1100   int i;
1101
1102   for (i = 0; argv[i] != NULL; i += 2)
1103     printf ("%s: %s\n", argv[i], argv[i+1]);
1104 }
1105
1106 int
1107 is_true (const char *str)
1108 {
1109   return
1110     STRCASENEQ (str, "0") &&
1111     STRCASENEQ (str, "f") &&
1112     STRCASENEQ (str, "false") &&
1113     STRCASENEQ (str, "n") &&
1114     STRCASENEQ (str, "no");
1115 }
1116
1117 /* Free strings from a non-NULL terminated char** */
1118 static void
1119 free_n_strings (char **str, size_t len)
1120 {
1121   size_t i;
1122
1123   for (i = 0; i < len; i++) {
1124     free (str[i]);
1125   }
1126   free (str);
1127 }
1128
1129 char **
1130 parse_string_list (const char *str)
1131 {
1132   char **argv = NULL;
1133   size_t argv_len = 0;
1134
1135   /* Current position pointer */
1136   const char *p = str;
1137
1138   /* Token might be simple:
1139    *  Token
1140    * or be quoted:
1141    *  'This is a single token'
1142    * or contain embedded single-quoted sections:
1143    *  This' is a sing'l'e to'ken
1144    *
1145    * The latter may seem over-complicated, but it's what a normal shell does.
1146    * Not doing it risks surprising somebody.
1147    *
1148    * This outer loop is over complete tokens.
1149    */
1150   while (*p) {
1151     char *tok = NULL;
1152     size_t tok_len = 0;
1153
1154     /* Skip leading whitespace */
1155     p += strspn (p, " \t");
1156
1157     char in_quote = 0;
1158
1159     /* This loop is over token 'fragments'. A token can be in multiple bits if
1160      * it contains single quotes. We also treat both sides of an escaped quote
1161      * as separate fragments because we can't just copy it: we have to remove
1162      * the \.
1163      */
1164     while (*p && (!c_isblank (*p) || in_quote)) {
1165       const char *end = p;
1166
1167       /* Check if the fragment starts with a quote */
1168       if ('\'' == *p) {
1169         /* Toggle in_quote */
1170         in_quote = !in_quote;
1171
1172         /* Skip the quote */
1173         p++; end++;
1174       }
1175
1176       /* If we're in a quote, look for an end quote */
1177       if (in_quote) {
1178         end += strcspn (end, "'");
1179       }
1180
1181       /* Otherwise, look for whitespace or a quote */
1182       else {
1183         end += strcspn (end, " \t'");
1184       }
1185
1186       /* Grow the token to accommodate the fragment */
1187       size_t tok_end = tok_len;
1188       tok_len += end - p;
1189       char *tok_new = realloc (tok, tok_len + 1);
1190       if (NULL == tok_new) {
1191         perror ("realloc");
1192         free_n_strings (argv, argv_len);
1193         free (tok);
1194         exit (EXIT_FAILURE);
1195       }
1196       tok = tok_new;
1197
1198       /* Check if we stopped on an escaped quote */
1199       if ('\'' == *end && end != p && *(end-1) == '\\') {
1200         /* Add everything before \' to the token */
1201         memcpy (&tok[tok_end], p, end - p - 1);
1202
1203         /* Add the quote */
1204         tok[tok_len-1] = '\'';
1205
1206         /* Already processed the quote */
1207         p = end + 1;
1208       }
1209
1210       else {
1211         /* Add the whole fragment */
1212         memcpy (&tok[tok_end], p, end - p);
1213
1214         p = end;
1215       }
1216     }
1217
1218     /* We've reached the end of a token. We shouldn't still be in quotes. */
1219     if (in_quote) {
1220       fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1221
1222       free_n_strings (argv, argv_len);
1223
1224       return NULL;
1225     }
1226
1227     /* Add this token if there is one. There might not be if there was
1228      * whitespace at the end of the input string */
1229     if (tok) {
1230       /* Add the NULL terminator */
1231       tok[tok_len] = '\0';
1232
1233       /* Add the argument to the argument list */
1234       argv_len++;
1235       char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1236       if (NULL == argv_new) {
1237         perror ("realloc");
1238         free_n_strings (argv, argv_len-1);
1239         free (tok);
1240         exit (EXIT_FAILURE);
1241       }
1242       argv = argv_new;
1243
1244       argv[argv_len-1] = tok;
1245     }
1246   }
1247
1248   /* NULL terminate the argument list */
1249   argv_len++;
1250   char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1251   if (NULL == argv_new) {
1252     perror ("realloc");
1253     free_n_strings (argv, argv_len-1);
1254     exit (EXIT_FAILURE);
1255   }
1256   argv = argv_new;
1257
1258   argv[argv_len-1] = NULL;
1259
1260   return argv;
1261 }
1262
1263 #ifdef HAVE_LIBREADLINE
1264 static char histfile[1024];
1265 static int nr_history_lines = 0;
1266 #endif
1267
1268 static void
1269 initialize_readline (void)
1270 {
1271 #ifdef HAVE_LIBREADLINE
1272   const char *home;
1273
1274   home = getenv ("HOME");
1275   if (home) {
1276     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1277     using_history ();
1278     (void) read_history (histfile);
1279   }
1280
1281   rl_readline_name = "guestfish";
1282   rl_attempted_completion_function = do_completion;
1283 #endif
1284 }
1285
1286 static void
1287 cleanup_readline (void)
1288 {
1289 #ifdef HAVE_LIBREADLINE
1290   int fd;
1291
1292   if (histfile[0] != '\0') {
1293     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1294     if (fd == -1) {
1295       perror (histfile);
1296       return;
1297     }
1298     close (fd);
1299
1300     (void) append_history (nr_history_lines, histfile);
1301   }
1302 #endif
1303 }
1304
1305 static void
1306 add_history_line (const char *line)
1307 {
1308 #ifdef HAVE_LIBREADLINE
1309   add_history (line);
1310   nr_history_lines++;
1311 #endif
1312 }
1313
1314 int
1315 xwrite (int fd, const void *v_buf, size_t len)
1316 {
1317   int r;
1318   const char *buf = v_buf;
1319
1320   while (len > 0) {
1321     r = write (fd, buf, len);
1322     if (r == -1) {
1323       perror ("write");
1324       return -1;
1325     }
1326     buf += r;
1327     len -= r;
1328   }
1329
1330   return 0;
1331 }
1332
1333 /* Resolve the special "win:..." form for Windows-specific paths.
1334  * This always returns a newly allocated string which is freed by the
1335  * caller function in "cmds.c".
1336  */
1337 char *
1338 resolve_win_path (const char *path)
1339 {
1340   char *ret;
1341   size_t i;
1342
1343   if (STRCASENEQLEN (path, "win:", 4)) {
1344     ret = strdup (path);
1345     if (ret == NULL)
1346       perror ("strdup");
1347     return ret;
1348   }
1349
1350   path += 4;
1351
1352   /* Drop drive letter, if it's "C:". */
1353   if (STRCASEEQLEN (path, "c:", 2))
1354     path += 2;
1355
1356   if (!*path) {
1357     ret = strdup ("/");
1358     if (ret == NULL)
1359       perror ("strdup");
1360     return ret;
1361   }
1362
1363   ret = strdup (path);
1364   if (ret == NULL) {
1365     perror ("strdup");
1366     return NULL;
1367   }
1368
1369   /* Blindly convert any backslashes into forward slashes.  Is this good? */
1370   for (i = 0; i < strlen (ret); ++i)
1371     if (ret[i] == '\\')
1372       ret[i] = '/';
1373
1374   char *t = guestfs_case_sensitive_path (g, ret);
1375   free (ret);
1376   ret = t;
1377
1378   return ret;
1379 }