Use a squashfs attached as /dev/sdd during the C API tests.
[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 #define _GNU_SOURCE // for strchrnul
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <getopt.h>
29 #include <signal.h>
30 #include <assert.h>
31 #include <ctype.h>
32
33 #ifdef HAVE_LIBREADLINE
34 #include <readline/readline.h>
35 #include <readline/history.h>
36 #endif
37
38 #include <guestfs.h>
39
40 #include "fish.h"
41
42 struct mp {
43   struct mp *next;
44   char *device;
45   char *mountpoint;
46 };
47
48 static void mount_mps (struct mp *mp);
49 static void interactive (void);
50 static void shell_script (void);
51 static void script (int prompt);
52 static void cmdline (char *argv[], int optind, int argc);
53 static int issue_command (const char *cmd, char *argv[]);
54 static void initialize_readline (void);
55 static void cleanup_readline (void);
56 static void add_history_line (const char *);
57
58 /* Currently open libguestfs handle. */
59 guestfs_h *g;
60
61 int read_only = 0;
62 int quit = 0;
63 int verbose = 0;
64
65 int
66 launch (guestfs_h *_g)
67 {
68   assert (_g == g);
69
70   if (guestfs_is_config (g)) {
71     if (guestfs_launch (g) == -1)
72       return -1;
73     if (guestfs_wait_ready (g) == -1)
74       return -1;
75   }
76   return 0;
77 }
78
79 static void
80 usage (void)
81 {
82   fprintf (stderr,
83            _("guestfish: guest filesystem shell\n"
84              "guestfish lets you edit virtual machine filesystems\n"
85              "Copyright (C) 2009 Red Hat Inc.\n"
86              "Usage:\n"
87              "  guestfish [--options] cmd [: cmd : cmd ...]\n"
88              "or for interactive use:\n"
89              "  guestfish\n"
90              "or from a shell script:\n"
91              "  guestfish <<EOF\n"
92              "  cmd\n"
93              "  ...\n"
94              "  EOF\n"
95              "Options:\n"
96              "  -h|--cmd-help        List available commands\n"
97              "  -h|--cmd-help cmd    Display detailed help on 'cmd'\n"
98              "  -a|--add image       Add image\n"
99              "  -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
100              "  -n|--no-sync         Don't autosync\n"
101              "  -r|--ro              Mount read-only\n"
102              "  -v|--verbose         Verbose messages\n"
103              "  -V|--version         Display version and exit\n"
104              "For more information,  see the manpage guestfish(1).\n"));
105 }
106
107 int
108 main (int argc, char *argv[])
109 {
110   static const char *options = "a:h::m:nrv?V";
111   static struct option long_options[] = {
112     { "add", 1, 0, 'a' },
113     { "cmd-help", 2, 0, 'h' },
114     { "help", 0, 0, '?' },
115     { "mount", 1, 0, 'm' },
116     { "no-sync", 0, 0, 'n' },
117     { "ro", 0, 0, 'r' },
118     { "verbose", 0, 0, 'v' },
119     { "version", 0, 0, 'V' },
120     { 0, 0, 0, 0 }
121   };
122   struct mp *mps = NULL;
123   struct mp *mp;
124   char *p;
125   int c;
126
127   initialize_readline ();
128
129   /* guestfs_create is meant to be a lightweight operation, so
130    * it's OK to do it early here.
131    */
132   g = guestfs_create ();
133   if (g == NULL) {
134     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
135     exit (1);
136   }
137
138   guestfs_set_autosync (g, 1);
139
140   /* If developing, add ./appliance to the path.  Note that libtools
141    * interferes with this because uninstalled guestfish is a shell
142    * script that runs the real program with an absolute path.  Detect
143    * that too.
144    *
145    * BUT if LIBGUESTFS_PATH environment variable is already set by
146    * the user, then don't override it.
147    */
148   if (getenv ("LIBGUESTFS_PATH") == NULL &&
149       argv[0] &&
150       (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
151     guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
152
153   for (;;) {
154     c = getopt_long (argc, argv, options, long_options, NULL);
155     if (c == -1) break;
156
157     switch (c) {
158     case 'a':
159       if (access (optarg, R_OK) != 0) {
160         perror (optarg);
161         exit (1);
162       }
163       if (guestfs_add_drive (g, optarg) == -1)
164         exit (1);
165       break;
166
167     case 'h':
168       if (optarg)
169         display_command (optarg);
170       else if (argv[optind] && argv[optind][0] != '-')
171         display_command (argv[optind++]);
172       else
173         list_commands ();
174       exit (0);
175
176     case 'm':
177       mp = malloc (sizeof (struct mp));
178       if (!mp) {
179         perror ("malloc");
180         exit (1);
181       }
182       p = strchr (optarg, ':');
183       if (p) {
184         *p = '\0';
185         mp->mountpoint = p+1;
186       } else
187         mp->mountpoint = "/";
188       mp->device = optarg;
189       mp->next = mps;
190       mps = mp;
191       break;
192
193     case 'n':
194       guestfs_set_autosync (g, 0);
195       break;
196
197     case 'r':
198       read_only = 1;
199       break;
200
201     case 'v':
202       verbose++;
203       guestfs_set_verbose (g, verbose);
204       break;
205
206     case 'V':
207       printf ("guestfish %s\n", PACKAGE_VERSION);
208       exit (0);
209
210     case '?':
211       usage ();
212       exit (0);
213
214     default:
215       fprintf (stderr, _("guestfish: unexpected command line option 0x%x\n"),
216                c);
217       exit (1);
218     }
219   }
220
221   /* If we've got mountpoints, we must launch the guest and mount them. */
222   if (mps != NULL) {
223     if (launch (g) == -1) exit (1);
224     mount_mps (mps);
225   }
226
227   /* Interactive, shell script, or command(s) on the command line? */
228   if (optind >= argc) {
229     if (isatty (0))
230       interactive ();
231     else
232       shell_script ();
233   }
234   else
235     cmdline (argv, optind, argc);
236
237   cleanup_readline ();
238
239   exit (0);
240 }
241
242 void
243 pod2text (const char *heading, const char *str)
244 {
245   FILE *fp;
246
247   fp = popen ("pod2text", "w");
248   if (fp == NULL) {
249     /* pod2text failed, maybe not found, so let's just print the
250      * source instead, since that's better than doing nothing.
251      */
252     printf ("%s\n\n%s\n", heading, str);
253     return;
254   }
255   fputs ("=head1 ", fp);
256   fputs (heading, fp);
257   fputs ("\n\n", fp);
258   fputs (str, fp);
259   pclose (fp);
260 }
261
262 /* List is built in reverse order, so mount them in reverse order. */
263 static void
264 mount_mps (struct mp *mp)
265 {
266   int r;
267
268   if (mp) {
269     mount_mps (mp->next);
270     if (!read_only)
271       r = guestfs_mount (g, mp->device, mp->mountpoint);
272     else
273       r = guestfs_mount_ro (g, mp->device, mp->mountpoint);
274     if (r == -1)
275       exit (1);
276   }
277 }
278
279 static void
280 interactive (void)
281 {
282   script (1);
283 }
284
285 static void
286 shell_script (void)
287 {
288   script (0);
289 }
290
291 #define FISH "><fs> "
292
293 static char *line_read = NULL;
294
295 static char *
296 rl_gets (int prompt)
297 {
298 #ifdef HAVE_LIBREADLINE
299
300   if (prompt) {
301     if (line_read) {
302       free (line_read);
303       line_read = NULL;
304     }
305
306     line_read = readline (prompt ? FISH : "");
307
308     if (line_read && *line_read)
309       add_history_line (line_read);
310
311     return line_read;
312   }
313
314 #endif /* HAVE_LIBREADLINE */
315
316   static char buf[8192];
317   int len;
318
319   if (prompt) printf (FISH);
320   line_read = fgets (buf, sizeof buf, stdin);
321
322   if (line_read) {
323     len = strlen (line_read);
324     if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
325   }
326
327   return line_read;
328 }
329
330 static void
331 script (int prompt)
332 {
333   char *buf;
334   char *cmd;
335   char *p, *pend;
336   char *argv[64];
337   int i, len;
338   int global_exit_on_error = !prompt;
339   int exit_on_error;
340
341   if (prompt)
342     printf (_("\n"
343               "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
344               "editing virtual machine filesystems.\n"
345               "\n"
346               "Type: 'help' for help with commands\n"
347               "      'quit' to quit the shell\n"
348               "\n"));
349
350   while (!quit) {
351     exit_on_error = global_exit_on_error;
352
353     buf = rl_gets (prompt);
354     if (!buf) {
355       quit = 1;
356       break;
357     }
358
359     /* Skip any initial whitespace before the command. */
360   again:
361     while (*buf && isspace (*buf))
362       buf++;
363
364     if (!*buf) continue;
365
366     /* If the next character is '#' then this is a comment. */
367     if (*buf == '#') continue;
368
369     /* If the next character is '!' then pass the whole lot to system(3). */
370     if (*buf == '!') {
371       int r;
372
373       r = system (buf+1);
374       if (exit_on_error) {
375         if (r == -1 ||
376             (WIFSIGNALED (r) &&
377              (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
378             WEXITSTATUS (r) != 0)
379           exit (1);
380       }
381       continue;
382     }
383
384     /* If the next character is '-' allow the command to fail without
385      * exiting on error (just for this one command though).
386      */
387     if (*buf == '-') {
388       exit_on_error = 0;
389       buf++;
390       goto again;
391     }
392
393     /* Get the command (cannot be quoted). */
394     len = strcspn (buf, " \t");
395
396     if (len == 0) continue;
397
398     cmd = buf;
399     i = 0;
400     if (buf[len] == '\0') {
401       argv[0] = NULL;
402       goto got_command;
403     }
404
405     buf[len] = '\0';
406     p = &buf[len+1];
407     p += strspn (p, " \t");
408
409     /* Get the parameters. */
410     while (*p && i < sizeof argv / sizeof argv[0]) {
411       /* Parameters which start with quotes or square brackets
412        * are treated specially.  Bare parameters are delimited
413        * by whitespace.
414        */
415       if (*p == '"') {
416         p++;
417         len = strcspn (p, "\"");
418         if (p[len] == '\0') {
419           fprintf (stderr, _("guestfish: unterminated double quote\n"));
420           if (exit_on_error) exit (1);
421           goto next_command;
422         }
423         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
424           fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
425           if (exit_on_error) exit (1);
426           goto next_command;
427         }
428         p[len] = '\0';
429         pend = p[len+1] ? &p[len+2] : &p[len+1];
430       } else if (*p == '\'') {
431         p++;
432         len = strcspn (p, "'");
433         if (p[len] == '\0') {
434           fprintf (stderr, _("guestfish: unterminated single quote\n"));
435           if (exit_on_error) exit (1);
436           goto next_command;
437         }
438         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
439           fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
440           if (exit_on_error) exit (1);
441           goto next_command;
442         }
443         p[len] = '\0';
444         pend = p[len+1] ? &p[len+2] : &p[len+1];
445         /*
446       } else if (*p == '[') {
447         int c = 1;
448         p++;
449         pend = p;
450         while (*pend && c != 0) {
451           if (*pend == '[') c++;
452           else if (*pend == ']') c--;
453           pend++;
454         }
455         if (c != 0) {
456           fprintf (stderr, _("guestfish: unterminated \"[...]\" sequence\n"));
457           if (exit_on_error) exit (1);
458           goto next_command;
459         }
460         if (*pend && (*pend != ' ' && *pend != '\t')) {
461           fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
462           if (exit_on_error) exit (1);
463           goto next_command;
464         }
465         *(pend-1) = '\0';
466         */
467       } else if (*p != ' ' && *p != '\t') {
468         len = strcspn (p, " \t");
469         if (p[len]) {
470           p[len] = '\0';
471           pend = &p[len+1];
472         } else
473           pend = &p[len];
474       } else {
475         fprintf (stderr, _("guestfish: internal error parsing string at '%s'\n"),
476                  p);
477         abort ();
478       }
479
480       argv[i++] = p;
481       p = pend;
482
483       if (*p)
484         p += strspn (p, " \t");
485     }
486
487     if (i == sizeof argv / sizeof argv[0]) {
488       fprintf (stderr, _("guestfish: too many arguments\n"));
489       if (exit_on_error) exit (1);
490       goto next_command;
491     }
492
493     argv[i] = NULL;
494
495   got_command:
496     if (issue_command (cmd, argv) == -1) {
497       if (exit_on_error) exit (1);
498     }
499
500   next_command:;
501   }
502   if (prompt) printf ("\n");
503 }
504
505 static void
506 cmdline (char *argv[], int optind, int argc)
507 {
508   const char *cmd;
509   char **params;
510
511   if (optind >= argc) return;
512
513   cmd = argv[optind++];
514   if (strcmp (cmd, ":") == 0) {
515     fprintf (stderr, _("guestfish: empty command on command line\n"));
516     exit (1);
517   }
518   params = &argv[optind];
519
520   /* Search for end of command list or ":" ... */
521   while (optind < argc && strcmp (argv[optind], ":") != 0)
522     optind++;
523
524   if (optind == argc) {
525     if (issue_command (cmd, params) == -1) exit (1);
526   } else {
527     argv[optind] = NULL;
528     if (issue_command (cmd, params) == -1) exit (1);
529     cmdline (argv, optind+1, argc);
530   }
531 }
532
533 static int
534 issue_command (const char *cmd, char *argv[])
535 {
536   int argc;
537
538   for (argc = 0; argv[argc] != NULL; ++argc)
539     ;
540
541   if (strcasecmp (cmd, "help") == 0) {
542     if (argc == 0)
543       list_commands ();
544     else
545       display_command (argv[0]);
546     return 0;
547   }
548   else if (strcasecmp (cmd, "quit") == 0 ||
549            strcasecmp (cmd, "exit") == 0 ||
550            strcasecmp (cmd, "q") == 0) {
551     quit = 1;
552     return 0;
553   }
554   else if (strcasecmp (cmd, "alloc") == 0 ||
555            strcasecmp (cmd, "allocate") == 0)
556     return do_alloc (cmd, argc, argv);
557   else if (strcasecmp (cmd, "echo") == 0)
558     return do_echo (cmd, argc, argv);
559   else if (strcasecmp (cmd, "edit") == 0 ||
560            strcasecmp (cmd, "vi") == 0 ||
561            strcasecmp (cmd, "emacs") == 0)
562     return do_edit (cmd, argc, argv);
563   else
564     return run_action (cmd, argc, argv);
565 }
566
567 void
568 list_builtin_commands (void)
569 {
570   /* help and quit should appear at the top */
571   printf ("%-20s %s\n",
572           "help", _("display a list of commands or help on a command"));
573   printf ("%-20s %s\n",
574           "quit", _("quit guestfish"));
575
576   printf ("%-20s %s\n",
577           "alloc", _("allocate an image"));
578   printf ("%-20s %s\n",
579           "echo", _("display a line of text"));
580   printf ("%-20s %s\n",
581           "edit", _("edit a file in the image"));
582
583   /* actions are printed after this (see list_commands) */
584 }
585
586 void
587 display_builtin_command (const char *cmd)
588 {
589   /* help for actions is auto-generated, see display_command */
590
591   if (strcasecmp (cmd, "alloc") == 0 ||
592       strcasecmp (cmd, "allocate") == 0)
593     printf (_("alloc - allocate an image\n"
594               "     alloc <filename> <size>\n"
595               "\n"
596               "    This creates an empty (zeroed) file of the given size,\n"
597               "    and then adds so it can be further examined.\n"
598               "\n"
599               "    For more advanced image creation, see qemu-img utility.\n"
600               "\n"
601               "    Size can be specified (where <nn> means a number):\n"
602               "    <nn>             number of kilobytes\n"
603               "      eg: 1440       standard 3.5\" floppy\n"
604               "    <nn>K or <nn>KB  number of kilobytes\n"
605               "    <nn>M or <nn>MB  number of megabytes\n"
606               "    <nn>G or <nn>GB  number of gigabytes\n"
607               "    <nn>sects        number of 512 byte sectors\n"));
608   else if (strcasecmp (cmd, "echo") == 0)
609     printf (_("echo - display a line of text\n"
610               "     echo [<params> ...]\n"
611               "\n"
612               "    This echos the parameters to the terminal.\n"));
613   else if (strcasecmp (cmd, "edit") == 0 ||
614            strcasecmp (cmd, "vi") == 0 ||
615            strcasecmp (cmd, "emacs") == 0)
616     printf (_("edit - edit a file in the image\n"
617               "     edit <filename>\n"
618               "\n"
619               "    This is used to edit a file.\n"
620               "\n"
621               "    It is the equivalent of (and is implemented by)\n"
622               "    running \"cat\", editing locally, and then \"write-file\".\n"
623               "\n"
624               "    Normally it uses $EDITOR, but if you use the aliases\n"
625               "    \"vi\" or \"emacs\" you will get those editors.\n"
626               "\n"
627               "    NOTE: This will not work reliably for large files\n"
628               "    (> 2 MB) or binary files containing \\0 bytes.\n"));
629   else if (strcasecmp (cmd, "help") == 0)
630     printf (_("help - display a list of commands or help on a command\n"
631               "     help cmd\n"
632               "     help\n"));
633   else if (strcasecmp (cmd, "quit") == 0 ||
634            strcasecmp (cmd, "exit") == 0 ||
635            strcasecmp (cmd, "q") == 0)
636     printf (_("quit - quit guestfish\n"
637               "     quit\n"));
638   else
639     fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
640              cmd);
641 }
642
643 void
644 free_strings (char **argv)
645 {
646   int argc;
647
648   for (argc = 0; argv[argc] != NULL; ++argc)
649     free (argv[argc]);
650   free (argv);
651 }
652
653 void
654 print_strings (char * const * const argv)
655 {
656   int argc;
657
658   for (argc = 0; argv[argc] != NULL; ++argc)
659     printf ("%s\n", argv[argc]);
660 }
661
662 void
663 print_table (char * const * const argv)
664 {
665   int i;
666
667   for (i = 0; argv[i] != NULL; i += 2)
668     printf ("%s: %s\n", argv[i], argv[i+1]);
669 }
670
671 int
672 is_true (const char *str)
673 {
674   return
675     strcasecmp (str, "0") != 0 &&
676     strcasecmp (str, "f") != 0 &&
677     strcasecmp (str, "false") != 0 &&
678     strcasecmp (str, "n") != 0 &&
679     strcasecmp (str, "no") != 0;
680 }
681
682 /* XXX We could improve list parsing. */
683 char **
684 parse_string_list (const char *str)
685 {
686   char **argv;
687   const char *p, *pend;
688   int argc, i;
689
690   argc = 1;
691   for (i = 0; str[i]; ++i)
692     if (str[i] == ' ') argc++;
693
694   argv = malloc (sizeof (char *) * (argc+1));
695   if (argv == NULL) { perror ("malloc"); exit (1); }
696
697   p = str;
698   i = 0;
699   while (*p) {
700     pend = strchrnul (p, ' ');
701     argv[i] = strndup (p, pend-p);
702     i++;
703     p = *pend == ' ' ? pend+1 : pend;
704   }
705   argv[i] = NULL;
706
707   return argv;
708 }
709
710 #ifdef HAVE_LIBREADLINE
711 static char histfile[1024];
712 static int nr_history_lines = 0;
713 #endif
714
715 static void
716 initialize_readline (void)
717 {
718 #ifdef HAVE_LIBREADLINE
719   const char *home;
720
721   home = getenv ("HOME");
722   if (home) {
723     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
724     using_history ();
725     (void) read_history (histfile);
726   }
727
728   rl_readline_name = "guestfish";
729   rl_attempted_completion_function = do_completion;
730 #endif
731 }
732
733 static void
734 cleanup_readline (void)
735 {
736 #ifdef HAVE_LIBREADLINE
737   int fd;
738
739   if (histfile[0] != '\0') {
740     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
741     if (fd == -1) {
742       perror (histfile);
743       return;
744     }
745     close (fd);
746
747     (void) append_history (nr_history_lines, histfile);
748   }
749 #endif
750 }
751
752 static void
753 add_history_line (const char *line)
754 {
755 #ifdef HAVE_LIBREADLINE
756   add_history (line);
757   nr_history_lines++;
758 #endif
759 }