Experiment with alternative longdesc format.
[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 #if 0
260 void
261 pod2text (const char *heading, const char *str)
262 {
263   FILE *fp;
264
265   fp = popen ("pod2text", "w");
266   if (fp == NULL) {
267     /* pod2text failed, maybe not found, so let's just print the
268      * source instead, since that's better than doing nothing.
269      */
270     printf ("%s\n\n%s\n", heading, str);
271     return;
272   }
273   fputs ("=head1 ", fp);
274   fputs (heading, fp);
275   fputs ("\n\n", fp);
276   fputs (str, fp);
277   pclose (fp);
278 }
279 #endif
280
281 /* List is built in reverse order, so mount them in reverse order. */
282 static void
283 mount_mps (struct mp *mp)
284 {
285   int r;
286
287   if (mp) {
288     mount_mps (mp->next);
289     if (!read_only)
290       r = guestfs_mount (g, mp->device, mp->mountpoint);
291     else
292       r = guestfs_mount_ro (g, mp->device, mp->mountpoint);
293     if (r == -1)
294       exit (1);
295   }
296 }
297
298 static void
299 add_drives (struct drv *drv)
300 {
301   int r;
302
303   if (drv) {
304     add_drives (drv->next);
305     if (!read_only)
306       r = guestfs_add_drive (g, drv->filename);
307     else
308       r = guestfs_add_drive_ro (g, drv->filename);
309     if (r == -1)
310       exit (1);
311   }
312 }
313
314 static void
315 interactive (void)
316 {
317   script (1);
318 }
319
320 static void
321 shell_script (void)
322 {
323   script (0);
324 }
325
326 #define FISH "><fs> "
327
328 static char *line_read = NULL;
329
330 static char *
331 rl_gets (int prompt)
332 {
333 #ifdef HAVE_LIBREADLINE
334
335   if (prompt) {
336     if (line_read) {
337       free (line_read);
338       line_read = NULL;
339     }
340
341     line_read = readline (prompt ? FISH : "");
342
343     if (line_read && *line_read)
344       add_history_line (line_read);
345
346     return line_read;
347   }
348
349 #endif /* HAVE_LIBREADLINE */
350
351   static char buf[8192];
352   int len;
353
354   if (prompt) printf (FISH);
355   line_read = fgets (buf, sizeof buf, stdin);
356
357   if (line_read) {
358     len = strlen (line_read);
359     if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
360   }
361
362   return line_read;
363 }
364
365 static void
366 script (int prompt)
367 {
368   char *buf;
369   char *cmd;
370   char *p, *pend;
371   char *argv[64];
372   int i, len;
373   int global_exit_on_error = !prompt;
374   int exit_on_error;
375
376   if (prompt)
377     printf (_("\n"
378               "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
379               "editing virtual machine filesystems.\n"
380               "\n"
381               "Type: 'help' for help with commands\n"
382               "      'quit' to quit the shell\n"
383               "\n"));
384
385   while (!quit) {
386     exit_on_error = global_exit_on_error;
387
388     buf = rl_gets (prompt);
389     if (!buf) {
390       quit = 1;
391       break;
392     }
393
394     /* Skip any initial whitespace before the command. */
395   again:
396     while (*buf && isspace (*buf))
397       buf++;
398
399     if (!*buf) continue;
400
401     /* If the next character is '#' then this is a comment. */
402     if (*buf == '#') continue;
403
404     /* If the next character is '!' then pass the whole lot to system(3). */
405     if (*buf == '!') {
406       int r;
407
408       r = system (buf+1);
409       if (exit_on_error) {
410         if (r == -1 ||
411             (WIFSIGNALED (r) &&
412              (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
413             WEXITSTATUS (r) != 0)
414           exit (1);
415       }
416       continue;
417     }
418
419     /* If the next character is '-' allow the command to fail without
420      * exiting on error (just for this one command though).
421      */
422     if (*buf == '-') {
423       exit_on_error = 0;
424       buf++;
425       goto again;
426     }
427
428     /* Get the command (cannot be quoted). */
429     len = strcspn (buf, " \t");
430
431     if (len == 0) continue;
432
433     cmd = buf;
434     i = 0;
435     if (buf[len] == '\0') {
436       argv[0] = NULL;
437       goto got_command;
438     }
439
440     buf[len] = '\0';
441     p = &buf[len+1];
442     p += strspn (p, " \t");
443
444     /* Get the parameters. */
445     while (*p && i < sizeof argv / sizeof argv[0]) {
446       /* Parameters which start with quotes or square brackets
447        * are treated specially.  Bare parameters are delimited
448        * by whitespace.
449        */
450       if (*p == '"') {
451         p++;
452         len = strcspn (p, "\"");
453         if (p[len] == '\0') {
454           fprintf (stderr, _("guestfish: unterminated double quote\n"));
455           if (exit_on_error) exit (1);
456           goto next_command;
457         }
458         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
459           fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
460           if (exit_on_error) exit (1);
461           goto next_command;
462         }
463         p[len] = '\0';
464         pend = p[len+1] ? &p[len+2] : &p[len+1];
465       } else if (*p == '\'') {
466         p++;
467         len = strcspn (p, "'");
468         if (p[len] == '\0') {
469           fprintf (stderr, _("guestfish: unterminated single quote\n"));
470           if (exit_on_error) exit (1);
471           goto next_command;
472         }
473         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
474           fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
475           if (exit_on_error) exit (1);
476           goto next_command;
477         }
478         p[len] = '\0';
479         pend = p[len+1] ? &p[len+2] : &p[len+1];
480         /*
481       } else if (*p == '[') {
482         int c = 1;
483         p++;
484         pend = p;
485         while (*pend && c != 0) {
486           if (*pend == '[') c++;
487           else if (*pend == ']') c--;
488           pend++;
489         }
490         if (c != 0) {
491           fprintf (stderr, _("guestfish: unterminated \"[...]\" sequence\n"));
492           if (exit_on_error) exit (1);
493           goto next_command;
494         }
495         if (*pend && (*pend != ' ' && *pend != '\t')) {
496           fprintf (stderr, _("guestfish: command arguments not separated by whitespace\n"));
497           if (exit_on_error) exit (1);
498           goto next_command;
499         }
500         *(pend-1) = '\0';
501         */
502       } else if (*p != ' ' && *p != '\t') {
503         len = strcspn (p, " \t");
504         if (p[len]) {
505           p[len] = '\0';
506           pend = &p[len+1];
507         } else
508           pend = &p[len];
509       } else {
510         fprintf (stderr, _("guestfish: internal error parsing string at '%s'\n"),
511                  p);
512         abort ();
513       }
514
515       argv[i++] = p;
516       p = pend;
517
518       if (*p)
519         p += strspn (p, " \t");
520     }
521
522     if (i == sizeof argv / sizeof argv[0]) {
523       fprintf (stderr, _("guestfish: too many arguments\n"));
524       if (exit_on_error) exit (1);
525       goto next_command;
526     }
527
528     argv[i] = NULL;
529
530   got_command:
531     if (issue_command (cmd, argv) == -1) {
532       if (exit_on_error) exit (1);
533     }
534
535   next_command:;
536   }
537   if (prompt) printf ("\n");
538 }
539
540 static void
541 cmdline (char *argv[], int optind, int argc)
542 {
543   const char *cmd;
544   char **params;
545
546   if (optind >= argc) return;
547
548   cmd = argv[optind++];
549   if (strcmp (cmd, ":") == 0) {
550     fprintf (stderr, _("guestfish: empty command on command line\n"));
551     exit (1);
552   }
553   params = &argv[optind];
554
555   /* Search for end of command list or ":" ... */
556   while (optind < argc && strcmp (argv[optind], ":") != 0)
557     optind++;
558
559   if (optind == argc) {
560     if (issue_command (cmd, params) == -1) exit (1);
561   } else {
562     argv[optind] = NULL;
563     if (issue_command (cmd, params) == -1) exit (1);
564     cmdline (argv, optind+1, argc);
565   }
566 }
567
568 static int
569 issue_command (const char *cmd, char *argv[])
570 {
571   int argc;
572
573   for (argc = 0; argv[argc] != NULL; ++argc)
574     ;
575
576   if (strcasecmp (cmd, "help") == 0) {
577     if (argc == 0)
578       list_commands ();
579     else
580       display_command (argv[0]);
581     return 0;
582   }
583   else if (strcasecmp (cmd, "quit") == 0 ||
584            strcasecmp (cmd, "exit") == 0 ||
585            strcasecmp (cmd, "q") == 0) {
586     quit = 1;
587     return 0;
588   }
589   else if (strcasecmp (cmd, "alloc") == 0 ||
590            strcasecmp (cmd, "allocate") == 0)
591     return do_alloc (cmd, argc, argv);
592   else if (strcasecmp (cmd, "echo") == 0)
593     return do_echo (cmd, argc, argv);
594   else if (strcasecmp (cmd, "edit") == 0 ||
595            strcasecmp (cmd, "vi") == 0 ||
596            strcasecmp (cmd, "emacs") == 0)
597     return do_edit (cmd, argc, argv);
598   else
599     return run_action (cmd, argc, argv);
600 }
601
602 void
603 list_builtin_commands (void)
604 {
605   /* help and quit should appear at the top */
606   printf ("%-20s %s\n",
607           "help", _("display a list of commands or help on a command"));
608   printf ("%-20s %s\n",
609           "quit", _("quit guestfish"));
610
611   printf ("%-20s %s\n",
612           "alloc", _("allocate an image"));
613   printf ("%-20s %s\n",
614           "echo", _("display a line of text"));
615   printf ("%-20s %s\n",
616           "edit", _("edit a file in the image"));
617
618   /* actions are printed after this (see list_commands) */
619 }
620
621 void
622 display_builtin_command (const char *cmd)
623 {
624   /* help for actions is auto-generated, see display_command */
625
626   if (strcasecmp (cmd, "alloc") == 0 ||
627       strcasecmp (cmd, "allocate") == 0)
628     printf (_("alloc - allocate an image\n"
629               "     alloc <filename> <size>\n"
630               "\n"
631               "    This creates an empty (zeroed) file of the given size,\n"
632               "    and then adds so it can be further examined.\n"
633               "\n"
634               "    For more advanced image creation, see qemu-img utility.\n"
635               "\n"
636               "    Size can be specified (where <nn> means a number):\n"
637               "    <nn>             number of kilobytes\n"
638               "      eg: 1440       standard 3.5\" floppy\n"
639               "    <nn>K or <nn>KB  number of kilobytes\n"
640               "    <nn>M or <nn>MB  number of megabytes\n"
641               "    <nn>G or <nn>GB  number of gigabytes\n"
642               "    <nn>sects        number of 512 byte sectors\n"));
643   else if (strcasecmp (cmd, "echo") == 0)
644     printf (_("echo - display a line of text\n"
645               "     echo [<params> ...]\n"
646               "\n"
647               "    This echos the parameters to the terminal.\n"));
648   else if (strcasecmp (cmd, "edit") == 0 ||
649            strcasecmp (cmd, "vi") == 0 ||
650            strcasecmp (cmd, "emacs") == 0)
651     printf (_("edit - edit a file in the image\n"
652               "     edit <filename>\n"
653               "\n"
654               "    This is used to edit a file.\n"
655               "\n"
656               "    It is the equivalent of (and is implemented by)\n"
657               "    running \"cat\", editing locally, and then \"write-file\".\n"
658               "\n"
659               "    Normally it uses $EDITOR, but if you use the aliases\n"
660               "    \"vi\" or \"emacs\" you will get those editors.\n"
661               "\n"
662               "    NOTE: This will not work reliably for large files\n"
663               "    (> 2 MB) or binary files containing \\0 bytes.\n"));
664   else if (strcasecmp (cmd, "help") == 0)
665     printf (_("help - display a list of commands or help on a command\n"
666               "     help cmd\n"
667               "     help\n"));
668   else if (strcasecmp (cmd, "quit") == 0 ||
669            strcasecmp (cmd, "exit") == 0 ||
670            strcasecmp (cmd, "q") == 0)
671     printf (_("quit - quit guestfish\n"
672               "     quit\n"));
673   else
674     fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
675              cmd);
676 }
677
678 void
679 free_strings (char **argv)
680 {
681   int argc;
682
683   for (argc = 0; argv[argc] != NULL; ++argc)
684     free (argv[argc]);
685   free (argv);
686 }
687
688 void
689 print_strings (char * const * const argv)
690 {
691   int argc;
692
693   for (argc = 0; argv[argc] != NULL; ++argc)
694     printf ("%s\n", argv[argc]);
695 }
696
697 void
698 print_table (char * const * const argv)
699 {
700   int i;
701
702   for (i = 0; argv[i] != NULL; i += 2)
703     printf ("%s: %s\n", argv[i], argv[i+1]);
704 }
705
706 int
707 is_true (const char *str)
708 {
709   return
710     strcasecmp (str, "0") != 0 &&
711     strcasecmp (str, "f") != 0 &&
712     strcasecmp (str, "false") != 0 &&
713     strcasecmp (str, "n") != 0 &&
714     strcasecmp (str, "no") != 0;
715 }
716
717 /* XXX We could improve list parsing. */
718 char **
719 parse_string_list (const char *str)
720 {
721   char **argv;
722   const char *p, *pend;
723   int argc, i;
724
725   argc = 1;
726   for (i = 0; str[i]; ++i)
727     if (str[i] == ' ') argc++;
728
729   argv = malloc (sizeof (char *) * (argc+1));
730   if (argv == NULL) { perror ("malloc"); exit (1); }
731
732   p = str;
733   i = 0;
734   while (*p) {
735     pend = strchrnul (p, ' ');
736     argv[i] = strndup (p, pend-p);
737     i++;
738     p = *pend == ' ' ? pend+1 : pend;
739   }
740   argv[i] = NULL;
741
742   return argv;
743 }
744
745 #ifdef HAVE_LIBREADLINE
746 static char histfile[1024];
747 static int nr_history_lines = 0;
748 #endif
749
750 static void
751 initialize_readline (void)
752 {
753 #ifdef HAVE_LIBREADLINE
754   const char *home;
755
756   home = getenv ("HOME");
757   if (home) {
758     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
759     using_history ();
760     (void) read_history (histfile);
761   }
762
763   rl_readline_name = "guestfish";
764   rl_attempted_completion_function = do_completion;
765 #endif
766 }
767
768 static void
769 cleanup_readline (void)
770 {
771 #ifdef HAVE_LIBREADLINE
772   int fd;
773
774   if (histfile[0] != '\0') {
775     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
776     if (fd == -1) {
777       perror (histfile);
778       return;
779     }
780     close (fd);
781
782     (void) append_history (nr_history_lines, histfile);
783   }
784 #endif
785 }
786
787 static void
788 add_history_line (const char *line)
789 {
790 #ifdef HAVE_LIBREADLINE
791   add_history (line);
792   nr_history_lines++;
793 #endif
794 }