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