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