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