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