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