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