1309c680170ff305323f634e8a4ace385c46cc74
[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 int g_launched = 0;
61
62 int read_only = 0;
63 int quit = 0;
64 int verbose = 0;
65
66 int
67 launch (guestfs_h *_g)
68 {
69   assert (_g == g);
70
71   if (!g_launched) {
72     if (guestfs_launch (g) == -1)
73       return -1;
74     if (guestfs_wait_ready (g) == -1)
75       return -1;
76     g_launched = 1;
77   }
78   return 0;
79 }
80
81 static void
82 usage (void)
83 {
84   fprintf (stderr,
85            "guestfish: guest filesystem shell\n"
86            "guestfish lets you edit virtual machine filesystems\n"
87            "Copyright (C) 2009 Red Hat Inc.\n"
88            "Usage:\n"
89            "  guestfish [--options] cmd [: cmd : cmd ...]\n"
90            "or for interactive use:\n"
91            "  guestfish\n"
92            "or from a shell script:\n"
93            "  guestfish <<EOF\n"
94            "  cmd\n"
95            "  ...\n"
96            "  EOF\n"
97            "Options:\n"
98            "  -h|--cmd-help        List available commands\n"
99            "  -h|--cmd-help cmd    Display detailed help on 'cmd'\n"
100            "  -a|--add image       Add image\n"
101            "  -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
102            "  -n|--no-sync         Don't autosync\n"
103            "  -r|--ro              Mount read-only\n"
104            "  -v|--verbose         Verbose messages\n"
105            "  -V|--version         Display version and exit\n"
106            "For more information,  see the manpage guestfish(1).\n");
107 }
108
109 int
110 main (int argc, char *argv[])
111 {
112   static const char *options = "a:h::m:nrv?V";
113   static struct option long_options[] = {
114     { "add", 1, 0, 'a' },
115     { "cmd-help", 2, 0, 'h' },
116     { "help", 0, 0, '?' },
117     { "mount", 1, 0, 'm' },
118     { "no-sync", 0, 0, 'n' },
119     { "ro", 0, 0, 'r' },
120     { "verbose", 0, 0, 'v' },
121     { "version", 0, 0, 'V' },
122     { 0, 0, 0, 0 }
123   };
124   struct mp *mps = NULL;
125   struct mp *mp;
126   char *p;
127   int c;
128
129   initialize_readline ();
130
131   /* guestfs_create is meant to be a lightweight operation, so
132    * it's OK to do it early here.
133    */
134   g = guestfs_create ();
135   if (g == NULL) {
136     fprintf (stderr, "guestfs_create: failed to create handle\n");
137     exit (1);
138   }
139
140   guestfs_set_autosync (g, 1);
141
142   /* If developing, add . to the path.  Note that libtools interferes
143    * with this because uninstalled guestfish is a shell script that runs
144    * the real program with an absolute path.  Detect that too.
145    *
146    * BUT if LIBGUESTFS_PATH environment variable is already set by
147    * the user, then don't override it.
148    */
149   if (getenv ("LIBGUESTFS_PATH") == NULL &&
150       argv[0] &&
151       (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
152     guestfs_set_path (g, ".:" GUESTFS_DEFAULT_PATH);
153
154   for (;;) {
155     c = getopt_long (argc, argv, options, long_options, NULL);
156     if (c == -1) break;
157
158     switch (c) {
159     case 'a':
160       if (access (optarg, R_OK) != 0) {
161         perror (optarg);
162         exit (1);
163       }
164       if (guestfs_add_drive (g, optarg) == -1)
165         exit (1);
166       break;
167
168     case 'h':
169       if (optarg)
170         display_command (optarg);
171       else if (argv[optind] && argv[optind][0] != '-')
172         display_command (argv[optind++]);
173       else
174         list_commands ();
175       exit (0);
176
177     case 'm':
178       mp = malloc (sizeof (struct mp));
179       if (!mp) {
180         perror ("malloc");
181         exit (1);
182       }
183       p = strchr (optarg, ':');
184       if (p) {
185         *p = '\0';
186         mp->mountpoint = p+1;
187       } else
188         mp->mountpoint = "/";
189       mp->device = optarg;
190       mp->next = mps;
191       mps = mp;
192       break;
193
194     case 'n':
195       guestfs_set_autosync (g, 0);
196       break;
197
198     case 'r':
199       read_only = 1;
200       break;
201
202     case 'v':
203       verbose++;
204       guestfs_set_verbose (g, verbose);
205       break;
206
207     case 'V':
208       printf ("guestfish %s\n", PACKAGE_VERSION);
209       exit (0);
210
211     case '?':
212       usage ();
213       exit (0);
214
215     default:
216       fprintf (stderr, "guestfish: unexpected command line option 0x%x\n", 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
339   if (prompt)
340     printf ("\n"
341             "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
342             "editing virtual machine filesystems.\n"
343             "\n"
344             "Type: 'help' for help with commands\n"
345             "      'quit' to quit the shell\n"
346             "\n");
347
348   while (!quit) {
349     buf = rl_gets (prompt);
350     if (!buf) {
351       quit = 1;
352       break;
353     }
354
355     /* Skip any initial whitespace before the command. */
356     while (*buf && isspace (*buf))
357       buf++;
358
359     if (!*buf) continue;
360
361     /* If the next character is '#' then this is a comment. */
362     if (*buf == '#') continue;
363
364     /* If the next character is '!' then pass the whole lot to system(3). */
365     if (*buf == '!') {
366       int r;
367
368       r = system (buf+1);
369       if (!prompt) {
370         if (r == -1 ||
371             (WIFSIGNALED (r) &&
372              (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
373             WEXITSTATUS (r) != 0)
374           exit (1);
375       }
376       continue;
377     }
378
379     /* Get the command (cannot be quoted). */
380     len = strcspn (buf, " \t");
381
382     if (len == 0) continue;
383
384     cmd = buf;
385     i = 0;
386     if (buf[len] == '\0') {
387       argv[0] = NULL;
388       goto got_command;
389     }
390
391     buf[len] = '\0';
392     p = &buf[len+1];
393     p += strspn (p, " \t");
394
395     /* Get the parameters. */
396     while (*p && i < sizeof argv / sizeof argv[0]) {
397       /* Parameters which start with quotes or square brackets
398        * are treated specially.  Bare parameters are delimited
399        * by whitespace.
400        */
401       if (*p == '"') {
402         p++;
403         len = strcspn (p, "\"");
404         if (p[len] == '\0') {
405           fprintf (stderr, "guestfish: unterminated double quote\n");
406           if (!prompt) exit (1);
407           goto next_command;
408         }
409         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
410           fprintf (stderr, "guestfish: command arguments not separated by whitespace\n");
411           if (!prompt) exit (1);
412           goto next_command;
413         }
414         p[len] = '\0';
415         pend = p[len+1] ? &p[len+2] : &p[len+1];
416       } else if (*p == '\'') {
417         p++;
418         len = strcspn (p, "'");
419         if (p[len] == '\0') {
420           fprintf (stderr, "guestfish: unterminated single quote\n");
421           if (!prompt) exit (1);
422           goto next_command;
423         }
424         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
425           fprintf (stderr, "guestfish: command arguments not separated by whitespace\n");
426           if (!prompt) exit (1);
427           goto next_command;
428         }
429         p[len] = '\0';
430         pend = p[len+1] ? &p[len+2] : &p[len+1];
431         /*
432       } else if (*p == '[') {
433         int c = 1;
434         p++;
435         pend = p;
436         while (*pend && c != 0) {
437           if (*pend == '[') c++;
438           else if (*pend == ']') c--;
439           pend++;
440         }
441         if (c != 0) {
442           fprintf (stderr, "guestfish: unterminated \"[...]\" sequence\n");
443           if (!prompt) exit (1);
444           goto next_command;
445         }
446         if (*pend && (*pend != ' ' && *pend != '\t')) {
447           fprintf (stderr, "guestfish: command arguments not separated by whitespace\n");
448           if (!prompt) exit (1);
449           goto next_command;
450         }
451         *(pend-1) = '\0';
452         */
453       } else if (*p != ' ' && *p != '\t') {
454         len = strcspn (p, " \t");
455         if (p[len]) {
456           p[len] = '\0';
457           pend = &p[len+1];
458         } else
459           pend = &p[len];
460       } else {
461         fprintf (stderr, "guestfish: internal error parsing string at '%s'\n",
462                  p);
463         abort ();
464       }
465
466       argv[i++] = p;
467       p = pend;
468
469       if (*p)
470         p += strspn (p, " \t");
471     }
472
473     if (i == sizeof argv / sizeof argv[0]) {
474       fprintf (stderr, "guestfish: too many arguments\n");
475       if (!prompt) exit (1);
476       goto next_command;
477     }
478
479     argv[i] = NULL;
480
481   got_command:
482     if (issue_command (cmd, argv) == -1) {
483       if (!prompt) exit (1);
484     }
485
486   next_command:;
487   }
488   if (prompt) printf ("\n");
489 }
490
491 static void
492 cmdline (char *argv[], int optind, int argc)
493 {
494   const char *cmd;
495   char **params;
496
497   if (optind >= argc) return;
498
499   cmd = argv[optind++];
500   if (strcmp (cmd, ":") == 0) {
501     fprintf (stderr, "guestfish: empty command on command line\n");
502     exit (1);
503   }
504   params = &argv[optind];
505
506   /* Search for end of command list or ":" ... */
507   while (optind < argc && strcmp (argv[optind], ":") != 0)
508     optind++;
509
510   if (optind == argc) {
511     if (issue_command (cmd, params) == -1) exit (1);
512   } else {
513     argv[optind] = NULL;
514     if (issue_command (cmd, params) == -1) exit (1);
515     cmdline (argv, optind+1, argc);
516   }
517 }
518
519 static int
520 issue_command (const char *cmd, char *argv[])
521 {
522   int argc;
523
524   for (argc = 0; argv[argc] != NULL; ++argc)
525     ;
526
527   if (strcasecmp (cmd, "help") == 0) {
528     if (argc == 0)
529       list_commands ();
530     else
531       display_command (argv[0]);
532     return 0;
533   }
534   else if (strcasecmp (cmd, "quit") == 0 ||
535            strcasecmp (cmd, "exit") == 0 ||
536            strcasecmp (cmd, "q") == 0) {
537     quit = 1;
538     return 0;
539   }
540   else if (strcasecmp (cmd, "alloc") == 0 ||
541            strcasecmp (cmd, "allocate") == 0)
542     return do_alloc (cmd, argc, argv);
543   else if (strcasecmp (cmd, "echo") == 0)
544     return do_echo (cmd, argc, argv);
545   else if (strcasecmp (cmd, "edit") == 0 ||
546            strcasecmp (cmd, "vi") == 0 ||
547            strcasecmp (cmd, "emacs") == 0)
548     return do_edit (cmd, argc, argv);
549   else
550     return run_action (cmd, argc, argv);
551 }
552
553 void
554 list_builtin_commands (void)
555 {
556   /* help and quit should appear at the top */
557   printf ("%-20s %s\n",
558           "help", "display a list of commands or help on a command");
559   printf ("%-20s %s\n",
560           "quit", "quit guestfish");
561
562   printf ("%-20s %s\n",
563           "alloc", "allocate an image");
564   printf ("%-20s %s\n",
565           "echo", "display a line of text");
566   printf ("%-20s %s\n",
567           "edit", "edit a file in the image");
568
569   /* actions are printed after this (see list_commands) */
570 }
571
572 void
573 display_builtin_command (const char *cmd)
574 {
575   /* help for actions is auto-generated, see display_command */
576
577   if (strcasecmp (cmd, "alloc") == 0 ||
578       strcasecmp (cmd, "allocate") == 0)
579     printf ("alloc - allocate an image\n"
580             "     alloc <filename> <size>\n"
581             "\n"
582             "    This creates an empty (zeroed) file of the given size,\n"
583             "    and then adds so it can be further examined.\n"
584             "\n"
585             "    For more advanced image creation, see qemu-img utility.\n"
586             "\n"
587             "    Size can be specified (where <nn> means a number):\n"
588             "    <nn>             number of kilobytes\n"
589             "      eg: 1440       standard 3.5\" floppy\n"
590             "    <nn>K or <nn>KB  number of kilobytes\n"
591             "    <nn>M or <nn>MB  number of megabytes\n"
592             "    <nn>G or <nn>GB  number of gigabytes\n"
593             "    <nn>sects        number of 512 byte sectors\n");
594   else if (strcasecmp (cmd, "echo") == 0)
595     printf ("echo - display a line of text\n"
596             "     echo [<params> ...]\n"
597             "\n"
598             "    This echos the parameters to the terminal.\n");
599   else if (strcasecmp (cmd, "edit") == 0 ||
600            strcasecmp (cmd, "vi") == 0 ||
601            strcasecmp (cmd, "emacs") == 0)
602     printf ("edit - edit a file in the image\n"
603             "     edit <filename>\n"
604             "\n"
605             "    This is used to edit a file.\n"
606             "\n"
607             "    It is the equivalent of (and is implemented by)\n"
608             "    running \"cat\", editing locally, and then \"write-file\".\n"
609             "\n"
610             "    Normally it uses $EDITOR, but if you use the aliases\n"
611             "    \"vi\" or \"emacs\" you will get those editors.\n"
612             "\n"
613             "    NOTE: This will not work reliably for large files\n"
614             "    (> 2 MB) or binary files containing \\0 bytes.\n");
615   else if (strcasecmp (cmd, "help") == 0)
616     printf ("help - display a list of commands or help on a command\n"
617             "     help cmd\n"
618             "     help\n");
619   else if (strcasecmp (cmd, "quit") == 0 ||
620            strcasecmp (cmd, "exit") == 0 ||
621            strcasecmp (cmd, "q") == 0)
622     printf ("quit - quit guestfish\n"
623             "     quit\n");
624   else
625     fprintf (stderr, "%s: command not known, use -h to list all commands\n",
626              cmd);
627 }
628
629 void
630 free_strings (char **argv)
631 {
632   int argc;
633
634   for (argc = 0; argv[argc] != NULL; ++argc)
635     free (argv[argc]);
636   free (argv);
637 }
638
639 void
640 print_strings (char * const * const argv)
641 {
642   int argc;
643
644   for (argc = 0; argv[argc] != NULL; ++argc)
645     printf ("%s\n", argv[argc]);
646 }
647
648 void
649 print_table (char * const * const argv)
650 {
651   int i;
652
653   for (i = 0; argv[i] != NULL; i += 2)
654     printf ("%s: %s\n", argv[i], argv[i+1]);
655 }
656
657 int
658 is_true (const char *str)
659 {
660   return
661     strcasecmp (str, "0") != 0 &&
662     strcasecmp (str, "f") != 0 &&
663     strcasecmp (str, "false") != 0 &&
664     strcasecmp (str, "n") != 0 &&
665     strcasecmp (str, "no") != 0;
666 }
667
668 /* XXX We could improve list parsing. */
669 char **
670 parse_string_list (const char *str)
671 {
672   char **argv;
673   const char *p, *pend;
674   int argc, i;
675
676   argc = 1;
677   for (i = 0; str[i]; ++i)
678     if (str[i] == ' ') argc++;
679
680   argv = malloc (sizeof (char *) * (argc+1));
681   if (argv == NULL) { perror ("malloc"); exit (1); }
682
683   p = str;
684   i = 0;
685   while (*p) {
686     pend = strchrnul (p, ' ');
687     argv[i] = strndup (p, pend-p);
688     i++;
689     p = *pend == ' ' ? pend+1 : pend;
690   }
691   argv[i] = NULL;
692
693   return argv;
694 }
695
696 #ifdef HAVE_LIBREADLINE
697 static char histfile[1024];
698 static int nr_history_lines = 0;
699 #endif
700
701 static void
702 initialize_readline (void)
703 {
704 #ifdef HAVE_LIBREADLINE
705   const char *home;
706
707   home = getenv ("HOME");
708   if (home) {
709     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
710     using_history ();
711     (void) read_history (histfile);
712   }
713
714   rl_readline_name = "guestfish";
715   rl_attempted_completion_function = do_completion;
716 #endif
717 }
718
719 static void
720 cleanup_readline (void)
721 {
722 #ifdef HAVE_LIBREADLINE
723   int fd;
724
725   if (histfile[0] != '\0') {
726     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
727     if (fd == -1) {
728       perror (histfile);
729       return;
730     }
731     close (fd);
732
733     (void) append_history (nr_history_lines, histfile);
734   }
735 #endif
736 }
737
738 static void
739 add_history_line (const char *line)
740 {
741 #ifdef HAVE_LIBREADLINE
742   add_history (line);
743   nr_history_lines++;
744 #endif
745 }