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