Generated code for blockdev_* calls, RInt64, enhanced tests.
[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 *p, *pend;
312   char *argv[64];
313   int i, len;
314
315   if (prompt)
316     printf ("\n"
317             "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
318             "editing virtual machine filesystems.\n"
319             "\n"
320             "Type: 'help' for help with commands\n"
321             "      'quit' to quit the shell\n"
322             "\n");
323
324   while (!quit) {
325     buf = rl_gets (prompt);
326     if (!buf) {
327       quit = 1;
328       break;
329     }
330
331     /* Skip any initial whitespace before the command. */
332     while (*buf && isspace (*buf))
333       buf++;
334
335     /* Get the command (cannot be quoted). */
336     len = strcspn (buf, " \t");
337
338     if (len == 0) continue;
339
340     cmd = buf;
341     i = 0;
342     if (buf[len] == '\0') {
343       argv[0] = NULL;
344       goto got_command;
345     }
346
347     buf[len] = '\0';
348     p = &buf[len+1];
349     p += strspn (p, " \t");
350
351     /* Get the parameters. */
352     while (*p && i < sizeof argv / sizeof argv[0]) {
353       /* Parameters which start with quotes or square brackets
354        * are treated specially.  Bare parameters are delimited
355        * by whitespace.
356        */
357       if (*p == '"') {
358         p++;
359         len = strcspn (p, "\"");
360         if (p[len] == '\0') {
361           fprintf (stderr, "guestfish: unterminated double quote\n");
362           if (!prompt) exit (1);
363           goto next_command;
364         }
365         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
366           fprintf (stderr, "guestfish: command arguments not separated by whitespace\n");
367           if (!prompt) exit (1);
368           goto next_command;
369         }
370         p[len] = '\0';
371         pend = &p[len+2];
372       } else if (*p == '\'') {
373         p++;
374         len = strcspn (p, "'");
375         if (p[len] == '\0') {
376           fprintf (stderr, "guestfish: unterminated single quote\n");
377           if (!prompt) exit (1);
378           goto next_command;
379         }
380         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
381           fprintf (stderr, "guestfish: command arguments not separated by whitespace\n");
382           if (!prompt) exit (1);
383           goto next_command;
384         }
385         p[len] = '\0';
386         pend = &p[len+2];
387         /*
388       } else if (*p == '[') {
389         int c = 1;
390         p++;
391         pend = p;
392         while (*pend && c != 0) {
393           if (*pend == '[') c++;
394           else if (*pend == ']') c--;
395           pend++;
396         }
397         if (c != 0) {
398           fprintf (stderr, "guestfish: unterminated \"[...]\" sequence\n");
399           if (!prompt) exit (1);
400           goto next_command;
401         }
402         if (*pend && (*pend != ' ' && *pend != '\t')) {
403           fprintf (stderr, "guestfish: command arguments not separated by whitespace\n");
404           if (!prompt) exit (1);
405           goto next_command;
406         }
407         *(pend-1) = '\0';
408         */
409       } else if (*p != ' ' && *p != '\t') {
410         len = strcspn (p, " \t");
411         if (p[len]) {
412           p[len] = '\0';
413           pend = &p[len+1];
414         } else
415           pend = &p[len];
416       } else {
417         fprintf (stderr, "guestfish: internal error parsing string at '%s'\n",
418                  p);
419         abort ();
420       }
421
422       argv[i++] = p;
423       p = pend;
424
425       if (*p)
426         p += strspn (p, " \t");
427     }
428
429     if (i == sizeof argv / sizeof argv[0]) {
430       fprintf (stderr, "guestfish: too many arguments\n");
431       if (!prompt) exit (1);
432       goto next_command;
433     }
434
435     argv[i] = NULL;
436
437   got_command:
438     if (issue_command (cmd, argv) == -1) {
439       if (!prompt) exit (1);
440     }
441
442   next_command:;
443   }
444   if (prompt) printf ("\n");
445 }
446
447 static void
448 cmdline (char *argv[], int optind, int argc)
449 {
450   const char *cmd;
451   char **params;
452
453   if (optind >= argc) return;
454
455   cmd = argv[optind++];
456   if (strcmp (cmd, ":") == 0) {
457     fprintf (stderr, "guestfish: empty command on command line\n");
458     exit (1);
459   }
460   params = &argv[optind];
461
462   /* Search for end of command list or ":" ... */
463   while (optind < argc && strcmp (argv[optind], ":") != 0)
464     optind++;
465
466   if (optind == argc) {
467     if (issue_command (cmd, params) == -1) exit (1);
468   } else {
469     argv[optind] = NULL;
470     if (issue_command (cmd, params) == -1) exit (1);
471     cmdline (argv, optind+1, argc);
472   }
473 }
474
475 static int
476 issue_command (const char *cmd, char *argv[])
477 {
478   int argc;
479
480   for (argc = 0; argv[argc] != NULL; ++argc)
481     ;
482
483   if (strcasecmp (cmd, "help") == 0) {
484     if (argc == 0)
485       list_commands ();
486     else
487       display_command (argv[0]);
488     return 0;
489   }
490   else if (strcasecmp (cmd, "quit") == 0 ||
491            strcasecmp (cmd, "exit") == 0 ||
492            strcasecmp (cmd, "q") == 0) {
493     quit = 1;
494     return 0;
495   }
496   else if (strcasecmp (cmd, "alloc") == 0 ||
497            strcasecmp (cmd, "allocate") == 0) {
498     if (argc != 2) {
499       fprintf (stderr, "use 'alloc file size' to create an image\n");
500       return -1;
501     }
502     else {
503       off_t size;
504       int fd;
505
506       if (parse_size (argv[1], &size) == -1)
507         return -1;
508
509       if (g_launched) {
510         fprintf (stderr, "can't allocate or add disks after launching\n");
511         return -1;
512       }
513
514       fd = open (argv[0], O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
515       if (fd == -1) {
516         perror (argv[0]);
517         return -1;
518       }
519
520       if (posix_fallocate (fd, 0, size) == -1) {
521         perror ("fallocate");
522         close (fd);
523         unlink (argv[0]);
524         return -1;
525       }
526
527       if (close (fd) == -1) {
528         perror (argv[0]);
529         unlink (argv[0]);
530         return -1;
531       }
532
533       if (guestfs_add_drive (g, argv[0]) == -1) {
534         unlink (argv[0]);
535         return -1;
536       }
537
538       return 0;
539     }
540   }
541   else
542     return run_action (cmd, argc, argv);
543 }
544
545 void
546 list_builtin_commands (void)
547 {
548   /* help and quit should appear at the top */
549   printf ("%-20s %s\n",
550           "help", "display a list of commands or help on a command");
551   printf ("%-20s %s\n",
552           "quit", "quit guestfish");
553
554   printf ("%-20s %s\n",
555           "alloc", "allocate an image");
556
557   /* actions are printed after this (see list_commands) */
558 }
559
560 void
561 display_builtin_command (const char *cmd)
562 {
563   /* help for actions is auto-generated, see display_command */
564
565   if (strcasecmp (cmd, "alloc") == 0)
566     printf ("alloc - allocate an image\n"
567             "     alloc <filename> <size>\n"
568             "\n"
569             "    This creates an empty (zeroed) file of the given size,\n"
570             "    and then adds so it can be further examined.\n"
571             "\n"
572             "    For more advanced image creation, see qemu-img utility.\n"
573             "\n"
574             "    Size can be specified (where <nn> means a number):\n"
575             "    <nn>             number of kilobytes\n"
576             "      eg: 1440       standard 3.5\" floppy\n"
577             "    <nn>K or <nn>KB  number of kilobytes\n"
578             "    <nn>M or <nn>MB  number of megabytes\n"
579             "    <nn>G or <nn>GB  number of gigabytes\n"
580             "    <nn>sects        number of 512 byte sectors\n");
581   else if (strcasecmp (cmd, "help") == 0)
582     printf ("help - display a list of commands or help on a command\n"
583             "     help cmd\n"
584             "     help\n");
585   else if (strcasecmp (cmd, "quit") == 0)
586     printf ("quit - quit guestfish\n"
587             "     quit\n");
588   else
589     fprintf (stderr, "%s: command not known, use -h to list all commands\n",
590              cmd);
591 }
592
593 /* Parse size parameter of alloc command. */
594 static int
595 parse_size (const char *str, off_t *size_rtn)
596 {
597   uint64_t size;
598   char type;
599
600   /* Note that the parsing here is looser than what is specified in the
601    * help, but we may tighten it up in future so beware.
602    */
603   if (sscanf (str, "%"SCNu64"%c", &size, &type) == 2) {
604     switch (type) {
605     case 'k': case 'K': size *= 1024; break;
606     case 'm': case 'M': size *= 1024 * 1024; break;
607     case 'g': case 'G': size *= 1024 * 1024 * 1024; break;
608     case 's': size *= 512; break;
609     default:
610       fprintf (stderr, "could not parse size specification '%s'\n", str);
611       return -1;
612     }
613   }
614   else if (sscanf (str, "%"SCNu64, &size) == 1)
615     size *= 1024;
616   else {
617     fprintf (stderr, "could not parse size specification '%s'\n", str);
618     return -1;
619   }
620
621   /* XXX 32 bit file offsets, if anyone uses them?  GCC should give
622    * a warning here anyhow.
623    */
624   *size_rtn = size;
625
626   return 0;
627 }
628
629 void
630 free_strings (char **argv)
631 {
632   int argc;
633
634   for (argc = 0; argv[argc] != NULL; ++argc)
635     free (argv[argc]);
636   free (argv);
637 }
638
639 void
640 print_strings (char * const * const argv)
641 {
642   int argc;
643
644   for (argc = 0; argv[argc] != NULL; ++argc)
645     printf ("%s\n", argv[argc]);
646 }
647
648 void
649 print_table (char * const * const argv)
650 {
651   int i;
652
653   for (i = 0; argv[i] != NULL; i += 2)
654     printf ("%s: %s\n", argv[i], argv[i+1]);
655 }
656
657 int
658 is_true (const char *str)
659 {
660   return
661     strcasecmp (str, "0") != 0 &&
662     strcasecmp (str, "f") != 0 &&
663     strcasecmp (str, "false") != 0 &&
664     strcasecmp (str, "n") != 0 &&
665     strcasecmp (str, "no") != 0;
666 }
667
668 /* XXX We could improve list parsing. */
669 char **
670 parse_string_list (const char *str)
671 {
672   char **argv;
673   const char *p, *pend;
674   int argc, i;
675
676   argc = 1;
677   for (i = 0; str[i]; ++i)
678     if (str[i] == ' ') argc++;
679
680   argv = malloc (sizeof (char *) * (argc+1));
681   if (argv == NULL) { perror ("malloc"); exit (1); }
682
683   p = str;
684   i = 0;
685   while (*p) {
686     pend = strchrnul (p, ' ');
687     argv[i] = strndup (p, pend-p);
688     i++;
689     p = *pend == ' ' ? pend+1 : pend;
690   }
691   argv[i] = NULL;
692
693   return argv;
694 }
695
696 #ifdef HAVE_LIBREADLINE
697 static char histfile[1024];
698 static int nr_history_lines = 0;
699 #endif
700
701 static void
702 initialize_readline (void)
703 {
704 #ifdef HAVE_LIBREADLINE
705   const char *home;
706
707   home = getenv ("HOME");
708   if (home) {
709     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
710     using_history ();
711     (void) read_history (histfile);
712   }
713
714   rl_readline_name = "guestfish";
715   rl_attempted_completion_function = do_completion;
716 #endif
717 }
718
719 static void
720 cleanup_readline (void)
721 {
722 #ifdef HAVE_LIBREADLINE
723   int fd;
724
725   if (histfile[0] != '\0') {
726     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
727     if (fd == -1) {
728       perror (histfile);
729       return;
730     }
731     close (fd);
732
733     (void) append_history (nr_history_lines, histfile);
734   }
735 #endif
736 }
737
738 static void
739 add_history_line (const char *line)
740 {
741 #ifdef HAVE_LIBREADLINE
742   add_history (line);
743   nr_history_lines++;
744 #endif
745 }