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