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