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