Don't echo output in scripts.
[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 (prompt) {
281     if (line_read) {
282       free (line_read);
283       line_read = NULL;
284     }
285
286     line_read = readline (prompt ? FISH : "");
287
288     if (line_read && *line_read)
289       add_history_line (line_read);
290
291     return line_read;
292   }
293
294 #endif /* HAVE_LIBREADLINE */
295
296   static char buf[8192];
297   int len;
298
299   if (prompt) printf (FISH);
300   line_read = fgets (buf, sizeof buf, stdin);
301
302   if (line_read) {
303     len = strlen (line_read);
304     if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
305   }
306
307   return line_read;
308 }
309
310 static void
311 script (int prompt)
312 {
313   char *buf;
314   char *cmd;
315   char *p, *pend;
316   char *argv[64];
317   int i, len;
318
319   if (prompt)
320     printf ("\n"
321             "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
322             "editing virtual machine filesystems.\n"
323             "\n"
324             "Type: 'help' for help with commands\n"
325             "      'quit' to quit the shell\n"
326             "\n");
327
328   while (!quit) {
329     buf = rl_gets (prompt);
330     if (!buf) {
331       quit = 1;
332       break;
333     }
334
335     /* Skip any initial whitespace before the command. */
336     while (*buf && isspace (*buf))
337       buf++;
338
339     /* Get the command (cannot be quoted). */
340     len = strcspn (buf, " \t");
341
342     if (len == 0) continue;
343
344     cmd = buf;
345     i = 0;
346     if (buf[len] == '\0') {
347       argv[0] = NULL;
348       goto got_command;
349     }
350
351     buf[len] = '\0';
352     p = &buf[len+1];
353     p += strspn (p, " \t");
354
355     /* Get the parameters. */
356     while (*p && i < sizeof argv / sizeof argv[0]) {
357       /* Parameters which start with quotes or square brackets
358        * are treated specially.  Bare parameters are delimited
359        * by whitespace.
360        */
361       if (*p == '"') {
362         p++;
363         len = strcspn (p, "\"");
364         if (p[len] == '\0') {
365           fprintf (stderr, "guestfish: unterminated double quote\n");
366           if (!prompt) exit (1);
367           goto next_command;
368         }
369         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
370           fprintf (stderr, "guestfish: command arguments not separated by whitespace\n");
371           if (!prompt) exit (1);
372           goto next_command;
373         }
374         p[len] = '\0';
375         pend = p[len+1] ? &p[len+2] : &p[len+1];
376       } else if (*p == '\'') {
377         p++;
378         len = strcspn (p, "'");
379         if (p[len] == '\0') {
380           fprintf (stderr, "guestfish: unterminated single quote\n");
381           if (!prompt) exit (1);
382           goto next_command;
383         }
384         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
385           fprintf (stderr, "guestfish: command arguments not separated by whitespace\n");
386           if (!prompt) exit (1);
387           goto next_command;
388         }
389         p[len] = '\0';
390         pend = p[len+1] ? &p[len+2] : &p[len+1];
391         /*
392       } else if (*p == '[') {
393         int c = 1;
394         p++;
395         pend = p;
396         while (*pend && c != 0) {
397           if (*pend == '[') c++;
398           else if (*pend == ']') c--;
399           pend++;
400         }
401         if (c != 0) {
402           fprintf (stderr, "guestfish: unterminated \"[...]\" sequence\n");
403           if (!prompt) exit (1);
404           goto next_command;
405         }
406         if (*pend && (*pend != ' ' && *pend != '\t')) {
407           fprintf (stderr, "guestfish: command arguments not separated by whitespace\n");
408           if (!prompt) exit (1);
409           goto next_command;
410         }
411         *(pend-1) = '\0';
412         */
413       } else if (*p != ' ' && *p != '\t') {
414         len = strcspn (p, " \t");
415         if (p[len]) {
416           p[len] = '\0';
417           pend = &p[len+1];
418         } else
419           pend = &p[len];
420       } else {
421         fprintf (stderr, "guestfish: internal error parsing string at '%s'\n",
422                  p);
423         abort ();
424       }
425
426       argv[i++] = p;
427       p = pend;
428
429       if (*p)
430         p += strspn (p, " \t");
431     }
432
433     if (i == sizeof argv / sizeof argv[0]) {
434       fprintf (stderr, "guestfish: too many arguments\n");
435       if (!prompt) exit (1);
436       goto next_command;
437     }
438
439     argv[i] = NULL;
440
441   got_command:
442     if (issue_command (cmd, argv) == -1) {
443       if (!prompt) exit (1);
444     }
445
446   next_command:;
447   }
448   if (prompt) printf ("\n");
449 }
450
451 static void
452 cmdline (char *argv[], int optind, int argc)
453 {
454   const char *cmd;
455   char **params;
456
457   if (optind >= argc) return;
458
459   cmd = argv[optind++];
460   if (strcmp (cmd, ":") == 0) {
461     fprintf (stderr, "guestfish: empty command on command line\n");
462     exit (1);
463   }
464   params = &argv[optind];
465
466   /* Search for end of command list or ":" ... */
467   while (optind < argc && strcmp (argv[optind], ":") != 0)
468     optind++;
469
470   if (optind == argc) {
471     if (issue_command (cmd, params) == -1) exit (1);
472   } else {
473     argv[optind] = NULL;
474     if (issue_command (cmd, params) == -1) exit (1);
475     cmdline (argv, optind+1, argc);
476   }
477 }
478
479 static int
480 issue_command (const char *cmd, char *argv[])
481 {
482   int argc;
483
484   for (argc = 0; argv[argc] != NULL; ++argc)
485     ;
486
487   if (strcasecmp (cmd, "help") == 0) {
488     if (argc == 0)
489       list_commands ();
490     else
491       display_command (argv[0]);
492     return 0;
493   }
494   else if (strcasecmp (cmd, "quit") == 0 ||
495            strcasecmp (cmd, "exit") == 0 ||
496            strcasecmp (cmd, "q") == 0) {
497     quit = 1;
498     return 0;
499   }
500   else if (strcasecmp (cmd, "alloc") == 0 ||
501            strcasecmp (cmd, "allocate") == 0)
502     return do_alloc (cmd, argc, argv);
503   else if (strcasecmp (cmd, "edit") == 0 ||
504            strcasecmp (cmd, "vi") == 0 ||
505            strcasecmp (cmd, "emacs") == 0)
506     return do_edit (cmd, argc, argv);
507   else
508     return run_action (cmd, argc, argv);
509 }
510
511 void
512 list_builtin_commands (void)
513 {
514   /* help and quit should appear at the top */
515   printf ("%-20s %s\n",
516           "help", "display a list of commands or help on a command");
517   printf ("%-20s %s\n",
518           "quit", "quit guestfish");
519
520   printf ("%-20s %s\n",
521           "alloc", "allocate an image");
522   printf ("%-20s %s\n",
523           "edit", "edit a file in the image");
524
525   /* actions are printed after this (see list_commands) */
526 }
527
528 void
529 display_builtin_command (const char *cmd)
530 {
531   /* help for actions is auto-generated, see display_command */
532
533   if (strcasecmp (cmd, "alloc") == 0 ||
534       strcasecmp (cmd, "allocate") == 0)
535     printf ("alloc - allocate an image\n"
536             "     alloc <filename> <size>\n"
537             "\n"
538             "    This creates an empty (zeroed) file of the given size,\n"
539             "    and then adds so it can be further examined.\n"
540             "\n"
541             "    For more advanced image creation, see qemu-img utility.\n"
542             "\n"
543             "    Size can be specified (where <nn> means a number):\n"
544             "    <nn>             number of kilobytes\n"
545             "      eg: 1440       standard 3.5\" floppy\n"
546             "    <nn>K or <nn>KB  number of kilobytes\n"
547             "    <nn>M or <nn>MB  number of megabytes\n"
548             "    <nn>G or <nn>GB  number of gigabytes\n"
549             "    <nn>sects        number of 512 byte sectors\n");
550   else if (strcasecmp (cmd, "edit") == 0 ||
551            strcasecmp (cmd, "vi") == 0 ||
552            strcasecmp (cmd, "emacs") == 0)
553     printf ("edit - edit a file in the image\n"
554             "     edit <filename>\n"
555             "\n"
556             "    This is used to edit a file.\n"
557             "\n"
558             "    It is the equivalent of (and is implemented by)\n"
559             "    running \"cat\", editing locally, and then \"write-file\".\n"
560             "\n"
561             "    Normally it uses $EDITOR, but if you use the aliases\n"
562             "    \"vi\" or \"emacs\" you will get those editors.\n"
563             "\n"
564             "    NOTE: This will not work reliably for large files\n"
565             "    (> 2 MB) or binary files containing \\0 bytes.\n");
566   else if (strcasecmp (cmd, "help") == 0)
567     printf ("help - display a list of commands or help on a command\n"
568             "     help cmd\n"
569             "     help\n");
570   else if (strcasecmp (cmd, "quit") == 0 ||
571            strcasecmp (cmd, "exit") == 0 ||
572            strcasecmp (cmd, "q") == 0)
573     printf ("quit - quit guestfish\n"
574             "     quit\n");
575   else
576     fprintf (stderr, "%s: command not known, use -h to list all commands\n",
577              cmd);
578 }
579
580 void
581 free_strings (char **argv)
582 {
583   int argc;
584
585   for (argc = 0; argv[argc] != NULL; ++argc)
586     free (argv[argc]);
587   free (argv);
588 }
589
590 void
591 print_strings (char * const * const argv)
592 {
593   int argc;
594
595   for (argc = 0; argv[argc] != NULL; ++argc)
596     printf ("%s\n", argv[argc]);
597 }
598
599 void
600 print_table (char * const * const argv)
601 {
602   int i;
603
604   for (i = 0; argv[i] != NULL; i += 2)
605     printf ("%s: %s\n", argv[i], argv[i+1]);
606 }
607
608 int
609 is_true (const char *str)
610 {
611   return
612     strcasecmp (str, "0") != 0 &&
613     strcasecmp (str, "f") != 0 &&
614     strcasecmp (str, "false") != 0 &&
615     strcasecmp (str, "n") != 0 &&
616     strcasecmp (str, "no") != 0;
617 }
618
619 /* XXX We could improve list parsing. */
620 char **
621 parse_string_list (const char *str)
622 {
623   char **argv;
624   const char *p, *pend;
625   int argc, i;
626
627   argc = 1;
628   for (i = 0; str[i]; ++i)
629     if (str[i] == ' ') argc++;
630
631   argv = malloc (sizeof (char *) * (argc+1));
632   if (argv == NULL) { perror ("malloc"); exit (1); }
633
634   p = str;
635   i = 0;
636   while (*p) {
637     pend = strchrnul (p, ' ');
638     argv[i] = strndup (p, pend-p);
639     i++;
640     p = *pend == ' ' ? pend+1 : pend;
641   }
642   argv[i] = NULL;
643
644   return argv;
645 }
646
647 #ifdef HAVE_LIBREADLINE
648 static char histfile[1024];
649 static int nr_history_lines = 0;
650 #endif
651
652 static void
653 initialize_readline (void)
654 {
655 #ifdef HAVE_LIBREADLINE
656   const char *home;
657
658   home = getenv ("HOME");
659   if (home) {
660     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
661     using_history ();
662     (void) read_history (histfile);
663   }
664
665   rl_readline_name = "guestfish";
666   rl_attempted_completion_function = do_completion;
667 #endif
668 }
669
670 static void
671 cleanup_readline (void)
672 {
673 #ifdef HAVE_LIBREADLINE
674   int fd;
675
676   if (histfile[0] != '\0') {
677     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
678     if (fd == -1) {
679       perror (histfile);
680       return;
681     }
682     close (fd);
683
684     (void) append_history (nr_history_lines, histfile);
685   }
686 #endif
687 }
688
689 static void
690 add_history_line (const char *line)
691 {
692 #ifdef HAVE_LIBREADLINE
693   add_history (line);
694   nr_history_lines++;
695 #endif
696 }