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