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