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